Skip to content

Commit

Permalink
@slidy/media - use generic for better DX
Browse files Browse the repository at this point in the history
  • Loading branch information
yhdgms1 committed Aug 19, 2022
1 parent 41fcbce commit 36ecdd8
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 14 deletions.
1 change: 1 addition & 0 deletions assets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"main": "index.js",
"devDependencies": {
"@slidy/animation": "workspace:*",
"@slidy/media": "workspace:*",
"svelte": "^3.49.0"
},
"keywords": [],
Expand Down
14 changes: 7 additions & 7 deletions packages/media/src/media.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { Options, Queries } from './types';

export function media({ queries, getter, cookie }: Partial<Options>) {
const subscribers: Set<(matches: Queries) => void> = new Set();
const matches: Queries = {};
export function media<T extends string>({ queries, getter, cookie }: Partial<Options<T>>) {
const subscribers: Set<(matches: Queries<T>) => void> = new Set();
const matches = {} as Queries<T>;

if (typeof window === 'object') {
for (const query in queries) {
Expand All @@ -13,22 +13,22 @@ export function media({ queries, getter, cookie }: Partial<Options>) {
}

function set(media: MediaQueryList | MediaQueryListEvent, query: string) {
matches[query] = media.matches;
matches[query as keyof Queries<T>] = media.matches;
update(matches);
getter && getter(matches);
cookie && (document.cookie = `media=${JSON.stringify(matches)}`);
}

function update(matches: Queries) {
function update(matches: Queries<T>) {
subscribers.forEach((fn) => fn(matches));
}

function subscribe(fn: (matches: Queries) => void) {
function subscribe(fn: (matches: Queries<T>) => void) {
fn(matches);
subscribers.add(fn);
return () => unsubscribe(fn);
}
const unsubscribe = (fn: (matches: Queries) => void): boolean => subscribers.delete(fn);
const unsubscribe = (fn: (matches: Queries<T>) => void): boolean => subscribers.delete(fn);

return { matches, subscribe };
}
12 changes: 5 additions & 7 deletions packages/media/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
type Queries = {
[key: string]: boolean | string | undefined;
};
type Queries<T extends string> = Record<T, string | boolean | undefined>;

type Getter = (matches: Queries) => void;
type Getter<T extends string> = (matches: Queries<T>) => void;

interface Options {
queries: Queries;
getter: Getter;
interface Options<T extends string> {
queries: Queries<T>;
getter: Getter<T>;
cookie: boolean;
}

Expand Down

1 comment on commit 36ecdd8

@Valexr
Copy link
Owner

@Valexr Valexr commented on 36ecdd8 Aug 19, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TX 🤓 Good approach 👍🏻

Please sign in to comment.