This commit is contained in:
MeghdadFadaee committed 2026-09-12 15:31:13 +03:30
commit d99df1ab95
27 files changed
+1035

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.{json,js,css,yml,yaml}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false
+10
View File
@@ -0,0 +1,10 @@
/CONTRIBUTING.md export-ignore
/SECURITY.md export-ignore
/tests export-ignore
/tests-js export-ignore
/.github export-ignore
/phpunit.xml export-ignore
/webpack.mix.js export-ignore
/package.json export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
+98
View File
@@ -0,0 +1,98 @@
name: Tests
on:
push:
pull_request:
permissions:
contents: read
jobs:
public-checks:
name: Public checks
runs-on: ubuntu-latest
steps:
- name: Check out the repository
uses: actions/checkout@v4
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
coverage: none
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Validate Composer metadata
run: composer validate --strict
- name: Run JavaScript tests
run: npm test
nova-integration:
name: Nova integration
runs-on: ubuntu-latest
steps:
- name: Check out the repository
uses: actions/checkout@v4
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
coverage: none
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Detect Nova credentials
id: nova
shell: bash
env:
NOVA_USERNAME: ${{ secrets.NOVA_USERNAME }}
NOVA_LICENSE_KEY: ${{ secrets.NOVA_LICENSE_KEY }}
run: |
if [[ -n "$NOVA_USERNAME" && -n "$NOVA_LICENSE_KEY" ]]; then
echo "available=true" >> "$GITHUB_OUTPUT"
else
echo "available=false" >> "$GITHUB_OUTPUT"
echo "::notice::Nova integration checks require NOVA_USERNAME and NOVA_LICENSE_KEY repository secrets."
fi
- name: Configure Nova authentication
if: steps.nova.outputs.available == 'true'
env:
NOVA_USERNAME: ${{ secrets.NOVA_USERNAME }}
NOVA_LICENSE_KEY: ${{ secrets.NOVA_LICENSE_KEY }}
run: composer config http-basic.nova.laravel.com "$NOVA_USERNAME" "$NOVA_LICENSE_KEY"
- name: Install Composer dependencies
if: steps.nova.outputs.available == 'true'
run: composer install --no-interaction --prefer-dist --no-progress
- name: Install frontend dependencies
if: steps.nova.outputs.available == 'true'
run: npm install --no-audit --no-fund
- name: Run PHP tests
if: steps.nova.outputs.available == 'true'
run: composer test
- name: Check PHP formatting
if: steps.nova.outputs.available == 'true'
run: vendor/bin/pint --test
- name: Build production assets
if: steps.nova.outputs.available == 'true'
run: npm run production
- name: Verify committed assets
if: steps.nova.outputs.available == 'true'
run: git diff --exit-code -- dist
+13
View File
@@ -0,0 +1,13 @@
/node_modules
/vendor
/.env
/.env.*
/auth.json
/.composer
/.phpunit.cache
/.phpunit.result.cache
/.idea
composer.lock
npm-debug.log
yarn-error.log
.DS_Store
+15
View File
@@ -0,0 +1,15 @@
# Changelog
All notable changes to Nova Menu Search will be documented in this file.
## Unreleased
## 1.0.0 - 2026-09-12
- Add sidebar search for authorized Nova main-menu links.
- Add nested menu breadcrumb matching.
- Add internal SPA and external-link navigation.
- Add desktop, responsive, dark-mode, RTL, and keyboard support.
- Add Persian and Arabic search normalization.
- Add English and Persian translations.
- Add publishable configuration.
+31
View File
@@ -0,0 +1,31 @@
# Contributing
Thank you for considering a contribution to Nova Menu Search.
## Development setup
This package requires access to Laravel Nova. Use Composer authentication configured outside the repository. Never commit Nova credentials, `auth.json`, `.env` files, or vendor sources.
Install dependencies and run the verification commands:
```bash
composer install
npm install
composer test
npm test
npm run production
vendor/bin/pint --test
```
Production assets under `dist/` must be rebuilt and included whenever frontend source changes.
## Pull requests
- Keep changes focused and backward compatible where practical.
- Add or update tests for changed behavior.
- Update `CHANGELOG.md` under `Unreleased` for user-facing changes.
- Update the README when a public contract, configuration option, or setup step changes.
- Do not index data beyond the authorized menu state supplied by Nova.
- Do not execute state-changing menu actions from search results.
For security vulnerabilities, follow [SECURITY.md](SECURITY.md) instead of opening a public issue.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Meghdad Fadaee
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+92
View File
@@ -0,0 +1,92 @@
# Nova Menu Search
[![Latest Version on Packagist](https://img.shields.io/packagist/v/meghdadfadaee/nova-menu-search.svg?style=flat-square)](https://packagist.org/packages/meghdadfadaee/nova-menu-search)
[![Total Downloads](https://img.shields.io/packagist/dt/meghdadfadaee/nova-menu-search.svg?style=flat-square)](https://packagist.org/packages/meghdadfadaee/nova-menu-search)
[![License](https://img.shields.io/packagist/l/meghdadfadaee/nova-menu-search.svg?style=flat-square)](LICENSE.md)
Search and navigate the authorized items in a Laravel Nova 5 main menu directly from the sidebar.
## Features
- Works with Nova's default or customized main menu.
- Supports nested menu sections and groups with breadcrumb context.
- Uses Nova's SPA navigation for internal links.
- Supports external GET links and their configured targets.
- Excludes state-changing menu actions such as POST and DELETE links.
- Searches only menu items already authorized and supplied by Nova.
- Handles desktop and responsive sidebars.
- Supports dark mode, RTL layouts, and keyboard access.
- Normalizes common Persian and Arabic character variants.
- Ships with English and Persian translations.
- Requires no migrations, routes, or application-side registration.
## Requirements
- PHP 8.1+
- Laravel 10–13
- Laravel Nova 5.8+
## Installation
This package requires an existing licensed Nova installation. Configure Composer authentication for Nova through Nova's documented mechanism; never commit `auth.json` or credentials. Then install the package:
```bash
composer require meghdadfadaee/nova-menu-search
```
Laravel discovers the service provider automatically. Refresh Nova and use the search field above the main menu. Press `Ctrl+K` on Windows/Linux or `Command+K` on macOS to focus it.
The compiled assets under `dist/` are included in releases, so consuming applications do not need Node.js or an additional build step.
## Configuration
The defaults work without publishing configuration. To customize them:
```bash
php artisan vendor:publish --tag=nova-menu-search-config
```
The published `config/nova-menu-search.php` contains:
```php
return [
'enabled' => true,
'placeholder' => null,
'no_results' => null,
'shortcut' => 'mod+k',
'max_results' => 10,
];
```
Set `placeholder` or `no_results` to strings to override their translations. Set `shortcut` to `null` to disable the shortcut. Shortcut values use Nova's Mousetrap syntax.
## How searching works
The package reads Nova's client-side `mainMenu` state after authorization has been applied. It recursively indexes navigable GET links and includes ancestor section/group labels in the searchable text. For example, a query such as `content posts` can match a `Posts` item nested below `Content`.
No server-side search endpoint is added, and hidden or unauthorized menu items are never added to the index. Non-GET items are intentionally excluded because selecting a search result should navigate rather than trigger a state-changing action.
## Development
The project requires access to the private Nova Composer repository:
```bash
composer install
npm install
composer test
npm test
npm run production
vendor/bin/pint --test
```
Rebuild and commit `dist/` whenever frontend source changes. The GitHub Actions workflow always runs credential-free JavaScript and Composer metadata checks. Add `NOVA_USERNAME` and `NOVA_LICENSE_KEY` repository secrets to enable the full PHP integration and production-build checks.
Please see [CONTRIBUTING.md](CONTRIBUTING.md) before submitting a change. Report vulnerabilities according to [SECURITY.md](SECURITY.md), not through a public issue.
## Changelog
Please see [CHANGELOG.md](CHANGELOG.md) for release history.
## License
Nova Menu Search is open-sourced software licensed under the [MIT license](LICENSE.md).
+16
View File
@@ -0,0 +1,16 @@
# Security Policy
## Supported versions
| Version | Supported |
|------------------|-----------|
| 1.x | Yes |
| Earlier versions | No |
## Reporting a vulnerability
Please report security vulnerabilities privately through the repository's GitHub Security Advisory feature. Do not disclose the issue publicly until a fix is available.
Include the affected package version, Laravel and Nova versions, reproduction steps, expected behavior, and security impact. Reports will be reviewed as soon as practical, and coordinated disclosure will be arranged when the issue is confirmed.
Never include Nova credentials, application secrets, private menu data, or production session details in a report.
+75
View File
@@ -0,0 +1,75 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "meghdadfadaee/nova-menu-search",
"description": "Search and navigate Laravel Nova main menu items from the sidebar.",
"type": "library",
"keywords": [
"laravel",
"menu",
"navigation",
"nova",
"nova-package",
"search"
],
"homepage": "https://github.com/MeghdadFadaee/nova-menu-search",
"license": "MIT",
"authors": [
{
"name": "Meghdad Fadaee"
}
],
"support": {
"issues": "https://github.com/MeghdadFadaee/nova-menu-search/issues",
"source": "https://github.com/MeghdadFadaee/nova-menu-search"
},
"require": {
"php": "^8.1",
"illuminate/support": "^10.48|^11.44|^12.1|^13.0",
"laravel/nova": "^5.8"
},
"require-dev": {
"laravel/nova-devtool": "^1.9",
"laravel/pint": "^1.20",
"orchestra/testbench-core": "^8.35|^9.12|^10.1|^11.0",
"pestphp/pest": "^2.36|^3.8|^4.0|^5.0",
"pestphp/pest-plugin-laravel": "^2.4|^3.0|^4.0|^5.0"
},
"repositories": [
{
"type": "composer",
"url": "https://nova.laravel.com"
}
],
"autoload": {
"psr-4": {
"MeghdadFadaee\\NovaMenuSearch\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"MeghdadFadaee\\NovaMenuSearch\\Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-main": "1.x-dev"
},
"laravel": {
"providers": [
"MeghdadFadaee\\NovaMenuSearch\\MenuSearchServiceProvider"
]
}
},
"scripts": {
"format": "pint",
"test": "pest"
},
"config": {
"allow-plugins": {
"pestphp/pest-plugin": true
},
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
}
+69
View File
@@ -0,0 +1,69 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Enable Menu Search
|--------------------------------------------------------------------------
|
| This option controls whether the package registers its Nova script and
| stylesheet. Disable it to remove menu search without uninstalling the
| package or deleting its published configuration.
|
*/
'enabled' => true,
/*
|--------------------------------------------------------------------------
| Search Placeholder
|--------------------------------------------------------------------------
|
| This text appears inside the sidebar search field. Leave the value null
| to use the translation supplied by the package for the current locale,
| or provide a string to override it for this application.
|
*/
'placeholder' => null,
/*
|--------------------------------------------------------------------------
| Empty Results Message
|--------------------------------------------------------------------------
|
| This message is displayed when a query does not match any authorized
| menu item. A null value uses the package translation for the current
| application locale.
|
*/
'no_results' => null,
/*
|--------------------------------------------------------------------------
| Keyboard Shortcut
|--------------------------------------------------------------------------
|
| The shortcut focuses the visible menu search field and uses Nova's
| Mousetrap syntax. The "mod" key maps to Command on macOS and Control on
| other platforms. Set this option to null to disable the shortcut.
|
*/
'shortcut' => 'mod+k',
/*
|--------------------------------------------------------------------------
| Maximum Results
|--------------------------------------------------------------------------
|
| This value limits how many matching menu links are shown for each query.
| The package always uses at least one result, even when this value is set
| to zero or a negative number.
|
*/
'max_results' => 10,
];
+1
View File
@@ -0,0 +1 @@
.nova-menu-search{margin-bottom:1rem}.nova-menu-search__field{align-items:center;border:1px solid #d1d5db;border-radius:.5rem;display:flex;min-height:2.5rem;padding-inline:.625rem;transition:border-color .12s ease,box-shadow .12s ease}.nova-menu-search__field:focus-within{border-color:rgb(var(--colors-primary-500,59 130 246));box-shadow:0 0 0 3px rgb(var(--colors-primary-500,59 130 246)/.18)}.nova-menu-search__icon{color:#6b7280;flex:none;font-size:1.25rem;line-height:1}.nova-menu-search__input{background:transparent;border:0;color:inherit;flex:1;font:inherit;min-width:0;outline:none;padding:.5rem}.nova-menu-search__input::-webkit-search-cancel-button{cursor:pointer}.nova-menu-search__shortcut{background:#f3f4f6;border:1px solid #e5e7eb;border-radius:.25rem;color:#6b7280;flex:none;font-family:inherit;font-size:.6875rem;line-height:1;padding:.25rem}.nova-menu-search__results{display:none;margin-top:.5rem}.nova-menu-search[data-active=true] .nova-menu-search__results{display:grid;gap:.25rem}.nova-menu-search[data-active=true]+.sidebar-menu{display:none}.nova-menu-search__result{border-radius:.375rem;color:#4b5563;display:flex;flex-direction:column;gap:.125rem;padding:.5rem .625rem;text-decoration:none}.nova-menu-search__result:focus,.nova-menu-search__result:hover{background:#e5e7eb;outline:none}.nova-menu-search__result-name{font-size:.875rem;font-weight:600}.nova-menu-search__result-trail{color:#6b7280;font-size:.6875rem}.nova-menu-search__empty{color:#6b7280;font-size:.8125rem;margin:0;padding:.75rem .625rem;text-align:center}.dark .nova-menu-search__field{border-color:#4b5563}.dark .nova-menu-search__shortcut{background:#1f2937;border-color:#4b5563;color:#9ca3af}.dark .nova-menu-search__result{color:#9ca3af}.dark .nova-menu-search__result:focus,.dark .nova-menu-search__result:hover{background:#1f2937}.dark .nova-menu-search__empty,.dark .nova-menu-search__result-trail{color:#6b7280}
+1
View File
@@ -0,0 +1 @@
(()=>{"use strict";var e,t={958(){function e(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,r){if(e){if("string"==typeof e)return t(e,r);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t(e,r):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var r={ك:"ک",ي:"ی",ى:"ی",ة:"ه",ۀ:"ه"};function n(e){return String(null!=e?e:"").normalize("NFKD").replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g,"").replace(/\u0640/g,"").replace(/[\u200C\u200D]/g," ").replace(/[كيىةۀ]/g,function(e){return r[e]}).toLocaleLowerCase().replace(/\s+/g," ").trim()}function a(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return(Array.isArray(t)?t:[]).flatMap(function(t){var o,u,i,l=String(null!==(o=null==t?void 0:t.name)&&void 0!==o?o:"").trim(),c=""===l?r:[].concat(e(r),[l]),s=String(null!==(u=null==t?void 0:t.method)&&void 0!==u?u:"GET").toUpperCase(),f=null!=t&&t.path&&"GET"===s?[{name:l,path:t.path,external:!0===t.external,target:null!==(i=t.target)&&void 0!==i?i:null,trail:c,searchableText:n(c.join(" "))}]:[];return[].concat(f,e(a(null==t?void 0:t.items,c)))})}function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}function u(e){return function(e){if(Array.isArray(e))return i(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return i(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function l(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function c(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?l(Object(r),!0).forEach(function(t){s(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):l(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function s(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=o(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=o(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==o(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Nova.booted(function(e,t){var r,o=c({label:"Search main menu",placeholder:"Search menu…",noResults:"No menu items found.",shortcut:"mod+k",maxResults:10},null!==(r=Nova.config("novaMenuSearch"))&&void 0!==r?r:{}),i=new Map,l=function(){return a(t.getters.mainMenu)},s=function(e){var t=e.input.value,r=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,a=n(t).split(" ").filter(Boolean);if(0===a.length)return[];var o=new Set;return e.filter(function(e){return a.every(function(t){return e.searchableText.includes(t)})}).filter(function(e){var t="".concat(e.path,"\0").concat(e.name);return!o.has(t)&&(o.add(t),!0)}).slice(0,Math.max(1,Number(r)||10))}(l(),t,o.maxResults);if(e.root.dataset.active=""===t.trim()?"false":"true",e.results.replaceChildren(),""!==t.trim()){if(0===r.length){var a=document.createElement("p");return a.className="nova-menu-search__empty",a.textContent=o.noResults,void e.results.append(a)}r.forEach(function(t){var r,n=document.createElement("a"),a=document.createElement("span"),o=document.createElement("span");(n.className="nova-menu-search__result",n.href=t.path,o.className="nova-menu-search__result-name",o.textContent=t.name,n.append(o),t.trail.length>1&&(a.className="nova-menu-search__result-trail",a.textContent=t.trail.slice(0,-1).join(" / "),n.append(a)),t.external)?(n.rel="noreferrer noopener",n.target=null!==(r=t.target)&&void 0!==r?r:"_blank"):n.addEveLine truncated
+4
View File
@@ -0,0 +1,4 @@
{
"/js/menu-search.js": "/js/menu-search.js?id=22f00acce6018c95418055e500df2516",
"/css/menu-search.css": "/css/menu-search.css?id=e2199a23537a67d51688b00bb51ad949"
}
+13
View File
@@ -0,0 +1,13 @@
{
"name": "nova-menu-search",
"private": true,
"scripts": {
"dev": "mix",
"watch": "mix watch",
"production": "mix --production",
"test": "node --test tests-js/*.test.js"
},
"devDependencies": {
"laravel-nova-devtool": "file:vendor/laravel/nova-devtool"
}
}
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Nova Menu Search">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
+124
View File
@@ -0,0 +1,124 @@
.nova-menu-search {
margin-bottom: 1rem;
}
.nova-menu-search__field {
align-items: center;
border: 1px solid rgb(209 213 219);
border-radius: 0.5rem;
display: flex;
min-height: 2.5rem;
padding-inline: 0.625rem;
transition: border-color 120ms ease, box-shadow 120ms ease;
}
.nova-menu-search__field:focus-within {
border-color: rgb(var(--colors-primary-500, 59 130 246));
box-shadow: 0 0 0 3px rgb(var(--colors-primary-500, 59 130 246) / 0.18);
}
.nova-menu-search__icon {
color: rgb(107 114 128);
flex: none;
font-size: 1.25rem;
line-height: 1;
}
.nova-menu-search__input {
background: transparent;
border: 0;
color: inherit;
flex: 1;
font: inherit;
min-width: 0;
outline: none;
padding: 0.5rem;
}
.nova-menu-search__input::-webkit-search-cancel-button {
cursor: pointer;
}
.nova-menu-search__shortcut {
background: rgb(243 244 246);
border: 1px solid rgb(229 231 235);
border-radius: 0.25rem;
color: rgb(107 114 128);
flex: none;
font-family: inherit;
font-size: 0.6875rem;
line-height: 1;
padding: 0.25rem;
}
.nova-menu-search__results {
display: none;
margin-top: 0.5rem;
}
.nova-menu-search[data-active='true'] .nova-menu-search__results {
display: grid;
gap: 0.25rem;
}
.nova-menu-search[data-active='true'] + .sidebar-menu {
display: none;
}
.nova-menu-search__result {
border-radius: 0.375rem;
color: rgb(75 85 99);
display: flex;
flex-direction: column;
gap: 0.125rem;
padding: 0.5rem 0.625rem;
text-decoration: none;
}
.nova-menu-search__result:hover,
.nova-menu-search__result:focus {
background: rgb(229 231 235);
outline: none;
}
.nova-menu-search__result-name {
font-size: 0.875rem;
font-weight: 600;
}
.nova-menu-search__result-trail {
color: rgb(107 114 128);
font-size: 0.6875rem;
}
.nova-menu-search__empty {
color: rgb(107 114 128);
font-size: 0.8125rem;
margin: 0;
padding: 0.75rem 0.625rem;
text-align: center;
}
.dark .nova-menu-search__field {
border-color: rgb(75 85 99);
}
.dark .nova-menu-search__shortcut {
background: rgb(31 41 55);
border-color: rgb(75 85 99);
color: rgb(156 163 175);
}
.dark .nova-menu-search__result {
color: rgb(156 163 175);
}
.dark .nova-menu-search__result:hover,
.dark .nova-menu-search__result:focus {
background: rgb(31 41 55);
}
.dark .nova-menu-search__result-trail,
.dark .nova-menu-search__empty {
color: rgb(107 114 128);
}
+162
View File
@@ -0,0 +1,162 @@
import {
collectSearchableItems,
filterSearchableItems,
} from './search'
Nova.booted((_app, store) => {
const configuration = {
label: 'Search main menu',
placeholder: 'Search menu…',
noResults: 'No menu items found.',
shortcut: 'mod+k',
maxResults: 10,
...(Nova.config('novaMenuSearch') ?? {}),
}
const installations = new Map()
const searchableItems = () => collectSearchableItems(store.getters.mainMenu)
const renderResults = (installation) => {
const query = installation.input.value
const results = filterSearchableItems(
searchableItems(),
query,
configuration.maxResults
)
installation.root.dataset.active = query.trim() === '' ? 'false' : 'true'
installation.results.replaceChildren()
if (query.trim() === '') {
return
}
if (results.length === 0) {
const emptyState = document.createElement('p')
emptyState.className = 'nova-menu-search__empty'
emptyState.textContent = configuration.noResults
installation.results.append(emptyState)
return
}
results.forEach(item => {
const link = document.createElement('a')
const trail = document.createElement('span')
const name = document.createElement('span')
link.className = 'nova-menu-search__result'
link.href = item.path
name.className = 'nova-menu-search__result-name'
name.textContent = item.name
link.append(name)
if (item.trail.length > 1) {
trail.className = 'nova-menu-search__result-trail'
trail.textContent = item.trail.slice(0, -1).join(' / ')
link.append(trail)
}
if (item.external) {
link.rel = 'noreferrer noopener'
link.target = item.target ?? '_blank'
} else {
link.addEventListener('click', event => {
event.preventDefault()
installation.input.value = ''
renderResults(installation)
Nova.visit(item.path)
})
}
installation.results.append(link)
})
}
const install = (menu) => {
if (installations.has(menu)) {
return
}
const root = document.createElement('div')
const field = document.createElement('div')
const icon = document.createElement('span')
const input = document.createElement('input')
const shortcut = document.createElement('kbd')
const results = document.createElement('div')
root.className = 'nova-menu-search'
root.dataset.active = 'false'
field.className = 'nova-menu-search__field'
icon.className = 'nova-menu-search__icon'
icon.setAttribute('aria-hidden', 'true')
icon.textContent = '⌕'
input.className = 'nova-menu-search__input'
input.type = 'search'
input.autocomplete = 'off'
input.spellcheck = false
input.placeholder = configuration.placeholder
input.setAttribute('aria-label', configuration.label)
results.className = 'nova-menu-search__results'
results.setAttribute('aria-live', 'polite')
if (configuration.shortcut) {
shortcut.className = 'nova-menu-search__shortcut'
shortcut.textContent = configuration.shortcut
.replace('mod', navigator.platform.includes('Mac') ? '⌘' : 'Ctrl')
.replace('+', ' ')
field.append(icon, input, shortcut)
} else {
field.append(icon, input)
}
root.append(field, results)
menu.before(root)
const installation = { root, input, results }
const stopWatching = store.watch(
() => store.getters.mainMenu,
() => renderResults(installation),
{ deep: true }
)
input.addEventListener('input', () => renderResults(installation))
input.addEventListener('keydown', event => {
if (event.key === 'Escape') {
input.value = ''
renderResults(installation)
input.blur()
}
})
installations.set(menu, { ...installation, stopWatching })
}
const scan = () => {
installations.forEach((installation, menu) => {
if (! menu.isConnected) {
installation.stopWatching()
installations.delete(menu)
}
})
document.querySelectorAll('.sidebar-menu').forEach(install)
}
const observer = new MutationObserver(scan)
observer.observe(document.body, { childList: true, subtree: true })
scan()
if (configuration.shortcut) {
Nova.addShortcut(configuration.shortcut, event => {
const visibleInput = [...installations.values()]
.map(installation => installation.input)
.find(input => input.offsetParent !== null)
if (visibleInput) {
event?.preventDefault()
visibleInput.focus()
}
})
}
})
+67
View File
@@ -0,0 +1,67 @@
const ARABIC_CHARACTER_EQUIVALENTS = {
ك: 'ک',
ي: 'ی',
ى: 'ی',
ة: 'ه',
ۀ: 'ه',
}
export function normalizeForSearch(value) {
return String(value ?? '')
.normalize('NFKD')
.replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '')
.replace(/\u0640/g, '')
.replace(/[\u200C\u200D]/g, ' ')
.replace(/[كيىةۀ]/g, character => ARABIC_CHARACTER_EQUIVALENTS[character])
.toLocaleLowerCase()
.replace(/\s+/g, ' ')
.trim()
}
export function collectSearchableItems(menuItems, ancestors = []) {
return (Array.isArray(menuItems) ? menuItems : []).flatMap(item => {
const name = String(item?.name ?? '').trim()
const trail = name === '' ? ancestors : [...ancestors, name]
const method = String(item?.method ?? 'GET').toUpperCase()
const current = item?.path && method === 'GET'
? [{
name,
path: item.path,
external: item.external === true,
target: item.target ?? null,
trail,
searchableText: normalizeForSearch(trail.join(' ')),
}]
: []
return [
...current,
...collectSearchableItems(item?.items, trail),
]
})
}
export function filterSearchableItems(items, query, maximumResults = 10) {
const terms = normalizeForSearch(query).split(' ').filter(Boolean)
if (terms.length === 0) {
return []
}
const seen = new Set()
return items
.filter(item => terms.every(term => item.searchableText.includes(term)))
.filter(item => {
const key = `${item.path}\u0000${item.name}`
if (seen.has(key)) {
return false
}
seen.add(key)
return true
})
.slice(0, Math.max(1, Number(maximumResults) || 10))
}
+7
View File
@@ -0,0 +1,7 @@
<?php
return [
'label' => 'Search main menu',
'placeholder' => 'Search menu…',
'no_results' => 'No menu items found.',
];
+7
View File
@@ -0,0 +1,7 @@
<?php
return [
'label' => 'جستجوی منوی اصلی',
'placeholder' => 'جستجو در منو…',
'no_results' => 'موردی در منو پیدا نشد.',
];
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace MeghdadFadaee\NovaMenuSearch;
use Illuminate\Support\ServiceProvider;
use Laravel\Nova\Events\ServingNova;
use Laravel\Nova\Nova;
class MenuSearchServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'nova-menu-search');
$this->publishes([
__DIR__.'/../config/nova-menu-search.php' => config_path('nova-menu-search.php'),
], 'nova-menu-search-config');
Nova::serving(function (ServingNova $event): void {
if (! config('nova-menu-search.enabled', true)) {
return;
}
Nova::script('nova-menu-search', __DIR__.'/../dist/js/menu-search.js');
Nova::style('nova-menu-search', __DIR__.'/../dist/css/menu-search.css');
Nova::provideToScript([
'novaMenuSearch' => [
'label' => trans('nova-menu-search::menu-search.label'),
'placeholder' => config('nova-menu-search.placeholder')
?: trans('nova-menu-search::menu-search.placeholder'),
'noResults' => config('nova-menu-search.no_results')
?: trans('nova-menu-search::menu-search.no_results'),
'shortcut' => config('nova-menu-search.shortcut', 'mod+k'),
'maxResults' => max(1, (int) config('nova-menu-search.max_results', 10)),
],
]);
});
}
public function register(): void
{
$this->mergeConfigFrom(__DIR__.'/../config/nova-menu-search.php', 'nova-menu-search');
}
}
+69
View File
@@ -0,0 +1,69 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
collectSearchableItems,
filterSearchableItems,
normalizeForSearch,
} from '../resources/js/search.js'
test('normalizes Arabic variants and diacritics for Persian searches', () => {
assert.equal(normalizeForSearch('كِتاب‌هاي ي'), 'کتاب های ی')
})
test('collects authorized navigable items with their menu trail', () => {
const menu = [
{
name: 'Content',
items: [
{ name: 'Posts', path: '/resources/posts' },
{ name: 'Run Import', path: '/imports', method: 'POST' },
],
},
]
assert.deepEqual(collectSearchableItems(menu), [
{
name: 'Posts',
path: '/resources/posts',
external: false,
target: null,
trail: ['Content', 'Posts'],
searchableText: 'content posts',
},
])
})
test('matches every query term across item names and ancestors', () => {
const items = collectSearchableItems([
{
name: 'Content',
items: [
{ name: 'Posts', path: '/resources/posts' },
{ name: 'Pages', path: '/resources/pages' },
],
},
{
name: 'Sales',
items: [{ name: 'Orders', path: '/resources/orders' }],
},
])
assert.deepEqual(
filterSearchableItems(items, 'content posts').map(item => item.name),
['Posts']
)
})
test('deduplicates links and respects the configured result limit', () => {
const items = collectSearchableItems([
{ name: 'Users', path: '/resources/users' },
{ name: 'Users', path: '/resources/users' },
{ name: 'User Roles', path: '/resources/roles' },
])
assert.deepEqual(
filterSearchableItems(items, 'user', 1).map(item => item.path),
['/resources/users']
)
})
@@ -0,0 +1,32 @@
<?php
use Laravel\Nova\Events\ServingNova;
use Laravel\Nova\Nova;
beforeEach(function (): void {
Nova::$scripts = [];
Nova::$styles = [];
});
it('registers its assets and localized configuration while serving Nova', function (): void {
ServingNova::dispatch($this->app, request());
expect(Nova::allScripts())->toHaveCount(1)
->and(Nova::allStyles())->toHaveCount(1)
->and(Nova::jsonVariables(request())['novaMenuSearch'])->toMatchArray([
'label' => 'Search main menu',
'placeholder' => 'Search menu…',
'noResults' => 'No menu items found.',
'shortcut' => 'mod+k',
'maxResults' => 10,
]);
});
it('does not register assets when menu search is disabled', function (): void {
config()->set('nova-menu-search.enabled', false);
ServingNova::dispatch($this->app, request());
expect(Nova::allScripts())->toBeEmpty()
->and(Nova::allStyles())->toBeEmpty();
});
+5
View File
@@ -0,0 +1,5 @@
<?php
use MeghdadFadaee\NovaMenuSearch\Tests\TestCase;
uses(TestCase::class)->in('Feature');
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace MeghdadFadaee\NovaMenuSearch\Tests;
use Laravel\Nova\NovaCoreServiceProvider;
use MeghdadFadaee\NovaMenuSearch\MenuSearchServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;
abstract class TestCase extends Orchestra
{
/**
* @return array<int, class-string>
*/
protected function getPackageProviders($app): array
{
return [
NovaCoreServiceProvider::class,
MenuSearchServiceProvider::class,
];
}
}
+11
View File
@@ -0,0 +1,11 @@
const mix = require('laravel-mix')
const NovaExtension = require('laravel-nova-devtool')
mix.extend('nova', new NovaExtension())
mix
.setPublicPath('dist')
.js('resources/js/menu-search.js', 'js')
.css('resources/css/menu-search.css', 'css')
.nova('meghdadfadaee/nova-menu-search')
.version()