Tree.php 12 KB

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