Skip to content

Commit

Permalink
fix(documentation): storybook ready event and improved the google-tag…
Browse files Browse the repository at this point in the history
…-manager integration (#2210)
  • Loading branch information
oliverschuerch authored Nov 3, 2023
1 parent 146aba1 commit f8bb13b
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 71 deletions.
53 changes: 13 additions & 40 deletions packages/documentation/.storybook/manager-head.html
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
<script src="/assets/scripts/storybook-events.js"></script>
<script src="/assets/scripts/analytics-helper.js"></script>
<script src="/assets/scripts/analytics-events.js"></script>

<script data-id="GtmConstants">
window?.gtm?.setConstant('ENVIRONMENTS', {
dev: '%STORYBOOK_GTM_PAGE_CONTEXT_ENVIRONMENT_DEV%',
int: '%STORYBOOK_GTM_PAGE_CONTEXT_ENVIRONMENT_INT%',
prod: '%STORYBOOK_GTM_PAGE_CONTEXT_ENVIRONMENT_PROD%',
});
window.__GTM__.set('GTM_KEY', '%STORYBOOK_GTM_KEY%');

window?.gtm?.setConstant(
'ENVIRONMENT_FALLBACK',
window.__GTM__.setEnvironments(
{
dev: '%STORYBOOK_GTM_PAGE_CONTEXT_ENVIRONMENT_DEV%',
int: '%STORYBOOK_GTM_PAGE_CONTEXT_ENVIRONMENT_INT%',
prod: '%STORYBOOK_GTM_PAGE_CONTEXT_ENVIRONMENT_PROD%',
},
'%STORYBOOK_GTM_PAGE_CONTEXT_ENVIRONMENT_FALLBACK%',
);

window.__GTM__.set('CONTENT_LANGUAGE', '%STORYBOOK_GTM_PAGE_CONTEXT_CONTENT_LANGUAGE%');
window.__GTM__.set('GEO_REGION', '%STORYBOOK_GTM_PAGE_CONTEXT_CONTENT_GEO_REGION%');
window.__GTM__.set('SOURCE_CODE_VERSION', '%STORYBOOK_GTM_PAGE_CONTEXT_SOURCE_CODE_VERSION%');
</script>

<script data-id="GoogleTagManager">
Expand All @@ -29,39 +35,6 @@
})(window, document, 'script', 'dataLayer', '%STORYBOOK_GTM_KEY%');

window.dataLayer = window.dataLayer || [];

// Page Context
window.addEventListener('storybook:ready', function () {
window.dataLayer.push({
event: 'page_context', // constant, required
spa: 'true', // constant, required
content_language: '%STORYBOOK_GTM_PAGE_CONTEXT_CONTENT_LANGUAGE%', // required
content_geo_region: '%STORYBOOK_GTM_PAGE_CONTEXT_CONTENT_GEO_REGION%', // required
source_code_version: '%STORYBOOK_GTM_PAGE_CONTEXT_SOURCE_CODE_VERSION%', // recommended
page_name_language_neutral: window.gtm.getPageTitle(), // required
page_url_language_neutral: window.location.href, // required
environment: window.gtm.getEnvironment(), // required
login_status: 'false', // required
platform_name: 'ms_design_system', // required
department_name: 'IT16.12', // required
business_unit: 'IT', // required
primary_segment: 'allgemein', // required
});
});

// Page Change
window.addEventListener('storybook:routeChange', function () {
window.dataLayer.push({
event: 'page_change', // constant, required
content_language: '%STORYBOOK_GTM_PAGE_CONTEXT_CONTENT_LANGUAGE%', // required
content_geo_region: '%STORYBOOK_GTM_PAGE_CONTEXT_CONTENT_GEO_REGION%', // required
page_name_language_neutral: window.gtm.getPageTitle(), // required
page_url_language_neutral: window.location.href, // required
virtual_pageview: 'true', // SPA route change indicator, boolean true/false
virtual_page_name: window.gtm.getPageTitle(), // SPA route change/transition new page name/page title
virtual_url: window.location.href, // SPA route change new URL
});
});
</script>

<!-- Documentation: https://dev.to/masakudamatsu/favicon-nightmare-how-to-maintain-sanity-3al7 -->
Expand Down
32 changes: 32 additions & 0 deletions packages/documentation/public/assets/scripts/analytics-events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Page Context
window.addEventListener('storybook:ready', function () {
window.dataLayer.push({
event: 'page_context', // constant, required
spa: 'true', // constant, required
content_language: window.__GTM__.get('CONTENT_LANGUAGE'), // required
content_geo_region: window.__GTM__.get('GEO_REGION'), // required
source_code_version: window.__GTM__.get('SOURCE_CODE_VERSION'), // recommended
page_name_language_neutral: window.__GTM__.getPageTitle(), // required
page_url_language_neutral: window.location.href, // required
environment: window.__GTM__.getEnvironment(), // required
login_status: 'false', // required
platform_name: 'ms_design_system', // required
department_name: 'IT16.12', // required
business_unit: 'IT', // required
primary_segment: 'allgemein', // required
});
});

// Page Change
window.addEventListener('storybook:routeChange', function () {
window.dataLayer.push({
event: 'page_change', // constant, required
content_language: window.__GTM__.get('CONTENT_LANGUAGE'), // required
content_geo_region: window.__GTM__.get('GEO_REGION'), // required
page_name_language_neutral: window.__GTM__.getPageTitle(), // required
page_url_language_neutral: window.location.href, // required
virtual_pageview: 'true', // SPA route change indicator, boolean true/false
virtual_page_name: window.__GTM__.getPageTitle(), // SPA route change/transition new page name/page title
virtual_url: window.location.href, // SPA route change new URL
});
});
69 changes: 38 additions & 31 deletions packages/documentation/public/assets/scripts/analytics-helper.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,45 @@
window.onload = function () {
new MutationObserver(function () {
const storyAnker = document.querySelector('#storybook-preview-wrapper > a');
class GTM {
constructor() {
this.environments = {
envs: null,
fallback: '',
};
this.constants = {};
}

if (storyAnker) {
this.disconnect();
set(name, value) {
if (!this.constants[name]) this.constants[name] = value;
}

// execute on next cycle to ensure the doc-title has been updated by storybook
setTimeout(() => {
window.dispatchEvent(new Event('storybook:ready'));
});
get(name) {
if (this.constants[name]) return this.constants[name];

new MutationObserver(() => {
// execute on next cycle to ensure the doc-title has been updated by storybook
setTimeout(() => {
window.dispatchEvent(new Event('storybook:routeChange'));
});
}).observe(storyAnker, { attributes: true });
}
}).observe(document.querySelector('#storybook-preview-wrapper'), { childList: true });
};
console.warn(`GTM Warning: There is no such property with the name ${name}`);
return undefined;
}

window.gtm = window.gtm || {};
window.__GTM__ = window.__GTM__ || {};
setEnvironments(envs, fallback) {
if (typeof envs !== 'object') {
console.warn(
'GTM Warning: Setting the environments failed. The values where not provided as an object ({ [envName]: "url1,url2", ... }).',
);
} else if (this.environments.envs) {
console.warn('GTM Warning: Environments already set. You can set them only once.');
} else {
this.environments.envs = { ...envs };
this.environments.fallback = fallback ?? Object.values(envs)[0];
}
}

window.gtm.setConstant = function (name, value) {
if (!window.__GTM__[name]) window.__GTM__[name] = value;
};
getEnvironment() {
return (Object.entries(this.environments.envs).find(([_env, hosts = '']) =>
hosts.split(',').some(host => window.location.host.indexOf(host) === 0),
) ?? [this.environments.fallback])[0];
}

window.gtm.getEnvironment = function () {
return (Object.entries(window.__GTM__.ENVIRONMENTS).find(([_env, hosts = '']) =>
hosts.split(',').some(host => window.location.host.indexOf(host) === 0),
) ?? [window.__GTM__.ENVIRONMENT_FALLBACK])[0];
};
getPageTitle() {
return document.head.querySelector('title')?.text ?? '';
}
}

window.gtm.getPageTitle = function () {
return document.head.querySelector('title')?.text ?? '';
};
window.__GTM__ = new GTM();
33 changes: 33 additions & 0 deletions packages/documentation/public/assets/scripts/storybook-events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
window.onload = function () {
const previewWrapper = document.querySelector('#storybook-preview-wrapper');
let storyAnchor = document.querySelector('#storybook-preview-wrapper > a');

if (storyAnchor) {
// if storyAnchor already exists, just emit ready event and listen for route-changes
ready();
} else {
// if storyAnchor does not exist yet, wait until its rendered, then emit ready event and listen for route-changes
new MutationObserver(function () {
storyAnchor = document.querySelector('#storybook-preview-wrapper > a');

if (storyAnchor) {
this.disconnect();
ready();
}
}).observe(previewWrapper, { childList: true });
}

function ready() {
// execute on next cycle to ensure the doc-title has been updated by storybook
setTimeout(() => {
window.dispatchEvent(new Event('storybook:ready'));
});

new MutationObserver(() => {
// execute on next cycle to ensure the doc-title has been updated by storybook
setTimeout(() => {
window.dispatchEvent(new Event('storybook:routeChange'));
});
}).observe(storyAnchor, { attributes: true });
}
};

0 comments on commit f8bb13b

Please sign in to comment.