Skip to content

Commit 0a8feb7

Browse files
authored
Merge pull request #872 from abdalladimes/internal-events-and-amplitude
Internal events and amplitude
2 parents 2761380 + 8a4d5b9 commit 0a8feb7

10 files changed

Lines changed: 177 additions & 88 deletions

scripts/_bundles/buildfire_lightcarousel.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

scripts/_bundles/buildfire_lightcarousel.min.js.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

scripts/_bundles/jquery_angular_buildfire_smartcrop.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

scripts/_bundles/jquery_angular_buildfire_smartcrop.min.js.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

scripts/buildfire.js

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,13 +184,13 @@ var buildfire = {
184184
colno: event.colno,
185185
lineno: event.lineno,
186186
message: event.message,
187-
stack: event.error && event.error.stack ? event.error && event.error.stack : "n/a",
187+
stack: (event.error && event.error.stack) ? event.error.stack : "n/a",
188188
url: event.filename
189189
}
190190
});
191191
}
192192
originalConsoleError('Error: ' + event.message, ' Script: ' + event.filename, ' Line: ' + event.lineno
193-
, ' Column: ' + event.colno, ' StackTrace: ' + event.error && event.error.stack ? event.error && event.error.stack : "n/a");
193+
, ' Column: ' + event.colno, ' StackTrace: ' + (event.error && event.error.stack) ? event.error.stack : "n/a");
194194
});
195195
},
196196
log: function (options, callback) {
@@ -269,6 +269,8 @@ var buildfire = {
269269
this.events[event] = [];
270270
}
271271
, trigger: function (event, data) {
272+
const internalEvent = new CustomEvent(`_internal_${event}`, { detail: data });
273+
window.dispatchEvent(internalEvent);
272274
if (this.events[event])
273275
for (var i = 0; i < this.events[event].length; i++) {
274276
try {
@@ -338,6 +340,15 @@ var buildfire = {
338340
}
339341
});
340342
}
343+
// Inject Amplitude if amplitudeData is present in querystring
344+
try {
345+
if (window.parsedQuerystring && window.parsedQuerystring.amplitudeData) {
346+
const amplitudeData = JSON.parse(decodeURIComponent(window.parsedQuerystring.amplitudeData));
347+
buildfire.analytics.injectAmplitude(amplitudeData);
348+
}
349+
} catch (error) {
350+
console.error('Failed to parse amplitudeData or inject Amplitude: ', error);
351+
}
341352

342353
if (window.location.pathname.indexOf('/widget/') >= 0 && buildfire.options.enablePluginJsonLoad) {
343354
buildfire.getContext((err, context) => {
@@ -423,6 +434,7 @@ var buildfire = {
423434
, 'services.commerce.inAppPurchase._triggerOnPurchaseResult'
424435
, 'services.reportAbuse._triggerOnAdminResponse'
425436
, 'geo.session._triggerOnSessionWatchChange'
437+
, 'analytics.injectAmplitude'
426438
]
427439
, _postMessageHandler: function (e) {
428440
if (e.source === window) {
@@ -1527,6 +1539,46 @@ var buildfire = {
15271539
params = {};
15281540
var p = new Packet(null, 'analytics.showReports', params);
15291541
buildfire._sendPacket(p, callback);
1542+
},
1543+
injectAmplitude: function (data) {
1544+
const html = document.getElementsByTagName('html')[0];
1545+
const amplitudeScript = document.createElement('script');
1546+
amplitudeScript.type = 'text/javascript';
1547+
amplitudeScript.src = 'https://cdn.amplitude.com/libs/analytics-browser-2.11.1-min.js.gz';
1548+
const amplitudeSessionReplayScript = document.createElement('script');
1549+
amplitudeSessionReplayScript.type = 'text/javascript';
1550+
amplitudeSessionReplayScript.src = 'https://cdn.amplitude.com/libs/plugin-session-replay-browser-1.8.0-min.js.gz';
1551+
1552+
const script = document.createElement('script');
1553+
script.type = 'text/javascript';
1554+
1555+
amplitudeScript.onload = function() {
1556+
html.appendChild(amplitudeSessionReplayScript);
1557+
amplitudeSessionReplayScript.onload = function() {
1558+
function initAmplitude() {
1559+
const config = {
1560+
deviceId: data.deviceId,
1561+
sessionId: parseInt(data.sessionId),
1562+
defaultTracking: true
1563+
};
1564+
1565+
const sessionReplayTracking = window.sessionReplay.plugin({
1566+
sampleRate: 1
1567+
});
1568+
1569+
window.amplitude.add(sessionReplayTracking);
1570+
amplitude.init(data.apiKey, null, config);
1571+
amplitude.track('iFrame Injected and Session Linked');
1572+
};
1573+
1574+
if (document.readyState === 'complete' || document.readyState === 'interactive') {
1575+
initAmplitude();
1576+
} else {
1577+
document.addEventListener('DOMContentLoaded', initAmplitude);
1578+
}
1579+
};
1580+
};
1581+
html.appendChild(amplitudeScript);
15301582
}
15311583
}
15321584
/// ref: https://github.com/BuildFire/sdk/wiki/How-to-use-Datastore
@@ -4541,13 +4593,29 @@ var buildfire = {
45414593
});
45424594
}
45434595
,overrideNativeLocalStorage: function() {
4596+
const nativeGetItem = window.localStorage.getItem;
4597+
const nativeSetItem = window.localStorage.setItem;
4598+
const nativeRemoveItem = window.localStorage.removeItem;
4599+
45444600
localStorage.getItem = function (key) {
4601+
// bypass buildfire localStorage for Amplitude keys in web environment
4602+
if (key && (key.indexOf('AMP_') === 0 || key.toLowerCase().includes('amplitude')) && buildfire.isWeb()) {
4603+
return nativeGetItem.call(window.localStorage, key);
4604+
}
45454605
return buildfire.localStorage.getItem(key);
45464606
};
45474607
localStorage.setItem = function (key, value) {
4608+
// bypass buildfire localStorage for Amplitude keys in web environment
4609+
if (key && (key.indexOf('AMP_') === 0 || key.toLowerCase().includes('amplitude')) && buildfire.isWeb()) {
4610+
return nativeSetItem.call(window.localStorage, key, value);
4611+
}
45484612
return buildfire.localStorage.setItem(key, value);
45494613
};
45504614
localStorage.removeItem = function (key) {
4615+
// bypass buildfire localStorage for Amplitude keys in web environment
4616+
if (key && (key.indexOf('AMP_') === 0 || key.toLowerCase().includes('amplitude')) && buildfire.isWeb()) {
4617+
return nativeRemoveItem.call(window.localStorage, key);
4618+
}
45514619
return buildfire.localStorage.removeItem(key);
45524620
};
45534621
localStorage.clear = function () {

scripts/buildfire.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

scripts/buildfire.min.js.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

scripts/buildfire/components/comments/comments.js

Lines changed: 80 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -213,49 +213,24 @@ buildfire.components.comments = {
213213
this.drawerOpened = false;
214214
this.comments = [];
215215

216-
// keyboard events
217-
buildfire.device.onKeyboardShow((data) => {
218-
this.keyboardShown = true;
219-
if (this.drawerOpened) {
220-
buildfire.components.swipeableDrawer.setStep('max');
221-
}
222-
});
223-
buildfire.device.onKeyboardHide(() => {
224-
this.keyboardShown = false;
225-
});
226-
227-
// auth state change
228-
buildfire.auth.onLogout(() => {
229-
if (this.listView) {
230-
this.listView.reset();
231-
}
232-
this.user = null;
233-
if (this.drawerOpened) {
234-
this._resetDrawer();
235-
}
236-
}, true);
237-
238-
buildfire.auth.onLogin((user) => {
239-
this.user = user;
240-
if (this.drawerOpened) {
241-
if (this.addingCommentInProgress) {
242-
this._addingCommentDone = () => {
243-
this._resetDrawer();
244-
this._addingCommentDone = null; // reset the function to avoid multiple calls
245-
}
246-
} else {
247-
this._resetDrawer();
248-
}
249-
}
250-
}, true);
251216
},
252217

253218
open(options = {}, callback) {
219+
this.isOpen = true;
254220

255221
buildfire.lazyLoadScript(
256222
{ relativeScriptsUrl: 'moment.min.js', scriptId: 'bfMomentSDK' }, () => {
257-
this.originalWidth = window.innerWidth;
258-
window.addEventListener('resize', this._onResize.bind(this), false);
223+
// keyboard events
224+
this._onKeyboardWillShowHandler = this._onKeyboardWillShow.bind(this);
225+
this._onKeyboardWillHideHandler = this._onKeyboardWillHide.bind(this);
226+
window.addEventListener('_internal_keyboardWillShow', this._onKeyboardWillShowHandler);
227+
window.addEventListener('_internal_keyboardWillHide', this._onKeyboardWillHideHandler);
228+
229+
// auth state change events
230+
this._onAuthLogoutHandler = this._onAuthLogout.bind(this);
231+
this._onAuthLoginHandler = this._onAuthLogin.bind(this);
232+
window.addEventListener('_internal_authOnLogout', this._onAuthLogoutHandler);
233+
window.addEventListener('_internal_authOnLogin', this._onAuthLoginHandler);
259234
this._openCommentsDrawer(options, callback);
260235
}
261236
)
@@ -421,7 +396,7 @@ buildfire.components.comments = {
421396
close(callback) {
422397
if (this.drawerOpened) {
423398
buildfire.components.swipeableDrawer.hide();
424-
this._destroy();
399+
this._cleanup();
425400
callback && callback(null);
426401
} else {
427402
callback && callback('Drawer is not opened');
@@ -575,8 +550,10 @@ buildfire.components.comments = {
575550
options.incrementValue = 1; // increment by 1
576551
this._updateSummary(options, (err, res) => {
577552
if (err) return callback(err);
578-
result.data.profileImage = this.user.imageUrl || 'https://app.buildfire.com/app/media/avatar.png';
579-
result.data.username = this._getNameOfUser({ user: this.user, isOwner: options.userId == this.user.userId });
553+
if (this.isOpen) {
554+
result.data.profileImage = this.user.imageUrl || 'https://app.buildfire.com/app/media/avatar.png';
555+
result.data.username = this._getNameOfUser({ user: this.user, isOwner: options.userId == this.user.userId });
556+
}
580557
callback(null, result);
581558
});
582559
}
@@ -598,10 +575,12 @@ buildfire.components.comments = {
598575
this.summary.count += 1;
599576
const listViewContainer = document.querySelector('#listViewContainer');
600577
listViewContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
601-
buildfire.components.swipeableDrawer.setHeaderContent(this._getDrawerHeaderHtml({
602-
count: this.summary.count,
603-
commentsHeader: this.options.translations?.commentsHeader
604-
}));
578+
if (this.isOpen) {
579+
buildfire.components.swipeableDrawer.setHeaderContent(this._getDrawerHeaderHtml({
580+
count: this.summary.count,
581+
commentsHeader: this.options.translations?.commentsHeader
582+
}));
583+
}
605584
if (callback) callback(null, commentToDisplay);
606585
});
607586
},
@@ -673,7 +652,7 @@ buildfire.components.comments = {
673652
<div id="commentSafeArea"></div>
674653
</div>
675654
<div class="add-comment-section">
676-
<img src="${this.user?.imageUrl || 'https://app.buildfire.com/app/media/avatar.png'}" alt="Profile Image">
655+
<img src="${buildfire.imageLib.cropImage(this.user?.imageUrl || 'https://app.buildfire.com/app/media/avatar.png', { size: 'xs', aspect: '1:1' })}" alt="Profile Image">
677656
<textarea name="commentInput" id="commentInput" maxlength="1000" placeholder="${this.options.translations?.addCommentPlaceholder ? this.options.translations.addCommentPlaceholder : 'Add comment'}"></textarea>
678657
<span id="addCommentIcon" class="add-comment bf-icon-arrow-right-tail"></span>
679658
</div>
@@ -692,7 +671,7 @@ buildfire.components.comments = {
692671
backdropEnabled: true,
693672
}, callback);
694673
buildfire.components.swipeableDrawer.onHide = () => {
695-
this._destroy();
674+
this._cleanup();
696675
if (this.onClose && typeof this.onClose === 'function') {
697676
this.onClose();
698677
}
@@ -758,7 +737,7 @@ buildfire.components.comments = {
758737
let actions = [
759738
{ actionId: 'report', text: this.options.translations?.report || 'Report' },
760739
];
761-
if (this.user?.userId && options.item.data.userId === this.user.userId) {
740+
if (this.user?.userId && options.item.data.userId === this.user?.userId) {
762741
actions = [{ actionId: 'delete', text: this.options.translations?.delete || 'Delete' }];
763742
}
764743
return { actions };
@@ -791,6 +770,8 @@ buildfire.components.comments = {
791770
count: this.summary.count,
792771
commentsHeader: this.options.translations?.commentsHeader
793772
}));
773+
// take copy in case the drawer is closed and _cleanup is called
774+
const options = this.options;
794775
this.deleteComment({
795776
itemId: event.item.data.itemId,
796777
commentId: event.item.data.commentId,
@@ -810,13 +791,13 @@ buildfire.components.comments = {
810791
});
811792
return;
812793
}
813-
this.listView.refresh();
794+
this.listView?.refresh();
814795
if (this.onDelete && typeof this.onDelete === 'function') {
815796
this.onDelete();
816797
}
817-
if (typeof this.options.translations?.commentDeleted == 'undefined' || (this.options.translations.commentDeleted !== null && (typeof this.options.translations.commentDeleted === 'string' && this.options.translations?.commentDeleted.trim() !== ''))) {
798+
if (typeof options.translations?.commentDeleted == 'undefined' || (options.translations.commentDeleted !== null && (typeof options.translations.commentDeleted === 'string' && options.translations?.commentDeleted.trim() !== ''))) {
818799
buildfire.dialog.toast({
819-
message: this.options.translations?.commentDeleted || 'Comment deleted successfully.',
800+
message: options.translations?.commentDeleted || 'Comment deleted successfully.',
820801
type: 'success',
821802
});
822803
}
@@ -841,7 +822,7 @@ buildfire.components.comments = {
841822
this.style.height = '40px';
842823
const newHeight = Math.min(this.scrollHeight, 100);
843824
this.style.height = `${newHeight}px`;
844-
commentSafeArea.style.marginBottom = `${newHeight + 80}px`;
825+
commentSafeArea.style.marginBottom = `${newHeight + 50}px`;
845826
};
846827

847828
addCommentIcon.addEventListener('click', () => {
@@ -851,6 +832,8 @@ buildfire.components.comments = {
851832
commentInput.style.height = '40px';
852833
commentSafeArea.style.marginBottom = '80px';
853834
this.addingCommentInProgress = true;
835+
// take copy in case the drawer is closed and _cleanup is called
836+
const options = this.options;
854837
this._addComment({
855838
itemId: this.options.itemId,
856839
userId: this.user?.userId,
@@ -869,9 +852,9 @@ buildfire.components.comments = {
869852
if (this.onAdd && typeof this.onAdd === 'function') {
870853
this.onAdd();
871854
}
872-
if (typeof this.options.translations?.commentAdded == 'undefined' || (this.options.translations.commentAdded !== null && (typeof this.options.translations.commentAdded === 'string' && this.options.translations?.commentAdded.trim() !== ''))) {
855+
if (typeof options.translations?.commentAdded == 'undefined' || (options.translations.commentAdded !== null && (typeof options.translations.commentAdded === 'string' && options.translations?.commentAdded.trim() !== ''))) {
873856
buildfire.dialog.toast({
874-
message: this.options.translations?.commentAdded || 'Comment added successfully.',
857+
message: options.translations?.commentAdded || 'Comment added successfully.',
875858
type: 'success',
876859
});
877860
}
@@ -883,26 +866,43 @@ buildfire.components.comments = {
883866
},
884867

885868
_resetDrawer() {
886-
this._openCommentsDrawer(this.options);
869+
if (this.drawerOpened) {
870+
this._openCommentsDrawer(this.options);
871+
}
887872
},
888873

874+
_onKeyboardWillShow() {
875+
this.keyboardShown = true;
876+
if (this.drawerOpened) {
877+
buildfire.components.swipeableDrawer.setStep('max');
878+
}
879+
},
889880

890-
_onResize() {
891-
if (!this.options) return; // might be destroyed already
892-
const currentWidth = window.innerWidth;
893-
if (this.originalWidth !== currentWidth) {
894-
const drawer = document.querySelector('.swipeable-drawer');
895-
if (drawer) drawer.style.height = '100%'; // reset height to 100% on resize
896-
clearTimeout(this.resizeTimeout);
897-
this.resizeTimeout = setTimeout(() => {
898-
this._initializeDrawer((err, res) => {
899-
this._configureAddCommentSection();
900-
this._initializeListView(() => {
901-
buildfire.components.swipeableDrawer.show();
902-
this.resizeFromKeyboard = false;
903-
});
904-
})
905-
}, 200);
881+
_onKeyboardWillHide() {
882+
this.keyboardShown = false;
883+
},
884+
885+
_onAuthLogout() {
886+
if (this.listView) {
887+
this.listView.reset();
888+
}
889+
this.user = null;
890+
if (this.drawerOpened) {
891+
this._resetDrawer();
892+
}
893+
},
894+
895+
_onAuthLogin(event) {
896+
this.user = event.detail;
897+
if (this.drawerOpened) {
898+
if (this.addingCommentInProgress) {
899+
this._addingCommentDone = () => {
900+
this._resetDrawer();
901+
this._addingCommentDone = null; // reset the function to avoid multiple calls
902+
}
903+
} else {
904+
this._resetDrawer();
905+
}
906906
}
907907
},
908908

@@ -995,15 +995,23 @@ buildfire.components.comments = {
995995
}
996996
},
997997

998-
_destroy() {
998+
_cleanup() {
999+
this.isOpen = false;
9991000
this.drawerOpened = false;
10001001
this.keyboardShown = false;
10011002
this.options = null;
10021003
this.summary = null;
10031004
this.listView = null;
10041005
this.user = null;
10051006
this.comments = [];
1006-
window.removeEventListener('resize', this._onResize.bind(this), false);
1007+
window.removeEventListener('_internal_keyboardWillShow', this._onKeyboardWillShowHandler);
1008+
window.removeEventListener('_internal_keyboardWillHide', this._onKeyboardWillHideHandler);
1009+
window.removeEventListener('_internal_authOnLogout', this._onAuthLogoutHandler);
1010+
window.removeEventListener('_internal_authOnLogin', this._onAuthLoginHandler);
1011+
this._onKeyboardWillShowHandler = null;
1012+
this._onKeyboardWillHideHandler = null;
1013+
this._onAuthLogoutHandler = null;
1014+
this._onAuthLoginHandler = null;
10071015
},
10081016

10091017
_addingCommentDone() { }

0 commit comments

Comments
 (0)