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

Remove loadSegment related logic (leveraged GTM) #1217

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Next Next commit
remove loadSegment related logic (leveraged GTM)
jasonbryant84 committed Oct 3, 2024

Verified

This commit was signed with the committer’s verified signature. The key has expired.
Czaki Grzegorz Bokota
commit 3e702ae60a0b99b07a04009c278fac08eb31ead3
3 changes: 1 addition & 2 deletions qdrant-landing/themes/qdrant-2024/assets/js/cookit.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getCookie, setCookie } from './helpers';
import { loadSegment, handleConsent } from './segment-helpers';
import { handleConsent } from './segment-helpers';

(function () {
window.cookit = function (options) {
@@ -60,7 +60,6 @@ import { loadSegment, handleConsent } from './segment-helpers';
// EVENT LISTENER (click)
button.addEventListener('click', () => {
if (!window.analytics) {
loadSegment();
handleConsent();
}

8 changes: 1 addition & 7 deletions qdrant-landing/themes/qdrant-2024/assets/js/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import scrollHandler from './scroll-handler';
import { XXL_BREAKPOINT } from './constants';
import { initGoToTopButton, getCookie } from './helpers';
import { loadSegment, createSegmentStoredPage } from './segment-helpers';
import { initGoToTopButton } from './helpers';

createSegmentStoredPage();

// on document ready
document.addEventListener('DOMContentLoaded', function () {
if (!window.analytics && getCookie('cookie-consent')) {
loadSegment();
}

// Top banner activation
const topBanner = document.querySelector('.top-banner');
if (topBanner) {
208 changes: 13 additions & 195 deletions qdrant-landing/themes/qdrant-2024/assets/js/segment-helpers.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,10 @@
import { getCookie, devLog, tagCloudUILinksWithAnonymousId } from './helpers';
import { devLog, tagCloudUILinksWithAnonymousId } from './helpers';

const WRITE_KEY = 'segmentWriteKey';
const PAGES_SESSION_STORAGE_KEY = 'segmentPages';
const INTERACTIONS_SESSION_STORAGE_KEY = 'segmentInteractions';
const PAYLOAD_BOILERPLATE = {
url: window.location.href,
title: document.title,
};

/*******************/
/* General helpers */
/*******************/
const storedPayload = () => {
if (getCookie('cookie-consent')) {
return PAYLOAD_BOILERPLATE;
}

const now = new Date();
return {
...PAYLOAD_BOILERPLATE,
storedEvent: true,
storedTimestamp: now.toISOString(),
}
};

const nameMapper = (url) => { // Mapping names based on pathname for Segment
return url.includes('/blog/') ? 'Blog' : 'Marketing Site';
};


/***************/
/* DOM helpers */
/***************/
@@ -40,16 +16,11 @@ const handleClickInteraction = (event) => {
action: 'clicked'
};

// If consented to tracking the track
if(getCookie('cookie-consent')) {
trackInteractionEvent(payload);

// If element can be clicked more than once (ie user remains on same page)
if (!event.target.hasAttribute('data-metric-keep')) {
event.target.removeEventListener('click', handleClickInteraction);
}
} else { // If no consent yet the store in sessionStorage in case of later consent
createSegmentStoredInteraction(payload);
trackInteractionEvent(payload);

// If element can be clicked more than once (ie user remains on same page)
if (!event.target.hasAttribute('data-metric-keep')) {
event.target.removeEventListener('click', handleClickInteraction);
}
};

@@ -65,88 +36,9 @@ function tagAllAnchors() {
}
}

// Segment Key Getter & Setter
const getSegmentWriteKey = () => {
return JSON.parse(sessionStorage.getItem(WRITE_KEY));
}
export const setSegmentWriteKey = (segmentWriteKey) => {
sessionStorage.setItem(WRITE_KEY, JSON.stringify(segmentWriteKey));
}

/****************/
/* Segment CRUD */
/****************/
// Getters
const getSegmentStoredPages = () => { // Get Page Entires
return JSON.parse(sessionStorage.getItem(PAGES_SESSION_STORAGE_KEY) || '[]');
};
const getSegmentStoredInteractions = () => { // Get Interaction Entires
return JSON.parse(sessionStorage.getItem(INTERACTIONS_SESSION_STORAGE_KEY) || '[]');
};

// Deletions
const removeSegmentStoredPages = () => { // Remove Page Entires
sessionStorage.removeItem(PAGES_SESSION_STORAGE_KEY);
};
const removeSegmentStoredInteractions = () => { // Remove Interaction Entires
sessionStorage.removeItem(INTERACTIONS_SESSION_STORAGE_KEY);
};

// Create and Queue
export function createSegmentStoredPage() { // Create and Queue Page Entry
const payload = storedPayload();

const existingPages = JSON.parse(sessionStorage.getItem(PAGES_SESSION_STORAGE_KEY) || '[]');
const updatedPages = [...existingPages, payload];
sessionStorage.setItem(PAGES_SESSION_STORAGE_KEY, JSON.stringify(updatedPages));
};

export function createSegmentStoredInteraction(payload) { // Create and Queue Interaction Entry
const updatedPayload = {
...payload,
...storedPayload()
};

const existingInteractions = JSON.parse(sessionStorage.getItem(INTERACTIONS_SESSION_STORAGE_KEY) || '[]');
const updatedInteractions = [...existingInteractions, updatedPayload];
sessionStorage.setItem(INTERACTIONS_SESSION_STORAGE_KEY, JSON.stringify(updatedInteractions));
};


/******************/
/* Tracking Logic */
/******************/
const trackStoredPageViews = () => {
const category = 'Qdrant.tech';

// Iterate over all stored page views
getSegmentStoredPages().forEach(properties => {
const name = nameMapper(properties.url);
const originalTimestamp = properties.storedEvent ? properties.storedTimestamp : null;
delete properties['storedTimestamp'];

if(window.analytics) {
window.analytics.page(
category,
name,
properties,
originalTimestamp ? { timestamp: originalTimestamp } : null
);
}
});

removeSegmentStoredPages();
}

const trackStoredInteractions = () => {
// Iterate over all stored interactions
getSegmentStoredInteractions().forEach(interactionPayload => {
trackInteractionEvent(interactionPayload);
});

removeSegmentStoredInteractions();
}

const trackEvent = (name, properties = {}) => {
const originalTimestamp = properties.storedEvent ? properties.storedTimestamp : null;
delete properties['storedTimestamp'];
@@ -176,84 +68,10 @@ export function handleConsent() {
devLog('User consented...')
}

/*******************/
/* Loading Segment */
/*******************/
export function loadSegment() {
const writeKey = getSegmentWriteKey();
if (!writeKey) return; // Fail silently?

devLog('Loading Segment...');

// Segment snippet initialization
var i = "analytics",
analytics = window[i] = window[i] || [];

if (!analytics.initialize) {
if (analytics.invoked) {
window.console && console.error && console.error("Segment snippet included twice.");
} else {
analytics.invoked = true;
analytics.methods = [
"trackSubmit", "trackClick", "trackLink", "trackForm", "pageview", "identify", "reset", "group", "track",
"ready", "alias", "debug", "page", "screen", "once", "off", "on", "addSourceMiddleware", "addIntegrationMiddleware",
"setAnonymousId", "addDestinationMiddleware", "register"
];

analytics.factory = function(e) {
return function() {
if (window[i].initialized) {
return window[i][e].apply(window[i], arguments);
}

var n = Array.prototype.slice.call(arguments);
if (["track", "screen", "alias", "group", "page", "identify"].indexOf(e) > -1) {
var c = document.querySelector("link[rel='canonical']");
n.push({
__t: "bpc",
c: c && c.getAttribute("href") || void 0,
p: location.pathname,
u: location.href,
s: location.search,
t: document.title,
r: document.referrer
});
}

n.unshift(e);
analytics.push(n);
return analytics;
}
};

for (var n = 0; n < analytics.methods.length; n++) {
var key = analytics.methods[n];
analytics[key] = analytics.factory(key);
}

analytics.load = function(key, n) {
var t = document.createElement("script");
t.type = "text/javascript";
t.async = true;
t.setAttribute("data-global-segment-analytics-key", i);
t.src = "https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";
var r = document.getElementsByTagName("script")[0];
r.parentNode.insertBefore(t, r);
analytics._loadOptions = n;
};

analytics._writeKey = writeKey;
analytics.SNIPPET_VERSION = "5.2.0";
analytics.load(writeKey);

analytics.ready(function() {
tagCloudUILinksWithAnonymousId();
tagAllAnchors();
});
}
}

// Track any pages that may have been visited and stored in session storage
trackStoredPageViews();
trackStoredInteractions();
};
/********************/
/* Tag DOM Elements */
/********************/
document.body.addEventListener('customSegmentIsReady', () => {
tagCloudUILinksWithAnonymousId();
tagAllAnchors();
}, false);
6 changes: 0 additions & 6 deletions qdrant-landing/themes/qdrant-2024/assets/js/segment-setup.js

This file was deleted.

13 changes: 13 additions & 0 deletions qdrant-landing/themes/qdrant-2024/layouts/partials/head.html
Original file line number Diff line number Diff line change
@@ -32,4 +32,17 @@

{{ partial "seo_schema" . }}
{{ partial "js-head" . }}

<script>
!function(){var i="analytics",analytics=window[i]=window[i]||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","screen","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware","register"];analytics.factory=function(e){return function(){if(window[i].initialized)return window[i][e].apply(window[i],arguments);var n=Array.prototype.slice.call(arguments);if(["track","screen","alias","group","page","identify"].indexOf(e)>-1){var c=document.querySelector("link[rel='canonical']");n.push({__t:"bpc",c:c&&c.getAttribute("href")||void 0,p:location.pathname,u:location.href,s:location.search,t:document.title,r:document.referrer})}n.unshift(e);analytics.push(n);return analytics}};for(var n=0;n<analytics.methods.length;n++){var key=analytics.methods[n];analytics[key]=analytics.factory(key)}analytics.load=function(key,n){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.setAttribute("data-global-segment-analytics-key",i);t.src="https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";var r=document.getElementsByTagName("script")[0];r.parentNode.insertBefore(t,r);analytics._loadOptions=n};analytics._writeKey="3lK2GlR2PZgPvIOHJuSlcwmuGnzbv9U8";;analytics.SNIPPET_VERSION="5.2.0";
analytics.load("{{ .Site.Params.segmentWriteKey }}");

analytics.ready(function() {
analytics.page("Qdrant.tech", document.title);

const customEvent = new CustomEvent('customSegmentIsReady');
document.body.dispatchEvent(customEvent);
});
}}();
</script>
</head>
Original file line number Diff line number Diff line change
@@ -36,8 +36,3 @@
<script src="{{ $documentationJs.RelPermalink }}"></script>
{{ end }}

<!--Segment-->
{{ if .Site.Params.segmentWriteKey }}
{{ $segmentJs := resources.Get "js/segment-setup.js" | js.Build (dict "params" (dict "segmentWriteKey" .Site.Params.segmentWriteKey)) | minify | resources.Fingerprint "sha512" }}
<script src="{{ $segmentJs.RelPermalink }}"></script>
{{ end }}