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