RowSelector.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace Dcat\Admin\Grid\Tools;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Grid;
  5. use Illuminate\Support\Arr;
  6. class RowSelector
  7. {
  8. protected $grid;
  9. protected $style = 'primary';
  10. protected $background;
  11. protected $rowClickable = false;
  12. protected $titleColumn;
  13. public function __construct(Grid $grid)
  14. {
  15. $this->grid = $grid;
  16. }
  17. public function style(string $style)
  18. {
  19. $this->style = $style;
  20. return $this;
  21. }
  22. public function background(string $value)
  23. {
  24. $this->background = $value;
  25. return $this;
  26. }
  27. public function click(bool $value = true)
  28. {
  29. $this->rowClickable = $value;
  30. return $this;
  31. }
  32. public function titleColumn(string $value)
  33. {
  34. $this->titleColumn = $value;
  35. return $this;
  36. }
  37. public function renderHeader()
  38. {
  39. return <<<HTML
  40. <div class="vs-checkbox-con vs-checkbox-{$this->style} checkbox-grid">
  41. <input type="checkbox" class="select-all {$this->grid->getSelectAllName()}">
  42. <span class="vs-checkbox"><span class="vs-checkbox--check"><i class="vs-icon feather icon-check"></i></span></span>
  43. </div>
  44. HTML;
  45. }
  46. public function renderColumn($row, $id)
  47. {
  48. $this->setupScript();
  49. return <<<EOT
  50. <div class="vs-checkbox-con vs-checkbox-{$this->style} checkbox-grid">
  51. <input type="checkbox" class="{$this->grid->getRowName()}-checkbox" data-id="{$id}" data-label="{$this->getTitle($row, $id)}">
  52. <span class="vs-checkbox"><span class="vs-checkbox--check"><i class="vs-icon feather icon-check"></i></span></span>
  53. </div>
  54. EOT;
  55. }
  56. protected function setupScript()
  57. {
  58. $clickable = $this->rowClickable ? 'true' : 'false';
  59. $background = $this->background ?: Admin::color()->dark20();
  60. Admin::script(
  61. <<<JS
  62. var selector = Dcat.RowSelector({
  63. checkboxSelector: '.{$this->grid->getRowName()}-checkbox',
  64. selectAllSelector: '.{$this->grid->getSelectAllName()}',
  65. clickRow: {$clickable},
  66. background: '{$background}',
  67. });
  68. Dcat.grid.addSelector(selector, '{$this->grid->getName()}');
  69. JS
  70. );
  71. }
  72. protected function getTitle($row, $id)
  73. {
  74. if ($key = $this->titleColumn) {
  75. $label = Arr::get($row->toArray(), $key);
  76. if ($label !== null && $label !== '') {
  77. return $label;
  78. }
  79. return $id;
  80. }
  81. $label = $row->name ?: $row->title;
  82. return $label ?: ($row->username ?: $id);
  83. }
  84. }