2
2
3
3
namespace Jonassiewertsen \Livewire \Replacers ;
4
4
5
- use Illuminate \Http \Response ;
6
5
use Illuminate \Support \Str ;
7
- use Livewire \Features \SupportAutoInjectedAssets \SupportAutoInjectedAssets ;
8
- use Livewire \Features \SupportScriptsAndAssets \SupportScriptsAndAssets ;
9
- use Livewire \Livewire ;
10
- use Livewire \Mechanisms \FrontendAssets \FrontendAssets ;
6
+ use Illuminate \Http \Response ;
7
+ use Statamic \StaticCaching \Cacher ;
11
8
use Statamic \StaticCaching \Replacer ;
9
+ use Statamic \StaticCaching \Cachers \NullCacher ;
10
+ use Livewire \Mechanisms \FrontendAssets \FrontendAssets ;
11
+ use Livewire \Features \SupportScriptsAndAssets \SupportScriptsAndAssets ;
12
+ use Livewire \Features \SupportAutoInjectedAssets \SupportAutoInjectedAssets ;
12
13
13
14
class AssetsReplacer implements Replacer
14
15
{
@@ -18,31 +19,54 @@ public function prepareResponseToCache(Response $responseToBeCached, Response $i
18
19
return ;
19
20
}
20
21
21
- if (! $ assets = SupportScriptsAndAssets::getAssets ()) {
22
+ // Don't disturb Livewire's assets injection when caching is off.
23
+ if (app (Cacher::class) instanceof NullCacher) {
22
24
return ;
23
25
}
24
26
27
+ $ assetsHead = '' ;
28
+ $ assetsBody = '' ;
29
+
30
+ $ assets = array_values (SupportScriptsAndAssets::getAssets ());
31
+
32
+ if (count ($ assets ) > 0 ) {
33
+ foreach ($ assets as $ asset ) {
34
+ $ assetsHead .= $ asset ."\n" ;
35
+ }
36
+ }
37
+
38
+ if ($ this ->shouldInjectLivewireAssets ($ initialResponse )) {
39
+ $ assetsHead .= FrontendAssets::styles ()."\n" ;
40
+ $ assetsBody .= FrontendAssets::scripts ()."\n" ;
41
+
42
+ /**
43
+ * Ensure Livewire injects its assets on the initial request.
44
+ * @see \Livewire\Features\SupportAutoInjectedAssets\SupportAutoInjectedAssets
45
+ */
46
+ app (FrontendAssets::class)->hasRenderedStyles = false ;
47
+ app (FrontendAssets::class)->hasRenderedScripts = false ;
48
+ }
49
+
25
50
$ responseToBeCached ->setContent (
26
- SupportAutoInjectedAssets::injectAssets (
27
- html: $ content ,
28
- assetsHead: implode ('' , $ assets ),
29
- assetsBody: ''
30
- )
51
+ SupportAutoInjectedAssets::injectAssets ($ content , $ assetsHead , $ assetsBody )
31
52
);
32
53
}
33
54
34
- public function replaceInCachedResponse (Response $ response )
55
+ protected function shouldInjectLivewireAssets (Response $ response ): bool
35
56
{
36
57
if (Str::contains ($ response , FrontendAssets::scripts ())) {
37
- return ;
58
+ return false ;
38
59
}
39
60
40
61
if (Str::contains ($ response , FrontendAssets::scriptConfig ())) {
41
- return ;
62
+ return false ;
42
63
}
43
64
44
- app (FrontendAssets::class)->hasRenderedScripts = false ;
65
+ return true ;
66
+ }
45
67
46
- Livewire::forceAssetInjection ();
68
+ public function replaceInCachedResponse (Response $ response )
69
+ {
70
+ //
47
71
}
48
72
}
0 commit comments