Modal.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace Dcat\Admin\Grid\Displayers;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Support\Helper;
  5. use Dcat\Admin\Support\RemoteRenderable;
  6. use Illuminate\Support\Str;
  7. class Modal extends AbstractDisplayer
  8. {
  9. protected $title;
  10. protected $renderable;
  11. public function title(string $title)
  12. {
  13. $this->title = $title;
  14. }
  15. protected function generateElementId()
  16. {
  17. $key = Str::random(8);
  18. return 'grid-modal-'.$this->grid->getName().$key;
  19. }
  20. protected function addRenderableModalScript(string $modalId, string $url)
  21. {
  22. $script = <<<JS
  23. (function () {
  24. var modal = $('#{$modalId}');
  25. modal.on('show.bs.modal', function (e) {
  26. modal.find('.modal-body').html('<div style="min-height:150px"></div>');
  27. modal.find('.modal-body').loading();
  28. $.ajax('{$url}').then(function (data) {
  29. modal.find('.modal-body').html(data);
  30. });
  31. })
  32. })();
  33. JS;
  34. Admin::script($script);
  35. }
  36. protected function setUpRemoteRenderable(string $modalId, RemoteRenderable $renderable)
  37. {
  38. $renderable->with('key', $this->getKey());
  39. $this->addRenderableModalScript($modalId, $renderable->getUrl());
  40. $renderable::collectAssets();
  41. }
  42. public function display($callback = null)
  43. {
  44. $title = $this->value ?: $this->trans('title');
  45. if (func_num_args() == 2) {
  46. [$title, $callback] = func_get_args();
  47. }
  48. $html = $this->value;
  49. $id = $this->generateElementId();
  50. if ($callback instanceof \Closure) {
  51. $html = Helper::render(
  52. $callback->call($this->row, $this)
  53. );
  54. } elseif (is_string($callback) && is_subclass_of($callback, RemoteRenderable::class)) {
  55. $html = '';
  56. $this->setUpRemoteRenderable($id, $callback::make());
  57. } elseif ($callback instanceof RemoteRenderable) {
  58. $html = '';
  59. $this->setUpRemoteRenderable($id, $callback);
  60. }
  61. $title = $this->title ?: $title;
  62. return <<<EOT
  63. <span class="grid-expand" data-toggle="modal" data-target="#{$id}">
  64. <a href="javascript:void(0)"><i class="fa fa-clone"></i>&nbsp;&nbsp;{$this->value}</a>
  65. </span>
  66. <div class="modal fade" id="{$id}" role="dialog">
  67. <div class="modal-dialog modal-lg">
  68. <div class="modal-content">
  69. <div class="modal-header">
  70. <h4 class="modal-title">{$title}</h4>
  71. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  72. </div>
  73. <div class="modal-body">
  74. {$html}
  75. </div>
  76. </div>
  77. </div>
  78. </div>
  79. EOT;
  80. }
  81. }