From 4bc6ad1bd5ab0b6eb0aacf1114970683ab7b41ee Mon Sep 17 00:00:00 2001 From: Jigar wala Date: Mon, 20 Feb 2023 18:03:39 +0530 Subject: [PATCH] :sparkles: Allow domTransformation to be passed as string (#1186) --- packages/dom/src/serialize-dom.js | 6 +++++- packages/dom/test/serialize-dom.test.js | 27 +++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/packages/dom/src/serialize-dom.js b/packages/dom/src/serialize-dom.js index 37802a133..a1b902c84 100644 --- a/packages/dom/src/serialize-dom.js +++ b/packages/dom/src/serialize-dom.js @@ -83,9 +83,13 @@ export function serializeDOM(options) { if (domTransformation) { try { + // eslint-disable-next-line no-eval + if (typeof (domTransformation) === 'string') domTransformation = window.eval(domTransformation); domTransformation(ctx.clone.documentElement); } catch (err) { - console.error('Could not transform the dom:', err.message); + let errorMessage = `Could not transform the dom: ${err.message}`; + ctx.warnings.add(errorMessage); + console.error(errorMessage); } } diff --git a/packages/dom/test/serialize-dom.test.js b/packages/dom/test/serialize-dom.test.js index dad4549bc..6a64377d3 100644 --- a/packages/dom/test/serialize-dom.test.js +++ b/packages/dom/test/serialize-dom.test.js @@ -236,8 +236,29 @@ describe('serializeDOM', () => { expect(document.querySelector('.delete-me').innerText).toBe('Delete me'); }); - it('logs any errors and returns the serialized DOM', () => { + it('String: transforms the DOM without modifying the original DOM', () => { let { html } = serializeDOM({ + domTransformation: "(dom) => { dom.querySelector('.delete-me').remove(); }" + }); + + expect(html).not.toMatch('Delete me'); + expect(document.querySelector('.delete-me').innerText).toBe('Delete me'); + }); + + it('String: Logs error when function is not correct', () => { + let { html, warnings } = serializeDOM({ + domTransformation: "(dom) => { dom.querySelector('.delete-me').delete(); }" + }); + + expect(html).toMatch('Delete me'); + expect(console.error) + .toHaveBeenCalledOnceWith('Could not transform the dom: dom.querySelector(...).delete is not a function'); + + expect(warnings).toEqual(['Could not transform the dom: dom.querySelector(...).delete is not a function']); + }); + + it('logs any errors and returns the serialized DOM', () => { + let { html, warnings } = serializeDOM({ domTransformation(dom) { throw new Error('test error'); // eslint-disable-next-line no-unreachable @@ -247,7 +268,9 @@ describe('serializeDOM', () => { expect(html).toMatch('Delete me'); expect(console.error) - .toHaveBeenCalledOnceWith('Could not transform the dom:', 'test error'); + .toHaveBeenCalledOnceWith('Could not transform the dom: test error'); + + expect(warnings).toEqual(['Could not transform the dom: test error']); }); }); });