Skip to content
Myr

markup.ts

This file

Path

apps/web/test/markup.ts

48 lines · 1.3 KiB · TypeScript

Last changed by

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

History of this file

Take it

Draw every list and subject from one row, one status line, one family fan and one set of fact blocksoscabrielbefore adoption886b726

lines 1–48why, one step back
1import type { ReactElement } from "react";
2import { renderToStaticMarkup } from "react-dom/server";34const ENTITIES: ReadonlyMap<string, string> = new Map([5 ["&#x27;", "'"],6 ["&amp;", "&"],7 ["&gt;", ">"],8 ["&lt;", "<"],9 ["&quot;", '"'],10]);1112export const markupOf = (element: ReactElement) =>13 renderToStaticMarkup(element);1415export const textIn = (markup: string) =>16 markup17 .replaceAll(/<[^>]+>/gu, "")18 .replaceAll(19 /&(?:#x27|amp|gt|lt|quot);/gu,20 (entity) => ENTITIES.get(entity) ?? entity21 );2223export const textOf = (element: ReactElement) => textIn(markupOf(element));2425export const positionsInOrder = (text: string, parts: readonly string[]) => {26 const positions: number[] = [];27 let from = 0;2829 for (const part of parts) {30 const at = from < 0 ? -1 : text.indexOf(part, from);3132 positions.push(at);33 from = at < 0 ? -1 : at + part.length;34 }3536 return positions;37};3839export const allInOrder = (text: string, parts: readonly string[]) =>40 positionsInOrder(text, parts).every((at) => at >= 0);4142export const tagsWith = (markup: string, attribute: string) =>43 [...markup.matchAll(/<[a-z][^>]*>/gu)].flatMap(([tag]) =>44 tag.includes(`${attribute}=`) ? [tag] : []45 );4647export const attributeOf = (tag: string, attribute: string) =>48 new RegExp(`\\b${attribute}="(?<value>[^"]*)"`, "u").exec(tag)?.groups?.value;