Fix backgrounds

This commit is contained in:
Georgi Gardev
2023-11-19 13:00:25 +02:00
parent 0c0660b9a2
commit 33da176b10
2 changed files with 11 additions and 12 deletions

View File

@@ -1,5 +1,4 @@
import { createMemo } from 'solid-js';
import { Random } from 'unsplash-js/dist/methods/photos/types';
import { getRandomBackground } from '~/api/unsplash';
import { BACKGROUND_FETCH_MINS } from '~/config';
import { sample } from '~/lib/array';
@@ -18,7 +17,7 @@ export function createBackgrounds() {
);
const shouldFetch =
!backgrounds?.backgrounds ||
!backgrounds.backgrounds ||
backgrounds.fetched_at < new Date().getTime() - 1000 * 60 * BACKGROUND_FETCH_MINS;
if (shouldFetch) {
@@ -30,22 +29,21 @@ export function createBackgrounds() {
);
}
const currentRandomBackground = createMemo<Background | undefined>(() =>
sample(backgrounds?.backgrounds ?? [])
const currentRandomBackground = createMemo<Background>(() =>
sample(backgrounds.backgrounds ?? [])
);
const isBackgroundSaved = (id?: string) =>
Boolean(id && favoriteBackgrounds.find((b) => b.id === id));
const isBackgroundSaved = (id: string) => Boolean(favoriteBackgrounds.find((b) => b.id === id));
const onUnfavoriteBackground = (id: string) =>
setFavroiteBackgrounds((prev) => prev.filter((b) => b.id !== id));
const onFavoriteBackground = () => {
setFavroiteBackgrounds((prev) => {
if (prev.find((background) => background.id === currentRandomBackground()?.id)) {
if (prev.find((background) => background.id === currentRandomBackground().id)) {
return prev;
}
return [...prev, currentRandomBackground()!];
return [...prev, currentRandomBackground()];
});
};

View File

@@ -1,4 +1,4 @@
import { Accessor, JSX, createContext, useContext } from 'solid-js';
import { Accessor, JSX, createContext, createMemo, useContext } from 'solid-js';
import { SetStoreFunction } from 'solid-js/store';
import { sample } from '~/lib/array';
import { createLocalStore } from '~/lib/create-local-store';
@@ -42,10 +42,11 @@ export function SettingsProvider(props: { children: JSX.Element }) {
onUnfavoriteBackground,
} = createBackgrounds();
const currentBackground = () =>
appSettings.useSavedBackgrounds ? sample(favoriteBackgrounds) : currentRandomBackground();
const currentBackground = createMemo(() =>
appSettings.useSavedBackgrounds ? sample(favoriteBackgrounds) : currentRandomBackground()
);
const isCurrentBackgroundSaved = () => isBackgroundSaved(currentBackground()?.id);
const isCurrentBackgroundSaved = () => isBackgroundSaved(currentBackground().id);
const onUnfavoriteCurrentBackground = () =>
currentBackground() && onUnfavoriteBackground(currentBackground()!.id);