Move core files into new folder

This commit is contained in:
schroda
2024-10-05 16:09:34 +02:00
parent 996bb62888
commit 23a86a77f0
173 changed files with 514 additions and 481 deletions

View File

@@ -1,61 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
// eslint-disable-next-line max-classes-per-file
export class Storage {
constructor(private readonly storage: typeof window.localStorage) {}
parseValue<T>(value: string | null, defaultValue: T): T {
if (value === null) {
return defaultValue;
}
return JSON.parse(value);
}
getItem(key: string): string | null {
return this.storage.getItem(key);
}
getItemParsed<T>(key: string, defaultValue: T): T {
return this.parseValue(this.getItem(key), defaultValue);
}
setItem(key: string, value: unknown, emitEvent: boolean = true): void {
const fireEvent = (valueToStore: string | undefined) => {
if (!emitEvent) {
return;
}
window.dispatchEvent(
new StorageEvent('storage', {
key,
oldValue: this.getItem(key),
newValue: valueToStore,
}),
);
};
if (value === undefined) {
this.storage.removeItem(key);
fireEvent(undefined);
return;
}
const valueToStore = JSON.stringify(value);
this.storage.setItem(key, valueToStore);
fireEvent(valueToStore);
}
}
export class AppStorage {
static readonly local: Storage = new Storage(window.localStorage);
static readonly session: Storage = new Storage(window.sessionStorage);
}

View File

@@ -1,87 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { Component, ErrorInfo, ReactNode, useEffect, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
interface Props {
children?: ReactNode;
setTrackPathChange: (change: boolean) => void;
}
interface State {
error: any;
}
class RealErrorBoundary extends Component<Props, State> {
// eslint-disable-next-line react/state-in-constructor
public state: State = { error: null };
private prevPath: string = '';
public static getDerivedStateFromError(error: any): State {
// Update state so the next render will show the fallback UI.
return { error };
}
componentDidMount() {
this.prevPath = window.location.pathname;
}
public componentDidUpdate() {
if (window.location.pathname !== this.prevPath) {
this.setState({ error: null });
}
this.prevPath = window.location.pathname;
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// eslint-disable-next-line
console.error('Uncaught error:', error, errorInfo);
// eslint-disable-next-line react/destructuring-assignment
this.props.setTrackPathChange(true);
}
public render() {
const { error } = this.state;
if (error) {
return (
<>
<h1>Something went wrong.</h1>
<p>{error.message ?? JSON.stringify(error)}</p>
</>
);
}
const { children } = this.props;
return children;
}
}
export const ErrorBoundary = ({ children }: { children: React.ReactNode }) => {
const [key, setKey] = useState(0);
const { pathname } = useLocation();
const previousPathnameRef = useRef(pathname);
const [trackPathChange, setTrackPathChange] = useState(false);
useEffect(() => {
if (trackPathChange && previousPathnameRef.current !== pathname) {
previousPathnameRef.current = pathname;
setKey((currentKey) => (currentKey + 1) % 999999);
setTrackPathChange(false);
}
}, [pathname, previousPathnameRef.current, trackPathChange]);
return (
<RealErrorBoundary key={key} setTrackPathChange={setTrackPathChange}>
{children}
</RealErrorBoundary>
);
};

View File

@@ -1,15 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
export const jsonSaveParse = <T = any>(...args: Parameters<typeof JSON.parse>): T | null => {
try {
return JSON.parse(...args);
} catch (e) {
return null;
}
};

View File

@@ -1,11 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { LoadingPlaceholder } from '@/components/util/LoadingPlaceholder.tsx';
export const lazyLoadFallback = { fallback: <LoadingPlaceholder /> };

View File

@@ -1,16 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
export const defaultPromiseErrorHandler = (name: string) => (error: any) => {
if (process.env.NODE_ENV === 'production') {
return;
}
// eslint-disable-next-line no-console
console.error(`${name} failed due to`, error);
};

View File

@@ -1,802 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { I18nResourceCode } from '@/i18n';
export type ISOLanguage = {
name: string;
nativeName: string;
};
// full list: https://github.com/meikidd/iso-639-1/blob/master/src/data.js
export const ISOLanguages: { [languageCode in I18nResourceCode]: ISOLanguage } & Record<string, ISOLanguage> = {
// #############################
// ### ###
// ### START: manually added ###
// ### ###
// #############################
'es-419': {
name: 'Spanish; Castilian',
nativeName: 'Español',
},
'pt-pt': {
name: 'Portuguese',
nativeName: 'Português (Portugal)',
},
'pt-br': {
name: 'Portuguese; Brasil',
nativeName: 'Português (Brasil)',
},
zh_Hans: {
name: 'Chinese (Simplified)',
nativeName: '中文 (HANS)',
},
zh_Hant: {
name: 'Chinese (Traditional)',
nativeName: '中文 (HANT)',
},
'zh-rhk': {
name: 'Chinese',
nativeName: '中文 (RHK)',
},
'zh-rtw': {
name: 'Chinese',
nativeName: '中文 (RTW)',
},
fil: {
name: 'Filipino',
nativeName: 'Filipino',
},
sh: {
name: 'Serbo-Croatian',
nativeName: 'srpskohrvatski',
},
'nb-NO': {
name: 'Norwegian Bokmål',
nativeName: 'Norsk bokmål',
},
// #############################
// ### ###
// ### END: manually added ###
// ### ###
// #############################
aa: {
name: 'Afar',
nativeName: 'Afaraf',
},
ab: {
name: 'Abkhaz',
nativeName: 'аҧсуа бызшәа',
},
ae: {
name: 'Avestan',
nativeName: 'avesta',
},
af: {
name: 'Afrikaans',
nativeName: 'Afrikaans',
},
ak: {
name: 'Akan',
nativeName: 'Akan',
},
am: {
name: 'Amharic',
nativeName: 'አማርኛ',
},
an: {
name: 'Aragonese',
nativeName: 'aragonés',
},
ar: {
name: 'Arabic',
nativeName: 'اَلْعَرَبِيَّةُ',
},
as: {
name: 'Assamese',
nativeName: 'অসমীয়া',
},
av: {
name: 'Avaric',
nativeName: 'авар мацӀ',
},
ay: {
name: 'Aymara',
nativeName: 'aymar aru',
},
az: {
name: 'Azerbaijani',
nativeName: 'azərbaycan dili',
},
ba: {
name: 'Bashkir',
nativeName: 'башҡорт теле',
},
be: {
name: 'Belarusian',
nativeName: 'беларуская мова',
},
bg: {
name: 'Bulgarian',
nativeName: 'български език',
},
bi: {
name: 'Bislama',
nativeName: 'Bislama',
},
bm: {
name: 'Bambara',
nativeName: 'bamanankan',
},
bn: {
name: 'Bengali',
nativeName: 'বাংলা',
},
bo: {
name: 'Tibetan',
nativeName: 'བོད་ཡིག',
},
br: {
name: 'Breton',
nativeName: 'brezhoneg',
},
bs: {
name: 'Bosnian',
nativeName: 'bosanski jezik',
},
ca: {
name: 'Catalan',
nativeName: 'Català',
},
ce: {
name: 'Chechen',
nativeName: 'нохчийн мотт',
},
ch: {
name: 'Chamorro',
nativeName: 'Chamoru',
},
co: {
name: 'Corsican',
nativeName: 'corsu',
},
cr: {
name: 'Cree',
nativeName: 'ᓀᐦᐃᔭᐍᐏᐣ',
},
cs: {
name: 'Czech',
nativeName: 'čeština',
},
cu: {
name: 'Old Church Slavonic',
nativeName: 'ѩзыкъ словѣньскъ',
},
cv: {
name: 'Chuvash',
nativeName: 'чӑваш чӗлхи',
},
cy: {
name: 'Welsh',
nativeName: 'Cymraeg',
},
da: {
name: 'Danish',
nativeName: 'Dansk',
},
de: {
name: 'German',
nativeName: 'Deutsch',
},
dv: {
name: 'Divehi',
nativeName: 'ދިވެހި',
},
dz: {
name: 'Dzongkha',
nativeName: 'རྫོང་ཁ',
},
ee: {
name: 'Ewe',
nativeName: 'Eʋegbe',
},
el: {
name: 'Greek',
nativeName: 'Ελληνικά',
},
en: {
name: 'English',
nativeName: 'English',
},
eo: {
name: 'Esperanto',
nativeName: 'Esperanto',
},
es: {
name: 'Spanish',
nativeName: 'Español',
},
et: {
name: 'Estonian',
nativeName: 'eesti',
},
eu: {
name: 'Basque',
nativeName: 'euskara',
},
fa: {
name: 'Persian',
nativeName: 'فارسی',
},
ff: {
name: 'Fula',
nativeName: 'Fulfulde',
},
fi: {
name: 'Finnish',
nativeName: 'suomi',
},
fj: {
name: 'Fijian',
nativeName: 'vosa Vakaviti',
},
fo: {
name: 'Faroese',
nativeName: 'Føroyskt',
},
fr: {
name: 'French',
nativeName: 'Français',
},
fy: {
name: 'Western Frisian',
nativeName: 'Frysk',
},
ga: {
name: 'Irish',
nativeName: 'Gaeilge',
},
gd: {
name: 'Scottish Gaelic',
nativeName: 'Gàidhlig',
},
gl: {
name: 'Galician',
nativeName: 'galego',
},
gn: {
name: 'Guaraní',
nativeName: "Avañe'ẽ",
},
gu: {
name: 'Gujarati',
nativeName: 'ગુજરાતી',
},
gv: {
name: 'Manx',
nativeName: 'Gaelg',
},
ha: {
name: 'Hausa',
nativeName: 'هَوُسَ',
},
he: {
name: 'Hebrew',
nativeName: 'עברית',
},
hi: {
name: 'Hindi',
nativeName: 'हिन्दी',
},
ho: {
name: 'Hiri Motu',
nativeName: 'Hiri Motu',
},
hr: {
name: 'Croatian',
nativeName: 'Hrvatski',
},
ht: {
name: 'Haitian',
nativeName: 'Kreyòl ayisyen',
},
hu: {
name: 'Hungarian',
nativeName: 'magyar',
},
hy: {
name: 'Armenian',
nativeName: 'Հայերեն',
},
hz: {
name: 'Herero',
nativeName: 'Otjiherero',
},
ia: {
name: 'Interlingua',
nativeName: 'Interlingua',
},
id: {
name: 'Indonesian',
nativeName: 'Bahasa Indonesia',
},
ie: {
name: 'Interlingue',
nativeName: 'Interlingue',
},
ig: {
name: 'Igbo',
nativeName: 'Asụsụ Igbo',
},
ii: {
name: 'Nuosu',
nativeName: 'ꆈꌠ꒿ Nuosuhxop',
},
ik: {
name: 'Inupiaq',
nativeName: 'Iñupiaq',
},
io: {
name: 'Ido',
nativeName: 'Ido',
},
is: {
name: 'Icelandic',
nativeName: 'Íslenska',
},
it: {
name: 'Italian',
nativeName: 'Italiano',
},
iu: {
name: 'Inuktitut',
nativeName: 'ᐃᓄᒃᑎᑐᑦ',
},
ja: {
name: 'Japanese',
nativeName: '日本語',
},
jv: {
name: 'Javanese',
nativeName: 'basa Jawa',
},
ka: {
name: 'Georgian',
nativeName: 'ქართული',
},
kg: {
name: 'Kongo',
nativeName: 'Kikongo',
},
ki: {
name: 'Kikuyu',
nativeName: 'Gĩkũyũ',
},
kj: {
name: 'Kwanyama',
nativeName: 'Kuanyama',
},
kk: {
name: 'Kazakh',
nativeName: 'қазақ тілі',
},
kl: {
name: 'Kalaallisut',
nativeName: 'kalaallisut',
},
km: {
name: 'Khmer',
nativeName: 'ខេមរភាសា',
},
kn: {
name: 'Kannada',
nativeName: 'ಕನ್ನಡ',
},
ko: {
name: 'Korean',
nativeName: '한국어',
},
kr: {
name: 'Kanuri',
nativeName: 'Kanuri',
},
ks: {
name: 'Kashmiri',
nativeName: 'कश्मीरी',
},
ku: {
name: 'Kurdish',
nativeName: 'Kurdî',
},
kv: {
name: 'Komi',
nativeName: 'коми кыв',
},
kw: {
name: 'Cornish',
nativeName: 'Kernewek',
},
ky: {
name: 'Kyrgyz',
nativeName: 'Кыргызча',
},
la: {
name: 'Latin',
nativeName: 'latine',
},
lb: {
name: 'Luxembourgish',
nativeName: 'Lëtzebuergesch',
},
lg: {
name: 'Ganda',
nativeName: 'Luganda',
},
li: {
name: 'Limburgish',
nativeName: 'Limburgs',
},
ln: {
name: 'Lingala',
nativeName: 'Lingála',
},
lo: {
name: 'Lao',
nativeName: 'ພາສາລາວ',
},
lt: {
name: 'Lithuanian',
nativeName: 'lietuvių kalba',
},
lu: {
name: 'Luba-Katanga',
nativeName: 'Kiluba',
},
lv: {
name: 'Latvian',
nativeName: 'latviešu valoda',
},
mg: {
name: 'Malagasy',
nativeName: 'fiteny malagasy',
},
mh: {
name: 'Marshallese',
nativeName: 'Kajin M̧ajeļ',
},
mi: {
name: 'Māori',
nativeName: 'te reo Māori',
},
mk: {
name: 'Macedonian',
nativeName: 'македонски јазик',
},
ml: {
name: 'Malayalam',
nativeName: 'മലയാളം',
},
mn: {
name: 'Mongolian',
nativeName: 'Монгол хэл',
},
mr: {
name: 'Marathi',
nativeName: 'मराठी',
},
ms: {
name: 'Malay',
nativeName: 'Bahasa Melayu',
},
mt: {
name: 'Maltese',
nativeName: 'Malti',
},
my: {
name: 'Burmese',
nativeName: 'ဗမာစာ',
},
na: {
name: 'Nauru',
nativeName: 'Dorerin Naoero',
},
nb: {
name: 'Norwegian Bokmål',
nativeName: 'Norsk bokmål',
},
nd: {
name: 'Northern Ndebele',
nativeName: 'isiNdebele',
},
ne: {
name: 'Nepali',
nativeName: 'नेपाली',
},
ng: {
name: 'Ndonga',
nativeName: 'Owambo',
},
nl: {
name: 'Dutch',
nativeName: 'Nederlands',
},
nn: {
name: 'Norwegian Nynorsk',
nativeName: 'Norsk nynorsk',
},
no: {
name: 'Norwegian',
nativeName: 'Norsk',
},
nr: {
name: 'Southern Ndebele',
nativeName: 'isiNdebele',
},
nv: {
name: 'Navajo',
nativeName: 'Diné bizaad',
},
ny: {
name: 'Chichewa',
nativeName: 'chiCheŵa',
},
oc: {
name: 'Occitan',
nativeName: 'occitan',
},
oj: {
name: 'Ojibwe',
nativeName: 'ᐊᓂᔑᓈᐯᒧᐎᓐ',
},
om: {
name: 'Oromo',
nativeName: 'Afaan Oromoo',
},
or: {
name: 'Oriya',
nativeName: 'ଓଡ଼ିଆ',
},
os: {
name: 'Ossetian',
nativeName: 'ирон æвзаг',
},
pa: {
name: 'Panjabi',
nativeName: 'ਪੰਜਾਬੀ',
},
pi: {
name: 'Pāli',
nativeName: 'पाऴि',
},
pl: {
name: 'Polish',
nativeName: 'Polski',
},
ps: {
name: 'Pashto',
nativeName: 'پښتو',
},
pt: {
name: 'Portuguese',
nativeName: 'Português',
},
qu: {
name: 'Quechua',
nativeName: 'Runa Simi',
// asdfasdfasdfasdf
},
rm: {
name: 'Romansh',
nativeName: 'rumantsch grischun',
},
rn: {
name: 'Kirundi',
nativeName: 'Ikirundi',
},
ro: {
name: 'Romanian',
nativeName: 'Română',
},
ru: {
name: 'Russian',
nativeName: 'Русский',
},
rw: {
name: 'Kinyarwanda',
nativeName: 'Ikinyarwanda',
},
sa: {
name: 'Sanskrit',
nativeName: 'संस्कृतम्',
},
sc: {
name: 'Sardinian',
nativeName: 'sardu',
},
sd: {
name: 'Sindhi',
nativeName: 'सिन्धी',
},
se: {
name: 'Northern Sami',
nativeName: 'Davvisámegiella',
},
sg: {
name: 'Sango',
nativeName: 'yângâ tî sängö',
},
si: {
name: 'Sinhala',
nativeName: 'සිංහල',
},
sk: {
name: 'Slovak',
nativeName: 'slovenčina',
},
sl: {
name: 'Slovenian',
nativeName: 'slovenščina',
},
sm: {
name: 'Samoan',
nativeName: "gagana fa'a Samoa",
},
sn: {
name: 'Shona',
nativeName: 'chiShona',
},
so: {
name: 'Somali',
nativeName: 'Soomaaliga',
},
sq: {
name: 'Albanian',
nativeName: 'Shqip',
},
sr: {
name: 'Serbian',
nativeName: 'српски језик',
},
ss: {
name: 'Swati',
nativeName: 'SiSwati',
},
st: {
name: 'Southern Sotho',
nativeName: 'Sesotho',
},
su: {
name: 'Sundanese',
nativeName: 'Basa Sunda',
},
sv: {
name: 'Swedish',
nativeName: 'Svenska',
},
sw: {
name: 'Swahili',
nativeName: 'Kiswahili',
},
ta: {
name: 'Tamil',
nativeName: 'தமிழ்',
},
te: {
name: 'Telugu',
nativeName: 'తెలుగు',
},
tg: {
name: 'Tajik',
nativeName: 'тоҷикӣ',
},
th: {
name: 'Thai',
nativeName: 'ไทย',
},
ti: {
name: 'Tigrinya',
nativeName: 'ትግርኛ',
},
tk: {
name: 'Turkmen',
nativeName: 'Türkmençe',
},
tl: {
name: 'Tagalog',
nativeName: 'Wikang Tagalog',
},
tn: {
name: 'Tswana',
nativeName: 'Setswana',
},
to: {
name: 'Tonga',
nativeName: 'faka Tonga',
},
tr: {
name: 'Turkish',
nativeName: 'Türkçe',
},
ts: {
name: 'Tsonga',
nativeName: 'Xitsonga',
},
tt: {
name: 'Tatar',
nativeName: 'татар теле',
},
tw: {
name: 'Twi',
nativeName: 'Twi',
},
ty: {
name: 'Tahitian',
nativeName: 'Reo Tahiti',
},
ug: {
name: 'Uyghur',
nativeName: 'ئۇيغۇرچە‎',
},
uk: {
name: 'Ukrainian',
nativeName: 'Українська',
},
ur: {
name: 'Urdu',
nativeName: 'اردو',
},
uz: {
name: 'Uzbek',
nativeName: 'Ўзбек',
},
ve: {
name: 'Venda',
nativeName: 'Tshivenḓa',
},
vi: {
name: 'Vietnamese',
nativeName: 'Tiếng Việt',
},
vo: {
name: 'Volapük',
nativeName: 'Volapük',
},
wa: {
name: 'Walloon',
nativeName: 'walon',
},
wo: {
name: 'Wolof',
nativeName: 'Wollof',
},
xh: {
name: 'Xhosa',
nativeName: 'isiXhosa',
},
yi: {
name: 'Yiddish',
nativeName: 'ייִדיש',
},
yo: {
name: 'Yoruba',
nativeName: 'Yorùbá',
},
za: {
name: 'Zhuang',
nativeName: 'Saɯ cueŋƅ',
},
zh: {
name: 'Chinese',
nativeName: '中文',
},
zu: {
name: 'Zulu',
nativeName: 'isiZulu',
},
};

View File

@@ -1,78 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { t } from 'i18next';
import { ISOLanguage, ISOLanguages } from '@/util/isoLanguages.ts';
export enum DefaultLanguage {
ALL = 'all',
OTHER = 'other',
LOCAL_SOURCE = 'localsourcelang',
}
function getISOLanguage(code: string): ISOLanguage | null {
if (ISOLanguages[code]) {
return ISOLanguages[code];
}
if (ISOLanguages[code.toLocaleLowerCase()]) {
return ISOLanguages[code.toLocaleLowerCase()];
}
const whereToCut = code.indexOf('-') !== -1 ? code.indexOf('-') : code.length;
const processedCode = code.toLocaleLowerCase().substring(0, whereToCut);
if (ISOLanguages[processedCode]) {
return ISOLanguages[processedCode];
}
return null;
}
export function getLanguage(code: string): { name: string; nativeName: string } {
const isoLanguage = getISOLanguage(code);
if (isoLanguage) {
return isoLanguage;
}
return {
name: t('global.language.label.language_with_code', { code }),
nativeName: t('global.language.label.language_with_code', { code }),
};
}
export function langCodeToName(code: string): string {
return getLanguage(code).nativeName;
}
function defaultNativeLang() {
return 'en'; // TODO: infer from the browser
}
export function extensionDefaultLangs() {
return [defaultNativeLang(), DefaultLanguage.ALL];
}
export function sourceDefualtLangs() {
return [defaultNativeLang(), DefaultLanguage.LOCAL_SOURCE];
}
export function sourceForcedDefaultLangs(): string[] {
return [DefaultLanguage.LOCAL_SOURCE];
}
export const langSortCmp = (a: string, b: string) => {
// puts english first for convience
const aLang = langCodeToName(a);
const bLang = langCodeToName(b);
if (a === 'en') return -1;
if (b === 'en') return 1;
return aLang.localeCompare(bLang);
};

View File

@@ -1,30 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useLocation, useNavigate } from 'react-router-dom';
import { useContext } from 'react';
import { NavBarContext } from '@/components/context/NavbarContext.tsx';
export const useBackButton = () => {
const navigate = useNavigate();
const location = useLocation();
const { history } = useContext(NavBarContext);
return () => {
const isHistoryEmpty = !history.length;
const isLastPageInHistoryCurrentPage = history.length === 1 && history[0] === location.pathname;
const canNavigateBack = !isHistoryEmpty && !isLastPageInHistoryCurrentPage;
if (canNavigateBack) {
navigate(-1);
return;
}
navigate('/library');
};
};

View File

@@ -1,25 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useEffect, useState } from 'react';
export const useDebounce = <Value>(value: Value, delay: number): Value => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};

View File

@@ -1,53 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useCallback, useEffect, useState } from 'react';
import { NavigationType, useLocation, useNavigationType } from 'react-router-dom';
const MAX_DEPTH = 50;
export const useHistory = () => {
const location = useLocation();
const navigationType = useNavigationType();
const [history, setHistory] = useState<string[]>([location.pathname]);
const updateHistory = useCallback((newHistory: string[]) => {
// prevent the history from getting too large (only relevant in case the app never gets reloaded (e.g. browser F5,
// electron window gets closed))
// theoretically the history should be empty for the "base" pages (e.g. library, updates, ...), but since the browser
// navigation is used, opening another base page pushes this page to this history, as if it had a different depth
// than the current page (expected history: library -> manga -> reader,
// possible history: library -> updates -> settings -> library -> manga -> reader)
setHistory(newHistory.slice(-MAX_DEPTH));
}, []);
useEffect(() => {
const isLastPageInHistory = location.key === 'default';
const ignoreInitialPop = isLastPageInHistory && history.length === 1;
if (ignoreInitialPop) {
return;
}
switch (navigationType) {
case NavigationType.Pop:
updateHistory([...history.slice(0, -1)]);
break;
case NavigationType.Push:
updateHistory([...history, location.pathname + location.search]);
break;
case NavigationType.Replace:
updateHistory([...history.slice(0, -1), location.pathname + location.search]);
break;
default:
throw new Error(`Unexpected NavigationType "${navigationType}"`);
}
}, [location]);
return history;
};

View File

@@ -1,31 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useLocalStorage } from '@/util/useStorage.tsx';
export const getPersistedServerSetting = <T,>(serverValue: T | undefined, lastValue: T): T => {
const isDisabled = serverValue === 0;
if (isDisabled) {
return lastValue;
}
return serverValue ?? lastValue;
};
export const usePersistedValue = <T,>(
key: string,
defaultValue: T,
currentValue: T | undefined,
getCurrentValue: (currentValue: T | undefined, persistedValue: T) => T,
): [T, (value: T) => void] => {
const [persistedValue, setPersistedValue] = useLocalStorage(key, defaultValue);
const value = getCurrentValue(currentValue, persistedValue);
return [value, setPersistedValue];
};

View File

@@ -1,33 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { RefObject, useLayoutEffect, useState } from 'react';
export const useResizeObserver = (
ref: RefObject<HTMLElement> | HTMLElement | undefined | null,
callback: ResizeObserverCallback,
): (() => void) => {
const [disconnect, setDisconnect] = useState<() => void>(() => {});
useLayoutEffect(() => {
const element = ref instanceof HTMLElement ? ref : ref?.current;
if (!element) {
return () => {};
}
const resizeObserver = new ResizeObserver(callback);
resizeObserver.observe(element);
setDisconnect(() => () => resizeObserver.disconnect());
return () => resizeObserver.disconnect();
}, [ref, callback]);
return disconnect;
};

View File

@@ -1,88 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { Dispatch, Reducer, SetStateAction, useCallback, useMemo, useReducer, useSyncExternalStore } from 'react';
import { AppStorage, Storage } from '@/util/AppStorage.ts';
const subscribeToStorageUpdates = (callback: () => void) => {
window.addEventListener('storage', callback);
return () => window.removeEventListener('storage', callback);
};
function useStorage<T>(storage: Storage, key: string, defaultValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>];
function useStorage<T = undefined>(
storage: Storage,
key: string,
): [T | undefined, Dispatch<SetStateAction<T | undefined>>];
function useStorage<T>(
storage: Storage,
key: string,
defaultValue?: T | (() => T) | undefined,
): [T | undefined, Dispatch<SetStateAction<T | undefined>>] {
const initialState = defaultValue instanceof Function ? defaultValue() : defaultValue;
const storedValueRaw = useSyncExternalStore(subscribeToStorageUpdates, () => storage.getItem(key));
const setValue = useCallback<React.Dispatch<React.SetStateAction<T | undefined>>>(
(value) => {
// Allow value to be a function so we have same API as useState
const valueToStore = value instanceof Function ? value(storage.getItemParsed(key, initialState)) : value;
storage.setItem(key, valueToStore);
},
[key],
);
const storedValue = useMemo(
() => (storedValueRaw !== null ? JSON.parse(storedValueRaw) : initialState),
[storedValueRaw, key],
);
return [storedValue, setValue];
}
const useReducerStorage = <S, A>(
storage: Storage,
reducer: Reducer<S, A>,
key: string,
defaultState: S | (() => S),
) => {
const [storedValue, setValue] = useStorage(storage, key, defaultState);
return useReducer((state: S, action: A): S => {
const newState = reducer(state, action);
setValue(newState);
return newState;
}, storedValue);
};
export function useLocalStorage<T>(key: string, defaultValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>];
export function useLocalStorage<T = undefined>(key: string): [T | undefined, Dispatch<SetStateAction<T | undefined>>];
export function useLocalStorage<T>(
key: string,
defaultValue?: T | undefined | (() => T | undefined),
): [T | undefined, Dispatch<SetStateAction<T | undefined>>] {
return useStorage(AppStorage.local, key, defaultValue);
}
export function useReducerLocalStorage<S, A>(reducer: Reducer<S, A>, key: string, defaultState: S | (() => S)) {
return useReducerStorage(AppStorage.local, reducer, key, defaultState);
}
export function useSessionStorage<T>(key: string, defaultValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>];
export function useSessionStorage<T = undefined>(key: string): [T | undefined, Dispatch<SetStateAction<T | undefined>>];
export function useSessionStorage<T>(
key: string,
defaultValue?: T | (() => T),
): [T | undefined, Dispatch<SetStateAction<T | undefined>>] {
return useStorage(AppStorage.session, key, defaultValue);
}
export function useReducerSessionStorage<S, A>(reducer: Reducer<S, A>, key: string, defaultState: S | (() => S)) {
return useReducerStorage(AppStorage.session, reducer, key, defaultState);
}

View File

@@ -7,8 +7,8 @@
*/
import { useCallback, useEffect, useMemo } from 'react';
import { defaultPromiseErrorHandler } from '@/util/defaultPromiseErrorHandler.ts';
import { useLocalStorage } from '@/util/useStorage.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { useLocalStorage } from '@/modules/core/hooks/useStorage.tsx';
const UPDATE_CHECK_INTERVAL = 1000 * 60 * 60; // 1 hour
const UPDATE_REMINDER_THRESHOLD = 1000 * 60 * 60; // 1 hour