| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\Api\Contracts; |
| 4 |
|
| 5 |
use FluentCart\App\Helpers\Helper; |
| 6 |
use FluentCart\App\Vite; |
| 7 |
use FluentCart\Framework\Support\Str; |
| 8 |
|
| 9 |
trait CanEnqueue |
| 10 |
{ |
| 11 |
protected ?string $slugPrefix = null; |
| 12 |
protected ?string $localizationKey = null; |
| 13 |
|
| 14 |
protected $isStylesLoaded = false; |
| 15 |
protected $isScriptsLoaded = false; |
| 16 |
|
| 17 |
|
| 18 |
protected function getScriptName(): string |
| 19 |
{ |
| 20 |
return $this->generateEnqueueSlug() . '_js'; |
| 21 |
} |
| 22 |
|
| 23 |
public function getScripts(): array |
| 24 |
{ |
| 25 |
return []; |
| 26 |
} |
| 27 |
|
| 28 |
public function enqueueScripts() |
| 29 |
{ |
| 30 |
if ($this->isScriptsLoaded) { |
| 31 |
return; |
| 32 |
} |
| 33 |
|
| 34 |
$this->isScriptsLoaded = true; |
| 35 |
|
| 36 |
$localizeData = $this->localizeData(); |
| 37 |
$localizeData['fluentCartRestVars'] = [ |
| 38 |
'rest' => Helper::getRestInfo(), |
| 39 |
'ajaxurl' => admin_url('admin-ajax.php') |
| 40 |
]; |
| 41 |
|
| 42 |
$this->enqueue_scripts($localizeData); |
| 43 |
|
| 44 |
|
| 45 |
} |
| 46 |
|
| 47 |
public function enqueue_scripts($localizeData = []): void |
| 48 |
{ |
| 49 |
Vite::enqueueAllScripts( |
| 50 |
$this->getScripts(), |
| 51 |
$this->getScriptName(), |
| 52 |
$localizeData |
| 53 |
); |
| 54 |
} |
| 55 |
|
| 56 |
public function getStyles(): array |
| 57 |
{ |
| 58 |
return []; |
| 59 |
} |
| 60 |
|
| 61 |
protected function getStyleName(): string |
| 62 |
{ |
| 63 |
return $this->generateEnqueueSlug() . '_css'; |
| 64 |
} |
| 65 |
|
| 66 |
public function enqueueStyles() |
| 67 |
{ |
| 68 |
if ($this->isStylesLoaded) { |
| 69 |
return; |
| 70 |
} |
| 71 |
|
| 72 |
$this->isStylesLoaded = true; |
| 73 |
|
| 74 |
$this->enqueue_styles(); |
| 75 |
} |
| 76 |
|
| 77 |
public function enqueue_styles(): void |
| 78 |
{ |
| 79 |
Vite::enqueueAllStyles( |
| 80 |
$this->getStyles(), |
| 81 |
$this->getStyleName() |
| 82 |
); |
| 83 |
} |
| 84 |
|
| 85 |
abstract protected function generateEnqueueSlug(): string; |
| 86 |
|
| 87 |
protected function getLocalizationKey(): string |
| 88 |
{ |
| 89 |
return $this->localizationKey ?? |
| 90 |
$this->generateEnqueueSlug() . '_data'; |
| 91 |
} |
| 92 |
|
| 93 |
|
| 94 |
public function localizeData(): array |
| 95 |
{ |
| 96 |
return []; |
| 97 |
} |
| 98 |
|
| 99 |
public function enqueueAssets() |
| 100 |
{ |
| 101 |
$this->enqueueScripts(); |
| 102 |
$this->enqueueStyles(); |
| 103 |
return $this; |
| 104 |
} |
| 105 |
} |
| 106 |
|