summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/web/src/FormElement/TermInput.php
blob: 352cce44b589b05df0478e71894bf4eba15da8b7 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<?php

namespace ipl\Web\FormElement;

use ipl\Html\Attributes;
use ipl\Html\Form;
use ipl\Html\FormElement\FieldsetElement;
use ipl\Html\FormElement\HiddenElement;
use ipl\Html\HtmlElement;
use ipl\Html\HtmlString;
use ipl\Stdlib\Events;
use ipl\Web\FormElement\TermInput\RegisteredTerm;
use ipl\Web\FormElement\TermInput\TermContainer;
use ipl\Web\FormElement\TermInput\ValidatedTerm;
use ipl\Web\Url;
use Psr\Http\Message\ServerRequestInterface;

class TermInput extends FieldsetElement
{
    use Events;

    /** @var string Emitted in case the user added new terms */
    const ON_ADD = 'on_add';

    /** @var string Emitted in case the user inserted new terms */
    const ON_PASTE = 'on_paste';

    /** @var string Emitted in case the user changed existing terms */
    const ON_SAVE = 'on_save';

    /** @var string Emitted in case the user removed terms */
    const ON_REMOVE = 'on_remove';

    /** @var string Emitted in case terms need to be enriched */
    const ON_ENRICH = 'on_enrich';

    /** @var Url The suggestion url */
    protected $suggestionUrl;

    /** @var bool Whether term direction is vertical */
    protected $verticalTermDirection = false;

    /** @var array Changes to transmit to the client */
    protected $changes = [];

    /** @var RegisteredTerm[] The terms */
    protected $terms = [];

    /** @var bool Whether this input has been automatically submitted */
    private $hasBeenAutoSubmitted = false;

    /** @var bool Whether the term input value has been pasted */
    private $valueHasBeenPasted;

    /** @var TermContainer The term container */
    protected $termContainer;

    /**
     * Set the suggestion url
     *
     * @param Url $url
     *
     * @return $this
     */
    public function setSuggestionUrl(Url $url): self
    {
        $this->suggestionUrl = $url;

        return $this;
    }

    /**
     * Get the suggestion url
     *
     * @return ?Url
     */
    public function getSuggestionUrl(): ?Url
    {
        return $this->suggestionUrl;
    }

    /**
     * Set whether term direction should be vertical
     *
     * @param bool $state
     *
     * @return $this
     */
    public function setVerticalTermDirection(bool $state = true): self
    {
        $this->verticalTermDirection = $state;

        return $this;
    }

    /**
     * Get the desired term direction
     *
     * @return ?string
     */
    public function getTermDirection(): ?string
    {
        return $this->verticalTermDirection ? 'vertical' : null;
    }

    /**
     * Set terms
     *
     * @param RegisteredTerm ...$terms
     *
     * @return $this
     */
    public function setTerms(RegisteredTerm ...$terms): self
    {
        $this->terms = $terms;

        return $this;
    }

    /**
     * Get the terms
     *
     * @return RegisteredTerm[]
     */
    public function getTerms(): array
    {
        return $this->terms;
    }

    public function getElements()
    {
        // TODO: Only a quick-fix. Remove once fieldsets are properly partially validated
        $this->ensureAssembled();

        return parent::getElements();
    }

    public function getValue($name = null, $default = null)
    {
        if ($name !== null) {
            return parent::getValue($name, $default);
        }

        $terms = [];
        foreach ($this->getTerms() as $term) {
            $terms[] = $term->render(',');
        }

        return implode(',', $terms);
    }

    public function setValue($value)
    {
        $recipients = $value;
        if (is_array($value)) {
            $recipients = $value['value'] ?? '';
            parent::setValue($value);
        }

        $terms = [];
        foreach ($this->parseValue($recipients) as $term) {
            $terms[] = new RegisteredTerm($term);
        }

        return $this->setTerms(...$terms);
    }

    /**
     * Parse the given separated string of terms
     *
     * @param string $value
     *
     * @return string[]
     */
    public function parseValue(string $value): array
    {
        $terms = [];

        $term = '';
        $ignoreSeparator = false;
        for ($i = 0; $i <= strlen($value); $i++) {
            if (! isset($value[$i])) {
                if (! empty($term)) {
                    $terms[] = rawurldecode($term);
                }

                break;
            }

            $c = $value[$i];
            if ($c === '"') {
                $ignoreSeparator = ! $ignoreSeparator;
            } elseif (! $ignoreSeparator && $c === ',') {
                $terms[] = rawurldecode($term);
                $term = '';
            } else {
                $term .= $c;
            }
        }

        return $terms;
    }

    /**
     * Prepare updates to transmit for this input during multipart responses
     *
     * @param ServerRequestInterface $request
     *
     * @return array
     */
    public function prepareMultipartUpdate(ServerRequestInterface $request): array
    {
        $updates = [];
        if ($this->valueHasBeenPasted()) {
            $updates[] = $this->termContainer();
            $updates[] = [
                HtmlString::create(json_encode(['#' . $this->getName() . '-search-input', []])),
                'Behavior:InputEnrichment'
            ];
        } elseif (! empty($this->changes)) {
            $updates[] = [
                HtmlString::create(json_encode(['#' . $this->getName() . '-search-input', $this->changes])),
                'Behavior:InputEnrichment'
            ];
        }

        if (empty($updates) && $this->hasBeenAutoSubmitted()) {
            $updates[] = $updates[] = [
                HtmlString::create(json_encode(['#' . $this->getName() . '-search-input', 'bogus'])),
                'Behavior:InputEnrichment'
            ];
        }

        return $updates;
    }

    /**
     * Get whether this input has been automatically submitted
     *
     * @return bool
     */
    private function hasBeenAutoSubmitted(): bool
    {
        return $this->hasBeenAutoSubmitted;
    }

    /**
     * Get whether the term input value has been pasted
     *
     * @return bool
     */
    private function valueHasBeenPasted(): bool
    {
        if ($this->valueHasBeenPasted === null) {
            $this->valueHasBeenPasted = ($this->getElement('data')->getValue()['type'] ?? null) === 'paste';
        }

        return $this->valueHasBeenPasted;
    }

    public function onRegistered(Form $form)
    {
        $termContainerId = $this->getName() . '-terms';
        $mainInputId = $this->getName() . '-search-input';
        $autoSubmittedBy = $form->getRequest()->getHeader('X-Icinga-Autosubmittedby');

        $this->hasBeenAutoSubmitted = in_array($mainInputId, $autoSubmittedBy, true)
            || in_array($termContainerId, $autoSubmittedBy, true);

        parent::onRegistered($form);
    }

    /**
     * Validate the given terms
     *
     * @param string $type The type of change to validate
     * @param array $terms The terms affected by the change
     * @param array $changes Potential changes made by validators
     *
     * @return bool
     */
    private function validateTerms(string $type, array $terms, array &$changes): bool
    {
        $validatedTerms = [];
        foreach ($terms as $index => $data) {
            $validatedTerms[$index] = ValidatedTerm::fromTermData($data);
        }

        switch ($type) {
            case 'submit':
            case 'exchange':
                $type = self::ON_ADD;

                break;
            case 'paste':
                $type = self::ON_PASTE;

                break;
            case 'save':
                $type = self::ON_SAVE;

                break;
            case 'remove':
            default:
                return true;
        }

        $this->emit($type, [$validatedTerms]);

        $invalid = false;
        foreach ($validatedTerms as $index => $term) {
            if (! $term->isValid()) {
                $invalid = true;
            }

            if (! $term->isValid() || $term->hasBeenChanged()) {
                $changes[$index] = $term->toTermData();
            }
        }

        return $invalid;
    }

    /**
     * Get the term container
     *
     * @return TermContainer
     */
    protected function termContainer(): TermContainer
    {
        if ($this->termContainer === null) {
            $this->termContainer = (new TermContainer($this))
                ->setAttribute('id', $this->getName() . '-terms');
        }

        return $this->termContainer;
    }

    protected function assemble()
    {
        $myName = $this->getName();

        $termInputId = $myName . '-term-input';
        $dataInputId = $myName . '-data-input';
        $searchInputId = $myName . '-search-input';
        $suggestionsId = $myName . '-suggestions';

        $termContainer = $this->termContainer();

        $suggestions = (new HtmlElement('div'))
            ->setAttribute('id', $suggestionsId)
            ->setAttribute('class', 'search-suggestions');

        $termInput = $this->createElement('hidden', 'value', [
            'id' => $termInputId,
            'disabled' => true
        ]);

        $dataInput = new class ('data', [
            'ignore' => true,
            'id' => $dataInputId,
            'validators' => ['callback' => function ($data) use ($termContainer) {
                $changes = [];
                $invalid = $this->validateTerms($data['type'], $data['terms'] ?? [], $changes);
                $this->changes = $changes;

                $terms = $this->getTerms();
                foreach ($changes as $index => $termData) {
                    $terms[$index]->applyTermData($termData);
                }

                return ! $invalid;
            }]
        ]) extends HiddenElement {
            /** @var TermInput */
            private $parent;

            public function setParent(TermInput $parent): void
            {
                $this->parent = $parent;
            }

            public function setValue($value)
            {
                $data = json_decode($value, true);
                if (($data['type'] ?? null) === 'paste') {
                    array_push($data['terms'], ...array_map(function ($t) {
                        return ['search' => $t];
                    }, $this->parent->parseValue($data['input'])));
                }

                return parent::setValue($data);
            }

            public function getValueAttribute()
            {
                return null;
            }
        };
        $dataInput->setParent($this);

        $label = $this->getLabel();
        $this->setLabel(null);

        // TODO: Separator customization
        $mainInput = $this->createElement('text', 'value', [
            'id' => $searchInputId,
            'label' => $label,
            'required' => $this->isRequired(),
            'placeholder' => $this->translate('Type to search. Separate multiple terms by comma.'),
            'class' => 'term-input',
            'autocomplete' => 'off',
            'data-term-separator' => ',',
            'data-enrichment-type' => 'terms',
            'data-with-multi-completion' => true,
            'data-no-auto-submit-on-remove' => true,
            'data-term-direction' => $this->getTermDirection(),
            'data-data-input' => '#' . $dataInputId,
            'data-term-input' => '#' . $termInputId,
            'data-term-container' => '#' . $termContainer->getAttribute('id')->getValue(),
            'data-term-suggestions' => '#' . $suggestionsId
        ]);
        $mainInput->getAttributes()
            ->registerAttributeCallback('value', function () {
                return null;
            });
        if ($this->getSuggestionUrl() !== null) {
            $mainInput->getAttributes()->registerAttributeCallback('data-suggest-url', function () {
                return (string) $this->getSuggestionUrl();
            });
        }

        $this->addElement($termInput);
        $this->addElement($dataInput);
        $this->addElement($mainInput);

        $mainInput->prependWrapper((new HtmlElement(
            'div',
            Attributes::create(['class' => ['term-input-area', $this->getTermDirection()]]),
            $termContainer,
            new HtmlElement('label', null, $mainInput)
        )));

        $this->addHtml($suggestions);

        if (! $this->hasBeenAutoSubmitted()) {
            $this->emit(self::ON_ENRICH, [$this->getTerms()]);
        }
    }
}