Skip to content

Commit

Permalink
Update manifest on navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
DK the Human committed Sep 5, 2019
1 parent 148d236 commit 7e77d8f
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
64 changes: 64 additions & 0 deletions packages/gatsby-plugin-manifest/src/__tests__/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { onRouteUpdate } from "../gatsby-browser"

describe(`gatsby-plugin-manifest`, () => {
const pluginOptions = {
name: `My Website`,
start_url: `/`,
localize: [
{
start_url: `/es/`,
lang: `es`,
},
],
}

beforeEach(() => {
global.__PATH_PREFIX__ = ``
document.head.innerHTML = `<link rel="manifest" href="/manifest.webmanifest">`
})

test(`has manifest in head`, () => {
const location = {
pathname: `/`,
}
onRouteUpdate({ location }, pluginOptions)
expect(document.head).toMatchInlineSnapshot(`
<head>
<link
href="/manifest.webmanifest"
rel="manifest"
/>
</head>
`)
})

test(`changes href of manifest if navigating to a localized app`, () => {
const location = {
pathname: `/es/`,
}
onRouteUpdate({ location }, pluginOptions)
expect(document.head).toMatchInlineSnapshot(`
<head>
<link
href="/manifest_es.webmanifest"
rel="manifest"
/>
</head>
`)
})

test(`keeps default manifest if not navigating to a localized app`, () => {
const location = {
pathname: `/random-path/`,
}
onRouteUpdate({ location }, pluginOptions)
expect(document.head).toMatchInlineSnapshot(`
<head>
<link
href="/manifest.webmanifest"
rel="manifest"
/>
</head>
`)
})
})
26 changes: 26 additions & 0 deletions packages/gatsby-plugin-manifest/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { withPrefix as fallbackWithPrefix, withAssetPrefix } from "gatsby"

const withPrefix = withAssetPrefix || fallbackWithPrefix

exports.onRouteUpdate = function({ location }, pluginOptions) {
const { localize } = pluginOptions
const manifestFilename = getManifestForPathname(location.pathname, localize)

const manifestEl = document.head.querySelector(`link[rel="manifest"]`)
if (manifestEl) {
manifestEl.setAttribute(`href`, withPrefix(manifestFilename))
}
}

function getManifestForPathname(pathname, localizedApps) {
let suffix = ``
if (Array.isArray(localizedApps)) {
const appOptions = localizedApps.find(app =>
RegExp(`^${app.start_url}.*`, `i`).test(pathname)
)
if (appOptions) {
suffix = `_${appOptions.lang}`
}
}
return `manifest${suffix}.webmanifest`
}

0 comments on commit 7e77d8f

Please sign in to comment.