Skip to content

Commit c732cd4

Browse files
committed
feat: handle context menu format bold and italic
1 parent c1a08de commit c732cd4

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/MarkdownTextInput.web.tsx

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,35 @@ const MarkdownTextInput = React.forwardRef<MarkdownTextInput, MarkdownTextInputP
236236
[parser, parseText, processedMarkdownStyle],
237237
);
238238

239+
const format = useCallback(
240+
(target: MarkdownTextInputElement, parsedText: string, cursorPosition: number, formatType: string): ParseTextResult => {
241+
if (!contentSelection.current) {
242+
return {
243+
text: '',
244+
cursorPosition: 0,
245+
};
246+
}
247+
let markdown;
248+
switch (formatType) {
249+
case 'formatBold':
250+
markdown = '*';
251+
break;
252+
case 'formatItalic':
253+
markdown = '_';
254+
break;
255+
default:
256+
markdown = '';
257+
}
258+
259+
const beforeSelectedText = parsedText.slice(0, contentSelection.current.start);
260+
const selectedText = parsedText.slice(contentSelection.current.start, contentSelection.current.end);
261+
const afterSelectedText = parsedText.slice(contentSelection.current.end);
262+
const text = `${beforeSelectedText}${markdown}${selectedText}${markdown}${afterSelectedText}`;
263+
return parseText(parser, target, text, processedMarkdownStyle, cursorPosition + 2, true);
264+
},
265+
[parser, parseText, processedMarkdownStyle],
266+
);
267+
239268
// Placeholder text color logic
240269
const updateTextColor = useCallback(
241270
(node: HTMLDivElement, text: string) => {
@@ -361,6 +390,10 @@ const MarkdownTextInput = React.forwardRef<MarkdownTextInput, MarkdownTextInputP
361390
case 'historyRedo':
362391
newInputUpdate = redo(divRef.current);
363392
break;
393+
case 'formatBold':
394+
case 'formatItalic':
395+
newInputUpdate = format(divRef.current, parsedText, newCursorPosition, inputType);
396+
break;
364397
default:
365398
newInputUpdate = parseText(parser, divRef.current, parsedText, processedMarkdownStyle, newCursorPosition, true, !inputType, inputType === 'pasteText');
366399
}
@@ -414,7 +447,7 @@ const MarkdownTextInput = React.forwardRef<MarkdownTextInput, MarkdownTextInputP
414447

415448
handleContentSizeChange();
416449
},
417-
[parser, updateTextColor, updateSelection, onChange, onChangeText, handleContentSizeChange, undo, redo, parseText, processedMarkdownStyle, setEventProps, maxLength],
450+
[parser, updateTextColor, updateSelection, onChange, onChangeText, handleContentSizeChange, undo, redo, format, parseText, processedMarkdownStyle, setEventProps, maxLength],
418451
);
419452

420453
const insertText = useCallback(

0 commit comments

Comments
 (0)