import { Block, Text } from 'slate';
import { isHotkey } from 'is-hotkey';

export default onKeyDown;

function onKeyDown(event, change) {
  const createDefaultBlock = () => {
    return Block.create({
      type: 'paragraph',
      nodes: [Text.create('')],
    });
  };

  if (isHotkey('Enter', event)) {
    /**
     * If "Enter" is pressed while a single void block is selected, a new
     * paragraph should be added above or below it, and the current selection
     * (range) should be collapsed to the start of the new paragraph.
     *
     * If the selected block is the first block in the document, create the
     * new block above it. If not, create the new block below it.
     */
    const { document: doc, range, anchorBlock, focusBlock } = change.value;
    const singleBlockSelected = anchorBlock === focusBlock;
    if (!singleBlockSelected || !focusBlock.isVoid) return;

    event.preventDefault();

    const focusBlockParent = doc.getParent(focusBlock.key);
    const focusBlockIndex = focusBlockParent.nodes.indexOf(focusBlock);
    const focusBlockIsFirstChild = focusBlockIndex === 0;

    const newBlock = createDefaultBlock();
    const newBlockIndex = focusBlockIsFirstChild ? 0 : focusBlockIndex + 1;

    return change
      .insertNodeByKey(focusBlockParent.key, newBlockIndex, newBlock)
      .collapseToStartOf(newBlock);
  }

  if (isHotkey(`mod+${event.key}`, event)) {
    const marks = {
      b: 'bold',
      i: 'italic',
      s: 'strikethrough',
      '`': 'code',
    };

    const mark = marks[event.key];

    if (mark) {
      event.preventDefault();
      return change.toggleMark(mark);
    }
  }
};

@@ -36,18 +36,16 @@
 ;%0Aimport
- %7B
  isHotke
@@ -45,18 +45,16 @@
 isHotkey
- %7D
  from 'i
@@ -1353,55 +1353,8 @@
  %7D%0A%0A
-  if (isHotkey(%60mod+$%7Bevent.key%7D%60, event)) %7B%0A  
   co
@@ -1369,35 +1369,41 @@
 s = 
-%7B
+%5B
 %0A    
-  b:
+%5B 'b',
  'bold'
+ %5D
 ,%0A    
- 
- i:
+%5B 'i',
  'it
@@ -1411,18 +1411,22 @@
 lic'
+ %5D
 ,%0A    
-  s:
+%5B 's',
  'st
@@ -1441,75 +1441,134 @@
 ugh'
+ %5D
 ,%0A    
- 
+%5B
  '%60'
-:
+,
  'code'
+ %5D
 ,%0A  
-  %7D
+%5D
 ;%0A%0A
-  
   const
+ %5B
  mark
- = marks%5Bevent.key
+Key, markName %5D = marks.find((%5B key %5D) =%3E isHotkey(%60mod+$%7Bkey%7D%60, event)) %7C%7C %5B
 %5D;%0A%0A
-  
   if
@@ -1573,22 +1573,24 @@
 if (mark
+Name
 ) %7B%0A
-  
     even
@@ -1609,18 +1609,16 @@
 ault();%0A
-  
     retu
@@ -1646,16 +1646,14 @@
 mark
-);%0A    %7D
+Name);
 %0A  %7D

update markdown mark hotkeys to use isHotkey