| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Web\Widget; |
| 4 |
|
| 5 |
use ipl\Html\HtmlDocument; |
| 6 |
use ipl\Html\ValidHtml; |
| 7 |
use ipl\Web\Compat\StyleWithNonce; |
| 8 |
use ipl\Web\Layout\ItemLayout; |
| 9 |
use ipl\Web\Layout\ItemTableLayout; |
| 10 |
use LogicException; |
| 11 |
|
| 12 |
/** |
| 13 |
* ItemTable |
| 14 |
* |
| 15 |
* @template Item |
| 16 |
* @extends ItemList<Item> |
| 17 |
*/ |
| 18 |
class ItemTable extends ItemList |
| 19 |
{ |
| 20 |
/** @var array<string, mixed> */ |
| 21 |
protected $baseAttributes = [ |
| 22 |
'class' => 'item-table', |
| 23 |
'data-base-target' => '_next' |
| 24 |
]; |
| 25 |
|
| 26 |
/** @var bool Whether the list already listens for an item's assembly to determine the number of caption columns */ |
| 27 |
protected $listeningForColumnCount = false; |
| 28 |
|
| 29 |
/** @var StyleWithNonce */ |
| 30 |
protected $style; |
| 31 |
|
| 32 |
protected function init(): void |
| 33 |
{ |
| 34 |
parent::init(); |
| 35 |
|
| 36 |
$this->setItemLayoutClass(ItemTableLayout::class); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Create a list item for the given data |
| 41 |
* |
| 42 |
* @param object $data |
| 43 |
* |
| 44 |
* @return ItemTableRow<Item> |
| 45 |
*/ |
| 46 |
protected function createListItem(object $data): ValidHtml |
| 47 |
{ |
| 48 |
return new ItemTableRow($data, $this); |
| 49 |
} |
| 50 |
|
| 51 |
public function getItemLayout($item): ItemLayout |
| 52 |
{ |
| 53 |
$layout = parent::getItemLayout($item); |
| 54 |
if (! $this->listeningForColumnCount) { |
| 55 |
$this->listeningForColumnCount = true; |
| 56 |
$layout->on(HtmlDocument::ON_ASSEMBLED, function (ItemTableLayout $layout) { |
| 57 |
$columns = $layout->getColumnCount(); |
| 58 |
if ($columns === 0) { |
| 59 |
throw new LogicException('An item table requires at least a single column.'); |
| 60 |
} |
| 61 |
|
| 62 |
$this->style->addFor($this, ['--columns' => $columns]); |
| 63 |
}); |
| 64 |
} |
| 65 |
|
| 66 |
return $layout; |
| 67 |
} |
| 68 |
|
| 69 |
protected function assemble(): void |
| 70 |
{ |
| 71 |
parent::assemble(); |
| 72 |
|
| 73 |
$this->style = new StyleWithNonce(); |
| 74 |
$this->addHtml($this->style); |
| 75 |
} |
| 76 |
} |