Skip to content

Commit

Permalink
Mwpw-138750 analytics update 2.1 (#1531)
Browse files Browse the repository at this point in the history
* mwpw-138750 analytics update 2.0

* pass placeholders from Target

* override and full url

* remove unneeded if

* add manifestUrl to Target

* add if back in to prevent duplicates

* add analytics btn and fix btn if Trgt on & no rtrn

* shorten analytics off title

* add indent to page button info

* make variantLable lower case for compare

* add ? if variantLabel is null

* merge manifest-utils into personalization

* remove 2 manifest-utils references

* remove 1 import of manifest-utils

* remove redundant function

* rework promise syntax

* update to "analytics manifest name"

* consolidate call of preview button

* update unit tests

* change controlPageLoad to true

* move functions to attributes.js

* streamline return line

* update regex for non latin alphabet

* remove empty line

* requested updates from Peyer

* restore constants in attributes

* mwpw-139041-ut-fix-v2

* rebase

* update normalizePath to other version

* ut coverage

---------

Co-authored-by: vivgoodrich <vivian.goodrich@gmail.com>
Co-authored-by: Blaine Gunn <Blainegunn@gmail.com>
  • Loading branch information
3 people authored Dec 4, 2023
1 parent a590648 commit c744452
Show file tree
Hide file tree
Showing 19 changed files with 380 additions and 158 deletions.
4 changes: 2 additions & 2 deletions libs/blocks/accordion/accordion.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createTag } from '../../utils/utils.js';
import { decorateButtons } from '../../utils/decorate.js';
import { processTrackingLabels } from '../../martech/analytics.js';
import { processTrackingLabels } from '../../martech/attributes.js';

const faq = { '@context': 'https://schema.org', '@type': 'FAQPage', mainEntity: [] };
const mediaCollection = {};
Expand Down Expand Up @@ -74,7 +74,7 @@ function createItem(accordion, id, heading, num, edit) {
const panelId = `accordion-${id}-content-${num}`;
const icon = createTag('span', { class: 'accordion-icon' });
const hTag = heading.querySelector('h1, h2, h3, h4, h5, h6');
const analyticsString = `open-${num}|${processTrackingLabels(heading.textContent)}`;
const analyticsString = `open-${num}--${processTrackingLabels(heading.textContent)}`;
const button = createTag('button', {
type: 'button',
id: triggerId,
Expand Down
3 changes: 2 additions & 1 deletion libs/blocks/global-navigation/utilities/utilities.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getConfig, getMetadata, loadStyle, loadLana } from '../../../utils/utils.js';
import { processTrackingLabels } from '../../../martech/attributes.js';

loadLana();

Expand Down Expand Up @@ -51,7 +52,7 @@ export const getFedsPlaceholderConfig = () => {
export function getAnalyticsValue(str, index) {
if (typeof str !== 'string' || !str.length) return str;

let analyticsValue = str.trim().replace(/[^\w]+/g, '_').replace(/^_+|_+$/g, '');
let analyticsValue = processTrackingLabels(str, false, 30);
analyticsValue = typeof index === 'number' ? `${analyticsValue}-${index}` : analyticsValue;

return analyticsValue;
Expand Down
19 changes: 14 additions & 5 deletions libs/features/personalization/add-preview-to-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,23 @@ export default async function addPreviewToConfig({
});

if (config.mep.override !== '') {
const persManifestPaths = persManifests.map((manifest) => {
if (manifest.startsWith('/')) return manifest;
try {
const url = new URL(manifest);
return url.pathname;
} catch (e) {
return manifest;
}
});

config.mep.override.split(',').forEach((manifestPair) => {
persManifests.push(manifestPair.trim().toLowerCase().split('--')[0]);
const manifestTitle = manifestPair.trim().toLowerCase().split('--')[0];
if (!persManifestPaths.includes(manifestTitle)) {
persManifests.push(manifestTitle);
}
});
}

if (config.mep.preview && !targetEnabled && !persManifests.length) {
import('./preview.js')
.then(({ default: decoratePreviewMode }) => decoratePreviewMode([]));
}
return persManifests;
}
39 changes: 0 additions & 39 deletions libs/features/personalization/manifest-utils.js

This file was deleted.

135 changes: 83 additions & 52 deletions libs/features/personalization/personalization.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable no-console */

import {
createTag, getConfig, loadIms, loadLink, loadScript, updateConfig,
} from '../../utils/utils.js';
Expand All @@ -11,6 +12,53 @@ const ENT_CACHE_EXPIRE = 1000 * 60 * 60 * 3; // 3 hours
const ENT_CACHE_REFRESH = 1000 * 60 * 3; // 3 minutes
const PAGE_URL = new URL(window.location.href);

export const NON_TRACKED_MANIFEST_TYPE = 'test or promo';

export const appendJsonExt = (path) => (path.endsWith('.json') ? path : `${path}.json`);

export const normalizePath = (p) => {
let path = p;

if (!path.includes('/')) {
return path;
}

const config = getConfig();

if (path.startsWith(config.codeRoot)
|| path.includes('.hlx.')
|| path.startsWith(`https://${config.productionDomain}`)) {
try {
path = new URL(path).pathname;
} catch (e) { /* return path below */ }
} else if (!path.startsWith('http') && !path.startsWith('/')) {
path = `/${path}`;
}
return path;
};

export const preloadManifests = ({ targetManifests = [], persManifests = [] }) => {
let manifests = targetManifests;

manifests = manifests.concat(
persManifests.map((manifestPath) => ({
manifestPath: appendJsonExt(manifestPath),
manifestUrl: manifestPath,
})),
);

for (const manifest of manifests) {
if (!manifest.manifestData && manifest.manifestPath) {
manifest.manifestPath = normalizePath(manifest.manifestPath);
loadLink(
manifest.manifestPath,
{ as: 'fetch', crossorigin: 'anonymous', rel: 'preload' },
);
}
}
return manifests;
};

/* c8 ignore start */
export const PERSONALIZATION_TAGS = {
all: () => true,
Expand Down Expand Up @@ -123,28 +171,6 @@ const consolidateObjects = (arr, prop) => arr.reduce((propMap, item) => {
return propMap;
}, {});

/* c8 ignore start */
function normalizePath(p) {
let path = p;

if (!path.includes('/')) {
return path;
}

const config = getConfig();

if (path.startsWith(config.codeRoot)
|| path.includes('.hlx.')
|| path.startsWith(`https://${config.productionDomain}`)) {
try {
path = new URL(path).pathname;
} catch (e) { /* return path below */ }
} else if (!path.startsWith('http') && !path.startsWith('/')) {
path = `/${path}`;
}
return path;
}

const matchGlob = (searchStr, inputStr) => {
const pattern = searchStr.replace(/\*\*/g, '.*');
const reg = new RegExp(`^${pattern}$`, 'i'); // devtool bug needs this backtick: `
Expand Down Expand Up @@ -403,7 +429,7 @@ async function getPersonalizationVariant(manifestPath, variantNames = [], varian
}

const matchVariant = (name) => {
if (name === variantLabel) return true;
if (name === variantLabel?.toLowerCase()) return true;
if (name.startsWith('param-')) return checkForParamMatch(name);
if (name.startsWith('ent-')) return checkForEntitlementMatch(name, entitlements);
if (entitlementKeys.includes(name)) {
Expand All @@ -416,21 +442,30 @@ async function getPersonalizationVariant(manifestPath, variantNames = [], varian
return matchingVariant;
}

export async function getPersConfig(name, variantLabel, manifestData, manifestPath) {
export async function getPersConfig(info) {
const {
name,
manifestData,
manifestPath,
manifestUrl,
manifestPlaceholders,
manifestInfo,
variantLabel,
} = info;
let data = manifestData;
if (!data) {
const fetchedData = await fetchData(manifestPath, DATA_TYPE.JSON);
if (fetchData) data = fetchedData;
}
let placeholders = false;
if (data?.placeholders?.data) {
placeholders = data.placeholders.data;
}

const persData = data?.experiences?.data || data?.data || data;
if (!persData) return null;
const config = parseConfig(persData);

const infoTab = manifestInfo || data?.info?.data;
config.manifestType = infoTab?.find((element) => element.key?.toLowerCase() === 'manifest-type')?.value?.toLowerCase() || 'personalization';
config.manifestOverrideName = infoTab?.find((element) => element.key?.toLowerCase() === 'manifest-override-name')?.value?.toLowerCase();

if (!config) {
/* c8 ignore next 3 */
console.log('Error loading personalization config: ', name || manifestPath);
Expand All @@ -453,6 +488,7 @@ export async function getPersConfig(name, variantLabel, manifestData, manifestPa
config.selectedVariant = 'default';
}

const placeholders = manifestPlaceholders || data?.placeholders?.data;
if (placeholders) {
updateConfig(
parsePlaceholders(placeholders, getConfig(), config.selectedVariantName),
Expand All @@ -461,6 +497,7 @@ export async function getPersConfig(name, variantLabel, manifestData, manifestPa

config.name = name;
config.manifest = manifestPath;
config.manifestUrl = manifestUrl;
return config;
}

Expand All @@ -475,14 +512,9 @@ const normalizeFragPaths = ({ selector, val }) => ({
});

export async function runPersonalization(info, config) {
const {
name,
manifestData,
manifestPath,
variantLabel,
} = info;
const { manifestPath } = info;

const experiment = await getPersConfig(name, variantLabel, manifestData, manifestPath);
const experiment = await getPersConfig(info);

if (!experiment) return null;

Expand Down Expand Up @@ -539,21 +571,10 @@ function cleanManifestList(manifests) {
return cleanedList;
}

const decoratePreviewCheck = async (config, experiments) => {
if (config.mep?.preview) {
const { default: decoratePreviewMode } = await import('./preview.js');
decoratePreviewMode(experiments);
}
};

export async function applyPers(manifests) {
const config = getConfig();

if (!manifests?.length) {
/* c8 ignore next */
decoratePreviewCheck(config, []);
return;
}
if (!manifests?.length) return;

getEntitlements();
const cleanedManifests = cleanManifestList(manifests);
Expand All @@ -572,9 +593,19 @@ export async function applyPers(manifests) {
expBlocks: consolidateObjects(results, 'blocks'),
expFragments: consolidateObjects(results, 'fragments'),
});
const trackingManifests = results.map((r) => r.experiment.manifest.split('/').pop().replace('.json', ''));
const trackingVariants = results.map((r) => r.experiment.selectedVariantName);
document.body.dataset.mep = `${trackingVariants.join('--')}|${trackingManifests.join('--')}`;

decoratePreviewCheck(config, experiments);
const pznList = results.filter((r) => (r.experiment.manifestType !== NON_TRACKED_MANIFEST_TYPE));
if (!pznList.length) {
document.body.dataset.mep = 'nopzn|nopzn';
return;
}
const pznVariants = pznList.map((r) => {
const val = r.experiment.selectedVariantName.replace('target-', '').trim().slice(0, 15);
return val === 'default' ? 'nopzn' : val;
});
const pznManifests = pznList.map((r) => {
const val = r.experiment?.manifestOverrideName || r.experiment?.manifest;
return val.split('/').pop().replace('.json', '').trim()
.slice(0, 15);
});
document.body.dataset.mep = `${pznVariants.join('--')}|${pznManifests.join('--')}`;
}
4 changes: 4 additions & 0 deletions libs/features/personalization/preview.css
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@
margin-left: 16px;
}

.mep-popup-header > div > div:not(.mep-manifest-page-info-title) {
padding-left: 15px;
}

@media screen and (max-width: 599px) {
.mep-hidden .mep-badge .mep-open {
margin-left: 0;
Expand Down
Loading

0 comments on commit c744452

Please sign in to comment.