-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathprofile-menu.js
More file actions
674 lines (579 loc) · 25.7 KB
/
profile-menu.js
File metadata and controls
674 lines (579 loc) · 25.7 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
define(function (require, exports, module) {
const Mustache = require("thirdparty/mustache/mustache"),
PopUpManager = require("widgets/PopUpManager"),
ThemeManager = require("view/ThemeManager"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
LoginService = require("./login-service");
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 basic data first for instant response
const renderedTemplate = Mustache.render(loginTemplate, {
Strings,
getProLink: brackets.config.purchase_url
});
$popup = $(renderedTemplate);
$("body").append($popup);
isPopupVisible = true;
positionPopup();
// Check for trial info asynchronously and update popup
KernalModeTrust.loginService.getEffectiveEntitlements().then(effectiveEntitlements => {
if (effectiveEntitlements && effectiveEntitlements.isInProTrial && isPopupVisible && $popup) {
// Add trial info to the existing popup
const planName = StringUtils.format(Strings.PROMO_PRO_TRIAL_DAYS_LEFT,
effectiveEntitlements.trialDaysRemaining);
const trialInfoHtml = `<div class="trial-plan-info">
<span class="phoenix-pro-title-plain">
<span class="pro-plan-name user-plan-name">${planName}</span>
<i class="fa-solid fa-feather" style="margin-left: 3px;"></i>
</span>
</div>`;
$popup.find('.popup-title').after(trialInfoHtml);
positionPopup(); // Reposition after adding content
}
}).catch(error => {
console.error('Failed to check trial info for login popup:', error);
});
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();
}
/**
* Update main navigation branding based on entitlements
*/
function _updateBranding(entitlements) {
const $brandingLink = $("#phcode-io-main-nav");
if (!entitlements) {
// Phoenix.pro is only for display purposes and should not be used to gate features.
// Use kernal mode apis for trusted check of pro features.
Phoenix.pro.plan = {
paidSubscriber: false,
name: "Community Edition"
};
}
if (entitlements && entitlements.plan){
Phoenix.pro.plan = {
paidSubscriber: entitlements.plan.paidSubscriber,
name: entitlements.plan.name,
validTill: entitlements.plan.validTill
};
}
if (entitlements && entitlements.plan && entitlements.plan.paidSubscriber) {
// Pro user (paid subscriber or trial): show plan name with feather icon
let displayName = entitlements.plan.name || brackets.config.main_pro_plan;
if (entitlements.isInProTrial) {
displayName = brackets.config.main_pro_plan; // Just "Phoenix Pro" for branding, not "Phoenix Pro Trial"
}
$brandingLink
.attr("href", "https://account.phcode.dev")
.addClass("phoenix-pro")
.html(`${displayName}<i class="fa-solid fa-feather orange-gold" style="margin-left: 3px;"></i>`);
} else {
// Free user: show phcode.io branding
$brandingLink
.attr("href", "https://phcode.io")
.removeClass("phoenix-pro")
.text("phcode.io");
}
}
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);
}
}
}
/**
* Update popup content with entitlements data
*/
function _updatePopupWithEntitlements(entitlements) {
if (!$popup || !entitlements) {
return;
}
// entitlements will always be present for login popup.
// Update plan information
const $getProLink = $popup.find('.get-phoenix-pro-profile');
if (entitlements.plan) {
const $planName = $popup.find('.user-plan-name');
// Update plan class and content based on paid subscriber status
$planName.removeClass('user-plan-free user-plan-paid');
if (entitlements.plan.paidSubscriber) {
// Use pro styling with feather icon for pro users (paid or trial)
if (entitlements.isInProTrial) {
// For trial users: separate "Phoenix Pro" with icon from "(X days left)" text
const planName = StringUtils.format(Strings.PROMO_PRO_TRIAL_DAYS_LEFT,
entitlements.trialDaysRemaining);
const proTitle = `<span class="phoenix-pro-title-plain">
<span class="pro-plan-name user-plan-name">${planName}</span>
<i class="fa-solid fa-feather" style="margin-left: 3px;"></i>
</span>`;
$planName.addClass('user-plan-paid').html(proTitle);
$getProLink.removeClass('forced-hidden');
} else {
// For paid users: regular plan name with icon
const proTitle = `<span class="phoenix-pro-title">
<span class="pro-plan-name user-plan-name">${entitlements.plan.name}</span>
<i class="fa-solid fa-feather" style="margin-left: 3px;"></i>
</span>`;
$planName.addClass('user-plan-paid').html(proTitle);
$getProLink.addClass('forced-hidden');
}
} else {
// Use simple text for free users
$planName.addClass('user-plan-free').text(entitlements.plan.name);
}
} else {
$getProLink.removeClass('forced-hidden');
}
// Update quota section if available
if (entitlements.profileview && entitlements.profileview.quota) {
const $quotaSection = $popup.find('.quota-section');
const quota = entitlements.profileview.quota;
// Remove forced-hidden and show quota section
$quotaSection.removeClass('forced-hidden');
// Update quota content
$quotaSection.find('.titleText').text(quota.titleText);
$quotaSection.find('.usageText').text(quota.usageText);
$quotaSection.find('.progress-fill').css('width', quota.usedPercent + '%');
}
// Update HTML message if available
if (entitlements.profileview && entitlements.profileview.htmlMessage) {
const $htmlMessageSection = $popup.find('.html-message');
$htmlMessageSection.removeClass('forced-hidden');
$htmlMessageSection.html(entitlements.profileview.htmlMessage);
}
// Reposition popup after content changes
positionPopup();
}
/**
* 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;
// Default template data (fallback) - start with cached plan info if available
const templateData = {
initials: profileData.profileIcon.initials,
avatarColor: profileData.profileIcon.color,
planClass: "user-plan-free",
planName: "Free Plan",
titleText: "Ai Quota Used",
usageText: "100 / 200 credits",
usedPercent: 0,
Strings: Strings,
getProLink: brackets.config.purchase_url
};
// Note: We don't await here to keep popup display instant
// Cached entitlements will be applied asynchronously after popup is shown
// Render template with data immediately
const renderedTemplate = Mustache.render(profileTemplate, templateData);
$popup = $(renderedTemplate);
$("body").append($popup);
isPopupVisible = true;
positionPopup();
// Apply cached effective entitlements immediately if available (including quota/messages)
KernalModeTrust.loginService.getEffectiveEntitlements(false).then(cachedEntitlements => {
if (cachedEntitlements && isPopupVisible) {
_updatePopupWithEntitlements(cachedEntitlements);
}
}).catch(error => {
console.error('Failed to apply cached entitlements to popup:', error);
});
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();
// Refresh entitlements in background and update popup if still visible
_refreshEntitlementsInBackground();
}
/**
* Refresh entitlements in background and update popup if still visible
*/
async function _refreshEntitlementsInBackground() {
try {
const freshEntitlements = await KernalModeTrust.loginService.getEffectiveEntitlements(true);
// Only update popup if it's still visible
if (isPopupVisible && $popup && freshEntitlements) {
_updatePopupWithEntitlements(freshEntitlements);
}
} catch (error) {
console.error('Failed to refresh entitlements in background:', error);
}
}
/**
* 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);
});
}
/**
* Check if user has an active trial (works for both logged-in and non-logged-in users)
*/
async function _hasActiveTrial() {
try {
const effectiveEntitlements = await KernalModeTrust.loginService.getEffectiveEntitlements();
return effectiveEntitlements && effectiveEntitlements.isInProTrial;
} catch (error) {
console.error('Failed to check trial status:', error);
return false;
}
}
/**
* Initialize branding for non-logged-in trial users on startup
*/
async function _initializeBrandingForTrialUsers() {
try {
const effectiveEntitlements = await KernalModeTrust.loginService.getEffectiveEntitlements();
if (effectiveEntitlements && effectiveEntitlements.isInProTrial) {
console.log('Profile Menu: Found active trial, updating branding...');
_updateBranding(effectiveEntitlements);
} else {
console.log('Profile Menu: No active trial found');
_updateBranding(null);
}
} catch (error) {
console.error('Failed to initialize branding for trial users:', 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"));
$icon.on('click', ()=>{
togglePopup();
});
// Initialize branding for non-logged-in trial users
_initializeBrandingForTrialUsers();
// Listen for entitlements changes to update branding for non-logged-in trial users
KernalModeTrust.loginService.on(KernalModeTrust.loginService.EVENT_ENTITLEMENTS_CHANGED, () => {
// When entitlements change (including trial activation) for non-logged-in users, update branding
if (!KernalModeTrust.loginService.isLoggedIn()) {
_initializeBrandingForTrialUsers();
}
});
}
function setNotLoggedIn() {
// Only close popup if it's not a background refresh
if (isPopupVisible && !isBackgroundRefresh) {
closePopup();
}
_removeProfileIcon();
// Reset branding, but preserve trial branding if user has active trial
_hasActiveTrial().then(hasActiveTrial => {
if (!hasActiveTrial) {
// Only reset branding if no trial exists
console.log('Profile Menu: No trial, resetting branding to free');
_updateBranding(null);
} else {
// User has trial, maintain pro branding
console.log('Profile Menu: Trial exists, maintaining pro branding');
_initializeBrandingForTrialUsers();
}
}).catch(error => {
console.error('Failed to check trial status during logout:', error);
// Fallback to resetting branding
_updateBranding(null);
});
// Clear cached entitlements when user logs out
KernalModeTrust.loginService.clearEntitlements();
}
function setLoggedIn(initial, color) {
// Only close popup if it's not a background refresh
if (isPopupVisible && !isBackgroundRefresh) {
closePopup();
}
_updateProfileIcon(initial, color);
// Preload effective entitlements when user logs in
KernalModeTrust.loginService.getEffectiveEntitlements()
.then(_updateBranding)
.catch(error => {
console.error('Failed to preload effective entitlements on login:', error);
});
}
exports.init = init;
exports.setNotLoggedIn = setNotLoggedIn;
exports.setLoggedIn = setLoggedIn;
// dont public exports things that extensions can use to get/put credentials and entitlements, display mods is fine
});