Tree.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. namespace Dcat\Admin;
  3. use Closure;
  4. use Dcat\Admin\Contracts\TreeRepository;
  5. use Dcat\Admin\Repositories\EloquentRepository;
  6. use Dcat\Admin\Traits\HasBuilderEvents;
  7. use Dcat\Admin\Tree\AbstractTool;
  8. use Dcat\Admin\Tree\Tools;
  9. use Illuminate\Contracts\Support\Htmlable;
  10. use Illuminate\Contracts\Support\Renderable;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Database\Eloquent\Model;
  13. use Illuminate\Support\Str;
  14. use Illuminate\Support\Traits\Macroable;
  15. class Tree implements Renderable
  16. {
  17. use HasBuilderEvents,
  18. Macroable;
  19. /**
  20. * @var array
  21. */
  22. protected $items = [];
  23. /**
  24. * @var string
  25. */
  26. protected $elementId = 'tree-';
  27. /**
  28. * @var TreeRepository
  29. */
  30. protected $repository;
  31. /**
  32. * @var \Closure
  33. */
  34. protected $queryCallback;
  35. /**
  36. * View of tree to render.
  37. *
  38. * @var string
  39. */
  40. protected $view = [
  41. 'tree' => 'admin::tree.container',
  42. 'branch' => 'admin::tree.branch',
  43. ];
  44. /**
  45. * @var \Closure
  46. */
  47. protected $callback;
  48. /**
  49. * @var null
  50. */
  51. protected $branchCallback = null;
  52. /**
  53. * @var string
  54. */
  55. public $path;
  56. /**
  57. * @var string
  58. */
  59. public $url;
  60. /**
  61. * @var bool
  62. */
  63. public $useCreate = true;
  64. /**
  65. * @var bool
  66. */
  67. public $useQuickCreate = true;
  68. /**
  69. * @var array
  70. */
  71. public $dialogFormDimensions = ['700px', '620px'];
  72. /**
  73. * @var bool
  74. */
  75. public $useSave = true;
  76. /**
  77. * @var bool
  78. */
  79. public $useRefresh = true;
  80. /**
  81. * @var bool
  82. */
  83. public $useEdit = true;
  84. /**
  85. * @var bool
  86. */
  87. public $useQuickEdit = true;
  88. /**
  89. * @var bool
  90. */
  91. public $useDelete = true;
  92. /**
  93. * @var array
  94. */
  95. protected $nestableOptions = [];
  96. /**
  97. * Header tools.
  98. *
  99. * @var Tools
  100. */
  101. public $tools;
  102. /**
  103. * @var Closure
  104. */
  105. protected $wrapper;
  106. /**
  107. * Menu constructor.
  108. *
  109. * @param Model|TreeRepository|string|null $model
  110. */
  111. public function __construct($repository = null, ?\Closure $callback = null)
  112. {
  113. $this->repository = $this->makeRepository($repository);
  114. $this->path = $this->path ?: request()->getPathInfo();
  115. $this->url = url($this->path);
  116. $this->elementId .= Str::random(8);
  117. $this->setupTools();
  118. $this->collectAssets();
  119. if ($callback instanceof \Closure) {
  120. call_user_func($callback, $this);
  121. }
  122. $this->callResolving();
  123. }
  124. /**
  125. * Setup tree tools.
  126. */
  127. public function setupTools()
  128. {
  129. $this->tools = new Tools($this);
  130. }
  131. /**
  132. * @param $repository
  133. *
  134. * @return TreeRepository
  135. */
  136. public function makeRepository($repository)
  137. {
  138. if (is_string($repository)) {
  139. $repository = new $repository();
  140. }
  141. if ($repository instanceof Model || $repository instanceof Builder) {
  142. $repository = EloquentRepository::make($repository);
  143. }
  144. if (! $repository instanceof TreeRepository) {
  145. $class = get_class($repository);
  146. throw new \InvalidArgumentException("The class [{$class}] must be a type of [".TreeRepository::class.'].');
  147. }
  148. return $repository;
  149. }
  150. /**
  151. * Collect assets.
  152. */
  153. protected function collectAssets()
  154. {
  155. Admin::collectAssets('jquery.nestable');
  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. * Set nestable options.
  196. *
  197. * @param array $options
  198. *
  199. * @return $this
  200. */
  201. public function nestable($options = [])
  202. {
  203. $this->nestableOptions = array_merge($this->nestableOptions, $options);
  204. return $this;
  205. }
  206. /**
  207. * Disable create.
  208. *
  209. * @return void
  210. */
  211. public function disableCreateButton()
  212. {
  213. $this->useCreate = false;
  214. }
  215. public function disableQuickCreateButton()
  216. {
  217. $this->useQuickCreate = false;
  218. }
  219. /**
  220. * @param string $width
  221. * @param string $height
  222. *
  223. * @return $this
  224. */
  225. public function setDialogFormDimensions(string $width, string $height)
  226. {
  227. $this->dialogFormDimensions = [$width, $height];
  228. return $this;
  229. }
  230. /**
  231. * Disable save.
  232. *
  233. * @return void
  234. */
  235. public function disableSaveButton()
  236. {
  237. $this->useSave = false;
  238. }
  239. /**
  240. * Disable refresh.
  241. *
  242. * @return void
  243. */
  244. public function disableRefreshButton()
  245. {
  246. $this->useRefresh = false;
  247. }
  248. public function disableQuickEditButton()
  249. {
  250. $this->useQuickEdit = false;
  251. }
  252. public function disableEditButton()
  253. {
  254. $this->useEdit = false;
  255. }
  256. public function disableDeleteButton()
  257. {
  258. $this->useDelete = false;
  259. }
  260. /**
  261. * @param Closure $closure
  262. *
  263. * @return $this;
  264. */
  265. public function wrap(\Closure $closure)
  266. {
  267. $this->wrapper = $closure;
  268. return $this;
  269. }
  270. /**
  271. * @return bool
  272. */
  273. public function hasWrapper()
  274. {
  275. return $this->wrapper ? true : false;
  276. }
  277. /**
  278. * Save tree order from a input.
  279. *
  280. * @param string $serialize
  281. *
  282. * @return bool
  283. */
  284. public function saveOrder($serialize)
  285. {
  286. $tree = json_decode($serialize, true);
  287. if (json_last_error() != JSON_ERROR_NONE) {
  288. throw new \InvalidArgumentException(json_last_error_msg());
  289. }
  290. $this->repository->saveOrder($tree);
  291. return true;
  292. }
  293. /**
  294. * Build tree grid scripts.
  295. *
  296. * @return string
  297. */
  298. protected function script()
  299. {
  300. $saveSucceeded = trans('admin.save_succeeded');
  301. $nestableOptions = json_encode($this->nestableOptions);
  302. return <<<JS
  303. (function () {
  304. var tree = $('#{$this->elementId}');
  305. tree.nestable($nestableOptions);
  306. $('.{$this->elementId}-save').on('click', function () {
  307. var serialize = tree.nestable('serialize'), _this = $(this);
  308. _this.buttonLoading();
  309. $.post('{$this->url}', {
  310. _token: Dcat.token,
  311. _order: JSON.stringify(serialize)
  312. },
  313. function () {
  314. _this.buttonLoading(false);
  315. Dcat.reload();
  316. Dcat.success('{$saveSucceeded}');
  317. });
  318. });
  319. $('.{$this->elementId}-tree-tools').on('click', function(e){
  320. var action = $(this).data('action');
  321. if (action === 'expand') {
  322. tree.nestable('expandAll');
  323. }
  324. if (action === 'collapse') {
  325. tree.nestable('collapseAll');
  326. }
  327. });
  328. })()
  329. JS;
  330. }
  331. /**
  332. * Set view of tree.
  333. *
  334. * @param string $view
  335. */
  336. public function view($view)
  337. {
  338. $this->view = $view;
  339. }
  340. /**
  341. * Return all items of the tree.
  342. *
  343. * @param array $items
  344. */
  345. public function getItems()
  346. {
  347. return $this->repository->withQuery($this->queryCallback)->toTree();
  348. }
  349. /**
  350. * Variables in tree template.
  351. *
  352. * @return array
  353. */
  354. public function variables()
  355. {
  356. return [
  357. 'id' => $this->elementId,
  358. 'tools' => $this->tools->render(),
  359. 'items' => $this->getItems(),
  360. 'useCreate' => $this->useCreate,
  361. 'useQuickCreate' => $this->useQuickCreate,
  362. 'useSave' => $this->useSave,
  363. 'useRefresh' => $this->useRefresh,
  364. 'useEdit' => $this->useEdit,
  365. 'useQuickEdit' => $this->useQuickEdit,
  366. 'useDelete' => $this->useDelete,
  367. 'createButton' => $this->renderCreateButton(),
  368. ];
  369. }
  370. /**
  371. * Setup tools.
  372. *
  373. * @param Closure|array|AbstractTool|Renderable|Htmlable|string $callback
  374. *
  375. * @return $this|Tools
  376. */
  377. public function tools($callback = null)
  378. {
  379. if ($callback === null) {
  380. return $this->tools;
  381. }
  382. if ($callback instanceof \Closure) {
  383. call_user_func($callback, $this->tools);
  384. return $this;
  385. }
  386. if (! is_array($callback)) {
  387. $callback = [$callback];
  388. }
  389. foreach ($callback as $tool) {
  390. $this->tools->add($tool);
  391. }
  392. return $this;
  393. }
  394. /**
  395. * @return string
  396. */
  397. protected function renderCreateButton()
  398. {
  399. if (! $this->useQuickCreate && ! $this->useCreate) {
  400. return '';
  401. }
  402. $url = $this->url.'/create';
  403. $new = trans('admin.new');
  404. $quickBtn = $btn = '';
  405. if ($this->useCreate) {
  406. $btn = "<button href='{$url}' class='btn btn-sm btn-success'><i class='feather icon-plus'></i><span class='d-none d-sm-inline'>&nbsp;{$new}</span></button>";
  407. }
  408. if ($this->useQuickCreate) {
  409. $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>";
  410. $quickBtn = "<button data-url='$url' class='btn btn-sm btn-success tree-quick-create'>$text</button>";
  411. }
  412. return "&nbsp;<div class='btn-group pull-right' style='margin-right:3px'>{$btn}{$quickBtn}</div>";
  413. }
  414. /**
  415. * @return void
  416. */
  417. protected function renderQuickEditButton()
  418. {
  419. if ($this->useQuickEdit) {
  420. [$width, $height] = $this->dialogFormDimensions;
  421. Form::dialog(trans('admin.edit'))
  422. ->click('.tree-quick-edit')
  423. ->success('Dcat.reload()')
  424. ->dimensions($width, $height);
  425. }
  426. }
  427. /**
  428. * @return void
  429. */
  430. protected function renderQuickCreateButton()
  431. {
  432. if ($this->useQuickCreate) {
  433. [$width, $height] = $this->dialogFormDimensions;
  434. Form::dialog(trans('admin.new'))
  435. ->click('.tree-quick-create')
  436. ->success('Dcat.reload()')
  437. ->dimensions($width, $height);
  438. }
  439. }
  440. /**
  441. * Render a tree.
  442. *
  443. * @return \Illuminate\Http\JsonResponse|string
  444. */
  445. public function render()
  446. {
  447. try {
  448. $this->callResolving();
  449. $this->setDefaultBranchCallback();
  450. $this->renderQuickEditButton();
  451. $this->renderQuickCreateButton();
  452. Admin::script($this->script());
  453. view()->share([
  454. 'path' => $this->url,
  455. 'keyName' => $this->repository->getKeyName(),
  456. 'branchView' => $this->view['branch'],
  457. 'branchCallback' => $this->branchCallback,
  458. ]);
  459. return $this->doWrap();
  460. } catch (\Throwable $e) {
  461. return Admin::makeExceptionHandler()->renderException($e);
  462. }
  463. }
  464. /**
  465. * @return string
  466. */
  467. protected function doWrap()
  468. {
  469. $view = view($this->view['tree'], $this->variables());
  470. if (! $wrapper = $this->wrapper) {
  471. return "<div class='card dcat-box'>{$view->render()}</div>";
  472. }
  473. return $wrapper($view);
  474. }
  475. /**
  476. * Get the string contents of the grid view.
  477. *
  478. * @return string
  479. */
  480. public function __toString()
  481. {
  482. return $this->render();
  483. }
  484. /**
  485. * Create a tree instance.
  486. *
  487. * @param mixed ...$param
  488. *
  489. * @return $this
  490. */
  491. public static function make(...$param)
  492. {
  493. return new static(...$param);
  494. }
  495. }