1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Ui;
6:
7: /**
8: * Vertically distributed columns based on CSS Grid system.
9: */
10: class Columns extends View
11: {
12: public $ui = 'grid';
13:
14: /**
15: * Explicitly specify the width of all columns. Normally that's 16, but
16: * Fomantic-UI allows you to override with 5 => "ui five column grid".
17: *
18: * @var int|null
19: */
20: public $width;
21:
22: /** @var int|false Sum of all column widths added so far. */
23: protected $calculatedWidth = 0;
24:
25: /** @var array<int, string> */
26: protected $cssWideClasses = [
27: 1 => 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
28: 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
29: ];
30:
31: /**
32: * Add new vertical column.
33: *
34: * @param int|array $defaults specify width (1..16) or relative to $width
35: *
36: * @return View
37: */
38: public function addColumn($defaults = [])
39: {
40: if (!is_array($defaults)) {
41: $defaults = [$defaults];
42: }
43:
44: $size = $defaults[0] ?? null;
45: unset($defaults[0]);
46:
47: $column = View::addTo($this, $defaults);
48:
49: if ($size && isset($this->cssWideClasses[$size])) {
50: $column->addClass($this->cssWideClasses[$size] . ' wide');
51: $this->calculatedWidth = false;
52: } elseif ($this->calculatedWidth !== false) {
53: ++$this->calculatedWidth;
54: }
55: $column->addClass('column');
56:
57: return $column;
58: }
59:
60: /**
61: * Adds a new row to your grid system. You can specify width of this row
62: * which will default to 16.
63: *
64: * @param int $width
65: *
66: * @return self
67: */
68: public function addRow($width = null)
69: {
70: return static::addTo($this, [$width, 'ui' => false])->addClass('row');
71: }
72:
73: #[\Override]
74: protected function renderView(): void
75: {
76: $width = $this->width ?? $this->calculatedWidth;
77: if ($this->content) {
78: $this->addClass($this->content);
79: $this->content = null;
80: }
81:
82: if (isset($this->cssWideClasses[$width])) {
83: $this->addClass($this->cssWideClasses[$width] . ' column');
84: }
85:
86: parent::renderView();
87: }
88: }
89: