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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 2 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
144 changes: 140 additions & 4 deletions packages/shared/src/hooks/input/useMarkdownInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
allowedFileSize,
uploadNotAcceptedMessage,
} from '../../graphql/posts';
import { isValidHttpUrl } from '../../lib';

export enum MarkdownCommand {
Upload = 'upload',
Expand Down Expand Up @@ -106,6 +107,24 @@ export const useMarkdownInput = ({
const { user } = useAuthContext();
const { displayToast } = useToastNotification();

const getTextBoundaries = (
text: string,
selectionStart: number,
selectionEnd: number,
) => {
const selectedText = text.substring(selectionStart, selectionEnd);
const trimmedText = selectedText.trim();
const leadingWhitespace =
selectedText.length - selectedText.trimStart().length;
const trailingWhitespace =
selectedText.length - selectedText.trimEnd().length;
return {
trimmedText,
newStart: selectionStart + leadingWhitespace,
newEnd: selectionEnd - trailingWhitespace,
};
};

useEffect(() => {
if (dirtyRef.current) {
return;
Expand Down Expand Up @@ -236,8 +255,90 @@ export const useMarkdownInput = ({
checkMention([selectionStart, selectionEnd]);
};

const handleTextFormatting = (
value: string,
symbol: string,
start: number,
end: number,
) => {
const { trimmedText, newStart, newEnd } = getTextBoundaries(
value,
start,
end,
);
const symbolLength = symbol.length;
const isFormatted =
value.substring(newStart - symbolLength, newStart) === symbol &&
value.substring(newEnd, newEnd + symbolLength) === symbol;

if (isFormatted) {
const updatedValue =
value.substring(0, newStart - symbolLength) +
trimmedText +
value.substring(newEnd + symbolLength);
return {
value: updatedValue,
selection: [newStart - symbolLength, newEnd - symbolLength] as const,
};
}

const updatedValue =
value.substring(0, newStart) +
symbol +
trimmedText +
symbol +
value.substring(newEnd);
return {
value: updatedValue,
selection: [newStart + symbolLength, newEnd + symbolLength] as const,
};
};

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

if (isSpecialKey) {
switch (e.key) {
case 'b': {
e.preventDefault();
const boldResult = handleTextFormatting(
textareaLocal.value,
'**',
textareaLocal.selectionStart,
textareaLocal.selectionEnd,
);
onUpdate(boldResult.value);
requestAnimationFrame(() => {
textareaLocal.setSelectionRange(...boldResult.selection);
});
return;
}
case 'i': {
e.preventDefault();
const italicResult = handleTextFormatting(
textareaLocal.value,
'_',
textareaLocal.selectionStart,
textareaLocal.selectionEnd,
);
onUpdate(italicResult.value);
requestAnimationFrame(() => {
textareaLocal.setSelectionRange(...italicResult.selection);
});
return;
}
case 'k': {
e.preventDefault();
e.stopPropagation();
onLinkCommand?.();
return;
}
default:
break;
}
}

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

Expand Down Expand Up @@ -317,15 +418,47 @@ export const useMarkdownInput = ({
};

const onPaste: ClipboardEventHandler<HTMLTextAreaElement> = (e) => {
if (!e.clipboardData.files?.length || !isUploadEnabled) {
if (!e.clipboardData.files?.length && !isUploadEnabled) {
Abhi-Bohora marked this conversation as resolved.
Show resolved Hide resolved
return;
}

e.preventDefault();
const textareaLocal = e.currentTarget;
const pastedText = e.clipboardData.getData('text');
if (
isValidHttpUrl(pastedText) &&
textareaLocal.selectionStart !== textareaLocal.selectionEnd
) {
e.preventDefault();
const { trimmedText, newStart, newEnd } = getTextBoundaries(
textareaLocal.value,
textareaLocal.selectionStart,
textareaLocal.selectionEnd,
);
const newText =
isValidHttpUrl(pastedText) && trimmedText
? `${textareaLocal.value.substring(
0,
newStart,
)}[${trimmedText}](${pastedText})${textareaLocal.value.substring(
newEnd,
)}`
: textareaLocal.value.substring(0, textareaLocal.selectionStart) +
pastedText +
textareaLocal.value.substring(textareaLocal.selectionEnd);
const linkEnd = newStart + `[${trimmedText}](${pastedText})`.length;
onUpdate(newText);
requestAnimationFrame(() => {
textareaLocal.setSelectionRange(linkEnd, linkEnd);
});
return;
}
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 +490,10 @@ export const useMarkdownInput = ({
onInput,
onKeyUp,
onKeyDown,
onPaste,
...uploadCommands,
},
};
};

export default useMarkdownInput;