Reader hotkeys

This commit is contained in:
schroda
2024-11-03 03:09:00 +01:00
parent 0ae9d9ebb2
commit 0b1c67ce9f
26 changed files with 781 additions and 31 deletions

View File

@@ -58,6 +58,7 @@
"react": "18.3.1",
"react-beautiful-dnd": "13.1.1",
"react-dom": "18.3.1",
"react-hotkeys-hook": "^4.6.1",
"react-i18next": "15.0.1",
"react-lazily": "0.9.2",
"react-router-dom": "6.26.1",

View File

@@ -496,6 +496,23 @@
},
"value": "{{value}}{{unit}}"
},
"hotkeys": {
"create": {
"dialog": {
"label": "Recorded keys: <Keys/>",
"placeholder": "Press keys",
"title": "Record keybind"
},
"error": {
"exists": "Hotkey already exists"
}
},
"info": {
"delete": "Click key to remove binding"
},
"title_one": "Keybind",
"title_other": "Keybinds"
},
"library": {
"action": {
"label": {
@@ -838,6 +855,18 @@
}
},
"exit_mode": "Open page on exit",
"hotkey": {
"menu": "Toggle menu",
"next_chapter": "Next chapter",
"next_page": "Next page",
"offset_spread_pages": "Toggle offset spread pages",
"previous_chapter": "Previous chapter",
"previous_page": "Previous page",
"scale_type": "Cycle image scale type",
"scroll_backward": "Scroll backward",
"scroll_forward": "Scroll forward",
"stretch_image": "Toggle stretch image"
},
"label": {
"behaviour": "Behaviour",
"fit_page_to_window": "Fit page to window",

View File

@@ -47,3 +47,13 @@ export interface MultiValueButtonDefaultableProps<Value extends string | number>
export type MultiValueButtonProps<Value extends string | number> =
| (MultiValueButtonBaseProps<Value> & PropertiesNever<MultiValueButtonDefaultableProps<Value>>)
| MultiValueButtonDefaultableProps<Value>;
export enum ScrollOffset {
BACKWARD,
FORWARD,
}
export enum ScrollDirection {
X,
Y,
}

View File

@@ -0,0 +1,23 @@
/*
* 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 { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
export const Kbd = styled(Typography)(({ theme }) => ({
display: 'inline-block',
padding: '0.2em 0.4em',
fontSize: '0.85em',
lineHeight: '1.4',
color: theme.palette.text.primary,
backgroundColor: theme.palette.background.paper,
border: `1px solid ${theme.palette.divider}`,
borderRadius: '3px',
boxShadow: `inset 0 -1px 0 ${theme.palette.divider}`,
fontFamily: 'monospace, monospace',
}));

View File

@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import { ReactNode, useMemo } from 'react';
import Button from '@mui/material/Button';
import { MultiValueButtonProps } from '@/modules/core/Core.types.ts';
import { getNextRotationValue } from '@/modules/core/utils/ValueRotationButton.utils.ts';
export const ValueRotationButton = <Value extends string | number>({
value,
@@ -48,16 +49,14 @@ export const ValueRotationButton = <Value extends string | number>({
return (
<Button
onClick={() => {
const nextValueIndex = (indexOfValue + 1) % values.length;
const wasLastValue = nextValueIndex === 0;
const nextValue = getNextRotationValue(indexOfValue, values, isDefaultable);
const isDefaultNextValue = isDefaultable && wasLastValue;
if (isDefaultNextValue) {
if (nextValue === undefined) {
onDefault?.();
return;
}
setValue(values[(indexOfValue + 1) % values.length]);
setValue(nextValue);
}}
sx={{ justifyContent: 'start', textTransform: 'unset', flexGrow: 1 }}
variant="contained"

View File

@@ -25,6 +25,7 @@ import { AppThemes, getTheme } from '@/modules/theme/services/AppThemes.ts';
import { useMetadataServerSettings } from '@/modules/settings/services/ServerSettingsMetadata.ts';
import { ReaderContextProvider } from '@/modules/reader/contexts/ReaderContextProvider.tsx';
import { DIRECTION_TO_CACHE } from '@/modules/theme/ThemeDirectionCache.ts';
import { AppHotkeysProvider } from '@/modules/hotkeys/contexts/AppHotkeysProvider.tsx';
interface Props {
children: React.ReactNode;
@@ -84,7 +85,9 @@ export const AppContext: React.FC<Props> = ({ children }) => {
<NavBarContextProvider>
<ActiveDeviceContextProvider>
<SnackbarProvider>
<ReaderContextProvider>{children}</ReaderContextProvider>
<ReaderContextProvider>
<AppHotkeysProvider>{children}</AppHotkeysProvider>
</ReaderContextProvider>
</SnackbarProvider>
</ActiveDeviceContextProvider>
</NavBarContextProvider>

View File

@@ -0,0 +1,23 @@
/*
* 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 getNextRotationValue = <Value>(
indexOfValue: number,
values: Value[],
isDefaultable?: boolean,
): Value | undefined => {
const nextValueIndex = (indexOfValue + 1) % values.length;
const wasLastValue = nextValueIndex === 0;
const isDefaultNextValue = !!isDefaultable && wasLastValue;
if (isDefaultNextValue) {
return undefined;
}
return values[(indexOfValue + 1) % values.length];
};

View File

@@ -0,0 +1,13 @@
/*
* 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 { HotkeyScope } from '@/modules/hotkeys/Hotkeys.types.ts';
export const HOTKEY_SCOPES = Object.fromEntries(
Object.values(HotkeyScope).map((scope) => [scope, { scopes: scope }]),
) as Record<HotkeyScope, { scopes: string }>;

View File

@@ -0,0 +1,14 @@
/*
* 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 enum HotkeyScope {
NONE = 'none',
GLOBAL = 'global',
MAIN_APP = 'main_app',
READER = 'reader',
}

View File

@@ -0,0 +1,26 @@
/*
* 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';
import { useHotkeysContext } from 'react-hotkeys-hook';
import { HotkeyScope } from '@/modules/hotkeys/Hotkeys.types.ts';
export const useDisableAllHotkeysWhileMounted = () => {
const { enabledScopes, enableScope, disableScope } = useHotkeysContext();
const [previouslyEnabledScopes] = useState(enabledScopes);
useEffect(() => {
enableScope(HotkeyScope.NONE);
previouslyEnabledScopes.forEach(disableScope);
return () => {
disableScope(HotkeyScope.NONE);
previouslyEnabledScopes.forEach(enableScope);
};
}, []);
};

View File

@@ -0,0 +1,15 @@
/*
* 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 { HotkeysProvider } from 'react-hotkeys-hook';
import { ReactNode } from 'react';
import { HotkeyScope } from '@/modules/hotkeys/Hotkeys.types.ts';
export const AppHotkeysProvider = ({ children }: { children?: ReactNode }) => (
<HotkeysProvider initiallyActiveScopes={[HotkeyScope.GLOBAL]}>{children}</HotkeysProvider>
);

View File

@@ -69,6 +69,7 @@ const APP_METADATA_OBJECT: Record<AppMetadataKeys, undefined> = {
profiles: undefined,
readingModesDefaultProfile: undefined,
defaultProfile: undefined,
hotkeys: undefined,
};
export const VALID_APP_METADATA_KEYS = Object.keys(APP_METADATA_OBJECT);
@@ -135,6 +136,7 @@ export const GLOBAL_METADATA_KEYS: AppMetadataKeys[] = [
'customFilter',
'shouldSkipDupChapters',
'profiles',
'hotkeys',
];
/**

View File

@@ -0,0 +1,131 @@
/*
* 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 { useHotkeys as useHotKeysHook, useHotkeysContext } from 'react-hotkeys-hook';
import { useEffect } from 'react';
import { HOTKEY_SCOPES } from '@/modules/hotkeys/Hotkeys.constants.ts';
import { ReaderService } from '@/modules/reader/services/ReaderService.ts';
import { ReaderHotkey, ReadingMode } from '@/modules/reader/types/Reader.types.ts';
import { useReaderOverlayContext } from '@/modules/reader/contexts/ReaderOverlayContext.tsx';
import { getNextRotationValue } from '@/modules/core/utils/ValueRotationButton.utils.ts';
import {
READER_PAGE_SCALE_MODE_VALUES,
ReaderScrollAmount,
} from '@/modules/reader/constants/ReaderSettings.constants.tsx';
import { useReaderStateMangaContext } from '@/modules/reader/contexts/state/ReaderStateMangaContext.tsx';
import { MangaIdInfo } from '@/modules/manga/Manga.types.ts';
import { HotkeyScope } from '@/modules/hotkeys/Hotkeys.types.ts';
import { ReaderControls } from '@/modules/reader/services/ReaderControls.ts';
import { ScrollDirection, ScrollOffset } from '@/modules/core/Core.types.ts';
const useHotkeys = (...args: Parameters<typeof useHotKeysHook>): ReturnType<typeof useHotKeysHook> => {
const [keys, callback, options, dependencies] = args;
return useHotKeysHook(keys, callback, { ...options, ...HOTKEY_SCOPES.reader }, dependencies);
};
const DEFAULT_MANGA: MangaIdInfo = { id: -1 };
const CONTINUOUS_READING_MODE_TO_SCROLL_DIRECTION: Record<ReadingMode, ScrollDirection> = {
[ReadingMode.SINGLE_PAGE]: ScrollDirection.Y,
[ReadingMode.DOUBLE_PAGE]: ScrollDirection.Y,
[ReadingMode.CONTINUOUS_VERTICAL]: ScrollDirection.Y,
[ReadingMode.CONTINUOUS_HORIZONTAL]: ScrollDirection.X,
};
export const ReaderHotkeys = ({
scrollElementRef,
}: {
scrollElementRef: React.MutableRefObject<HTMLElement | null>;
}) => {
const { enableScope, disableScope } = useHotkeysContext();
const { manga } = useReaderStateMangaContext();
const { isVisible, setIsVisible } = useReaderOverlayContext();
const { hotkeys, pageScaleMode, shouldStretchPage, shouldOffsetDoubleSpreads, readingMode, readingDirection } =
ReaderService.useSettings();
const openChapter = ReaderControls.useOpenChapter();
const openPage = ReaderControls.useOpenPage();
const updateSetting = ReaderService.useCreateUpdateSetting(manga ?? DEFAULT_MANGA);
const deleteSetting = ReaderService.useCreateDeleteSetting(manga ?? DEFAULT_MANGA);
useHotkeys(hotkeys[ReaderHotkey.PREVIOUS_PAGE], () => openPage('previous'), [openPage]);
useHotkeys(hotkeys[ReaderHotkey.NEXT_PAGE], () => openPage('next'), [openPage]);
useHotkeys(
hotkeys[ReaderHotkey.SCROLL_BACKWARD],
() =>
scrollElementRef.current &&
ReaderControls.scroll(
ScrollOffset.BACKWARD,
CONTINUOUS_READING_MODE_TO_SCROLL_DIRECTION[readingMode.value],
readingDirection.value,
scrollElementRef.current,
ReaderScrollAmount.SMALL,
),
{ preventDefault: true },
[readingMode.value, readingDirection.value],
);
useHotkeys(
hotkeys[ReaderHotkey.SCROLL_FORWARD],
() =>
scrollElementRef.current &&
ReaderControls.scroll(
ScrollOffset.FORWARD,
CONTINUOUS_READING_MODE_TO_SCROLL_DIRECTION[readingMode.value],
readingDirection.value,
scrollElementRef.current,
ReaderScrollAmount.SMALL,
),
{ preventDefault: true },
[readingMode.value, readingDirection.value],
);
useHotkeys(hotkeys[ReaderHotkey.PREVIOUS_CHAPTER], () => openChapter('previous'), [openChapter]);
useHotkeys(hotkeys[ReaderHotkey.NEXT_CHAPTER], () => openChapter('next'), [openChapter]);
useHotkeys(hotkeys[ReaderHotkey.TOGGLE_MENU], () => setIsVisible(!isVisible), [isVisible]);
useHotkeys(
hotkeys[ReaderHotkey.CYCLE_SCALE_TYPE],
() => {
if (pageScaleMode.isDefault) {
updateSetting('pageScaleMode', READER_PAGE_SCALE_MODE_VALUES[0]);
return;
}
const nextValue = getNextRotationValue(
READER_PAGE_SCALE_MODE_VALUES.indexOf(pageScaleMode.value),
READER_PAGE_SCALE_MODE_VALUES,
true,
);
if (nextValue === undefined) {
deleteSetting('pageScaleMode');
return;
}
updateSetting('pageScaleMode', nextValue);
},
[updateSetting, deleteSetting, pageScaleMode],
);
useHotkeys(
hotkeys[ReaderHotkey.STRETCH_IMAGE],
() => updateSetting('shouldStretchPage', !shouldStretchPage.value),
[updateSetting, shouldStretchPage.value],
);
useHotkeys(
hotkeys[ReaderHotkey.OFFSET_SPREAD_PAGES],
() => updateSetting('shouldOffsetDoubleSpreads', !shouldOffsetDoubleSpreads.value),
[updateSetting, shouldOffsetDoubleSpreads.value],
);
useEffect(() => {
enableScope(HotkeyScope.READER);
return () => disableScope(HotkeyScope.READER);
}, []);
return null;
};

View File

@@ -14,11 +14,14 @@ import { useReaderStateMangaContext } from '@/modules/reader/contexts/state/Read
import { ReaderService } from '@/modules/reader/services/ReaderService.ts';
import { ReaderSettingsTabs } from '@/modules/reader/components/settings/ReaderSettingsTabs.tsx';
import { ReaderSettingTab } from '@/modules/reader/constants/ReaderSettings.constants.tsx';
import { useDisableAllHotkeysWhileMounted } from '@/modules/hotkeys/Hotkeys.utils.ts';
export const ReaderSettings = ({ isOpen, close }: { isOpen: boolean; close: () => void }) => {
const { manga } = useReaderStateMangaContext();
const settings = ReaderService.useSettings();
useDisableAllHotkeysWhileMounted();
const [activeTab, setActiveTab] = useState(0);
if (!manga) {

View File

@@ -22,6 +22,7 @@ import { ReaderGeneralSettings } from '@/modules/reader/components/settings/gene
import { ReaderFilterSettings } from '@/modules/reader/components/settings/filters/ReaderFilterSettings.tsx';
import { ReaderBehaviourSettings } from '@/modules/reader/components/settings/behaviour/ReaderBehaviourSettings.tsx';
import { ReaderDefaultLayoutSettings } from '@/modules/reader/components/settings/layout/ReaderDefaultLayoutSettings.tsx';
import { ReaderHotkeysSettings } from '@/modules/reader/components/settings/hotkeys/ReaderHotkeysSettings.tsx';
interface BaseProps {
activeTab: number;
@@ -160,6 +161,20 @@ export const ReaderSettingsTabs = ({
/>
</TabPanel>
);
case ReaderSettingTab.HOTKEYS:
return (
<TabPanel
key={id}
index={id}
currentIndex={activeTab}
sx={{ p: areDefaultSettings ? 2 : undefined }}
>
<ReaderHotkeysSettings
settings={settings}
updateSetting={(...args) => updateSetting(...args)}
/>
</TabPanel>
);
default:
throw new Error(`Unexpected "ReaderSettingTab" (${id})`);
}

View File

@@ -0,0 +1,45 @@
/*
* 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 { Fragment } from 'react';
import Stack from '@mui/material/Stack';
import { useTranslation } from 'react-i18next';
import Tooltip from '@mui/material/Tooltip';
import { Kbd } from '@/modules/core/components/Kbd.tsx';
export const Hotkey = ({ keys, removeKey }: { keys: string[]; removeKey?: (key: string) => void }) => {
const { t } = useTranslation();
return (
<Stack sx={{ flexDirection: 'row', flexWrap: 'wrap', gap: 1 }}>
{keys.map((key, index) => (
<Fragment key={key}>
<Tooltip title={t('global.button.delete')} hidden={!removeKey}>
<Stack
sx={{
flexDirection: 'row',
flexWrap: 'wrap',
gap: 0.5,
cursor: removeKey ? 'pointer' : undefined,
}}
onClick={() => removeKey?.(key)}
>
{key.split('+').map((splitKey, splitIndex, splitKeys) => (
<Fragment key={splitKey}>
<Kbd>{splitKey}</Kbd>
{splitIndex === splitKeys.length - 1 ? '' : '+'}
</Fragment>
))}
</Stack>
</Tooltip>
{index === keys.length - 1 ? '' : ','}
</Fragment>
))}
</Stack>
);
};

View File

@@ -0,0 +1,46 @@
/*
* 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 Stack from '@mui/material/Stack';
import { useTranslation } from 'react-i18next';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import RestartAltIcon from '@mui/icons-material/RestartAlt';
import { ReaderSettingsTypeProps } from '@/modules/reader/types/Reader.types.ts';
import { ReaderSettingHotkey } from '@/modules/reader/components/settings/hotkeys/ReaderSettingHotkey.tsx';
import { DEFAULT_READER_SETTINGS, READER_HOTKEYS } from '@/modules/reader/constants/ReaderSettings.constants.tsx';
export const ReaderHotkeysSettings = ({ settings, updateSetting }: ReaderSettingsTypeProps) => {
const { t } = useTranslation();
return (
<Stack sx={{ gap: 2 }}>
<Stack sx={{ alignItems: 'end' }}>
<Typography variant="caption">{t('hotkeys.info.delete')}</Typography>
</Stack>
{READER_HOTKEYS.map((hotkey) => (
<ReaderSettingHotkey
key={hotkey}
hotkey={hotkey}
keys={settings.hotkeys[hotkey]}
existingKeys={Object.values(settings.hotkeys).flat()}
updateSetting={(keys) => updateSetting('hotkeys', { ...settings.hotkeys, [hotkey]: keys })}
/>
))}
<Stack sx={{ alignItems: 'end' }}>
<Button
variant="contained"
startIcon={<RestartAltIcon />}
onClick={() => updateSetting('hotkeys', DEFAULT_READER_SETTINGS.hotkeys)}
>
{t('global.button.reset')}
</Button>
</Stack>
</Stack>
);
};

View File

@@ -0,0 +1,78 @@
/*
* 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 Stack from '@mui/material/Stack';
import { useTranslation } from 'react-i18next';
import AddIcon from '@mui/icons-material/Add';
import RestartAltIcon from '@mui/icons-material/RestartAlt';
import Typography from '@mui/material/Typography';
import Tooltip from '@mui/material/Tooltip';
import { bindTrigger, usePopupState } from 'material-ui-popup-state/hooks';
import IconButton from '@mui/material/IconButton';
import { ReaderHotkey } from '@/modules/reader/types/Reader.types.ts';
import { DEFAULT_READER_SETTINGS } from '@/modules/reader/constants/ReaderSettings.constants.tsx';
import { TranslationKey } from '@/Base.types.ts';
import { RecordHotkey } from '@/modules/reader/components/settings/hotkeys/RecordHotkey.tsx';
import { Hotkey } from '@/modules/reader/components/settings/hotkeys/Hotkey.tsx';
const READER_HOTKEY_TO_TITLE: Record<ReaderHotkey, TranslationKey> = {
[ReaderHotkey.PREVIOUS_PAGE]: 'reader.settings.hotkey.previous_page',
[ReaderHotkey.NEXT_PAGE]: 'reader.settings.hotkey.next_page',
[ReaderHotkey.SCROLL_BACKWARD]: 'reader.settings.hotkey.scroll_backward',
[ReaderHotkey.SCROLL_FORWARD]: 'reader.settings.hotkey.scroll_forward',
[ReaderHotkey.PREVIOUS_CHAPTER]: 'reader.settings.hotkey.previous_chapter',
[ReaderHotkey.NEXT_CHAPTER]: 'reader.settings.hotkey.next_chapter',
[ReaderHotkey.TOGGLE_MENU]: 'reader.settings.hotkey.menu',
[ReaderHotkey.CYCLE_SCALE_TYPE]: 'reader.settings.hotkey.scale_type',
[ReaderHotkey.STRETCH_IMAGE]: 'reader.settings.hotkey.stretch_image',
[ReaderHotkey.OFFSET_SPREAD_PAGES]: 'reader.settings.hotkey.offset_spread_pages',
};
export const ReaderSettingHotkey = ({
hotkey,
keys,
existingKeys,
updateSetting,
}: {
hotkey: ReaderHotkey;
keys: string[];
existingKeys: string[];
updateSetting: (keys: string[]) => void;
}) => {
const { t } = useTranslation();
const popupState = usePopupState({ popupId: 'reader-setting-record-hotkey', variant: 'dialog' });
return (
<>
<Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
<Typography sx={{ flexGrow: 1 }}>{t(READER_HOTKEY_TO_TITLE[hotkey])}</Typography>
<Hotkey
keys={keys}
removeKey={(keyToRemove) => updateSetting(keys.filter((key) => key !== keyToRemove))}
/>
<Tooltip title={t('global.button.add')}>
<IconButton {...bindTrigger(popupState)} color="inherit">
<AddIcon />
</IconButton>
</Tooltip>
<Tooltip title={t('global.button.reset')}>
<IconButton onClick={() => updateSetting(DEFAULT_READER_SETTINGS.hotkeys[hotkey])} color="inherit">
<RestartAltIcon />
</IconButton>
</Tooltip>
</Stack>
{popupState.isOpen && (
<RecordHotkey
onClose={popupState.close}
onCreate={(recordedKeys) => updateSetting([...keys, ...recordedKeys])}
existingKeys={existingKeys}
/>
)}
</>
);
};

View File

@@ -0,0 +1,91 @@
/*
* 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 } from 'react';
import Stack from '@mui/material/Stack';
import { Trans, useTranslation } from 'react-i18next';
import { useRecordHotkeys } from 'react-hotkeys-hook';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import { Hotkey } from '@/modules/reader/components/settings/hotkeys/Hotkey.tsx';
export const RecordHotkey = ({
onClose,
onCreate,
existingKeys,
}: {
onClose: () => void;
onCreate: (keys: string[]) => void;
existingKeys: string[];
}) => {
const { t } = useTranslation();
const [recordedKeys, { start, stop, resetKeys }] = useRecordHotkeys();
const keys = [[...recordedKeys].join('+')];
const isExistingKey = keys.some((key) =>
existingKeys.map((existingKey) => existingKey.toLowerCase()).includes(key.toLowerCase()),
);
useEffect(() => {
start();
return () => {
stop();
};
}, []);
return (
<Dialog open onClose={onClose} fullWidth>
<DialogTitle>{t('hotkeys.create.dialog.title')}</DialogTitle>
<DialogContent>
<Stack sx={{ flexDirection: 'row', gap: 1 }}>
<Trans
i18nKey="hotkeys.create.dialog.label"
components={{
Keys: recordedKeys.size ? (
<Hotkey keys={keys} />
) : (
<Typography>{t('hotkeys.create.dialog.placeholder')}</Typography>
),
}}
>
Recorded keys:
</Trans>
</Stack>
{isExistingKey && <Typography color="error">{t('hotkeys.create.error.exists')}</Typography>}
</DialogContent>
<DialogActions>
<Stack
direction="row"
sx={{
justifyContent: 'space-between',
width: '100%',
}}
>
<Button onClick={resetKeys}>{t('global.button.reset')}</Button>
<Stack direction="row">
<Button onClick={onClose}>{t('global.button.cancel')}</Button>
<Button
disabled={isExistingKey}
onClick={() => {
onClose();
onCreate(keys);
}}
>
{t('global.button.create')}
</Button>
</Stack>
</Stack>
</DialogActions>
</Dialog>
);
};

View File

@@ -6,7 +6,6 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import Stack from '@mui/material/Stack';
import { useTranslation } from 'react-i18next';
import { IReaderSettingsWithDefaultFlag, ReadingMode } from '@/modules/reader/types/Reader.types.ts';
import { SliderInput } from '@/modules/core/components/inputs/SliderInput.tsx';
@@ -21,29 +20,32 @@ export const ReaderSettingPageGap = ({
}) => {
const { t } = useTranslation();
const isChangeable = [ReadingMode.CONTINUOUS_HORIZONTAL, ReadingMode.CONTINUOUS_VERTICAL].includes(
readingMode.value,
);
if (!isChangeable) {
return null;
}
return (
<Stack>
{[ReadingMode.CONTINUOUS_HORIZONTAL, ReadingMode.CONTINUOUS_VERTICAL].includes(readingMode.value) && (
<SliderInput
label={t('reader.settings.label.page_gap')}
value={t('global.value', { value: pageGap.value, unit: t('global.unit.px') })}
slotProps={{
slider: {
defaultValue: DEFAULT_READER_SETTINGS.readerWidth.value,
value: pageGap.value,
step: 1,
min: 0,
max: 20,
onChange: (_, value) => {
updateSetting(value as number, false);
},
onChangeCommitted: (_, value) => {
updateSetting(value as number, true);
},
},
}}
/>
)}
</Stack>
<SliderInput
label={t('reader.settings.label.page_gap')}
value={t('global.value', { value: pageGap.value, unit: t('global.unit.px') })}
slotProps={{
slider: {
defaultValue: DEFAULT_READER_SETTINGS.readerWidth.value,
value: pageGap.value,
step: 1,
min: 0,
max: 20,
onChange: (_, value) => {
updateSetting(value as number, false);
},
onChangeCommitted: (_, value) => {
updateSetting(value as number, true);
},
},
}}
/>
);
};

View File

@@ -21,6 +21,7 @@ import {
ProgressBarType,
ReaderBackgroundColor,
ReaderExitMode,
ReaderHotkey,
ReaderOverlayMode,
ReaderPageScaleMode,
ReadingDirection,
@@ -53,6 +54,7 @@ const GLOBAL_READER_SETTING_OBJECT: Record<keyof IReaderSettingsGlobal, undefine
backgroundColor: undefined,
profiles: undefined,
readingModesDefaultProfile: undefined,
hotkeys: undefined,
};
export const GLOBAL_READER_SETTING_KEYS = Object.keys(GLOBAL_READER_SETTING_OBJECT);
@@ -114,6 +116,18 @@ export const DEFAULT_READER_SETTINGS: IReaderSettings = {
[ReadingMode.CONTINUOUS_HORIZONTAL]: DEFAULT_READER_PROFILE,
},
defaultProfile: DEFAULT_READER_PROFILE,
hotkeys: {
[ReaderHotkey.PREVIOUS_PAGE]: ['arrowleft', 'a'],
[ReaderHotkey.NEXT_PAGE]: ['arrowright', 'd'],
[ReaderHotkey.SCROLL_BACKWARD]: ['arrowup', 'w'],
[ReaderHotkey.SCROLL_FORWARD]: ['arrowdown', 's'],
[ReaderHotkey.PREVIOUS_CHAPTER]: ['comma'],
[ReaderHotkey.NEXT_CHAPTER]: ['period'],
[ReaderHotkey.TOGGLE_MENU]: ['m'],
[ReaderHotkey.CYCLE_SCALE_TYPE]: ['i'],
[ReaderHotkey.STRETCH_IMAGE]: ['f'],
[ReaderHotkey.OFFSET_SPREAD_PAGES]: ['o'],
},
};
export const READER_PROGRESS_BAR_POSITION_TO_PLACEMENT: Record<ProgressBarPosition, TooltipProps['placement']> = {
@@ -191,6 +205,7 @@ export enum ReaderSettingTab {
GENERAL,
FILTER,
BEHAVIOUR,
HOTKEYS,
}
export const READER_SETTING_TABS: Record<
@@ -221,4 +236,21 @@ export const READER_SETTING_TABS: Record<
label: 'reader.settings.label.behaviour',
supportsTouchDevices: true,
},
[ReaderSettingTab.HOTKEYS]: {
id: ReaderSettingTab.HOTKEYS,
label: 'hotkeys.title_other',
supportsTouchDevices: false,
},
};
/**
* percentage values
*/
export enum ReaderScrollAmount {
SMALL = 25,
LARGE = 95,
}
export const READER_HOTKEYS = Object.values(ReaderHotkey).filter(
(hotkey) => typeof hotkey === 'number',
) as ReaderHotkey[];

View File

@@ -0,0 +1,128 @@
/*
* 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, useMemo } from 'react';
import { Direction } from '@mui/material/styles';
import { userReaderStatePagesContext } from '@/modules/reader/contexts/state/ReaderStatePagesContext.tsx';
import { getNextPageIndex, getPage } from '@/modules/reader/utils/ReaderProgressBar.utils.tsx';
import { getOptionForDirection } from '@/theme.tsx';
import { ReaderService } from '@/modules/reader/services/ReaderService.ts';
import { useReaderStateChaptersContext } from '@/modules/reader/contexts/state/ReaderStateChaptersContext.tsx';
import { ReadingDirection } from '@/modules/reader/types/Reader.types.ts';
import { ScrollDirection, ScrollOffset } from '@/modules/core/Core.types.ts';
import { ReaderScrollAmount } from '@/modules/reader/constants/ReaderSettings.constants.tsx';
const READING_DIRECTION_TO_DIRECTION: Record<ReadingDirection, Direction> = {
[ReadingDirection.LTR]: 'ltr',
[ReadingDirection.RTL]: 'rtl',
};
const SCROLL_DIRECTION_BY_SCROLL_OFFSET_BY_READING_DIRECTION: Record<ReadingDirection, Record<ScrollOffset, 1 | -1>> = {
[ReadingDirection.LTR]: {
[ScrollOffset.BACKWARD]: -1,
[ScrollOffset.FORWARD]: 1,
},
[ReadingDirection.RTL]: {
[ScrollOffset.BACKWARD]: 1,
[ScrollOffset.FORWARD]: -1,
},
};
export class ReaderControls {
static scroll(
offset: ScrollOffset,
direction: ScrollDirection,
readingDirection: ReadingDirection,
element: HTMLElement,
scrollAmountPercentage: number = ReaderScrollAmount.LARGE,
): void {
if (!element) {
return;
}
const scrollAmount = scrollAmountPercentage / 100;
const scrollDirection = SCROLL_DIRECTION_BY_SCROLL_OFFSET_BY_READING_DIRECTION[readingDirection][offset];
const getNewScrollPosition = (currentPos: number, elementSize: number) =>
currentPos + elementSize * scrollAmount * scrollDirection;
switch (direction) {
case ScrollDirection.X:
element.scroll({
left: getNewScrollPosition(element.scrollLeft, element.clientWidth),
behavior: 'smooth',
});
break;
case ScrollDirection.Y:
element.scroll({
top: getNewScrollPosition(element.scrollTop, element.clientHeight),
behavior: 'smooth',
});
break;
default:
throw new Error(`Unexpected "ScrollDirection" (${direction})`);
}
}
static useOpenChapter(): (offset: 'previous' | 'next') => void {
const { readingDirection } = ReaderService.useSettings();
const { previousChapter, nextChapter } = useReaderStateChaptersContext();
const direction = READING_DIRECTION_TO_DIRECTION[readingDirection.value];
const openPreviousChapter = ReaderService.useNavigateToChapter(previousChapter);
const openNextChapter = ReaderService.useNavigateToChapter(nextChapter);
return useCallback(
(offset) => {
switch (offset) {
case 'previous':
getOptionForDirection(openPreviousChapter, openNextChapter, direction)();
break;
case 'next':
getOptionForDirection(openNextChapter, openPreviousChapter, direction)();
break;
default:
throw new Error(`Unexpected "offset" (${offset})`);
}
},
[direction, openPreviousChapter, openNextChapter],
);
}
static useOpenPage(): (offset: 'previous' | 'next') => void {
const { currentPageIndex, setCurrentPageIndex, pages } = userReaderStatePagesContext();
const { readingDirection } = ReaderService.useSettings();
const currentPage = useMemo(() => getPage(currentPageIndex, pages), [currentPageIndex, pages]);
const previousPageIndex = useMemo(
() => getNextPageIndex('previous', currentPage.pagesIndex, pages),
[currentPage, pages],
);
const nextPageIndex = useMemo(
() => getNextPageIndex('next', currentPage.pagesIndex, pages),
[currentPage, pages],
);
const direction = READING_DIRECTION_TO_DIRECTION[readingDirection.value];
return useCallback(
(offset) => {
switch (offset) {
case 'previous':
setCurrentPageIndex(getOptionForDirection(previousPageIndex, nextPageIndex, direction));
break;
case 'next':
setCurrentPageIndex(getOptionForDirection(nextPageIndex, previousPageIndex, direction));
break;
default:
throw new Error(`Unexpected "offset" (${offset})`);
}
},
[direction, previousPageIndex, nextPageIndex],
);
}
}

View File

@@ -46,7 +46,6 @@ const DIRECTION_TO_READING_DIRECTION: Record<Direction, ReadingDirection> = {
export class ReaderService {
static useNavigateToChapter(chapter?: TChapterReader): () => void {
const navigate = useNavigate();
return useCallback(() => chapter && navigate(Chapters.getReaderUrl(chapter), { replace: true }), [chapter]);
}

View File

@@ -93,6 +93,7 @@ const convertSettingsToMetadata = (
readerWidth: JSON.stringify(settings.readerWidth),
profiles: JSON.stringify(settings.profiles),
readingModesDefaultProfile: JSON.stringify(settings.readingModesDefaultProfile),
hotkeys: JSON.stringify(settings.hotkeys),
});
export const DEFAULT_READER_SETTINGS_WITH_DEFAULT_FLAG = convertToSettingsWithDefaultFlag(
@@ -130,6 +131,8 @@ const convertMetadataToSettings = (
profiles.includes(profile) ? profile : DEFAULT_READER_PROFILE,
]),
) as IReaderSettings['readingModesDefaultProfile'],
hotkeys:
jsonSaveParse<IReaderSettings['hotkeys']>((metadata.hotkeys as string) ?? '') ?? defaultSettings.hotkeys,
};
};

View File

@@ -119,6 +119,7 @@ export interface IReaderSettingsGlobal {
backgroundColor: ReaderBackgroundColor;
profiles: string[];
readingModesDefaultProfile: Record<ReadingMode, string>;
hotkeys: Record<ReaderHotkey, string[]>;
}
export interface IReaderSettingsManga {
@@ -179,3 +180,16 @@ export type ReaderSettingsTypeProps =
| ReaderSettingsTypeDefaultableProps
| (PropertiesNever<Omit<ReaderSettingsTypeDefaultableProps, keyof ReaderSettingsTypeBaseProps>> &
ReaderSettingsTypeNonDefaultableProps);
export enum ReaderHotkey {
PREVIOUS_PAGE,
NEXT_PAGE,
SCROLL_BACKWARD,
SCROLL_FORWARD,
PREVIOUS_CHAPTER,
NEXT_CHAPTER,
TOGGLE_MENU,
CYCLE_SCALE_TYPE,
STRETCH_IMAGE,
OFFSET_SPREAD_PAGES,
}

View File

@@ -6684,6 +6684,11 @@ react-dom@18.3.1:
loose-envify "^1.1.0"
scheduler "^0.23.2"
react-hotkeys-hook@^4.6.1:
version "4.6.1"
resolved "https://registry.yarnpkg.com/react-hotkeys-hook/-/react-hotkeys-hook-4.6.1.tgz#db9066c07377a1c8be067a238ab16e328266345a"
integrity sha512-XlZpbKUj9tkfgPgT9gA+1p7Ey6vFIZHttUjPqpTdyT5nqQ8mHL7elxvSbaC+dpSiHUSmr21Ya1mDxBZG3aje4Q==
react-i18next@15.0.1:
version "15.0.1"
resolved "https://registry.yarnpkg.com/react-i18next/-/react-i18next-15.0.1.tgz#fc662d93829ecb39683fe2757a47ebfbc5c912a0"