Skip to content

Commit

Permalink
fix(gatsby-plugin-sharp): url encode file names (gatsbyjs#10650)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
huntercaron authored and gpetrioli committed Jan 22, 2019
1 parent 4ebc2e5 commit f958e43
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
27 changes: 25 additions & 2 deletions packages/gatsby-plugin-sharp/src/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`, () => {
Expand Down Expand Up @@ -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: {
Expand Down
6 changes: 5 additions & 1 deletion packages/gatsby-plugin-sharp/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit f958e43

Please sign in to comment.