-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
818 lines (664 loc) · 22.7 KB
/
Copy pathscript.js
File metadata and controls
818 lines (664 loc) · 22.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
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
document.addEventListener('DOMContentLoaded', function () {
const chats = document.querySelectorAll('[data-chat]');
const localProjectMatches = [
{
keywords: ['fintech', 'financial', 'finance', 'banking', 'payments', 'payment'],
ctaLabel: 'View a fintech example',
ctaUrl: '/examples/fintech/'
},
{
keywords: ['saas', 'b2b', 'enterprise software', 'platform'],
ctaLabel: 'View a SaaS example',
ctaUrl: '/examples/saas/'
},
{
keywords: ['healthcare', 'medical', 'clinical', 'patient', 'health'],
ctaLabel: 'View a healthcare example',
ctaUrl: '/examples/healthcare/'
},
{
keywords: ['medical', 'sales', 'device', 'emergency', 'mobile', 'app'],
ctaLabel: 'View an app example',
ctaUrl: '/examples/mobile-app/'
},
{
keywords: ['design system', 'design systems', 'components', 'component library', 'tokens'],
ctaLabel: 'View design systems work',
ctaUrl: '/examples/design-systems/'
},
{
keywords: ['dashboard', 'dashboards', 'data', 'analytics', 'reporting'],
ctaLabel: 'See a dashboard example',
ctaUrl: '/examples/dashboards/'
},
{
keywords: ['workflow', 'workflows', 'ux process', 'process'],
ctaLabel: 'Explore a workflow example',
ctaUrl: '/examples/workflows/'
},
{
keywords: ['case study', 'case studies', 'project', 'projects', 'portfolio'],
ctaLabel: 'Browse example case studies',
ctaUrl: '/examples/'
}
];
function isFollowupAcceptance(message) {
const normalized = (message || '').trim().toLowerCase();
return [
'yes',
'yes please',
'please do',
'sure',
'ok',
'okay',
'show me',
'show me that',
'what is it',
'what’s the other one',
'tell me more',
'another one'
].includes(normalized);
}
chats.forEach(function (chat, chatIndex) {
const viewport = chat.querySelector('[data-viewport]');
const thread = chat.querySelector('[data-thread]');
const composer = chat.querySelector('[data-composer-inner]');
const introItem1 = chat.querySelector('[data-intro-bubble]');
const introItem2 = chat.querySelector('[data-intro-bubble-2]');
const introBubble1 = introItem1 ? introItem1.querySelector('.chat-bubble') : null;
const introBubble2 = introItem2 ? introItem2.querySelector('.chat-bubble') : null;
if (!viewport || !thread || !composer || !introBubble1) return;
let chatInputActive = false;
let input = null;
let sendBtn = null;
let form = null;
const SESSION_STORAGE_AVAILABLE = (function () {
try {
const testKey = '__chat_module_test__';
sessionStorage.setItem(testKey, '1');
sessionStorage.removeItem(testKey);
return true;
} catch (err) {
return false;
}
})();
const chatStorageId =
chat.getAttribute('data-chat-id') ||
chat.getAttribute('id') ||
'default';
const sessionKeyBase = 'chatModule:' + chatStorageId + ':chat:' + chatIndex;
const introDismissedKey = sessionKeyBase + ':introDismissed';
const threadStateKey = sessionKeyBase + ':threadState';
function getSessionValue(key) {
if (!SESSION_STORAGE_AVAILABLE) return null;
return sessionStorage.getItem(key);
}
function setSessionValue(key, value) {
if (!SESSION_STORAGE_AVAILABLE) return;
sessionStorage.setItem(key, value);
}
function getSessionFlag(key) {
return getSessionValue(key) === 'true';
}
function setSessionFlag(key, value) {
setSessionValue(key, value ? 'true' : 'false');
}
function isIntroDismissedForSession() {
return getSessionFlag(introDismissedKey);
}
function dismissIntroForSession() {
setSessionFlag(introDismissedKey, true);
}
function getStoredThreadState() {
return getSessionValue(threadStateKey);
}
function hasStoredThreadState() {
const stored = getStoredThreadState();
return !!(stored && stored.trim().length);
}
function persistThreadState() {
if (!SESSION_STORAGE_AVAILABLE) return;
setSessionValue(threadStateKey, thread.innerHTML);
}
function restoreThreadState() {
const stored = getStoredThreadState();
if (!stored) return false;
thread.innerHTML = stored;
requestAnimationFrame(function () {
scrollViewportToBottom();
});
return true;
}
function scrollViewportToBottom() {
requestAnimationFrame(function () {
viewport.scrollTo({
top: viewport.scrollHeight,
behavior: 'smooth'
});
});
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function createThreadItem(side) {
const item = document.createElement('div');
item.className =
'chat-item ' + (side === 'right' ? 'chat-item-right' : 'chat-item-left');
return item;
}
function createBubble(side, html) {
const bubble = document.createElement('div');
bubble.className =
'chat-bubble ' + (side === 'right' ? 'chat-bubble-right' : 'chat-bubble-left');
bubble.innerHTML = html;
return bubble;
}
function createTypingBubble(side) {
return createBubble(
side || 'left',
'<div class="chat-typing"><span class="chat-typing-dot"></span><span class="chat-typing-dot"></span><span class="chat-typing-dot"></span></div>'
);
}
function getTypingDuration(text) {
const words = text.split(/\s+/).length;
return Math.min(1500, Math.max(600, words * 45));
}
function findProjectMatch(message) {
const normalized = (message || '').toLowerCase();
for (let i = 0; i < localProjectMatches.length; i++) {
const entry = localProjectMatches[i];
const matched = entry.keywords.some(function (keyword) {
return normalized.includes(keyword);
});
if (matched) return entry;
}
return null;
}
function extractFirstUrlFromText(text) {
if (!text) return null;
const match = text.match(/https?:\/\/[^\s<>"')]+|\/[a-z0-9\-_/]+\/?/i);
return match ? match[0] : null;
}
function normalizeUrlForHref(url) {
if (!url) return '';
if (/^https?:\/\//i.test(url)) return url;
if (url.charAt(0) === '/') return url;
return '/' + url.replace(/^\/+/, '');
}
function deriveProjectNameFromUrl(url) {
if (!url) return '';
const normalizedUrl = normalizeUrlForHref(url);
const projectNames = {
'/examples/saas/': 'SaaS Example',
'/examples/fintech/': 'Fintech Example',
'/examples/healthcare/': 'Healthcare Example',
'/examples/mobile-app/': 'Mobile App Example',
'/examples/design-systems/': 'Design Systems',
'/examples/dashboards/': 'Dashboard Example',
'/examples/workflows/': 'Workflow Example',
'/examples/': 'Examples',
'/resume/': 'Profile'
};
if (projectNames[normalizedUrl]) return projectNames[normalizedUrl];
if (projectNames[url]) return projectNames[url];
let working = normalizedUrl;
if (/^https?:\/\//i.test(working)) {
try {
const parsed = new URL(working);
working = parsed.pathname;
} catch (e) {
// keep original string
}
}
const trimmed = working.replace(/^\/+|\/+$/g, '');
if (!trimmed) return 'page';
const slug = trimmed.split('/').pop() || '';
return slug
.split('-')
.map(function (part) {
return part.charAt(0).toUpperCase() + part.slice(1);
})
.join(' ');
}
function deriveInlineLinkText(message, options) {
if (!options || !options.ctaUrl) return '';
if (options.inlineLinkText) return options.inlineLinkText;
const lowered = (message || '').toLowerCase();
const keywordCandidates = [
'saas example',
'fintech example',
'healthcare example',
'mobile app example',
'design systems',
'profile',
'examples',
'enterprise saas case study',
'fintech case study',
'healthcare case study',
'app case study',
'this page',
'this project',
'this case study',
'here'
];
for (let i = 0; i < keywordCandidates.length; i++) {
const candidate = keywordCandidates[i];
if (lowered.includes(candidate)) {
return message.substr(lowered.indexOf(candidate), candidate.length);
}
}
const candidates = [
/another\s+[a-z0-9/&+\- ]{1,60}\s+project/i,
/[a-z0-9/&+\- ]{1,60}\s+project/i,
/[a-z0-9/&+\- ]{1,60}\s+case study/i,
/[a-z0-9/&+\- ]{1,60}\s+work/i,
/[a-z0-9/&+\- ]{1,60}\s+example/i
];
for (let i = 0; i < candidates.length; i++) {
const match = message.match(candidates[i]);
if (match && match[0]) {
const candidate = match[0].trim();
if (
candidate.length > 2 &&
candidate.length < 80 &&
!/^visit\s/i.test(candidate) &&
!/^view\s/i.test(candidate) &&
!/^see\s/i.test(candidate) &&
!/^explore\s/i.test(candidate) &&
!/^browse\s/i.test(candidate)
) {
return candidate;
}
}
}
return deriveProjectNameFromUrl(options.ctaUrl);
}
function stripRawUrlFromAnswer(message, options) {
let output = message || '';
const allUrls = [];
if (options && options.ctaUrl) {
allUrls.push(options.ctaUrl);
}
const discoveredUrl = extractFirstUrlFromText(output);
if (discoveredUrl) {
allUrls.push(discoveredUrl);
}
allUrls.forEach(function (url) {
const escapedUrl = escapeRegExp(url);
output = output.replace(new RegExp(escapedUrl, 'gi'), '');
});
output = output.replace(/You can view (?:my |this )?here:\s*/gi, '');
output = output.replace(/You can view (?:my |this )?/gi, 'You can view ');
output = output.replace(/View it here:\s*/gi, '');
output = output.replace(/See it here:\s*/gi, '');
output = output.replace(/Check it out here:\s*/gi, '');
output = output.replace(/\(\s*\)/g, '');
output = output.replace(/\s{2,}/g, ' ').trim();
return output;
}
function stripStandaloneCtaLabelFromAnswer(message, options) {
let output = message || '';
if (!options || !options.ctaLabel) return output;
const escapedLabel = escapeRegExp(options.ctaLabel);
output = output.replace(new RegExp('^\\s*' + escapedLabel + '\\s*$', 'gim'), '');
output = output.replace(new RegExp('\\n\\s*' + escapedLabel + '\\s*$', 'gim'), '');
output = output.replace(/\n{3,}/g, '\n\n').trim();
return output;
}
function sanitizeAnswerText(message, options) {
let output = message || '';
output = stripRawUrlFromAnswer(output, options);
output = stripStandaloneCtaLabelFromAnswer(output, options);
output = output.replace(
/if you want[, ]+i can point you to (a|another|second).*?(too)?\.?/gi,
''
);
output = output.replace(
/i can also point you to (a|another|second).*?(too)?\.?/gi,
''
);
output = output.replace(
/let me know if you'd like another.*?\./gi,
''
);
output = output.replace(
/i can show you another.*?\./gi,
''
);
output = output.replace(/:\s*/g, ' ');
output = output.replace(/\s+([.!?,])/g, '$1');
output = output.replace(/\s{2,}/g, ' ');
output = output.replace(/\n{3,}/g, '\n\n').trim();
return output;
}
function insertInlineLinkIntoHtml(message, options) {
if (!options || !options.ctaUrl) {
return '<p>' + escapeHtml(message) + '</p>';
}
const cleanMessage = sanitizeAnswerText(message, options);
const linkText = deriveInlineLinkText(cleanMessage, options);
const safeLinkText = linkText ? escapeHtml(linkText) : '';
const safeUrl = escapeHtml(normalizeUrlForHref(options.ctaUrl));
let escapedMessage = escapeHtml(cleanMessage);
let linked = false;
if (safeLinkText) {
const linkedMarkup =
'<a class="chat-case-study-link" href="' +
safeUrl +
'">' +
safeLinkText +
'</a>';
const pattern = new RegExp(escapeRegExp(safeLinkText), 'i');
if (pattern.test(escapedMessage)) {
escapedMessage = escapedMessage.replace(pattern, linkedMarkup);
linked = true;
}
}
if (!linked && options.forceAppendInlineLink) {
const fallbackProjectName = escapeHtml(
deriveProjectNameFromUrl(options.ctaUrl) || 'page'
);
if (escapedMessage) {
escapedMessage +=
' <a class="chat-case-study-link" href="' +
safeUrl +
'">' +
fallbackProjectName +
'</a>.';
} else {
escapedMessage =
'<a class="chat-case-study-link" href="' +
safeUrl +
'">' +
fallbackProjectName +
'</a>';
}
}
return '<p>' + escapedMessage + '</p>';
}
function buildBotHtml(message, options) {
return insertInlineLinkIntoHtml(message, options || {});
}
function markItemAsIntro(item, isIntro) {
if (isIntro) {
item.setAttribute('data-intro-message', 'true');
}
}
function removeIntroMessagesFromThread() {
const introMessages = thread.querySelectorAll('[data-intro-message="true"]');
if (!introMessages.length) return;
introMessages.forEach(function (item) {
item.remove();
});
persistThreadState();
scrollViewportToBottom();
}
function addTypingThenMessage(message, delay = 0, options = {}) {
const item = createThreadItem('left');
const typing = createTypingBubble('left');
markItemAsIntro(item, !!options.isIntro);
item.appendChild(typing);
setTimeout(function () {
thread.appendChild(item);
typing.classList.add('chat-bubble-visible');
scrollViewportToBottom();
}, delay);
setTimeout(function () {
typing.innerHTML = buildBotHtml(message, options);
persistThreadState();
scrollViewportToBottom();
}, delay + getTypingDuration(message));
}
function addTypingThenHtml(html, delay = 0, options = {}) {
const item = createThreadItem('left');
const typing = createTypingBubble('left');
markItemAsIntro(item, !!options.isIntro);
item.appendChild(typing);
setTimeout(function () {
thread.appendChild(item);
typing.classList.add('chat-bubble-visible');
scrollViewportToBottom();
}, delay);
const temp = document.createElement('div');
temp.innerHTML = html;
const textForTiming = temp.textContent.trim() || '...';
setTimeout(function () {
typing.innerHTML = html;
persistThreadState();
scrollViewportToBottom();
}, delay + getTypingDuration(textForTiming));
}
function addUserBubble(text) {
const item = createThreadItem('right');
const bubble = createBubble('right', '<p>' + escapeHtml(text) + '</p>');
item.appendChild(bubble);
thread.appendChild(item);
requestAnimationFrame(function () {
bubble.classList.add('chat-bubble-visible');
persistThreadState();
scrollViewportToBottom();
});
}
function setComposerToInput(placeholderText) {
const inputId = 'chat-module-input-' + chatIndex;
composer.innerHTML = `
<form class="chat-module-form" action="#" method="post" novalidate>
<label for="${inputId}" class="sr-only">Ask a question</label>
<input
id="${inputId}"
name="message"
type="text"
class="chat-real-input"
placeholder="${escapeHtml(placeholderText)}"
autocomplete="off"
disabled
aria-disabled="true"
/>
</form>
`;
form = composer.querySelector('.chat-module-form');
input = composer.querySelector('.chat-real-input');
sendBtn = null;
if (!form || !input) return;
input.addEventListener('input', function () {
updateSendButtonState();
});
form.addEventListener('submit', function (e) {
e.preventDefault();
handleSubmit();
});
}
function injectSendButton() {
if (!form || sendBtn) return;
const button = document.createElement('button');
button.type = 'submit';
button.className = 'chat-send-btn';
button.setAttribute('aria-label', 'Send message');
button.textContent = 'Send';
form.appendChild(button);
sendBtn = button;
sendBtn.addEventListener('click', function (e) {
e.preventDefault();
handleSubmit();
});
updateSendButtonState();
}
function enableComposer() {
if (!input) return;
chatInputActive = true;
input.disabled = false;
input.setAttribute('aria-disabled', 'false');
injectSendButton();
updateSendButtonState();
}
function disableComposer() {
if (!input) return;
chatInputActive = false;
input.disabled = true;
input.setAttribute('aria-disabled', 'true');
if (sendBtn) {
sendBtn.classList.remove('chat-send-visible');
}
}
function updateSendButtonState() {
if (!input || !sendBtn) return;
if (!chatInputActive) {
sendBtn.classList.remove('chat-send-visible');
sendBtn.disabled = true;
sendBtn.setAttribute('aria-disabled', 'true');
return;
}
if (input.value.trim().length > 0) {
sendBtn.disabled = false;
sendBtn.setAttribute('aria-disabled', 'false');
sendBtn.classList.add('chat-send-visible');
} else {
sendBtn.disabled = true;
sendBtn.setAttribute('aria-disabled', 'true');
sendBtn.classList.remove('chat-send-visible');
}
}
function normalizeAnswerPayload(data, message) {
if (!data || typeof data !== 'object') {
return {
answer: "I'm not sure.",
ctaLabel: null,
ctaUrl: null,
inlineLinkText: null
};
}
const rawAnswer = data.answer || "I'm not sure.";
const rawUrlFromAnswer = extractFirstUrlFromText(rawAnswer);
const fallbackMatch = findProjectMatch(message);
const ctaLabel = data.ctaLabel || (fallbackMatch ? fallbackMatch.ctaLabel : null);
const ctaUrl =
data.ctaUrl ||
rawUrlFromAnswer ||
(fallbackMatch ? fallbackMatch.ctaUrl : null);
const inlineLinkText = deriveInlineLinkText(rawAnswer, {
ctaLabel: ctaLabel,
ctaUrl: ctaUrl,
inlineLinkText: data.inlineLinkText || null
});
return {
answer: sanitizeAnswerText(rawAnswer, {
ctaLabel: ctaLabel,
ctaUrl: ctaUrl
}),
ctaLabel: ctaLabel,
ctaUrl: ctaUrl,
inlineLinkText: inlineLinkText
};
}
async function sendRealQuestion(message) {
addUserBubble(message);
const typingItem = createThreadItem('left');
const typing = createTypingBubble('left');
typingItem.appendChild(typing);
thread.appendChild(typingItem);
typing.classList.add('chat-bubble-visible');
scrollViewportToBottom();
try {
const response = await fetch('/api/chat/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: message })
});
const data = await response.json();
const normalized = normalizeAnswerPayload(data, message);
typingItem.remove();
const singleMessage = normalized.answer
.replace(/\s+([.!?,])/g, '$1')
.replace(/\s{2,}/g, ' ')
.trim();
addTypingThenMessage(singleMessage, 0, {
ctaLabel: normalized.ctaLabel,
ctaUrl: normalized.ctaUrl,
inlineLinkText: normalized.inlineLinkText,
forceAppendInlineLink: true
});
} catch (e) {
typingItem.remove();
const fallbackMatch = findProjectMatch(message);
addTypingThenMessage(
'Sorry — something went wrong.',
0,
fallbackMatch
? {
ctaLabel: fallbackMatch.ctaLabel,
ctaUrl: fallbackMatch.ctaUrl,
forceAppendInlineLink: true
}
: {}
);
}
}
function handleSubmit() {
if (!chatInputActive || !input) return;
const message = input.value.trim();
if (!message) return;
if (!isIntroDismissedForSession()) {
dismissIntroForSession();
removeIntroMessagesFromThread();
}
input.value = '';
updateSendButtonState();
sendRealQuestion(message);
}
function renderIntroSequence() {
if (introItem1 && introBubble1) {
const firstIntroHtml = introBubble1.innerHTML;
introItem1.style.display = 'none';
addTypingThenHtml(firstIntroHtml, 0, { isIntro: true });
}
if (introItem2 && introBubble2) {
const secondIntroText = introBubble2.textContent.trim();
introItem2.style.display = 'none';
setTimeout(function () {
addTypingThenMessage(secondIntroText, 0, { isIntro: true });
}, 3000);
}
setTimeout(function () {
enableComposer();
if (input) {
input.focus();
}
}, 4500);
}
function renderReturningSessionState() {
if (introItem1) introItem1.style.display = 'none';
if (introItem2) introItem2.style.display = 'none';
enableComposer();
if (input) {
input.focus();
}
scrollViewportToBottom();
}
setComposerToInput('Ask a question…');
disableComposer();
chat.addEventListener('keydown', function (e) {
if (!chatInputActive) return;
if (!e.target.classList.contains('chat-real-input')) return;
if (e.key === 'Enter') {
e.preventDefault();
handleSubmit();
}
});
if (hasStoredThreadState()) {
if (introItem1) introItem1.style.display = 'none';
if (introItem2) introItem2.style.display = 'none';
restoreThreadState();
renderReturningSessionState();
} else if (isIntroDismissedForSession()) {
renderReturningSessionState();
} else {
renderIntroSequence();
}
chat.classList.add('chat-ready');
});
});