diff --git a/README.md b/README.md index 63e2333..5c178eb 100644 --- a/README.md +++ b/README.md @@ -56,13 +56,30 @@ Check out the [tests](./src/__tests__/index.ts) for some examples. ## API -### `visualHTML(div: Element, options?: { shallow?: boolean })` +### `visualHTML(div: Element, options?: { shallow?: boolean, styleRules?: SelectorWithStyles[] })` ```javascript visualHTML(document.body); // Returns the visual information of all nested elements in the body. visualHTML(document.body, { shallow: true }); // Returns just visual information for the `` element. ``` +### `getDocumentStyleRules(document: Document)` + +Every capture reads and specificity sorts the document's style rules, which is +the bulk of its work. A suite capturing many elements against the same +stylesheets can do that once and hand the result to each call: + +```javascript +const styleRules = getDocumentStyleRules(document); + +for (const el of elements) { + snapshot(visualHTML(el, { styleRules })); +} +``` + +Media conditions are evaluated as the rules are read, so parse again whenever +the viewport changes. + ## How it works `visual-html` works by building up an HTML representation of the DOM including only attributes that account for the visual display of the element. diff --git a/src/__tests__/index.ts b/src/__tests__/index.ts index 5abcf01..2aa33ac 100644 --- a/src/__tests__/index.ts +++ b/src/__tests__/index.ts @@ -1,4 +1,4 @@ -import visualHTML from ".."; +import visualHTML, { getDocumentStyleRules } from ".."; const { matchMedia: _matchMedia } = window; const { supports: _supports } = @@ -370,3 +370,129 @@ function testHTML(html: string, styles: string = "") { document.head.removeChild(style); return result; } + +test("styles an element from pre-parsed rules after its stylesheet is gone", () => { + const style = document.createElement("style"); + style.innerHTML = ".parsed { color: green; }"; + document.head.appendChild(style); + const div = document.createElement("div"); + div.className = "parsed"; + document.body.appendChild(div); + + const styleRules = getDocumentStyleRules(document); + document.head.removeChild(style); + const result = visualHTML(div, { styleRules }); + document.body.removeChild(div); + + expect(result).toMatchInlineSnapshot(`"
"`); +}); + +test("keeps urls as authored rather than resolved against the document", () => { + expect( + testHTML(` +