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