Tree.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. <?php
  2. namespace Dcat\Admin;
  3. use Closure;
  4. use Dcat\Admin\Contracts\TreeRepository;
  5. use Dcat\Admin\Exception\InvalidArgumentException;
  6. use Dcat\Admin\Repositories\EloquentRepository;
  7. use Dcat\Admin\Support\Helper;
  8. use Dcat\Admin\Traits\HasBuilderEvents;
  9. use Dcat\Admin\Traits\HasVariables;
  10. use Dcat\Admin\Tree\AbstractTool;
  11. use Dcat\Admin\Tree\Actions;
  12. use Dcat\Admin\Tree\Tools;
  13. use Illuminate\Contracts\Support\Htmlable;
  14. use Illuminate\Contracts\Support\Renderable;
  15. use Illuminate\Database\Eloquent\Builder;
  16. use Illuminate\Database\Eloquent\Model;
  17. use Illuminate\Support\Str;
  18. use Illuminate\Support\Traits\Macroable;
  19. /**
  20. * Class Tree.
  21. *
  22. * @see https://github.com/dbushell/Nestable
  23. */
  24. class Tree implements Renderable
  25. {
  26. use HasBuilderEvents;
  27. use HasVariables;
  28. use Macroable;
  29. const SAVE_ORDER_NAME = '_order';
  30. /**
  31. * @var array
  32. */
  33. protected $items = [];
  34. /**
  35. * @var string
  36. */
  37. protected $elementId = 'tree-';
  38. /**
  39. * @var TreeRepository
  40. */
  41. protected $repository;
  42. /**
  43. * @var \Closure
  44. */
  45. protected $queryCallback;
  46. /**
  47. * View of tree to render.
  48. *
  49. * @var string
  50. */
  51. protected $view = 'admin::tree.container';
  52. /**
  53. * @var string
  54. */
  55. protected $branchView = 'admin::tree.branch';
  56. /**
  57. * @var \Closure
  58. */
  59. protected $callback;
  60. /**
  61. * @var null
  62. */
  63. protected $branchCallback = null;
  64. /**
  65. * @var string
  66. */
  67. public $path;
  68. /**
  69. * @var string
  70. */
  71. public $url;
  72. /**
  73. * @var bool
  74. */
  75. public $useCreate = true;
  76. /**
  77. * @var bool
  78. */
  79. public $expand = true;
  80. /**
  81. * @var bool
  82. */
  83. public $useQuickCreate = true;
  84. /**
  85. * @var array
  86. */
  87. public $dialogFormDimensions = ['700px', '670px'];
  88. /**
  89. * @var bool
  90. */
  91. public $useSave = true;
  92. /**
  93. * @var bool
  94. */
  95. public $useRefresh = true;
  96. /**
  97. * @var array
  98. */
  99. protected $nestableOptions = [];
  100. /**
  101. * Header tools.
  102. *
  103. * @var Tools
  104. */
  105. public $tools;
  106. /**
  107. * @var string
  108. */
  109. protected $actionsClass;
  110. /**
  111. * @var \Closure[]
  112. */
  113. protected $actionCallbacks = [];
  114. /**
  115. * @var Closure
  116. */
  117. protected $wrapper;
  118. /**
  119. * Menu constructor.
  120. *
  121. * @param Model|TreeRepository|string|null $model
  122. */
  123. public function __construct($repository = null, ?\Closure $callback = null)
  124. {
  125. $this->repository = $this->makeRepository($repository);
  126. $this->path = $this->path ?: request()->getPathInfo();
  127. $this->url = url($this->path);
  128. $this->elementId .= Str::random(8);
  129. $this->setUpTools();
  130. if ($callback instanceof \Closure) {
  131. call_user_func($callback, $this);
  132. }
  133. $this->callResolving();
  134. }
  135. /**
  136. * Setup tree tools.
  137. */
  138. public function setUpTools()
  139. {
  140. $this->tools = new Tools($this);
  141. }
  142. /**
  143. * @param $repository
  144. * @return TreeRepository
  145. */
  146. public function makeRepository($repository)
  147. {
  148. if (is_string($repository)) {
  149. $repository = new $repository();
  150. }
  151. if ($repository instanceof Model || $repository instanceof Builder) {
  152. $repository = EloquentRepository::make($repository);
  153. }
  154. if (! $repository instanceof TreeRepository) {
  155. $class = get_class($repository);
  156. throw new InvalidArgumentException("The class [{$class}] must be a type of [".TreeRepository::class.'].');
  157. }
  158. return $repository;
  159. }
  160. /**
  161. * Initialize branch callback.
  162. *
  163. * @return void
  164. */
  165. protected function setDefaultBranchCallback()
  166. {
  167. if (is_null($this->branchCallback)) {
  168. $this->branchCallback = function ($branch) {
  169. $key = $branch[$this->repository->getPrimaryKeyColumn()];
  170. $title = $branch[$this->repository->getTitleColumn()];
  171. return "$key - $title";
  172. };
  173. }
  174. }
  175. /**
  176. * Set branch callback.
  177. *
  178. * @param \Closure $branchCallback
  179. * @return $this
  180. */
  181. public function branch(\Closure $branchCallback)
  182. {
  183. $this->branchCallback = $branchCallback;
  184. return $this;
  185. }
  186. /**
  187. * Set query callback this tree.
  188. *
  189. * @return $this
  190. */
  191. public function query(\Closure $callback)
  192. {
  193. $this->queryCallback = $callback;
  194. return $this;
  195. }
  196. /**
  197. * number of levels an item can be nested (default 5).
  198. *
  199. * @see https://github.com/dbushell/Nestable
  200. *
  201. * @param int $max
  202. * @return $this
  203. */
  204. public function maxDepth(int $max)
  205. {
  206. return $this->nestable(['maxDepth' => $max]);
  207. }
  208. /**
  209. * Set nestable options.
  210. *
  211. * @param array $options
  212. * @return $this
  213. */
  214. public function nestable($options = [])
  215. {
  216. $this->nestableOptions = array_merge($this->nestableOptions, $options);
  217. return $this;
  218. }
  219. /**
  220. * @param bool $value
  221. * @return void
  222. */
  223. public function expand(bool $value = true)
  224. {
  225. $this->expand = $value;
  226. }
  227. /**
  228. * Disable create.
  229. *
  230. * @param bool $value
  231. * @return void
  232. */
  233. public function disableCreateButton(bool $value = true)
  234. {
  235. $this->useCreate = ! $value;
  236. }
  237. public function showCreateButton(bool $value = true)
  238. {
  239. return $this->disableCreateButton(! $value);
  240. }
  241. public function disableQuickCreateButton(bool $value = true)
  242. {
  243. $this->useQuickCreate = ! $value;
  244. }
  245. public function showQuickCreateButton(bool $value = true)
  246. {
  247. return $this->disableQuickCreateButton(! $value);
  248. }
  249. /**
  250. * @param string $width
  251. * @param string $height
  252. * @return $this
  253. */
  254. public function setDialogFormDimensions(string $width, string $height)
  255. {
  256. $this->dialogFormDimensions = [$width, $height];
  257. return $this;
  258. }
  259. /**
  260. * Disable save.
  261. *
  262. * @param bool $value
  263. * @return void
  264. */
  265. public function disableSaveButton(bool $value = true)
  266. {
  267. $this->useSave = ! $value;
  268. }
  269. public function showSaveButton(bool $value = true)
  270. {
  271. return $this->disableSaveButton(! $value);
  272. }
  273. /**
  274. * Disable refresh.
  275. *
  276. * @param bool $value
  277. * @return void
  278. */
  279. public function disableRefreshButton(bool $value = true)
  280. {
  281. $this->useRefresh = ! $value;
  282. }
  283. public function showRefreshButton(bool $value = true)
  284. {
  285. return $this->disableRefreshButton(! $value);
  286. }
  287. public function disableQuickEditButton(bool $value = true)
  288. {
  289. $this->actions(function (Actions $actions) use ($value) {
  290. $actions->disableQuickEdit($value);
  291. });
  292. }
  293. public function showQuickEditButton(bool $value = true)
  294. {
  295. return $this->disableQuickEditButton(! $value);
  296. }
  297. public function disableEditButton(bool $value = true)
  298. {
  299. $this->actions(function (Actions $actions) use ($value) {
  300. $actions->disableEdit($value);
  301. });
  302. }
  303. public function showEditButton(bool $value = true)
  304. {
  305. return $this->disableEditButton(! $value);
  306. }
  307. public function disableDeleteButton(bool $value = true)
  308. {
  309. $this->actions(function (Actions $actions) use ($value) {
  310. $actions->disableDelete($value);
  311. });
  312. }
  313. public function showDeleteButton(bool $value = true)
  314. {
  315. return $this->disableDeleteButton(! $value);
  316. }
  317. /**
  318. * @param Closure $closure
  319. * @return $this;
  320. */
  321. public function wrap(\Closure $closure)
  322. {
  323. $this->wrapper = $closure;
  324. return $this;
  325. }
  326. /**
  327. * @return bool
  328. */
  329. public function hasWrapper()
  330. {
  331. return $this->wrapper ? true : false;
  332. }
  333. /**
  334. * Save tree order from a input.
  335. *
  336. * @param string $serialize
  337. * @return bool
  338. */
  339. public function saveOrder($serialize)
  340. {
  341. $tree = json_decode($serialize, true);
  342. if (json_last_error() != JSON_ERROR_NONE) {
  343. throw new InvalidArgumentException(json_last_error_msg());
  344. }
  345. $this->repository->saveOrder($tree);
  346. return true;
  347. }
  348. /**
  349. * Set view of tree.
  350. *
  351. * @param string $view
  352. * @return $this
  353. */
  354. public function view($view)
  355. {
  356. $this->view = $view;
  357. return $this;
  358. }
  359. /**
  360. * @param string $view
  361. * @return $this
  362. */
  363. public function branchView($view)
  364. {
  365. $this->branchView = $view;
  366. return $this;
  367. }
  368. /**
  369. * @return \Closure
  370. */
  371. public function resolveAction()
  372. {
  373. return function ($branch) {
  374. $class = $this->actionsClass ?: Actions::class;
  375. $action = new $class();
  376. $action->setParent($this);
  377. $action->setRow($branch);
  378. $this->callActionCallbacks($action);
  379. return $action->render();
  380. };
  381. }
  382. protected function callActionCallbacks(Actions $actions)
  383. {
  384. foreach ($this->actionCallbacks as $callback) {
  385. $callback->call($actions->row, $actions);
  386. }
  387. }
  388. /**
  389. * 自定义行操作类.
  390. *
  391. * @param string $actionClass
  392. * @return $this
  393. */
  394. public function setActionClass(string $actionClass)
  395. {
  396. $this->actionsClass = $actionClass;
  397. return $this;
  398. }
  399. /**
  400. * 设置行操作回调.
  401. *
  402. * @param \Closure|array $callback
  403. * @return $this
  404. */
  405. public function actions($callback)
  406. {
  407. if ($callback instanceof \Closure) {
  408. $this->actionCallbacks[] = $callback;
  409. } else {
  410. $this->actionCallbacks[] = function (Actions $actions) use ($callback) {
  411. if (! is_array($callback)) {
  412. $callback = [$callback];
  413. }
  414. foreach ($callback as $value) {
  415. $actions->append(clone $value);
  416. }
  417. };
  418. }
  419. return $this;
  420. }
  421. /**
  422. * Return all items of the tree.
  423. *
  424. * @param array $items
  425. */
  426. public function getItems()
  427. {
  428. return $this->repository->withQuery($this->queryCallback)->toTree();
  429. }
  430. /**
  431. * Variables in tree template.
  432. *
  433. * @return array
  434. */
  435. public function defaultVariables()
  436. {
  437. return [
  438. 'id' => $this->elementId,
  439. 'tools' => $this->tools->render(),
  440. 'items' => $this->getItems(),
  441. 'useCreate' => $this->useCreate,
  442. 'useQuickCreate' => $this->useQuickCreate,
  443. 'useSave' => $this->useSave,
  444. 'useRefresh' => $this->useRefresh,
  445. 'createButton' => $this->renderCreateButton(),
  446. 'nestableOptions' => $this->nestableOptions,
  447. 'url' => $this->url,
  448. 'resolveAction' => $this->resolveAction(),
  449. 'expand' => $this->expand,
  450. ];
  451. }
  452. /**
  453. * @return mixed
  454. */
  455. public function getKeyName()
  456. {
  457. return $this->repository->getKeyName();
  458. }
  459. /**
  460. * @return string
  461. */
  462. public function resource()
  463. {
  464. return $this->url;
  465. }
  466. /**
  467. * Set resource path.
  468. *
  469. * @param string $path
  470. * @return $this
  471. */
  472. public function setResource($path)
  473. {
  474. $this->url = admin_url($path);
  475. return $this;
  476. }
  477. /**
  478. * Setup tools.
  479. *
  480. * @param Closure|array|AbstractTool|Renderable|Htmlable|string $callback
  481. * @return $this|Tools
  482. */
  483. public function tools($callback = null)
  484. {
  485. if ($callback === null) {
  486. return $this->tools;
  487. }
  488. if ($callback instanceof \Closure) {
  489. call_user_func($callback, $this->tools);
  490. return $this;
  491. }
  492. if (! is_array($callback)) {
  493. $callback = [$callback];
  494. }
  495. foreach ($callback as $tool) {
  496. $this->tools->add($tool);
  497. }
  498. return $this;
  499. }
  500. /**
  501. * @return string
  502. */
  503. protected function renderCreateButton()
  504. {
  505. if (! $this->useQuickCreate && ! $this->useCreate) {
  506. return '';
  507. }
  508. $url = $this->url.'/create';
  509. $new = trans('admin.new');
  510. $quickBtn = $btn = '';
  511. if ($this->useCreate) {
  512. $btn = "<a href='{$url}' class='btn btn-sm btn-primary'><i class='feather icon-plus'></i><span class='d-none d-sm-inline'>&nbsp;{$new}</span></a>";
  513. }
  514. if ($this->useQuickCreate) {
  515. $text = $this->useCreate ? '<i class=\' fa fa-clone\'></i>' : "<i class='feather icon-plus'></i><span class='d-none d-sm-inline'>&nbsp; $new</span>";
  516. $quickBtn = "<button data-url='$url' class='btn btn-sm btn-primary tree-quick-create'>$text</button>";
  517. }
  518. return "&nbsp;<div class='btn-group pull-right' style='margin-right:3px'>{$btn}{$quickBtn}</div>";
  519. }
  520. /**
  521. * @return void
  522. */
  523. protected function renderQuickCreateButton()
  524. {
  525. if ($this->useQuickCreate) {
  526. [$width, $height] = $this->dialogFormDimensions;
  527. Form::dialog(trans('admin.new'))
  528. ->click('.tree-quick-create')
  529. ->success('Dcat.reload()')
  530. ->dimensions($width, $height);
  531. }
  532. }
  533. /**
  534. * Render a tree.
  535. *
  536. * @return \Illuminate\Http\JsonResponse|string
  537. */
  538. public function render()
  539. {
  540. $this->callResolving();
  541. $this->setDefaultBranchCallback();
  542. $this->renderQuickCreateButton();
  543. view()->share([
  544. 'currentUrl' => $this->url,
  545. 'keyName' => $this->getKeyName(),
  546. 'branchView' => $this->branchView,
  547. 'branchCallback' => $this->branchCallback,
  548. ]);
  549. return $this->doWrap();
  550. }
  551. /**
  552. * @return string
  553. */
  554. protected function doWrap()
  555. {
  556. $view = view($this->view, $this->variables());
  557. if (! $wrapper = $this->wrapper) {
  558. $html = Admin::resolveHtml($view->render())['html'];
  559. return "<div class='card'>{$html}</div>";
  560. }
  561. return Admin::resolveHtml(Helper::render($wrapper($view)))['html'];
  562. }
  563. /**
  564. * Get the string contents of the grid view.
  565. *
  566. * @return string
  567. */
  568. public function __toString()
  569. {
  570. return $this->render();
  571. }
  572. /**
  573. * Create a tree instance.
  574. *
  575. * @param mixed ...$param
  576. * @return $this
  577. */
  578. public static function make(...$param)
  579. {
  580. return new static(...$param);
  581. }
  582. }