Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion desktop-app/e2e/tests/keyboard-shortcuts-modal.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ test.describe('Keyboard Shortcuts Modal', () => {
}

await expect(app.page.getByText('General Shortcuts')).toBeVisible();
await expect(app.page.getByText('Previewer Shorcuts')).toBeVisible();
await expect(app.page.getByText('Previewer Shortcuts')).toBeVisible();
});

test('shortcuts modal can be closed', async ({app}) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ export const SHORTCUT_CHANNEL = {

export type ShortcutChannel = (typeof SHORTCUT_CHANNEL)[keyof typeof SHORTCUT_CHANNEL];

export const SHORTCUT_KEYS: {[key in ShortcutChannel]: string[]} = {
export type ShortcutBindings = {[key in ShortcutChannel]: string[]};
export type ShortcutOverrides = Partial<ShortcutBindings>;

export const SHORTCUT_KEYS: ShortcutBindings = {
[SHORTCUT_CHANNEL.BACK]: ['alt+left'],
[SHORTCUT_CHANNEL.BOOKMARK]: ['mod+d'],
[SHORTCUT_CHANNEL.DELETE_ALL]: ['mod+alt+del', 'mod+alt+backspace'],
Expand All @@ -39,3 +42,52 @@ export const SHORTCUT_KEYS: {[key in ShortcutChannel]: string[]} = {
[SHORTCUT_CHANNEL.ZOOM_IN]: ['mod+=', 'mod++', 'mod+shift+='],
[SHORTCUT_CHANNEL.ZOOM_OUT]: ['mod+-'],
};

export const NON_CUSTOMIZABLE_SHORTCUT_CHANNELS: ShortcutChannel[] = [SHORTCUT_CHANNEL.RELOAD];

export const CUSTOMIZABLE_SHORTCUT_CHANNELS: ShortcutChannel[] = Object.values(
SHORTCUT_CHANNEL
).filter((channel) => !NON_CUSTOMIZABLE_SHORTCUT_CHANNELS.includes(channel));

export const SHORTCUT_CATEGORIES: {
id: number;
name: string;
channels: ShortcutChannel[];
}[] = [
{
id: 0,
name: 'General Shortcuts',
channels: [
SHORTCUT_CHANNEL.BACK,
SHORTCUT_CHANNEL.BOOKMARK,
SHORTCUT_CHANNEL.DELETE_ALL,
SHORTCUT_CHANNEL.DELETE_CACHE,
SHORTCUT_CHANNEL.DELETE_COOKIES,
SHORTCUT_CHANNEL.DELETE_STORAGE,
SHORTCUT_CHANNEL.EDIT_URL,
],
},
{
id: 1,
name: 'Previewer Shortcuts',
channels: [
SHORTCUT_CHANNEL.FORWARD,
SHORTCUT_CHANNEL.INSPECT_ELEMENTS,
SHORTCUT_CHANNEL.PREVIEW_LAYOUT,
SHORTCUT_CHANNEL.RELOAD,
SHORTCUT_CHANNEL.ROTATE_ALL,
SHORTCUT_CHANNEL.SCREENSHOT_ALL,
SHORTCUT_CHANNEL.THEME,
SHORTCUT_CHANNEL.TOGGLE_RULERS,
SHORTCUT_CHANNEL.ZOOM_IN,
SHORTCUT_CHANNEL.ZOOM_OUT,
],
},
];

export const resolveShortcutBindings = (overrides: ShortcutOverrides = {}): ShortcutBindings => {
return (Object.keys(SHORTCUT_KEYS) as ShortcutChannel[]).reduce((bindings, channel) => {
bindings[channel] = overrides[channel] ?? SHORTCUT_KEYS[channel];
return bindings;
}, {} as ShortcutBindings);
};
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
import {SHORTCUT_KEYS, ShortcutChannel} from './constants';
import {useSelector} from 'react-redux';
import {selectResolvedShortcutBindings} from 'renderer/store/features/shortcuts';
import {ShortcutChannel} from './constants';
import useMousetrapEmitter from './useMousetrapEmitter';

const KeyboardShortcutsManager = () => {
// eslint-disable-next-line no-restricted-syntax
for (const [channel, keys] of Object.entries(SHORTCUT_KEYS)) {
// eslint-disable-next-line react-hooks/rules-of-hooks
useMousetrapEmitter(keys, channel as ShortcutChannel);
}
interface ShortcutBindingProps {
channel: ShortcutChannel;
keys: string[];
}

const ShortcutBinding = ({channel, keys}: ShortcutBindingProps) => {
useMousetrapEmitter(keys, channel);
return null;
};

const KeyboardShortcutsManager = () => {
const shortcutBindings = useSelector(selectResolvedShortcutBindings);

return (
<>
{Object.entries(shortcutBindings).map(([channel, keys]) => (
<ShortcutBinding key={channel} channel={channel as ShortcutChannel} keys={keys} />
))}
</>
);
};

export default KeyboardShortcutsManager;
Original file line number Diff line number Diff line change
@@ -1,32 +1,200 @@
import {useEffect, useRef, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import Button from 'renderer/components/Button';
import {
CUSTOMIZABLE_SHORTCUT_CHANNELS,
ShortcutChannel,
} from 'renderer/components/KeyboardShortcutsManager/constants';
import {
clearShortcutOverride,
selectShortcutOverride,
setShortcutOverride,
} from 'renderer/store/features/shortcuts';

interface Props {
channel: ShortcutChannel;
text: string[];
}

const ShortcutButton = ({text}: Props) => {
const btnText = text[0].split('+');
const btnTextLength = btnText.length - 1;
const SPECIAL_CODE_MAP: {[key: string]: string} = {
ArrowDown: 'down',
ArrowLeft: 'left',
ArrowRight: 'right',
ArrowUp: 'up',
Backspace: 'backspace',
Comma: ',',
Delete: 'del',
Equal: '=',
Minus: '-',
Period: '.',
Slash: '/',
Space: 'space',
};

const formatText = (value: string) => {
if (value === 'mod') {
if (navigator?.userAgent?.includes('Windows')) {
return `Ctrl`;
}
return `⌘`;
const formatText = (value: string) => {
if (value === 'mod') {
if (navigator?.userAgent?.includes('Windows')) {
return 'Ctrl';
}
return '⌘';
}

if (value === 'alt') return 'Alt';
if (value === 'shift') return 'Shift';
if (value === 'del') return 'Del';
if (value === 'backspace') return 'Backspace';
if (value.length === 1) return value.toUpperCase();
return value;
};

const ShortcutPreview = ({shortcut}: {shortcut: string}) => {
const btnText = shortcut.split('+');
const btnTextLength = btnText.length - 1;

if (value.length === 1) return value.toUpperCase();
return value;
};
return (
<div>
{btnText.map((value, i) => (
<span key={value}>
<span className="inline-flex items-center">
{btnText.map((value, index) => (
<span key={`${shortcut}-${value}-${index}`}>
<span className="rounded border border-gray-200 bg-gray-100 px-[6px] py-[2px] text-xs font-semibold text-gray-800 dark:border-gray-500 dark:bg-gray-600 dark:text-gray-100">
{formatText(value)}
</span>
{i < btnTextLength && <span className="px-1">+</span>}
{index < btnTextLength && <span className="px-1">+</span>}
</span>
))}
</span>
);
};

const normalizeShortcutFromEvent = (event: React.KeyboardEvent<HTMLButtonElement>) => {
const segments = [];

if (event.ctrlKey || event.metaKey) {
segments.push('mod');
}
if (event.altKey) {
segments.push('alt');
}
if (event.shiftKey) {
segments.push('shift');
}

let key = SPECIAL_CODE_MAP[event.code];
if (!key && event.code.startsWith('Key')) {
key = event.code.slice(3).toLowerCase();
}
if (!key && event.code.startsWith('Digit')) {
key = event.code.slice(5);
}

if (!key) {
const normalizedKey = event.key.toLowerCase();
if (['control', 'meta', 'alt', 'shift'].includes(normalizedKey)) {
return null;
}
key = normalizedKey;
}

return [...segments, key].join('+');
};

const ShortcutButton = ({channel, text}: Props) => {
const dispatch = useDispatch();
const shortcutOverride = useSelector(selectShortcutOverride(channel));
const isCustomizable = CUSTOMIZABLE_SHORTCUT_CHANNELS.includes(channel);
const isOverridden = shortcutOverride != null;
const [isCapturing, setIsCapturing] = useState(false);
const captureButtonRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (isCapturing) {
captureButtonRef.current?.focus();
}
}, [isCapturing]);

const handleStartCapture = () => {
if (!isCustomizable) {
return;
}
setIsCapturing(true);
};

const handleKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>) => {
event.preventDefault();
event.stopPropagation();

if (event.key === 'Escape') {
setIsCapturing(false);
return;
}

const shortcut = normalizeShortcutFromEvent(event);
if (!shortcut) {
return;
}

dispatch(
setShortcutOverride({
channel,
keys: [shortcut],
})
);
setIsCapturing(false);
};

return (
<div className="flex items-center gap-2">
{isCapturing ? (
<button
ref={captureButtonRef}
type="button"
onKeyDown={handleKeyDown}
data-testid={`shortcut-${channel}-capture`}
className="rounded border border-emerald-500 bg-emerald-100 px-2 py-1 text-xs font-semibold text-emerald-900 focus:outline-none dark:bg-emerald-900/30 dark:text-emerald-100"
>
Press shortcut
</button>
) : (
<div className="flex flex-wrap items-center gap-1">
{text.map((shortcut, index) => (
<span key={`${channel}-${shortcut}-${index}`}>
<ShortcutPreview shortcut={shortcut} />
{index < text.length - 1 ? (
<span className="px-1 text-xs text-slate-500 dark:text-slate-300">/</span>
) : null}
</span>
))}
</div>
)}

{isCustomizable ? (
<div className="flex items-center gap-1">
{isCapturing ? (
<Button className="px-2 text-xs" isTextButton onClick={() => setIsCapturing(false)}>
Cancel
</Button>
) : (
<Button
className="px-2 text-xs"
isTextButton
onClick={handleStartCapture}
data-testid={`shortcut-${channel}-edit`}
>
{isOverridden ? 'Change' : 'Edit'}
</Button>
)}
{isOverridden && !isCapturing ? (
<Button
className="px-2 text-xs"
isTextButton
onClick={() => dispatch(clearShortcutOverride(channel))}
data-testid={`shortcut-${channel}-reset`}
>
Reset
</Button>
) : null}
</div>
) : (
<span className="text-xs text-slate-500 dark:text-slate-300">Fixed</span>
)}
</div>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ interface Props {
}

const ShortcutName = ({text}: Props) => {
const formattedText = text.replace('_', ' ').toLowerCase();
const formattedText = text.replace(/_/g, ' ').toLowerCase();
return <div className="capitalize">{formattedText}</div>;
};

Expand Down
Loading
Loading