Skip to content

Commit

Permalink
✨ feat(hotkeys): compatible with SSR
Browse files Browse the repository at this point in the history
  • Loading branch information
Asuka109 committed Nov 8, 2023
1 parent 08a3cb9 commit 99fa4f8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
32 changes: 22 additions & 10 deletions src/components/HotKeys/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
'use client';

import { createStyles } from 'antd-style';
import { Fragment, memo } from 'react';
import { Fragment, memo, useEffect, useState } from 'react';
import { Flexbox } from 'react-layout-kit';

import { CLEAN_MESSAGE_KEY, PREFIX_KEY } from '@/const/hotkeys';
import { isApplePlatform } from '@/utils/platform';

const useStyles = createStyles(
Expand All @@ -28,26 +31,35 @@ const useStyles = createStyles(
`,
);

const HOTKEY_MAPPINGS: Partial<Record<string, string>> = {
alt: isApplePlatform() ? 'option' : 'alt',
};

export interface HotKeysProps {
desc?: string;
keys: string;
}

const HotKeys = memo<HotKeysProps>(({ keys, desc }) => {
const { styles } = useStyles();
const keysGroup = keys
.split('+')
.filter(Boolean)
.map((k) => HOTKEY_MAPPINGS[k] ?? k);
const [keysGroup, setKeysGroup] = useState(keys.split('+'));
const visibility = typeof window === 'undefined' ? 'hidden' : 'visible';

useEffect(() => {
const mapping: Record<string, string> = {
[CLEAN_MESSAGE_KEY]: isApplePlatform() ? '⌫' : 'backspace',
[PREFIX_KEY]: isApplePlatform() ? '⌥' : 'alt',
};
const newValue = keys
.split('+')
.filter(Boolean)
.map((k) => mapping[k] ?? k);
setKeysGroup(newValue);
}, [keys]);

const content = (
<Flexbox align={'center'} className={styles} gap={2} horizontal>
{keysGroup.map((key, index) => (
<Fragment key={index}>
<kbd>{key.toUpperCase()}</kbd>
<kbd>
<span style={{ visibility }}>{key.toUpperCase()}</span>
</kbd>
{index + 1 < keysGroup.length && <span>+</span>}
</Fragment>
))}
Expand Down
4 changes: 2 additions & 2 deletions src/utils/platform.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import UAParser from 'ua-parser-js';

export const getPlatform = () => {
const ua = navigator.userAgent;
return new UAParser(ua || '').getOS();
let ua = navigator.userAgent;
return new UAParser(ua).getOS();
};

export const isApplePlatform = () => {
Expand Down

0 comments on commit 99fa4f8

Please sign in to comment.