From 80f682428efe18a153549b296e15fafb631aaee6 Mon Sep 17 00:00:00 2001 From: "s.siefke.ext@bitworkers.eu" Date: Sun, 14 Apr 2019 22:16:55 +0200 Subject: [PATCH] fix: preview now working for files without xmlns --- package.json | 2 +- packages/extension/src/configuration.ts | 3 --- packages/extension/src/preview/preview.ts | 30 ++++++++++++++++++++++- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index e38d466..6fcc40c 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,7 @@ "bundlesize": [ { "path": "./packages/extension/dist/extension.js", - "maxSize": "7.2 kB", + "maxSize": "7.6 kB", "compression": "none" }, { diff --git a/packages/extension/src/configuration.ts b/packages/extension/src/configuration.ts index cdc7490..819d9f6 100644 --- a/packages/extension/src/configuration.ts +++ b/packages/extension/src/configuration.ts @@ -40,7 +40,6 @@ export const configuration: Configuration = { addChangeListener(callback) { if (!listeners) { listeners = [] - console.log('inside') context.subscriptions.push( vscode.workspace.onDidChangeConfiguration(event => { if (!event.affectsConfiguration('svgPreview')) { @@ -60,11 +59,9 @@ export const configuration: Configuration = { listeners.push(callback) }, get(key, resource) { - console.log('before') const result = vscode.workspace .getConfiguration('svgPreview', resource) .get(key) - console.log('after') return result }, } diff --git a/packages/extension/src/preview/preview.ts b/packages/extension/src/preview/preview.ts index d501ba2..5c400b8 100644 --- a/packages/extension/src/preview/preview.ts +++ b/packages/extension/src/preview/preview.ts @@ -140,13 +140,41 @@ const postMessage = (message: Message): void => { }) } +function indexOfGroup(match, n): number { + let { index } = match + for (let i = 1; i < n; i++) { + index += match[i].length + } + return index +} + +async function getActualContent(): Promise { + let content = await withInlineStyles( + path.dirname(state.fsPath), + state.content + ) + const match = /(]*?)(>)/i.exec(content) + if (match) { + // insert xmlns if it doesn't exist + const svgTagStart = indexOfGroup(match, 0) + const svgTagEnd = indexOfGroup(match, 3) + const svgTagContent = content.slice(svgTagStart, svgTagEnd) + if (!/xmlns=/.test(svgTagContent)) { + content = `${content.slice( + 0, + svgTagStart + 4 + )} xmlns="http://www.w3.org/2000/svg" ${content.slice(svgTagStart + 4)}` + } + } + return content +} /** * Update the contents. */ async function invalidateContent(): Promise { postMessage({ command: 'update.content', - payload: await withInlineStyles(path.dirname(state.fsPath), state.content), + payload: await getActualContent(), }) }