diff --git a/src/commands/imageCommand.tsx b/src/commands/imageCommand.tsx index 5be46d57..e2d4ac98 100644 --- a/src/commands/imageCommand.tsx +++ b/src/commands/imageCommand.tsx @@ -1,22 +1,23 @@ import * as React from "react"; -import {Command} from "../types"; -import {TextApi, TextState} from "../types/CommandOptions"; -import {selectWord} from "../util/MarkdownUtil"; +import { Command } from "../types"; +import { TextApi, TextState } from "../types/CommandOptions"; +import { selectWord } from "../util/MarkdownUtil"; export const imageCommand: Command = { - name: "image", - buttonProps: {"aria-label": "Add image"}, - execute: (state0: TextState, api: TextApi) => { - // Adjust the selection to encompass the whole word if the caret is inside one - const newSelectionRange = selectWord({text: state0.text, selection: state0.selection}); - const state1 = api.setSelectionRange(newSelectionRange); - // Replaces the current selection with the bold mark up - const state2 = api.replaceSelection(`![${state1.selectedText}](image-url)`); - // Adjust the selection to not contain the ** - api.setSelectionRange({ - start: state2.selection.end - 12 - state1.selectedText.length, - end: state2.selection.end - 12 - }); - }, - keyCommand: "image", + name: "image", + buttonProps: { "aria-label": "Add image" }, + execute: (state0: TextState, api: TextApi) => { + // Select everything + const newSelectionRange = selectWord({ text: state0.text, selection: state0.selection }); + const state1 = api.setSelectionRange(newSelectionRange); + // Replaces the current selection with the image + const imageTemplate = state1.selectedText || "https://example.com/your-image.png"; + api.replaceSelection(`![](${imageTemplate})`); + // Adjust the selection to not contain the ** + api.setSelectionRange({ + start: 4 + state1.selection.start, + end: 4 + state1.selection.start + imageTemplate.length + }); + }, + keyCommand: "image" }; \ No newline at end of file diff --git a/src/types/CommandOptions.ts b/src/types/CommandOptions.ts index 25342e3b..dd9d0cc3 100644 --- a/src/types/CommandOptions.ts +++ b/src/types/CommandOptions.ts @@ -10,9 +10,13 @@ export interface TextApi { /** * Replaces the current selection with the new text. This will make the new selectedText to be empty, the * selection start and selection end will be the same and will both point to the end - * @param text + * @param text Text that should replace the current selection */ replaceSelection (text: string): TextState; + /** + * Selects the specified text range + * @param selection + */ setSelectionRange (selection: TextRange): TextState; }