Lazy.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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->load($load);
  15. $this->class('lazy-box');
  16. $this->id('lazy-'.Str::random(8));
  17. }
  18. /**
  19. * 设置是否立即加载.
  20. *
  21. * @param bool $value
  22. *
  23. * @return $this
  24. */
  25. public function load(bool $value)
  26. {
  27. $this->load = $value;
  28. return $this;
  29. }
  30. /**
  31. * 获取触发异步渲染JS代码.
  32. *
  33. * @return string
  34. */
  35. public function getLoadScript()
  36. {
  37. return "$('{$this->getElementSelector()}').trigger('{$this->target}:load');";
  38. }
  39. protected function addScript()
  40. {
  41. $loader = $this->load ? "target.trigger('{$this->target}:load')" : '';
  42. $this->script = <<<JS
  43. (function () {
  44. var target = $('{$this->getElementSelector()}'), body = target;
  45. {$this->getRenderableScript()}
  46. body.html('<div style="min-height:150px"></div>').loading();
  47. {$loader}
  48. })();
  49. JS;
  50. }
  51. public function html()
  52. {
  53. $this->addScript();
  54. return <<<HTML
  55. <div {$this->formatHtmlAttributes()}></div>
  56. HTML;
  57. }
  58. }