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

Rewrite useFormAction to respect basename #23

Closed
wants to merge 2 commits into from
Closed
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
47 changes: 37 additions & 10 deletions packages/svelte/src/remix-router-svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
type AgnosticRouteMatch,
createBrowserHistory,
createHashHistory,
joinPaths,
createPath,
} from "@remix-run/router";
import { onDestroy, type SvelteComponent } from "svelte";
import { derived, get, writable, type Readable } from "svelte/store";
Expand Down Expand Up @@ -172,24 +174,49 @@ export function useMatches() {
);
}

function getPathContributingMatches(matches: DataRouteMatch[]) {
return matches.filter(
(match, index) =>
index === 0 ||
(!match.route.index &&
match.pathnameBase !== matches[index - 1].pathnameBase)
);
}

export function useFormAction(action = "."): string {
let { router } = getRouterContext();
let route = getRouteContext();
let basename = getRouterContext().router.basename;
let matches = getRouterContext().router.state.matches;
let [match] = matches.slice(-1);
let resolvedAction = action ?? ".";
let location = useLocation();
let { pathname } = get(location);

let { pathname, search, hash } = get(location);
let path = resolveTo(
action,
router.state.matches.map((match) => match.pathnameBase),
resolvedAction,
getPathContributingMatches(matches).map((match) => match.pathnameBase),
pathname
);
if (action == null) {
path.search = search;
path.hash = hash;
if (match.route.index) {
let params = new URLSearchParams(path.search);
params.delete("index");
path.search = params.toString() ? `?${params.toString()}` : "";
}
}

if ((!action || action === ".") && match.route.index) {
path.search = path.search
? path.search.replace(/^\?/, "?index&")
: "?index";
}

let search = path.search;
if (action === "." && route.index) {
search = search ? search.replace(/^\?/, "?index&") : "?index";
if (basename !== "/") {
path.pathname =
path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
}

return path.pathname + search;
return createPath(path);
}

let fetcherId = 0;
Expand Down