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

41.86% Statements 18/43
0% Branches 0/20
8.33% Functions 1/12
35.71% Lines 10/28

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 502x     2x   2x 37x   2x                         2x   2x           2x                         2x   2x          
import {Editor, Element as SlateElement, type Path, Transforms} from 'slate';
import type {BulletedListElement, CustomElement, ListElementType, NumberedListElement, OlType, UlType} from '../types';
 
export const LIST_TYPES: ListElementType[] = ['ul', 'ol', 'checklist', 'stepper'];
 
const isElement = (node: unknown): node is CustomElement => SlateElement.isElement(node);
export const isListType = (format: string): format is ListElementType => LIST_TYPES.includes(format as ListElementType);
 
export const getActiveUlType = (editor: Editor): UlType | null => {
  const {selection} = editor;
  if (!selection) return null;
  const match = Editor.above(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && node.type === 'ul',
    mode: 'lowest',
  });
  if (!match) return null;
  const [element] = match as [BulletedListElement, Path];
  return element.ulType ?? 'disc';
};
 
export const isUlTypeActive = (editor: Editor, ulType: UlType): boolean => getActiveUlType(editor) === ulType;
 
export const setUlType = (editor: Editor, ulType: UlType): void => {
  Transforms.setNodes(editor, {ulType} as Partial<CustomElement>, {
    match: (node) => isElement(node) && node.type === 'ul',
  });
};
 
export const getActiveOlType = (editor: Editor): OlType | null => {
  const {selection} = editor;
  if (!selection) return null;
  const match = Editor.above(editor, {
    at: Editor.unhangRange(editor, selection),
    match: (node) => isElement(node) && node.type === 'ol',
    mode: 'lowest',
  });
  if (!match) return null;
  const [element] = match as [NumberedListElement, Path];
  return element.olType ?? 'decimal';
};
 
export const isOlTypeActive = (editor: Editor, olType: OlType): boolean => getActiveOlType(editor) === olType;
 
export const setOlType = (editor: Editor, olType: OlType): void => {
  Transforms.setNodes(editor, {olType} as Partial<CustomElement>, {
    match: (node) => isElement(node) && node.type === 'ol',
  });
};