-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.js
More file actions
1035 lines (949 loc) · 40.5 KB
/
Copy pathanalytics.js
File metadata and controls
1035 lines (949 loc) · 40.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(() => {
"use strict";
const posthogProjectKey = "phc_khcQc7asdJTMzQQBk7dWTVdbgiT4NFDz5dkLT6GCBqnA";
const posthogApiHost = "https://us.i.posthog.com";
const posthogUiHost = "https://us.posthog.com";
const trackedHosts = new Set(["tudzai.github.io"]);
const schemaVersion = "2026-08-16.2";
const analyticsPreferenceKey = "portfolio-analytics-preference";
const analyticsControlParameter = "portfolio_analytics";
const bridgeMessageType = "portfolio-analytics-bridge-v1";
const scrollMilestones = [25, 50, 75, 90, 100];
const activeTimeMilestones = [10, 30, 60, 120];
const fileExtensions = new Set([
"csv",
"doc",
"docx",
"json",
"pdf",
"ppt",
"pptx",
"txt",
"xls",
"xlsm",
"xlsx",
"zip",
]);
if (!trackedHosts.has(window.location.hostname)) return;
if (window.__portfolioAnalyticsLoaded) return;
function readAnalyticsPreference() {
try {
return window.localStorage.getItem(analyticsPreferenceKey);
} catch {
return null;
}
}
function applyAnalyticsControlParameter() {
let requestedPreference = null;
try {
requestedPreference = new URLSearchParams(window.location.search).get(analyticsControlParameter);
} catch {
return readAnalyticsPreference();
}
try {
if (requestedPreference === "off" || requestedPreference === "internal") {
window.localStorage.setItem(analyticsPreferenceKey, requestedPreference);
} else if (requestedPreference === "on" || requestedPreference === "external") {
window.localStorage.removeItem(analyticsPreferenceKey);
}
} catch {
return requestedPreference === "internal" ? "internal" : null;
}
return readAnalyticsPreference();
}
function hasPrivacySignal() {
const doNotTrackValues = [
window.navigator.doNotTrack,
window.doNotTrack,
window.navigator.msDoNotTrack,
];
return window.navigator.globalPrivacyControl === true || doNotTrackValues.some((value) => value === "1" || value === "yes");
}
const analyticsPreference = applyAnalyticsControlParameter();
if (analyticsPreference === "off" || hasPrivacySignal()) return;
window.__portfolioAnalyticsLoaded = true;
function isEmbeddedFrame() {
try {
return window.self !== window.top;
} catch {
return true;
}
}
function isRestrictedAnalyticsRoute(pathname = window.location.pathname) {
const relativePath = pathname.replace(/^\/Portfolio(?:\/|$)/, "/").replace(/\/{2,}/g, "/");
return relativePath === "/knowledge-vault" || relativePath.startsWith("/knowledge-vault/");
}
function shouldBridgeToParent() {
if (!isEmbeddedFrame()) return false;
try {
return window.parent.location.origin !== window.location.origin;
} catch {
return true;
}
}
function safeUrl(url) {
if (!url) return null;
try {
const parsed = new URL(url, window.location.href);
if (parsed.protocol === "mailto:" || parsed.protocol === "tel:") return parsed.protocol;
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return parsed.protocol;
return `${parsed.origin}${parsed.pathname}`;
} catch {
return null;
}
}
function safeHostname(url) {
if (!url) return null;
try {
return new URL(url, window.location.href).hostname || null;
} catch {
return null;
}
}
function redactSensitiveText(value, maxLength = 300) {
if (typeof value !== "string") return value;
return value
.replace(/[\u0000-\u001f\u007f]+/g, " ")
.replace(/https?:\/\/[^\s<>"'\])}]+/gi, (url) => safeUrl(url) || "[url redacted]")
.replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, "[email redacted]")
.replace(/\s+/g, " ")
.trim()
.slice(0, maxLength);
}
function redactReplayText(value) {
if (typeof value !== "string") return value;
return value.replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, "[email redacted]");
}
function safeSlug(value) {
const slug = String(value || "").toLowerCase();
return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug) ? slug : null;
}
function safeCampaignValue(value) {
const campaignValue = String(value || "").trim().toLowerCase();
return /^(?=.*[a-z])[a-z0-9][a-z0-9._~-]{0,63}$/.test(campaignValue) ? campaignValue : null;
}
function getPageContext(pathname = window.location.pathname) {
let relativePath = pathname.replace(/^\/Portfolio(?:\/|$)/, "/").replace(/\/{2,}/g, "/");
const trimmedPath = relativePath.replace(/^\/|\/$/g, "");
const parts = trimmedPath ? trimmedPath.split("/") : [];
const fileName = parts[parts.length - 1] || "";
const embedded = isEmbeddedFrame();
let pageType = "portfolio";
let contentGroup = "system";
let contentSlug = null;
let artifactType = null;
if (parts.length === 0 || (parts.length === 1 && parts[0] === "index.html")) {
pageType = "home";
contentGroup = "home";
contentSlug = "home";
} else if (fileName === "cv.html") {
pageType = "cv";
contentGroup = "cv";
contentSlug = "cv";
artifactType = "pdf_viewer";
} else if (parts[0] === "collections-agent") {
pageType = "redirect";
contentGroup = "blog";
contentSlug = "predictive-collections-agent";
artifactType = "interactive_deck";
} else if (parts[0] === "knowledge-vault") {
pageType = "private_tool";
contentGroup = "knowledge";
contentSlug = "knowledge-vault";
} else if (fileName === "share.html") {
pageType = "share_redirect";
contentGroup = "system";
contentSlug = "share";
} else if (fileName === "404.html" || document.title.toLowerCase().startsWith("redirecting")) {
pageType = "404";
contentGroup = "system";
contentSlug = "404";
} else if (parts[0] === "blog") {
contentGroup = "blog";
if (parts.length === 1 || (parts.length === 2 && fileName === "index.html")) {
pageType = "hub";
contentSlug = "blog";
} else {
contentSlug = safeSlug(parts[1]);
if (parts[2] === "deck" || parts[2] === "deck.html") {
pageType = "deck";
artifactType = "interactive_deck";
} else {
pageType = "article";
}
}
} else if (parts[0] === "showcase" && parts[1]) {
contentGroup = parts[1].replace(/-/g, "_");
const isHub = parts.length === 2 || (parts.length === 3 && fileName === "index.html");
if (isHub) {
pageType = "hub";
contentSlug = parts[1];
} else if (parts[1] === "powerbi" && fileName === "project-preview.html") {
pageType = "preview";
artifactType = "interactive_preview";
try {
contentSlug = safeSlug(new URLSearchParams(window.location.search).get("project")) || "project-preview";
} catch {
contentSlug = "project-preview";
}
} else {
contentSlug = safeSlug(parts[2]);
if (fileName === "preview.html" || embedded) {
pageType = "preview";
artifactType = "interactive_preview";
} else if (fileName === "model.html") {
pageType = "model";
artifactType = "finance_model";
} else if (parts[1] === "financial-models") {
pageType = "model";
artifactType = "finance_model";
} else {
pageType = parts[1] === "powerbi" ? "project" : "case";
}
}
}
return {
page_type: pageType,
content_group: contentGroup,
content_slug: contentSlug,
artifact_type: artifactType,
frame_context: embedded ? "embedded" : "top_level",
is_embedded_frame: embedded,
};
}
function getMarketingAttribution() {
const attribution = {};
try {
const params = new URLSearchParams(window.location.search);
["utm_source", "utm_medium", "utm_campaign"].forEach((key) => {
const value = safeCampaignValue(params.get(key));
if (value) attribution[key] = value;
});
} catch {
return attribution;
}
return attribution;
}
function buildEntryContext() {
return {
entry_path: window.location.pathname,
entry_referrer_host: safeHostname(document.referrer),
...getMarketingAttribution(),
};
}
function getEntryContext() {
const storageKey = "portfolio-entry-context-v1";
try {
const existing = JSON.parse(window.sessionStorage.getItem(storageKey) || "null");
if (existing && typeof existing === "object" && typeof existing.entry_path === "string") return existing;
const created = buildEntryContext();
window.sessionStorage.setItem(storageKey, JSON.stringify(created));
return created;
} catch {
return buildEntryContext();
}
}
const entryContext = getEntryContext();
const likelyBot = Boolean(window.navigator.webdriver) || /(?:bot|crawler|spider|headless|lighthouse)/i.test(window.navigator.userAgent || "");
const bridgeOnly = shouldBridgeToParent();
const restrictedAnalytics = isRestrictedAnalyticsRoute();
function getCommonProperties() {
return {
schema_version: schemaVersion,
environment: "production",
page_path: window.location.pathname,
page_url: safeUrl(window.location.href),
...getPageContext(),
...entryContext,
is_internal_or_test: analyticsPreference === "internal",
is_likely_bot: likelyBot,
};
}
function sanitizeCustomProperties(properties = {}) {
const sanitized = {};
Object.entries(properties).forEach(([key, value]) => {
if (!/^[A-Za-z0-9_$.-]{1,80}$/.test(key)) return;
const lowerKey = key.toLowerCase();
if (/(?:email|phone|telephone|copied_text|search_query|input_value)$/.test(lowerKey)) return;
if (typeof value === "string") {
if (/(?:url|referrer|destination|href|resource_src)$/.test(lowerKey)) {
sanitized[key] = safeUrl(value);
} else {
sanitized[key] = redactSensitiveText(value);
}
} else if (typeof value === "number") {
sanitized[key] = Number.isFinite(value) ? value : null;
} else if (typeof value === "boolean" || value === null) {
sanitized[key] = value;
} else if (Array.isArray(value)) {
sanitized[key] = value
.slice(0, 20)
.map((item) => (typeof item === "string" ? redactSensitiveText(item, 120) : item))
.filter((item) => ["string", "number", "boolean"].includes(typeof item));
}
});
return sanitized;
}
function sanitizePostHogPropertyTree(value, key = "", depth = 0) {
if (depth > 8) return null;
if (typeof value === "string") {
if (/(?:url|referrer|href|destination|resource_src)/i.test(key)) return safeUrl(value);
return redactSensitiveText(value, 1000);
}
if (typeof value === "number") return Number.isFinite(value) ? value : null;
if (typeof value === "boolean" || value === null) return value;
if (Array.isArray(value)) {
return value.map((item) => sanitizePostHogPropertyTree(item, key, depth + 1));
}
if (!value || typeof value !== "object") return null;
const sanitized = {};
Object.entries(value).forEach(([nestedKey, nestedValue]) => {
const normalizedNestedKey = nestedKey.replace(/^\$/, "");
if (/(?:email|phone|telephone|copied_text|search_query|input_value)$/i.test(nestedKey)) return;
if (/(?:gclid|dclid|fbclid|msclkid|ttclid|twclid|li_fat_id)$/i.test(nestedKey)) return;
if (/(?:^|_)utm_(?:content|term|id|source_platform|creative_format|marketing_tactic)$/i.test(normalizedNestedKey)) return;
if (/(?:^|_)utm_(?:source|medium|campaign)$/i.test(normalizedNestedKey)) {
sanitized[nestedKey] = safeCampaignValue(nestedValue);
return;
}
sanitized[nestedKey] = sanitizePostHogPropertyTree(nestedValue, nestedKey, depth + 1);
});
return sanitized;
}
function getTrustedEventContext(properties) {
const commonProperties = getCommonProperties();
const embeddedPath =
properties?.frame_context === "embedded" && typeof properties.embedded_page_path === "string"
? properties.embedded_page_path
: null;
if (!embeddedPath || !(embeddedPath === "/Portfolio" || embeddedPath.startsWith("/Portfolio/"))) {
return commonProperties;
}
return {
...commonProperties,
...getPageContext(embeddedPath),
page_path: embeddedPath,
page_url: safeUrl(embeddedPath),
frame_context: "embedded",
is_embedded_frame: true,
};
}
function beforeSendPostHogEvent(event) {
if (!event || typeof event !== "object") return event;
// Replay snapshots are structured rrweb payloads. Rewriting their nested
// properties makes the recording impossible for PostHog to reconstruct.
if (event.event === "$snapshot") return event;
const rawProperties = event.properties && typeof event.properties === "object" ? event.properties : {};
const properties = sanitizePostHogPropertyTree(rawProperties);
event.properties = {
...properties,
...getTrustedEventContext(properties),
};
return event;
}
function redactRecordedRequest(request) {
if (!request || typeof request !== "object") return request;
if (typeof request.name === "string") request.name = safeUrl(request.name) || request.name.split(/[?#]/)[0];
return request;
}
if (!bridgeOnly) {
if (window.posthog?.__loaded || window.posthog?.__SV) return;
!function(t,e){var o,n,p,r;e.__SV||(window.posthog&&window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="xi Si init Ni ji pr qi Ui $i capture calculateEventProperties Zi register register_once register_for_session unregister unregister_for_session Yi getFeatureFlag getFeatureFlagPayload getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSurveysLoaded onSessionId getSurveys getActiveMatchingSurveys renderSurvey displaySurvey cancelPendingSurvey canRenderSurvey canRenderSurveyAsync Ki identify setPersonProperties unsetPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset setIdentity clearIdentity get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException addExceptionStep captureLog startExceptionAutocapture stopExceptionAutocapture loadToolbar get_property getSessionProperty Qi Wi createPersonProfile setInternalOrTestUser Ji Fi tn opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing get_explicit_consent_status is_capturing clear_opt_in_out_capturing zi debug mr it getPageViewId captureTraceFeedback captureTraceMetric Ri".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
window.posthog.init(posthogProjectKey, {
api_host: posthogApiHost,
ui_host: posthogUiHost,
defaults: "2026-05-30",
person_profiles: "identified_only",
capture_pageview: !isEmbeddedFrame(),
capture_pageleave: !isEmbeddedFrame(),
autocapture: restrictedAnalytics ? false : {
dom_event_allowlist: ["click", "change", "submit"],
element_allowlist: ["a", "button", "form", "input", "select", "textarea", "label"],
css_selector_ignorelist: [
".ph-no-autocapture",
"[data-ph-no-autocapture]",
"[data-sensitive]",
"a[href^='mailto:']",
"a[href^='tel:']",
],
element_attribute_ignorelist: ["value", "data-email", "data-phone", "data-sensitive"],
capture_copied_text: false,
},
capture_dead_clicks: !restrictedAnalytics,
capture_heatmaps: !restrictedAnalytics,
capture_exceptions: !restrictedAnalytics,
disable_surveys: true,
disable_persistence: restrictedAnalytics,
disable_session_recording: restrictedAnalytics || isEmbeddedFrame() || analyticsPreference === "internal",
session_recording: {
maskAllInputs: true,
maskTextSelector: "*",
maskTextFn: redactReplayText,
maskCapturedNetworkRequestFn: redactRecordedRequest,
},
before_send: beforeSendPostHogEvent,
});
}
function capturePortfolioEvent(eventName, properties = {}) {
if (typeof eventName !== "string" || !/^[A-Za-z0-9_$][A-Za-z0-9_$ .-]{0,79}$/.test(eventName)) return;
if (restrictedAnalytics && eventName !== "portfolio_page_loaded") return;
const sanitizedProperties = sanitizeCustomProperties(properties);
if (bridgeOnly) {
window.parent.postMessage(
{
type: bridgeMessageType,
event_name: eventName,
page_path: window.location.pathname,
page_title: redactSensitiveText(document.title, 160),
properties: sanitizedProperties,
},
"https://tudzai.github.io",
);
return;
}
if (!window.posthog || typeof window.posthog.capture !== "function") return;
window.posthog.capture(eventName, sanitizedProperties);
}
window.portfolioAnalytics = Object.freeze({
capture: capturePortfolioEvent,
getPageContext,
safeUrl,
schemaVersion,
});
document.dispatchEvent(new CustomEvent("portfolio:analytics-ready"));
if (!isEmbeddedFrame()) {
window.addEventListener("message", (event) => {
const data = event.data;
if (!data || data.type !== bridgeMessageType || typeof data.event_name !== "string") return;
const frame = Array.from(document.querySelectorAll("iframe")).find((candidate) => candidate.contentWindow === event.source);
if (!frame) return;
try {
if (new URL(frame.getAttribute("src") || "", window.location.href).origin !== window.location.origin) return;
} catch {
return;
}
capturePortfolioEvent(data.event_name, {
...sanitizeCustomProperties(data.properties),
frame_context: "embedded",
is_embedded_frame: true,
embedded_page_path: typeof data.page_path === "string" ? data.page_path : null,
embedded_page_title: typeof data.page_title === "string" ? data.page_title : null,
embed_title: frame.getAttribute("title") || null,
parent_page_path: window.location.pathname,
});
});
}
const pageContext = getPageContext();
const tracksPageEngagement = !pageContext.is_embedded_frame;
let interactionCount = 0;
let sectionsViewedCount = 0;
let maxScrollDepth = 0;
let activeMilliseconds = 0;
let lastActiveTick = Date.now();
let wasVisibleAtLastActiveTick = document.visibilityState === "visible";
let pageSummarySent = false;
let firstPreviewInteraction = true;
const reachedScrollMilestones = new Set();
const reachedActiveMilestones = new Set();
function recordInteraction() {
interactionCount += 1;
}
function getElementLabel(element, maxLength = 120) {
if (!element) return null;
return redactSensitiveText(
element.dataset?.trackLabel ||
element.getAttribute?.("aria-label") ||
element.getAttribute?.("title") ||
element.textContent ||
element.id ||
"",
maxLength,
) || null;
}
function getCtaLocation(element) {
if (!element) return "unspecified";
if (element.dataset?.trackLocation) return redactSensitiveText(element.dataset.trackLocation, 80) || "unspecified";
const owner = element.closest?.("section, article, nav, header, footer");
if (!owner) return "unspecified";
return (
owner.id ||
owner.dataset?.trackSection ||
redactSensitiveText(owner.getAttribute("aria-label") || "", 80) ||
owner.classList?.[0] ||
owner.tagName.toLowerCase()
);
}
function getFileExtension(pathname) {
const match = String(pathname || "").toLowerCase().match(/\.([a-z0-9]{1,8})$/);
return match && fileExtensions.has(match[1]) ? match[1] : null;
}
function getLinkKind(link, url, fileExtension) {
const href = link.getAttribute("href") || "";
const protocol = url?.protocol || "";
if (protocol === "mailto:" || protocol === "tel:") return "contact";
if (fileExtension === "pdf") return "pdf";
if (fileExtension) return "file";
if (url && url.origin !== window.location.origin) return "outbound";
if (href.startsWith("#")) return "anchor";
return "internal";
}
function getExternalPlatform(hostname) {
const host = String(hostname || "").toLowerCase();
if (host.includes("linkedin.com")) return "linkedin";
if (host.includes("github.com")) return "github";
return host || null;
}
function capturePreviewInteraction(control, controlType, selectedValue = null) {
const eventName = pageContext.page_type === "deck" ? "portfolio_deck_interacted" : "portfolio_preview_interacted";
capturePortfolioEvent(eventName, {
control_type: controlType,
control_id: control.id || control.dataset?.tab || control.dataset?.page || control.name || null,
control_label: getElementLabel(control),
selected_value: selectedValue,
is_first_interaction: firstPreviewInteraction,
});
firstPreviewInteraction = false;
}
capturePortfolioEvent("portfolio_page_loaded", {
referrer_url: safeUrl(document.referrer),
});
if (pageContext.page_type === "404") {
capturePortfolioEvent("portfolio_404_viewed", {
attempted_path: window.location.pathname,
referrer_url: safeUrl(document.referrer),
});
}
document.addEventListener("click", (event) => {
const target = event.target instanceof Element ? event.target : null;
if (!target) return;
const link = target.closest("a[href]");
if (link) {
const href = link.getAttribute("href");
if (!href || href.startsWith("javascript:")) return;
let url;
try {
url = new URL(href, window.location.href);
} catch {
return;
}
recordInteraction();
const fileExtension = getFileExtension(url.pathname);
const linkKind = getLinkKind(link, url, fileExtension);
const ctaLocation = getCtaLocation(link);
const isCvPdf = url.pathname.toLowerCase().includes("truong-dinh-anh-tu-cv");
const opensCvPage = url.pathname.toLowerCase().endsWith("/cv.html");
const declaredTrackingElement = link.closest("[data-track-event], [data-blog-track-event]");
const declaredEventName =
declaredTrackingElement?.dataset?.trackEvent || declaredTrackingElement?.dataset?.blogTrackEvent || null;
const contactMethod = url.protocol === "mailto:" ? "email" : url.protocol === "tel:" ? "phone" : null;
const fileAction = fileExtension || link.hasAttribute("download")
? link.hasAttribute("download")
? "download_clicked"
: "open_clicked"
: null;
const cvAction = isCvPdf
? link.hasAttribute("download")
? "download_pdf_clicked"
: "open_pdf_clicked"
: opensCvPage
? "open_cv_page_clicked"
: null;
const commonLinkProperties = {
link_kind: linkKind,
link_label: linkKind === "contact" ? null : getElementLabel(link),
cta_location: ctaLocation,
destination_url: safeUrl(url.href),
destination_path: url.origin === window.location.origin ? url.pathname : null,
destination_host: url.hostname || null,
external_platform: linkKind === "outbound" ? getExternalPlatform(url.hostname) : null,
opens_new_tab: link.target === "_blank",
file_extension: fileExtension,
has_download_attribute: link.hasAttribute("download"),
is_cv_pdf: isCvPdf,
contact_method: contactMethod,
file_action: fileAction,
artifact_type: isCvPdf ? "cv" : fileExtension ? "portfolio_artifact" : null,
cv_action: cvAction,
declared_event_name: declaredEventName,
};
capturePortfolioEvent("portfolio_link_clicked", commonLinkProperties);
if (url.protocol === "mailto:" || url.protocol === "tel:") {
capturePortfolioEvent("portfolio_contact_clicked", {
contact_method: url.protocol === "mailto:" ? "email" : "phone",
cta_location: ctaLocation,
});
}
if (fileExtension || link.hasAttribute("download")) {
capturePortfolioEvent("portfolio_file_interaction", {
file_extension: fileExtension,
file_action: link.hasAttribute("download") ? "download_clicked" : "open_clicked",
artifact_type: isCvPdf ? "cv" : "portfolio_artifact",
cta_location: ctaLocation,
destination_path: url.origin === window.location.origin ? url.pathname : null,
});
}
if (isCvPdf || opensCvPage) {
capturePortfolioEvent("portfolio_cv_interaction", {
cv_action: isCvPdf
? link.hasAttribute("download")
? "download_pdf_clicked"
: "open_pdf_clicked"
: "open_cv_page_clicked",
cta_location: ctaLocation,
opens_new_tab: link.target === "_blank",
});
}
return;
}
const button = target.closest("button, [role='button']");
if (!button) return;
if (button.closest(".ph-no-autocapture, [data-ph-no-autocapture]")) return;
recordInteraction();
if (button.closest("[data-track-event]")) return;
if (pageContext.page_type === "preview" || pageContext.page_type === "deck") {
capturePreviewInteraction(button, "button");
} else {
capturePortfolioEvent("portfolio_control_used", {
control_type: "button",
control_id: button.id || button.dataset?.tab || button.dataset?.page || null,
control_label: getElementLabel(button),
cta_location: getCtaLocation(button),
});
}
});
document.addEventListener("change", (event) => {
const control = event.target instanceof Element ? event.target : null;
if (!control || !control.matches("select, input[type='checkbox'], input[type='radio']")) return;
if (control.closest(".ph-no-autocapture, [data-ph-no-autocapture]")) return;
recordInteraction();
let selectedValue = null;
if (control instanceof HTMLSelectElement) {
selectedValue = redactSensitiveText(control.selectedOptions[0]?.textContent || control.value, 120);
} else if (control instanceof HTMLInputElement) {
selectedValue = control.checked ? "checked" : "unchecked";
}
if (pageContext.page_type === "preview" || pageContext.page_type === "deck") {
capturePreviewInteraction(control, control.tagName.toLowerCase(), selectedValue);
} else {
capturePortfolioEvent("portfolio_control_changed", {
control_type: control.tagName.toLowerCase(),
control_id: control.id || control.getAttribute("name") || null,
control_label: getElementLabel(control),
selected_value: selectedValue,
});
}
});
const searchTimers = new WeakMap();
document.addEventListener("input", (event) => {
const input = event.target instanceof HTMLInputElement ? event.target : null;
if (!input || (input.type !== "search" && !input.matches("[data-blog-search]"))) return;
const existingTimer = searchTimers.get(input);
if (existingTimer) window.clearTimeout(existingTimer);
searchTimers.set(
input,
window.setTimeout(() => {
const length = input.value.trim().length;
const lengthBucket = length === 0 ? "0" : length === 1 ? "1" : length <= 3 ? "2-3" : length <= 7 ? "4-7" : "8+";
const declaredResultSelector = input.dataset.searchResultSelector;
let resultCount = document.querySelectorAll(".blog-feature-card, .blog-archive-card").length;
if (declaredResultSelector) {
try {
resultCount = document.querySelectorAll(declaredResultSelector).length;
} catch {
resultCount = 0;
}
}
capturePortfolioEvent("portfolio_search_used", {
query_length_bucket: lengthBucket,
result_count: resultCount,
});
}, 750),
);
});
document.addEventListener("copy", (event) => {
const target = event.target instanceof Element ? event.target : null;
recordInteraction();
capturePortfolioEvent("portfolio_copy_intent", {
source_element: target?.tagName?.toLowerCase() || null,
source_section: getCtaLocation(target),
});
});
window.addEventListener(
"error",
(event) => {
const resource = event.target instanceof Element ? event.target : null;
if (!resource || resource === document.documentElement) return;
const tagName = resource.tagName?.toLowerCase();
if (!["img", "script", "link", "iframe", "object", "embed", "video", "audio", "source"].includes(tagName)) return;
const source = resource.getAttribute("src") || resource.getAttribute("href") || resource.getAttribute("data");
capturePortfolioEvent("portfolio_resource_load_failed", {
resource_type: tagName,
resource_url: safeUrl(source),
resource_host: safeHostname(source),
});
},
true,
);
function updateActiveTime() {
if (!tracksPageEngagement) return;
const now = Date.now();
if (wasVisibleAtLastActiveTick) activeMilliseconds += Math.min(5000, Math.max(0, now - lastActiveTick));
lastActiveTick = now;
wasVisibleAtLastActiveTick = document.visibilityState === "visible";
const activeSeconds = Math.floor(activeMilliseconds / 1000);
activeTimeMilestones.forEach((milestone) => {
if (activeSeconds < milestone || reachedActiveMilestones.has(milestone)) return;
reachedActiveMilestones.add(milestone);
capturePortfolioEvent("portfolio_active_time_reached", {
seconds_threshold: milestone,
});
});
}
if (tracksPageEngagement) {
document.addEventListener("visibilitychange", updateActiveTime);
window.setInterval(updateActiveTime, 1000);
}
function updateScrollDepth() {
if (!tracksPageEngagement || pageContext.page_type === "deck") return;
const documentHeight = Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight || 0);
const viewportBottom = window.scrollY + window.innerHeight;
const depth = documentHeight > 0 ? Math.min(100, Math.max(0, Math.round((viewportBottom / documentHeight) * 100))) : 100;
maxScrollDepth = Math.max(maxScrollDepth, depth);
scrollMilestones.forEach((milestone) => {
if (depth < milestone || reachedScrollMilestones.has(milestone)) return;
reachedScrollMilestones.add(milestone);
capturePortfolioEvent("portfolio_scroll_depth_reached", {
depth_percent: milestone,
});
});
}
window.addEventListener("scroll", updateScrollDepth, { passive: true });
window.addEventListener("resize", updateScrollDepth, { passive: true });
function sendPageSummary(reason) {
if (!tracksPageEngagement || pageSummarySent) return;
updateActiveTime();
updateScrollDepth();
pageSummarySent = true;
capturePortfolioEvent("portfolio_page_engaged", {
engagement_reason: reason,
active_seconds: Math.round(activeMilliseconds / 1000),
elapsed_seconds: Math.round(performance.now() / 1000),
max_scroll_depth: maxScrollDepth,
interaction_count: interactionCount,
sections_viewed: sectionsViewedCount,
});
}
window.addEventListener("pagehide", () => sendPageSummary("pagehide"));
window.addEventListener("pageshow", (event) => {
if (event.persisted) {
lastActiveTick = Date.now();
wasVisibleAtLastActiveTick = document.visibilityState === "visible";
}
});
function setupSectionTracking() {
if (!tracksPageEngagement || !("IntersectionObserver" in window)) return;
const candidates = Array.from(
new Set(document.querySelectorAll("main > section, main > article > section, [data-track-section]")),
).filter((element) => !element.closest(".slide"));
if (!candidates.length) return;
const viewed = new WeakSet();
const timers = new WeakMap();
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
const element = entry.target;
if (entry.isIntersecting && entry.intersectionRatio >= 0.5 && !viewed.has(element)) {
if (timers.has(element)) return;
timers.set(
element,
window.setTimeout(() => {
if (viewed.has(element)) return;
viewed.add(element);
sectionsViewedCount += 1;
const index = candidates.indexOf(element);
const heading = element.querySelector("h1, h2, h3");
capturePortfolioEvent("portfolio_section_viewed", {
section_id: element.id || element.dataset.trackSection || `section-${index + 1}`,
section_order: index + 1,
section_heading: getElementLabel(heading),
visible_ratio: Math.round(entry.intersectionRatio * 100) / 100,
});
}, 1000),
);
} else {
const timer = timers.get(element);
if (timer) window.clearTimeout(timer);
timers.delete(element);
}
});
},
{ threshold: [0.5, 0.75] },
);
candidates.forEach((element) => observer.observe(element));
}
function setupSlideTracking() {
const slides = Array.from(document.querySelectorAll(".slide"));
if (!slides.length || !("MutationObserver" in window)) return;
let lastSlide = null;
const captureActiveSlide = () => {
const activeSlide = slides.find(
(slide) =>
(slide.classList.contains("active") || slide.classList.contains("visible")) &&
window.getComputedStyle(slide).visibility !== "hidden",
);
if (!activeSlide || activeSlide === lastSlide) return;
lastSlide = activeSlide;
const slideIndex = slides.indexOf(activeSlide) + 1;
capturePortfolioEvent("portfolio_slide_viewed", {
slide_id: activeSlide.id || activeSlide.dataset.slide || `slide-${slideIndex}`,
slide_index: slideIndex,
slide_total: slides.length,
slide_title: getElementLabel(activeSlide.querySelector("h1, h2, h3")) || activeSlide.getAttribute("aria-label") || null,
});
};
const observer = new MutationObserver(captureActiveSlide);
slides.forEach((slide) => observer.observe(slide, { attributes: true, attributeFilter: ["class", "hidden"] }));
captureActiveSlide();
}
function setupEmbedTracking() {
const embeds = Array.from(document.querySelectorAll("iframe, object, embed"));
if (!embeds.length) return;
const viewed = new WeakSet();
const viewTimers = new WeakMap();
const observer = "IntersectionObserver" in window
? new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
const embed = entry.target;
if (entry.isIntersecting && entry.intersectionRatio >= 0.5 && !viewed.has(embed)) {
if (viewTimers.has(embed)) return;
viewTimers.set(
embed,
window.setTimeout(() => {
viewed.add(embed);
const source = embed.getAttribute("src") || embed.getAttribute("data");
const isPdf = String(source || "").toLowerCase().includes(".pdf");
capturePortfolioEvent("portfolio_embed_viewed", {
embed_type: isPdf ? "pdf" : embed.tagName.toLowerCase(),
embed_title: embed.getAttribute("title") || embed.getAttribute("aria-label") || null,
destination_url: safeUrl(source),
});
if (isPdf) {
capturePortfolioEvent("portfolio_cv_interaction", {
cv_action: "embedded_preview_viewed",
cta_location: getCtaLocation(embed),
});
}
}, 1000),
);
} else {
const timer = viewTimers.get(embed);
if (timer) window.clearTimeout(timer);
viewTimers.delete(embed);
}
});
},
{ threshold: [0.5] },
)
: null;
embeds.forEach((embed) => {
const captureLoaded = () => {
const source = embed.getAttribute("src") || embed.getAttribute("data");
capturePortfolioEvent("portfolio_embed_loaded", {
embed_type: String(source || "").toLowerCase().includes(".pdf") ? "pdf" : embed.tagName.toLowerCase(),
embed_title: embed.getAttribute("title") || embed.getAttribute("aria-label") || null,
destination_url: safeUrl(source),
});
};
embed.addEventListener("load", captureLoaded, { once: true });
observer?.observe(embed);
try {
if (embed instanceof HTMLIFrameElement && embed.contentDocument?.readyState === "complete") captureLoaded();
} catch {
// Cross-origin and sandboxed embeds are tracked by their load event.
}
});
}
function setupMediaTracking() {
const progressByMedia = new WeakMap();
document.addEventListener(
"play",
(event) => {
const media = event.target instanceof HTMLMediaElement ? event.target : null;
if (!media) return;
recordInteraction();
capturePortfolioEvent("portfolio_media_started", {
media_id: media.id || safeUrl(media.currentSrc || media.src),
media_type: media.tagName.toLowerCase(),
current_seconds: Math.round(media.currentTime || 0),
});
},
true,
);
document.addEventListener(
"timeupdate",
(event) => {
const media = event.target instanceof HTMLMediaElement ? event.target : null;
if (!media || !Number.isFinite(media.duration) || media.duration <= 0) return;
const reached = progressByMedia.get(media) || new Set();
const progress = (media.currentTime / media.duration) * 100;
[25, 50, 75, 100].forEach((milestone) => {
if (progress < milestone || reached.has(milestone)) return;
reached.add(milestone);
capturePortfolioEvent("portfolio_media_progress", {
media_id: media.id || safeUrl(media.currentSrc || media.src),
media_type: media.tagName.toLowerCase(),
progress_percent: milestone,
});
});
progressByMedia.set(media, reached);
},
true,
);
document.addEventListener(
"ended",
(event) => {
const media = event.target instanceof HTMLMediaElement ? event.target : null;
if (!media) return;
capturePortfolioEvent("portfolio_media_completed", {
media_id: media.id || safeUrl(media.currentSrc || media.src),
media_type: media.tagName.toLowerCase(),
});
},
true,
);
}
function capturePagePerformance() {
if (!window.performance || typeof window.performance.getEntriesByType !== "function") return;