Açıklama Yok

codeCommand.tsx 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import * as React from "react";
  2. import {Command} from "../types";
  3. import {
  4. insertAfter,
  5. insertBefore,
  6. insertBeforeAndAfter, insertBreaksAfterSoThatThereIsAnEmptyLineAfter,
  7. insertBreaksBeforeSoThatThereIsAnEmptyLineBefore,
  8. selectWordIfCaretIsInsideOne,
  9. } from "../util/MarkdownUtil";
  10. import {buildNewDraftState, getMarkdownStateFromDraftState} from "../util/DraftUtil";
  11. export const codeCommand: Command = {
  12. buttonContentBuilder: ({ iconProvider }) => iconProvider("code"),
  13. buttonProps: { "aria-label": "Insert code" },
  14. execute: (state) => {
  15. let {text, selection} = getMarkdownStateFromDraftState(state);
  16. selection = selectWordIfCaretIsInsideOne({text, selection});
  17. // when there's no breaking line
  18. if (text.slice(selection.start, selection.end).indexOf("\n") === -1) {
  19. const mdState = insertBeforeAndAfter({text, selection}, "`");
  20. return buildNewDraftState(state, mdState);
  21. }
  22. let textInsertion;
  23. // insert breaks before, if needed
  24. textInsertion = insertBreaksBeforeSoThatThereIsAnEmptyLineBefore({text, selection});
  25. text = textInsertion.newText;
  26. selection = textInsertion.newSelection;
  27. // inserts ```\n before
  28. textInsertion = insertBefore(text, "```\n", selection, false);
  29. text = textInsertion.newText;
  30. selection = textInsertion.newSelection;
  31. // inserts ```\n after
  32. textInsertion = insertAfter(text, "\n```", selection);
  33. text = textInsertion.newText;
  34. selection = textInsertion.newSelection;
  35. // insert breaks after, if needed
  36. textInsertion = insertBreaksAfterSoThatThereIsAnEmptyLineAfter({text, selection});
  37. text = textInsertion.newText;
  38. selection = textInsertion.newSelection;
  39. return buildNewDraftState(state, {text, selection});
  40. },
  41. };