From 2a1fddb65a01247f1f142ab154eea69894fb29a6 Mon Sep 17 00:00:00 2001 From: MeghdadFadaee Date: Tue, 15 Sep 2026 16:36:25 +0330 Subject: [PATCH] init --- .editorconfig | 15 ++ .gitattributes | 11 + .github/workflows/tests.yml | 84 +++++++ .gitignore | 7 + CHANGELOG.md | 21 ++ CONTRIBUTING.md | 30 +++ LICENSE.md | 21 ++ README.md | 83 +++++++ SECURITY.md | 12 + composer.json | 54 +++++ config/nova-form-dock.php | 123 +++++++++++ dist/css/form-dock.css | 179 +++++++++++++++ dist/js/form-dock.js | 332 ++++++++++++++++++++++++++++ phpunit.xml.dist | 17 ++ src/NovaFormDockServiceProvider.php | 36 +++ tests/AssetRegistrationTest.php | 29 +++ tests/ConfigurationTest.php | 16 ++ tests/TestCase.php | 19 ++ tests/bootstrap.php | 13 ++ 19 files changed, 1102 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-form-dock.php create mode 100644 dist/css/form-dock.css create mode 100644 dist/js/form-dock.js create mode 100644 phpunit.xml.dist create mode 100644 src/NovaFormDockServiceProvider.php create mode 100644 tests/AssetRegistrationTest.php create mode 100644 tests/ConfigurationTest.php create mode 100644 tests/TestCase.php create mode 100644 tests/bootstrap.php diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..bec56c4 --- /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 + +[*.md] +trim_trailing_whitespace = false + +[*.{json,yml,yaml}] +indent_size = 2 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..af56402 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +/.github export-ignore +/tests export-ignore +/.agents export-ignore +/.codex export-ignore +/.idea export-ignore +/.phpunit.cache export-ignore +/.phpunit.result.cache export-ignore +composer.lock export-ignore +/.editorconfig export-ignore +/.gitattributes export-ignore +/phpunit.xml.dist export-ignore diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..d3780d8 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,84 @@ +name: Tests + +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + metadata: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.4' + coverage: none + + - name: Validate Composer metadata + run: composer validate --strict --no-check-publish + + - name: Check JavaScript syntax + run: node --check dist/js/form-dock.js + + nova-credentials: + runs-on: ubuntu-latest + outputs: + available: ${{ steps.credentials.outputs.available }} + + steps: + - name: Check Nova credentials + id: credentials + 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 "Nova credentials are unavailable; the licensed test matrix will be skipped." + fi + + tests: + needs: nova-credentials + if: needs.nova-credentials.outputs.available == 'true' + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + php: ['8.2', '8.3', '8.4', '8.5'] + + name: PHP ${{ matrix.php }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + + - name: Configure Nova authentication + run: composer config http-basic.nova.laravel.com "${{ secrets.NOVA_USERNAME }}" "${{ secrets.NOVA_LICENSE_KEY }}" + + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + + - name: Check formatting + run: vendor/bin/pint --test + + - name: Run tests + run: composer test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d712c4a --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/vendor/ +/.phpunit.cache/ +/.idea/ +/.agents/ +/.codex/ +composer.lock +/.phpunit.result.cache diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8ab1e82 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +All notable changes to Nova Form Dock will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [1.0.0] - 2026-09-15 + +### Added + +- Adaptive action docks for Nova 5 create and update forms. +- Top, bottom, left, and right dock positions. +- Start, center, and end button alignment. +- Responsive positioning, RTL, dark mode, safe-area, and reduced-motion support. +- Resource and form-type scoping through published configuration. + +[Unreleased]: https://github.com/MeghdadFadaee/nova-form-dock/compare/v1.0.0...HEAD +[1.0.0]: https://github.com/MeghdadFadaee/nova-form-dock/releases/tag/v1.0.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c9bc57c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,30 @@ +# Contributing + +Contributions are welcome through GitHub issues and pull requests. + +## Development + +Laravel Nova is a licensed dependency. Configure Composer authentication for +`nova.laravel.com`, then install the dependencies: + +```bash +composer install +``` + +Run formatting and tests before submitting a pull request: + +```bash +composer format +composer test +``` + +The GitHub Actions test matrix requires repository secrets named +`NOVA_USERNAME` and `NOVA_LICENSE_KEY`. The licensed PHP test matrix runs +automatically whenever both secrets are available and is skipped otherwise, +including for pull requests from forks. Metadata and JavaScript syntax checks +always run. + +Keep changes compatible with the supported PHP, Laravel, and Nova versions in +`composer.json`. Changes to Nova form detection should fail safely when the +expected markup is unavailable and should preserve Nova's original form +buttons and submission behavior. 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..466b2d6 --- /dev/null +++ b/README.md @@ -0,0 +1,83 @@ +# Nova Form Dock + +[![Tests](https://github.com/MeghdadFadaee/nova-form-dock/actions/workflows/tests.yml/badge.svg)](https://github.com/MeghdadFadaee/nova-form-dock/actions/workflows/tests.yml) +[![Latest Version on Packagist](https://img.shields.io/packagist/v/meghdadfadaee/nova-form-dock.svg)](https://packagist.org/packages/meghdadfadaee/nova-form-dock) +[![License](https://img.shields.io/packagist/l/meghdadfadaee/nova-form-dock.svg)](LICENSE.md) + +Nova Form Dock adds an adaptive action dock to long Laravel Nova 5 resource +forms. It keeps Nova's original form buttons and behavior while making those +actions continuously available on long create and update pages. + +## Features + +- Activates only when a form is taller than the viewport by default. +- Supports create and update pages without changing Nova resources. +- Excludes inline relationship modals and attached-resource forms. +- Measures the dock so it never covers the final form fields. +- Follows Nova's content width, including responsive and RTL layouts. +- Supports top, bottom, left, and right docks with configurable alignment. +- Supports Nova dark mode, compact mobile actions, safe areas, and reduced motion. +- Ships compiled assets; consuming applications do not need an NPM build. + +## Installation + +Install this package in an existing Laravel Nova 5.9.5 or newer application. +Your application must already have valid Composer credentials for Nova's +licensed package repository. + +```bash +composer require meghdadfadaee/nova-form-dock +``` + +The service provider is discovered automatically. To publish the optional +configuration file: + +```bash +php artisan vendor:publish --tag=nova-form-dock-config +``` + +## Configuration + +Use `mode => 'always'` to dock supported forms regardless of their height. The +`resources.only` and `resources.except` arrays accept Nova resource URI keys. + +```php +return [ + 'enabled' => true, + 'mode' => 'automatic', + 'minimum_form_height' => null, + 'forms' => [ + 'create' => true, + 'update' => true, + ], + 'resources' => [ + 'only' => [], + 'except' => [], + ], + 'appearance' => [ + 'position' => 'bottom', + 'mobile_position' => 'bottom', + 'alignment' => 'end', + 'compact_mobile' => true, + 'floating_gap' => 12, + ], +]; +``` + +When `minimum_form_height` is `null`, the current viewport height is used as +the activation threshold. + +`position` and `mobile_position` accept `top`, `bottom`, `left`, or `right`. +Keeping `mobile_position` set to `bottom` gives side docks a more usable mobile +fallback. `alignment` accepts `start`, `center`, or `end`; start and end follow +the document direction for horizontal docks. + +## Compatibility + +This release targets Laravel Nova 5.9.5 or newer and PHP 8.2 or newer. The +package fails safely when it cannot recognize Nova's full-page create or update +form markup. + +## License + +Nova Form Dock is open-source software licensed under the MIT license. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..3aef817 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,12 @@ +# Security Policy + +## Supported Versions + +Security fixes are provided for the latest stable major release. + +## Reporting a Vulnerability + +Please do not disclose security vulnerabilities in a public issue. Use the +private vulnerability reporting feature in the GitHub Security tab for this +repository. Include reproduction steps, affected versions, and any known +mitigations. You can expect an initial response within seven days. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..e45ce6b --- /dev/null +++ b/composer.json @@ -0,0 +1,54 @@ +{ + "name": "meghdadfadaee/nova-form-dock", + "description": "An adaptive, accessible action dock for long Laravel Nova resource forms.", + "keywords": ["laravel", "nova", "forms", "sticky", "user-interface"], + "homepage": "https://github.com/MeghdadFadaee/nova-form-dock", + "license": "MIT", + "type": "library", + "authors": [ + { + "name": "Meghdad Fadaee" + } + ], + "support": { + "issues": "https://github.com/MeghdadFadaee/nova-form-dock/issues", + "source": "https://github.com/MeghdadFadaee/nova-form-dock" + }, + "require": { + "php": "^8.2", + "illuminate/support": "^10.48|^11.44|^12.1|^13.0", + "laravel/nova": "^5.9.5" + }, + "require-dev": { + "laravel/pint": "^1.20", + "orchestra/testbench": "^8.35|^9.12|^10.1|^11.0", + "phpunit/phpunit": "^10.0|^11.0|^12.0|^13.0" + }, + "repositories": [ + { + "type": "composer", + "url": "https://nova.laravel.com" + } + ], + "autoload": { + "psr-4": {"MeghdadFadaee\\NovaFormDock\\": "src/"} + }, + "autoload-dev": { + "psr-4": {"MeghdadFadaee\\NovaFormDock\\Tests\\": "tests/"} + }, + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + }, + "laravel": { + "providers": ["MeghdadFadaee\\NovaFormDock\\NovaFormDockServiceProvider"] + } + }, + "scripts": { + "format": "pint", + "test": "phpunit" + }, + "config": {"sort-packages": true}, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/config/nova-form-dock.php b/config/nova-form-dock.php new file mode 100644 index 0000000..4505ba2 --- /dev/null +++ b/config/nova-form-dock.php @@ -0,0 +1,123 @@ + true, + + /* + |-------------------------------------------------------------------------- + | Activation Mode + |-------------------------------------------------------------------------- + | + | The "automatic" mode docks actions only when the natural form height is + | greater than the available viewport height. The "always" mode docks every + | supported full-page form regardless of its height. + | + | Supported values: "automatic", "always" + | + */ + 'mode' => 'automatic', + + /* + |-------------------------------------------------------------------------- + | Minimum Form Height + |-------------------------------------------------------------------------- + | + | Define the minimum form height, in CSS pixels, required before automatic + | mode activates the dock. When this value is null, the package calculates + | the available viewport height dynamically for each form. + | + */ + 'minimum_form_height' => null, + + /* + |-------------------------------------------------------------------------- + | Supported Form Types + |-------------------------------------------------------------------------- + | + | These options independently enable the dock for Nova's full-page create + | and update forms. Relationship modals and attached-resource forms are + | excluded even when both options are enabled. + | + */ + 'forms' => [ + 'create' => true, + 'update' => true, + ], + + /* + |-------------------------------------------------------------------------- + | Resource Scoping + |-------------------------------------------------------------------------- + | + | Scope the dock using Nova resource URI keys, such as "users" or "posts". + | Leave "only" empty to allow every resource. Resources in "except" are + | always excluded and take precedence over resources listed in "only". + | + */ + 'resources' => [ + 'only' => [], + 'except' => [], + ], + + /* + |-------------------------------------------------------------------------- + | Dock Appearance + |-------------------------------------------------------------------------- + | + | Configure where the action dock appears and how Nova's existing buttons + | are arranged. These settings change only presentation; the original Nova + | buttons and their submission behavior remain unchanged. + | + */ + 'appearance' => [ + /* + | The desktop viewport edge used by the dock. Top and bottom docks use + | a horizontal layout, while left and right docks use a vertical layout. + | + | Supported values: "top", "bottom", "left", "right" + */ + 'position' => 'bottom', + + /* + | The viewport edge used on screens narrower than 768 pixels. Keeping + | this set to "bottom" provides a usable fallback when the desktop dock + | is positioned on the left or right side of the form. + | + | Supported values: "top", "bottom", "left", "right" + */ + 'mobile_position' => 'bottom', + + /* + | The button alignment inside the dock. For horizontal docks, "start" + | and "end" follow the document direction and therefore support RTL. + | For vertical docks, they correspond to the top and bottom respectively. + | + | Supported values: "start", "center", "end" + */ + 'alignment' => 'end', + + /* + | When enabled, mobile top and bottom docks place the primary submit + | button on its own row and arrange secondary actions compactly below it. + | Disable this option to retain Nova's default mobile button arrangement. + */ + 'compact_mobile' => true, + + /* + | The space, in CSS pixels, between the dock and its selected viewport + | edge. Bottom and vertically aligned docks also include the device's + | safe-area inset automatically when one is present. + */ + 'floating_gap' => 12, + ], +]; diff --git a/dist/css/form-dock.css b/dist/css/form-dock.css new file mode 100644 index 0000000..ef1384f --- /dev/null +++ b/dist/css/form-dock.css @@ -0,0 +1,179 @@ +[data-nfd-form][data-nfd-active][data-nfd-position="bottom"] { + padding-bottom: calc( + var(--nfd-original-padding-bottom, 0px) + + var(--nfd-actions-height, 0px) + 1.5rem + ) !important; +} + +[data-nfd-form][data-nfd-active][data-nfd-position="top"] { + padding-top: calc( + var(--nfd-original-padding-top, 0px) + + var(--nfd-actions-height, 0px) + 1.5rem + ) !important; +} + +[data-nfd-form][data-nfd-active][data-nfd-position="left"] { + padding-left: calc( + var(--nfd-original-padding-left, 0px) + + var(--nfd-actions-width, 0px) + 1.5rem + ) !important; +} + +[data-nfd-form][data-nfd-active][data-nfd-position="right"] { + padding-right: calc( + var(--nfd-original-padding-right, 0px) + + var(--nfd-actions-width, 0px) + 1.5rem + ) !important; +} + +[data-nfd-actions] { + position: fixed !important; + z-index: 40; + padding: 0.75rem 1rem !important; + border: 1px solid rgba(var(--colors-gray-200), 0.9); + border-radius: 0.75rem; + background: rgba(var(--colors-gray-50), 0.92); + box-shadow: + 0 -2px 8px rgb(0 0 0 / 0.06), + 0 8px 24px rgb(0 0 0 / 0.12); + backdrop-filter: blur(12px); + transition: + opacity 120ms ease-out, + transform 120ms ease-out; + animation: nfd-enter 120ms ease-out; +} + +[data-nfd-actions][data-nfd-position="top"], +[data-nfd-actions][data-nfd-position="bottom"] { + right: var(--nfd-inline-end, 1rem); + left: var(--nfd-inline-start, 1rem); +} + +[data-nfd-actions][data-nfd-position="top"] { + top: var(--nfd-block-start, 1rem); +} + +[data-nfd-actions][data-nfd-position="bottom"] { + bottom: calc( + var(--nfd-floating-gap, 12px) + env(safe-area-inset-bottom, 0px) + ); +} + +[data-nfd-actions][data-nfd-position="left"], +[data-nfd-actions][data-nfd-position="right"] { + display: flex !important; + width: min(14rem, calc(100vw - 2rem)); + flex-direction: column !important; + align-items: stretch !important; + gap: 0.5rem !important; +} + +[data-nfd-actions][data-nfd-position="left"] { + left: var(--nfd-inline-start, 1rem); +} + +[data-nfd-actions][data-nfd-position="right"] { + right: var(--nfd-inline-end, 1rem); +} + +[data-nfd-actions][data-nfd-position="left"] > *, +[data-nfd-actions][data-nfd-position="right"] > * { + width: 100%; + margin: 0 !important; +} + +[data-nfd-actions][data-nfd-position="left"][data-nfd-alignment="start"], +[data-nfd-actions][data-nfd-position="right"][data-nfd-alignment="start"] { + top: var(--nfd-block-start, 1rem); +} + +[data-nfd-actions][data-nfd-position="left"][data-nfd-alignment="center"], +[data-nfd-actions][data-nfd-position="right"][data-nfd-alignment="center"] { + top: 50%; + translate: 0 -50%; +} + +[data-nfd-actions][data-nfd-position="left"][data-nfd-alignment="end"], +[data-nfd-actions][data-nfd-position="right"][data-nfd-alignment="end"] { + bottom: calc( + var(--nfd-floating-gap, 12px) + env(safe-area-inset-bottom, 0px) + ); +} + +[data-nfd-actions][data-nfd-position="top"][data-nfd-alignment="start"], +[data-nfd-actions][data-nfd-position="bottom"][data-nfd-alignment="start"] { + justify-content: flex-start !important; +} + +[data-nfd-actions][data-nfd-position="top"][data-nfd-alignment="center"], +[data-nfd-actions][data-nfd-position="bottom"][data-nfd-alignment="center"] { + justify-content: center !important; +} + +[data-nfd-actions][data-nfd-position="top"][data-nfd-alignment="end"], +[data-nfd-actions][data-nfd-position="bottom"][data-nfd-alignment="end"] { + justify-content: flex-end !important; +} + +@keyframes nfd-enter { + from { + opacity: 0.7; + transform: translateY(4px); + } +} + +.dark [data-nfd-actions] { + border-color: rgba(var(--colors-gray-700), 0.9); + background: rgba(var(--colors-gray-900), 0.92); + box-shadow: + 0 -2px 8px rgb(0 0 0 / 0.18), + 0 8px 24px rgb(0 0 0 / 0.3); +} + +@media (max-width: 767px) { + [data-nfd-actions][data-nfd-compact-mobile][data-nfd-position="top"], + [data-nfd-actions][data-nfd-compact-mobile][data-nfd-position="bottom"] { + display: flex !important; + flex-flow: row wrap !important; + align-items: stretch !important; + gap: 0.5rem !important; + } + + [data-nfd-actions][data-nfd-compact-mobile][data-nfd-position="top"] > *, + [data-nfd-actions][data-nfd-compact-mobile][data-nfd-position="bottom"] > * { + flex: 1 1 auto; + margin: 0 !important; + } + + [data-nfd-actions][data-nfd-type="create"] > [dusk="create-button"], + [data-nfd-actions][data-nfd-type="update"] > [dusk="update-button"] { + order: -1; + flex-basis: 100%; + } +} + +@media (prefers-reduced-motion: reduce) { + [data-nfd-actions] { + animation: none; + transition: none; + } +} + +@media print { + [data-nfd-form][data-nfd-active] { + padding: var(--nfd-original-padding-top, 0px) + var(--nfd-original-padding-right, 0px) + var(--nfd-original-padding-bottom, 0px) + var(--nfd-original-padding-left, 0px) !important; + } + + [data-nfd-actions] { + position: static !important; + width: auto; + padding: 0 !important; + border: 0; + box-shadow: none; + translate: none; + backdrop-filter: none; + } +} diff --git a/dist/js/form-dock.js b/dist/js/form-dock.js new file mode 100644 index 0000000..c900945 --- /dev/null +++ b/dist/js/form-dock.js @@ -0,0 +1,332 @@ +(function () { + 'use strict' + + const FORM_SELECTOR = '#nova [dusk="content"] form[data-form-unique-id]' + const controllers = new Map() + let scanFrame = null + let started = false + + function configuredValue(value, allowedValues, fallback) { + return allowedValues.includes(value) ? value : fallback + } + + function packageConfig() { + const configured = Nova.config('novaFormDock') || {} + const positions = ['top', 'bottom', 'left', 'right'] + + return { + mode: configured.mode === 'always' ? 'always' : 'automatic', + minimumFormHeight: Number(configured.minimum_form_height) || null, + forms: { + create: configured.forms?.create !== false, + update: configured.forms?.update !== false, + }, + resources: { + only: Array.isArray(configured.resources?.only) + ? configured.resources.only + : [], + except: Array.isArray(configured.resources?.except) + ? configured.resources.except + : [], + }, + appearance: { + position: configuredValue( + configured.appearance?.position, + positions, + 'bottom', + ), + mobilePosition: configuredValue( + configured.appearance?.mobile_position, + positions, + 'bottom', + ), + alignment: configuredValue( + configured.appearance?.alignment, + ['start', 'center', 'end'], + 'end', + ), + compactMobile: configured.appearance?.compact_mobile !== false, + floatingGap: Math.max( + 0, + Number(configured.appearance?.floating_gap) || 0, + ), + }, + } + } + + function effectivePosition(config) { + return window.matchMedia('(max-width: 767px)').matches + ? config.appearance.mobilePosition + : config.appearance.position + } + + function formDetails(form) { + if (form.closest('.modal')) { + return null + } + + const actions = form.lastElementChild + + if (!actions) { + return null + } + + if ( + actions.querySelector(':scope > [dusk="create-button"]') && + actions.querySelector(':scope > [dusk="cancel-create-button"]') + ) { + return { actions, type: 'create' } + } + + if ( + actions.querySelector(':scope > [dusk="update-button"]') && + actions.querySelector(':scope > [dusk="cancel-update-button"]') + ) { + return { actions, type: 'update' } + } + + return null + } + + function currentResource() { + const match = window.location.pathname.match(/\/resources\/([^/]+)/) + + if (!match) { + return null + } + + try { + return decodeURIComponent(match[1]) + } catch { + return null + } + } + + function resourceIsEnabled(config) { + const resource = currentResource() + + if (!resource || config.resources.except.includes(resource)) { + return false + } + + return ( + config.resources.only.length === 0 || + config.resources.only.includes(resource) + ) + } + + function scheduleScan() { + if (scanFrame !== null) { + return + } + + scanFrame = window.requestAnimationFrame(() => { + scanFrame = null + scan() + }) + } + + function createController(form, details) { + const computedStyle = window.getComputedStyle(form) + const resizeObserver = window.ResizeObserver + ? new ResizeObserver(scheduleScan) + : { disconnect() {}, observe() {} } + + resizeObserver.observe(form) + resizeObserver.observe(details.actions) + + if (details.actions.previousElementSibling) { + resizeObserver.observe(details.actions.previousElementSibling) + } + + return { + actions: details.actions, + form, + naturalActionHeight: details.actions.getBoundingClientRect().height, + originalPadding: { + top: computedStyle.paddingTop, + right: computedStyle.paddingRight, + bottom: computedStyle.paddingBottom, + left: computedStyle.paddingLeft, + }, + resizeObserver, + type: details.type, + } + } + + function naturalFormHeight(controller) { + const { actions, form } = controller + const content = actions.previousElementSibling + + if (!content) { + return form.scrollHeight + } + + const contentRect = content.getBoundingClientRect() + const verticalPadding = + Number.parseFloat(controller.originalPadding.top) + + Number.parseFloat(controller.originalPadding.bottom) + + return contentRect.height + controller.naturalActionHeight + verticalPadding + 32 + } + + function shouldActivate(controller, config) { + if (!config.forms[controller.type] || !resourceIsEnabled(config)) { + return false + } + + if (config.mode === 'always') { + return true + } + + const availableViewportHeight = Math.max( + 320, + window.innerHeight - Math.max(0, controller.form.getBoundingClientRect().top), + ) + const threshold = config.minimumFormHeight || availableViewportHeight + + return naturalFormHeight(controller) > threshold + } + + function setDockDimensions(controller, config) { + const formRect = controller.form.getBoundingClientRect() + const actionRect = controller.actions.getBoundingClientRect() + const headerBottom = document.querySelector('#nova header') + ?.getBoundingClientRect().bottom + const floatingGap = config.appearance.floatingGap + + Object.entries(controller.originalPadding).forEach(([side, value]) => { + controller.form.style.setProperty(`--nfd-original-padding-${side}`, value) + }) + + controller.form.style.setProperty('--nfd-actions-height', `${actionRect.height}px`) + controller.form.style.setProperty('--nfd-actions-width', `${actionRect.width}px`) + controller.actions.style.setProperty( + '--nfd-inline-start', + `${Math.max(0, formRect.left)}px`, + ) + controller.actions.style.setProperty( + '--nfd-inline-end', + `${Math.max(0, window.innerWidth - formRect.right)}px`, + ) + controller.actions.style.setProperty( + '--nfd-floating-gap', + `${floatingGap}px`, + ) + controller.actions.style.setProperty( + '--nfd-block-start', + `${Math.max(floatingGap, (headerBottom || 0) + floatingGap)}px`, + ) + } + + function activate(controller, config) { + const position = effectivePosition(config) + + controller.form.dataset.nfdForm = '' + controller.form.dataset.nfdActive = '' + controller.form.dataset.nfdPosition = position + controller.actions.dataset.nfdActions = '' + controller.actions.dataset.nfdType = controller.type + controller.actions.dataset.nfdPosition = position + controller.actions.dataset.nfdAlignment = config.appearance.alignment + + if (config.appearance.compactMobile) { + controller.actions.dataset.nfdCompactMobile = '' + } else { + delete controller.actions.dataset.nfdCompactMobile + } + + setDockDimensions(controller, config) + } + + function deactivate(controller) { + delete controller.form.dataset.nfdForm + delete controller.form.dataset.nfdActive + delete controller.form.dataset.nfdPosition + delete controller.actions.dataset.nfdActions + delete controller.actions.dataset.nfdType + delete controller.actions.dataset.nfdPosition + delete controller.actions.dataset.nfdAlignment + delete controller.actions.dataset.nfdCompactMobile + + Object.keys(controller.originalPadding).forEach(side => { + controller.form.style.removeProperty(`--nfd-original-padding-${side}`) + }) + + controller.form.style.removeProperty('--nfd-actions-height') + controller.form.style.removeProperty('--nfd-actions-width') + controller.actions.style.removeProperty('--nfd-inline-start') + controller.actions.style.removeProperty('--nfd-inline-end') + controller.actions.style.removeProperty('--nfd-floating-gap') + controller.actions.style.removeProperty('--nfd-block-start') + } + + function destroy(controller) { + deactivate(controller) + controller.resizeObserver.disconnect() + controllers.delete(controller.form) + } + + function scan() { + const config = packageConfig() + const candidates = new Set() + + document.querySelectorAll(FORM_SELECTOR).forEach(form => { + const details = formDetails(form) + + if (!details) { + return + } + + candidates.add(form) + + let controller = controllers.get(form) + + if (!controller || controller.actions !== details.actions) { + if (controller) { + destroy(controller) + } + + controller = createController(form, details) + controllers.set(form, controller) + } + + if (!controller.form.hasAttribute('data-nfd-active')) { + controller.naturalActionHeight = details.actions.getBoundingClientRect().height + } + + if (shouldActivate(controller, config)) { + activate(controller, config) + } else { + deactivate(controller) + } + }) + + controllers.forEach(controller => { + if (!controller.form.isConnected || !candidates.has(controller.form)) { + destroy(controller) + } + }) + } + + function start() { + if (started) { + return + } + + started = true + + const observer = new MutationObserver(scheduleScan) + observer.observe(document.documentElement, { + childList: true, + subtree: true, + }) + + window.addEventListener('resize', scheduleScan, { passive: true }) + window.addEventListener('scroll', scheduleScan, { passive: true }) + Nova.$router?.on('navigate', scheduleScan) + scheduleScan() + } + + Nova.booting(start) +})() diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..45a19c3 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,17 @@ + + + + + tests + + + + + src + + + diff --git a/src/NovaFormDockServiceProvider.php b/src/NovaFormDockServiceProvider.php new file mode 100644 index 0000000..21ad046 --- /dev/null +++ b/src/NovaFormDockServiceProvider.php @@ -0,0 +1,36 @@ +mergeConfigFrom( + __DIR__.'/../config/nova-form-dock.php', + 'nova-form-dock', + ); + } + + public function boot(): void + { + $this->publishes([ + __DIR__.'/../config/nova-form-dock.php' => config_path('nova-form-dock.php'), + ], 'nova-form-dock-config'); + + if (! config('nova-form-dock.enabled', true)) { + return; + } + + Nova::serving(function (): void { + Nova::style('nova-form-dock', __DIR__.'/../dist/css/form-dock.css'); + Nova::script('nova-form-dock', __DIR__.'/../dist/js/form-dock.js'); + Nova::provideToScript([ + 'novaFormDock' => config('nova-form-dock'), + ]); + }); + } +} diff --git a/tests/AssetRegistrationTest.php b/tests/AssetRegistrationTest.php new file mode 100644 index 0000000..049223b --- /dev/null +++ b/tests/AssetRegistrationTest.php @@ -0,0 +1,29 @@ +app, Request::create('/nova'))); + + $style = collect(Nova::allStyles()) + ->first(fn ($asset): bool => $asset->name() === 'nova-form-dock'); + $script = collect(Nova::allScripts()) + ->first(fn ($asset): bool => $asset->name() === 'nova-form-dock'); + + $this->assertNotNull($style); + $this->assertNotNull($script); + $this->assertFileExists($style->path()); + $this->assertFileExists($script->path()); + $this->assertSame( + 'automatic', + Nova::jsonVariables(Request::create('/nova'))['novaFormDock']['mode'], + ); + } +} diff --git a/tests/ConfigurationTest.php b/tests/ConfigurationTest.php new file mode 100644 index 0000000..0604021 --- /dev/null +++ b/tests/ConfigurationTest.php @@ -0,0 +1,16 @@ +assertTrue(config('nova-form-dock.enabled')); + $this->assertSame('automatic', config('nova-form-dock.mode')); + $this->assertTrue(config('nova-form-dock.forms.create')); + $this->assertTrue(config('nova-form-dock.forms.update')); + $this->assertSame('bottom', config('nova-form-dock.appearance.position')); + $this->assertSame('end', config('nova-form-dock.appearance.alignment')); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..2120d71 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,19 @@ + + */ + protected function getPackageProviders($app): array + { + return [ + NovaFormDockServiceProvider::class, + ]; + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..df6991c --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,13 @@ +