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