Tree.php 14 KB

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