Grid.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. <?php
  2. namespace Dcat\Admin;
  3. use Closure;
  4. use Dcat\Admin\Grid\Column;
  5. use Dcat\Admin\Grid\Displayers;
  6. use Dcat\Admin\Grid\Model;
  7. use Dcat\Admin\Grid\Responsive;
  8. use Dcat\Admin\Grid\Row;
  9. use Dcat\Admin\Grid\Tools;
  10. use Dcat\Admin\Grid\Concerns;
  11. use Dcat\Admin\Contracts\Repository;
  12. use Dcat\Admin\Support\Helper;
  13. use Dcat\Admin\Traits\HasBuilderEvents;
  14. use Illuminate\Support\Traits\Macroable;
  15. use Illuminate\Contracts\Support\Htmlable;
  16. use Illuminate\Contracts\Support\Renderable;
  17. use Illuminate\Support\Collection;
  18. use Illuminate\Support\Str;
  19. class Grid
  20. {
  21. use HasBuilderEvents,
  22. Concerns\HasElementNames,
  23. Concerns\HasFilter,
  24. Concerns\HasTools,
  25. Concerns\HasActions,
  26. Concerns\HasPaginator,
  27. Concerns\HasExporter,
  28. Concerns\HasMultipleHeader,
  29. Concerns\HasQuickSearch,
  30. Concerns\HasSelector,
  31. Macroable {
  32. __call as macroCall;
  33. }
  34. /**
  35. * The grid data model instance.
  36. *
  37. * @var \Dcat\Admin\Grid\Model
  38. */
  39. protected $model;
  40. /**
  41. * Collection of all grid columns.
  42. *
  43. * @var \Illuminate\Support\Collection
  44. */
  45. protected $columns;
  46. /**
  47. * Collection of all data rows.
  48. *
  49. * @var \Illuminate\Support\Collection
  50. */
  51. protected $rows;
  52. /**
  53. * Rows callable fucntion.
  54. *
  55. * @var \Closure[]
  56. */
  57. protected $rowsCallback = [];
  58. /**
  59. * All column names of the grid.
  60. *
  61. * @var array
  62. */
  63. protected $columnNames = [];
  64. /**
  65. * Grid builder.
  66. *
  67. * @var \Closure
  68. */
  69. protected $builder;
  70. /**
  71. * Mark if the grid is built.
  72. *
  73. * @var bool
  74. */
  75. protected $built = false;
  76. /**
  77. * All variables in grid view.
  78. *
  79. * @var array
  80. */
  81. protected $variables = [];
  82. /**
  83. * Resource path of the grid.
  84. *
  85. * @var
  86. */
  87. protected $resourcePath;
  88. /**
  89. * Default primary key name.
  90. *
  91. * @var string
  92. */
  93. protected $keyName = 'id';
  94. /**
  95. * View for grid to render.
  96. *
  97. * @var string
  98. */
  99. protected $view = 'admin::grid.table';
  100. /**
  101. * @var Closure
  102. */
  103. protected $header;
  104. /**
  105. * @var Closure
  106. */
  107. protected $footer;
  108. /**
  109. * @var Closure
  110. */
  111. protected $wrapper;
  112. /**
  113. * @var Responsive
  114. */
  115. protected $responsive;
  116. /**
  117. * @var bool
  118. */
  119. protected $addNumberColumn = false;
  120. /**
  121. * @var string
  122. */
  123. protected $tableId;
  124. /**
  125. * Options for grid.
  126. *
  127. * @var array
  128. */
  129. protected $options = [
  130. 'show_pagination' => true,
  131. 'show_filter' => true,
  132. 'show_actions' => true,
  133. 'show_quick_edit_button' => false,
  134. 'show_edit_button' => true,
  135. 'show_view_button' => true,
  136. 'show_delete_button' => true,
  137. 'show_row_selector' => true,
  138. 'show_create_btn' => true,
  139. 'show_quick_create_btn' => false,
  140. 'show_bordered' => false,
  141. 'show_toolbar' => true,
  142. 'show_exporter' => false,
  143. 'row_selector_style' => 'primary',
  144. 'row_selector_circle' => true,
  145. 'row_selector_clicktr' => false,
  146. 'row_selector_label_key' => null,
  147. 'row_selector_bg' => 'var(--20)',
  148. 'dialog_form_area' => ['700px', '670px'],
  149. 'table_header_style' => 'table-header-gray',
  150. ];
  151. /**
  152. * Create a new grid instance.
  153. *
  154. * Grid constructor.
  155. * @param Repository|null $repository
  156. * @param null $builder
  157. */
  158. public function __construct(?Repository $repository = null, ?\Closure $builder = null)
  159. {
  160. if ($repository) {
  161. $this->keyName = $repository->getKeyName();
  162. }
  163. $this->model = new Model(request(), $repository);
  164. $this->columns = new Collection();
  165. $this->rows = new Collection();
  166. $this->builder = $builder;
  167. $this->tableId = 'grid-'.Str::random(8);
  168. $this->model()->setGrid($this);
  169. $this->setupTools();
  170. $this->setupFilter();
  171. $this->callResolving();
  172. }
  173. /**
  174. * Get table ID.
  175. *
  176. * @return string
  177. */
  178. public function getTableId()
  179. {
  180. return $this->tableId;
  181. }
  182. /**
  183. * Get primary key name of model.
  184. *
  185. * @return string
  186. */
  187. public function getKeyName()
  188. {
  189. return $this->keyName ?: 'id';
  190. }
  191. /**
  192. * Set primary key name.
  193. *
  194. * @param string $name
  195. */
  196. public function setKeyName(string $name)
  197. {
  198. $this->keyName = $name;
  199. }
  200. /**
  201. * Add column to Grid.
  202. *
  203. * @param string $name
  204. * @param string $label
  205. *
  206. * @return Column
  207. */
  208. public function column($name, $label = '')
  209. {
  210. if (strpos($name, '.') !== false) {
  211. list($relationName, $relationColumn) = explode('.', $name);
  212. $label = empty($label) ? admin_trans_field($relationColumn) : $label;
  213. $name = Str::snake($relationName).'.'.$relationColumn;
  214. }
  215. $column = $this->addColumn($name, $label);
  216. return $column;
  217. }
  218. /**
  219. * Add number column.
  220. *
  221. * @param null|string $label
  222. * @return Column
  223. */
  224. public function number(?string $label = null)
  225. {
  226. return $this->addColumn('#', $label ?: '#')->bold();
  227. }
  228. /**
  229. * Batch add column to grid.
  230. *
  231. * @example
  232. * 1.$grid->columns(['name' => 'Name', 'email' => 'Email' ...]);
  233. * 2.$grid->columns('name', 'email' ...)
  234. *
  235. * @param array $columns
  236. *
  237. * @return null
  238. */
  239. public function columns($columns = [])
  240. {
  241. if (func_num_args() == 0) {
  242. return $this->columns;
  243. }
  244. if (func_num_args() == 1 && is_array($columns)) {
  245. foreach ($columns as $column => $label) {
  246. $this->column($column, $label);
  247. }
  248. return;
  249. }
  250. foreach (func_get_args() as $column) {
  251. $this->column($column);
  252. }
  253. }
  254. /**
  255. * @return Collection
  256. */
  257. public function getColumns()
  258. {
  259. return $this->columns;
  260. }
  261. /**
  262. * Add column to grid.
  263. *
  264. * @param string $field
  265. * @param string $label
  266. *
  267. * @return Column
  268. */
  269. protected function addColumn($field = '', $label = '')
  270. {
  271. $column = new Column($field, $label);
  272. $column->setGrid($this);
  273. $this->columns->put($field, $column);
  274. return $column;
  275. }
  276. /**
  277. * Get Grid model.
  278. *
  279. * @return Model
  280. */
  281. public function model()
  282. {
  283. return $this->model;
  284. }
  285. /**
  286. * @return array
  287. */
  288. public function getColumnNames()
  289. {
  290. return $this->columnNames;
  291. }
  292. /**
  293. * @param array $options
  294. * @return $this
  295. */
  296. public function setRowSelectorOptions(array $options = [])
  297. {
  298. if (isset($options['style'])) {
  299. $this->options['row_selector_style'] = $options['style'];
  300. }
  301. if (isset($options['circle'])) {
  302. $this->options['row_selector_circle'] = $options['circle'];
  303. }
  304. if (isset($options['clicktr'])) {
  305. $this->options['row_selector_clicktr'] = $options['clicktr'];
  306. }
  307. if (isset($options['label'])) {
  308. $this->options['row_selector_label_key'] = $options['label_name'];
  309. }
  310. if (isset($options['bg'])) {
  311. $this->options['row_selector_bg'] = $options['bg'];
  312. }
  313. return $this;
  314. }
  315. /**
  316. * Prepend checkbox column for grid.
  317. *
  318. * @return void
  319. */
  320. protected function prependRowSelectorColumn()
  321. {
  322. if (!$this->options['show_row_selector']) {
  323. return;
  324. }
  325. $circle = $this->options['row_selector_circle'] ? 'checkbox-circle' : '';
  326. $column = new Column(
  327. Column::SELECT_COLUMN_NAME,
  328. <<<HTML
  329. <div class="checkbox checkbox-{$this->options['row_selector_style']} $circle checkbox-grid">
  330. <input type="checkbox" class="select-all {$this->getSelectAllName()}"><label></label>
  331. </div>
  332. HTML
  333. );
  334. $column->setGrid($this);
  335. $column->displayUsing(Displayers\RowSelector::class);
  336. $this->columns->prepend($column, Column::SELECT_COLUMN_NAME);
  337. }
  338. /**
  339. * Apply column filter to grid query.
  340. */
  341. protected function applyColumnFilter()
  342. {
  343. $this->columns->each->bindFilterQuery($this->model());
  344. }
  345. /**
  346. * Build the grid.
  347. *
  348. * @return void
  349. */
  350. public function build()
  351. {
  352. if ($this->built) {
  353. return;
  354. }
  355. $collection = $this->processFilter(false);
  356. $data = $collection->toArray();
  357. $this->prependRowSelectorColumn();
  358. $this->appendActionsColumn();
  359. Column::setOriginalGridModels($collection);
  360. $this->columns->map(function (Column $column) use (&$data) {
  361. $column->fill($data);
  362. $this->columnNames[] = $column->getName();
  363. });
  364. $this->buildRows($data);
  365. $this->built = true;
  366. if ($data && $this->responsive) {
  367. $this->responsive->build();
  368. }
  369. $this->sortHeaders();
  370. }
  371. /**
  372. * Build the grid rows.
  373. *
  374. * @param array $data
  375. *
  376. * @return void
  377. */
  378. protected function buildRows(array $data)
  379. {
  380. $this->rows = collect($data)->map(function ($model) {
  381. return new Row($this, $model);
  382. });
  383. if ($this->rowsCallback) {
  384. foreach ($this->rowsCallback as $value) {
  385. $value($this->rows);
  386. }
  387. }
  388. }
  389. /**
  390. * Set grid row callback function.
  391. *
  392. * @param Closure $callable
  393. *
  394. * @return Collection|null
  395. */
  396. public function rows(Closure $callable = null)
  397. {
  398. if (is_null($callable)) {
  399. return $this->rows;
  400. }
  401. $this->rowsCallback[] = $callable;
  402. }
  403. /**
  404. * Get create url.
  405. *
  406. * @return string
  407. */
  408. public function getCreateUrl()
  409. {
  410. $queryString = '';
  411. if ($constraints = $this->model()->getConstraints()) {
  412. $queryString = http_build_query($constraints);
  413. }
  414. return sprintf('%s/create%s',
  415. $this->getResource(),
  416. $queryString ? ('?'.$queryString) : ''
  417. );
  418. }
  419. /**
  420. * @param string $width
  421. * @param string $height
  422. * @return $this
  423. */
  424. public function setModalFormDimensions(string $width, string $height)
  425. {
  426. $this->options['dialog_form_area'] = [$width, $height];
  427. return $this;
  428. }
  429. /**
  430. * Render create button for grid.
  431. *
  432. * @return string
  433. */
  434. public function renderCreateButton()
  435. {
  436. if (!$this->options['show_create_btn'] && !$this->options['show_quick_create_btn']) {
  437. return '';
  438. }
  439. return (new Tools\CreateButton($this))->render();
  440. }
  441. /**
  442. * @return $this
  443. */
  444. public function withBorder()
  445. {
  446. $this->options['show_bordered'] = true;
  447. return $this;
  448. }
  449. /**
  450. * Set grid header.
  451. *
  452. * @param Closure|string|Renderable $content
  453. *
  454. * @return $this|Closure
  455. */
  456. public function header($content = null)
  457. {
  458. if (!$content) {
  459. return $this->header;
  460. }
  461. $this->header = $content;
  462. return $this;
  463. }
  464. /**
  465. * Render grid header.
  466. *
  467. * @return string
  468. */
  469. public function renderHeader()
  470. {
  471. if (!$this->header) {
  472. return '';
  473. }
  474. $content = Helper::render($this->header, [$this->processFilter(false)]);
  475. if (empty($content)) {
  476. return '';
  477. }
  478. if ($content instanceof Renderable) {
  479. $content = $content->render();
  480. }
  481. if ($content instanceof Htmlable) {
  482. $content = $content->toHtml();
  483. }
  484. return <<<HTML
  485. <div class="box-header clearfix" style="border-top:1px solid #ebeff2">{$content}</div>
  486. HTML;
  487. }
  488. /**
  489. * Set grid footer.
  490. *
  491. * @param Closure|string|Renderable $content
  492. *
  493. * @return $this|Closure
  494. */
  495. public function footer($content = null)
  496. {
  497. if (!$content) {
  498. return $this->footer;
  499. }
  500. $this->footer = $content;
  501. return $this;
  502. }
  503. /**
  504. * Render grid footer.
  505. *
  506. * @return string
  507. */
  508. public function renderFooter()
  509. {
  510. if (!$this->footer) {
  511. return '';
  512. }
  513. $content = Helper::render($this->footer, [$this->processFilter(false)]);
  514. if (empty($content)) {
  515. return '';
  516. }
  517. if ($content instanceof Renderable) {
  518. $content = $content->render();
  519. }
  520. if ($content instanceof Htmlable) {
  521. $content = $content->toHtml();
  522. }
  523. return <<<HTML
  524. <div class="box-footer clearfix">{$content}</div>
  525. HTML;
  526. }
  527. /**
  528. * Get or set option for grid.
  529. *
  530. * @param string $key
  531. * @param mixed $value
  532. *
  533. * @return $this|mixed
  534. */
  535. public function option($key, $value = null)
  536. {
  537. if (is_null($value)) {
  538. return $this->options[$key];
  539. }
  540. $this->options[$key] = $value;
  541. return $this;
  542. }
  543. /**
  544. * Disable row selector.
  545. *
  546. * @return $this
  547. */
  548. public function disableRowSelector(bool $disable = true)
  549. {
  550. $this->tools->disableBatchActions($disable);
  551. return $this->option('show_row_selector', !$disable);
  552. }
  553. /**
  554. * Show row selector.
  555. *
  556. * @return $this
  557. */
  558. public function showRowSelector(bool $val = true)
  559. {
  560. return $this->disableRowSelector(!$val);
  561. }
  562. /**
  563. * Remove create button on grid.
  564. *
  565. * @return $this
  566. */
  567. public function disableCreateButton(bool $disable = true)
  568. {
  569. return $this->option('show_create_btn', !$disable);
  570. }
  571. /**
  572. * Show create button.
  573. *
  574. * @return $this
  575. */
  576. public function showCreateButton(bool $val = true)
  577. {
  578. return $this->disableCreateButton(!$val);
  579. }
  580. /**
  581. * @param bool $disable
  582. * @return $this
  583. */
  584. public function disableQuickCreateButton(bool $disable = true)
  585. {
  586. return $this->option('show_quick_create_btn', !$disable);
  587. }
  588. /**
  589. * @param bool $val
  590. * @return $this
  591. */
  592. public function showQuickCreateButton(bool $val = true)
  593. {
  594. return $this->disableQuickCreateButton(!$val);
  595. }
  596. /**
  597. * If allow creation.
  598. *
  599. * @return bool
  600. */
  601. public function allowCreateBtn()
  602. {
  603. return $this->options['show_create_btn'];
  604. }
  605. /**
  606. * If grid show quick create button.
  607. *
  608. * @return bool
  609. */
  610. public function allowQuickCreateBtn()
  611. {
  612. return $this->options['show_quick_create_btn'];
  613. }
  614. /**
  615. * Set resource path.
  616. *
  617. * @param string $path
  618. * @return $this
  619. */
  620. public function resource(string $path)
  621. {
  622. if (!empty($path)) {
  623. $this->resourcePath = admin_url($path);
  624. }
  625. return $this;
  626. }
  627. /**
  628. * Get resource path.
  629. *
  630. * @return string
  631. */
  632. public function getResource()
  633. {
  634. return $this->resourcePath ?: (
  635. $this->resourcePath = url(app('request')->getPathInfo())
  636. );
  637. }
  638. /**
  639. * Create a grid instance.
  640. *
  641. * @param mixed ...$params
  642. * @return $this
  643. */
  644. public static function make(...$params)
  645. {
  646. return new static(...$params);
  647. }
  648. /**
  649. * Enable responsive tables.
  650. * @see https://github.com/nadangergeo/RWD-Table-Patterns
  651. *
  652. * @return Responsive
  653. */
  654. public function responsive()
  655. {
  656. if (!$this->responsive) {
  657. $this->responsive = new Responsive($this);
  658. }
  659. return $this->responsive;
  660. }
  661. /**
  662. * @return bool
  663. */
  664. public function allowResponsive()
  665. {
  666. return $this->responsive ? true : false;
  667. }
  668. /**
  669. * @param Closure $closure
  670. * @return $this;
  671. */
  672. public function wrap(\Closure $closure)
  673. {
  674. $this->wrapper = $closure;
  675. return $this;
  676. }
  677. /**
  678. * @return bool
  679. */
  680. public function hasWrapper()
  681. {
  682. return $this->wrapper ? true : false;
  683. }
  684. /**
  685. * Add variables to grid view.
  686. *
  687. * @param array $variables
  688. *
  689. * @return $this
  690. */
  691. public function with($variables = [])
  692. {
  693. $this->variables = $variables;
  694. return $this;
  695. }
  696. /**
  697. * Get all variables will used in grid view.
  698. *
  699. * @return array
  700. */
  701. protected function variables()
  702. {
  703. $this->variables['grid'] = $this;
  704. $this->variables['tableId'] = $this->tableId;
  705. return $this->variables;
  706. }
  707. /**
  708. * Set a view to render.
  709. *
  710. * @param string $view
  711. * @param array $variables
  712. */
  713. public function setView($view, $variables = [])
  714. {
  715. if (!empty($variables)) {
  716. $this->with($variables);
  717. }
  718. $this->view = $view;
  719. }
  720. /**
  721. * Set grid title.
  722. *
  723. * @param string $title
  724. *
  725. * @return $this
  726. */
  727. public function setTitle($title)
  728. {
  729. $this->variables['title'] = $title;
  730. return $this;
  731. }
  732. /**
  733. * Set grid description.
  734. *
  735. * @param string $description
  736. *
  737. * @return $this
  738. */
  739. public function setDescription($description)
  740. {
  741. $this->variables['description'] = $description;
  742. return $this;
  743. }
  744. /**
  745. * Set resource path for grid.
  746. *
  747. * @param string $path
  748. *
  749. * @return $this
  750. */
  751. public function setResource($path)
  752. {
  753. $this->resourcePath = $path;
  754. return $this;
  755. }
  756. /**
  757. * Get the string contents of the grid view.
  758. *
  759. * @return string
  760. */
  761. public function render()
  762. {
  763. $this->handleExportRequest();
  764. try {
  765. $this->callComposing();
  766. $this->build();
  767. } catch (\Throwable $e) {
  768. return Admin::makeExceptionHandler()->renderException($e);
  769. }
  770. return $this->doWrap();
  771. }
  772. /**
  773. * @return string
  774. */
  775. protected function doWrap()
  776. {
  777. $view = view($this->view, $this->variables());
  778. if (!$wrapper = $this->wrapper) {
  779. return $view->render();
  780. }
  781. return $wrapper($view);
  782. }
  783. /**
  784. * Add column to grid.
  785. *
  786. * @param string $name
  787. * @return Column
  788. */
  789. public function __get($name)
  790. {
  791. return $this->addColumn($name);
  792. }
  793. /**
  794. * Dynamically add columns to the grid view.
  795. *
  796. * @param $method
  797. * @param $arguments
  798. *
  799. * @return Column
  800. */
  801. public function __call($method, $arguments)
  802. {
  803. if (static::hasMacro($method)) {
  804. return $this->macroCall($method, $arguments);
  805. }
  806. return $this->addColumn($method, $arguments[0] ?? null);
  807. }
  808. }