xref: /webtrees/app/Module/InteractiveTree/TreeView.php (revision e873f434551745f888937263ff89e80db3b0f785)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module\InteractiveTree;
21
22use Fisharebest\Webtrees\Family;
23use Fisharebest\Webtrees\Gedcom;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Individual;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Support\Collection;
29
30use function count;
31
32use const JSON_THROW_ON_ERROR;
33
34/**
35 * Class TreeView
36 */
37class TreeView
38{
39    // HTML element name
40    private string $name;
41
42    /**
43     * Treeview Constructor
44     *
45     * @param string $name the name of the TreeView object’s instance
46     */
47    public function __construct(string $name = 'tree')
48    {
49        $this->name = $name;
50    }
51
52    /**
53     * Draw the viewport which creates the draggable/zoomable framework
54     * Size is set by the container, as the viewport can scale itself automatically
55     *
56     * @param Individual $individual  Draw the chart for this individual
57     * @param int        $generations number of generations to draw
58     *
59     * @return array<string>  HTML and Javascript
60     */
61    public function drawViewport(Individual $individual, int $generations): array
62    {
63        $html = view('modules/interactive-tree/chart', [
64            'module'     => 'tree',
65            'name'       => $this->name,
66            'individual' => $this->drawPerson($individual, $generations, 0, null, '', true),
67            'tree'       => $individual->tree(),
68        ]);
69
70        return [
71            $html,
72            'var ' . $this->name . 'Handler = new TreeViewHandler("' . $this->name . '", "' . e($individual->tree()->name()) . '");',
73        ];
74    }
75
76    /**
77     * Return a JSON structure to a JSON request
78     *
79     * @param Tree   $tree
80     * @param string $request list of JSON requests
81     *
82     * @return string
83     */
84    public function getIndividuals(Tree $tree, string $request): string
85    {
86        $json_requests = explode(';', $request);
87        $r             = [];
88
89        foreach ($json_requests as $json_request) {
90            $firstLetter = substr($json_request, 0, 1);
91            $json_request = substr($json_request, 1);
92
93            switch ($firstLetter) {
94                case 'c':
95                    $families = Collection::make(explode(',', $json_request))
96                        ->map(static fn (string $xref): Family|null => Registry::familyFactory()->make($xref, $tree))
97                        ->filter();
98
99                    $r[] = $this->drawChildren($families, 1, true);
100                    break;
101
102                case 'p':
103                    [$xref, $order] = explode('@', $json_request);
104
105                    $family = Registry::familyFactory()->make($xref, $tree);
106                    if ($family instanceof Family) {
107                        // Prefer the paternal line
108                        $parent = $family->husband() ?? $family->wife();
109
110                        // The family may have no parents (just children).
111                        if ($parent instanceof Individual) {
112                            $r[] = $this->drawPerson($parent, 0, 1, $family, $order, false);
113                        }
114                    }
115                    break;
116            }
117        }
118
119        return json_encode($r, JSON_THROW_ON_ERROR);
120    }
121
122    /**
123     * Get the details for a person and their life partner(s)
124     *
125     * @param Individual $individual the individual to return the details for
126     *
127     * @return string
128     */
129    public function getDetails(Individual $individual): string
130    {
131        $html = $this->getPersonDetails($individual, null);
132        foreach ($individual->spouseFamilies() as $family) {
133            $spouse = $family->spouse($individual);
134            if ($spouse) {
135                $html .= $this->getPersonDetails($spouse, $family);
136            }
137        }
138
139        return $html;
140    }
141
142    /**
143     * Return the details for a person
144     *
145     * @param Individual  $individual
146     * @param Family|null $family
147     *
148     * @return string
149     */
150    private function getPersonDetails(Individual $individual, Family|null $family = null): string
151    {
152        $chart_url = route('module', [
153            'module' => 'tree',
154            'action' => 'Chart',
155            'xref'   => $individual->xref(),
156            'tree'   => $individual->tree()->name(),
157        ]);
158
159        $hmtl = $this->getThumbnail($individual);
160        $hmtl .= '<a class="tv_link" href="' . e($individual->url()) . '">' . $individual->fullName() . '</a> <a href="' . e($chart_url) . '" title="' . I18N::translate('Interactive tree of %s', strip_tags($individual->fullName())) . '" class="tv_link tv_treelink">' . view('icons/individual') . '</a>';
161        foreach ($individual->facts(Gedcom::BIRTH_EVENTS, true) as $fact) {
162            $hmtl .= $fact->summary();
163        }
164        if ($family instanceof Family) {
165            foreach ($family->facts(Gedcom::MARRIAGE_EVENTS, true) as $fact) {
166                $hmtl .= $fact->summary();
167            }
168        }
169        foreach ($individual->facts(Gedcom::DEATH_EVENTS, true) as $fact) {
170            $hmtl .= $fact->summary();
171        }
172
173        return '<div class="tv' . $individual->sex() . ' tv_person_expanded">' . $hmtl . '</div>';
174    }
175
176    /**
177     * Draw the children for some families
178     *
179     * @param Collection<int,Family> $familyList array of families to draw the children for
180     * @param int                    $gen        number of generations to draw
181     * @param bool                   $ajax       true for an ajax call
182     *
183     * @return string
184     */
185    private function drawChildren(Collection $familyList, int $gen = 1, bool $ajax = false): string
186    {
187        $html          = '';
188        $children2draw = [];
189        $f2load        = [];
190
191        foreach ($familyList as $f) {
192            $children = $f->children();
193            if ($children->isNotEmpty()) {
194                $f2load[] = $f->xref();
195                foreach ($children as $child) {
196                    // Eliminate duplicates - e.g. when adopted by a step-parent
197                    $children2draw[$child->xref()] = $child;
198                }
199            }
200        }
201        $tc = count($children2draw);
202        if ($tc > 0) {
203            $f2load = implode(',', $f2load);
204            $nbc    = 0;
205            foreach ($children2draw as $child) {
206                $nbc++;
207                if ($tc === 1) {
208                    $co = 'c'; // unique
209                } elseif ($nbc === 1) {
210                    $co = 't'; // first
211                } elseif ($nbc === $tc) {
212                    $co = 'b'; //last
213                } else {
214                    $co = 'h';
215                }
216                $html .= $this->drawPerson($child, $gen - 1, -1, null, $co, false);
217            }
218            if (!$ajax) {
219                $html = '<td align="right"' . ($gen === 0 ? ' abbr="c' . $f2load . '"' : '') . '>' . $html . '</td>' . $this->drawHorizontalLine();
220            }
221        }
222
223        return $html;
224    }
225
226    /**
227     * Draw a person in the tree
228     *
229     * @param Individual  $person The Person object to draw the box for
230     * @param int         $gen    The number of generations up or down to print
231     * @param int         $state  Whether we are going up or down the tree, -1 for descendents +1 for ancestors
232     * @param Family|null $pfamily
233     * @param string      $line   b, c, h, t. Required for drawing lines between boxes
234     * @param bool        $isRoot
235     *
236     * @return string
237     */
238    private function drawPerson(Individual $person, int $gen, int $state, Family|null $pfamily, string $line, bool $isRoot): string
239    {
240        if ($gen < 0) {
241            return '';
242        }
243
244        if ($pfamily instanceof Family) {
245            $partner = $pfamily->spouse($person);
246        } else {
247            $partner = $person->getCurrentSpouse();
248        }
249
250        if ($isRoot) {
251            $html = '<table id="tvTreeBorder" class="tv_tree"><tbody><tr><td id="tv_tree_topleft"></td><td id="tv_tree_top"></td><td id="tv_tree_topright"></td></tr><tr><td id="tv_tree_left"></td><td>';
252        } else {
253            $html = '';
254        }
255        /* height 1% : this hack enable the div auto-dimensioning in td for FF & Chrome */
256        $html .= '<table class="tv_tree"' . ($isRoot ? ' id="tv_tree"' : '') . ' style="height: 1%"><tbody><tr>';
257
258        if ($state <= 0) {
259            // draw children
260            $html .= $this->drawChildren($person->spouseFamilies(), $gen);
261        } else {
262            // draw the parent’s lines
263            $html .= $this->drawVerticalLine($line) . $this->drawHorizontalLine();
264        }
265
266        /* draw the person. Do NOT add person or family id as an id, since a same person could appear more than once in the tree !!! */
267        // Fixing the width for td to the box initial width when the person is the root person fix a rare bug that happen when a person without child and without known parents is the root person : an unwanted white rectangle appear at the right of the person’s boxes, otherwise.
268        $html .= '<td' . ($isRoot ? ' style="width:1px"' : '') . '><div class="tv_box' . ($isRoot ? ' rootPerson' : '') . '" dir="' . I18N::direction() . '" style="text-align: ' . (I18N::direction() === 'rtl' ? 'right' : 'left') . '; direction: ' . I18N::direction() . '" abbr="' . $person->xref() . '" onclick="' . $this->name . 'Handler.expandBox(this, event);">';
269        $html .= $this->drawPersonName($person, '');
270
271        $fop = []; // $fop is fathers of partners
272
273        if ($partner !== null) {
274            $dashed = '';
275            foreach ($person->spouseFamilies() as $family) {
276                $spouse = $family->spouse($person);
277                if ($spouse instanceof Individual) {
278                    $spouse_parents = $spouse->childFamilies()->first();
279                    if ($spouse_parents instanceof Family) {
280                        $spouse_parent = $spouse_parents->husband() ?? $spouse_parents->wife();
281
282                        if ($spouse_parent instanceof Individual) {
283                            $fop[] = [$spouse_parent, $spouse_parents];
284                        }
285                    }
286
287                    $html .= $this->drawPersonName($spouse, $dashed);
288                    $dashed = 'dashed';
289                }
290            }
291        }
292        $html .= '</div></td>';
293
294        $primaryChildFamily = $person->childFamilies()->first();
295        if ($primaryChildFamily instanceof Family) {
296            $parent = $primaryChildFamily->husband() ?? $primaryChildFamily->wife();
297        } else {
298            $parent = null;
299        }
300
301        if ($parent instanceof Individual || $fop !== [] || $state < 0) {
302            $html .= $this->drawHorizontalLine();
303        }
304
305        /* draw the parents */
306        if ($state >= 0 && ($parent instanceof Individual || $fop !== [])) {
307            $unique = $parent === null || $fop === [];
308            $html .= '<td align="left"><table class="tv_tree"><tbody>';
309
310            if ($parent instanceof Individual) {
311                $u = $unique ? 'c' : 't';
312                $html .= '<tr><td ' . ($gen === 0 ? ' abbr="p' . $primaryChildFamily->xref() . '@' . $u . '"' : '') . '>';
313                $html .= $this->drawPerson($parent, $gen - 1, 1, $primaryChildFamily, $u, false);
314                $html .= '</td></tr>';
315            }
316
317            if ($fop !== []) {
318                $n  = 0;
319                $nb = count($fop);
320                foreach ($fop as $p) {
321                    $n++;
322                    $u = $unique ? 'c' : ($n === $nb || empty($p[1]) ? 'b' : 'h');
323                    $html .= '<tr><td ' . ($gen === 0 ? ' abbr="p' . $p[1]->xref() . '@' . $u . '"' : '') . '>' . $this->drawPerson($p[0], $gen - 1, 1, $p[1], $u, false) . '</td></tr>';
324                }
325            }
326            $html .= '</tbody></table></td>';
327        }
328
329        if ($state < 0) {
330            $html .= $this->drawVerticalLine($line);
331        }
332
333        $html .= '</tr></tbody></table>';
334
335        if ($isRoot) {
336            $html .= '</td><td id="tv_tree_right"></td></tr><tr><td id="tv_tree_bottomleft"></td><td id="tv_tree_bottom"></td><td id="tv_tree_bottomright"></td></tr></tbody></table>';
337        }
338
339        return $html;
340    }
341
342    /**
343     * Draw a person name preceded by sex icon, with parents as tooltip
344     *
345     * @param Individual $individual The individual to draw
346     * @param string     $dashed     Either "dashed", to print dashed top border to separate multiple spouses, or ""
347     *
348     * @return string
349     */
350    private function drawPersonName(Individual $individual, string $dashed): string
351    {
352        $family = $individual->childFamilies()->first();
353        if ($family) {
354            $family_name = strip_tags($family->fullName());
355        } else {
356            $family_name = I18N::translateContext('unknown family', 'unknown');
357        }
358        switch ($individual->sex()) {
359            case 'M':
360                /* I18N: e.g. “Son of [father name & mother name]” */
361                $title = ' title="' . I18N::translate('Son of %s', $family_name) . '"';
362                break;
363            case 'F':
364                /* I18N: e.g. “Daughter of [father name & mother name]” */
365                $title = ' title="' . I18N::translate('Daughter of %s', $family_name) . '"';
366                break;
367            default:
368                /* I18N: e.g. “Child of [father name & mother name]” */
369                $title = ' title="' . I18N::translate('Child of %s', $family_name) . '"';
370                break;
371        }
372        $sex = $individual->sex();
373
374        return '<div class="tv' . $sex . ' ' . $dashed . '"' . $title . '><a href="' . e($individual->url()) . '"></a>' . $individual->fullName() . ' <span class="dates">' . $individual->lifespan() . '</span></div>';
375    }
376
377    /**
378     * Get the thumbnail image for the given person
379     *
380     * @param Individual $individual
381     *
382     * @return string
383     */
384    private function getThumbnail(Individual $individual): string
385    {
386        if ($individual->tree()->getPreference('SHOW_HIGHLIGHT_IMAGES') !== '' && $individual->tree()->getPreference('SHOW_HIGHLIGHT_IMAGES') !== '0') {
387            return $individual->displayImage(40, 50, 'crop', []);
388        }
389
390        return '';
391    }
392
393    /**
394     * Draw a vertical line
395     *
396     * @param string $line A parameter that set how to draw this line with auto-resizing capabilities
397     *
398     * @return string
399     * WARNING : some tricky hacks are required in CSS to ensure cross-browser compliance
400     * some browsers shows an image, which imply a size limit in height,
401     * and some other browsers (ex: firefox) shows a <div> tag, which have no size limit in height
402     * Therefore, Firefox is a good choice to print very big trees.
403     */
404    private function drawVerticalLine(string $line): string
405    {
406        return '<td class="tv_vline tv_vline_' . $line . '"><div class="tv_vline tv_vline_' . $line . '"></div></td>';
407    }
408
409    /**
410     * Draw an horizontal line
411     */
412    private function drawHorizontalLine(): string
413    {
414        return '<td class="tv_hline"><div class="tv_hline"></div></td>';
415    }
416}
417