Tree.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. class Tree implements Renderable
  20. {
  21. use HasBuilderEvents;
  22. use HasVariables;
  23. use Macroable;
  24. const SAVE_ORDER_NAME = '_order';
  25. /**
  26. * @var array
  27. */
  28. protected $items = [];
  29. /**
  30. * @var string
  31. */
  32. protected $elementId = 'tree-';
  33. /**
  34. * @var TreeRepository
  35. */
  36. protected $repository;
  37. /**
  38. * @var \Closure
  39. */
  40. protected $queryCallback;
  41. /**
  42. * View of tree to render.
  43. *
  44. * @var string
  45. */
  46. protected $view = 'admin::tree.container';
  47. /**
  48. * @var string
  49. */
  50. protected $branchView = 'admin::tree.branch';
  51. /**
  52. * @var \Closure
  53. */
  54. protected $callback;
  55. /**
  56. * @var null
  57. */
  58. protected $branchCallback = null;
  59. /**
  60. * @var string
  61. */
  62. public $path;
  63. /**
  64. * @var string
  65. */
  66. public $url;
  67. /**
  68. * @var bool
  69. */
  70. public $useCreate = true;
  71. /**
  72. * @var bool
  73. */
  74. public $useQuickCreate = true;
  75. /**
  76. * @var array
  77. */
  78. public $dialogFormDimensions = ['700px', '670px'];
  79. /**
  80. * @var bool
  81. */
  82. public $useSave = true;
  83. /**
  84. * @var bool
  85. */
  86. public $useRefresh = true;
  87. /**
  88. * @var array
  89. */
  90. protected $nestableOptions = [];
  91. /**
  92. * Header tools.
  93. *
  94. * @var Tools
  95. */
  96. public $tools;
  97. /**
  98. * @var string
  99. */
  100. protected $actionsClass;
  101. /**
  102. * @var \Closure[]
  103. */
  104. protected $actionCallbacks = [];
  105. /**
  106. * @var Closure
  107. */
  108. protected $wrapper;
  109. /**
  110. * Menu constructor.
  111. *
  112. * @param Model|TreeRepository|string|null $model
  113. */
  114. public function __construct($repository = null, ?\Closure $callback = null)
  115. {
  116. $this->repository = $this->makeRepository($repository);
  117. $this->path = $this->path ?: request()->getPathInfo();
  118. $this->url = url($this->path);
  119. $this->elementId .= Str::random(8);
  120. $this->setupTools();
  121. $this->requireAssets();
  122. if ($callback instanceof \Closure) {
  123. call_user_func($callback, $this);
  124. }
  125. $this->callResolving();
  126. }
  127. /**
  128. * Setup tree tools.
  129. */
  130. public function setupTools()
  131. {
  132. $this->tools = new Tools($this);
  133. }
  134. /**
  135. * @param $repository
  136. *
  137. * @return TreeRepository
  138. */
  139. public function makeRepository($repository)
  140. {
  141. if (is_string($repository)) {
  142. $repository = new $repository();
  143. }
  144. if ($repository instanceof Model || $repository instanceof Builder) {
  145. $repository = EloquentRepository::make($repository);
  146. }
  147. if (! $repository instanceof TreeRepository) {
  148. $class = get_class($repository);
  149. throw new InvalidArgumentException("The class [{$class}] must be a type of [".TreeRepository::class.'].');
  150. }
  151. return $repository;
  152. }
  153. /**
  154. * Collect assets.
  155. */
  156. protected function requireAssets()
  157. {
  158. Admin::requireAssets('jquery.nestable');
  159. }
  160. /**
  161. * Initialize branch callback.
  162. *
  163. * @return void
  164. */
  165. protected function setDefaultBranchCallback()
  166. {
  167. if (is_null($this->branchCallback)) {
  168. $this->branchCallback = function ($branch) {
  169. $key = $branch[$this->repository->getPrimaryKeyColumn()];
  170. $title = $branch[$this->repository->getTitleColumn()];
  171. return "$key - $title";
  172. };
  173. }
  174. }
  175. /**
  176. * Set branch callback.
  177. *
  178. * @param \Closure $branchCallback
  179. *
  180. * @return $this
  181. */
  182. public function branch(\Closure $branchCallback)
  183. {
  184. $this->branchCallback = $branchCallback;
  185. return $this;
  186. }
  187. /**
  188. * Set query callback this tree.
  189. *
  190. * @return $this
  191. */
  192. public function query(\Closure $callback)
  193. {
  194. $this->queryCallback = $callback;
  195. return $this;
  196. }
  197. /**
  198. * Set nestable options.
  199. *
  200. * @param array $options
  201. *
  202. * @return $this
  203. */
  204. public function nestable($options = [])
  205. {
  206. $this->nestableOptions = array_merge($this->nestableOptions, $options);
  207. return $this;
  208. }
  209. /**
  210. * Disable create.
  211. *
  212. * @param bool $value
  213. *
  214. * @return void
  215. */
  216. public function disableCreateButton(bool $value = true)
  217. {
  218. $this->useCreate = ! $value;
  219. }
  220. public function disableQuickCreateButton(bool $value = true)
  221. {
  222. $this->useQuickCreate = ! $value;
  223. }
  224. /**
  225. * @param string $width
  226. * @param string $height
  227. *
  228. * @return $this
  229. */
  230. public function setDialogFormDimensions(string $width, string $height)
  231. {
  232. $this->dialogFormDimensions = [$width, $height];
  233. return $this;
  234. }
  235. /**
  236. * Disable save.
  237. *
  238. * @param bool $value
  239. *
  240. * @return void
  241. */
  242. public function disableSaveButton(bool $value = true)
  243. {
  244. $this->useSave = ! $value;
  245. }
  246. /**
  247. * Disable refresh.
  248. *
  249. * @param bool $value
  250. *
  251. * @return void
  252. */
  253. public function disableRefreshButton(bool $value = true)
  254. {
  255. $this->useRefresh = ! $value;
  256. }
  257. public function disableQuickEditButton(bool $value = true)
  258. {
  259. $this->actions(function (Actions $actions) use ($value) {
  260. $actions->disableQuickEdit($value);
  261. });
  262. }
  263. public function disableEditButton(bool $value = true)
  264. {
  265. $this->actions(function (Actions $actions) use ($value) {
  266. $actions->disableEdit($value);
  267. });
  268. }
  269. public function disableDeleteButton(bool $value = true)
  270. {
  271. $this->actions(function (Actions $actions) use ($value) {
  272. $actions->disableDelete($value);
  273. });
  274. }
  275. /**
  276. * @param Closure $closure
  277. *
  278. * @return $this;
  279. */
  280. public function wrap(\Closure $closure)
  281. {
  282. $this->wrapper = $closure;
  283. return $this;
  284. }
  285. /**
  286. * @return bool
  287. */
  288. public function hasWrapper()
  289. {
  290. return $this->wrapper ? true : false;
  291. }
  292. /**
  293. * Save tree order from a input.
  294. *
  295. * @param string $serialize
  296. *
  297. * @return bool
  298. */
  299. public function saveOrder($serialize)
  300. {
  301. $tree = json_decode($serialize, true);
  302. if (json_last_error() != JSON_ERROR_NONE) {
  303. throw new InvalidArgumentException(json_last_error_msg());
  304. }
  305. $this->repository->saveOrder($tree);
  306. return true;
  307. }
  308. /**
  309. * Set view of tree.
  310. *
  311. * @param string $view
  312. *
  313. * @return $this
  314. */
  315. public function view($view)
  316. {
  317. $this->view = $view;
  318. return $this;
  319. }
  320. /**
  321. * @param string $view
  322. *
  323. * @return $this
  324. */
  325. public function branchView($view)
  326. {
  327. $this->branchView = $view;
  328. return $this;
  329. }
  330. /**
  331. * @return \Closure
  332. */
  333. public function resolveAction()
  334. {
  335. return function ($branch) {
  336. $class = $this->actionsClass ?: Actions::class;
  337. $action = new $class();
  338. $action->setParent($this);
  339. $action->setRow($branch);
  340. $this->callActionCallbacks($action);
  341. return $action->render();
  342. };
  343. }
  344. protected function callActionCallbacks(Actions $actions)
  345. {
  346. foreach ($this->actionCallbacks as $callback) {
  347. $callback->call($actions->row, $actions);
  348. }
  349. }
  350. /**
  351. * 自定义行操作类.
  352. *
  353. * @param string $actionClass
  354. *
  355. * @return $this
  356. */
  357. public function setActionClass(string $actionClass)
  358. {
  359. $this->actionsClass = $actionClass;
  360. return $this;
  361. }
  362. /**
  363. * 设置行操作回调.
  364. *
  365. * @param \Closure|array $callback
  366. *
  367. * @return $this
  368. */
  369. public function actions($callback)
  370. {
  371. if ($callback instanceof \Closure) {
  372. $this->actionCallbacks[] = $callback;
  373. } else {
  374. $this->actionCallbacks[] = function (Actions $actions) use ($callback) {
  375. $actions->append($callback);
  376. };
  377. }
  378. return $this;
  379. }
  380. /**
  381. * Return all items of the tree.
  382. *
  383. * @param array $items
  384. */
  385. public function getItems()
  386. {
  387. return $this->repository->withQuery($this->queryCallback)->toTree();
  388. }
  389. /**
  390. * Variables in tree template.
  391. *
  392. * @return array
  393. */
  394. public function defaultVariables()
  395. {
  396. return [
  397. 'id' => $this->elementId,
  398. 'tools' => $this->tools->render(),
  399. 'items' => $this->getItems(),
  400. 'useCreate' => $this->useCreate,
  401. 'useQuickCreate' => $this->useQuickCreate,
  402. 'useSave' => $this->useSave,
  403. 'useRefresh' => $this->useRefresh,
  404. 'createButton' => $this->renderCreateButton(),
  405. 'nestableOptions' => $this->nestableOptions,
  406. 'url' => $this->url,
  407. 'resolveAction' => $this->resolveAction(),
  408. ];
  409. }
  410. /**
  411. * @return mixed
  412. */
  413. public function getKeyName()
  414. {
  415. return $this->repository->getKeyName();
  416. }
  417. /**
  418. * @return string
  419. */
  420. public function resource()
  421. {
  422. return $this->url;
  423. }
  424. /**
  425. * Set resource path.
  426. *
  427. * @param string $path
  428. *
  429. * @return $this
  430. */
  431. public function setResource($path)
  432. {
  433. $this->url = admin_url($path);
  434. return $this;
  435. }
  436. /**
  437. * Setup tools.
  438. *
  439. * @param Closure|array|AbstractTool|Renderable|Htmlable|string $callback
  440. *
  441. * @return $this|Tools
  442. */
  443. public function tools($callback = null)
  444. {
  445. if ($callback === null) {
  446. return $this->tools;
  447. }
  448. if ($callback instanceof \Closure) {
  449. call_user_func($callback, $this->tools);
  450. return $this;
  451. }
  452. if (! is_array($callback)) {
  453. $callback = [$callback];
  454. }
  455. foreach ($callback as $tool) {
  456. $this->tools->add($tool);
  457. }
  458. return $this;
  459. }
  460. /**
  461. * @return string
  462. */
  463. protected function renderCreateButton()
  464. {
  465. if (! $this->useQuickCreate && ! $this->useCreate) {
  466. return '';
  467. }
  468. $url = $this->url.'/create';
  469. $new = trans('admin.new');
  470. $quickBtn = $btn = '';
  471. if ($this->useCreate) {
  472. $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>";
  473. }
  474. if ($this->useQuickCreate) {
  475. $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>";
  476. $quickBtn = "<button data-url='$url' class='btn btn-sm btn-primary tree-quick-create'>$text</button>";
  477. }
  478. return "&nbsp;<div class='btn-group pull-right' style='margin-right:3px'>{$btn}{$quickBtn}</div>";
  479. }
  480. /**
  481. * @return void
  482. */
  483. protected function renderQuickCreateButton()
  484. {
  485. if ($this->useQuickCreate) {
  486. [$width, $height] = $this->dialogFormDimensions;
  487. Form::dialog(trans('admin.new'))
  488. ->click('.tree-quick-create')
  489. ->success('Dcat.reload()')
  490. ->dimensions($width, $height);
  491. }
  492. }
  493. /**
  494. * Render a tree.
  495. *
  496. * @return \Illuminate\Http\JsonResponse|string
  497. */
  498. public function render()
  499. {
  500. $this->callResolving();
  501. $this->setDefaultBranchCallback();
  502. $this->renderQuickCreateButton();
  503. view()->share([
  504. 'currentUrl' => $this->url,
  505. 'keyName' => $this->getKeyName(),
  506. 'branchView' => $this->branchView,
  507. 'branchCallback' => $this->branchCallback,
  508. ]);
  509. return $this->doWrap();
  510. }
  511. /**
  512. * @return string
  513. */
  514. protected function doWrap()
  515. {
  516. $view = view($this->view, $this->variables());
  517. if (! $wrapper = $this->wrapper) {
  518. $html = Admin::resolveHtml($view->render())['html'];
  519. return "<div class='card'>{$html}</div>";
  520. }
  521. return Admin::resolveHtml(Helper::render($wrapper($view)))['html'];
  522. }
  523. /**
  524. * Get the string contents of the grid view.
  525. *
  526. * @return string
  527. */
  528. public function __toString()
  529. {
  530. return $this->render();
  531. }
  532. /**
  533. * Create a tree instance.
  534. *
  535. * @param mixed ...$param
  536. *
  537. * @return $this
  538. */
  539. public static function make(...$param)
  540. {
  541. return new static(...$param);
  542. }
  543. }