-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseGrid.php
More file actions
540 lines (452 loc) · 19.1 KB
/
BaseGrid.php
File metadata and controls
540 lines (452 loc) · 19.1 KB
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
<?php
/* Icinga Notifications Web | (c) 2023 Icinga GmbH | GPLv2 */
namespace Icinga\Module\Notifications\Widget\TimeGrid;
use DateInterval;
use DateTime;
use Generator;
use Icinga\Module\Notifications\Common\Links;
use ipl\Html\Attributes;
use ipl\Html\BaseHtmlElement;
use ipl\Html\HtmlElement;
use ipl\Html\Text;
use ipl\I18n\Translation;
use ipl\Web\Style;
use ipl\Web\Url;
use ipl\Web\Widget\ButtonLink;
use ipl\Web\Widget\Link;
use LogicException;
use SplObjectStorage;
use Traversable;
use function ipl\Stdlib\iterable_value_first;
/**
* @phpstan-type GridArea array{0: int, 1: int, 2: int, 3: int}
* @phpstan-import-type ContinuationType from Entry
*/
abstract class BaseGrid extends BaseHtmlElement
{
use Translation;
/** @var string The chronological order of entries is oriented horizontally */
protected const HORIZONTAL_FLOW_OF_TIME = 'horizontal-flow';
/** @var string The chronological order of entries is oriented vertically */
protected const VERTICAL_FLOW_OF_TIME = 'vertical-flow';
/** @var int Return this in {@see getSectionsPerStep} to signal an infinite number of sections */
protected const INFINITE = 0;
protected $tag = 'div';
protected $defaultAttributes = ['class' => ['time-grid']];
/** @var string The orientation of this grid's chronological order of entries */
protected $flowOfTime = self::HORIZONTAL_FLOW_OF_TIME;
/** @var EntryProvider */
protected $provider;
/** @var Style */
protected $style;
/** @var DateTime */
protected $start;
/** @var DateTime */
protected $end;
/** @var array Extra counts stored as [date1 => count1, date2 => count2]*/
protected $extraEntriesCount = [];
/**
* Create a new time grid
*
* @param EntryProvider $provider The provider for the grid's entries
* @param Style $style Required to place entries onto the grid's overlay
* @param DateTime $start When the shown timespan should start
*/
public function __construct(EntryProvider $provider, Style $style, DateTime $start)
{
$this->provider = $provider;
$this->style = $style;
$this->setGridStart($start);
// It's done here as there's no real need for this being dynamic
$this->defaultAttributes['class'][] = $this->flowOfTime;
}
public function getGridStart(): DateTime
{
return $this->start;
}
public function setGridStart(DateTime $start): self
{
$this->start = $start;
return $this;
}
public function getGridEnd(): DateTime
{
if ($this->end === null) {
$this->end = $this->calculateGridEnd();
}
return $this->end;
}
/**
* Create steps to show on the grid
*
* @return Traversable<int, GridStep>
*/
abstract protected function createGridSteps(): Traversable;
abstract protected function calculateGridEnd(): DateTime;
abstract protected function getNoOfVisuallyConnectedHours(): int;
/**
* Translate the given grid area positions suitable for the current grid
*
* @param int $rowStart
* @param int $rowEnd
* @param int $colStart
* @param int $colEnd
*
* @return GridArea
*/
protected function getGridArea(int $rowStart, int $rowEnd, int $colStart, int $colEnd): array
{
return [$rowStart, $colStart, $rowEnd, $colEnd];
}
protected function getSectionsPerStep(): int
{
return $this->getMaximumRowSpan();
}
protected function getMaximumRowSpan(): int
{
return 4;
}
protected function getRowStartModifier(): int
{
return 1; // CSS starts counting rows from 1, not zero
}
protected function createGrid(): BaseHtmlElement
{
$grid = new HtmlElement('div', Attributes::create(['class' => 'grid']));
$this->assembleGrid($grid);
return $grid;
}
protected function assembleGrid(BaseHtmlElement $grid): void
{
foreach ($this->createGridSteps() as $step) {
$url = $this->provider->getStepUrl($step);
if ($url !== null) {
$step->setHtmlContent((new Link(null, $url))->openInModal()->addFrom($step));
}
if ($step->getEnd()->format('H') === '00') {
$extraEntryUrl = $this->provider->getExtraEntryUrl($step);
if ($extraEntryUrl !== null) {
$step->addHtml(
(new ExtraEntryCount(null, $extraEntryUrl))
->setGrid($this)
->setGridStep($step->getStart())
);
}
}
$grid->addHtml($step);
}
}
protected function createGridOverlay(): BaseHtmlElement
{
$overlay = new HtmlElement('div', Attributes::create(['class' => 'overlay']));
$this->assembleGridOverlay($overlay);
return $overlay;
}
/**
* Fetch the count of additional entries for the given date
*
* @param DateTime $date
*
* @return int
*/
public function getExtraEntryCount(DateTime $date): int
{
return $this->extraEntriesCount[$date->format('Y-m-d')] ?? 0;
}
/**
* Yield the entries to show on the grid and place them using a flowing layout
*
* Entry positions are automatically calculated and can span multiple rows.
* Collisions are prevented and the grid can have a limited number of sections.
*
* @param Traversable<int, Entry> $entries
*
* @return Generator<GridArea, Entry>
*/
final protected function yieldFlowingEntries(Traversable $entries): Generator
{
$maxRowSpan = $this->getMaximumRowSpan();
$sectionsPerStep = $this->getSectionsPerStep();
$rowStartModifier = $this->getRowStartModifier();
$infiniteSections = $sectionsPerStep === self::INFINITE;
if ($infiniteSections) {
$fillAvailableSpace = false;
} else {
// +1 because rows are 0-based here, but CSS grid rows are 1-based, hence the default modifier is 1
$fillAvailableSpace = $maxRowSpan === ($sectionsPerStep - $rowStartModifier + 1);
}
$gridStartsAt = $this->getGridStart();
$gridEndsAt = $this->getGridEnd();
$amountOfDays = $gridStartsAt->diff($gridEndsAt)->days;
$gridBorderAt = $this->getNoOfVisuallyConnectedHours() * 2;
if ($infiniteSections && $amountOfDays !== $gridBorderAt / 48) {
throw new LogicException(
'The number of days in the grid must match the number of visually'
. ' connected hours, when an infinite number of sections is used.'
);
}
$cellOccupiers = [];
/** @var SplObjectStorage<Entry, int[][]> $occupiedCells */
$occupiedCells = new SplObjectStorage();
foreach ($entries as $entry) {
$actualStart = Util::roundToNearestThirtyMinute($entry->getStart());
if ($actualStart < $gridStartsAt) {
$entryStartPos = 0;
} else {
$entryStartPos = Util::diffHours($gridStartsAt, $actualStart) * 2;
}
$actualEnd = Util::roundToNearestThirtyMinute($entry->getEnd());
if ($actualEnd > $gridEndsAt) {
$entryEndPos = $amountOfDays * 48;
} else {
$entryEndPos = Util::diffHours($gridStartsAt, $actualEnd) * 2;
}
$rows = [];
for ($i = $entryStartPos; $i < $entryEndPos && $i < $amountOfDays * 48; $i++) {
$row = (int) floor($i / $gridBorderAt);
$column = $i % $gridBorderAt;
$rowStart = $row * $sectionsPerStep;
$rows[$rowStart][] = $column;
$cellOccupiers[$rowStart][$column][] = spl_object_id($entry);
}
$occupiedCells->attach($entry, $rows);
}
$rowPlacements = [];
foreach ($cellOccupiers as $row => $columns) {
foreach ($columns as $occupiers) {
foreach ($occupiers as $id) {
if (isset($rowPlacements[$id][$row])) {
// Ignore already placed rows for now, they may be moved separately below though
continue;
}
$rowStart = $row + $rowStartModifier;
$rowSpan = $maxRowSpan;
$competingOccupiers = array_filter($occupiers, function ($id) use ($rowPlacements, $row) {
return isset($rowPlacements[$id][$row]);
});
usort($competingOccupiers, function ($id, $otherId) use ($rowPlacements, $row) {
return $rowPlacements[$id][$row][0] <=> $rowPlacements[$otherId][$row][0];
});
foreach ($competingOccupiers as $otherId) {
list($otherRowStart, $otherRowSpan) = $rowPlacements[$otherId][$row];
if ($otherRowStart === $rowStart) {
if ($fillAvailableSpace) {
$otherRowSpan = (int) ceil($otherRowSpan / 2);
$rowStart += $otherRowSpan;
$rowSpan -= $otherRowSpan;
$rowPlacements[$otherId][$row] = [$otherRowStart, $otherRowSpan];
} else {
$rowStart += $maxRowSpan;
}
} elseif ($fillAvailableSpace) {
$rowSpan = $otherRowStart - $rowStart;
break; // It occupies space now that was already reserved, so it should be safe to use
}
}
$rowPlacements[$id][$row] = [$rowStart, $rowSpan];
}
}
}
$this->extraEntriesCount = [];
foreach ($occupiedCells as $entry) {
$continuationType = null;
$rows = $occupiedCells->getInfo();
$fromPrevGrid = $gridStartsAt > $entry->getStart();
$remainingRows = count($rows);
$toNextGrid = false;
foreach ($rows as $row => $hours) {
list($rowStart, $rowSpan) = $rowPlacements[spl_object_id($entry)][$row];
$colStart = min($hours);
$colEnd = max($hours);
// Calculate number of entries that are not displayed in the grid for each date
if (! $infiniteSections && $rowStart > $row + $sectionsPerStep) {
$startOffset = (int) (($row / $sectionsPerStep) * ($gridBorderAt / 48) + $colStart / 48);
$endOffset = (int) (($row / $sectionsPerStep) * ($gridBorderAt / 48) + $colEnd / 48);
$startDate = (clone $this->getGridStart())->add(new DateInterval("P$startOffset" . 'D'));
$duration = $endOffset - $startOffset;
for ($i = 0; $i <= $duration; $i++) {
$countIdx = $startDate->format('Y-m-d');
if (! isset($this->extraEntriesCount[$countIdx])) {
$this->extraEntriesCount[$countIdx] = 1;
} else {
$this->extraEntriesCount[$countIdx] += 1;
}
$startDate->add(new DateInterval('P1D'));
}
continue;
}
$gridArea = $this->getGridArea(
$rowStart,
$rowStart + $rowSpan,
$colStart + 1,
$colEnd + 2
);
$isLastRow = $remainingRows === 1;
if ($isLastRow) {
$toNextGrid = $gridEndsAt < $entry->getEnd();
}
$backward = $continuationType || $fromPrevGrid;
$forward = ! $isLastRow || $toNextGrid;
if ($backward && $forward) {
$entry->setContinuationType(Entry::ACROSS_BOTH_EDGES);
} elseif ($backward) {
$entry->setContinuationType(Entry::ACROSS_LEFT_EDGE);
} elseif ($forward) {
$entry->setContinuationType(Entry::ACROSS_RIGHT_EDGE);
} elseif ($fromPrevGrid && $toNextGrid) {
$entry->setContinuationType(Entry::ACROSS_GRID);
} elseif ($fromPrevGrid) {
$entry->setContinuationType(Entry::FROM_PREV_GRID);
} elseif ($toNextGrid) {
$entry->setContinuationType(Entry::TO_NEXT_GRID);
}
yield $gridArea => $entry;
$continuationType = $entry->getContinuationType();
$fromPrevGrid = false;
$remainingRows -= 1;
}
}
if ($infiniteSections) {
$lastRow = array_reduce($rowPlacements, function ($carry, $placements) {
return array_reduce($placements, function ($carry, $placement) {
return max($placement[0] + $placement[1], $carry);
}, $carry);
}, 1);
$this->style->addFor($this, [
'--primaryRows' => $lastRow === 1 ? 1 : ($lastRow - $rowStartModifier) / $maxRowSpan,
'--rowsPerStep' => $maxRowSpan
]);
}
}
/**
* Yield the entries to show on the grid and place them using a fixed layout
*
* Entry positions are expected to be registered on each individual entry and cannot span multiple rows.
* Collisions won't be prevented and the grid is expected to allow for an infinite number of sections.
*
* @param Traversable<int, Entry> $entries
*
* @return Generator<GridArea, Entry>
*/
final protected function yieldFixedEntries(Traversable $entries): Generator
{
if ($this->getMaximumRowSpan() !== 1) {
throw new LogicException('Fixed layouts require a maximum row span of 1');
}
if ($this->getSectionsPerStep() !== self::INFINITE) {
throw new LogicException('Fixed layouts currently only work with an infinite number of sections');
}
$rowStartModifier = $this->getRowStartModifier();
$gridStartsAt = $this->getGridStart();
$gridEndsAt = $this->getGridEnd();
$amountOfDays = $gridStartsAt->diff($gridEndsAt)->days;
$gridBorderAt = $this->getNoOfVisuallyConnectedHours() * 2;
if ($amountOfDays !== $gridBorderAt / 48) {
throw new LogicException(
'The number of days in the grid must match the number'
. ' of visually connected hours, when a fixed layout is used.'
);
}
$lastRow = 1;
foreach ($entries as $entry) {
$position = $entry->getPosition();
if ($position === null) {
throw new LogicException('All entries must have a position set when using a fixed layout');
}
$rowStart = $position + $rowStartModifier;
if ($rowStart > $lastRow) {
$lastRow = $rowStart;
}
$actualStart = Util::roundToNearestThirtyMinute($entry->getStart());
if ($actualStart < $gridStartsAt) {
$colStart = 0;
} else {
$colStart = Util::diffHours($gridStartsAt, $actualStart) * 2;
}
$actualEnd = Util::roundToNearestThirtyMinute($entry->getEnd());
if ($actualEnd > $gridEndsAt) {
$colEnd = $gridBorderAt;
} else {
$colEnd = Util::diffHours($gridStartsAt, $actualEnd) * 2;
}
if ($colStart > $gridBorderAt || $colEnd === $colStart) {
throw new LogicException(sprintf(
'Invalid entry (%d) position: %s to %s. Grid dimension: %s to %s',
$entry->getId(),
$actualStart->format('Y-m-d H:i:s'),
$actualEnd->format('Y-m-d H:i:s'),
$gridStartsAt->format('Y-m-d'),
$gridEndsAt->format('Y-m-d')
));
}
$gridArea = $this->getGridArea(
$rowStart,
$rowStart + 1,
$colStart + 1,
$colEnd + 1
);
$fromPrevGrid = $gridStartsAt > $entry->getStart();
$toNextGrid = $gridEndsAt < $entry->getEnd();
if ($fromPrevGrid && $toNextGrid) {
$entry->setContinuationType(Entry::ACROSS_GRID);
} elseif ($fromPrevGrid) {
$entry->setContinuationType(Entry::FROM_PREV_GRID);
} elseif ($toNextGrid) {
$entry->setContinuationType(Entry::TO_NEXT_GRID);
}
yield $gridArea => $entry;
}
$this->style->addFor($this, [ // +1 to create extra row for the `add rotation` button
'--primaryRows' => $lastRow === 1 ? 1 : $lastRow - $rowStartModifier + 1 + 1,
'--rowsPerStep' => 1
]);
}
protected function assembleGridOverlay(BaseHtmlElement $overlay): void
{
$entries = $this->provider->getEntries();
$firstEntry = iterable_value_first($entries);
if ($firstEntry === null) {
return;
}
if ($firstEntry->getPosition() === null) {
$generator = $this->yieldFlowingEntries($entries);
} else {
$generator = $this->yieldFixedEntries($entries);
}
$addButtonCreated = false;
foreach ($generator as $gridArea => $entry) {
[$rowStart, $colStart, $rowEnd, $colEnd] = $gridArea;
if (! $addButtonCreated && $entry->getAttributes()->has('data-rotation-position')) {
$btn = new HtmlElement('div', new Attributes(['class' => 'btn-container']));
$btn->addHtml(
(new ButtonLink(
$this->translate('Add another Rotation'),
Links::rotationAdd(Url::fromRequest()->getParam('id')),
'plus'
))->openInModal(),
new HtmlElement(
'span',
new Attributes(['class' => 'hint']),
new Text($this->translate('to override rotations above'))
)
);
// occupy the entire row
$this->style->addFor($btn, [
'grid-area' => sprintf('~"%d / %d / %d / %d"', $rowStart, 1, $rowEnd, -1)
]);
$overlay->addHtml($btn);
$addButtonCreated = true;
}
if ($addButtonCreated) { // result row must be below
$rowStart++;
$rowEnd++;
}
$this->style->addFor($entry, [
'--entry-bg' => $entry->getColor(10),
'--entry-border-color' => $entry->getColor(50),
'grid-area' => sprintf('~"%d / %d / %d / %d"', $rowStart, $colStart, $rowEnd, $colEnd)
]);
$overlay->addHtml($entry);
}
}
}