Skip to content

Commit 46786b7

Browse files
fix(item): active menu item on child route
1 parent 3f067b0 commit 46786b7

File tree

1 file changed

+41
-14
lines changed

1 file changed

+41
-14
lines changed

src/Item.php

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class Item implements Arrayable
3434
'route' => null,
3535
'title' => '',
3636
'type' => 'link', // link | divider | header
37-
'url' => null,
37+
'url' => '#',
3838
];
3939

4040
/**
@@ -144,7 +144,7 @@ public function fill($properties): Item
144144
*/
145145
public function getAttributes($except = null)
146146
{
147-
return $this->htmlAttributes(Arr::except($this->attributes, $except));
147+
return $this->htmlAttributes(Arr::except($this->properties['attributes'], $except));
148148
}
149149

150150
/**
@@ -156,6 +156,7 @@ public function getUrl(): string
156156
if (is_array($this->route)) {
157157
return URL::route(Arr::get($this->route, 0), Arr::get($this->route, 1, []));
158158
}
159+
159160
if (is_string($this->route)) {
160161
return URL::route($this->route);
161162
}
@@ -169,7 +170,7 @@ public function getUrl(): string
169170
return URL::to($this->url, [], true);
170171
}
171172

172-
return '';
173+
return '#';
173174
}
174175

175176
/**
@@ -194,22 +195,48 @@ public function hasIcon(): bool
194195
*/
195196
public function isActive()
196197
{
197-
if ($this->route) {
198-
if (is_array($this->route)) {
199-
return Route::is(Arr::get($this->route, 0));
200-
}
201-
if (is_string($this->route)) {
202-
return Route::is($this->route);
198+
// Check if one of the children is active
199+
foreach ($this->children() as $child) {
200+
if ($child->isActive()) {
201+
return true;
203202
}
204203
}
205204

206-
if ($this->url) {
207-
return Request::is($this->url);
205+
// Custom set active path
206+
if ($path = $this->getActiveWhen()) {
207+
return Request::is($path);
208208
}
209209

210-
return $this->children()->contains(function ($child) {
211-
return $child->isActive();
212-
}) ?? false;
210+
$path = ltrim(str_replace(url('/'), '', $this->getUrl()), '/');
211+
return Request::is(
212+
$path,
213+
$path . '/*'
214+
);
215+
}
216+
217+
/**
218+
* @param string $path
219+
*
220+
* @return $this
221+
*/
222+
public function isActiveWhen($path)
223+
{
224+
// Remove unwanted chars
225+
$path = ltrim($path, '/');
226+
$path = rtrim($path, '/');
227+
$path = rtrim($path, '?');
228+
229+
$this->activeWhen = $path;
230+
231+
return $this;
232+
}
233+
234+
/**
235+
* @return string
236+
*/
237+
public function getActiveWhen()
238+
{
239+
return $this->activeWhen;
213240
}
214241

215242
/**

0 commit comments

Comments
 (0)