summaryrefslogtreecommitdiffstats
path: root/library/Reporting/Web/Flatpickr.php
blob: 5f6605df96dbf1ad0bda6dda696d81252e0b9f61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
// Icinga Reporting | (c) 2019 Icinga GmbH | GPLv2

namespace Icinga\Module\Reporting\Web;

use Icinga\Application\Version;
use ipl\Html\Html;
use ipl\Web\Compat\CompatDecorator;

class Flatpickr extends CompatDecorator
{
    protected $allowInput = true;

    /**
     * Set whether to allow manual input
     *
     * @param bool $state
     *
     * @return $this
     */
    public function setAllowInput(bool $state): self
    {
        $this->allowInput = $state;

        return $this;
    }

    protected function assembleElement()
    {
        if (version_compare(Version::VERSION, '2.9.0', '>=')) {
            $element = parent::assembleElement();
        } else {
            $element = $this->formElement;
        }

        if (version_compare(Version::VERSION, '2.10.0', '<')) {
            $element->getAttributes()->set('data-use-flatpickr-fallback', true);
        } else {
            $element->getAttributes()->set('data-use-datetime-picker', true);
        }

        if (! $this->allowInput) {
            return $element;
        }

        $element->getAttributes()
            ->set('data-input', true)
            ->set('data-flatpickr-wrap', true)
            ->set('data-flatpickr-allow-input', true)
            ->set('data-flatpickr-click-opens', 'false');

        return [
            $element,
            Html::tag('button', ['type' => 'button', 'class' => 'icon-calendar', 'data-toggle' => true]),
            Html::tag('button', ['type' => 'button', 'class' => 'icon-cancel', 'data-clear' => true])
        ];
    }

    protected function assemble()
    {
        if (version_compare(Version::VERSION, '2.9.0', '>=')) {
            parent::assemble();
            return;
        }

        if ($this->formElement->hasBeenValidated() && ! $this->formElement->isValid()) {
            $this->getAttributes()->add('class', 'has-error');
        }

        $this->add(array_filter([
            $this->assembleLabel(),
            $this->assembleElement(),
            $this->assembleDescription(),
            $this->assembleErrors()
        ]));
    }
}