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

@@ -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);
},
},
}}
/>
);
};