Lazy.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Dcat\Admin\Widgets;
  3. use Dcat\Admin\Contracts\LazyRenderable;
  4. use Dcat\Admin\Traits\InteractsWithRenderApi;
  5. use Illuminate\Support\Str;
  6. class Lazy extends Widget
  7. {
  8. use InteractsWithRenderApi;
  9. protected $target = 'lazy';
  10. protected $load = true;
  11. public function __construct(LazyRenderable $renderable = null, bool $load = true)
  12. {
  13. $this->setRenderable($renderable);
  14. $this->class('lazy-box');
  15. $this->id('lazy-'.Str::random(8));
  16. }
  17. /**
  18. * 设置是否立即加载.
  19. *
  20. * @param bool $value
  21. *
  22. * @return $this
  23. */
  24. public function load(bool $value)
  25. {
  26. $this->load = $value;
  27. return $this;
  28. }
  29. /**
  30. * 获取触发异步渲染JS代码.
  31. *
  32. * @return string
  33. */
  34. public function getLoadScript()
  35. {
  36. return "$('{$this->getElementSelector()}').trigger('{$this->target}:load');";
  37. }
  38. protected function addScript()
  39. {
  40. $loader = $this->load ? "target.trigger('{$this->target}:load')" : '';
  41. $this->script = <<<JS
  42. (function () {
  43. var target = $('{$this->getElementSelector()}'), body = target;
  44. {$this->getRenderableScript()}
  45. body.html('<div style="min-height:150px"></div>').loading();
  46. {$loader}
  47. })();
  48. JS;
  49. }
  50. public function html()
  51. {
  52. $this->addScript();
  53. return <<<HTML
  54. <div {$this->formatHtmlAttributes()}></div>
  55. HTML;
  56. }
  57. }