-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathGrid.php
692 lines (592 loc) · 22.5 KB
/
Grid.php
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
<?php
declare(strict_types=1);
namespace Atk4\Ui;
use Atk4\Core\Factory;
use Atk4\Core\HookTrait;
use Atk4\Data\Model;
use Atk4\Ui\Table\Column\ActionButtons;
use Atk4\Ui\UserAction\ConfirmationExecutor;
use Atk4\Ui\UserAction\ExecutorInterface;
/**
* Implements a more sophisticated and interactive Data-Table component.
*/
class Grid extends View
{
use HookTrait;
/** @var Menu|false Will be initialized to Menu object, however you can set this to false to disable menu. */
public $menu;
/** @var JsSearch */
public $quickSearch;
/** @var array Field names to search for in Model. It will automatically add quicksearch component to grid if set. */
public $searchFieldNames = [];
/**
* Paginator is automatically added below the table and will divide long tables into pages.
*
* You can provide your own Paginator object here to customize.
*
* @var Paginator|false
*/
public $paginator;
/** @var int Number of items per page to display. */
public $ipp = 50;
/**
* Calling addActionButton will add a new column inside $table, and will be re-used
* for next addActionButton().
*
* @var Table\Column\ActionButtons
*/
public $actionButtons;
/**
* Calling addAction will add a new column inside $table with dropdown menu,
* and will be re-used for next addActionMenuItem().
*
* @var Table\Column
*/
public $actionMenu;
/**
* Calling addSelection will add a new column inside $table, containing checkboxes.
* This column will be stored here, in case you want to access it.
*
* @var Table\Column\Checkbox
*/
public $selection;
/**
* Grid can be sorted by clicking on column headers. This will be automatically enabled
* if Model supports ordering. You may override by setting true/false.
*
* @var bool
*/
public $sortable;
/** @var string|null Set this if you want GET argument name to look beautifully for sorting. */
public $sortTrigger;
/** @var Table|false Component that actually renders data rows / columns and possibly totals. */
public $table;
/** @var View The container for table and paginator. */
public $container;
public $defaultTemplate = 'grid.html';
/** @var string Defines which Table Decorator to use for ActionButtons. */
protected $actionButtonsDecorator = [Table\Column\ActionButtons::class];
/** @var array Defines which Table Decorator to use for ActionMenu. */
protected $actionMenuDecorator = [Table\Column\ActionMenu::class, 'label' => 'Actions...'];
protected function init(): void
{
parent::init();
$this->container = View::addTo($this, ['template' => $this->template->cloneRegion('Container')]);
$this->template->del('Container');
if (!$this->sortTrigger) {
$this->sortTrigger = $this->name . '_sort';
}
// if menu not disabled ot not already assigned as existing object
if ($this->menu !== false && !is_object($this->menu)) {
$this->menu = $this->add(Factory::factory([Menu::class, 'activate_on_click' => false], $this->menu), 'Menu');
}
$this->table = $this->initTable();
if ($this->paginator !== false) {
$seg = View::addTo($this->container, [], ['Paginator'])->addStyle('text-align', 'center');
$this->paginator = $seg->add(Factory::factory([Paginator::class, 'reload' => $this->container], $this->paginator));
$this->stickyGet($this->paginator->name);
}
// TODO dirty way to set stickyGet - add addQuickSearch to find the expected search input component ID and then remove it
if ($this->menu !== false) {
$appUniqueHashesBackup = $this->getApp()->unique_hashes;
$menuElementNameCountsBackup = \Closure::bind(fn () => $this->_element_name_counts, $this->menu, AbstractView::class)();
try {
$menuRight = $this->menu->addMenuRight(); // @phpstan-ignore-line
$menuItemView = View::addTo($menuRight->addItem()->setElement('div'));
$quickSearch = JsSearch::addTo($menuItemView);
$this->stickyGet($quickSearch->name . '_q');
$this->menu->removeElement($menuRight->short_name);
} finally {
$this->getApp()->unique_hashes = $appUniqueHashesBackup;
\Closure::bind(fn () => $this->_element_name_counts = $menuElementNameCountsBackup, $this->menu, AbstractView::class)();
}
}
}
protected function initTable(): Table
{
/** @var Table */
$table = $this->container->add(Factory::factory([Table::class, 'very compact very basic striped single line', 'reload' => $this->container], $this->table), 'Table');
return $table;
}
/**
* Set Table\Column\Actions seed.
*/
public function setActionDecorator($seed)
{
$this->actionButtonsDecorator = $seed;
}
/**
* Set Table\Column\ActionMenu seed.
*/
public function setActionMenuDecorator($seed)
{
$this->actionMenuDecorator = $seed;
}
/**
* Add new column to grid. If column with this name already exists,
* an. Simply calls Table::addColumn(), so check that method out.
*
* @param string $name Data model field name
* @param array|string|object|null $columnDecorator
* @param array|string|object|null $field
*
* @return Table\Column
*/
public function addColumn($name, $columnDecorator = null, $field = null)
{
return $this->table->addColumn($name, $columnDecorator, $field);
}
/**
* Add additional decorator for existing column.
*
* @param string $name Column name
* @param Table\Column|array $decorator Seed or object of the decorator
*/
public function addDecorator($name, $decorator)
{
return $this->table->addDecorator($name, $decorator);
}
/**
* Add a new buton to the Grid Menu with a given text.
*
* WARNING: needs to be reviewed!
*
* @param mixed $text
*/
public function addButton($text)
{
if (!$this->menu) {
throw new Exception('Unable to add Button without Menu');
}
return Button::addTo($this->menu->addItem(), [$text]);
}
/**
* Set item per page value.
*
* If an array is passed, it will also add an ItemPerPageSelector to paginator.
*
* @param int|array $ipp
* @param string $label
*/
public function setIpp($ipp, $label = 'Items per page:')
{
if (is_array($ipp)) {
$this->addItemsPerPageSelector($ipp, $label);
} else {
$this->ipp = $ipp;
}
}
/**
* Add ItemsPerPageSelector View in grid menu or paginator in order to dynamically setup number of item per page.
*
* @param array $items an array of item's per page value
* @param string $label the memu item label
*
* @return $this
*/
public function addItemsPerPageSelector($items = [10, 25, 50, 100], $label = 'Items per page:')
{
if ($ipp = (int) $this->container->stickyGet('ipp')) {
$this->ipp = $ipp;
} else {
$this->ipp = $items[0];
}
$pageLength = ItemsPerPageSelector::addTo($this->paginator, ['pageLengthItems' => $items, 'label' => $label, 'currentIpp' => $this->ipp], ['afterPaginator']);
$this->paginator->template->trySet('PaginatorType', 'ui grid');
if ($sortBy = $this->getSortBy()) {
$pageLength->stickyGet($this->sortTrigger, $sortBy);
}
$pageLength->onPageLengthSelect(function ($ipp) {
$this->ipp = $ipp;
$this->setModelLimitFromPaginator();
// add ipp to quicksearch
if ($this->quickSearch instanceof JsSearch) {
$this->container->js(true, $this->quickSearch->js()->atkJsSearch('setUrlArgs', ['ipp', $this->ipp]));
}
$this->applySort();
// return the view to reload.
return $this->container;
});
return $this;
}
/**
* Add dynamic scrolling paginator.
*
* @param int $ipp number of item per page to start with
* @param array $options an array with js Scroll plugin options
* @param View $container The container holding the lister for scrolling purpose. Default to view owner.
* @param string $scrollRegion A specific template region to render. Render output is append to container html element.
*
* @return $this
*/
public function addJsPaginator($ipp, $options = [], $container = null, $scrollRegion = 'Body')
{
if ($this->paginator) {
$this->paginator->destroy();
// prevent action(count) to be output twice.
$this->paginator = null;
}
if ($sortBy = $this->getSortBy()) {
$this->stickyGet($this->sortTrigger, $sortBy);
}
$this->applySort();
$this->table->addJsPaginator($ipp, $options, $container, $scrollRegion);
return $this;
}
/**
* Add dynamic scrolling paginator in container.
* Use this to make table headers fixed.
*
* @param int $ipp number of item per page to start with
* @param int $containerHeight number of pixel the table container should be
* @param array $options an array with js Scroll plugin options
* @param View $container The container holding the lister for scrolling purpose. Default to view owner.
* @param string $scrollRegion A specific template region to render. Render output is append to container html element.
*
* @return $this
*/
public function addJsPaginatorInContainer($ipp, $containerHeight, $options = [], $container = null, $scrollRegion = 'Body')
{
$this->table->hasCollapsingCssActionColumn = false;
$options = array_merge($options, [
'hasFixTableHeader' => true,
'tableContainerHeight' => $containerHeight,
]);
// adding a state context to js scroll plugin.
$options = array_merge(['stateContext' => '#' . $this->container->name], $options);
return $this->addJsPaginator($ipp, $options, $container, $scrollRegion);
}
/**
* Add Search input field using js action.
* By default, will query server when using Enter key on input search field.
* You can change it to query server on each keystroke by passing $autoQuery true,.
*
* @param array $fields the list of fields to search for
* @param bool $hasAutoQuery will query server on each key pressed
*/
public function addQuickSearch($fields = [], $hasAutoQuery = false)
{
if (!$this->model) {
throw new Exception('Call setModel() before addQuickSearch()');
}
if (!$fields) {
$fields = [$this->model->title_field];
}
if (!$this->menu) {
throw new Exception('Unable to add QuickSearch without Menu');
}
$view = View::addTo($this->menu
->addMenuRight()->addItem()->setElement('div'));
$this->quickSearch = JsSearch::addTo($view, ['reload' => $this->container, 'autoQuery' => $hasAutoQuery]);
$q = trim($this->stickyGet($this->quickSearch->name . '_q') ?? '');
if ($q !== '') {
$scope = Model\Scope::createOr();
foreach ($fields as $field) {
$scope->addCondition($field, 'like', '%' . $q . '%');
}
$this->model->addCondition($scope);
}
$this->quickSearch->initValue = $q;
}
/**
* Returns JS for reloading View.
*
* @param array $args
* @param JsExpression|null $afterSuccess
* @param array $apiConfig
*
* @return \Atk4\Ui\JsReload
*/
public function jsReload($args = [], $afterSuccess = null, $apiConfig = [])
{
return new JsReload($this->container, $args, $afterSuccess, $apiConfig);
}
/**
* Adds a new button into the action column on the right. For Crud this
* column will already contain "delete" and "edit" buttons.
*
* @param string|array|View $button Label text, object or seed for the Button
* @param JsExpressionable|\Closure $action JavaScript action or callback
*
* @return object
*/
public function addActionButton($button, $action = null, string $confirmMsg = '', $isDisabled = false)
{
return $this->getActionButtons()->addButton($button, $action, $confirmMsg, $isDisabled);
}
/**
* Add a button for executing a model action via an action executor.
*/
public function addExecutorButton(UserAction\ExecutorInterface $executor, Button $button = null)
{
$btn = $button ? $this->add($button) : $this->getExecutorFactory()->createTrigger($executor->getAction(), $this->getExecutorFactory()::TABLE_BUTTON);
$confirmation = $executor->getAction()->getConfirmation() ?: '';
$disabled = is_bool($executor->getAction()->enabled) ? !$executor->getAction()->enabled : $executor->getAction()->enabled;
return $this->getActionButtons()->addButton($btn, $executor, $confirmation, $disabled);
}
private function getActionButtons(): ActionButtons
{
if (!$this->actionButtons) {
$this->actionButtons = $this->table->addColumn(null, $this->actionButtonsDecorator);
}
return $this->actionButtons;
}
/**
* Similar to addAction. Will add Button that when click will display
* a Dropdown menu.
*
* @param View $view
*
* @return mixed
*/
public function addActionMenuItem($view, $action = null, string $confirmMsg = '', bool $isDisabled = false)
{
return $this->getActionMenu()->addActionMenuItem($view, $action, $confirmMsg, $isDisabled);
}
public function addExecutorMenuItem(ExecutorInterface $executor)
{
$item = $this->getExecutorFactory()->createTrigger($executor->getAction(), $this->getExecutorFactory()::TABLE_MENU_ITEM);
// ConfirmationExecutor take care of showing the user confirmation, thus make it empty.
$confirmation = !$executor instanceof ConfirmationExecutor ? ($executor->getAction()->getConfirmation() ?: '') : '';
$disabled = is_bool($executor->getAction()->enabled) ? !$executor->getAction()->enabled : $executor->getAction()->enabled;
return $this->getActionMenu()->addActionMenuItem($item, $executor, $confirmation, $disabled);
}
private function getActionMenu()
{
if (!$this->actionMenu) {
$this->actionMenu = $this->table->addColumn(null, $this->actionMenuDecorator);
}
return $this->actionMenu;
}
/**
* Add action menu item using an array.
*/
public function addActionMenuItems(array $actions = [])
{
foreach ($actions as $action) {
$this->addActionMenuItem($action);
}
}
/**
* Add action menu items using Model.
* You may specify the scope of actions to be added.
*
* @param string|null $appliesTo the scope of model action
*/
public function addActionMenuFromModel(string $appliesTo = null)
{
if (!$this->model) {
throw new Exception('Model not set, set it prior to add item.');
}
foreach ($this->model->getUserActions($appliesTo) as $action) {
$this->addActionMenuItem($action);
}
}
/**
* An array of column name where filter is needed.
* Leave empty to include all column in grid.
*
* @param array|null $names an array with the name of column
*
* @return $this
*/
public function addFilterColumn($names = null)
{
if (!$this->menu) {
throw new Exception('Unable to add Filter Column without Menu');
}
$this->menu->addItem(['Clear Filters'], new \Atk4\Ui\JsReload($this->table->reload, ['atk_clear_filter' => 1]));
$this->table->setFilterColumn($names);
return $this;
}
/**
* Add a dropdown menu to header column.
*
* @param string $columnName the name of column where to add dropdown
* @param array $items the menu items to add
* @param \Closure $fx the callback function to execute when an item is selected
* @param string $icon the icon
* @param string $menuId the menu id return by callback
*/
public function addDropdown($columnName, $items, \Closure $fx, $icon = 'caret square down', $menuId = null)
{
if (!isset($this->table->columns[$columnName])) {
throw new Exception('The column where you want to add dropdown does not exist: ' . $columnName);
}
$column = $this->table->columns[$columnName];
if (!$menuId) {
$menuId = $columnName;
}
$column->addDropdown($items, function ($item) use ($fx) {
return $fx([$item]);
}, $icon, $menuId);
}
/**
* Add a popup to header column.
*
* @param string $columnName the name of column where to add popup
* @param Popup $popup popup view
* @param string $icon the icon
*
* @return mixed
*/
public function addPopup($columnName, $popup = null, $icon = 'caret square down')
{
if (!isset($this->table->columns[$columnName])) {
throw new Exception('The column where you want to add popup does not exist: ' . $columnName);
}
$column = $this->table->columns[$columnName];
return $column->addPopup($popup, $icon);
}
/**
* Similar to addAction but when button is clicked, modal is displayed
* with the $title and $callback is executed through VirtualPage.
*
* @param string|array|View $button
* @param string $title
* @param \Closure $callback function($page) {...
* @param array $args extra url argument for callback
*
* @return object
*/
public function addModalAction($button, $title, \Closure $callback, $args = [])
{
if (!$this->actionButtons) {
$this->actionButtons = $this->table->addColumn(null, $this->actionButtonsDecorator);
}
return $this->actionButtons->addModal($button, $title, $callback, $this, $args);
}
/**
* Use addExecutorButton or addExecutorMenuItem.
*
* @deprecated.
*/
public function addUserAction(Model\UserAction $action)
{
$executor = $this->getExecutorFactory()->create($action, $this);
$this->addExecutorButton($executor);
}
/**
* Get sortBy value from url parameter.
*
* @return string|null
*/
public function getSortBy()
{
return $_GET[$this->sortTrigger] ?? null;
}
/**
* Apply ordering to the current model as per the sort parameters.
*/
public function applySort()
{
if ($this->sortable === false) {
return;
}
$sortBy = $this->getSortBy();
if ($sortBy && $this->paginator) {
$this->paginator->addReloadArgs([$this->sortTrigger => $sortBy]);
}
$isDesc = false;
if ($sortBy && $sortBy[0] === '-') {
$isDesc = true;
$sortBy = substr($sortBy, 1);
}
$this->table->sortable = true;
if ($sortBy && isset($this->table->columns[$sortBy]) && $this->model->hasField($sortBy)) {
$this->model->setOrder($sortBy, $isDesc ? 'desc' : 'asc');
$this->table->sort_by = $sortBy;
$this->table->sort_order = $isDesc ? 'descending' : 'ascending';
}
$this->table->on(
'click',
'thead>tr>th.sortable',
new JsReload($this->container, [$this->sortTrigger => (new Jquery())->data('sort')])
);
}
/**
* Sets data Model of Grid.
*
* If $columns is not defined, then automatically will add columns for all
* visible model fields. If $columns is set to false, then will not add
* columns at all.
*
* @param array<int, string>|null $columns
*/
public function setModel(Model $model, array $columns = null): void
{
$this->table->setModel($model, $columns);
parent::setModel($model);
if ($this->searchFieldNames) {
$this->addQuickSearch($this->searchFieldNames, true);
}
}
/**
* Makes rows of this grid selectable by creating new column on the left with
* checkboxes.
*
* @return Table\Column\Checkbox
*/
public function addSelection()
{
$this->selection = $this->table->addColumn(null, [Table\Column\Checkbox::class]);
// Move last column to the beginning in table column array.
array_unshift($this->table->columns, array_pop($this->table->columns));
return $this->selection;
}
/**
* Add column with drag handler on each row.
* Drag handler allow to reorder table via drag n drop.
*
* @return Table\Column
*/
public function addDragHandler()
{
$handler = $this->table->addColumn(null, [Table\Column\DragHandler::class]);
// Move last column to the beginning in table column array.
array_unshift($this->table->columns, array_pop($this->table->columns));
return $handler;
}
/**
* Will set model limit according to paginator value.
*/
private function setModelLimitFromPaginator()
{
$this->paginator->setTotal((int) ceil((int) $this->model->action('count')->getOne() / $this->ipp));
$this->model->setLimit($this->ipp, ($this->paginator->page - 1) * $this->ipp);
}
/**
* Before rendering take care of data sorting.
*/
protected function renderView(): void
{
// take care of sorting
$this->applySort();
parent::renderView();
}
/**
* Recursively renders view.
*/
protected function recursiveRender(): void
{
// bind with paginator
if ($this->paginator) {
$this->setModelLimitFromPaginator();
}
if ($this->quickSearch instanceof JsSearch) {
if ($sortBy = $this->getSortBy()) {
$this->container->js(true, $this->quickSearch->js()->atkJsSearch('setUrlArgs', [$this->sortTrigger, $sortBy]));
}
}
parent::recursiveRender();
}
/**
* Proxy function for Table::jsRow().
*
* @return Jquery
*/
public function jsRow()
{
return $this->table->jsRow();
}
}