Skip to content

Commit

Permalink
handle url replacement in random image controller a bit better
Browse files Browse the repository at this point in the history
  • Loading branch information
progapandist committed Jun 9, 2024
1 parent fb6fb71 commit 3d1508b
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions app/javascript/controllers/random_image_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,25 @@ export default class extends Controller {

// Update the page URL with the current slug value while keeping all query parameters
const currentSlug = this.slugValue;
const currentPath = window.location.pathname.replace(
/\/works\/\w+/,
`/works/${currentSlug}`
);
const currentURL = `${currentPath}${window.location.search}${window.location.hash}`;
window.history.replaceState({}, "", currentURL);
console.log("slug value", currentSlug);

let currentPath = window.location.pathname;

if (/\/works\/\w+/.test(currentPath)) {
// If "/works/smth" is present, replace it with "/works/${currentSlug}"
currentPath = currentPath.replace(
/\/works\/\w+/,
`/works/${currentSlug}`
);
} else {
// Otherwise, prepend "/works/${currentSlug}" to the current path
currentPath = `/works/${currentSlug}${currentPath}`;
}

console.log("currentPath", currentPath);

const newURL = `${window.location.origin}${currentPath}${window.location.search}${window.location.hash}`;
window.history.replaceState({}, "", newURL);
}

handleClick(event) {
Expand Down

0 comments on commit 3d1508b

Please sign in to comment.