Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: markdown formatting using keyboard shortcut #4058

Merged
merged 8 commits into from
Feb 3, 2025
Merged
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
52 changes: 46 additions & 6 deletions packages/shared/src/hooks/input/useMarkdownInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ import {
Y_AXIS_KEYS,
} from '../../lib/element';
import type { UserShortProfile } from '../../lib/user';
import { getLinkReplacement, getMentionReplacement } from '../../lib/markdown';
import {
getLinkReplacement,
getMentionReplacement,
getStyleReplacement,
} from '../../lib/markdown';
import { handleRegex } from '../../graphql/users';
import { UploadState, useSyncUploader } from './useSyncUploader';
import { useToastNotification } from '../useToastNotification';
Expand All @@ -38,6 +42,7 @@ import {
allowedFileSize,
uploadNotAcceptedMessage,
} from '../../graphql/posts';
import { isValidHttpUrl } from '../../lib';

export enum MarkdownCommand {
Upload = 'upload',
Expand Down Expand Up @@ -191,6 +196,12 @@ export const useMarkdownInput = ({
};

const onLinkCommand = () => command.replaceWord(getLinkReplacement, onUpdate);
const onLinkPaste = (pastedLink: string) => {
const onLinkPasteCommand: GetReplacementFn = (type, props) =>
getLinkReplacement(type, { ...props, url: pastedLink });

return command.replaceWord(onLinkPasteCommand, onUpdate);
};

const onMentionCommand = async () => {
const { replacement } = await command.replaceWord(
Expand Down Expand Up @@ -238,6 +249,27 @@ export const useMarkdownInput = ({

const onKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = async (e) => {
const isSpecialKey = e.ctrlKey || e.metaKey;

if (isSpecialKey) {
switch (e.key) {
case 'b': {
e.preventDefault();
return await command.replaceWord(getStyleReplacement('**'), onUpdate);
}
case 'i': {
e.preventDefault();
return await command.replaceWord(getStyleReplacement('_'), onUpdate);
}
case 'k': {
e.preventDefault();
e.stopPropagation();
return await onLinkCommand?.();
}
default:
break;
}
}

const isSubmitting =
isSpecialKey && e.key === KeyboardCommand.Enter && input?.length;

Expand Down Expand Up @@ -316,16 +348,21 @@ export const useMarkdownInput = ({
startUploading();
};

const onPaste: ClipboardEventHandler<HTMLTextAreaElement> = (e) => {
if (!e.clipboardData.files?.length || !isUploadEnabled) {
const onPaste: ClipboardEventHandler<HTMLTextAreaElement> = async (e) => {
const pastedText = e.clipboardData.getData('text');
if (isValidHttpUrl(pastedText)) {
e.preventDefault();
await onLinkPaste(pastedText);
return;
}

e.preventDefault();
if (e.clipboardData.files?.length && isUploadEnabled) {
e.preventDefault();

Array.from(e.clipboardData.files).forEach(verifyFile);
Array.from(e.clipboardData.files).forEach(verifyFile);

startUploading();
startUploading();
}
};

const onCloseMention = useCallback(() => setQuery(undefined), []);
Expand Down Expand Up @@ -357,7 +394,10 @@ export const useMarkdownInput = ({
onInput,
onKeyUp,
onKeyDown,
onPaste,
...uploadCommands,
},
};
};

export default useMarkdownInput;
22 changes: 18 additions & 4 deletions packages/shared/src/lib/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,35 @@ import type { GetReplacementFn } from './textarea';
import { CursorType, isFalsyOrSpace } from './textarea';

const urlText = 'url';
const getUrlText = (content = '') => `[${content}](${urlText})`;
const getUrlText = (content = '', url = urlText) => `[${content}](${url})`;

export const getLinkReplacement: GetReplacementFn = (
type,
{ word, selection: [start] },
{ word, url, selection: [start] },
) => {
const replacement = getUrlText(word);
const urlReplacement = url ?? urlText;
const replacement = getUrlText(word, urlReplacement);

if (type === CursorType.Isolated) {
const offset = start + 1;
return { replacement, offset: [offset, offset] };
}

const end = start + replacement.length - 1;
return { replacement, offset: [end - urlText.length, end] };
return { replacement, offset: [end - urlReplacement.length, end] };
};

export const getStyleReplacement = (wrapper: string): GetReplacementFn => {
return (type: CursorType, { word, selection: [start] }) => {
const replacement = `${wrapper}${word}${wrapper}`;

if (type === CursorType.Isolated) {
const offset = start + wrapper.length;
return { replacement, offset: [offset, offset] };
}

return { replacement };
};
};

export const getMentionReplacement: GetReplacementFn = (
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/lib/textarea.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ interface GetReplacementOptionalProps {
selection: number[];
trailingChar?: string;
leadingChar?: string;
url?: string;
}

interface Replacement {
Expand Down