1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Twigpack plugin for Craft CMS 3.x |
4
|
|
|
* |
5
|
|
|
* Twigpack is the conduit between Twig and webpack, with manifest.json & |
6
|
|
|
* webpack-dev-server HMR support |
7
|
|
|
* |
8
|
|
|
* @link https://nystudio107.com/ |
9
|
|
|
* @copyright Copyright (c) 2018 nystudio107 |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace nystudio107\twigpack\helpers; |
13
|
|
|
|
14
|
|
|
use Craft; |
15
|
|
|
use craft\helpers\Json as JsonHelper; |
16
|
|
|
use craft\helpers\UrlHelper; |
17
|
|
|
|
18
|
|
|
use yii\base\Exception; |
19
|
|
|
use yii\caching\TagDependency; |
20
|
|
|
use yii\web\NotFoundHttpException; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @author nystudio107 |
24
|
|
|
* @package Twigpack |
25
|
|
|
* @since 1.0.0 |
26
|
|
|
*/ |
27
|
|
|
class Manifest |
28
|
|
|
{ |
29
|
|
|
// Constants |
30
|
|
|
// ========================================================================= |
31
|
|
|
|
32
|
|
|
const CACHE_KEY = 'twigpack'; |
33
|
|
|
const CACHE_TAG = 'twigpack'; |
34
|
|
|
|
35
|
|
|
const DEVMODE_CACHE_DURATION = 1; |
36
|
|
|
|
37
|
|
|
// Protected Static Properties |
38
|
|
|
// ========================================================================= |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @var array |
42
|
|
|
*/ |
43
|
|
|
protected static $files; |
44
|
|
|
|
45
|
|
|
// Public Static Methods |
46
|
|
|
// ========================================================================= |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param array $config |
50
|
|
|
* @param string $moduleName |
51
|
|
|
* @param bool $async |
52
|
|
|
* |
53
|
|
|
* @return null|string |
54
|
|
|
* @throws NotFoundHttpException |
55
|
|
|
*/ |
56
|
|
|
public static function getCssModuleTags(array $config, string $moduleName, bool $async) |
57
|
|
|
{ |
58
|
|
|
$legacyModule = self::getModule($config, $moduleName, 'legacy'); |
59
|
|
|
if ($legacyModule === null) { |
60
|
|
|
return ''; |
61
|
|
|
} |
62
|
|
|
$lines = []; |
63
|
|
|
if ($async) { |
64
|
|
|
$lines[] = "<link rel=\"preload\" href=\"{$legacyModule}\" as=\"style\" onload=\"this.onload=null;this.rel='stylesheet'\" />"; |
65
|
|
|
$lines[] = "<noscript><link rel=\"stylesheet\" href=\"{$legacyModule}\"></noscript>"; |
66
|
|
|
} else { |
67
|
|
|
$lines[] = "<link rel=\"stylesheet\" href=\"{$legacyModule}\" />"; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return implode("\r\n", $lines); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Returns the uglified loadCSS rel=preload Polyfill as per: |
75
|
|
|
* https://github.com/filamentgroup/loadCSS#how-to-use-loadcss-recommended-example |
76
|
|
|
* |
77
|
|
|
* @return string |
78
|
|
|
*/ |
79
|
|
|
public static function getCssRelPreloadPolyfill(): string |
80
|
|
|
{ |
81
|
|
|
return <<<EOT |
82
|
|
|
<script> |
83
|
|
|
/*! loadCSS. [c]2017 Filament Group, Inc. MIT License */ |
84
|
|
|
!function(t){"use strict";t.loadCSS||(t.loadCSS=function(){});var e=loadCSS.relpreload={};if(e.support=function(){var e;try{e=t.document.createElement("link").relList.supports("preload")}catch(t){e=!1}return function(){return e}}(),e.bindMediaToggle=function(t){var e=t.media||"all";function a(){t.media=e}t.addEventListener?t.addEventListener("load",a):t.attachEvent&&t.attachEvent("onload",a),setTimeout(function(){t.rel="stylesheet",t.media="only x"}),setTimeout(a,3e3)},e.poly=function(){if(!e.support())for(var a=t.document.getElementsByTagName("link"),n=0;n<a.length;n++){var o=a[n];"preload"!==o.rel||"style"!==o.getAttribute("as")||o.getAttribute("data-loadcss")||(o.setAttribute("data-loadcss",!0),e.bindMediaToggle(o))}},!e.support()){e.poly();var a=t.setInterval(e.poly,500);t.addEventListener?t.addEventListener("load",function(){e.poly(),t.clearInterval(a)}):t.attachEvent&&t.attachEvent("onload",function(){e.poly(),t.clearInterval(a)})}"undefined"!=typeof exports?exports.loadCSS=loadCSS:t.loadCSS=loadCSS}("undefined"!=typeof global?global:this); |
85
|
|
|
</script> |
86
|
|
|
EOT; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* @param array $config |
91
|
|
|
* @param string $moduleName |
92
|
|
|
* @param bool $async |
93
|
|
|
* |
94
|
|
|
* @return null|string |
95
|
|
|
* @throws NotFoundHttpException |
96
|
|
|
*/ |
97
|
|
|
public static function getJsModuleTags(array $config, string $moduleName, bool $async) |
98
|
|
|
{ |
99
|
|
|
$legacyModule = self::getModule($config, $moduleName, 'legacy'); |
100
|
|
|
if ($legacyModule === null) { |
101
|
|
|
return ''; |
102
|
|
|
} |
103
|
|
|
if ($async) { |
104
|
|
|
$modernModule = self::getModule($config, $moduleName, 'modern'); |
105
|
|
|
if ($modernModule === null) { |
106
|
|
|
return ''; |
107
|
|
|
} |
108
|
|
|
} |
109
|
|
|
$lines = []; |
110
|
|
|
if ($async) { |
111
|
|
|
$lines[] = "<script type=\"module\" src=\"{$modernModule}\"></script>"; |
|
|
|
|
112
|
|
|
$lines[] = "<script nomodule src=\"{$legacyModule}\"></script>"; |
113
|
|
|
} else { |
114
|
|
|
$lines[] = "<script src=\"{$legacyModule}\"></script>"; |
115
|
|
|
} |
116
|
|
|
|
117
|
|
|
return implode("\r\n", $lines); |
118
|
|
|
} |
119
|
|
|
|
120
|
|
|
/** |
121
|
|
|
* Safari 10.1 supports modules, but does not support the `nomodule` |
122
|
|
|
* attribute - it will load <script nomodule> anyway. This snippet solve |
123
|
|
|
* this problem, but only for script tags that load external code, e.g.: |
124
|
|
|
* <script nomodule src="nomodule.js"></script> |
125
|
|
|
* |
126
|
|
|
* Again: this will **not* # prevent inline script, e.g.: |
127
|
|
|
* <script nomodule>alert('no modules');</script>. |
128
|
|
|
* |
129
|
|
|
* This workaround is possible because Safari supports the non-standard |
130
|
|
|
* 'beforeload' event. This allows us to trap the module and nomodule load. |
131
|
|
|
* |
132
|
|
|
* Note also that `nomodule` is supported in later versions of Safari - |
133
|
|
|
* it's just 10.1 that omits this attribute. |
134
|
|
|
* |
135
|
|
|
* c.f.: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc |
136
|
|
|
* |
137
|
|
|
* @return string |
138
|
|
|
*/ |
139
|
|
|
public static function getSafariNomoduleFix(): string |
140
|
|
|
{ |
141
|
|
|
return <<<EOT |
142
|
|
|
<script> |
143
|
|
|
!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}(); |
144
|
|
|
</script> |
145
|
|
|
EOT; |
146
|
|
|
} |
147
|
|
|
|
148
|
|
|
/** |
149
|
|
|
* Return the URI to a module |
150
|
|
|
* |
151
|
|
|
* @param array $config |
152
|
|
|
* @param string $moduleName |
153
|
|
|
* @param string $type |
154
|
|
|
* |
155
|
|
|
* @return null|string |
156
|
|
|
* @throws NotFoundHttpException |
157
|
|
|
*/ |
158
|
|
|
public static function getModule(array $config, string $moduleName, string $type = 'modern') |
159
|
|
|
{ |
160
|
|
|
$module = null; |
161
|
|
|
// Determine whether we should use the devServer for HMR or not |
162
|
|
|
$devMode = Craft::$app->getConfig()->getGeneral()->devMode; |
163
|
|
|
$isHot = ($devMode && $config['useDevServer']); |
164
|
|
|
// Get the manifest file |
165
|
|
|
$manifest = self::getManifestFile($config, $isHot, $type); |
166
|
|
|
if ($manifest !== null) { |
167
|
|
|
// Make sure it exists in the manifest |
168
|
|
|
if ($manifest[$moduleName] === null) { |
169
|
|
|
self::reportError(Craft::t( |
170
|
|
|
'twigpack', |
171
|
|
|
'Module does not exist in the manifest: {moduleName}', |
172
|
|
|
['moduleName' => $moduleName] |
173
|
|
|
)); |
174
|
|
|
|
175
|
|
|
return null; |
176
|
|
|
} |
177
|
|
|
$module = $manifest[$moduleName]; |
178
|
|
|
$prefix = $isHot |
179
|
|
|
? $config['devServer']['publicPath'] |
180
|
|
|
: $config['server']['publicPath']; |
181
|
|
|
// If the module isn't a full URL, prefix it |
182
|
|
|
if (!UrlHelper::isAbsoluteUrl($module)) { |
183
|
|
|
$module = self::combinePaths($prefix, $module); |
184
|
|
|
} |
185
|
|
|
// Make sure it's a full URL |
186
|
|
|
if (!UrlHelper::isAbsoluteUrl($module)) { |
187
|
|
|
try { |
188
|
|
|
$module = UrlHelper::siteUrl($module); |
189
|
|
|
} catch (Exception $e) { |
190
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
191
|
|
|
} |
192
|
|
|
} |
193
|
|
|
} |
194
|
|
|
|
195
|
|
|
return $module; |
196
|
|
|
} |
197
|
|
|
|
198
|
|
|
/** |
199
|
|
|
* Return a JSON-decoded manifest file |
200
|
|
|
* |
201
|
|
|
* @param array $config |
202
|
|
|
* @param bool $isHot |
203
|
|
|
* @param string $type |
204
|
|
|
* |
205
|
|
|
* @return null|array |
206
|
|
|
* @throws NotFoundHttpException |
207
|
|
|
*/ |
208
|
|
|
public static function getManifestFile(array $config, bool &$isHot, string $type = 'modern') |
209
|
|
|
{ |
210
|
|
|
$manifest = null; |
211
|
|
|
// Try to get the manifest |
212
|
|
|
while ($manifest === null) { |
213
|
|
|
$manifestPath = $isHot |
214
|
|
|
? $config['devServer']['manifestPath'] |
215
|
|
|
: $config['server']['manifestPath']; |
216
|
|
|
// Normalize the path |
217
|
|
|
$path = self::combinePaths($manifestPath, $config['manifest'][$type]); |
218
|
|
|
$manifest = self::getJsonFileFromUri($path); |
219
|
|
|
// If the manifest isn't found, and it was hot, fall back on non-hot |
220
|
|
|
if ($manifest === null) { |
221
|
|
|
// We couldn't find a manifest; throw an error |
222
|
|
|
self::reportError(Craft::t( |
223
|
|
|
'twigpack', |
224
|
|
|
'Manifest file not found at: {manifestPath}', |
225
|
|
|
['manifestPath' => $manifestPath] |
226
|
|
|
), true); |
227
|
|
|
if ($isHot) { |
228
|
|
|
// Try again, but not with home module replacement |
229
|
|
|
$isHot = false; |
230
|
|
|
} else { |
231
|
|
|
// Give up and return null |
232
|
|
|
return null; |
233
|
|
|
} |
234
|
|
|
} |
235
|
|
|
} |
236
|
|
|
|
237
|
|
|
return $manifest; |
238
|
|
|
} |
239
|
|
|
|
240
|
|
|
/** |
241
|
|
|
* Invalidate all of the manifest caches |
242
|
|
|
*/ |
243
|
|
|
public static function invalidateCaches() |
244
|
|
|
{ |
245
|
|
|
$cache = Craft::$app->getCache(); |
246
|
|
|
TagDependency::invalidate($cache, self::CACHE_TAG); |
247
|
|
|
Craft::info('All manifest caches cleared', __METHOD__); |
248
|
|
|
} |
249
|
|
|
|
250
|
|
|
// Protected Static Methods |
251
|
|
|
// ========================================================================= |
252
|
|
|
|
253
|
|
|
/** |
254
|
|
|
* Return the contents of a file from a URI path |
255
|
|
|
* |
256
|
|
|
* @param string $path |
257
|
|
|
* |
258
|
|
|
* @return mixed |
259
|
|
|
*/ |
260
|
|
|
protected static function getJsonFileFromUri(string $path) |
261
|
|
|
{ |
262
|
|
|
// Make sure it's a full URL |
263
|
|
|
if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) { |
264
|
|
|
try { |
265
|
|
|
$path = UrlHelper::siteUrl($path); |
266
|
|
|
} catch (Exception $e) { |
267
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
268
|
|
|
} |
269
|
|
|
} |
270
|
|
|
|
271
|
|
|
return self::getJsonFileContents($path); |
272
|
|
|
} |
273
|
|
|
|
274
|
|
|
/** |
275
|
|
|
* Return the contents of a file from the passed in path |
276
|
|
|
* |
277
|
|
|
* @param string $path |
278
|
|
|
* |
279
|
|
|
* @return mixed |
280
|
|
|
*/ |
281
|
|
|
protected static function getJsonFileContents(string $path) |
282
|
|
|
{ |
283
|
|
|
// Return the memoized manifest if it exists |
284
|
|
|
if (!empty(self::$files[$path])) { |
285
|
|
|
return self::$files[$path]; |
286
|
|
|
} |
287
|
|
|
// Create the dependency tags |
288
|
|
|
$dependency = new TagDependency([ |
289
|
|
|
'tags' => [ |
290
|
|
|
self::CACHE_TAG, |
291
|
|
|
self::CACHE_TAG.$path, |
292
|
|
|
], |
293
|
|
|
]); |
294
|
|
|
// Set the cache duration based on devMode |
295
|
|
|
$cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode |
296
|
|
|
? self::DEVMODE_CACHE_DURATION |
297
|
|
|
: null; |
298
|
|
|
// Get the result from the cache, or parse the file |
299
|
|
|
$cache = Craft::$app->getCache(); |
300
|
|
|
$file = $cache->getOrSet( |
301
|
|
|
self::CACHE_KEY.$path, |
302
|
|
|
function () use ($path) { |
303
|
|
|
$result = null; |
304
|
|
|
$string = @file_get_contents($path); |
305
|
|
|
if ($string) { |
306
|
|
|
$result = JsonHelper::decodeIfJson($string); |
307
|
|
|
} |
308
|
|
|
|
309
|
|
|
return $result; |
310
|
|
|
}, |
311
|
|
|
$cacheDuration, |
312
|
|
|
$dependency |
313
|
|
|
); |
314
|
|
|
self::$files[$path] = $file; |
315
|
|
|
|
316
|
|
|
return $file; |
317
|
|
|
} |
318
|
|
|
|
319
|
|
|
/** |
320
|
|
|
* Combined the passed in paths, whether file system or URL |
321
|
|
|
* |
322
|
|
|
* @param string ...$paths |
323
|
|
|
* |
324
|
|
|
* @return string |
325
|
|
|
*/ |
326
|
|
|
protected static function combinePaths(string ...$paths): string |
327
|
|
|
{ |
328
|
|
|
$last_key = \count($paths) - 1; |
329
|
|
|
array_walk($paths, function (&$val, $key) use ($last_key) { |
330
|
|
|
switch ($key) { |
331
|
|
|
case 0: |
332
|
|
|
$val = rtrim($val, '/ '); |
333
|
|
|
break; |
334
|
|
|
case $last_key: |
335
|
|
|
$val = ltrim($val, '/ '); |
336
|
|
|
break; |
337
|
|
|
default: |
338
|
|
|
$val = trim($val, '/ '); |
339
|
|
|
break; |
340
|
|
|
} |
341
|
|
|
}); |
342
|
|
|
|
343
|
|
|
$first = array_shift($paths); |
344
|
|
|
$last = array_pop($paths); |
345
|
|
|
$paths = array_filter($paths); |
346
|
|
|
array_unshift($paths, $first); |
347
|
|
|
$paths[] = $last; |
348
|
|
|
|
349
|
|
|
return implode('/', $paths); |
350
|
|
|
} |
351
|
|
|
|
352
|
|
|
/** |
353
|
|
|
* @param string $error |
354
|
|
|
* @param bool $soft |
355
|
|
|
* |
356
|
|
|
* @throws NotFoundHttpException |
357
|
|
|
*/ |
358
|
|
|
protected static function reportError(string $error, $soft = false) |
359
|
|
|
{ |
360
|
|
|
$devMode = Craft::$app->getConfig()->getGeneral()->devMode; |
361
|
|
|
if ($devMode && !$soft) { |
362
|
|
|
throw new NotFoundHttpException($error); |
363
|
|
|
} |
364
|
|
|
Craft::error($error, __METHOD__); |
365
|
|
|
} |
366
|
|
|
} |
367
|
|
|
|