You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

337 lines
11 KiB

  1. <?php
  2. /*
  3. * The MIT License
  4. *
  5. * Copyright 2019 Blobt.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. */
  25. namespace iron\widgets;
  26. use Yii;
  27. use yii\base\Widget;
  28. use yii\helpers\ArrayHelper;
  29. use yii\helpers\Html;
  30. use yii\helpers\Url;
  31. /**
  32. * 参照yii\widgets\Menu,根据AdminLTE样式从写的一个小物件
  33. * @author Blobt
  34. * @email 380255922@qq.com
  35. * 使用例子
  36. * <?php
  37. * echo Menu::widget([
  38. * 'items' => [
  39. * ['label' => 'MAIN NAVIGATION', 'is_header' => true],
  40. * ['label' => 'Documentation', 'url' => 'https:www.baidu.com', 'icon' => 'fa-book'],
  41. * ['label' => 'Products', 'url' => ['product/index'], 'items' => [
  42. * ['label' => 'New Arrivals', 'url' => ['product/index', 'tag' => 'new']],
  43. * ['label' => 'Most Popular', 'url' => ['product/index', 'tag' => 'popular']],
  44. * ]],
  45. * ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
  46. * ]
  47. * ]);
  48. * ?>
  49. *
  50. *
  51. */
  52. class Menu extends Widget {
  53. /**
  54. * @var array 菜单的item数组。
  55. * 菜单的item同时也是一个数组,结构如下所述:
  56. * lable: string, optional,指定选项的label
  57. * encode:boolean, optional,label是否需要转义
  58. * url: string or array, optional, 生产菜单的路径
  59. * 产生结果和yii的Url::to()方法一致,并且会套用[[linkTemplate]]模板
  60. * visible: boolean, optional, 选项是否可见,默认是true(可见)
  61. * active: boolean or Closure, optional, 是否被选中
  62. * 如果为true,则会在css中添加[[activeCssClass]]
  63. * 当使用Closure时候,匿名函数必须是`function ($item, $hasActiveChild, $isItemActive, $widget)`
  64. * 匿名函数必须返回true或者false
  65. * 如果不是使用匿名函数,就会使用[[isItemActive]]来判断item是否被选中
  66. * items: array, optional, 指定子菜单选项,格式和父菜单是一样的
  67. * template: string, optional,选项的渲染模板
  68. * submenuTemplate: string, optional, 子菜单渲染模板
  69. * options: array, optional, 指定html属性
  70. */
  71. public $items = [];
  72. /**
  73. * @var array html属性,这些指定的属性会加到所有的item中
  74. */
  75. public $itemOptions = [];
  76. /**
  77. * @var string 链接的渲染模板
  78. */
  79. public $linkTemplateWithSub = "<a href=\"{url}\" class=\"nav-link {class}\"><i class=\" nav-icon fas {icon}\"></i><p>{label}<i class=\"right fas fa-angle-left\"></i></p></a>";
  80. public $linkTemplateNoSub = "<a href=\"{url}\" class=\"nav-link {class}\"><i class=\"far {icon} nav-icon\"></i><p>{label}</p></a>";
  81. /**
  82. * @var string label的渲染模板
  83. */
  84. public $labelTemplate = '{label}';
  85. /**
  86. * @var string 子菜单的渲染模板
  87. */
  88. public $submenuTemplate = "\n<ul class=\"nav nav-treeview\">\n{items}\n</ul>\n";
  89. /**
  90. * @var boolean label是否要进行html转义
  91. */
  92. public $encodeLabels = true;
  93. /**
  94. * @var string 被选中的菜单的CSS类
  95. */
  96. public $activeCssClass = 'active';
  97. /**
  98. * @var string 控制二级菜单开合
  99. */
  100. public $menuOpenClass = 'menu-open';
  101. /**
  102. * @var boolean 是否根据路由去判断菜单项是否被选中
  103. */
  104. public $activateItems = true;
  105. /**
  106. * @var boolean 当某一个子菜单的选中时候是否也关联选中父菜单
  107. */
  108. public $activateParents = true;
  109. /**
  110. * @var boolean 如果item的url没有设置时,是否不显示该item
  111. */
  112. public $hideEmptyItems = true;
  113. /**
  114. * @var array 菜单容器标签的属性
  115. */
  116. public $options = [
  117. 'class' => 'nav nav-pills nav-sidebar flex-column',
  118. 'data-widget' => 'treeview',
  119. 'role'=>'menu',
  120. 'data-accordion'=>'false'
  121. ];
  122. /**
  123. * @var string 第一个菜单item的css类
  124. */
  125. public $firstItemCssClass;
  126. /**
  127. * @var string 最后一个菜单item的css类
  128. */
  129. public $lastItemCssClass;
  130. /**
  131. * @var string 路由 ,run的时候会自动获取当前路由
  132. */
  133. public $route;
  134. /**
  135. * @var string $_GET参数
  136. */
  137. public $params;
  138. /**
  139. * @var string 菜单项默认Icon
  140. */
  141. public $defaultIcon = 'fa-circle';
  142. /**
  143. * 渲染菜单
  144. */
  145. public function run() {
  146. if ($this->route === null && Yii::$app->controller !== null) {
  147. $this->route = Yii::$app->controller->getRoute();
  148. }
  149. if ($this->params === null) {
  150. $this->params = Yii::$app->request->getQueryParams();
  151. }
  152. $items = $this->normalizeItems($this->items, $hasActiveChild);
  153. if (!empty($items)) {
  154. $options = $this->options;
  155. $tag = ArrayHelper::remove($options, 'tag', 'ul');
  156. return Html::tag($tag, $this->renderItems($items), $options);
  157. }
  158. }
  159. /**
  160. * 渲染菜单
  161. * @param array $items
  162. * @return string 渲染结果
  163. */
  164. protected function renderItems($items) {
  165. $lines = [];
  166. $n = count($items);
  167. foreach ($items as $i => $item) {
  168. /* 获取菜单项的自定义属性 */
  169. $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
  170. $tag = ArrayHelper::remove($options, 'tag', 'li');
  171. $class = ['nav-item'];
  172. if (isset($item['active'])) {
  173. $class[] = $this->activeCssClass;
  174. if (isset($item['items'])) {
  175. $class[] = $this->menuOpenClass;
  176. }
  177. }
  178. if ($i === 0 && $this->firstItemCssClass !== null) {
  179. $class[] = $this->firstItemCssClass;
  180. }
  181. if ($i === $n - 1 && $this->lastItemCssClass !== null) {
  182. $class[] = $this->lastItemCssClass;
  183. }
  184. if (isset($item['items'])) {
  185. $class[] = 'has-treeview';
  186. }
  187. if (isset($item['is_header']) && $item['is_header']) {
  188. $class[] = "header";
  189. }
  190. Html::addCssClass($options, $class);
  191. $menu = $this->renderItem($item);
  192. if (!empty($item['items'])) {
  193. $submenuTemplate = ArrayHelper::getValue($item, 'submenuTemplate', $this->submenuTemplate);
  194. $menu .= strtr($submenuTemplate, [
  195. '{items}' => $this->renderItems($item['items']),
  196. ]);
  197. }
  198. $lines[] = Html::tag($tag, $menu, $options);
  199. }
  200. return implode("\n", $lines);
  201. }
  202. /**
  203. * 渲染菜单项
  204. * @param array $item
  205. * @return string 渲染结果
  206. */
  207. protected function renderItem($item) {
  208. if (isset($item['url'])) {
  209. if (isset($item['template'])) {
  210. $template = $item['template'];
  211. } else {
  212. $template = isset($item['items']) ? $this->linkTemplateWithSub : $this->linkTemplateNoSub;
  213. }
  214. return strtr($template, [
  215. '{url}' => Html::encode(Url::to($item['url'])),
  216. '{label}' => Html::encode($item['label']),
  217. '{class}'=>isset($item['active'])?'active':'',
  218. '{icon}' => Html::encode($item['icon'])
  219. ]);
  220. }
  221. $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
  222. return strtr($template, [
  223. '{label}' => $item['label'],
  224. '{class}'=>isset($item['active'])?'active':''
  225. ]);
  226. }
  227. /**
  228. * 判断菜单项是否被选中
  229. * @param $item array
  230. * @return boolean $item
  231. */
  232. protected function isItemActive($item) {
  233. if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
  234. $route = Yii::getAlias($item['url'][0]);
  235. if ($route[0] !== '/' && Yii::$app->controller) {
  236. $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
  237. }
  238. if (ltrim($route, '/') !== $this->route) {
  239. return false;
  240. }
  241. return true;
  242. }
  243. return false;
  244. }
  245. /**
  246. * 格式化菜单item
  247. * @param string $item
  248. * @param bool $active
  249. */
  250. protected function normalizeItems($items, &$active) {
  251. foreach ($items as $i => $item) {
  252. /* 去除visible 为 false的item */
  253. if (isset($item['visible']) && !$item['visible']) {
  254. unset($items[$i]);
  255. continue;
  256. }
  257. /* 添加默认icon */
  258. if (!isset($item['icon'])) {
  259. if (!empty($this->defaultIcon)) {
  260. $items[$i]['icon'] = $this->defaultIcon;
  261. }
  262. }
  263. /* 添加label */
  264. if (!isset($item['label'])) {
  265. $item['label'] = '';
  266. }
  267. /* 转义HTML */
  268. $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
  269. if ($encodeLabel) {
  270. $items[$i]['label'] = Html::encode($item['label']);
  271. }
  272. /* 格式化子菜单 item */
  273. $hasActiveChild = false;
  274. if (isset($item['items'])) {
  275. $items[$i]['items'] = $this->normalizeItems($item['items'], $hasActiveChild);
  276. if (empty($items[$i]['items']) && $this->hideEmptyItems) {
  277. unset($items[$i]['items']);
  278. }
  279. }
  280. /* 处理菜单是否被选中 */
  281. if (!isset($item['active'])) {
  282. if ($this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item)) {
  283. $active = $items[$i]['active'] = true;
  284. }
  285. } elseif ($item['active'] instanceof Closure) {
  286. $active = $items[$i]['active'] = call_user_func($item['active'], $item, $hasActiveChild, $this->isItemActive($item), $this);
  287. } elseif ($item['active']) {
  288. $active = true;
  289. }
  290. }
  291. return array_values($items);
  292. }
  293. }