Tree.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 disableQuickCreateButton(bool $value = true)
  231. {
  232. $this->useQuickCreate = ! $value;
  233. }
  234. /**
  235. * @param string $width
  236. * @param string $height
  237. *
  238. * @return $this
  239. */
  240. public function setDialogFormDimensions(string $width, string $height)
  241. {
  242. $this->dialogFormDimensions = [$width, $height];
  243. return $this;
  244. }
  245. /**
  246. * Disable save.
  247. *
  248. * @param bool $value
  249. *
  250. * @return void
  251. */
  252. public function disableSaveButton(bool $value = true)
  253. {
  254. $this->useSave = ! $value;
  255. }
  256. /**
  257. * Disable refresh.
  258. *
  259. * @param bool $value
  260. *
  261. * @return void
  262. */
  263. public function disableRefreshButton(bool $value = true)
  264. {
  265. $this->useRefresh = ! $value;
  266. }
  267. public function disableQuickEditButton(bool $value = true)
  268. {
  269. $this->actions(function (Actions $actions) use ($value) {
  270. $actions->disableQuickEdit($value);
  271. });
  272. }
  273. public function disableEditButton(bool $value = true)
  274. {
  275. $this->actions(function (Actions $actions) use ($value) {
  276. $actions->disableEdit($value);
  277. });
  278. }
  279. public function disableDeleteButton(bool $value = true)
  280. {
  281. $this->actions(function (Actions $actions) use ($value) {
  282. $actions->disableDelete($value);
  283. });
  284. }
  285. /**
  286. * @param Closure $closure
  287. *
  288. * @return $this;
  289. */
  290. public function wrap(\Closure $closure)
  291. {
  292. $this->wrapper = $closure;
  293. return $this;
  294. }
  295. /**
  296. * @return bool
  297. */
  298. public function hasWrapper()
  299. {
  300. return $this->wrapper ? true : false;
  301. }
  302. /**
  303. * Save tree order from a input.
  304. *
  305. * @param string $serialize
  306. *
  307. * @return bool
  308. */
  309. public function saveOrder($serialize)
  310. {
  311. $tree = json_decode($serialize, true);
  312. if (json_last_error() != JSON_ERROR_NONE) {
  313. throw new InvalidArgumentException(json_last_error_msg());
  314. }
  315. $this->repository->saveOrder($tree);
  316. return true;
  317. }
  318. /**
  319. * Set view of tree.
  320. *
  321. * @param string $view
  322. *
  323. * @return $this
  324. */
  325. public function view($view)
  326. {
  327. $this->view = $view;
  328. return $this;
  329. }
  330. /**
  331. * @param string $view
  332. *
  333. * @return $this
  334. */
  335. public function branchView($view)
  336. {
  337. $this->branchView = $view;
  338. return $this;
  339. }
  340. /**
  341. * @return \Closure
  342. */
  343. public function resolveAction()
  344. {
  345. return function ($branch) {
  346. $class = $this->actionsClass ?: Actions::class;
  347. $action = new $class();
  348. $action->setParent($this);
  349. $action->setRow($branch);
  350. $this->callActionCallbacks($action);
  351. return $action->render();
  352. };
  353. }
  354. protected function callActionCallbacks(Actions $actions)
  355. {
  356. foreach ($this->actionCallbacks as $callback) {
  357. $callback->call($actions->row, $actions);
  358. }
  359. }
  360. /**
  361. * 自定义行操作类.
  362. *
  363. * @param string $actionClass
  364. *
  365. * @return $this
  366. */
  367. public function setActionClass(string $actionClass)
  368. {
  369. $this->actionsClass = $actionClass;
  370. return $this;
  371. }
  372. /**
  373. * 设置行操作回调.
  374. *
  375. * @param \Closure|array $callback
  376. *
  377. * @return $this
  378. */
  379. public function actions($callback)
  380. {
  381. if ($callback instanceof \Closure) {
  382. $this->actionCallbacks[] = $callback;
  383. } else {
  384. $this->actionCallbacks[] = function (Actions $actions) use ($callback) {
  385. if (! is_array($callback)) {
  386. $callback = [$callback];
  387. }
  388. foreach ($callback as $value) {
  389. $actions->append(clone $value);
  390. }
  391. };
  392. }
  393. return $this;
  394. }
  395. /**
  396. * Return all items of the tree.
  397. *
  398. * @param array $items
  399. */
  400. public function getItems()
  401. {
  402. return $this->repository->withQuery($this->queryCallback)->toTree();
  403. }
  404. /**
  405. * Variables in tree template.
  406. *
  407. * @return array
  408. */
  409. public function defaultVariables()
  410. {
  411. return [
  412. 'id' => $this->elementId,
  413. 'tools' => $this->tools->render(),
  414. 'items' => $this->getItems(),
  415. 'useCreate' => $this->useCreate,
  416. 'useQuickCreate' => $this->useQuickCreate,
  417. 'useSave' => $this->useSave,
  418. 'useRefresh' => $this->useRefresh,
  419. 'createButton' => $this->renderCreateButton(),
  420. 'nestableOptions' => $this->nestableOptions,
  421. 'url' => $this->url,
  422. 'resolveAction' => $this->resolveAction(),
  423. ];
  424. }
  425. /**
  426. * @return mixed
  427. */
  428. public function getKeyName()
  429. {
  430. return $this->repository->getKeyName();
  431. }
  432. /**
  433. * @return string
  434. */
  435. public function resource()
  436. {
  437. return $this->url;
  438. }
  439. /**
  440. * Set resource path.
  441. *
  442. * @param string $path
  443. *
  444. * @return $this
  445. */
  446. public function setResource($path)
  447. {
  448. $this->url = admin_url($path);
  449. return $this;
  450. }
  451. /**
  452. * Setup tools.
  453. *
  454. * @param Closure|array|AbstractTool|Renderable|Htmlable|string $callback
  455. *
  456. * @return $this|Tools
  457. */
  458. public function tools($callback = null)
  459. {
  460. if ($callback === null) {
  461. return $this->tools;
  462. }
  463. if ($callback instanceof \Closure) {
  464. call_user_func($callback, $this->tools);
  465. return $this;
  466. }
  467. if (! is_array($callback)) {
  468. $callback = [$callback];
  469. }
  470. foreach ($callback as $tool) {
  471. $this->tools->add($tool);
  472. }
  473. return $this;
  474. }
  475. /**
  476. * @return string
  477. */
  478. protected function renderCreateButton()
  479. {
  480. if (! $this->useQuickCreate && ! $this->useCreate) {
  481. return '';
  482. }
  483. $url = $this->url.'/create';
  484. $new = trans('admin.new');
  485. $quickBtn = $btn = '';
  486. if ($this->useCreate) {
  487. $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>";
  488. }
  489. if ($this->useQuickCreate) {
  490. $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>";
  491. $quickBtn = "<button data-url='$url' class='btn btn-sm btn-primary tree-quick-create'>$text</button>";
  492. }
  493. return "&nbsp;<div class='btn-group pull-right' style='margin-right:3px'>{$btn}{$quickBtn}</div>";
  494. }
  495. /**
  496. * @return void
  497. */
  498. protected function renderQuickCreateButton()
  499. {
  500. if ($this->useQuickCreate) {
  501. [$width, $height] = $this->dialogFormDimensions;
  502. Form::dialog(trans('admin.new'))
  503. ->click('.tree-quick-create')
  504. ->success('Dcat.reload()')
  505. ->dimensions($width, $height);
  506. }
  507. }
  508. /**
  509. * Render a tree.
  510. *
  511. * @return \Illuminate\Http\JsonResponse|string
  512. */
  513. public function render()
  514. {
  515. $this->callResolving();
  516. $this->setDefaultBranchCallback();
  517. $this->renderQuickCreateButton();
  518. view()->share([
  519. 'currentUrl' => $this->url,
  520. 'keyName' => $this->getKeyName(),
  521. 'branchView' => $this->branchView,
  522. 'branchCallback' => $this->branchCallback,
  523. ]);
  524. return $this->doWrap();
  525. }
  526. /**
  527. * @return string
  528. */
  529. protected function doWrap()
  530. {
  531. $view = view($this->view, $this->variables());
  532. if (! $wrapper = $this->wrapper) {
  533. $html = Admin::resolveHtml($view->render())['html'];
  534. return "<div class='card'>{$html}</div>";
  535. }
  536. return Admin::resolveHtml(Helper::render($wrapper($view)))['html'];
  537. }
  538. /**
  539. * Get the string contents of the grid view.
  540. *
  541. * @return string
  542. */
  543. public function __toString()
  544. {
  545. return $this->render();
  546. }
  547. /**
  548. * Create a tree instance.
  549. *
  550. * @param mixed ...$param
  551. *
  552. * @return $this
  553. */
  554. public static function make(...$param)
  555. {
  556. return new static(...$param);
  557. }
  558. }