From d99df1ab95e1ca4e55645b41d08f55f5458ea6c3 Mon Sep 17 00:00:00 2001 From: MeghdadFadaee Date: Sat, 12 Sep 2026 15:31:13 +0330 Subject: [PATCH] init --- .editorconfig | 15 ++ .gitattributes | 10 ++ .github/workflows/tests.yml | 98 +++++++++++ .gitignore | 13 ++ CHANGELOG.md | 15 ++ CONTRIBUTING.md | 31 ++++ LICENSE.md | 21 +++ README.md | 92 ++++++++++ SECURITY.md | 16 ++ composer.json | 75 ++++++++ config/nova-menu-search.php | 69 ++++++++ dist/css/menu-search.css | 1 + dist/js/menu-search.js | 1 + dist/mix-manifest.json | 4 + package.json | 13 ++ phpunit.xml | 12 ++ resources/css/menu-search.css | 124 ++++++++++++++ resources/js/menu-search.js | 162 ++++++++++++++++++ resources/js/search.js | 67 ++++++++ resources/lang/en/menu-search.php | 7 + resources/lang/fa/menu-search.php | 7 + src/MenuSearchServiceProvider.php | 44 +++++ tests-js/search.test.js | 69 ++++++++ .../Feature/MenuSearchServiceProviderTest.php | 32 ++++ tests/Pest.php | 5 + tests/TestCase.php | 21 +++ webpack.mix.js | 11 ++ 27 files changed, 1035 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/workflows/tests.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 composer.json create mode 100644 config/nova-menu-search.php create mode 100644 dist/css/menu-search.css create mode 100644 dist/js/menu-search.js create mode 100644 dist/mix-manifest.json create mode 100644 package.json create mode 100644 phpunit.xml create mode 100644 resources/css/menu-search.css create mode 100644 resources/js/menu-search.js create mode 100644 resources/js/search.js create mode 100644 resources/lang/en/menu-search.php create mode 100644 resources/lang/fa/menu-search.php create mode 100644 src/MenuSearchServiceProvider.php create mode 100644 tests-js/search.test.js create mode 100644 tests/Feature/MenuSearchServiceProviderTest.php create mode 100644 tests/Pest.php create mode 100644 tests/TestCase.php create mode 100644 webpack.mix.js diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..22452bd --- /dev/null +++ b/.editorconfig @@ -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 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..69ff138 --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..13c1b71 --- /dev/null +++ b/.github/workflows/tests.yml @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bba714e --- /dev/null +++ b/.gitignore @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fca34c2 --- /dev/null +++ b/CHANGELOG.md @@ -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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..8823392 --- /dev/null +++ b/CONTRIBUTING.md @@ -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. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..59f8ffb --- /dev/null +++ b/LICENSE.md @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fbf9303 --- /dev/null +++ b/README.md @@ -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). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..5f1f831 --- /dev/null +++ b/SECURITY.md @@ -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. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..cc18400 --- /dev/null +++ b/composer.json @@ -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 +} diff --git a/config/nova-menu-search.php b/config/nova-menu-search.php new file mode 100644 index 0000000..8f7187c --- /dev/null +++ b/config/nova-menu-search.php @@ -0,0 +1,69 @@ + 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, +]; diff --git a/dist/css/menu-search.css b/dist/css/menu-search.css new file mode 100644 index 0000000..5a6341f --- /dev/null +++ b/dist/css/menu-search.css @@ -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} diff --git a/dist/js/menu-search.js b/dist/js/menu-search.js new file mode 100644 index 0000000..3531e43 --- /dev/null +++ b/dist/js/menu-search.js @@ -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);r1&&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);r2&&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.addEventListener("click",function(r){r.preventDefault(),e.input.value="",s(e),Nova.visit(t.path)});e.results.append(n)})}},f=function(e){if(!i.has(e)){var r=document.createElement("div"),n=document.createElement("div"),a=document.createElement("span"),u=document.createElement("input"),l=document.createElement("kbd"),f=document.createElement("div");r.className="nova-menu-search",r.dataset.active="false",n.className="nova-menu-search__field",a.className="nova-menu-search__icon",a.setAttribute("aria-hidden","true"),a.textContent="⌕",u.className="nova-menu-search__input",u.type="search",u.autocomplete="off",u.spellcheck=!1,u.placeholder=o.placeholder,u.setAttribute("aria-label",o.label),f.className="nova-menu-search__results",f.setAttribute("aria-live","polite"),o.shortcut?(l.className="nova-menu-search__shortcut",l.textContent=o.shortcut.replace("mod",navigator.platform.includes("Mac")?"⌘":"Ctrl").replace("+"," "),n.append(a,u,l)):n.append(a,u),r.append(n,f),e.before(r);var m={root:r,input:u,results:f},p=t.watch(function(){return t.getters.mainMenu},function(){return s(m)},{deep:!0});u.addEventListener("input",function(){return s(m)}),u.addEventListener("keydown",function(e){"Escape"===e.key&&(u.value="",s(m),u.blur())}),i.set(e,c(c({},m),{},{stopWatching:p}))}},m=function(){i.forEach(function(e,t){t.isConnected||(e.stopWatching(),i.delete(t))}),document.querySelectorAll(".sidebar-menu").forEach(f)};new MutationObserver(m).observe(document.body,{childList:!0,subtree:!0}),m(),o.shortcut&&Nova.addShortcut(o.shortcut,function(e){var t=u(i.values()).map(function(e){return e.input}).find(function(e){return null!==e.offsetParent});t&&(null==e||e.preventDefault(),t.focus())})})},86(){}},r={};function n(e){var a=r[e];if(void 0!==a)return a.exports;var o=r[e]={exports:{}};return t[e](o,o.exports,n),o.exports}n.m=t,e=[],n.O=(t,r,a,o)=>{if(!r){var u=1/0;for(s=0;s=o)&&Object.keys(n.O).every(e=>n.O[e](r[l]))?r.splice(l--,1):(i=!1,o0&&e[s-1][2]>o;s--)e[s]=e[s-1];e[s]=[r,a,o]},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={864:0,507:0};n.O.j=t=>0===e[t];var t=(t,r)=>{var a,o,[u,i,l]=r,c=0;if(u.some(t=>0!==e[t])){for(a in i)n.o(i,a)&&(n.m[a]=i[a]);if(l)var s=l(n)}for(t&&t(r);cn(958));var a=n.O(void 0,[507],()=>n(86));a=n.O(a)})(); \ No newline at end of file diff --git a/dist/mix-manifest.json b/dist/mix-manifest.json new file mode 100644 index 0000000..7c4a06e --- /dev/null +++ b/dist/mix-manifest.json @@ -0,0 +1,4 @@ +{ + "/js/menu-search.js": "/js/menu-search.js?id=22f00acce6018c95418055e500df2516", + "/css/menu-search.css": "/css/menu-search.css?id=e2199a23537a67d51688b00bb51ad949" +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..8456325 --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..e801681 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,12 @@ + + + + + tests + + + diff --git a/resources/css/menu-search.css b/resources/css/menu-search.css new file mode 100644 index 0000000..dbcba22 --- /dev/null +++ b/resources/css/menu-search.css @@ -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); +} diff --git a/resources/js/menu-search.js b/resources/js/menu-search.js new file mode 100644 index 0000000..089c5cf --- /dev/null +++ b/resources/js/menu-search.js @@ -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() + } + }) + } +}) diff --git a/resources/js/search.js b/resources/js/search.js new file mode 100644 index 0000000..5a8e779 --- /dev/null +++ b/resources/js/search.js @@ -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)) +} diff --git a/resources/lang/en/menu-search.php b/resources/lang/en/menu-search.php new file mode 100644 index 0000000..1e86b80 --- /dev/null +++ b/resources/lang/en/menu-search.php @@ -0,0 +1,7 @@ + 'Search main menu', + 'placeholder' => 'Search menu…', + 'no_results' => 'No menu items found.', +]; diff --git a/resources/lang/fa/menu-search.php b/resources/lang/fa/menu-search.php new file mode 100644 index 0000000..5eda490 --- /dev/null +++ b/resources/lang/fa/menu-search.php @@ -0,0 +1,7 @@ + 'جستجوی منوی اصلی', + 'placeholder' => 'جستجو در منو…', + 'no_results' => 'موردی در منو پیدا نشد.', +]; diff --git a/src/MenuSearchServiceProvider.php b/src/MenuSearchServiceProvider.php new file mode 100644 index 0000000..a929c1a --- /dev/null +++ b/src/MenuSearchServiceProvider.php @@ -0,0 +1,44 @@ +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'); + } +} diff --git a/tests-js/search.test.js b/tests-js/search.test.js new file mode 100644 index 0000000..48072f4 --- /dev/null +++ b/tests-js/search.test.js @@ -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'] + ) +}) diff --git a/tests/Feature/MenuSearchServiceProviderTest.php b/tests/Feature/MenuSearchServiceProviderTest.php new file mode 100644 index 0000000..e44d006 --- /dev/null +++ b/tests/Feature/MenuSearchServiceProviderTest.php @@ -0,0 +1,32 @@ +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(); +}); diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..c313320 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,5 @@ +in('Feature'); diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..092f988 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,21 @@ + + */ + protected function getPackageProviders($app): array + { + return [ + NovaCoreServiceProvider::class, + MenuSearchServiceProvider::class, + ]; + } +} diff --git a/webpack.mix.js b/webpack.mix.js new file mode 100644 index 0000000..daa175e --- /dev/null +++ b/webpack.mix.js @@ -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()