QuickSearch.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. <?php
  2. namespace Dcat\Admin\Grid\Tools;
  3. use Dcat\Admin\Admin;
  4. use Illuminate\Support\Arr;
  5. class QuickSearch extends AbstractTool
  6. {
  7. /**
  8. * @var string
  9. */
  10. protected $view = 'admin::grid.quick-search';
  11. /**
  12. * @var string
  13. */
  14. protected $placeholder = null;
  15. /**
  16. * @var string
  17. */
  18. protected $queryName = '__search__';
  19. /**
  20. * @var int rem
  21. */
  22. protected $width = 27;
  23. /**
  24. * @param string|null $name
  25. *
  26. * @return $this
  27. */
  28. public function setQueryName(?string $name)
  29. {
  30. $this->queryName = $name;
  31. return $this;
  32. }
  33. /**
  34. * @return string
  35. */
  36. public function queryName()
  37. {
  38. return $this->queryName;
  39. }
  40. /**
  41. * @param int $width
  42. *
  43. * @return $this
  44. */
  45. public function width(int $width)
  46. {
  47. $this->width = $width;
  48. return $this;
  49. }
  50. /**
  51. * Set placeholder.
  52. *
  53. * @param string $text
  54. *
  55. * @return $this
  56. */
  57. public function placeholder(?string $text = '')
  58. {
  59. $this->placeholder = $text;
  60. return $this;
  61. }
  62. /**
  63. * @return string
  64. */
  65. public function value()
  66. {
  67. return request($this->queryName);
  68. }
  69. /**
  70. * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  71. */
  72. public function render()
  73. {
  74. $this->setupScript();
  75. $request = request();
  76. $query = $request->query();
  77. Arr::forget($query, [
  78. $this->queryName,
  79. $this->parent->model()->getPageName(),
  80. '_pjax',
  81. ]);
  82. $vars = [
  83. 'action' => $request->url().'?'.http_build_query($query),
  84. 'key' => $this->queryName,
  85. 'value' => $this->value(),
  86. 'placeholder' => $this->placeholder ?: trans('admin.search'),
  87. 'width' => $this->width,
  88. ];
  89. return view($this->view, $vars);
  90. }
  91. protected function setupScript()
  92. {
  93. $script = <<<'JS'
  94. var show = function () {
  95. var t = $(this),
  96. clear = t.parent().find('.quick-search-clear');
  97. if (t.val()) {
  98. clear.css({color: '#333'});
  99. } else {
  100. clear.css({color: '#fff'});
  101. }
  102. return false;
  103. };
  104. $('input.quick-search-input').on('focus', show).on('keyup', show);
  105. $('.quick-search-clear').click(function () {
  106. $(this).parent().find('.quick-search-input').val('');
  107. $(this).closest('form').submit();
  108. });
  109. JS;
  110. Admin::script($script);
  111. }
  112. }