Skip to content

Commit

Permalink
feat: use svelte-hash
Browse files Browse the repository at this point in the history
  • Loading branch information
Bellisario committed Jul 1, 2024
1 parent 30b8db0 commit 87ce4b9
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 59 deletions.
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"postcss-logical": "^7.0.1",
"svelte": "^4.2.18",
"svelte-check": "^3.8.4",
"svelte-hash": "^1.0.1",
"svelte-preprocess": "^6.0.1",
"tslib": "^2.6.3",
"typescript": "^5.5.2",
Expand Down
65 changes: 6 additions & 59 deletions src/lib/player.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { derived, get, writable } from 'svelte/store';
import { derived, writable } from 'svelte/store';
import type { FavoriteStore } from '$types/FavoritesStore';
import { type MenuEntry } from '$types/MenuEntry';

import { createHashStore } from 'svelte-hash';

export const duration = writable(0);
export const currentTime = writable(0);
export const paused = writable(true);
Expand Down Expand Up @@ -92,63 +94,8 @@ export function shuffle<T>(array: T[]): T[] {
return newArray;
}


// ------------------------------------------------------------
// HASH Management
// ------------------------------------------------------------

interface Hash {
search?: string;
album?: string;
[key: string]: string | undefined;
}

export const hash = writable<Hash>(loadHash());

function updateHash() {

const hashValues = get(hash);

// if hash is set to an empty object, remove it
if (Object.keys(hashValues).length === 0) return window.history.pushState(null, '', '#');

const urlHash = new URLSearchParams(window.location.hash.slice(1));

// get keys
Object.keys(hashValues).forEach((key) => {
// get value
const value = hashValues[key];

// if value is empty, return
if (!value) return urlHash.delete(key);

// set value
urlHash.set(key, value);
});

if (window.location.hash.slice(1) === urlHash.toString()) return;

// set hash
window.history.pushState(null, '', `#${urlHash.toString()}`);
}

function loadHash() {
const urlHash = new URLSearchParams(window.location.hash.slice(1));

const hashValues: Hash = {};

// get keys
urlHash.forEach((value, key) => {
// set value
hashValues[key] = value;
});

return hashValues;
search: string;
album: string;
}

hash.subscribe(updateHash);

// listen for history changes
window.addEventListener('popstate', () => {
hash.set(loadHash());
});
export const hash = createHashStore<Hash>();

0 comments on commit 87ce4b9

Please sign in to comment.