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 fileTake it
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import type { ReactElement } from "react";import { renderToStaticMarkup } from "react-dom/server";
const ENTITIES: ReadonlyMap<string, string> = new Map([ ["'", "'"], ["&", "&"], [">", ">"], ["<", "<"], [""", '"'],]);
export const markupOf = (element: ReactElement) => renderToStaticMarkup(element);
export const textIn = (markup: string) => markup .replaceAll(/<[^>]+>/gu, "") .replaceAll( /&(?:#x27|amp|gt|lt|quot);/gu, (entity) => ENTITIES.get(entity) ?? entity );
export const textOf = (element: ReactElement) => textIn(markupOf(element));
export const positionsInOrder = (text: string, parts: readonly string[]) => { const positions: number[] = []; let from = 0;
for (const part of parts) { const at = from < 0 ? -1 : text.indexOf(part, from);
positions.push(at); from = at < 0 ? -1 : at + part.length; }
return positions;};
export const allInOrder = (text: string, parts: readonly string[]) => positionsInOrder(text, parts).every((at) => at >= 0);
export const tagsWith = (markup: string, attribute: string) => [...markup.matchAll(/<[a-z][^>]*>/gu)].flatMap(([tag]) => tag.includes(`${attribute}=`) ? [tag] : [] );
export const attributeOf = (tag: string, attribute: string) => new RegExp(`\\b${attribute}="(?<value>[^"]*)"`, "u").exec(tag)?.groups?.value;