From f958e430cf32dfe3f2fe1788c31384329962ff0a Mon Sep 17 00:00:00 2001 From: Hunter Caron Date: Thu, 27 Dec 2018 05:40:53 -0500 Subject: [PATCH] fix(gatsby-plugin-sharp): url encode file names (#10650) Uses `encodeURI()` to fix an issue with image files that contain spaces in the name breaking srcset. This encodes the file names with the appropriate `%20` and such. --- .../src/__tests__/index.js | 27 +++++++++++++++++-- packages/gatsby-plugin-sharp/src/index.js | 6 ++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/packages/gatsby-plugin-sharp/src/__tests__/index.js b/packages/gatsby-plugin-sharp/src/__tests__/index.js index a5bf03e437d12..a1d38df161a7f 100644 --- a/packages/gatsby-plugin-sharp/src/__tests__/index.js +++ b/packages/gatsby-plugin-sharp/src/__tests__/index.js @@ -45,6 +45,29 @@ describe(`gatsby-plugin-sharp`, () => { // We expect value to be rounded to 1 expect(result.height).toBe(1) }) + + it(`file name works with spaces & special characters`, async () => { + // test name encoding with various characters + const testName = `spaces and '"@#$%^&,` + + const queueResult = await queueImageResizing({ + file: getFileObject( + path.join(__dirname, `images/144-density.png`), + testName + ), + args: { width: 3 }, + }) + + const queueResultName = path.parse(queueResult.src).name + + // decoding to check for outputting same name + expect(decodeURIComponent(queueResultName)).toBe(testName) + + // regex for special characters above and spaces + // testname should match, the queue result should not + expect(testName.match(/[!@#$^&," ]/)).not.toBe(false) + expect(queueResultName.match(/[!@#$^&," ]/)).not.toBe(true) + }) }) describe(`fluid`, () => { @@ -298,10 +321,10 @@ describe(`gatsby-plugin-sharp`, () => { }) }) -function getFileObject(absolutePath) { +function getFileObject(absolutePath, name = `test`) { return { id: `${absolutePath} absPath of file`, - name: `test`, + name: name, absolutePath, extension: `png`, internal: { diff --git a/packages/gatsby-plugin-sharp/src/index.js b/packages/gatsby-plugin-sharp/src/index.js index dc17f04bcdc0b..9d805855032d2 100644 --- a/packages/gatsby-plugin-sharp/src/index.js +++ b/packages/gatsby-plugin-sharp/src/index.js @@ -451,9 +451,13 @@ function queueImageResizing({ file, args = {}, reporter }) { queueJob(job, reporter) + // encode the file name for URL + const encodedImgSrc = `/${encodeURIComponent(file.name)}.${fileExtension}` + // Prefix the image src. const digestDirPrefix = `${file.internal.contentDigest}/${argsDigestShort}` - const prefixedSrc = options.pathPrefix + `/static/${digestDirPrefix}` + imgSrc + const prefixedSrc = + options.pathPrefix + `/static/${digestDirPrefix}` + encodedImgSrc return { src: prefixedSrc,