From 7e77d8f1c94e730c449b47330604d28317e82e4b Mon Sep 17 00:00:00 2001 From: DK the Human Date: Thu, 5 Sep 2019 14:18:47 -0500 Subject: [PATCH] Update manifest on navigation --- .../src/__tests__/gatsby-browser.js | 64 +++++++++++++++++++ .../src/gatsby-browser.js | 26 ++++++++ 2 files changed, 90 insertions(+) create mode 100644 packages/gatsby-plugin-manifest/src/__tests__/gatsby-browser.js create mode 100644 packages/gatsby-plugin-manifest/src/gatsby-browser.js diff --git a/packages/gatsby-plugin-manifest/src/__tests__/gatsby-browser.js b/packages/gatsby-plugin-manifest/src/__tests__/gatsby-browser.js new file mode 100644 index 0000000000000..f36ee535d9b5f --- /dev/null +++ b/packages/gatsby-plugin-manifest/src/__tests__/gatsby-browser.js @@ -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 = `` + }) + + test(`has manifest in head`, () => { + const location = { + pathname: `/`, + } + onRouteUpdate({ location }, pluginOptions) + expect(document.head).toMatchInlineSnapshot(` + + + + `) + }) + + test(`changes href of manifest if navigating to a localized app`, () => { + const location = { + pathname: `/es/`, + } + onRouteUpdate({ location }, pluginOptions) + expect(document.head).toMatchInlineSnapshot(` + + + + `) + }) + + test(`keeps default manifest if not navigating to a localized app`, () => { + const location = { + pathname: `/random-path/`, + } + onRouteUpdate({ location }, pluginOptions) + expect(document.head).toMatchInlineSnapshot(` + + + + `) + }) +}) diff --git a/packages/gatsby-plugin-manifest/src/gatsby-browser.js b/packages/gatsby-plugin-manifest/src/gatsby-browser.js new file mode 100644 index 0000000000000..c3adc42caca67 --- /dev/null +++ b/packages/gatsby-plugin-manifest/src/gatsby-browser.js @@ -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` +}