UNPKG

5.59 kBJavaScriptView Raw
1/**
2 * react-router v8.5.3
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { createPath, parsePath, warning } from "../router/history.js";
12import { stripBasename } from "../router/utils.js";
13const defaultEncType = "application/x-www-form-urlencoded";
14function isHtmlElement(object) {
15 return typeof HTMLElement !== "undefined" && object instanceof HTMLElement;
16}
17function isButtonElement(object) {
18 return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
19}
20function isFormElement(object) {
21 return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
22}
23function isInputElement(object) {
24 return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
25}
26function isModifiedEvent(event) {
27 return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
28}
29function shouldProcessLinkClick(event, target) {
30 let element = event.currentTarget;
31 return event.button === 0 && (!target || target === "_self") && !isModifiedEvent(event) && !((element?.localName === "a" || element?.localName === "area") && element.hasAttribute("href") && element.hasAttribute("download"));
32}
33/**
34* Creates a URLSearchParams object using the given initializer.
35*
36* This is identical to `new URLSearchParams(init)` except it also supports
37* arrays as values in the object form of the initializer instead of just
38* strings. This is convenient when you need multiple values for a given key,
39* but don't want to use an array initializer.
40*
41* @example
42* // Instead of:
43* let searchParams = new URLSearchParams([
44* ["sort", "name"],
45* ["sort", "price"],
46* ]);
47*
48* // You can do:
49* let searchParams = createSearchParams({
50* sort: ["name", "price"],
51* });
52*
53* @public
54* @category Utils
55* @param init The value used to initialize the URL search parameters.
56* @returns A URLSearchParams object containing the initialized search
57* parameters.
58*/
59function createSearchParams(init = "") {
60 return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
61 let value = init[key];
62 return memo.concat(Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]);
63 }, []));
64}
65function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
66 let searchParams = createSearchParams(locationSearch);
67 if (defaultSearchParams) defaultSearchParams.forEach((_, key) => {
68 if (!searchParams.has(key)) defaultSearchParams.getAll(key).forEach((value) => {
69 searchParams.append(key, value);
70 });
71 });
72 return searchParams;
73}
74let _formDataSupportsSubmitter = null;
75function isFormDataSubmitterSupported() {
76 if (_formDataSupportsSubmitter === null) try {
77 new FormData(document.createElement("form"), 0);
78 _formDataSupportsSubmitter = false;
79 } catch {
80 _formDataSupportsSubmitter = true;
81 }
82 return _formDataSupportsSubmitter;
83}
84const supportedFormEncTypes = new Set([
85 "application/x-www-form-urlencoded",
86 "multipart/form-data",
87 "text/plain"
88]);
89function getFormEncType(encType) {
90 encType = encType?.toLowerCase() ?? null;
91 if (encType != null && !supportedFormEncTypes.has(encType)) {
92 warning(false, `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`);
93 return null;
94 }
95 return encType;
96}
97function stripBasenameFromAction(action, basename) {
98 if (basename === "/") return action;
99 let path = parsePath(action);
100 let pathname = stripBasename(path.pathname || "", basename);
101 return pathname == null ? null : createPath({
102 ...path,
103 pathname
104 });
105}
106function getFormSubmissionInfo(target, basename) {
107 let method;
108 let action;
109 let encType;
110 let formData;
111 let body;
112 if (isFormElement(target)) {
113 let attr = target.getAttribute("action");
114 action = attr ? stripBasenameFromAction(attr, basename) : null;
115 method = target.getAttribute("method") || "get";
116 encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
117 formData = new FormData(target);
118 } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
119 let form = target.form;
120 if (form == null) throw new Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);
121 let attr = target.getAttribute("formaction") || form.getAttribute("action");
122 action = attr ? stripBasenameFromAction(attr, basename) : null;
123 method = target.getAttribute("formmethod") || form.getAttribute("method") || "get";
124 encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
125 formData = new FormData(form, target);
126 if (!isFormDataSubmitterSupported()) {
127 let { name, type, value } = target;
128 if (type === "image") {
129 let prefix = name ? `${name}.` : "";
130 formData.append(`${prefix}x`, "0");
131 formData.append(`${prefix}y`, "0");
132 } else if (name) formData.append(name, value);
133 }
134 } else if (isHtmlElement(target)) throw new Error("Cannot submit element that is not <form>, <button>, or <input type=\"submit|image\">");
135 else {
136 method = "get";
137 action = null;
138 encType = defaultEncType;
139 body = target;
140 }
141 if (formData && encType === "text/plain") {
142 body = formData;
143 formData = void 0;
144 }
145 return {
146 action,
147 method: method.toLowerCase(),
148 encType,
149 formData,
150 body
151 };
152}
153//#endregion
154export { createSearchParams, getFormSubmissionInfo, getSearchParamsForLocation, shouldProcessLinkClick };