Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[gatsby-plugin-sharp] Url Encoding Image File Names #10650

Merged
merged 4 commits into from
Dec 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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