All files / mutxt-react/src/MuTxt behavior.ts

72.78% Statements 238/327
62.18% Branches 148/238
62.06% Functions 36/58
76.86% Lines 196/255

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 4622x 2x                 2x 2x   2x   2x 2x                                   256x 7x   2x         2x         2x 5x 5x 5x   10x   5x     2x 13x 13x 13x   38x   13x     2x 5x 5x 5x   10x     5x 1x 1x     2x 4x 4x 4x   9x   4x     2x                       2x     2x 7x 25x         2x 34x 34x 34x   72x     34x     2x 3x 3x 3x   9x     3x     2x 7x 7x 7x 7x 7x 21x   7x 1x 3x     7x 1x 4x     6x 18x         2x                               2x         2x 1x   4x       2x 9x 9x 9x 9x 9x 9x 9x 3x 3x 2x 2x           2x 2x   1x 1x     2x 5x   2x 5x         2x 1x 1x 1x   2x   1x 1x 1x 1x 1x 1x               2x                               2x 5x 5x 5x   10x     5x                           2x 9x 9x 9x   18x     9x 3x 3x 2x 1x 1x     2x           2x 5x 5x 5x 5x 5x 5x 4x 3x   3x 3x       3x 3x 2x 1x 1x               2x 6x 6x 6x 6x 6x 6x 5x   4x 4x 2x 1x 1x           1x 1x   1x 1x     2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x     5x 5x 5x 5x   5x 2x 2x 2x 2x     3x       5x         5x                                                     5x 5x 5x                       5x     2x     2x     2x       2x       2x             2x        
import {Editor, Element as SlateElement, Node, Path, Range, Transforms} from 'slate';
import {HistoryEditor} from 'slate-history';
import type {
  BlockFormat,
  CustomElement,
  ListElementType,
  MarkFormat,
  SlateTextAlign,
  ToolbarButtonDefinition,
} from './types';
import {removeLink} from './behavior/link';
import {isListType, LIST_TYPES} from './behavior/lists';
 
export {isListType, LIST_TYPES};
 
export const ALIGNMENTS: SlateTextAlign[] = ['left', 'center', 'right', 'justify'];
export const MARKS: MarkFormat[] = [
  'bg',
  'bold',
  'code',
  'del',
  'fg',
  'ins',
  'italic',
  'kbd',
  'mark',
  'overline',
  'spoiler',
  'strikethrough',
  'sub',
  'sup',
  'underline',
];
 
const isElement = (node: unknown): node is CustomElement => SlateElement.isElement(node);
const isFormattableBlock = (node: CustomElement): boolean => !isListType(node.type) && node.type !== 'embed';
 
export const isMarkActive = (editor: Editor, format: MarkFormat): boolean => {
  const marks = Editor.marks(editor);
  return marks ? marks[format] === true : false;
};
 
export const toggleMark = (editor: Editor, format: MarkFormat): void => {
  if (isMarkActive(editor, format)) Editor.removeMark(editor, format);
  else Editor.addMark(editor, format, true);
};
 
export const getActiveBlock = (editor: Editor): CustomElement | null => {
  const {selection} = editor;
  Iif (!selection) return null;
  const [match] = Editor.nodes(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && Editor.isBlock(editor, node),
  });
  return (match as [CustomElement, number[]] | undefined)?.[0] ?? null;
};
 
export const isBlockActive = (editor: Editor, format: Exclude<BlockFormat, ListElementType>): boolean => {
  const {selection} = editor;
  Iif (!selection) return false;
  const [match] = Editor.nodes(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && node.type === format,
  });
  return !!match;
};
 
const isAtEndOfBlock = (editor: Editor, format: Exclude<BlockFormat, ListElementType>): boolean => {
  const {selection} = editor;
  Iif (!selection || !Range.isCollapsed(selection)) return false;
  const match = Editor.above(editor, {
    at: selection,
    match: (node) => isElement(node) && node.type === format,
    mode: 'lowest',
  });
  if (!match) return false;
  const [, path] = match;
  return Editor.isEnd(editor, selection.anchor, path);
};
 
export const isListActive = (editor: Editor, format: ListElementType): boolean => {
  const {selection} = editor;
  Iif (!selection) return false;
  const [match] = Editor.nodes(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && node.type === format,
  });
  return !!match;
};
 
export const getActiveAlignment = (editor: Editor): SlateTextAlign => {
  const {selection} = editor;
  if (!selection) return 'left';
  const [match] = Editor.nodes(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && Editor.isBlock(editor, node) && isFormattableBlock(node),
  });
  if (!match) return 'left';
  const [element] = match as [CustomElement, number[]];
  return (element as {align?: SlateTextAlign}).align ?? 'left';
};
 
export const isAlignmentActive = (editor: Editor, alignment: SlateTextAlign): boolean =>
  getActiveAlignment(editor) === alignment;
 
const unwrapLists = (editor: Editor): void => {
  Transforms.unwrapNodes(editor, {
    match: (node) => isElement(node) && isListType(node.type),
    split: true,
  });
};
 
export const getCurrentBlockEntry = (editor: Editor): [CustomElement, Path] | null => {
  const {selection} = editor;
  Iif (!selection) return null;
  const match = Editor.above(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && Editor.isBlock(editor, node),
    mode: 'lowest',
  });
  return (match as [CustomElement, Path] | undefined) ?? null;
};
 
const getCurrentListType = (editor: Editor): ListElementType | null => {
  const {selection} = editor;
  Iif (!selection) return null;
  const match = Editor.above(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && isListType(node.type),
    mode: 'lowest',
  });
  return match ? ((match[0] as CustomElement).type as ListElementType) : null;
};
 
export const toggleBlock = (editor: Editor, format: BlockFormat): void => {
  const isList = isListType(format);
  const isActive = isList ? isListActive(editor, format) : isBlockActive(editor, format);
  unwrapLists(editor);
  const nextType = isActive ? 'p' : isList ? 'li' : format;
  Transforms.setNodes(editor, {type: nextType} as Partial<CustomElement>, {
    match: (node) => isElement(node) && Editor.isBlock(editor, node) && isFormattableBlock(node),
  });
  if (!isActive && isList) {
    Transforms.wrapNodes(editor, {type: format, children: []} as CustomElement, {
      match: (node) => isElement(node) && node.type === 'li',
    });
  }
  if (format === 'checklist' && !isActive) {
    Transforms.setNodes(editor, {checked: false} as Partial<CustomElement>, {
      match: (node) => isElement(node) && node.type === 'li',
    });
  } else {
    Transforms.unsetNodes(editor, 'checked', {
      match: (node) => isElement(node) && Editor.isBlock(editor, node) && !isListType(node.type),
    });
  }
};
 
export const setAlignment = (editor: Editor, alignment: SlateTextAlign): void => {
  const current = getActiveAlignment(editor);
  const shouldUnset = alignment === 'left' || current === alignment;
 
  if (shouldUnset) {
    Transforms.unsetNodes(editor, 'align', {
      match: (node) => isElement(node) && Editor.isBlock(editor, node) && isFormattableBlock(node),
    });
    return;
  }
 
  Transforms.setNodes(editor, {align: alignment} as Partial<CustomElement>, {
    match: (node) => isElement(node) && Editor.isBlock(editor, node) && isFormattableBlock(node),
  });
};
 
export const eraseMarks = (editor: Editor): void => {
  removeLink(editor);
  for (const mark of MARKS) Editor.removeMark(editor, mark);
};
 
export const setChecklistItemChecked = (editor: Editor, path: Path, checked: boolean): void => {
  Transforms.setNodes(editor, {checked} as Partial<CustomElement>, {
    at: path,
    match: (node) => isElement(node) && node.type === 'li',
  });
};
 
export const resetEmptyBlockToP = (editor: Editor): boolean => {
  const {selection} = editor;
  Iif (!selection || !Range.isCollapsed(selection)) return false;
  const entry = getCurrentBlockEntry(editor);
  Iif (!entry) return false;
  const [block] = entry;
  Iif (block.type === 'embed') return false;
  if (Node.string(block) !== '') return false;
  Iif (block.type === 'p') return false;
  if (block.type === 'li') {
    const listType = getCurrentListType(editor);
    Iif (!listType) {
      Transforms.setNodes(editor, {type: 'p'} as Partial<CustomElement>, {
        match: (node) => isElement(node) && Editor.isBlock(editor, node) && node.type === 'li',
      });
      return true;
    }
    toggleBlock(editor, listType);
    return true;
  }
  toggleBlock(editor, block.type as Exclude<BlockFormat, ListElementType>);
  return true;
};
 
export const isInRawTextBlock = (editor: Editor): boolean =>
  isBlockActive(editor, 'code-block') || isBlockActive(editor, 'pre');
 
export const insertCodeBlockBreak = (editor: Editor): boolean => {
  Eif (!isInRawTextBlock(editor)) return false;
  Editor.insertText(editor, '\n');
  return true;
};
 
export const insertCodeBlockExit = (editor: Editor): boolean => {
  const {selection} = editor;
  Iif (!selection) return false;
  const [match] = Editor.nodes(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && (node.type === 'code-block' || node.type === 'pre'),
  });
  Iif (!match) return false;
  const [, path] = match;
  const afterPath = Path.next(path);
  Transforms.insertNodes(editor, {type: 'p', children: [{text: ''}]} as CustomElement, {at: afterPath});
  Transforms.select(editor, afterPath);
  return true;
};
 
/**
 * If the caret is anywhere inside a `stepper` list, drop a fresh paragraph
 * after the list and move the caret there — an explicit way to "exit" the
 * stepper without having to land on an empty step.
 */
export const exitStepperList = (editor: Editor): boolean => {
  const {selection} = editor;
  if (!selection) return false;
  const match = Editor.above(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && (node as CustomElement).type === 'stepper',
    mode: 'lowest',
  });
  if (!match) return false;
  const [, path] = match as [CustomElement, Path];
  const afterPath = Path.next(path);
  Transforms.insertNodes(editor, {type: 'p', children: [{text: ''}]} as CustomElement, {at: afterPath});
  Transforms.select(editor, afterPath);
  return true;
};
 
const isInStepperLi = (editor: Editor): boolean => {
  const {selection} = editor;
  Iif (!selection) return false;
  const li = Editor.above(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && (node as CustomElement).type === 'li',
    mode: 'lowest',
  });
  Eif (!li) return false;
  const stepper = Editor.above(editor, {
    at: li[1],
    match: (node) => isElement(node) && (node as CustomElement).type === 'stepper',
    mode: 'lowest',
  });
  return !!stepper;
};
 
/**
 * If the caret is at the end of a code-block or pre block and the block's
 * text content already ends with `\n\n`, strip those trailing newlines and
 * exit the block into a new paragraph below.
 */
export const tryExitCodeBlockOnTripleEnter = (editor: Editor): boolean => {
  const {selection} = editor;
  Iif (!selection || !Range.isCollapsed(selection)) return false;
  const match = Editor.above(editor, {
    at: selection,
    match: (node) => isElement(node) && (node.type === 'code-block' || node.type === 'pre'),
    mode: 'lowest',
  });
  if (!match) return false;
  const [block, path] = match as [CustomElement, Path];
  if (!Editor.isEnd(editor, selection.anchor, path)) return false;
  if (!Node.string(block).endsWith('\n\n')) return false;
  Transforms.delete(editor, {distance: 2, unit: 'character', reverse: true});
  return insertCodeBlockExit(editor);
};
 
const HEADING_TYPES: ReadonlySet<string> = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'title', 'subtitle']);
 
/**
 * If the caret is at offset 0 of a block whose previous sibling is an empty
 * `<p>`, remove that empty paragraph.
 */
export const removeEmptyPrevP = (editor: Editor): boolean => {
  const {selection} = editor;
  Iif (!selection || !Range.isCollapsed(selection)) return false;
  const entry = getCurrentBlockEntry(editor);
  Iif (!entry) return false;
  const [, path] = entry;
  if (!Editor.isStart(editor, selection.anchor, path)) return false;
  if (!Path.hasPrevious(path)) return false;
  const prevPath = Path.previous(path);
  let prevNode: unknown;
  try {
    prevNode = Node.get(editor, prevPath);
  } catch {
    return false;
  }
  Iif (!isElement(prevNode)) return false;
  if (prevNode.type !== 'p') return false;
  if (Node.string(prevNode) !== '') return false;
  Transforms.removeNodes(editor, {at: prevPath});
  return true;
};
 
/**
 * Backspace at offset 0 of a non-empty heading, blockquote, callout, or list
 * item converts that block to a paragraph instead of merging with the
 * previous block. Empty blocks are handled by `resetEmptyBlockToP`.
 */
export const resetBlockToPAtStart = (editor: Editor): boolean => {
  const {selection} = editor;
  Iif (!selection || !Range.isCollapsed(selection)) return false;
  const entry = getCurrentBlockEntry(editor);
  Iif (!entry) return false;
  const [block, path] = entry;
  if (Node.string(block) === '') return false;
  if (!Editor.isStart(editor, selection.anchor, path)) return false;
  const isResettable =
    HEADING_TYPES.has(block.type) || block.type === 'blockquote' || block.type === 'callout' || block.type === 'li';
  if (!isResettable) return false;
  if (block.type === 'li') {
    const listType = getCurrentListType(editor);
    Iif (!listType) {
      Transforms.setNodes(editor, {type: 'p'} as Partial<CustomElement>, {
        match: (node) => isElement(node) && Editor.isBlock(editor, node) && node.type === 'li',
      });
      return true;
    }
    toggleBlock(editor, listType);
    return true;
  }
  toggleBlock(editor, block.type as Exclude<BlockFormat, ListElementType>);
  return true;
};
 
export const withCodeBlockBreaks = <T extends Editor>(editor: T): T => {
  const {insertBreak} = editor;
  editor.insertBreak = () => {
    Iif (tryExitCodeBlockOnTripleEnter(editor)) return;
    Iif (insertCodeBlockBreak(editor)) return;
    Iif (resetEmptyBlockToP(editor)) return;
    const activeBlock = getActiveBlock(editor);
    const inHeading = activeBlock && HEADING_TYPES.has(activeBlock.type);
    const inHeadingOrBlockquoteOrCallout = activeBlock && ['blockquote', 'callout'].includes(activeBlock.type);
    const atEndOfTitle = isAtEndOfBlock(editor, 'title');
    const inStepperLi = isInStepperLi(editor);
    let convertPreviousSibling = false;
    Eif (inHeading || inHeadingOrBlockquoteOrCallout) {
      const entry = getCurrentBlockEntry(editor);
      const sel = editor.selection;
      Eif (entry && sel && Range.isCollapsed(sel)) {
        convertPreviousSibling = Editor.isStart(editor, sel.anchor, entry[1]);
      }
    }
    const inCallout = activeBlock && activeBlock.type === 'callout';
    insertBreak();
    Eif (inHeading || inHeadingOrBlockquoteOrCallout) {
      const nextType: CustomElement['type'] = atEndOfTitle ? 'subtitle' : 'p';
      let targetPath: Path | undefined;
      if (convertPreviousSibling) {
        const cursorEntry = getCurrentBlockEntry(editor);
        Eif (cursorEntry && Path.hasPrevious(cursorEntry[1])) {
          targetPath = Path.previous(cursorEntry[1]);
          Transforms.setNodes(editor, {type: nextType} as Partial<CustomElement>, {at: targetPath});
        }
      } else {
        Transforms.setNodes(editor, {type: nextType} as Partial<CustomElement>);
      }
      // Drop callout-specific attributes so the new <p> doesn't inherit them
      // when the user breaks out of a callout.
      Iif (inCallout) {
        const unsetOpts = targetPath ? {at: targetPath} : undefined;
        Transforms.unsetNodes(editor, ['variant', 'icon', 'title', 'color'], unsetOpts);
      }
    }
    Iif (inStepperLi) {
      Transforms.unsetNodes(
        editor,
        [
          'stepTitle',
          'stepDesc',
          'stepState',
          'stepIndicator',
          'stepChar',
          'stepCol',
          'stepBg',
          'ring',
          'ringCol',
          'ringWidth',
          'halo',
          'haloCol',
          'haloWidth',
          'line',
          'lineCol',
          'lineWidth',
        ],
        {match: (node) => isElement(node) && (node as CustomElement).type === 'li'},
      );
    }
  };
 
  // Inside a code-block or pre block, paste raw text.
  const reactEditor = editor as Editor & {insertData?: (data: DataTransfer) => void};
  const {insertData} = reactEditor;
  Iif (insertData) {
    reactEditor.insertData = (data: DataTransfer) => {
      if (isInRawTextBlock(editor)) {
        const text = data.getData('text/plain');
        if (text) {
          Editor.insertText(editor, text);
          return;
        }
      }
      insertData(data);
    };
  }
  return editor;
};
 
export const canUndo = (editor: Editor): boolean =>
  HistoryEditor.isHistoryEditor(editor) && editor.history.undos.length > 0;
 
export const canRedo = (editor: Editor): boolean =>
  HistoryEditor.isHistoryEditor(editor) && editor.history.redos.length > 0;
 
export const undo = (editor: Editor): void => {
  if (HistoryEditor.isHistoryEditor(editor)) editor.undo();
};
 
export const redo = (editor: Editor): void => {
  if (HistoryEditor.isHistoryEditor(editor)) editor.redo();
};
 
export const MARK_BUTTONS: ToolbarButtonDefinition<MarkFormat>[] = [
  {key: 'bold', title: 'Bold', iconSet: 'radix', icon: 'font-bold', shortcut: 'Cmd+B', format: 'bold'},
  {key: 'italic', title: 'Italic', iconSet: 'lucide', icon: 'italic', shortcut: 'Cmd+I', format: 'italic'},
  {key: 'underline', title: 'Underline', iconSet: 'tabler', icon: 'underline', shortcut: 'Cmd+U', format: 'underline'},
  {key: 'code', title: 'Inline code', iconSet: 'tabler', icon: 'code', shortcut: 'Cmd+E', format: 'code'},
];
 
export const ACTION_BUTTONS: ToolbarButtonDefinition[] = [
  {key: 'undo', title: 'Undo', iconSet: 'lucide', icon: 'undo', shortcut: 'Cmd+Z'},
  {key: 'redo', title: 'Redo', iconSet: 'lucide', icon: 'redo', shortcut: 'Cmd+Shift+Z'},
];