Skip to content

Laravel Precognition #91

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions app/app/Http/Controllers/PrecognitionFormController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace App\Http\Controllers;

use App\Http\Requests\CreateUserRequest;

class PrecognitionFormController
{
public function __invoke(CreateUserRequest $request)
{
dd($request->all());

return redirect()->route('navigation.one');
}
}
31 changes: 31 additions & 0 deletions app/app/Http/Requests/CreateUserRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'name' => ['required', 'string'],
'email' => $this->isPrecognitive() ? ['in:valid@protone.media'] : ['required', 'email', 'in:valid@protone.media'],
];
}
}
13 changes: 13 additions & 0 deletions app/resources/views/form/precognition.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
@extends('layout')

@section('content')

FormPrecognition

<x-splade-form precognition="email">
<x-splade-input name="name" label="Name" />
<x-splade-input name="email" label="Email" />
<x-splade-submit />
</x-splade-form>

@endsection
7 changes: 7 additions & 0 deletions app/routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
use App\Http\Controllers\ModalController;
use App\Http\Controllers\NavigationController;
use App\Http\Controllers\NestedFormController;
use App\Http\Controllers\PrecognitionFormController;
use App\Http\Controllers\SimpleFormController;
use App\Http\Controllers\SlowFormController;
use App\Http\Controllers\TableController;
use App\Http\Controllers\ToastController;
use App\Http\Controllers\TwoFieldsFormController;
use App\Http\UserTableView;
use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
Expand Down Expand Up @@ -114,6 +116,11 @@
Route::view('form/nested', 'form.nested')->name('form.nested');
Route::post('form/nested', NestedFormController::class)->name('form.nested.submit');

Route::view('form/precognition', 'form.precognition')->name('form.precognition');
Route::post('form/precognition', PrecognitionFormController::class)
->name('form.precognition.submit')
->middleware(HandlePrecognitiveRequests::class);

Route::get('form/components/simple', [FormComponentsController::class, 'simple'])->name('form.components.simple');
Route::get('form/components/vmodel', [FormComponentsController::class, 'vmodel'])->name('form.components.vmodel');
Route::get('form/components/checkbox', [FormComponentsController::class, 'checkbox'])->name('form.components.checkbox');
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
],
"require": {
"php": "^8.0 || ^8.1",
"illuminate/contracts": "^9.22"
"illuminate/contracts": "^9.34"
},
"require-dev": {
"laravel/pint": "^1.0",
Expand Down
94 changes: 86 additions & 8 deletions lib/Components/Form.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import isBoolean from "lodash-es/isBoolean";
import mapValues from "lodash-es/mapValues";
import set from "lodash-es/set";
import startsWith from "lodash-es/startsWith";
import debounce from "lodash-es/debounce";

export default {
inject: ["stack"],
Expand Down Expand Up @@ -98,7 +99,13 @@ export default {
type: [Boolean, Array],
required: false,
default: false
}
},

precognition: {
type: [Boolean, Array],
required: false,
default: false
},
},

emits: ["success", "error"],
Expand All @@ -113,7 +120,9 @@ export default {
recentlySuccessful: false,
recentlySuccessfulTimeoutId: null,
formElement: null,
touchedPrecognitionKeys: [],
elementsUploading: [],
precognitionDebounceFunction: null,
};
},

Expand Down Expand Up @@ -173,24 +182,48 @@ export default {
this.$put(attribute, defaultValue);
});

this.formElement.querySelectorAll("[data-validation-key]").forEach((element) => {
element.addEventListener("change", this.handlePrecognition);
});

this.missingAttributes = [];
this.touchedPrecognitionKeys = [];

// Create watchers
if(this.submitOnChange === true) {
this.$watch("values", () => {
this.$nextTick(() => this.request());
}, { deep: true });
}else if(isArray(this.submitOnChange)) {
} else if(isArray(this.submitOnChange)) {
this.submitOnChange.forEach((key) => {
this.$watch(`values.${key}`, () => {
this.$nextTick(() => this.request());
}, { deep: true });
});
}

// Create watchers
if(this.precognition === true) {
this.$watch("values", () => {
this.$nextTick(() => this.precognitionDebounceFunction());
}, { deep: true });
} else if(isArray(this.precognition)) {
this.precognition.forEach((key) => {
this.$watch(`values.${key}`, () => {
this.$nextTick(() => this.precognitionDebounceFunction());
}, { deep: true });
});
}

this.isMounted = true;
},

created() {
this.precognitionDebounceFunction = debounce(() => {
this.handlePrecognition();
}, 1250);
},

methods: {
$startUploading(eventData) {
this.elementsUploading.push(eventData[0]);
Expand All @@ -213,9 +246,15 @@ export default {
},

$put(key, value) {
this.$touchForPrecognition(key);

return set(this.values, key, value);
},

$touchForPrecognition(key) {
this.touchedPrecognitionKeys = [...new Set([key, ...this.touchedPrecognitionKeys])];
},

focusAndScrollToElement(element) {
let shouldFocus = true;

Expand Down Expand Up @@ -282,21 +321,31 @@ export default {
.catch(() => {});
},

async handlePrecognition() {
await this.handleRequest(true, isArray(this.precognition) ?this.precognition:[]);
},

async request() {
await this.handleRequest(false, []);
},

/*
* Maps the values into a FormData instance and then
* performs an async request.
*/
async request() {
async handleRequest(precognition, precognitionRules) {
if(this.$uploading) {
return;
}

await this.$nextTick();

this.processing = true;
this.wasSuccessful = false;
this.recentlySuccessful = false;
clearTimeout(this.recentlySuccessfulTimeoutId);
if(!precognition) {
this.processing = true;
this.wasSuccessful = false;
this.recentlySuccessful = false;
clearTimeout(this.recentlySuccessfulTimeoutId);
}

const data = (this.values instanceof FormData)
? this.values
Expand All @@ -308,6 +357,25 @@ export default {
headers["X-Splade-Prevent-Refresh"] = true;
}

if(precognition) {
headers["Precognition"] = true;

let validateOnly = this.touchedPrecognitionKeys;

if(precognitionRules.length > 0) {
validateOnly = validateOnly.filter((key) => {
return precognitionRules.includes(key);
});

if(validateOnly.length === 0) {
// Non of the touched keys are in the precognition rules.
return;
}
}

headers["Precognition-Validate-Only"] = validateOnly.join(",");
}

let method = this.method.toUpperCase();

if(method !== "GET" && method !== "POST") {
Expand All @@ -317,6 +385,12 @@ export default {

Splade.request(this.action, method, data, headers)
.then((response) => {
if (response.headers.precognition) {
return;
}

this.processing = false;

this.$emit("success", response);

if (this.restoreOnSuccess) {
Expand All @@ -327,12 +401,15 @@ export default {
this.reset();
}

this.processing = false;
this.wasSuccessful = true;
this.recentlySuccessful = true;
this.recentlySuccessfulTimeoutId = setTimeout(() => this.recentlySuccessful = false, 2000);
})
.catch(async (error) => {
if(precognition) {
return;
}

this.processing = false;
this.$emit("error", error);

Expand Down Expand Up @@ -371,6 +448,7 @@ export default {
"$all",
"$attrs",
"$put",
"$touch",
"$startUploading",
"$stopUploading",
"$processing",
Expand Down
8 changes: 8 additions & 0 deletions lib/Splade.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@ const newPages = ref(0);
* Handles an incoming response from a Splade request.
*/
function newPageFromResponse(response, replace) {
if (response.headers.precognition) {
return;
}

newPages.value++;

const url = response.request.responseURL;
Expand Down Expand Up @@ -466,6 +470,10 @@ function request(url, method, data, headers, replace) {

promise
.then((response) => {
if (response.status === 204 && response.headers.precognition) {
_validationErrors.value[stack.value] = {};
}

newPageFromResponse(response, replace);
fireEvent("request-response", { url, method, data, headers, replace, response });
})
Expand Down
1 change: 1 addition & 0 deletions resources/views/functional/form.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
:scroll-on-error="@js($scrollOnError)"
:splade-id="@js($spladeId)"
:submit-on-change="@js($submitOnChange)"
:precognition="@js($precognition)"
>
<template #default="{!! $scope !!}">
<form data-splade-id="{{ $spladeId }}" v-bind="form.$attrs" @submit.prevent="form.submit" {{ $attributes->only(['action', 'method'])->merge(['method' => 'POST']) }}>
Expand Down
5 changes: 5 additions & 0 deletions src/Components/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public function __construct(
$unguarded = null,
public bool $scrollOnError = true,
public array|bool|string $submitOnChange = false,
public array|bool|string $precognition = false,
) {
// We'll use this instance in the static 'selected()' method,
// which is a workaround for a Vue bug. Later, when the
Expand All @@ -70,6 +71,10 @@ public function __construct(
if (is_string($submitOnChange)) {
$this->submitOnChange = static::splitByComma($submitOnChange);
}

if (is_string($precognition)) {
$this->precognition = static::splitByComma($precognition);
}
}

/**
Expand Down