-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathJavaScriptAssetService.php
More file actions
327 lines (249 loc) · 8.84 KB
/
JavaScriptAssetService.php
File metadata and controls
327 lines (249 loc) · 8.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
<?php
namespace Sheaf\Cli\Services;
use Exception;
use Illuminate\Support\Facades\File;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Process;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\text;
class JavaScriptAssetService
{
protected ContentTemplateService $contentTemplateService;
public function __construct(
protected Command $command,
protected bool $forceOverwrite = false,
protected bool $shouldSetupLivewire = false
) {
$this->contentTemplateService = new ContentTemplateService();
}
/**
* Create JavaScript files for dark mode functionality
*/
public function createDarkModeAssets(): bool
{
try {
$this->ensureDirectoryStructure();
$utilsCreated = $this->createUtilsFile();
$themeCreated = $this->createThemeFile();
if ($utilsCreated || $themeCreated) {
$this->displayCreationSummary($utilsCreated, $themeCreated);
$this->addImportToAppJsFile();
return true;
}
return false;
} catch (\Exception $e) {
$this->command->error("Failed to create JavaScript assets: {$e->getMessage()}");
return false;
}
}
/**
* Set up the app.js file
*/
public function setupAppJs()
{
if ($this->shouldSetupLivewire) {
$this->SetupLivewire();
return;
}
$this->installAndSetupAlpine();
}
public function installAndSetupAlpine()
{
// check if livewire version 3 is installed
if ($this->hasLivewire3()) {
return;
}
if (!$this->isNpmPackageInstalled('alpinejs')) {
$result = spin(
callback: fn() => Process::run("npm install alpinejs @alpinejs/anchor"),
message: "Installing alpinejs and @alpinejs/anchor..."
);
if ($result->failed()) {
$this->command->error("Failed to install Alpine.js. {$result->errorOutput()}");
return;
} else {
$this->command->line("<fg=green>✓ alpinejs and alpinejs/anchor Installed.</fg=green>");
}
}
$appJsPath = $this->getMainJsFilePath();
$appJsContent = File::get($appJsPath);
if ($this->isAlpineAlreadyImported($appJsContent)) {
return;
}
$alpineInitialize = $this->contentTemplateService->getStubContent('alpinejs');
$newContent = $appJsContent . $alpineInitialize;
File::put($appJsPath, $newContent);
}
/**
* Set up livewire scripts
*/
public function SetupLivewire()
{
$appJsPath = $this->getMainJsFilePath();
$appJsContent = File::get($appJsPath);
if (preg_match('/import\s+{[^}]*\bLivewire\b[^}]*\bAlpine\b[^}]*}/i', $appJsContent)) {
return;
}
$livewireStarterKit = $this->contentTemplateService->getStubContent('livewirejs');
$newContent = $appJsContent . $livewireStarterKit;
File::put($appJsPath, $newContent);
}
/**
* Create utils.js file
*/
protected function createUtilsFile(): bool
{
$path = resource_path("js/utils.js");
$this->updateSheafLock("resources/js/utils.js", "dark-theme");
if (File::exists($path) && !$this->forceOverwrite) {
$this->command->warn("File already exists: utils.js");
if (!$this->command->confirm('Overwrite existing utils.js file?', false)) {
return false;
}
}
$content = $this->contentTemplateService->getStubContent('utils.js');
File::put($path, $content);
$this->command->info("✓ Created: resources/js/utils.js");
return true;
}
/**
* Create theme.js file in globals directory
*/
protected function createThemeFile(): bool
{
$filePath = resource_path("js/globals/theme.js");
if (File::exists($filePath) && !$this->forceOverwrite) {
$this->command->warn("File already exists: globals/theme.js");
if (!$this->command->confirm('Overwrite existing theme.js file?', false)) {
return false;
}
}
$content = $this->contentTemplateService->getStubContent('theme.js');
File::put($filePath, $content);
$this->command->info("✓ Created: resources/js/globals/theme.js");
return true;
}
/**
* Ensure directory structure exists
*/
protected function ensureDirectoryStructure(): void
{
$baseDir = resource_path('js');
$globalsDir = "$baseDir/globals";
if (!File::exists($globalsDir)) {
File::makeDirectory($globalsDir, 0755, true);
$this->command->info('✓ Created directory: resources/js/globals');
}
}
/**
* Display creation summary
*/
protected function displayCreationSummary(bool $utilsCreated, bool $themeCreated): void
{
$this->command->newLine();
$this->command->line('<fg=green>JavaScript Assets Created:</fg=green>');
if ($utilsCreated) {
$this->command->line(' ✓ utils.js - Alpine.js reactive magic property utilities');
}
if ($themeCreated) {
$this->command->line(' ✓ globals/theme.js - Dark mode theme management system');
}
}
/**
* Provide import instructions for the created files
*/
protected function addImportToAppJsFile(): void
{
$file = 'app.js';
$path = $this->getMainJsFilePath();
$content = File::get($path);
// Check if import already exists
if (!preg_match('/^import\s+[\'"]\.\/globals\/theme\.js[\'"]/', $content)) {
$importStatement = "import './globals/theme.js'; /* By Sheaf.dev */ \n\n";
$content = $importStatement . $content;
}
File::put($path, $content);
$this->command->line(" ✓ Added import statement to: {$file}");
}
public function getMainJsFilePath()
{
$path = resource_path('/js/app.js');
if (!File::exists($path)) {
$path = text(
label: "Enter the path (relative to resources/) to your main JS file:",
placeholder: '/js/app.js',
default: "/js/app.js",
);
$path = resource_path($path);
}
if (File::exists($path)) {
return $path;
}
$confirm = confirm("The $path is not exists, do you want to create it?", true);
if (!$confirm) {
throw new Exception("The path $path is not exists, can not complete the initialization.");
}
File::ensureDirectoryExists(resource_path('js'));
File::put($path, "// Created by Sheaf UI \n");
return $path;
}
/**
* Check if Alpine.js is already imported
*/
protected function isAlpineAlreadyImported(string $content): bool
{
$patterns = [
'/import\s+.*alpine/i',
'/require\s*\(\s*[\'"]alpine/i',
'/from\s+[\'"]alpinejs[\'"]/',
];
foreach ($patterns as $pattern) {
if (preg_match($pattern, $content)) {
return true;
}
}
return false;
}
public function isNpmPackageInstalled($packageName)
{
$packageJsonPath = base_path('package.json');
if (!file_exists($packageJsonPath)) {
return false;
}
$packageJson = json_decode(File::get($packageJsonPath), true);
// Check in dependencies
if (isset($packageJson['dependencies'][$packageName])) {
return true;
}
// Check in devDependencies
if (isset($packageJson['devDependencies'][$packageName])) {
return true;
}
return false;
}
/**
* Check if Livewire version 3 is installed
*/
protected function hasLivewire3(): bool
{
if (!\Composer\InstalledVersions::isInstalled('livewire/livewire')) {
return false;
}
$version = \Composer\InstalledVersions::getPrettyVersion('livewire/livewire');
return version_compare($version, 'v3.0.0', '>=');
}
protected function updateSheafLock($path, $name) {
$sheafLockPath = base_path('sheaf-lock.json');
$sheafLock = [];
if(File::exists($sheafLockPath)) {
$sheafLock = json_decode(File::get($sheafLockPath), true) ?: [];
}
$sheafLock['files'] ??= [];
$sheafLock['files'][$path] ??= [];
if(!in_array($name, $sheafLock['files'][$path], true)) {
$sheafLock['files'][$path][] = $name;
}
File::put($sheafLockPath, json_encode($sheafLock, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
}