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

MWPW-145574 - Dynamic Nav Gnav Implementation #2180

Merged
merged 5 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
8 changes: 6 additions & 2 deletions libs/blocks/global-navigation/global-navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -949,8 +949,12 @@ class Gnav {

export default async function init(block) {
try {
const { locale, mep } = getConfig();
const url = getMetadata('gnav-source') || `${locale.contentRoot}/gnav`;
const { locale, mep, dynamicNavKey } = getConfig();
let url = getMetadata('gnav-source') || `${locale.contentRoot}/gnav`;
if (dynamicNavKey) {
const { default: dynamicNav } = await import('../../features/dynamic-navigation.js');
url = dynamicNav(url, dynamicNavKey);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should probably have a new function getGnavSource (or something along those lines) that produces the url and contains all the logic for generating the url within it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with Raghav, we should extract it into a separate function that generates the URL.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm. I am not so sure that I agree. The dynamic nav is an opt in feature requiring a consumer to update their config to have the dynamicNavKey in order to kick off the experience.

Though it may make the init function a bit cleaner, a function combining the two would mix both the default behavior and an opt in feature, which I am not certain aids in readability.

Interested to see what you think.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the future we may have logic added or subtracted from our hypothetical getSource function. init is and should be agnostic about the details of getting the url and that is communicated well by a separate function.

The separation between default and opt in behaviour can be communicated well enough in the function itself by the if statement you'll have to add. And the notion of what constitutes default vs non default behavior now and in the future is malleable enough that it makes sense to cordon it off from our main init logic so that it's clear in the future where gnav url generation logic should go.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I appreciate your thoughtful and full response! I see what you're saying. To be honest, I am still on the fence because it feels a bit like premature optimization and we'd be adding 3 lines of code by pulling these 5 out into a function.

Maybe @mokimo can weigh in since he recommended the approach.

Copy link
Contributor

@mokimo mokimo Apr 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sharmrj So you'd think something like this?

const getSource = async () => {
    const { locale, dynamicNavKey } = getConfig();
    let url = getMetadata('gnav-source') || `${locale.contentRoot}/gnav`;
    if (dynamicNavKey) {
      const { default: dynamicNav } = await import('../../features/dynamic-navigation.js');
      url = dynamicNav(url, dynamicNavKey);
    }
    return url
}

export default async function init(block) {
  try {
    const { locale, mep } = getConfig();
    const url = await getSource()
    const content = await fetchAndProcessPlainHtml({ url })
      .catch((e) => lanaLog({
        message: `Error fetching gnav content url: ${url}`,
        e,
        tags: 'errorType=error,module=gnav',
      }));
....

@sharmrj and @bandana147 are the new gnav code owners 😁 So if that's how they'd prefer it, no objections.

Since the init function is growing already, it does look pretty clean indeed, extracting it into a small helper

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup. That's what I was envisioning.

Copy link
Contributor Author

@JasonHowellSlavin JasonHowellSlavin Apr 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good. I'll make those changes you requested @sharmrj. Any thoughts on modifying the unit tests? Since the function is called in init seems that the tests can remain as is.

I'll be sure to update the docs as well @mokimo.

Thank you both for your input!

const content = await fetchAndProcessPlainHtml({ url })
.catch((e) => lanaLog({
message: `Error fetching gnav content url: ${url}`,
Expand Down
21 changes: 21 additions & 0 deletions libs/features/dynamic-navigation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { getMetadata } from '../utils/utils.js';

export default function dynamicNav(url, key) {
const metadataContent = getMetadata('dynamic-nav');

if (metadataContent === 'entry') {
window.sessionStorage.setItem('gnavSource', url);
window.sessionStorage.setItem('dynamicNavKey', key);
return url;
}

if (metadataContent !== 'on') return url;

if (key !== window.sessionStorage.getItem('dynamicNavKey')) return url;

const source = window.sessionStorage.getItem('gnavSource');

if (!source) return url;

return source;
JasonHowellSlavin marked this conversation as resolved.
Show resolved Hide resolved
}
26 changes: 26 additions & 0 deletions test/blocks/global-navigation/global-navigation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import globalNavigationMock from './mocks/global-navigation.plain.js';
import globalNavigationActiveMock from './mocks/global-navigation-active.plain.js';
import globalNavigationWideColumnMock from './mocks/global-navigation-wide-column.plain.js';
import globalNavigationCrossCloud from './mocks/global-navigation-cross-cloud.plain.js';
import { getConfig } from '../../../tools/send-to-caas/send-utils.js';

const ogFetch = window.fetch;

Expand Down Expand Up @@ -1406,5 +1407,30 @@ describe('global navigation', () => {
fetchStub.calledOnceWith('https://www.stage.adobe.com/federal/path/to/gnav.plain.html'),
).to.be.true;
});

it('fetches navigation saved in sessionStorage', async () => {
const dynamicNavOn = toFragment`<meta name="dynamic-nav" content="on">`;
const conf = getConfig();
setConfig({ dynamicNavKey: 'milo', ...conf });
document.head.append(dynamicNavOn);
window.sessionStorage.setItem('dynamicNavKey', 'milo');
window.sessionStorage.setItem('gnavSource', '/some-path');
await initGnav(document.body.querySelector('header'));
expect(
fetchStub.calledOnceWith('/some-path.plain.html'),
).to.be.true;
});

it('does not fetch from sessionStorage url when dyanmicNavKey is not present', async () => {
const dynamicNavOn = toFragment`<meta name="dynamic-nav" content="on">`;
document.head.append(dynamicNavOn);
document.body.replaceChildren(toFragment`<header class="global-navigation"></header>`);
window.sessionStorage.setItem('dynamicNavKey', 'milo');
window.sessionStorage.setItem('gnavSource', '/some-path');
await initGnav(document.body.querySelector('header'));
expect(
fetchStub.calledOnceWith('http://localhost:2000/gnav.plain.html'),
).to.be.true;
});
});
});
48 changes: 48 additions & 0 deletions test/features/dynamic-nav/dynamicNav.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { readFile } from '@web/test-runner-commands';
import { expect } from '@esm-bundle/chai';
import { setConfig } from '../../../libs/utils/utils.js';
import dynamicNav from '../../../libs/features/dynamic-navigation.js';

describe('Dynamic nav', () => {
beforeEach(() => {
const conf = { dynamicNavKey: 'bacom' };
setConfig(conf);
window.sessionStorage.setItem('gnavSource', 'some-source-string');
});

it('Saves the gnavSource and dynamicNavKey to session storage', async () => {
document.head.innerHTML = await readFile({ path: './mocks/entry.html' });
window.sessionStorage.removeItem('gnavSource');
dynamicNav('gnav/aem-sites', 'bacom');
expect(window.sessionStorage.getItem('gnavSource')).to.equal('gnav/aem-sites');
expect(window.sessionStorage.getItem('dynamicNavKey')).to.equal('bacom');
});

it('Returns the provided url when the dynamic nav metadata is not present', async () => {
document.head.innerHTML = await readFile({ path: './mocks/off.html' });
const url = dynamicNav('gnav/aem-sites', 'nocom');
expect(window.sessionStorage.getItem('gnavSource')).to.equal('some-source-string');
expect(url).to.equal('gnav/aem-sites');
});

it('Returns the provided url with when the wrong dynamicNavKey is passed', async () => {
document.head.innerHTML = await readFile({ path: './mocks/on.html' });
const url = dynamicNav('gnav/aem-sites', 'nocom');
expect(window.sessionStorage.getItem('gnavSource')).to.equal('some-source-string');
expect(url).to.equal('gnav/aem-sites');
});

it('Returns the sessionStorage url if the item exists, the keys match, and dynamic nav is on', async () => {
document.head.innerHTML = await readFile({ path: './mocks/on.html' });
const url = dynamicNav('gnav/aem-sites', 'bacom');
expect(window.sessionStorage.getItem('gnavSource')).to.equal('some-source-string');
expect(url).to.equal('some-source-string');
});

it('Returns the pprovided url if it does not find an item in sessionStorage and dynamic nav is on', async () => {
document.head.innerHTML = await readFile({ path: './mocks/on.html' });
window.sessionStorage.removeItem('gnavSource');
const url = dynamicNav('gnav/aem-sites', 'bacom');
expect(url).to.equal('gnav/aem-sites');
});
});
1 change: 1 addition & 0 deletions test/features/dynamic-nav/mocks/entry.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<meta name="dynamic-nav" content="entry">
1 change: 1 addition & 0 deletions test/features/dynamic-nav/mocks/off.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<meta name="stub" content="stub">
1 change: 1 addition & 0 deletions test/features/dynamic-nav/mocks/on.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<meta name="dynamic-nav" content="on">
Loading