From fe4abb83064b5a5f4b6a875fd07ab642782431b2 Mon Sep 17 00:00:00 2001 From: John Philip Date: Sun, 16 Feb 2025 23:30:23 -0500 Subject: [PATCH] update logic for determining if svg needs to be fetched Signed-off-by: John Philip --- .changeset/techdocs-late-ants-remain.md | 5 +++ .../reader/transformers/addBaseUrl.test.ts | 32 +++++++++++++++++++ .../src/reader/transformers/addBaseUrl.ts | 5 ++- 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 .changeset/techdocs-late-ants-remain.md diff --git a/.changeset/techdocs-late-ants-remain.md b/.changeset/techdocs-late-ants-remain.md new file mode 100644 index 0000000000..cb1d34b461 --- /dev/null +++ b/.changeset/techdocs-late-ants-remain.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-techdocs': patch +--- + +Updates logic to check for SVG sources when inlining svgs. diff --git a/plugins/techdocs/src/reader/transformers/addBaseUrl.test.ts b/plugins/techdocs/src/reader/transformers/addBaseUrl.test.ts index 0fb72caab3..3e4b70a9a9 100644 --- a/plugins/techdocs/src/reader/transformers/addBaseUrl.test.ts +++ b/plugins/techdocs/src/reader/transformers/addBaseUrl.test.ts @@ -137,6 +137,36 @@ describe('addBaseUrl', () => { }); }); + it('preserves anchors in the original src', async () => { + const svgContent = ''; + const expectedSrc = `data:image/svg+xml;base64,${Buffer.from( + svgContent, + ).toString('base64')}`; + + (global.fetch as jest.Mock).mockReturnValue({ + text: jest.fn().mockResolvedValue(svgContent), + }); + + const root = await createTestShadowDom( + '', + { + preTransformers: [ + addBaseUrl({ + techdocsStorageApi, + entityId: mockEntityId, + path: '', + }), + ], + postTransformers: [], + }, + ); + + await waitFor(() => { + const actualSrc = root.getElementById('x')?.getAttribute('src'); + expect(expectedSrc).toEqual(actualSrc); + }); + }); + it('inlines absolute url svgs pointed at our backend', async () => { const svgContent = ''; const expectedSrc = `data:image/svg+xml;base64,${Buffer.from( @@ -195,4 +225,6 @@ describe('addBaseUrl', () => { }); }); }); + + it('preserves metadata about the original src', async () => {}); }); diff --git a/plugins/techdocs/src/reader/transformers/addBaseUrl.ts b/plugins/techdocs/src/reader/transformers/addBaseUrl.ts index 96a5888a2a..04ce4222d3 100644 --- a/plugins/techdocs/src/reader/transformers/addBaseUrl.ts +++ b/plugins/techdocs/src/reader/transformers/addBaseUrl.ts @@ -33,7 +33,10 @@ const isSvgNeedingInlining = ( attrVal: string, apiOrigin: string, ) => { - const isSrcToSvg = attrName === 'src' && attrVal.endsWith('.svg'); + // Let's let the URL object do automatic parsing of the pathname for us + const pathname = new URL(attrVal, 'https://ignored.com').pathname; + const isSrcToSvg = attrName === 'src' && pathname.endsWith('.svg'); + const isRelativeUrl = !attrVal.match(/^([a-z]*:)?\/\//i); const pointsToOurBackend = attrVal.startsWith(apiOrigin); return isSrcToSvg && (isRelativeUrl || pointsToOurBackend);