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