Tree.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. *
  145. * @return TreeRepository
  146. */
  147. public function makeRepository($repository)
  148. {
  149. if (is_string($repository)) {
  150. $repository = new $repository();
  151. }
  152. if ($repository instanceof Model || $repository instanceof Builder) {
  153. $repository = EloquentRepository::make($repository);
  154. }
  155. if (! $repository instanceof TreeRepository) {
  156. $class = get_class($repository);
  157. throw new InvalidArgumentException("The class [{$class}] must be a type of [".TreeRepository::class.'].');
  158. }
  159. return $repository;
  160. }
  161. /**
  162. * Initialize branch callback.
  163. *
  164. * @return void
  165. */
  166. protected function setDefaultBranchCallback()
  167. {
  168. if (is_null($this->branchCallback)) {
  169. $this->branchCallback = function ($branch) {
  170. $key = $branch[$this->repository->getPrimaryKeyColumn()];
  171. $title = $branch[$this->repository->getTitleColumn()];
  172. return "$key - $title";
  173. };
  174. }
  175. }
  176. /**
  177. * Set branch callback.
  178. *
  179. * @param \Closure $branchCallback
  180. *
  181. * @return $this
  182. */
  183. public function branch(\Closure $branchCallback)
  184. {
  185. $this->branchCallback = $branchCallback;
  186. return $this;
  187. }
  188. /**
  189. * Set query callback this tree.
  190. *
  191. * @return $this
  192. */
  193. public function query(\Closure $callback)
  194. {
  195. $this->queryCallback = $callback;
  196. return $this;
  197. }
  198. /**
  199. * number of levels an item can be nested (default 5).
  200. *
  201. * @see https://github.com/dbushell/Nestable
  202. *
  203. * @param int $max
  204. *
  205. * @return $this
  206. */
  207. public function maxDepth(int $max)
  208. {
  209. return $this->nestable(['maxDepth' => $max]);
  210. }
  211. /**
  212. * Set nestable options.
  213. *
  214. * @param array $options
  215. *
  216. * @return $this
  217. */
  218. public function nestable($options = [])
  219. {
  220. $this->nestableOptions = array_merge($this->nestableOptions, $options);
  221. return $this;
  222. }
  223. /**
  224. * @param bool $value
  225. *
  226. * @return void
  227. */
  228. public function expand(bool $value = true)
  229. {
  230. $this->expand = $value;
  231. }
  232. /**
  233. * Disable create.
  234. *
  235. * @param bool $value
  236. *
  237. * @return void
  238. */
  239. public function disableCreateButton(bool $value = true)
  240. {
  241. $this->useCreate = ! $value;
  242. }
  243. public function showCreateButton(bool $value = true)
  244. {
  245. return $this->disableCreateButton(! $value);
  246. }
  247. public function disableQuickCreateButton(bool $value = true)
  248. {
  249. $this->useQuickCreate = ! $value;
  250. }
  251. public function showQuickCreateButton(bool $value = true)
  252. {
  253. return $this->disableQuickCreateButton(! $value);
  254. }
  255. /**
  256. * @param string $width
  257. * @param string $height
  258. *
  259. * @return $this
  260. */
  261. public function setDialogFormDimensions(string $width, string $height)
  262. {
  263. $this->dialogFormDimensions = [$width, $height];
  264. return $this;
  265. }
  266. /**
  267. * Disable save.
  268. *
  269. * @param bool $value
  270. *
  271. * @return void
  272. */
  273. public function disableSaveButton(bool $value = true)
  274. {
  275. $this->useSave = ! $value;
  276. }
  277. public function showSaveButton(bool $value = true)
  278. {
  279. return $this->disableSaveButton(! $value);
  280. }
  281. /**
  282. * Disable refresh.
  283. *
  284. * @param bool $value
  285. *
  286. * @return void
  287. */
  288. public function disableRefreshButton(bool $value = true)
  289. {
  290. $this->useRefresh = ! $value;
  291. }
  292. public function showRefreshButton(bool $value = true)
  293. {
  294. return $this->disableRefreshButton(! $value);
  295. }
  296. public function disableQuickEditButton(bool $value = true)
  297. {
  298. $this->actions(function (Actions $actions) use ($value) {
  299. $actions->disableQuickEdit($value);
  300. });
  301. }
  302. public function showQuickEditButton(bool $value = true)
  303. {
  304. return $this->disableQuickEditButton(! $value);
  305. }
  306. public function disableEditButton(bool $value = true)
  307. {
  308. $this->actions(function (Actions $actions) use ($value) {
  309. $actions->disableEdit($value);
  310. });
  311. }
  312. public function showEditButton(bool $value = true)
  313. {
  314. return $this->disableEditButton(! $value);
  315. }
  316. public function disableDeleteButton(bool $value = true)
  317. {
  318. $this->actions(function (Actions $actions) use ($value) {
  319. $actions->disableDelete($value);
  320. });
  321. }
  322. public function showDeleteButton(bool $value = true)
  323. {
  324. return $this->disableDeleteButton(! $value);
  325. }
  326. /**
  327. * @param Closure $closure
  328. *
  329. * @return $this;
  330. */
  331. public function wrap(\Closure $closure)
  332. {
  333. $this->wrapper = $closure;
  334. return $this;
  335. }
  336. /**
  337. * @return bool
  338. */
  339. public function hasWrapper()
  340. {
  341. return $this->wrapper ? true : false;
  342. }
  343. /**
  344. * Save tree order from a input.
  345. *
  346. * @param string $serialize
  347. *
  348. * @return bool
  349. */
  350. public function saveOrder($serialize)
  351. {
  352. $tree = json_decode($serialize, true);
  353. if (json_last_error() != JSON_ERROR_NONE) {
  354. throw new InvalidArgumentException(json_last_error_msg());
  355. }
  356. $this->repository->saveOrder($tree);
  357. return true;
  358. }
  359. /**
  360. * Set view of tree.
  361. *
  362. * @param string $view
  363. *
  364. * @return $this
  365. */
  366. public function view($view)
  367. {
  368. $this->view = $view;
  369. return $this;
  370. }
  371. /**
  372. * @param string $view
  373. *
  374. * @return $this
  375. */
  376. public function branchView($view)
  377. {
  378. $this->branchView = $view;
  379. return $this;
  380. }
  381. /**
  382. * @return \Closure
  383. */
  384. public function resolveAction()
  385. {
  386. return function ($branch) {
  387. $class = $this->actionsClass ?: Actions::class;
  388. $action = new $class();
  389. $action->setParent($this);
  390. $action->setRow($branch);
  391. $this->callActionCallbacks($action);
  392. return $action->render();
  393. };
  394. }
  395. protected function callActionCallbacks(Actions $actions)
  396. {
  397. foreach ($this->actionCallbacks as $callback) {
  398. $callback->call($actions->row, $actions);
  399. }
  400. }
  401. /**
  402. * 自定义行操作类.
  403. *
  404. * @param string $actionClass
  405. *
  406. * @return $this
  407. */
  408. public function setActionClass(string $actionClass)
  409. {
  410. $this->actionsClass = $actionClass;
  411. return $this;
  412. }
  413. /**
  414. * 设置行操作回调.
  415. *
  416. * @param \Closure|array $callback
  417. *
  418. * @return $this
  419. */
  420. public function actions($callback)
  421. {
  422. if ($callback instanceof \Closure) {
  423. $this->actionCallbacks[] = $callback;
  424. } else {
  425. $this->actionCallbacks[] = function (Actions $actions) use ($callback) {
  426. if (! is_array($callback)) {
  427. $callback = [$callback];
  428. }
  429. foreach ($callback as $value) {
  430. $actions->append(clone $value);
  431. }
  432. };
  433. }
  434. return $this;
  435. }
  436. /**
  437. * Return all items of the tree.
  438. *
  439. * @param array $items
  440. */
  441. public function getItems()
  442. {
  443. return $this->repository->withQuery($this->queryCallback)->toTree();
  444. }
  445. /**
  446. * Variables in tree template.
  447. *
  448. * @return array
  449. */
  450. public function defaultVariables()
  451. {
  452. return [
  453. 'id' => $this->elementId,
  454. 'tools' => $this->tools->render(),
  455. 'items' => $this->getItems(),
  456. 'useCreate' => $this->useCreate,
  457. 'useQuickCreate' => $this->useQuickCreate,
  458. 'useSave' => $this->useSave,
  459. 'useRefresh' => $this->useRefresh,
  460. 'createButton' => $this->renderCreateButton(),
  461. 'nestableOptions' => $this->nestableOptions,
  462. 'url' => $this->url,
  463. 'resolveAction' => $this->resolveAction(),
  464. 'expand' => $this->expand,
  465. ];
  466. }
  467. /**
  468. * @return mixed
  469. */
  470. public function getKeyName()
  471. {
  472. return $this->repository->getKeyName();
  473. }
  474. /**
  475. * @return string
  476. */
  477. public function resource()
  478. {
  479. return $this->url;
  480. }
  481. /**
  482. * Set resource path.
  483. *
  484. * @param string $path
  485. *
  486. * @return $this
  487. */
  488. public function setResource($path)
  489. {
  490. $this->url = admin_url($path);
  491. return $this;
  492. }
  493. /**
  494. * Setup tools.
  495. *
  496. * @param Closure|array|AbstractTool|Renderable|Htmlable|string $callback
  497. *
  498. * @return $this|Tools
  499. */
  500. public function tools($callback = null)
  501. {
  502. if ($callback === null) {
  503. return $this->tools;
  504. }
  505. if ($callback instanceof \Closure) {
  506. call_user_func($callback, $this->tools);
  507. return $this;
  508. }
  509. if (! is_array($callback)) {
  510. $callback = [$callback];
  511. }
  512. foreach ($callback as $tool) {
  513. $this->tools->add($tool);
  514. }
  515. return $this;
  516. }
  517. /**
  518. * @return string
  519. */
  520. protected function renderCreateButton()
  521. {
  522. if (! $this->useQuickCreate && ! $this->useCreate) {
  523. return '';
  524. }
  525. $url = $this->url.'/create';
  526. $new = trans('admin.new');
  527. $quickBtn = $btn = '';
  528. if ($this->useCreate) {
  529. $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>";
  530. }
  531. if ($this->useQuickCreate) {
  532. $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>";
  533. $quickBtn = "<button data-url='$url' class='btn btn-sm btn-primary tree-quick-create'>$text</button>";
  534. }
  535. return "&nbsp;<div class='btn-group pull-right' style='margin-right:3px'>{$btn}{$quickBtn}</div>";
  536. }
  537. /**
  538. * @return void
  539. */
  540. protected function renderQuickCreateButton()
  541. {
  542. if ($this->useQuickCreate) {
  543. [$width, $height] = $this->dialogFormDimensions;
  544. Form::dialog(trans('admin.new'))
  545. ->click('.tree-quick-create')
  546. ->success('Dcat.reload()')
  547. ->dimensions($width, $height);
  548. }
  549. }
  550. /**
  551. * Render a tree.
  552. *
  553. * @return \Illuminate\Http\JsonResponse|string
  554. */
  555. public function render()
  556. {
  557. $this->callResolving();
  558. $this->setDefaultBranchCallback();
  559. $this->renderQuickCreateButton();
  560. view()->share([
  561. 'currentUrl' => $this->url,
  562. 'keyName' => $this->getKeyName(),
  563. 'branchView' => $this->branchView,
  564. 'branchCallback' => $this->branchCallback,
  565. ]);
  566. return $this->doWrap();
  567. }
  568. /**
  569. * @return string
  570. */
  571. protected function doWrap()
  572. {
  573. $view = view($this->view, $this->variables());
  574. if (! $wrapper = $this->wrapper) {
  575. $html = Admin::resolveHtml($view->render())['html'];
  576. return "<div class='card'>{$html}</div>";
  577. }
  578. return Admin::resolveHtml(Helper::render($wrapper($view)))['html'];
  579. }
  580. /**
  581. * Get the string contents of the grid view.
  582. *
  583. * @return string
  584. */
  585. public function __toString()
  586. {
  587. return $this->render();
  588. }
  589. /**
  590. * Create a tree instance.
  591. *
  592. * @param mixed ...$param
  593. *
  594. * @return $this
  595. */
  596. public static function make(...$param)
  597. {
  598. return new static(...$param);
  599. }
  600. }