-
-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathprofile-menu.js
More file actions
437 lines (367 loc) · 15.2 KB
/
profile-menu.js
File metadata and controls
437 lines (367 loc) · 15.2 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
define(function (require, exports, module) {
const Mustache = require("thirdparty/mustache/mustache"),
PopUpManager = require("widgets/PopUpManager"),
ThemeManager = require("view/ThemeManager"),
Strings = require("strings");
const KernalModeTrust = window.KernalModeTrust;
if(!KernalModeTrust){
// integrated extensions will have access to kernal mode, but not external extensions
throw new Error("profile menu should have access to KernalModeTrust. Cannot boot without trust ring");
}
let $icon;
function _createSVGIcon(initials, bgColor) {
return `<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10" fill="${bgColor}"/>
<text x="12" y="12" text-anchor="middle" dominant-baseline="central" font-size="10" fill="#fff" font-family="Inter, sans-serif">
${initials}</text>
</svg>`;
}
function _updateProfileIcon(initials, bgColor) {
$icon.empty()
.append(_createSVGIcon(initials, bgColor));
}
function _removeProfileIcon() {
$icon.empty();
}
// HTML templates
const loginTemplate = require("text!./html/login-popup.html");
const profileTemplate = require("text!./html/profile-popup.html");
// for the popup DOM element
let $popup = null;
// this is to track whether the popup is visible or not
let isPopupVisible = false;
// Track if we're doing a background refresh to avoid closing user-opened popups
let isBackgroundRefresh = false;
// this is to handle document click events to close popup
let documentClickHandler = null;
function _handleSignInBtnClick() {
closePopup(); // need to close the current popup to show the new one
KernalModeTrust.loginService.signInToAccount();
}
function _handleSignOutBtnClick() {
closePopup();
KernalModeTrust.loginService.signOutAccount();
}
function _handleContactSupportBtnClick() {
Phoenix.app.openURLInDefaultBrowser(brackets.config.support_url);
}
function _handleAccountDetailsBtnClick() {
Phoenix.app.openURLInDefaultBrowser(brackets.config.account_url);
}
/**
* Close the popup if it's open
* this is called at various instances like when the user click on the profile icon even if the popup is open
* or when user clicks somewhere else on the document
*/
function closePopup() {
if ($popup) {
PopUpManager.removePopUp($popup);
$popup = null;
isPopupVisible = false;
}
// we need to remove document click handler if it already exists
if (documentClickHandler) {
$(document).off("mousedown", documentClickHandler);
documentClickHandler = null;
}
}
/**
* this function is to position the popup near the profile button
*/
function positionPopup() {
const $profileButton = $("#user-profile-button");
if ($profileButton.length && $popup) {
const buttonPos = $profileButton.offset();
const popupWidth = $popup.outerWidth();
const windowWidth = $(window).width();
// pos above the profile button
let top = buttonPos.top - $popup.outerHeight() - 10;
// If popup would go off the right edge of the window, align right edge of popup with right edge of button
let left = Math.min(
buttonPos.left - popupWidth + $profileButton.outerWidth(),
windowWidth - popupWidth - 10
);
// never go off left edge
left = Math.max(10, left);
$popup.css({
top: top + "px",
left: left + "px"
});
}
}
/**
* this function is responsible to set up a click handler to close the popup when clicking outside
*/
function _setupDocumentClickHandler() {
// remove any existing handlers
if (documentClickHandler) {
$(document).off("mousedown", documentClickHandler);
}
// add the new click handler
documentClickHandler = function (event) {
// if the click is outside the popup and not on the profile button (which toggles the popup)
if ($popup && !$popup[0].contains(event.target) && !$("#user-profile-button")[0].contains(event.target)) {
closePopup();
}
};
// this is needed so we don't close the popup immediately as the profile button is clicked
setTimeout(function() {
$(document).on("mousedown", documentClickHandler);
}, 100);
}
/**
* Shows the sign-in popup when the user is not logged in
*/
function showLoginPopup() {
// If popup is already visible, just close it
if (isPopupVisible) {
closePopup();
return;
}
// create the popup element
closePopup(); // close any existing popup first
// Render template with data
const renderedTemplate = Mustache.render(loginTemplate, {Strings});
$popup = $(renderedTemplate);
$("body").append($popup);
isPopupVisible = true;
positionPopup();
PopUpManager.addPopUp($popup, function() {
$popup.remove();
$popup = null;
isPopupVisible = false;
}, true, { closeCurrentPopups: true });
// event handlers for buttons
$popup.find("#phoenix-signin-btn").on("click", function () {
_handleSignInBtnClick();
});
$popup.find("#phoenix-support-btn").on("click", function () {
_handleContactSupportBtnClick();
closePopup();
});
// handle window resize to reposition popup
$(window).on("resize.profilePopup", function () {
if (isPopupVisible) {
positionPopup();
}
});
_setupDocumentClickHandler();
}
let userEmail="";
class SecureEmail extends HTMLElement {
constructor() {
super();
// Create closed shadow root - this is for security that extensions wont be able to read email from DOM
const shadow = this.attachShadow({ mode: 'closed' });
// Create the email display with some obfuscation techniques
shadow.innerHTML = `<span>${userEmail}</span>`;
}
}
// Register the custom element
/* eslint-disable-next-line*/
customElements.define ('secure-email', SecureEmail); // space is must in define ( to prevent build fail
let userName="";
class SecureName extends HTMLElement {
constructor() {
super();
// Create closed shadow root - this is for security that extensions wont be able to read name from DOM
const shadow = this.attachShadow({ mode: 'closed' });
// Create the email display with some obfuscation techniques
shadow.innerHTML = `<span>${userName}</span>`;
}
}
// Register the custom element
/* eslint-disable-next-line*/
customElements.define ('secure-name', SecureName); // space is must in define ( to prevent build fail
/**
* Load user details iframe with secure user information
*/
function _loadUserDetailsIframe() {
if (!Phoenix.isNativeApp && $popup) {
const $iframe = $popup.find("#user-details-frame");
const $secureName = $popup.find(".user-name secure-name");
const $secureEmail = $popup.find(".user-email secure-email");
if ($iframe.length) {
// Get account base URL for iframe using login service
const accountBaseURL = KernalModeTrust.loginService.getAccountBaseURL();
const currentTheme = ThemeManager.getCurrentTheme();
const nameColor = (currentTheme && currentTheme.dark) ? "FFFFFF" : "000000";
// Configure iframe URL with styling parameters
const iframeURL = `${accountBaseURL}/getUserDetailFrame?` +
`includeName=true&` +
`nameFontSize=14px&` +
`emailFontSize=12px&` +
`nameColor=%23${nameColor}&` +
`emailColor=%23666666&` +
`backgroundColor=transparent`;
// Listen for iframe load events
const messageHandler = function(event) {
// Only accept messages from trusted account domain
// Handle proxy case where accountBaseURL is '/proxy/accounts'
let trustedOrigin;
if (accountBaseURL.startsWith('/proxy/accounts')) {
// For localhost with proxy, accept messages from current origin
trustedOrigin = window.location.origin;
} else {
// For production, get origin from account URL
trustedOrigin = new URL(accountBaseURL).origin;
}
if (event.origin !== trustedOrigin) {
return;
}
if (event.data && event.data.loaded) {
// Hide secure DOM elements and show iframe
$secureName.hide();
$secureEmail.hide();
$iframe.show();
// Adjust iframe height based on content
$iframe.css('height', '36px'); // Approximate height for name + email
// Remove event listener
window.removeEventListener('message', messageHandler);
}
};
// Add message listener
window.addEventListener('message', messageHandler);
// Set iframe source to load user details
$iframe.attr('src', iframeURL);
// Fallback timeout - if iframe doesn't load in 5 seconds, keep secure elements
setTimeout(() => {
if ($iframe.is(':hidden')) {
console.log('User details iframe failed to load, keeping secure elements');
window.removeEventListener('message', messageHandler);
}
}, 5000);
}
}
}
/**
* Shows the user profile popup when the user is logged in
*/
function showProfilePopup() {
// If popup is already visible, just close it
if (isPopupVisible) {
closePopup();
return;
}
const profileData = KernalModeTrust.loginService.getProfile();
userEmail = profileData.email;
userName = profileData.firstName + " " + profileData.lastName;
const templateData = {
initials: profileData.profileIcon.initials,
avatarColor: profileData.profileIcon.color,
planClass: "user-plan-free", // "user-plan-paid" for paid plan
planName: "Free Plan",
quotaUsed: "7,000",
quotaTotal: "10,000",
quotaUnit: "tokens",
quotaPercent: 70,
Strings: Strings
};
// Render template with data
const renderedTemplate = Mustache.render(profileTemplate, templateData);
$popup = $(renderedTemplate);
$("body").append($popup);
isPopupVisible = true;
positionPopup();
PopUpManager.addPopUp($popup, function() {
$popup.remove();
$popup = null;
isPopupVisible = false;
}, true, { closeCurrentPopups: true });
$popup.find("#phoenix-account-btn").on("click", function () {
_handleAccountDetailsBtnClick();
closePopup();
});
$popup.find("#phoenix-support-btn").on("click", function () {
_handleContactSupportBtnClick();
closePopup();
});
$popup.find("#phoenix-signout-btn").on("click", function () {
_handleSignOutBtnClick();
});
// handle window resize to reposition popup
$(window).on("resize.profilePopup", function () {
if (isPopupVisible) {
positionPopup();
}
});
_setupDocumentClickHandler();
// Load user details iframe for browser apps (after popup is created)
_loadUserDetailsIframe();
}
/**
* Toggle the profile popup based on the user's login status
*/
function togglePopup() {
// check if the popup is already visible or not. if visible close it
if (isPopupVisible) {
closePopup();
return;
}
// Show popup immediately with cached status for instant response
if (KernalModeTrust.loginService.isLoggedIn()) {
showProfilePopup();
} else {
showLoginPopup();
}
// Schedule background verification to update the popup if status changed
// Store the current login state before verification
const wasLoggedInBefore = KernalModeTrust.loginService.isLoggedIn();
// Set flag to indicate this is a background refresh
isBackgroundRefresh = true;
KernalModeTrust.loginService.verifyLoginStatus().then(() => {
// Clear the background refresh flag
isBackgroundRefresh = false;
// If the login status changed while popup is open, update it
if (isPopupVisible) {
const isLoggedInNow = KernalModeTrust.loginService.isLoggedIn();
if (wasLoggedInBefore !== isLoggedInNow) {
// Status changed, close current popup and show correct one
closePopup();
if (isLoggedInNow) {
showProfilePopup();
} else {
showLoginPopup();
}
}
// If status didn't change, don't do anything to avoid closing popup
}
}).catch(error => {
// Clear the background refresh flag even on error
isBackgroundRefresh = false;
console.error("Background login status verification failed:", error);
});
}
function init() {
const helpButtonID = "user-profile-button";
$icon = $("<a>")
.attr({
id: helpButtonID,
href: "#",
class: "user",
title: Strings.CMD_USER_PROFILE
})
.appendTo($("#main-toolbar .bottom-buttons"));
// _updateProfileIcon("CA", "blue");
$icon.on('click', ()=>{
togglePopup();
});
}
function setNotLoggedIn() {
// Only close popup if it's not a background refresh
if (isPopupVisible && !isBackgroundRefresh) {
closePopup();
}
_removeProfileIcon();
}
function setLoggedIn(initial, color) {
// Only close popup if it's not a background refresh
if (isPopupVisible && !isBackgroundRefresh) {
closePopup();
}
_updateProfileIcon(initial, color);
}
exports.init = init;
exports.setNotLoggedIn = setNotLoggedIn;
exports.setLoggedIn = setLoggedIn;
});