Skip to content

Commit

Permalink
Improve-scroll-positions (#235)
Browse files Browse the repository at this point in the history
* Use origin plus pathname for saving scroll positions

* Use fuzzy search for scrolling to saved positions
  • Loading branch information
david-tejada authored Nov 11, 2023
1 parent e3f5517 commit 50d24f7
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/content/actions/customScrollPositions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Fuse from "fuse.js";
import { retrieve, store } from "../../common/storage";
import { notify } from "../notify/notify";
import { getMainScrollable, getScrollBehavior } from "./scroll";
Expand All @@ -14,11 +15,15 @@ export async function storeScrollPosition(name: string) {

const scrollPositions = await retrieve("customScrollPositions");
const scrollPositionsForCurrentPage =
scrollPositions.get(window.location.href) ?? new Map<string, number>();
scrollPositions.get(window.location.origin + window.location.pathname) ??
new Map<string, number>();

scrollPositionsForCurrentPage.set(name, scrollTop);

scrollPositions.set(window.location.href, scrollPositionsForCurrentPage);
scrollPositions.set(
window.location.origin + window.location.pathname,
scrollPositionsForCurrentPage
);
await store("customScrollPositions", scrollPositions);

await notify(`Scroll position "${name}" saved`, { type: "success" });
Expand All @@ -29,12 +34,22 @@ export async function scrollToPosition(name: string) {

const scrollPositions = await retrieve("customScrollPositions");
const scrollPositionsForCurrentPage =
scrollPositions.get(window.location.href) ?? new Map<string, number>();
scrollPositions.get(window.location.origin + window.location.pathname) ??
new Map<string, number>();

const position = scrollPositionsForCurrentPage.get(name);
const scrollPositionsArray = [...scrollPositionsForCurrentPage].map(
([name, number]) => ({ name, number })
);

const fuse = new Fuse(scrollPositionsArray, {
keys: ["name"],
});

const results = fuse.search(name);
const position = results[0]?.item.number;

if (!position) {
await notify(`No scroll position saved for "${name}"`, { type: "error" });
await notify(`No scroll position matching "${name}"`, { type: "error" });
return;
}

Expand Down

0 comments on commit 50d24f7

Please sign in to comment.