|
| 1 | +import { Alpine as TAlpine } from 'alpinejs' |
| 2 | +import { client, Config, createValidator, RequestMethod, resolveName, toSimpleValidationErrors, ValidationConfig } from 'laravel-precognition' |
| 3 | +import cloneDeep from 'lodash.clonedeep' |
| 4 | +import get from 'lodash.get' |
| 5 | +import set from 'lodash.set' |
| 6 | +import { Form } from './types' |
| 7 | + |
| 8 | +export default function (Alpine: TAlpine) { |
| 9 | + Alpine.magic('form', (el) => <Data extends Record<string, unknown>>(method: RequestMethod, url: string, inputs: Data, config: ValidationConfig = {}): Data&Form<Data> => { |
| 10 | + // @ts-expect-error |
| 11 | + method = method.toLowerCase() |
| 12 | + |
| 13 | + syncWithDom(el, method, url) |
| 14 | + |
| 15 | + /** |
| 16 | + * The original data. |
| 17 | + */ |
| 18 | + const originalData = cloneDeep(inputs) |
| 19 | + |
| 20 | + /** |
| 21 | + * The original input names. |
| 22 | + */ |
| 23 | + const originalInputs = Object.keys(originalData) |
| 24 | + |
| 25 | + /** |
| 26 | + * Internal reactive state. |
| 27 | + */ |
| 28 | + const state: { |
| 29 | + touched: string[], |
| 30 | + valid: string[], |
| 31 | + } = Alpine.reactive({ |
| 32 | + touched: [], |
| 33 | + valid: [], |
| 34 | + }) |
| 35 | + |
| 36 | + /** |
| 37 | + * The validator instance. |
| 38 | + */ |
| 39 | + const validator = createValidator(client => client[method](url, form.data(), config), originalData) |
| 40 | + .on('validatingChanged', () => { |
| 41 | + form.validating = validator.validating() |
| 42 | + }) |
| 43 | + .on('touchedChanged', () => { |
| 44 | + state.valid = validator.valid() |
| 45 | + |
| 46 | + state.touched = validator.touched() |
| 47 | + }) |
| 48 | + .on('errorsChanged', () => { |
| 49 | + state.valid = validator.valid() |
| 50 | + |
| 51 | + form.hasErrors = validator.hasErrors() |
| 52 | + |
| 53 | + form.errors = toSimpleValidationErrors(validator.errors()) |
| 54 | + }) |
| 55 | + |
| 56 | + /** |
| 57 | + * Resolve the config for a form submission. |
| 58 | + */ |
| 59 | + const resolveSubmitConfig = (config: Config): Config => ({ |
| 60 | + ...config, |
| 61 | + precognitive: false, |
| 62 | + onStart: () => { |
| 63 | + form.processing = true; |
| 64 | + |
| 65 | + (config.onStart ?? (() => null))() |
| 66 | + }, |
| 67 | + onFinish: () => { |
| 68 | + form.processing = false; |
| 69 | + |
| 70 | + (config.onFinish ?? (() => null))() |
| 71 | + }, |
| 72 | + onValidationError: (response, error) => { |
| 73 | + validator.setErrors(response.data.errors) |
| 74 | + |
| 75 | + return config.onValidationError |
| 76 | + ? config.onValidationError(response) |
| 77 | + : Promise.reject(error) |
| 78 | + }, |
| 79 | + }) |
| 80 | + |
| 81 | + /** |
| 82 | + * Create a new form instance. |
| 83 | + */ |
| 84 | + const createForm = (): Data&Form<Data> => ({ |
| 85 | + ...cloneDeep(inputs), |
| 86 | + data() { |
| 87 | + return originalInputs.reduce((carry, name) => ({ |
| 88 | + ...carry, |
| 89 | + [name]: cloneDeep(form[name]), |
| 90 | + }), {}) as Data |
| 91 | + }, |
| 92 | + touched(name) { |
| 93 | + return state.touched.includes(name) |
| 94 | + }, |
| 95 | + validate(name) { |
| 96 | + name = resolveName(name) |
| 97 | + |
| 98 | + validator.validate(name, get(form.data(), name)) |
| 99 | + |
| 100 | + return form |
| 101 | + }, |
| 102 | + validating: false, |
| 103 | + valid(name) { |
| 104 | + return state.valid.includes(name) |
| 105 | + }, |
| 106 | + invalid(name) { |
| 107 | + return typeof form.errors[name] !== 'undefined' |
| 108 | + }, |
| 109 | + errors: {}, |
| 110 | + hasErrors: false, |
| 111 | + setErrors(errors) { |
| 112 | + validator.setErrors(errors) |
| 113 | + |
| 114 | + return form |
| 115 | + }, |
| 116 | + reset(...names) { |
| 117 | + const original = cloneDeep(originalData) |
| 118 | + |
| 119 | + if (names.length === 0) { |
| 120 | + // @ts-expect-error |
| 121 | + originalInputs.forEach(name => (form[name] = original[name])) |
| 122 | + } else { |
| 123 | + names.forEach(name => set(form, name, get(original, name))) |
| 124 | + } |
| 125 | + |
| 126 | + validator.reset(...names) |
| 127 | + |
| 128 | + return form |
| 129 | + }, |
| 130 | + setValidationTimeout(duration) { |
| 131 | + validator.setTimeout(duration) |
| 132 | + |
| 133 | + return form |
| 134 | + }, |
| 135 | + processing: false, |
| 136 | + async submit(config = {}) { |
| 137 | + return client[method](url, form.data(), resolveSubmitConfig(config)) |
| 138 | + }, |
| 139 | + }) |
| 140 | + |
| 141 | + /** |
| 142 | + * The form instance. |
| 143 | + */ |
| 144 | + const form = Alpine.reactive(createForm()) as Data&Form<Data> |
| 145 | + |
| 146 | + return form |
| 147 | + }) |
| 148 | +} |
| 149 | + |
| 150 | +/** |
| 151 | + * Sync the DOM form with the Precognitive form. |
| 152 | + */ |
| 153 | +const syncWithDom = (el: Node, method: RequestMethod, url: string): void => { |
| 154 | + if (! (el instanceof Element && el.nodeName === 'FORM')) { |
| 155 | + return |
| 156 | + } |
| 157 | + |
| 158 | + syncSyntheticMethodInput(el, method) |
| 159 | + syncMethodAttribute(el, method) |
| 160 | + syncActionAttribute(el, url) |
| 161 | +} |
| 162 | + |
| 163 | +/** |
| 164 | + * Sync the form's "method" attribute. |
| 165 | + */ |
| 166 | +const syncMethodAttribute = (el: Element, method: RequestMethod) => { |
| 167 | + if (method !== 'get' && ! el.hasAttribute('method')) { |
| 168 | + el.setAttribute('method', 'POST') |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +/** |
| 173 | + * Sync the form's "action" attribute. |
| 174 | + */ |
| 175 | +const syncActionAttribute = (el: Element, url: string) => { |
| 176 | + if (! el.hasAttribute('action')) { |
| 177 | + el.setAttribute('action', url) |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +/** |
| 182 | + * Sync the form's sythentic "method" input. |
| 183 | + */ |
| 184 | +const syncSyntheticMethodInput = (el: Element, method: RequestMethod) => { |
| 185 | + if (['get', 'post'].includes(method)) { |
| 186 | + return |
| 187 | + } |
| 188 | + |
| 189 | + const existing = el.querySelector('input[type="hidden"][name="_method"]') |
| 190 | + |
| 191 | + if (existing !== null) { |
| 192 | + return |
| 193 | + } |
| 194 | + |
| 195 | + console.log('here') |
| 196 | + |
| 197 | + const input = el.insertAdjacentElement('afterbegin', document.createElement('input')) |
| 198 | + |
| 199 | + if (input === null) { |
| 200 | + return |
| 201 | + } |
| 202 | + |
| 203 | + input.setAttribute('type', 'hidden') |
| 204 | + input.setAttribute('name', '_method') |
| 205 | + input.setAttribute('value', method.toUpperCase()) |
| 206 | +} |
0 commit comments