-
-
Notifications
You must be signed in to change notification settings - Fork 624
Expand file tree
/
Copy pathNavItem.php
More file actions
636 lines (553 loc) · 16.1 KB
/
NavItem.php
File metadata and controls
636 lines (553 loc) · 16.1 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
<?php
namespace Statamic\CP\Navigation;
use Illuminate\Support\Collection;
use Statamic\CommandPalette\Category;
use Statamic\CommandPalette\Link;
use Statamic\Facades\CP\Nav;
use Statamic\Facades\URL;
use Statamic\Statamic;
use Statamic\Support\Str;
use Statamic\Support\Svg;
use Statamic\Support\Traits\FluentlyGetsAndSets;
class NavItem
{
use FluentlyGetsAndSets;
protected $display;
protected $section;
protected $id;
protected $url;
protected $icon;
protected $children;
protected $isChild;
protected $wasOriginallyChild;
protected $authorization;
protected $active;
protected $view;
protected $order;
protected $hidden;
protected $manipulations;
protected $original;
protected $attributes;
protected $extra;
/**
* Get or set display.
*
* @param string|null $display
* @return mixed
*/
public function display($display = null)
{
return $this->fluentlyGetOrSet('display')->value($display);
}
/**
* Get or set section name.
*
* @param string|null $section
* @return mixed
*/
public function section($section = null)
{
return $this->fluentlyGetOrSet('section')->value($section);
}
/**
* Get or set the ID for referencing in preferences.
*
* @param string|null $id
* @return mixed
*/
public function id($id = null)
{
return $this
->fluentlyGetOrSet('id')
->setter(function ($value) {
return Str::endsWith($value, '::')
? $value.static::snakeCase($this->display())
: $value;
})
->getter(function ($value) {
if ($value) {
return $value;
}
$section = static::snakeCase($this->section());
$item = static::snakeCase($this->display());
return "{$section}::{$item}";
})
->value($id);
}
/**
* Preserve current ID.
*
* @return $this
*/
public function preserveCurrentId()
{
return $this->id($this->id());
}
/**
* Set url by cp route name.
*
* @param array|string $name
* @param mixed $params
* @return mixed
*/
public function route($name, $params = [])
{
return $this->url(cp_route($name, $params));
}
/**
* Get or set URL.
*
* @param string|null $url
* @return mixed
*/
public function url($url = null)
{
return $this
->fluentlyGetOrSet('url')
->setter(function ($url) {
if (URL::isAbsolute($url)) {
return $url;
}
if (Str::startsWith($url, '/')) {
return url($url);
}
return url(config('statamic.cp.route').'/'.$url);
})
->afterSetter(function ($url) {
$cpUrl = url(config('statamic.cp.route')).'/';
if (! $this->active && Str::startsWith($url, $cpUrl)) {
$this->active = $this->generateActivePatternForCpUrl($url);
}
})
->value($url);
}
/**
* Generate active URL pattern to determine when to resolve children for `hasActiveChild()` checks.
*
* @param string $url
* @return string
*/
protected function generateActivePatternForCpUrl($url)
{
$cpUrl = url(config('statamic.cp.route')).'/';
$relativeUrl = str_replace($cpUrl, '', URL::removeQueryAndFragment($url));
$relativeUrl = rtrim($relativeUrl, '/');
return $relativeUrl.'(/(.*)?|$)';
}
/**
* Generate active URL patterns for this item's children.
*
* @return Collection
*/
protected function generateActivePatternsForChildren()
{
if (! $this->children()) {
return collect();
}
return collect(NavBuilder::getUnresolvedChildrenUrlsForItem($this) ?? [])
->map(fn ($url) => $this->generateActivePatternForCpUrl($url));
}
/**
* Get editable url for nav builder UI.
*/
public function editableUrl()
{
if (! $this->url) {
return null;
}
if (Str::startsWith($this->url, url('/'))) {
return str_replace(url('/'), '', $this->url);
}
return $this->url;
}
/**
* Get or set icon.
*
* @param string|null $icon
* @return mixed
*/
public function icon($icon = null)
{
return $this->fluentlyGetOrSet('icon')->args(func_get_args());
}
/**
* Get icon as resolved renderable SVG.
*
* @return string
*/
public function svg()
{
$value = $this->icon() ?? 'collections';
if (! Str::startsWith($value, '<svg')) {
$value = Statamic::svg("icons/{$value}");
}
$value = $this->sanitizeSvg($value);
return Svg::withClasses($value, 'size-4 shrink-0');
}
private function sanitizeSvg(string $svg): string
{
try {
return Svg::sanitize($svg);
} catch (\Throwable $e) {
return '';
}
}
/**
* Get or set HTML attributes.
*
* @param array|null $attrs
* @return mixed
*/
public function attributes($attrs = null)
{
return $this
->fluentlyGetOrSet('attributes')
->value($attrs);
}
/**
* Get or set extra data.
*
* @param array|null $extra
* @return mixed
*/
public function extra($extra = null)
{
return $this
->fluentlyGetOrSet('extra')
->value($extra);
}
/**
* Get or set child nav items.
*
* @param array|null $items
* @param bool $generateNewIds
* @return mixed
*/
public function children($items = null, $generateNewIds = true)
{
if (is_null($items)) {
return $this->children;
}
if (is_callable($items)) {
$this->children = $items;
return $this;
}
$this->children = collect($items)
->map(function ($value, $key) {
return $value instanceof self
? $value
: Nav::item($key)->url($value);
})
->map(function ($navItem) use ($generateNewIds) {
return $navItem
->id($generateNewIds ? $this->id().'::' : $navItem->id())
->icon($navItem->icon() ?? $this->icon())
->section($this->section())
->isChild(true);
})
->values();
if ($this->children->isEmpty()) {
$this->children = null;
}
return $this;
}
/**
* Track if this nav item is a child of another nav item.
*
* @param bool|null $isChild
* @return mixed
*/
public function isChild($isChild = null)
{
return $this
->fluentlyGetOrSet('isChild')
->getter(function ($value) {
return (bool) $value;
})
->afterSetter(function ($value) {
if ($value === true && ! isset($this->wasOriginallyChild)) {
$this->wasOriginallyChild = $value;
}
})
->value($isChild);
}
/**
* Check if current url is a restful descendant.
*/
protected function currentUrlIsRestfulDescendant(): bool
{
return (bool) Str::endsWith(request()->url(), [
'/create',
'/edit',
]);
}
/**
* Check if we should assume nested URL conventions for active state on children.
*/
protected function doesntHaveExplicitChildren(): bool
{
return (bool) ! $this->children;
}
/**
* Check if this nav item was ever a child before user preferences were applied.
*/
protected function wasOriginallyChild(): bool
{
return (bool) $this->wasOriginallyChild;
}
/**
* Resolve children closure.
*
* @return $this
*/
public function resolveChildren()
{
if (! is_callable($this->children)) {
return $this;
}
// Resolve children closure
$this->children($this->children()());
// Resolve children closure on synced original instance
if ($this->original() && is_callable($this->original->children())) {
$this->original()->children($this->original->children()());
}
// Sync original on each new child item
if ($this->children()) {
$this->children()->each(fn ($item) => $item->syncOriginal());
}
return $this;
}
/**
* Get or set authorization.
*
* @param string|null $ability
* @param array $arguments
* @return mixed
*/
public function authorization($ability = null, $arguments = [])
{
if (is_null($ability)) {
return $this->authorization;
}
$this->authorization = (object) [
'ability' => $ability,
'arguments' => $arguments,
];
return $this;
}
/**
* Get or set authorization (an alias for consistency with Laravel's can() method).
*
* @param string|null $ability
* @param array $arguments
* @return mixed
*/
public function can($ability = null, $arguments = [])
{
return $this->authorization($ability, $arguments);
}
/**
* Determine whether the nav item is currently active.
*
* @return bool
*/
public function isActive()
{
if ($this->hasActiveChild()) {
return true;
}
// If the current URL is not explicitly referenced in the CP nav,
// and if this item is/was ever a child nav item,
// then check against URL heirarchy conventions using regex pattern.
if ($this->currentUrlIsNotExplicitlyReferencedInNav()) {
switch (true) {
case $this->currentUrlIsRestfulDescendant():
case $this->doesntHaveExplicitChildren():
case $this->wasOriginallyChild():
return $this->isActiveByPattern($this->active);
}
}
return URL::tidy(request()->url()) === URL::removeQueryAndFragment($this->url);
}
/**
* Determine whether the nav item has a currently active child.
*
* @return bool
*/
protected function hasActiveChild()
{
// If children are already resolved to a collection, just check `isActive()` on each child item.
if ($this->children() instanceof Collection) {
return $this
->children()
->filter(fn ($item) => $item->isActive())
->isNotEmpty();
}
// If the current URL is not explicitly referenced in the CP nav,
// and if this item has children to check against,
// then check against URL heirarchy conventions using regex pattern.
if ($this->currentUrlIsNotExplicitlyReferencedInNav() && $this->children()) {
return $this->isActiveByPattern($this->generateActivePatternsForChildren());
}
// If children closure has not been resolved, and children urls are cached, check against cached children.
if ($childrenUrls = NavBuilder::getUnresolvedChildrenUrlsForItem($this)) {
return collect($childrenUrls)
->map(fn ($url) => URL::removeQueryAndFragment($url))
->contains(URL::tidy(request()->url()));
}
return false;
}
/**
* Determine whether the current URL is explicitly referenced in nav.
*
* @return bool
*/
protected function currentUrlIsNotExplicitlyReferencedInNav()
{
return ! NavBuilder::getAllUrls()->contains(URL::tidy(request()->url()));
}
/**
* Determine whether the nav item is currently active using the regex technique for deeply nested hierarchical urls.
*
* @param string|array $active
* @return bool
*/
protected function isActiveByPattern($active)
{
if (! $active) {
return false;
}
return collect($active)
->map(fn ($pattern) => preg_quote(config('statamic.cp.route'), '#').'/'.$pattern)
->filter(fn ($pattern) => preg_match('#'.$pattern.'#', request()->decodedPath()) === 1)
->isNotEmpty();
}
/**
* Get or set custom view.
*
* @param string|null $view
* @return mixed
*/
public function view($view = null)
{
return $this->fluentlyGetOrSet('view')->value($view);
}
/**
* Get or set nav item order.
*
* @param int|null $order
* @return mixed
*/
public function order($order = null)
{
return $this->fluentlyGetOrSet('order')->value($order);
}
/**
* Get or set hidden status.
*
* @param bool|null $hidden
* @return mixed
*/
public function hidden($hidden = null)
{
return $this->fluentlyGetOrSet('hidden')
->getter(function ($value) {
return $value ?? false;
})
->value($hidden);
}
/**
* Get whether the nav item is to be hidden, but still made available for nav builder UI.
*
* @return bool
*/
public function isHidden()
{
return $this->hidden();
}
/**
* Get or set preferences manipulations.
*
* @param string|null $manipulations
* @return mixed
*/
public function manipulations($manipulations = null)
{
return $this->fluentlyGetOrSet('manipulations')->value($manipulations);
}
/**
* Sync original state.
*
* @return $this
*/
public function syncOriginal()
{
$this->original = null; // Clear original property so it can never appear in cloned instance.
$this->original = clone $this;
return $this;
}
/**
* Get original state.
*
* @return mixed
*/
public function original()
{
return $this->original;
}
/**
* Alias for `display()`, left here for backwards compatibility.
*
* @param string|null $name
* @return mixed
*/
public function name(...$arguments)
{
return $this->display(...$arguments);
}
/**
* Transform nav item and associated children to valid command palette `Link` instances.
*/
public function commandPaletteLinks(?NavItem $parentItem = null): array
{
$displayItem = $parentItem ?? $this;
$sectionText = $displayItem->section() !== 'Top Level'
? __($displayItem->section())
: null;
$itemText = __($displayItem->display());
$childText = $parentItem
? __($this->display())
: null;
$text = collect([$sectionText, $itemText, $childText])
->filter()
->values()
->all();
$link = (new Link(text: $text, category: Category::Navigation))
->url($this->url())
->icon($this->icon());
if ($children = $this->resolveChildren()->children()) {
$childLinks = $children->flatMap(fn ($child) => $child->commandPaletteLinks($this));
}
return collect([$link])
->merge($childLinks ?? [])
->all();
}
/**
* Convert to snake case.
*
* @param string $string
* @return string
*/
public static function snakeCase($string)
{
// Preserve colons `:` segments for child items and cloned ids.
$string = Str::replace(':', '___colon___', $string);
// Convert to lowercase and slug, removing all special characters.
$string = Str::modifyMultiple($string, ['lower', 'slug']);
// Convert to snake case.
$string = Str::replace('-', '_', $string);
// Put colons `:` back for child items and cloned ids.
$string = Str::replace('___colon___', ':', $string);
return $string;
}
}