utils.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { safeAttrValue } from 'xss';
  2. const checkedRegEx = /(\*|-) \[x\]/;
  3. const uncheckedRegEx = /(\*|-) \[\s\]/;
  4. /**
  5. * Toggles the checkbox at the specified index in the given markdown string.
  6. *
  7. * @param markdown - The markdown string containing checkboxes.
  8. * @param index - The index of the checkbox to toggle.
  9. * @returns The updated markdown string with the checkbox toggled.
  10. */
  11. export const toggleCheckbox = (markdown: string, index: number) => {
  12. let cursor = 0;
  13. const lines = markdown.split('\n');
  14. for (let lineNumber = 0; lineNumber < lines.length; lineNumber++) {
  15. const line = lines[lineNumber];
  16. const checked = checkedRegEx.test(line);
  17. const unchecked = uncheckedRegEx.test(line);
  18. if (checked || unchecked) {
  19. if (cursor === index) {
  20. const regExp = checked ? checkedRegEx : uncheckedRegEx;
  21. const replacement = checked ? '[ ]' : '[x]';
  22. lines[lineNumber] = line.replace(regExp, `$1 ${replacement}`);
  23. break;
  24. }
  25. cursor++;
  26. }
  27. }
  28. return lines.join('\n');
  29. };
  30. export function serializeAttr(tag: string, name: string, value: string) {
  31. const safe = safeAttrValue(tag, name, value, { process: (v) => v });
  32. return safe ? `${name}="${safe}"` : '';
  33. }