CNESST Deploy Claude Opus 4.6 commited on
Commit
15b764f
·
1 Parent(s): 6f62ade

feat: Add voice search, quick chips, copy button, and PWA support

Browse files

- Feature 1 — Voice Search: mic button using Web Speech API (fr-CA),
auto-submits on final transcript, pulsing animation while listening,
hidden gracefully on unsupported browsers

- Feature 2 — Quick Suggestion Chips: 6 chips (Hauteur garde-corps,
SIMDUT étiquetage, Protection chutes, Échafaudage, Amiante, Pompe béton)
that immediately send the question; welcome card fades out on first send

- Feature 3 — Share/Copy button: 📋 Copier on each bot response (hidden
until hover, always visible on touch devices); uses navigator.share on
mobile, clipboard API with execCommand fallback; shows toast notification

- Feature 4 — PWA: manifest.json (name "Assistant CNESST", dark theme),
sw.js (app shell cache, network-first for navigation, API bypass),
icon-192.png + icon-512.png (safety-yellow hard hat on dark background)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

static/icon-192.png ADDED
static/icon-512.png ADDED
static/index.html CHANGED
@@ -4,6 +4,13 @@
4
  <meta charset="UTF-8" />
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <title>Assistant CNESST ⚠️🏗️</title>
 
 
 
 
 
 
 
7
  <style>
8
  /* ── Reset & Base ─────────────────────────────────────────────────── */
9
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
@@ -516,6 +523,92 @@
516
  transform: translateX(-50%) translateY(0);
517
  }
518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
  /* ── Responsive ───────────────────────────────────────────────────── */
520
  @media (max-width: 480px) {
521
  .header { padding: 12px 14px; }
@@ -556,7 +649,7 @@
556
  <main class="messages" id="messages">
557
 
558
  <!-- Welcome card -->
559
- <div class="welcome">
560
  <h2>👋 Bienvenue sur l'Assistant CNESST</h2>
561
  <p>
562
  Je peux répondre à tes questions sur le <strong>Code de sécurité pour les travaux de construction (CSTC)</strong>
@@ -567,12 +660,14 @@
567
  ⚠️ Ce chatbot donne de l'information légale — pas des conseils juridiques.
568
  Pour des situations spécifiques, consulte la CNESST ou un avocat.
569
  </p>
570
- <div class="welcome-chips">
571
- <button class="chip" onclick="setQuestion('Quelle est la hauteur minimale d\'un garde-corps?')">🔒 Hauteur garde-corps</button>
572
- <button class="chip" onclick="setQuestion('Quelles sont les obligations de l\'employeur en santé sécurité?')">📋 Obligations employeur</button>
573
- <button class="chip" onclick="setQuestion('Quelles sont les règles pour travailler dans un espace clos?')">🚧 Espace clos</button>
574
- <button class="chip" onclick="setQuestion('Quelle protection est requise contre les chutes?')">🪜 Protection contre les chutes</button>
575
- <button class="chip" onclick="setQuestion('Quelles sont les règles pour les échafaudages?')">🏗️ Échafaudages</button>
 
 
576
  </div>
577
  </div>
578
 
@@ -591,6 +686,11 @@
591
  oninput="autoResize(this)"
592
  ></textarea>
593
  </div>
 
 
 
 
 
594
  <button type="submit" class="send-btn" id="sendBtn" onclick="sendMessage()">
595
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
596
  <line x1="22" y1="2" x2="11" y2="13"></line>
@@ -598,7 +698,7 @@
598
  </svg>
599
  </button>
600
  </form>
601
- <p class="input-hint">Entrée pour envoyer · Maj+Entrée pour un saut de ligne</p>
602
  </div>
603
 
604
  </div>
@@ -610,12 +710,16 @@
610
  // ── State ────────────────────────────────────────────────────────────
611
  const history = []; // [{role, content}]
612
  let isLoading = false;
 
613
 
614
  // ── DOM refs ─────────────────────────────────────────────────────────
615
- const messagesEl = document.getElementById('messages');
616
- const inputField = document.getElementById('inputField');
617
- const sendBtn = document.getElementById('sendBtn');
618
- const modeToggle = document.getElementById('mode-toggle');
 
 
 
619
  const modeLabelExpert = document.getElementById('mode-label-expert');
620
  const modeLabelTerrain = document.getElementById('mode-label-terrain');
621
 
@@ -647,13 +751,30 @@
647
  }
648
  }
649
 
650
- // ── Chip suggestion ───────────────────────────────────────────────────
 
 
 
 
 
 
 
651
  function setQuestion(q) {
652
  inputField.value = q;
653
  autoResize(inputField);
654
  inputField.focus();
655
  }
656
 
 
 
 
 
 
 
 
 
 
 
657
  // ── Scroll to bottom ─────────────────────────────────────────────────
658
  function scrollToBottom() {
659
  messagesEl.scrollTop = messagesEl.scrollHeight;
@@ -821,15 +942,50 @@
821
  showToast('Merci pour votre évaluation !');
822
  }
823
 
824
- function showToast(msg) {
825
  const toast = document.getElementById('feedbackToast');
826
  toast.textContent = msg;
827
  toast.classList.add('show');
828
- setTimeout(() => toast.classList.remove('show'), 2500);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
829
  }
830
 
831
  // ── Append bot message ────────────────────────────────────────────────
832
  function appendBotMessage(answer, sources, messageId, question) {
 
 
 
 
833
  const div = document.createElement('div');
834
  div.className = 'message bot';
835
  div.innerHTML = `
@@ -838,8 +994,15 @@
838
  <div class="answer-text">${formatAnswer(answer)}</div>
839
  ${buildSourcesHtml(sources)}
840
  ${messageId ? buildFeedbackHtml(messageId, question) : ''}
 
 
 
841
  </div>
842
  `;
 
 
 
 
843
  messagesEl.appendChild(div);
844
  scrollToBottom();
845
  }
@@ -872,6 +1035,9 @@
872
  const text = inputField.value.trim();
873
  if (!text || isLoading) return;
874
 
 
 
 
875
  // Clear input
876
  inputField.value = '';
877
  inputField.style.height = 'auto';
@@ -879,6 +1045,7 @@
879
  // Set loading state
880
  isLoading = true;
881
  sendBtn.disabled = true;
 
882
 
883
  // Append user bubble
884
  appendUserMessage(text);
@@ -924,9 +1091,100 @@
924
  } finally {
925
  isLoading = false;
926
  sendBtn.disabled = false;
 
927
  inputField.focus();
928
  }
929
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
930
  </script>
931
  </body>
932
  </html>
 
4
  <meta charset="UTF-8" />
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <title>Assistant CNESST ⚠️🏗️</title>
7
+ <!-- PWA Manifest -->
8
+ <link rel="manifest" href="/static/manifest.json" />
9
+ <meta name="theme-color" content="#0f1117" />
10
+ <meta name="apple-mobile-web-app-capable" content="yes" />
11
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
12
+ <meta name="apple-mobile-web-app-title" content="CNESST" />
13
+ <link rel="apple-touch-icon" href="/static/icon-192.png" />
14
  <style>
15
  /* ── Reset & Base ─────────────────────────────────────────────────── */
16
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
 
523
  transform: translateX(-50%) translateY(0);
524
  }
525
 
526
+ /* ── Mic button ───────────────────────────────────────────────────── */
527
+ .mic-btn {
528
+ width: 44px;
529
+ height: 44px;
530
+ border-radius: var(--radius-sm);
531
+ background: var(--surface2);
532
+ border: 1px solid var(--border);
533
+ color: var(--text-muted);
534
+ display: flex;
535
+ align-items: center;
536
+ justify-content: center;
537
+ cursor: pointer;
538
+ flex-shrink: 0;
539
+ font-size: 1.25rem;
540
+ transition: all 0.15s;
541
+ -webkit-tap-highlight-color: transparent;
542
+ user-select: none;
543
+ }
544
+
545
+ .mic-btn:hover:not(:disabled) {
546
+ background: var(--surface);
547
+ border-color: var(--accent);
548
+ color: var(--text);
549
+ }
550
+
551
+ .mic-btn:disabled { opacity: 0.35; cursor: not-allowed; }
552
+
553
+ .mic-btn.listening {
554
+ background: #3a1a1a;
555
+ border-color: var(--danger);
556
+ color: var(--danger);
557
+ animation: micPulse 1s ease-in-out infinite;
558
+ }
559
+
560
+ .mic-btn.hidden { display: none !important; }
561
+
562
+ @keyframes micPulse {
563
+ 0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.45); }
564
+ 50% { box-shadow: 0 0 0 8px rgba(239, 68, 68, 0); }
565
+ }
566
+
567
+ /* ── Copy / Share button on bot messages ──────────────────────────── */
568
+ .bubble-actions {
569
+ display: flex;
570
+ gap: 6px;
571
+ margin-top: 8px;
572
+ opacity: 0;
573
+ transition: opacity 0.2s;
574
+ }
575
+
576
+ .message.bot:hover .bubble-actions,
577
+ .message.bot:focus-within .bubble-actions {
578
+ opacity: 1;
579
+ }
580
+
581
+ /* Always visible on touch / no-hover devices */
582
+ @media (hover: none) {
583
+ .bubble-actions { opacity: 1; }
584
+ }
585
+
586
+ .copy-btn {
587
+ display: flex;
588
+ align-items: center;
589
+ gap: 4px;
590
+ padding: 4px 10px;
591
+ background: var(--surface2);
592
+ border: 1px solid var(--border);
593
+ border-radius: 999px;
594
+ color: var(--text-muted);
595
+ font-size: 0.73rem;
596
+ cursor: pointer;
597
+ transition: all 0.15s;
598
+ white-space: nowrap;
599
+ }
600
+
601
+ .copy-btn:hover {
602
+ background: var(--surface);
603
+ border-color: var(--accent);
604
+ color: var(--text);
605
+ }
606
+
607
+ .copy-btn.copied {
608
+ border-color: var(--success);
609
+ color: var(--success);
610
+ }
611
+
612
  /* ── Responsive ───────────────────────────────────────────────────── */
613
  @media (max-width: 480px) {
614
  .header { padding: 12px 14px; }
 
649
  <main class="messages" id="messages">
650
 
651
  <!-- Welcome card -->
652
+ <div class="welcome" id="welcomeCard">
653
  <h2>👋 Bienvenue sur l'Assistant CNESST</h2>
654
  <p>
655
  Je peux répondre à tes questions sur le <strong>Code de sécurité pour les travaux de construction (CSTC)</strong>
 
660
  ⚠️ Ce chatbot donne de l'information légale — pas des conseils juridiques.
661
  Pour des situations spécifiques, consulte la CNESST ou un avocat.
662
  </p>
663
+ <!-- Quick suggestion chips — hidden once conversation starts -->
664
+ <div class="welcome-chips" id="suggestionChips">
665
+ <button class="chip" onclick="sendChip('Quelle est la hauteur minimale d\'un garde-corps?')">🔒 Hauteur garde-corps?</button>
666
+ <button class="chip" onclick="sendChip('Quelles sont les règles d\'étiquetage SIMDUT?')">🧪 SIMDUT étiquetage?</button>
667
+ <button class="chip" onclick="sendChip('Quelle protection est requise contre les chutes?')">🪜 Protection chutes?</button>
668
+ <button class="chip" onclick="sendChip('Quelles sont les exigences pour les échafaudages?')">🏗️ Échafaudage exigences?</button>
669
+ <button class="chip" onclick="sendChip('Quelles sont les règles pour travailler avec l\'amiante sur un chantier?')">☣️ Amiante sur chantier?</button>
670
+ <button class="chip" onclick="sendChip('Quels sont les permis requis pour une pompe à béton?')">🚛 Permis pompe béton?</button>
671
  </div>
672
  </div>
673
 
 
686
  oninput="autoResize(this)"
687
  ></textarea>
688
  </div>
689
+ <!-- Mic button — hidden if SpeechRecognition not supported -->
690
+ <button type="button" class="mic-btn hidden" id="micBtn"
691
+ title="Dictée vocale (fr-CA)" aria-label="Démarrer la dictée vocale">
692
+ 🎤
693
+ </button>
694
  <button type="submit" class="send-btn" id="sendBtn" onclick="sendMessage()">
695
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
696
  <line x1="22" y1="2" x2="11" y2="13"></line>
 
698
  </svg>
699
  </button>
700
  </form>
701
+ <p class="input-hint" id="inputHint">Entrée pour envoyer · Maj+Entrée pour un saut de ligne</p>
702
  </div>
703
 
704
  </div>
 
710
  // ── State ────────────────────────────────────────────────────────────
711
  const history = []; // [{role, content}]
712
  let isLoading = false;
713
+ let conversationStarted = false;
714
 
715
  // ── DOM refs ─────────────────────────────────────────────────────────
716
+ const messagesEl = document.getElementById('messages');
717
+ const inputField = document.getElementById('inputField');
718
+ const sendBtn = document.getElementById('sendBtn');
719
+ const micBtn = document.getElementById('micBtn');
720
+ const inputHint = document.getElementById('inputHint');
721
+ const welcomeCard = document.getElementById('welcomeCard');
722
+ const modeToggle = document.getElementById('mode-toggle');
723
  const modeLabelExpert = document.getElementById('mode-label-expert');
724
  const modeLabelTerrain = document.getElementById('mode-label-terrain');
725
 
 
751
  }
752
  }
753
 
754
+ // ── Chip suggestion (immediate send) ─────────────────────────────────
755
+ function sendChip(q) {
756
+ inputField.value = q;
757
+ autoResize(inputField);
758
+ sendMessage();
759
+ }
760
+
761
+ // ── Legacy setQuestion (fills field only, doesn't send) ───────────────
762
  function setQuestion(q) {
763
  inputField.value = q;
764
  autoResize(inputField);
765
  inputField.focus();
766
  }
767
 
768
+ // ── Hide welcome card once conversation starts ────────────────────────
769
+ function hideWelcomeCard() {
770
+ if (!conversationStarted && welcomeCard) {
771
+ conversationStarted = true;
772
+ welcomeCard.style.transition = 'opacity 0.3s ease';
773
+ welcomeCard.style.opacity = '0';
774
+ setTimeout(() => { welcomeCard.style.display = 'none'; }, 320);
775
+ }
776
+ }
777
+
778
  // ── Scroll to bottom ─────────────────────────────────────────────────
779
  function scrollToBottom() {
780
  messagesEl.scrollTop = messagesEl.scrollHeight;
 
942
  showToast('Merci pour votre évaluation !');
943
  }
944
 
945
+ function showToast(msg, durationMs) {
946
  const toast = document.getElementById('feedbackToast');
947
  toast.textContent = msg;
948
  toast.classList.add('show');
949
+ setTimeout(() => toast.classList.remove('show'), durationMs || 2500);
950
+ }
951
+
952
+ // ─�� Copy / share bot response ─────────────────────────────────────────
953
+ async function copyBotResponse(btn, rawText) {
954
+ // On mobile with native share, offer share sheet
955
+ if (navigator.share && /Mobi|Android/i.test(navigator.userAgent)) {
956
+ try {
957
+ await navigator.share({ title: 'Assistant CNESST', text: rawText });
958
+ showToast('✅ Partagé !');
959
+ return;
960
+ } catch (e) {
961
+ if (e.name === 'AbortError') return; // user cancelled
962
+ }
963
+ }
964
+ // Clipboard
965
+ try {
966
+ await navigator.clipboard.writeText(rawText);
967
+ } catch (e) {
968
+ // Fallback for HTTP / older browsers
969
+ const ta = document.createElement('textarea');
970
+ ta.value = rawText;
971
+ ta.style.cssText = 'position:fixed;opacity:0';
972
+ document.body.appendChild(ta);
973
+ ta.select();
974
+ document.execCommand('copy');
975
+ document.body.removeChild(ta);
976
+ }
977
+ btn.textContent = '✅ Copié !';
978
+ btn.classList.add('copied');
979
+ showToast('📋 Copié dans le presse-papiers !');
980
+ setTimeout(() => { btn.textContent = '📋 Copier'; btn.classList.remove('copied'); }, 2000);
981
  }
982
 
983
  // ── Append bot message ────────────────────────────────────────────────
984
  function appendBotMessage(answer, sources, messageId, question) {
985
+ const rawText = answer; // plain text for clipboard
986
+ const isMobile = /Mobi|Android/i.test(navigator.userAgent);
987
+ const shareLabel = (navigator.share && isMobile) ? '↗️ Partager' : '📋 Copier';
988
+
989
  const div = document.createElement('div');
990
  div.className = 'message bot';
991
  div.innerHTML = `
 
994
  <div class="answer-text">${formatAnswer(answer)}</div>
995
  ${buildSourcesHtml(sources)}
996
  ${messageId ? buildFeedbackHtml(messageId, question) : ''}
997
+ <div class="bubble-actions">
998
+ <button class="copy-btn" title="Copier la réponse">${shareLabel}</button>
999
+ </div>
1000
  </div>
1001
  `;
1002
+ // Attach copy handler after inserting to DOM
1003
+ const copyBtnEl = div.querySelector('.copy-btn');
1004
+ copyBtnEl.addEventListener('click', () => copyBotResponse(copyBtnEl, rawText));
1005
+
1006
  messagesEl.appendChild(div);
1007
  scrollToBottom();
1008
  }
 
1035
  const text = inputField.value.trim();
1036
  if (!text || isLoading) return;
1037
 
1038
+ // Hide welcome card on first message
1039
+ hideWelcomeCard();
1040
+
1041
  // Clear input
1042
  inputField.value = '';
1043
  inputField.style.height = 'auto';
 
1045
  // Set loading state
1046
  isLoading = true;
1047
  sendBtn.disabled = true;
1048
+ if (micBtn) micBtn.disabled = true;
1049
 
1050
  // Append user bubble
1051
  appendUserMessage(text);
 
1091
  } finally {
1092
  isLoading = false;
1093
  sendBtn.disabled = false;
1094
+ if (micBtn) micBtn.disabled = false;
1095
  inputField.focus();
1096
  }
1097
  }
1098
+
1099
+ // ════════════════════════════════════════════════════════════════════
1100
+ // ── FEATURE 1: Voice Search (Web Speech API) ─────────────────────
1101
+ // ════════════════════════════════════════════════════════════════════
1102
+ (function initVoiceSearch() {
1103
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
1104
+ if (!SpeechRecognition) {
1105
+ // Keep mic button hidden — unsupported browser
1106
+ return;
1107
+ }
1108
+
1109
+ // Show the mic button
1110
+ micBtn.classList.remove('hidden');
1111
+
1112
+ const recognition = new SpeechRecognition();
1113
+ recognition.lang = 'fr-CA';
1114
+ recognition.continuous = false;
1115
+ recognition.interimResults = true;
1116
+ recognition.maxAlternatives = 1;
1117
+
1118
+ let isListening = false;
1119
+
1120
+ recognition.onstart = () => {
1121
+ isListening = true;
1122
+ micBtn.classList.add('listening');
1123
+ micBtn.setAttribute('title', 'Écoute… (cliquer pour arrêter)');
1124
+ inputHint.textContent = '🎤 Parlez maintenant…';
1125
+ };
1126
+
1127
+ recognition.onend = () => {
1128
+ isListening = false;
1129
+ micBtn.classList.remove('listening');
1130
+ micBtn.setAttribute('title', 'Dictée vocale (fr-CA)');
1131
+ inputHint.textContent = 'Entrée pour envoyer · Maj+Entrée pour un saut de ligne';
1132
+ };
1133
+
1134
+ recognition.onerror = (event) => {
1135
+ isListening = false;
1136
+ micBtn.classList.remove('listening');
1137
+ micBtn.setAttribute('title', 'Dictée vocale (fr-CA)');
1138
+ inputHint.textContent = 'Entrée pour envoyer · Maj+Entrée pour un saut de ligne';
1139
+ if (event.error === 'not-allowed') {
1140
+ showToast('⛔ Accès au micro refusé — vérifiez les permissions.', 3500);
1141
+ } else if (event.error !== 'no-speech' && event.error !== 'aborted') {
1142
+ showToast('⚠️ Erreur micro : ' + event.error, 3000);
1143
+ }
1144
+ };
1145
+
1146
+ recognition.onresult = (event) => {
1147
+ let interim = '';
1148
+ let final = '';
1149
+ for (let i = event.resultIndex; i < event.results.length; i++) {
1150
+ const t = event.results[i][0].transcript;
1151
+ if (event.results[i].isFinal) final += t;
1152
+ else interim += t;
1153
+ }
1154
+ // Show interim in field
1155
+ if (interim) {
1156
+ inputField.value = interim;
1157
+ autoResize(inputField);
1158
+ }
1159
+ // Auto-submit on final result
1160
+ if (final.trim()) {
1161
+ inputField.value = final.trim();
1162
+ autoResize(inputField);
1163
+ setTimeout(() => sendMessage(), 350);
1164
+ }
1165
+ };
1166
+
1167
+ micBtn.addEventListener('click', () => {
1168
+ if (isListening) {
1169
+ recognition.stop();
1170
+ } else {
1171
+ inputField.value = '';
1172
+ autoResize(inputField);
1173
+ try { recognition.start(); } catch (e) { /* ignore duplicate start */ }
1174
+ }
1175
+ });
1176
+ })();
1177
+
1178
+ // ════════════════════════════════════════════════════════════════════
1179
+ // ── FEATURE 4: PWA — Service Worker Registration ─────────────────
1180
+ // ════════════════════════════════════════════════════════════════════
1181
+ if ('serviceWorker' in navigator) {
1182
+ window.addEventListener('load', () => {
1183
+ navigator.serviceWorker.register('/static/sw.js')
1184
+ .then(reg => console.log('[SW] Registered, scope:', reg.scope))
1185
+ .catch(err => console.warn('[SW] Registration failed:', err));
1186
+ });
1187
+ }
1188
  </script>
1189
  </body>
1190
  </html>
static/manifest.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Assistant CNESST",
3
+ "short_name": "CNESST",
4
+ "description": "Chatbot de santé et sécurité du travail — CSTC & LSST",
5
+ "start_url": "/",
6
+ "display": "standalone",
7
+ "orientation": "portrait-primary",
8
+ "background_color": "#0f1117",
9
+ "theme_color": "#0f1117",
10
+ "lang": "fr-CA",
11
+ "categories": ["productivity", "utilities"],
12
+ "icons": [
13
+ {
14
+ "src": "/static/icon-192.png",
15
+ "sizes": "192x192",
16
+ "type": "image/png",
17
+ "purpose": "any maskable"
18
+ },
19
+ {
20
+ "src": "/static/icon-512.png",
21
+ "sizes": "512x512",
22
+ "type": "image/png",
23
+ "purpose": "any maskable"
24
+ }
25
+ ],
26
+ "screenshots": [],
27
+ "shortcuts": [
28
+ {
29
+ "name": "Nouvelle question",
30
+ "short_name": "Question",
31
+ "description": "Ouvrir l'assistant CNESST",
32
+ "url": "/",
33
+ "icons": [{ "src": "/static/icon-192.png", "sizes": "192x192" }]
34
+ }
35
+ ]
36
+ }
static/sw.js ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Service Worker — Assistant CNESST
3
+ * Caches the app shell (HTML, CSS, JS) for offline access.
4
+ * API responses (/api/*) are NOT cached — they require a live connection.
5
+ */
6
+
7
+ const CACHE_NAME = 'cnesst-shell-v1';
8
+
9
+ // Resources that form the app shell
10
+ const SHELL_URLS = [
11
+ '/',
12
+ '/static/index.html',
13
+ '/static/manifest.json',
14
+ '/static/icon-192.png',
15
+ '/static/icon-512.png'
16
+ ];
17
+
18
+ // ── Install: pre-cache the shell ──────────────────────────────────────────
19
+ self.addEventListener('install', (event) => {
20
+ event.waitUntil(
21
+ caches.open(CACHE_NAME).then((cache) => {
22
+ return cache.addAll(SHELL_URLS).catch((err) => {
23
+ // Some resources may not exist yet (icons) — don't fail the install
24
+ console.warn('[SW] Pre-cache warning:', err);
25
+ });
26
+ }).then(() => self.skipWaiting())
27
+ );
28
+ });
29
+
30
+ // ── Activate: clean up old caches ─────────────────────────────────────────
31
+ self.addEventListener('activate', (event) => {
32
+ event.waitUntil(
33
+ caches.keys().then((keys) =>
34
+ Promise.all(
35
+ keys
36
+ .filter((key) => key !== CACHE_NAME)
37
+ .map((key) => caches.delete(key))
38
+ )
39
+ ).then(() => self.clients.claim())
40
+ );
41
+ });
42
+
43
+ // ── Fetch: serve shell from cache, API requests always from network ────────
44
+ self.addEventListener('fetch', (event) => {
45
+ const url = new URL(event.request.url);
46
+
47
+ // Never intercept API calls — they must reach the backend
48
+ if (url.pathname.startsWith('/api/')) {
49
+ return; // let the browser handle it normally
50
+ }
51
+
52
+ // For navigation requests (HTML), try network first, fallback to cache
53
+ if (event.request.mode === 'navigate') {
54
+ event.respondWith(
55
+ fetch(event.request)
56
+ .then((response) => {
57
+ // Update the cache with the fresh response
58
+ const clone = response.clone();
59
+ caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
60
+ return response;
61
+ })
62
+ .catch(() => caches.match('/') || caches.match('/static/index.html'))
63
+ );
64
+ return;
65
+ }
66
+
67
+ // For static assets: cache-first strategy
68
+ event.respondWith(
69
+ caches.match(event.request).then((cached) => {
70
+ if (cached) return cached;
71
+
72
+ return fetch(event.request).then((response) => {
73
+ // Only cache successful responses for our own origin
74
+ if (response.ok && url.origin === self.location.origin) {
75
+ const clone = response.clone();
76
+ caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
77
+ }
78
+ return response;
79
+ });
80
+ })
81
+ );
82
+ });