Account for displaying SVGs in the frontend.
Signed-off-by: Eric Peterson <ericpeterson@spotify.com>
This commit is contained in:
@@ -47,8 +47,17 @@ const mockEntityId = {
|
||||
namespace: '',
|
||||
name: '',
|
||||
};
|
||||
|
||||
describe('addBaseUrl', () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
beforeEach(() => {
|
||||
global.fetch = jest.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it('contains relative paths', () => {
|
||||
createTestShadowDom(fixture, {
|
||||
preTransformers: [
|
||||
@@ -86,4 +95,34 @@ describe('addBaseUrl', () => {
|
||||
'',
|
||||
);
|
||||
});
|
||||
|
||||
it('transforms svg img src to data uri', async () => {
|
||||
const svgContent = '<svg></svg>';
|
||||
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 = createTestShadowDom('<img id="x" src="test.svg" />', {
|
||||
preTransformers: [
|
||||
addBaseUrl({
|
||||
techdocsStorageApi,
|
||||
entityId: mockEntityId,
|
||||
path: '',
|
||||
}),
|
||||
],
|
||||
postTransformers: [],
|
||||
});
|
||||
|
||||
await new Promise<void>(done => {
|
||||
process.nextTick(() => {
|
||||
const actualSrc = root.getElementById('x')?.getAttribute('src');
|
||||
expect(expectedSrc).toEqual(actualSrc);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -38,10 +38,27 @@ export const addBaseUrl = ({
|
||||
.forEach(async (elem: T) => {
|
||||
const elemAttribute = elem.getAttribute(attributeName);
|
||||
if (!elemAttribute) return;
|
||||
elem.setAttribute(
|
||||
attributeName,
|
||||
await techdocsStorageApi.getBaseUrl(elemAttribute, entityId, path),
|
||||
|
||||
// Special handling for SVG images.
|
||||
const newValue = await techdocsStorageApi.getBaseUrl(
|
||||
elemAttribute,
|
||||
entityId,
|
||||
path,
|
||||
);
|
||||
if (attributeName === 'src' && elemAttribute.endsWith('.svg')) {
|
||||
try {
|
||||
const svg = await fetch(newValue);
|
||||
const svgContent = await svg.text();
|
||||
elem.setAttribute(
|
||||
attributeName,
|
||||
`data:image/svg+xml;base64,${btoa(svgContent)}`,
|
||||
);
|
||||
} catch (e) {
|
||||
elem.setAttribute('alt', `Error: ${elemAttribute}`);
|
||||
}
|
||||
} else {
|
||||
elem.setAttribute(attributeName, newValue);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user