Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.28% covered (warning)
88.28%
256 / 290
53.33% covered (warning)
53.33%
16 / 30
CRAP
0.00% covered (danger)
0.00%
0 / 1
ZObjectDiffVisualiser
88.28% covered (warning)
88.28%
256 / 290
53.33% covered (warning)
53.33%
16 / 30
137.68
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 visualiseDiff
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
9
 collectIdentifiers
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 collectValueIdentifiers
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 renderEntry
79.41% covered (warning)
79.41%
27 / 34
0.00% covered (danger)
0.00%
0 / 1
13.26
 renderMultilingualContainer
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
5.01
 renderMonolingual
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 languageContext
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
8.01
 fieldPathOf
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 navigate
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
 isMultilingualContainer
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 isMonolingual
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 monolingualLanguageZid
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 monolingualText
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
2.50
 labelWithLanguage
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 languageAttributes
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 languageCellAttributes
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 renderPathLabel
76.47% covered (warning)
76.47%
13 / 17
0.00% covered (danger)
0.00%
0 / 1
8.83
 itemHandle
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
10.06
 localiseGroupKey
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 generateOpRowHtml
68.75% covered (warning)
68.75%
11 / 16
0.00% covered (danger)
0.00%
0 / 1
7.10
 generateChangeRowHtml
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
3
 generateMoveRowHtml
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 generateMovedLine
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 sidedValue
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 getChangedLine
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 valueKeyOf
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
5.20
 generateSectionHeaderHtml
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 generateDiffHeaderHtml
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 generateHtmlDiffTableRow
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * WikiLambda ZObjectDiffVisualiser: turns a computed ZObjectDiffer diff into
4 * grouped, labelled MediaWiki diff-table rows.
5 *
6 * @file
7 * @ingroup Extensions
8 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
9 * @license MIT
10 */
11
12namespace MediaWiki\Extension\WikiLambda\Diff;
13
14use Diff\DiffOp\DiffOp;
15use Diff\DiffOp\DiffOpAdd;
16use Diff\DiffOp\DiffOpChange;
17use Diff\DiffOp\DiffOpRemove;
18use MediaWiki\Extension\WikiLambda\Registry\ZTypeRegistry;
19use MediaWiki\Html\Html;
20use MediaWiki\Language\MessageLocalizer;
21use UnexpectedValueException;
22use Wikimedia\Diff\WordLevelDiff;
23
24/**
25 * Renders the flattened output of ZObjectDiffer as a sequence of MediaWiki
26 * diff-table rows, grouped under human-readable, localised headers for the
27 * top-level ZPersistentObject keys (name, aliases, description, value).
28 *
29 * This is the WikiLambda analogue of Wikibase's BasicDiffView. It reuses
30 * ZObjectDiffer::flattenDiff() — the same diff the authorization layer
31 * consumes — rather than re-walking the object tree.
32 *
33 * A change to a list item is headed by what identifies that item — its
34 * language for a monolingual value (Z11/Z31), otherwise whatever
35 * DiffItemIdentifier can make of its content — rather than by its position,
36 * which means nothing to a reader and shifts as items are inserted. Additions
37 * and removals of a whole multilingual structure (Z12/Z32) are decomposed into
38 * one row per language, matching how Wikibase presents term diffs.
39 *
40 * Values are rendered by ZObjectValueRenderer, so that adding or removing a
41 * whole sub-tree shows its labelled structure rather than its JSON.
42 */
43class ZObjectDiffVisualiser {
44
45    /** @var ZObjectValueRenderer Renders the values carried by the diff's operations */
46    private readonly ZObjectValueRenderer $values;
47
48    /** @var DiffItemIdentifier Names the list items the diff's paths point at */
49    private readonly DiffItemIdentifier $items;
50
51    /** @var array The old Object being compared, for the duration of one render */
52    private array $oldObject = [];
53
54    /** @var array The new Object being compared, for the duration of one render */
55    private array $newObject = [];
56
57    /**
58     * @param MessageLocalizer $messageLocalizer
59     * @param DiffLabelResolver $labels Resolves the keys, references and
60     *   languages appearing in the diff to display text in the viewer's language.
61     */
62    public function __construct(
63        private readonly MessageLocalizer $messageLocalizer,
64        private readonly DiffLabelResolver $labels
65    ) {
66        $this->values = new ZObjectValueRenderer( $messageLocalizer, $labels );
67        $this->items = new DiffItemIdentifier( $labels );
68    }
69
70    /**
71     * Build the HTML diff body (a sequence of <tr> rows) for a computed diff.
72     *
73     * @param DiffOp $diffOp The diff returned by ZObjectDiffer::doDiff()
74     * @param array $oldObject The old ZObject as a nested array
75     * @param array $newObject The new ZObject as a nested array
76     * @return string HTML: one or more <tr> tags, or '' if there are no changes
77     */
78    public function visualiseDiff( DiffOp $diffOp, array $oldObject = [], array $newObject = [] ): string {
79        // A diff operation records what changed but not what surrounds it, so the
80        // two compared Objects are kept for the duration of this render, to be
81        // navigated whenever a change has to be read in context.
82        $this->oldObject = $oldObject;
83        $this->newObject = $newObject;
84
85        // Partition the flattened changes into the two top-level sections shown
86        // as <h2> headings — "About" (name, aliases, description) and "Contents"
87        // (the value/body) — preserving encounter order within each. Anything
88        // else (e.g. a bare identifier or type change) is rendered ungrouped.
89        $aboutKeys = [
90            ZTypeRegistry::Z_PERSISTENTOBJECT_LABEL,
91            ZTypeRegistry::Z_PERSISTENTOBJECT_ALIASES,
92            ZTypeRegistry::Z_PERSISTENTOBJECT_DESCRIPTION,
93        ];
94        $about = [];
95        $contents = [];
96        $other = [];
97        $identifiers = [];
98        foreach ( ZObjectDiffer::flattenDiff( $diffOp ) as $entry ) {
99            $this->collectIdentifiers( $entry, $identifiers );
100            $head = $entry['path'][0] ?? null;
101            if ( in_array( $head, $aboutKeys, true ) ) {
102                $about[] = $entry;
103            } elseif ( $head === ZTypeRegistry::Z_PERSISTENTOBJECT_VALUE ) {
104                $contents[] = $entry;
105            } else {
106                $other[] = $entry;
107            }
108        }
109
110        // Resolve every label the diff needs up front, so that a diff touching
111        // many objects costs a fixed number of database reads rather than growing
112        // with the number of rows.
113        $this->labels->prefetch( $identifiers );
114
115        $html = '';
116        if ( $about ) {
117            $html .= $this->generateSectionHeaderHtml( 'wikilambda-diff-section-about' );
118            foreach ( $about as $entry ) {
119                $html .= $this->renderEntry( $entry['path'], $entry['op'], false );
120            }
121        }
122        if ( $contents ) {
123            $html .= $this->generateSectionHeaderHtml( 'wikilambda-diff-section-contents' );
124            foreach ( $contents as $entry ) {
125                // The "Value" group key is represented by the section heading, so
126                // drop it from the per-row breadcrumb.
127                $html .= $this->renderEntry( $entry['path'], $entry['op'], true );
128            }
129        }
130        foreach ( $other as $entry ) {
131            $html .= $this->renderEntry( $entry['path'], $entry['op'], false );
132        }
133        return $html;
134    }
135
136    /**
137     * Collect the ZObject identifiers one flattened diff entry will need display
138     * text for: the keys naming it, which are its path segments, and any
139     * reference it changes, which may be nested inside a changed sub-tree (the
140     * language of a monolingual value, say).
141     *
142     * Deliberately over-collects rather than predicting what each row will
143     * actually render: the resolver batches by shape and discards the rest, so a
144     * superfluous identifier costs nothing beyond a slightly wider query.
145     *
146     * @param array $entry A 'path' and 'op' pair from ZObjectDiffer::flattenDiff()
147     * @param string[] &$identifiers Accumulator, appended to in place
148     */
149    private function collectIdentifiers( array $entry, array &$identifiers ): void {
150        foreach ( $entry['path'] as $segment ) {
151            $identifiers[] = (string)$segment;
152        }
153
154        $op = $entry['op'];
155        $this->collectValueIdentifiers( $this->sidedValue( $op ), $identifiers );
156        if ( $op instanceof DiffOpChange ) {
157            $this->collectValueIdentifiers( $op->getOldValue(), $identifiers );
158            $this->collectValueIdentifiers( $op->getNewValue(), $identifiers );
159        }
160    }
161
162    /**
163     * Collect the strings held anywhere in a diff value, any of which may turn
164     * out to be a reference, along with its keys, which are labelled when the
165     * value is rendered as a structure.
166     *
167     * @param mixed $value
168     * @param string[] &$identifiers Accumulator, appended to in place
169     */
170    private function collectValueIdentifiers( $value, array &$identifiers ): void {
171        if ( is_string( $value ) ) {
172            $identifiers[] = $value;
173            return;
174        }
175        if ( is_array( $value ) ) {
176            foreach ( $value as $key => $item ) {
177                $identifiers[] = (string)$key;
178                $this->collectValueIdentifiers( $item, $identifiers );
179            }
180        }
181    }
182
183    /**
184     * Render a single flattened diff entry, choosing a language-aware layout for
185     * monolingual and multilingual values and falling back to a plain path
186     * breadcrumb otherwise.
187     *
188     * @param array $path
189     * @param DiffOp $op
190     * @param bool $dropGroupHead Whether the top-level group key is already shown
191     *   as a section heading and should be omitted from the breadcrumb
192     * @return string
193     */
194    private function renderEntry(
195        array $path, DiffOp $op, bool $dropGroupHead
196    ): string {
197        $type = $op->getType();
198
199        // Addition/removal of a whole monolingual or multilingual structure:
200        // read the language(s) straight from the value and decompose.
201        if ( $type === 'add' || $type === 'remove' ) {
202            $value = $this->sidedValue( $op );
203            if ( is_array( $value ) && $this->isMultilingualContainer( $value ) ) {
204                return $this->renderMultilingualContainer( $path, $value, $type, $dropGroupHead );
205            }
206            if ( is_array( $value ) && $this->isMonolingual( $value ) ) {
207                return $this->renderMonolingual(
208                    $this->fieldPathOf( $path ),
209                    $this->monolingualLanguageZid( $value ),
210                    $this->monolingualText( $value ),
211                    $type,
212                    $dropGroupHead
213                );
214            }
215        }
216
217        // Any leaf change, or addition/removal of a single string, that sits
218        // inside a monolingual value (e.g. one alias in a set) is headed by its
219        // language rather than by the raw list index.
220        $context = $this->languageContext( $path );
221        if ( $context !== null ) {
222            $header = $this->generateDiffHeaderHtml(
223                $this->labelWithLanguage( $context['fieldPath'], $context['oldLanguageZid'], $dropGroupHead ),
224                $this->labelWithLanguage( $context['fieldPath'], $context['newLanguageZid'], $dropGroupHead )
225            );
226            $oldLanguage = $this->languageAttributes( $context['oldLanguageZid'] );
227            $newLanguage = $this->languageAttributes( $context['newLanguageZid'] );
228            // A move reports itself as a change, so test for it first.
229            if ( $op instanceof DiffOpMove ) {
230                return $header . $this->generateMoveRowHtml( $op, null, $oldLanguage, $newLanguage );
231            }
232            if ( $type === 'change' ) {
233                '@phan-var DiffOpChange $op';
234                return $header . $this->generateChangeRowHtml( $op, null, $oldLanguage, $newLanguage );
235            }
236            $line = $this->getChangedLine(
237                $type === 'add' ? 'ins' : 'del',
238                $this->sidedValue( $op )
239            );
240            return $header . ( $type === 'add'
241                ? $this->generateHtmlDiffTableRow( null, $line, null, $newLanguage )
242                : $this->generateHtmlDiffTableRow( $line, null, $oldLanguage ) );
243        }
244
245        // Fallback: a breadcrumb of labelled keys, with any list index along the way
246        // replaced by the identity of the item it points at. The operation is
247        // passed because this path names it exactly, so where it ends in an index
248        // the operation's own value is that item.
249        return $this->generateDiffHeaderHtml( $this->renderPathLabel( $path, $dropGroupHead, $op ) )
250            . $this->generateOpRowHtml( $op, $this->valueKeyOf( $path ) );
251    }
252
253    /**
254     * Decompose an added/removed multilingual container (Z12/Z32) into one row
255     * per language, rather than dumping its raw JSON.
256     *
257     * @param array $fieldPath Path to the field holding the container
258     * @param array $container The Z12/Z32 value
259     * @param string $type 'add' or 'remove'
260     * @param bool $dropGroupHead
261     * @return string
262     */
263    private function renderMultilingualContainer(
264        array $fieldPath, array $container, string $type, bool $dropGroupHead
265    ): string {
266        $listKey = $container['Z1K1'] === ZTypeRegistry::Z_MULTILINGUALSTRING
267            ? ZTypeRegistry::Z_MULTILINGUALSTRING_VALUE
268            : ZTypeRegistry::Z_MULTILINGUALSTRINGSET_VALUE;
269
270        $html = '';
271        foreach ( $container[$listKey] ?? [] as $item ) {
272            // Skip the leading type reference (e.g. 'Z11') in the typed list.
273            if ( !is_array( $item ) || !$this->isMonolingual( $item ) ) {
274                continue;
275            }
276            $html .= $this->renderMonolingual(
277                $fieldPath,
278                $this->monolingualLanguageZid( $item ),
279                $this->monolingualText( $item ),
280                $type,
281                $dropGroupHead
282            );
283        }
284        return $html;
285    }
286
287    /**
288     * Render a single monolingual (Z11/Z31) value as an added or removed row,
289     * headed by its field label and language.
290     *
291     * @param array $fieldPath
292     * @param string|null $languageZid
293     * @param string $text
294     * @param string $type 'add' or 'remove'
295     * @param bool $dropGroupHead
296     * @return string
297     */
298    private function renderMonolingual(
299        array $fieldPath, ?string $languageZid, string $text, string $type, bool $dropGroupHead
300    ): string {
301        $header = $this->generateDiffHeaderHtml(
302            $this->labelWithLanguage( $fieldPath, $languageZid, $dropGroupHead )
303        );
304        $language = $this->languageAttributes( $languageZid );
305        $line = $this->getChangedLine( $type === 'add' ? 'ins' : 'del', $text );
306        return $header . ( $type === 'add'
307            ? $this->generateHtmlDiffTableRow( null, $line, null, $language )
308            : $this->generateHtmlDiffTableRow( $line, null, $language ) );
309    }
310
311    /**
312     * If a changed leaf sits inside a monolingual value, return the field path
313     * (up to the multilingual container) and the language of that value on each
314     * side, so the change can be headed "<field> (<language>)" instead of by
315     * list index.
316     *
317     * Each side is read from its own Object, because an edit can move a value to
318     * a different language: correcting a name tagged as English to Dutch leaves
319     * the removed text English, and heading it Dutch tells the reader that the
320     * Dutch name used to be something it never was. A side the path does not
321     * reach — an entry that only one revision has — takes the other side's
322     * language, so a pure addition or removal is still headed.
323     *
324     * itemHandle() asks the same question for breadcrumbs and answers it the
325     * other way, falling back to a position where the two sides disagree. It can
326     * afford to, because an index states nothing false. Here there is no such
327     * neutral answer: dropping the language leaves the row headed by a raw
328     * index, which is what this layout exists to avoid. So each side states what
329     * it holds.
330     *
331     * @param array $path
332     * @return array{fieldPath:array,oldLanguageZid:string,newLanguageZid:string}|null
333     */
334    private function languageContext( array $path ): ?array {
335        for ( $i = count( $path ) - 1; $i >= 0; $i-- ) {
336            $languageKey = match ( $path[$i] ) {
337                ZTypeRegistry::Z_MULTILINGUALSTRING_VALUE => ZTypeRegistry::Z_MONOLINGUALSTRING_LANGUAGE,
338                ZTypeRegistry::Z_MULTILINGUALSTRINGSET_VALUE => ZTypeRegistry::Z_MONOLINGUALSTRINGSET_LANGUAGE,
339                default => null,
340            };
341            if ( $languageKey === null || !isset( $path[$i + 1] ) ) {
342                continue;
343            }
344
345            // The monolingual entry is at <container>/<index>; its language is a sibling.
346            $languagePath = array_merge( array_slice( $path, 0, $i + 2 ), [ $languageKey ] );
347            $oldLanguageZid = $this->navigate( $this->oldObject, $languagePath );
348            $newLanguageZid = $this->navigate( $this->newObject, $languagePath );
349            if ( !is_string( $oldLanguageZid ) && !is_string( $newLanguageZid ) ) {
350                // Not actually a monolingual container here; keep scanning
351                // outwards in case an enclosing one applies.
352                continue;
353            }
354
355            return [
356                'fieldPath' => array_slice( $path, 0, $i ),
357                'oldLanguageZid' => is_string( $oldLanguageZid ) ? $oldLanguageZid : $newLanguageZid,
358                'newLanguageZid' => is_string( $newLanguageZid ) ? $newLanguageZid : $oldLanguageZid,
359            ];
360        }
361        return null;
362    }
363
364    /**
365     * If a path ends in a multilingual container entry (…/Z12K1/<index> or
366     * …/Z32K1/<index>), strip that suffix to get the field that holds it.
367     *
368     * @param array $path
369     * @return array
370     */
371    private function fieldPathOf( array $path ): array {
372        $count = count( $path );
373        if ( $count >= 2 && (
374            $path[$count - 2] === ZTypeRegistry::Z_MULTILINGUALSTRING_VALUE ||
375            $path[$count - 2] === ZTypeRegistry::Z_MULTILINGUALSTRINGSET_VALUE
376        ) ) {
377            return array_slice( $path, 0, $count - 2 );
378        }
379        return $path;
380    }
381
382    /**
383     * Walk a nested array by a path of keys/indices, returning null if any step
384     * is missing.
385     *
386     * @param array $object
387     * @param array $path
388     * @return mixed
389     */
390    private function navigate( array $object, array $path ) {
391        $node = $object;
392        foreach ( $path as $key ) {
393            if ( !is_array( $node ) || !array_key_exists( $key, $node ) ) {
394                return null;
395            }
396            $node = $node[$key];
397        }
398        return $node;
399    }
400
401    private function isMultilingualContainer( array $value ): bool {
402        return ( $value['Z1K1'] ?? null ) === ZTypeRegistry::Z_MULTILINGUALSTRING
403            || ( $value['Z1K1'] ?? null ) === ZTypeRegistry::Z_MULTILINGUALSTRINGSET;
404    }
405
406    private function isMonolingual( array $value ): bool {
407        return ( $value['Z1K1'] ?? null ) === ZTypeRegistry::Z_MONOLINGUALSTRING
408            || ( $value['Z1K1'] ?? null ) === ZTypeRegistry::Z_MONOLINGUALSTRINGSET;
409    }
410
411    private function monolingualLanguageZid( array $value ): ?string {
412        $language = ( $value['Z1K1'] ?? null ) === ZTypeRegistry::Z_MONOLINGUALSTRING
413            ? ( $value[ZTypeRegistry::Z_MONOLINGUALSTRING_LANGUAGE] ?? null )
414            : ( $value[ZTypeRegistry::Z_MONOLINGUALSTRINGSET_LANGUAGE] ?? null );
415        return is_string( $language ) ? $language : null;
416    }
417
418    /**
419     * Extract the display string(s) from a monolingual value: the text of a Z11,
420     * or the comma-joined strings of a Z31 string set (skipping the leading type
421     * reference in the typed list).
422     *
423     * @param array $value
424     * @return string
425     */
426    private function monolingualText( array $value ): string {
427        if ( ( $value['Z1K1'] ?? null ) === ZTypeRegistry::Z_MONOLINGUALSTRING ) {
428            return (string)( $value[ZTypeRegistry::Z_MONOLINGUALSTRING_VALUE] ?? '' );
429        }
430        $strings = array_slice( $value[ZTypeRegistry::Z_MONOLINGUALSTRINGSET_VALUE] ?? [], 1 );
431        return implode( ', ', array_filter( $strings, 'is_string' ) );
432    }
433
434    /**
435     * Compose a field label ("Name", "Value / Z8K1 / …") with its language in
436     * parentheses. Plain text; escaped when placed in the header.
437     *
438     * @param array $fieldPath
439     * @param string|null $languageZid
440     * @param bool $dropGroupHead
441     * @return string
442     */
443    private function labelWithLanguage( array $fieldPath, ?string $languageZid, bool $dropGroupHead ): string {
444        $label = $this->renderPathLabel( $fieldPath, $dropGroupHead );
445        if ( $languageZid === null ) {
446            return $label;
447        }
448        $language = '(' . $this->labels->getLanguage( $languageZid )['name'] . ')';
449        return $label === '' ? $language : $label . ' ' . $language;
450    }
451
452    /**
453     * Resolve the HTML lang/dir attributes for a language-specific value, so it
454     * renders in its own script and direction rather than inheriting the
455     * interface chrome's direction. Returns null when there is no language.
456     *
457     * @param string|null $languageZid
458     * @return array{code:string,dir:string}|null
459     */
460    private function languageAttributes( ?string $languageZid ): ?array {
461        if ( $languageZid === null ) {
462            return null;
463        }
464        $language = $this->labels->getLanguage( $languageZid );
465        return [ 'code' => $language['code'], 'dir' => $language['dir'] ];
466    }
467
468    /**
469     * HTML attributes tagging a value cell with its own language and direction.
470     * These go on the cell's block-level content <div> (not an inline span) so
471     * the value gets both its base direction and alignment, overriding the diff
472     * table's inherited direction. Empty when the language is unknown.
473     *
474     * @param array{code:string,dir:string}|null $language
475     * @return array
476     */
477    private function languageCellAttributes( ?array $language ): array {
478        if ( $language === null ) {
479            return [];
480        }
481        $attributes = [ 'dir' => $language['dir'] ];
482        if ( $language['code'] !== '' ) {
483            $attributes['lang'] = $language['code'];
484        }
485        return $attributes;
486    }
487
488    /**
489     * Turn a diff path into a human-readable breadcrumb: the head segment (a
490     * top-level ZPersistentObject key) becomes its localised group label, keys
491     * become their labels, and a list index becomes the identity of the item it
492     * points at.
493     *
494     * @param array $path Sequence of keys/indices, e.g. [ 'Z2K3', 'Z12K1', 1, 'Z11K2' ]
495     * @param bool $dropGroupHead When true, the top-level group key is shown as a
496     *   section heading, so drop it from the breadcrumb
497     * @param DiffOp|null $op The operation this path names, where the last segment
498     *   is a list index and the operation therefore carries the whole item
499     * @return string Plain text, e.g. "Name / English"
500     */
501    private function renderPathLabel(
502        array $path, bool $dropGroupHead = false, ?DiffOp $op = null
503    ): string {
504        if ( $path === [] ) {
505            return $dropGroupHead
506                ? ''
507                : $this->messageLocalizer->msg( 'wikilambda-diff-group-object' )->text();
508        }
509
510        $segments = $dropGroupHead ? [] : [ $this->localiseGroupKey( (string)$path[0] ) ];
511        for ( $position = 1; $position < count( $path ); $position++ ) {
512            $segment = $path[$position];
513            if ( !is_int( $segment ) ) {
514                $segments[] = $this->labels->getKeyLabel( (string)$segment );
515                continue;
516            }
517
518            $handle = $this->itemHandle( $path, $position, $op );
519            if ( $handle === null ) {
520                // Nothing identifies the item, so its position is all there is.
521                $segments[] = (string)$segment;
522            } elseif ( $segments === [] ) {
523                $segments[] = $handle;
524            } else {
525                // Qualify the key naming the list, rather than reading as another
526                // step along the path — the same shape as "Name (English)".
527                $segments[count( $segments ) - 1] .= ' (' . $handle . ')';
528            }
529        }
530        return implode( ' / ', $segments );
531    }
532
533    /**
534     * Name the list item a path points at, or return null to leave it numbered.
535     *
536     * Which of the two Objects to read the item from needs care, because a list
537     * index is only meaningful on one side once the list has changed length:
538     * removing the fourth of five items leaves a different item at index three in
539     * the new Object. So where the operation carries the whole item — an addition
540     * or a removal of it — that value is used, which is exact. Otherwise the
541     * change is to something inside the item, which therefore exists on both
542     * sides, and a handle is used only when both sides agree on it; disagreement
543     * means the lists are misaligned, and a number is better than a wrong name.
544     *
545     * @param array $path
546     * @param int $position Which segment of the path the item's index is
547     * @param DiffOp|null $op
548     * @return string|null
549     */
550    private function itemHandle( array $path, int $position, ?DiffOp $op ): ?string {
551        // The operation carries the whole item only when the path stops at it.
552        if ( $op !== null && $position === count( $path ) - 1 ) {
553            if ( $op instanceof DiffOpMove ) {
554                return $this->items->getHandle( $op->getValue() );
555            }
556            if ( $op instanceof DiffOpAdd || $op instanceof DiffOpRemove ) {
557                return $this->items->getHandle( $this->sidedValue( $op ) );
558            }
559        }
560
561        $itemPath = array_slice( $path, 0, $position + 1 );
562        $new = $this->navigate( $this->newObject, $itemPath );
563        $old = $this->navigate( $this->oldObject, $itemPath );
564        if ( $new === null || $old === null ) {
565            // Present on one side only, so whichever it is names it unambiguously.
566            return $this->items->getHandle( $new ?? $old );
567        }
568
569        $handle = $this->items->getHandle( $new );
570        return ( $handle !== null && $handle === $this->items->getHandle( $old ) ) ? $handle : null;
571    }
572
573    /**
574     * Map a top-level ZPersistentObject key to its localised group label,
575     * falling back to the raw key for anything unrecognised.
576     *
577     * @param string $key
578     * @return string
579     */
580    private function localiseGroupKey( string $key ): string {
581        $message = match ( $key ) {
582            ZTypeRegistry::Z_PERSISTENTOBJECT_ID => 'wikilambda-diff-group-zid',
583            ZTypeRegistry::Z_PERSISTENTOBJECT_VALUE => 'wikilambda-diff-group-value',
584            ZTypeRegistry::Z_PERSISTENTOBJECT_LABEL => 'wikilambda-diff-group-name',
585            ZTypeRegistry::Z_PERSISTENTOBJECT_ALIASES => 'wikilambda-diff-group-aliases',
586            ZTypeRegistry::Z_PERSISTENTOBJECT_DESCRIPTION => 'wikilambda-diff-group-description',
587            default => null,
588        };
589        return $message === null ? $key : $this->messageLocalizer->msg( $message )->text();
590    }
591
592    /**
593     * Render the value row(s) for a single atomic diff operation (fallback path,
594     * used when no language-aware layout applies).
595     *
596     * @param DiffOp $op
597     * @param string|null $valueKey The key immediately holding the changed value
598     * @return string
599     */
600    private function generateOpRowHtml( DiffOp $op, ?string $valueKey = null ): string {
601        // A move reports itself as a change, so test for it before the type.
602        if ( $op instanceof DiffOpMove ) {
603            return $this->generateMoveRowHtml( $op, $valueKey );
604        }
605
606        switch ( $op->getType() ) {
607            case 'add':
608                '@phan-var DiffOpAdd $op';
609                return $this->generateHtmlDiffTableRow(
610                    null,
611                    $this->getChangedLine( 'ins', $op->getNewValue(), $valueKey )
612                );
613
614            case 'remove':
615                '@phan-var DiffOpRemove $op';
616                return $this->generateHtmlDiffTableRow(
617                    $this->getChangedLine( 'del', $op->getOldValue(), $valueKey ),
618                    null
619                );
620
621            case 'change':
622                '@phan-var DiffOpChange $op';
623                return $this->generateChangeRowHtml( $op, $valueKey );
624
625            default:
626                throw new UnexpectedValueException( 'Unsupported diff operation type: ' . $op->getType() );
627        }
628    }
629
630    /**
631     * Render a change to a leaf value. A reference-valued change is shown as a
632     * whole-token swap of links (old on the deleted side, new on the added);
633     * anything else uses an inline word-level diff.
634     *
635     * @param DiffOpChange $op
636     * @param string|null $valueKey The key immediately holding the changed value
637     * @param array{code:string,dir:string}|null $oldLanguage Old value's language, if any
638     * @param array{code:string,dir:string}|null $newLanguage New value's language, if any
639     * @return string
640     */
641    private function generateChangeRowHtml(
642        DiffOpChange $op, ?string $valueKey = null, ?array $oldLanguage = null, ?array $newLanguage = null
643    ): string {
644        $oldValue = $op->getOldValue();
645        $newValue = $op->getNewValue();
646
647        // Show both sides whole, rather than word-diffing them against each other,
648        // when either is a structure — a value swapped for one of a different
649        // type, say — or a reference. Word-diffing those compares serialisations
650        // and ZID spellings, not meanings.
651        if ( $this->values->rendersWhole( $oldValue, $valueKey )
652            || $this->values->rendersWhole( $newValue, $valueKey )
653        ) {
654            return $this->generateHtmlDiffTableRow(
655                $this->getChangedLine( 'del', $oldValue, $valueKey ),
656                $this->getChangedLine( 'ins', $newValue, $valueKey ),
657                $oldLanguage,
658                $newLanguage
659            );
660        }
661
662        $old = $this->values->renderText( $oldValue );
663        $new = $this->values->renderText( $newValue );
664
665        // WordLevelDiff splits its input on newlines and returns one
666        // (already-escaped) HTML fragment per line; ZObject leaf values may be
667        // multi-line, so join every line with a visible break rather than
668        // taking only the first as a single-line diff would.
669        $wordLevelDiff = new WordLevelDiff( [ $old ], [ $new ] );
670        return $this->generateHtmlDiffTableRow(
671            implode( '<br />', $wordLevelDiff->orig() ),
672            implode( '<br />', $wordLevelDiff->closing() ),
673            $oldLanguage,
674            $newLanguage
675        );
676    }
677
678    /**
679     * Render a re-ordered item as the position it left against the position it
680     * now holds, showing the item on both sides.
681     *
682     * The item has to be shown even though its content did not change, because
683     * the row's header does not always say which item this is: a re-ordered
684     * alias, for instance, is headed by its language, which every alias in the
685     * set shares. Positions alone would leave the reader nothing to go on.
686     *
687     * Positions are shown as they are in the list, where the first item is at
688     * index 1, index 0 being the reference to the type of the items.
689     *
690     * @param DiffOpMove $op
691     * @param string|null $valueKey The key immediately holding the item
692     * @param array{code:string,dir:string}|null $oldLanguage
693     * @param array{code:string,dir:string}|null $newLanguage
694     * @return string
695     */
696    private function generateMoveRowHtml(
697        DiffOpMove $op, ?string $valueKey = null, ?array $oldLanguage = null, ?array $newLanguage = null
698    ): string {
699        $value = $this->values->render( $op->getValue(), $valueKey );
700        return $this->generateHtmlDiffTableRow(
701            $this->generateMovedLine( 'del', $op->getOldIndex(), $value ),
702            $this->generateMovedLine( 'ins', $op->getNewIndex(), $value ),
703            $oldLanguage,
704            $newLanguage
705        );
706    }
707
708    /**
709     * One side of a re-ordering: the item, and where it sits on this side.
710     *
711     * @param string $tag 'ins' or 'del'
712     * @param int $index
713     * @param string $valueHtml The rendered item, already escaped
714     * @return string
715     */
716    private function generateMovedLine( string $tag, int $index, string $valueHtml ): string {
717        return Html::rawElement(
718            $tag,
719            [ 'class' => 'diffchange diffchange-inline' ],
720            $this->messageLocalizer->msg( 'wikilambda-diff-value-moved' )
721                ->numParams( $index )
722                ->rawParams( $valueHtml )
723                ->text()
724        );
725    }
726
727    /**
728     * Return the value carried by an added or removed diff operation, narrowing
729     * the base DiffOp type to the add/remove subtypes that expose it.
730     *
731     * @param DiffOp $op
732     * @return mixed The new value for an addition, the old value for a removal,
733     *   or null for any other operation type
734     */
735    private function sidedValue( DiffOp $op ) {
736        if ( $op instanceof DiffOpAdd ) {
737            return $op->getNewValue();
738        }
739        if ( $op instanceof DiffOpRemove ) {
740            return $op->getOldValue();
741        }
742        return null;
743    }
744
745    /**
746     * Wrap a value in an inline diff-change element, rendered as readable,
747     * escaped HTML.
748     *
749     * @param string $tag 'ins' for additions, 'del' for removals
750     * @param mixed $value
751     * @param string|null $valueKey The key immediately holding the value
752     * @return string
753     */
754    private function getChangedLine( string $tag, $value, ?string $valueKey = null ): string {
755        return Html::rawElement(
756            $tag,
757            [ 'class' => 'diffchange diffchange-inline' ],
758            $this->values->render( $value, $valueKey )
759        );
760    }
761
762    /**
763     * The key that says how a leaf value at this path should be read — in
764     * particular whether a reference-shaped one may be linked to its target.
765     *
766     * Normally the last path segment, but a value at a list index has no key of
767     * its own, and the index carries none of the meaning a key would: taking it
768     * literally would treat every item of every list as linkable, so a plain
769     * string that happened to read "Z40" would become a link. Judge such an item
770     * by the list's declared item type instead, and otherwise fall back to the
771     * nearest enclosing key.
772     *
773     * @param array $path
774     * @return string|null Null when nothing in the path decides it, meaning the
775     *   value is free text and must not be linked
776     */
777    private function valueKeyOf( array $path ): ?string {
778        for ( $position = count( $path ) - 1; $position >= 0; $position-- ) {
779            $segment = $path[$position];
780            if ( !is_int( $segment ) ) {
781                return (string)$segment;
782            }
783
784            $listPath = array_slice( $path, 0, $position );
785            $list = $this->navigate( $this->newObject, $listPath )
786                ?? $this->navigate( $this->oldObject, $listPath );
787            if ( is_array( $list ) && ( $list[0] ?? null ) === ZTypeRegistry::Z_STRING ) {
788                // A list of strings holds literal text, however it is spelled.
789                return ZTypeRegistry::Z_STRING_VALUE;
790            }
791        }
792        return null;
793    }
794
795    /**
796     * Emit a full-width table row carrying an <h2> section heading (e.g. the
797     * "About" and "Contents" super-groups).
798     *
799     * @param string $messageKey
800     * @return string
801     */
802    private function generateSectionHeaderHtml( string $messageKey ): string {
803        $heading = Html::element( 'h2', [], $this->messageLocalizer->msg( $messageKey )->text() );
804        return Html::rawElement( 'tr', [],
805            Html::rawElement( 'td', [ 'colspan' => '4' ], $heading ) );
806    }
807
808    /**
809     * Emit the two-cell 'diff-lineno' header row that labels a change. The two
810     * cells can differ, because an edit can change what the value is a label
811     * for; each cell then labels its own side.
812     *
813     * @param string $oldName Plain-text label for the deleted side
814     * @param string|null $newName Plain-text label for the added side, or null
815     *   where both sides carry the same label
816     * @return string
817     */
818    private function generateDiffHeaderHtml( string $oldName, ?string $newName = null ): string {
819        $cell = static fn ( string $name ): string =>
820            Html::element( 'td', [ 'colspan' => '2', 'class' => 'diff-lineno' ], $name );
821        return Html::rawElement( 'tr', [], $cell( $oldName ) . $cell( $newName ?? $oldName ) );
822    }
823
824    /**
825     * Emit a diff-table row with the old (deleted) and/or new (added) sides.
826     * At least one of the two HTML fragments must be non-null.
827     *
828     * @param string|null $oldHtml Pre-escaped HTML for the deleted side, or null
829     * @param string|null $newHtml Pre-escaped HTML for the added side, or null
830     * @param array{code:string,dir:string}|null $oldLanguage Language/direction to
831     *   tag the deleted value with; null leaves it undirected
832     * @param array{code:string,dir:string}|null $newLanguage Language/direction to
833     *   tag the added value with; null leaves it undirected
834     * @return string
835     */
836    private function generateHtmlDiffTableRow(
837        ?string $oldHtml, ?string $newHtml, ?array $oldLanguage = null, ?array $newLanguage = null
838    ): string {
839        $html = Html::openElement( 'tr' );
840        if ( $oldHtml !== null ) {
841            $html .= Html::rawElement( 'td', [ 'class' => 'diff-marker', 'data-marker' => '−' ] );
842            $html .= Html::rawElement( 'td', [ 'class' => 'diff-deletedline' ],
843                Html::rawElement( 'div', $this->languageCellAttributes( $oldLanguage ), $oldHtml ) );
844        }
845        if ( $newHtml !== null ) {
846            if ( $oldHtml === null ) {
847                $html .= Html::element( 'td', [ 'colspan' => '2' ], "\u{00A0}" );
848            }
849            $html .= Html::rawElement( 'td', [ 'class' => 'diff-marker', 'data-marker' => '+' ] );
850            $html .= Html::rawElement( 'td', [ 'class' => 'diff-addedline' ],
851                Html::rawElement( 'div', $this->languageCellAttributes( $newLanguage ), $newHtml ) );
852        }
853        $html .= Html::closeElement( 'tr' );
854        return $html;
855    }
856}