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