1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Ui;
6:
7: use Atk4\Core\Factory;
8:
9: class Tabs extends View
10: {
11: public $defaultTemplate = 'tabs.html';
12: public $ui = 'tabular menu';
13:
14: /** @var string name of active tab */
15: public $activeTabName;
16:
17: /**
18: * @param string|TabsTab $name
19: * @param \Closure(VirtualPage, mixed, mixed, mixed, mixed, mixed, mixed, mixed, mixed, mixed, mixed): void $callback
20: *
21: * @return View
22: */
23: public function addTab($name, \Closure $callback = null, array $settings = [])
24: {
25: $item = $this->addTabMenuItem($name, $settings);
26: $sub = $this->addSubView($item->name);
27:
28: // if there is callback action, then use VirtualPage
29: if ($callback) {
30: $vp = VirtualPage::addTo($sub, ['ui' => '']);
31: $item->setPath($vp->getJsUrl('cut'));
32:
33: $vp->set($callback);
34: }
35:
36: return $sub;
37: }
38:
39: /**
40: * Adds dynamic tab in tabs widget which will load a separate
41: * page/url when activated.
42: *
43: * @param string|TabsTab $name
44: * @param string|array<0|string, string|int|false> $page URL to open inside a tab
45: */
46: public function addTabUrl($name, $page, array $settings = []): void
47: {
48: $item = $this->addTabMenuItem($name, $settings);
49: $this->addSubView($item->name);
50:
51: $item->setPath($page);
52: }
53:
54: /**
55: * Add a tab menu item.
56: *
57: * @param string|TabsTab $name
58: *
59: * @return TabsTab|View tab menu item view
60: */
61: protected function addTabMenuItem($name, array $settings)
62: {
63: if (is_object($name)) {
64: $tab = $name;
65: } else {
66: $tab = new TabsTab($name);
67: }
68:
69: $tab = $this->add(Factory::mergeSeeds(['class' => ['item'], 'settings' => $settings], $tab), 'Menu')
70: ->setAttr('data-tab', $tab->name);
71:
72: if (!$this->activeTabName) {
73: $this->activeTabName = $tab->name;
74: }
75:
76: return $tab;
77: }
78:
79: /**
80: * Add sub view to tab.
81: *
82: * @param string $name name of view
83: *
84: * @return TabsSubview
85: */
86: protected function addSubView($name)
87: {
88: return TabsSubview::addTo($this, ['dataTabName' => $name], ['Tabs']);
89: }
90:
91: #[\Override]
92: protected function renderView(): void
93: {
94: // use content as class name
95: if ($this->content) {
96: $this->addClass($this->content);
97: $this->content = null;
98: }
99:
100: parent::renderView();
101: }
102: }
103: