Skip to content
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

feat: unshadow form and data in enhance #9902

Merged
merged 11 commits into from
May 16, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 5 additions & 0 deletions .changeset/odd-crews-own.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': minor
---

feat: unshadow `data` and `form` in `enhance` and warn about future deprecation when used in `dev` mode
60 changes: 46 additions & 14 deletions packages/kit/src/runtime/app/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,26 @@ export function deserialize(result) {
return parsed;
}

/**
* @param {string} oldName
* @param {string} newName
* @param {string} callLocation
* @returns void
*/
function warn_on_access(oldName, newName, callLocation) {
elliott-with-the-longest-name-on-github marked this conversation as resolved.
Show resolved Hide resolved
if (!DEV) return;
// TODO 2.0: Remove this code
console.warn(
`\`${oldName}\` has been deprecated in favor of \`${newName}\`. \`${oldName}\` will be removed in a future version. (Called from ${callLocation})`
);
}

/** @type {import('$app/forms').enhance} */
export function enhance(form, submit = () => {}) {
export function enhance(formElement, submit = () => {}) {
elliott-with-the-longest-name-on-github marked this conversation as resolved.
Show resolved Hide resolved
if (
DEV &&
/** @type {HTMLFormElement} */ (HTMLFormElement.prototype.cloneNode.call(form)).method !==
'post'
/** @type {HTMLFormElement} */ (HTMLFormElement.prototype.cloneNode.call(formElement))
.method !== 'post'
) {
throw new Error('use:enhance can only be used on <form> fields with method="POST"');
}
Expand All @@ -35,7 +49,7 @@ export function enhance(form, submit = () => {}) {
if (result.type === 'success') {
if (reset !== false) {
// We call reset from the prototype to avoid DOM clobbering
HTMLFormElement.prototype.reset.call(form);
HTMLFormElement.prototype.reset.call(formElement);
}
await invalidateAll();
}
Expand All @@ -60,28 +74,38 @@ export function enhance(form, submit = () => {}) {
// We do cloneNode for avoid DOM clobbering - https://github.com/sveltejs/kit/issues/7593
event.submitter?.hasAttribute('formaction')
? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formAction
: /** @type {HTMLFormElement} */ (HTMLFormElement.prototype.cloneNode.call(form)).action
: /** @type {HTMLFormElement} */ (HTMLFormElement.prototype.cloneNode.call(formElement))
.action
);

const data = new FormData(form);
const formData = new FormData(formElement);
elliott-with-the-longest-name-on-github marked this conversation as resolved.
Show resolved Hide resolved
elliott-with-the-longest-name-on-github marked this conversation as resolved.
Show resolved Hide resolved

const submitter_name = event.submitter?.getAttribute('name');
if (submitter_name) {
data.append(submitter_name, event.submitter?.getAttribute('value') ?? '');
formData.append(submitter_name, event.submitter?.getAttribute('value') ?? '');
}

const controller = new AbortController();

let cancelled = false;
const cancel = () => (cancelled = true);

// TODO 2.0: Remove `data` and `form`
const callback =
(await submit({
action,
cancel,
controller,
data,
form,
get data() {
warn_on_access('data', 'formData', 'use:enhance submit function');
return formData;
},
formData,
get form() {
warn_on_access('form', 'formElement', 'use:enhance submit function');
return formElement;
},
formElement,
submitter: event.submitter
})) ?? fallback_callback;
if (cancelled) return;
Expand All @@ -97,7 +121,7 @@ export function enhance(form, submit = () => {}) {
'x-sveltekit-action': 'true'
},
cache: 'no-store',
body: data,
body: formData,
signal: controller.signal
});

Expand All @@ -110,21 +134,29 @@ export function enhance(form, submit = () => {}) {

callback({
action,
data,
form,
get data() {
warn_on_access('data', 'formData', 'callback returned from use:enhance submit function');
return formData;
},
formData,
get form() {
warn_on_access('form', 'formElement', 'callback returned from use:enhance submit function');
return formElement;
},
formElement,
update: (opts) => fallback_callback({ action, result, reset: opts?.reset }),
// @ts-expect-error generic constraints stuff we don't care about
result
});
}

// @ts-expect-error
HTMLFormElement.prototype.addEventListener.call(form, 'submit', handle_submit);
HTMLFormElement.prototype.addEventListener.call(formElement, 'submit', handle_submit);

return {
destroy() {
// @ts-expect-error
HTMLFormElement.prototype.removeEventListener.call(form, 'submit', handle_submit);
HTMLFormElement.prototype.removeEventListener.call(formElement, 'submit', handle_submit);
}
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// TODO 2.0: Remove this code and corresponding tests
export const actions = {
formSubmit: () => {
return {
formSubmit: true
};
},

formCallback: () => {
return {
formCallback: true
};
},

dataSubmit: () => {
return {
dataSubmit: true
};
},

dataCallback: () => {
return {
dataCallback: true
};
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<script>
import { enhance } from '$app/forms';

export let form;

const accessFormSubmit = (node) => {
return enhance(node, ({ form }) => {});
};
const accessDataSubmit = (node) => {
return enhance(node, ({ data }) => {});
};
const accessFormCallback = (node) => {
return enhance(
node,
() =>
({ form, update }) =>
update()
);
};
const accessDataCallback = (node) => {
elliott-with-the-longest-name-on-github marked this conversation as resolved.
Show resolved Hide resolved
return enhance(
node,
() =>
({ data, update }) =>
update()
);
};
</script>

<form method="POST" action="?/formSubmit" use:accessFormSubmit>
<button id="access-form-in-submit" type="submit"
>{form?.formSubmit ? 'processed' : 'not processed'}</button
>
</form>

<form method="POST" action="?/dataSubmit" use:accessDataSubmit>
<button id="access-data-in-submit" type="submit"
>{form?.dataSubmit ? 'processed' : 'not processed'}</button
>
</form>

<form method="POST" action="?/formCallback" use:accessFormCallback>
<button id="access-form-in-callback" type="submit"
>{form?.formCallback ? 'processed' : 'not processed'}</button
>
</form>

<form method="POST" action="?/dataCallback" use:accessDataCallback>
<button id="access-data-in-callback" type="submit"
>{form?.dataCallback ? 'processed' : 'not processed'}</button
>
</form>
45 changes: 45 additions & 0 deletions packages/kit/test/apps/basics/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,51 @@ test.describe('Matchers', () => {
});

test.describe('Actions', () => {
for (const { id, oldName, newName, callLocation } of [
elliott-with-the-longest-name-on-github marked this conversation as resolved.
Show resolved Hide resolved
{
id: 'access-form-in-submit',
oldName: 'form',
newName: 'formElement',
callLocation: 'use:enhance submit function'
},
{
id: 'access-form-in-callback',
oldName: 'form',
newName: 'formElement',
callLocation: 'callback returned from use:enhance submit function'
},
{
id: 'access-data-in-submit',
oldName: 'data',
newName: 'formData',
callLocation: 'use:enhance submit function'
},
{
id: 'access-data-in-callback',
oldName: 'data',
newName: 'formData',
callLocation: 'callback returned from use:enhance submit function'
}
]) {
test(`Accessing v2 deprecated properties results in a warning log, type: ${id}`, async ({
page,
javaScriptEnabled
}) => {
test.skip(!javaScriptEnabled, 'skip when js is disabled');
test.skip(!process.env.DEV, 'skip when not in dev mode');
await page.goto('/actions/enhance/old-property-access');
const logPromise = page.waitForEvent('console');
const button = page.locator(`#${id}`);
await button.click();
await button.textContent('processed');
const log = await logPromise;
expect(log.text()).toBe(
`\`${oldName}\` has been deprecated in favor of \`${newName}\`. \`${oldName}\` will be removed in a future version. (Called from ${callLocation})`
);
expect(log.type()).toBe('warning');
});
}

test('Error props are returned', async ({ page, javaScriptEnabled }) => {
await page.goto('/actions/form-errors');
await page.click('button');
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/test/apps/dev-only/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "test-basics",
"name": "fack-off",
elliott-with-the-longest-name-on-github marked this conversation as resolved.
Show resolved Hide resolved
"private": true,
"version": "0.0.2-next.0",
"scripts": {
Expand Down
7 changes: 6 additions & 1 deletion packages/kit/types/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,19 @@ declare module '$app/forms' {
> = (input: {
action: URL;
data: FormData;
formData: FormData;
form: HTMLFormElement;
formElement: HTMLFormElement;
controller: AbortController;
cancel(): void;
submitter: HTMLElement | null;
}) => MaybePromise<
| void
| ((opts: {
data: FormData;
formData: FormData;
form: HTMLFormElement;
formElement: HTMLFormElement;
action: URL;
result: ActionResult<Success, Invalid>;
/**
Expand All @@ -108,7 +113,7 @@ declare module '$app/forms' {
Success extends Record<string, unknown> | undefined = Record<string, any>,
Invalid extends Record<string, unknown> | undefined = Record<string, any>
>(
form: HTMLFormElement,
formElement: HTMLFormElement,
/**
* Called upon submission with the given FormData and the `action` that should be triggered.
* If `cancel` is called, the form will not be submitted.
Expand Down