Files
pages/static/js/notifications.js
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

50 lines
14 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
'use strict';
if(window.pageswikiNotificationsInitialized)return;window.pageswikiNotificationsInitialized=true;
const api='/_/api/v1/notifications',ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en;
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
const request=async(url=api+'?limit=30',options={})=>{const r=await fetch(url,{credentials:'same-origin',signal:AbortSignal.timeout(10000),...options,headers:{Accept:'application/json','Content-Type':'application/json',...options.headers}});if(!r.ok||r.redirected)throw Error(t('Notification request failed.','通知の処理に失敗しました。'));return r.json();};
const href=item=>{try{const u=new URL(item.href||'/v/notification?uuid='+encodeURIComponent(item.uuid),location.origin);return u.origin===location.origin?u.href:'/v/notification';}catch{return '/v/notification';}};
function render(root,items){root.replaceChildren(...items.map(item=>{const a=el('a',undefined,'notification-item'+(item.status==='unread'?' unread':''));a.href=href(item);a.append(el('strong',item.message||t('Notification','通知')),el('time',new Date(Number(item.created_at_ms)).toLocaleString()));return a;}));if(!items.length)root.append(el('p',t('No notifications.','通知はありません。'),'muted'));}
document.addEventListener('DOMContentLoaded',()=>{
const launch=document.querySelector('[data-notification-launch]'),dialog=document.querySelector('[data-notification-dialog]'),badge=document.querySelector('[data-notification-badge]'),dialogRoot=dialog?.querySelector('[data-notifications-list]'),pageRoot=document.querySelector('.notifications-page [data-notifications-list]');if(!dialogRoot&&!pageRoot)return;
const owner=dialog?.dataset.owner,key='pageswiki.notifications.v1:'+location.host+':'+(dialog?.dataset.domain||'')+':'+owner;
const read=(suffix,fallback)=>{try{return JSON.parse(localStorage.getItem(key+suffix))??fallback;}catch{return fallback;}},write=(suffix,value)=>{try{localStorage.setItem(key+suffix,JSON.stringify(value));}catch{}};
const defaults={toast:true,browser:false,auto:false,sound:'none',volume:30};let prefs={...defaults,...read('.settings',{})};
let previousVisit=Number(read('.visit',0)),lastServerTime=0,first=true,pending=false,autoPending=false,registration=null,subscription=null,pushReady=false,audio=null,seenIDs=[];const tabID=crypto.randomUUID();
const settings=el('details',undefined,'notification-settings');settings.append(el('summary','⚙ '+t('Notification settings','通知設定')));const panel=el('div');settings.append(panel);dialog?.querySelector('footer')?.before(settings);const settingStatus=el('p');settingStatus.role='status';const controls={};
function toggle(name,label){const l=el('label'),i=el('input');i.type='checkbox';i.checked=!!prefs[name];controls[name]=i;l.append(i,el('span',label));panel.append(l);i.onchange=()=>{prefs[name]=i.checked;write('.settings',prefs);};return i;}
toggle('toast',t('Quiet toast while focused','操作中は右下に一時通知'));toggle('auto',t('Open Inbox on return if new notifications exist','再訪時に新着があればInboxを自動表示'));const browserToggle=toggle('browser',t('Background notifications (Web Push)','バックグラウンド通知(Web Push)'));
const soundLabel=el('label',t('Sound','通知音')),sound=el('select');sound.ariaLabel=t('Sound','通知音');[['none',t('Off','なし')],['soft',t('Soft','ソフト')],['chime',t('Chime','チャイム')],['bell',t('Bell','ベル')]].forEach(([value,label])=>{const o=el('option',label);o.value=value;sound.append(o);});sound.value=prefs.sound;soundLabel.append(sound);panel.append(soundLabel);
const volumeLabel=el('label',t('Volume','音量')),volume=el('input');volume.type='range';volume.min=0;volume.max=100;volume.value=prefs.volume;volume.ariaLabel=t('Volume','音量');volumeLabel.append(volume);panel.append(volumeLabel);
async function unlockAudio(){try{audio??=new(window.AudioContext||window.webkitAudioContext)();await audio.resume();}catch{}}
function play(){if(prefs.sound==='none'||!audio||audio.state!=='running')return;const notes=prefs.sound==='chime'?[660,880]:prefs.sound==='bell'?[880,440]:[520];notes.forEach((hz,i)=>{const osc=audio.createOscillator(),gain=audio.createGain(),start=audio.currentTime+i*.15;osc.frequency.value=hz;gain.gain.setValueAtTime(0,start);gain.gain.linearRampToValueAtTime(Math.min(100,Math.max(0,Number(prefs.volume)||0))/100*.12,start+.02);gain.gain.exponentialRampToValueAtTime(.0001,start+.3);osc.connect(gain);gain.connect(audio.destination);osc.start(start);osc.stop(start+.32);osc.onended=()=>{osc.disconnect();gain.disconnect();};});}
sound.onchange=async()=>{prefs.sound=sound.value;write('.settings',prefs);await unlockAudio();play();};volume.oninput=()=>{prefs.volume=Number(volume.value);write('.settings',prefs);};const test=el('button',t('Test sound','試聴'));test.type='button';test.onclick=async()=>{await unlockAudio();play();};
panel.append(test,el('small',t('Settings are per account and browser. Selected sounds need an active page and interaction; closed-tab sound follows OS settings. Push requires HTTPS, permission and a valid login session.','このアカウント・ブラウザごとの設定です。選択した音はページ動作中・操作後のみ再生します。タブ終了時の音はOS設定に従います。PushにはHTTPS・通知許可・有効なログインが必要です。')),settingStatus);
const toasts=el('div',undefined,'notification-toasts');toasts.setAttribute('aria-live','polite');document.body.append(toasts);
function toast(items){const box=el('div',undefined,'notification-toast'),a=el('a',items.length===1?(items[0].message||t('New notification','新着通知')):t(`${items.length} new notifications`,`${items.length}件の新着通知`));a.href=items.length===1?href(items[0]):'/v/notification';const close=el('button','×');close.type='button';close.ariaLabel=t('Dismiss','閉じる');close.onclick=()=>box.remove();box.append(a,close);toasts.append(box);while(toasts.children.length>3)toasts.firstElementChild.remove();setTimeout(()=>box.remove(),8000);}
const paging=new WeakMap();
async function refresh(target=dialogRoot||pageRoot,mark=false,onlyNew=false,append=false){
let state=paging.get(target);if(!append||!state){state={since:previousVisit,mark,onlyNew,next:''};paging.set(target,state);}state.button?.remove();
try{const data=await request(api+'?limit=30'+(append?'&before='+encodeURIComponent(state.next):''));let items=data.notifications||[];if(state.onlyNew)items=items.filter(n=>n.created_at_ms>=state.since);
if(append){const holder=el('div');render(holder,items);if(items.length)target.append(...holder.children);}else render(target,items);
if(state.mark){await Promise.all(items.filter(n=>n.status==='unread').map(n=>request(api+'/read',{method:'POST',body:JSON.stringify({uuid:n.uuid})})));if(badge)badge.hidden=true;}
state.next=data.next_cursor;if(state.next&&(!state.onlyNew||items.length===30)){const more=el('button',t('Load more','さらに表示'));more.type='button';more.className='notification-more';more.onclick=()=>{more.disabled=true;refresh(target,state.mark,state.onlyNew,true);};state.button=more;target.after(more);}return data;
}catch(e){if(append)target.append(el('p',e.message,'muted'));else target.replaceChildren(el('p',e.message,'muted'));return null;}
}
const focused=()=>!document.hidden&&document.hasFocus();
function showInbox(automatic=false){if(!dialog||dialog.open)return;if(automatic&&(!focused()||document.querySelector('dialog[open]')||/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName)||document.activeElement?.isContentEditable)){autoPending=true;return;}autoPending=false;dialog.showModal();if(badge)badge.hidden=true;refresh(dialogRoot,true,automatic).then(data=>{if(data){previousVisit=data.server_time_ms||Date.now();write('.visit',previousVisit);}});}
launch?.addEventListener('click',()=>showInbox());dialog?.addEventListener('click',e=>{if(e.target===dialog)dialog.close();});dialog?.querySelector('[data-notification-close]')?.addEventListener('click',()=>dialog.close());document.querySelector('[data-notifications-refresh]')?.addEventListener('click',()=>refresh(pageRoot||dialogRoot));if(pageRoot)refresh(pageRoot);
async function deliver(items){if(!items.length)return;const run=async()=>{const seen=read('.delivered',[]),fresh=items.filter(n=>!seen.includes(n.uuid));if(!fresh.length)return;if(!focused())return;write('.delivered',[...fresh.map(n=>n.uuid),...seen].slice(0,200));if(prefs.toast){toast(fresh);play();}};if(navigator.locks)await navigator.locks.request(key+'.delivery',run);else await run();}
async function poll(){if(pending)return;pending=true;try{const data=await request(api+'?unread=1&limit=30'),items=data.notifications||[];lastServerTime=data.server_time_ms||Date.now();if(badge&&!dialog?.open)badge.hidden=!items.length;if(first){first=false;if(prefs.auto&&previousVisit&&items.some(n=>n.created_at_ms>=previousVisit))showInbox(true);else if(!document.hidden){previousVisit=lastServerTime;write('.visit',previousVisit);}}else{if(!dialog?.open)await deliver(items.filter(n=>n.created_at_ms>=previousVisit));if(autoPending&&focused())showInbox(true);if(focused()&&!autoPending&&!dialog?.open){previousVisit=lastServerTime;write('.visit',previousVisit);}}if(dialog?.open&&focused()&&items.some(n=>n.created_at_ms>=previousVisit)){const updated=await refresh(dialogRoot,true);if(updated){previousVisit=updated.server_time_ms;write('.visit',previousVisit);}}seenIDs=focused()?items.map(n=>n.uuid):[];await syncPush();}catch{}finally{pending=false;}}
const decode=v=>Uint8Array.from(atob(v.replace(/-/g,'+').replace(/_/g,'/')),c=>c.charCodeAt(0));
async function registerWorker(){if(!window.isSecureContext||!('serviceWorker'in navigator)||!('PushManager'in window)||!('Notification'in window))throw Error(t('Web Push is unavailable in this browser.','このブラウザではWeb Pushを利用できません。'));registration=await navigator.serviceWorker.register('/static/js/notifications-worker.js',{scope:'/static/js/'});if(!registration.active)await new Promise((resolve,reject)=>{const worker=registration.installing||registration.waiting;if(!worker)return reject(Error('Worker unavailable'));const timer=setTimeout(()=>reject(Error('Worker activation timed out')),10000);worker.addEventListener('statechange',()=>{if(worker.state==='activated'){clearTimeout(timer);resolve();}});});return registration;}
async function syncPush(){if(!prefs.browser||!subscription)return;let presence=read('.focus',{});if(focused()){presence={id:tabID,until:Date.now()+90000};write('.focus',presence);}else if(presence.id===tabID){presence={};write('.focus',presence);}await request(api+'/push',{method:'POST',body:JSON.stringify({subscription:subscription.toJSON(),focused:focused()||presence.until>Date.now(),seen:focused()?seenIDs:[]})});pushReady=true;}
async function enablePush(ask){if(ask&&'Notification'in window&&Notification.permission!=='granted'){if(await Notification.requestPermission()!=='granted')throw Error(t('Browser notification permission was not granted.','ブラウザ通知が許可されていません。'));}await registerWorker();if(Notification.permission!=='granted')throw Error(t('Allow notifications in browser settings.','ブラウザ設定から通知を許可してください。'));const {public_key}=await request(api+'/push');subscription=await registration.pushManager.getSubscription();const globalOwner=localStorage.getItem('pageswiki.push.owner');if(subscription&&globalOwner!==key){await subscription.unsubscribe();subscription=null;}subscription??=await registration.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:decode(public_key)});await syncPush();localStorage.setItem('pageswiki.push.owner',key);settingStatus.textContent=t('Background notifications enabled.','バックグラウンド通知を有効にしました。');}
browserToggle.onchange=async()=>{browserToggle.disabled=true;try{prefs.browser=browserToggle.checked;if(prefs.browser){await enablePush(true);await unlockAudio();}else{subscription??=await(await registerWorker()).pushManager.getSubscription();if(subscription){await request(api+'/push',{method:'DELETE',body:JSON.stringify({subscription:subscription.toJSON()})});await subscription.unsubscribe();}subscription=null;pushReady=false;settingStatus.textContent=t('Background notifications disabled.','バックグラウンド通知を無効にしました。');}write('.settings',prefs);}catch(e){prefs.browser=pushReady;browserToggle.checked=prefs.browser;settingStatus.textContent=e.message;}finally{browserToggle.disabled=false;}};
document.addEventListener('pointerdown',()=>{if(prefs.sound!=='none')unlockAudio();},{passive:true});document.addEventListener('visibilitychange',()=>{if(document.hidden){if(lastServerTime)write('.visit',lastServerTime);}else{if(prefs.auto){previousVisit=Number(read('.visit',previousVisit));first=true;}poll();}syncPush().catch(()=>{});});window.addEventListener('focus',()=>{poll();syncPush().catch(()=>{});});window.addEventListener('blur',()=>syncPush().catch(()=>{}));
window.addEventListener('storage',e=>{if(e.key===key+'.settings'){prefs={...defaults,...read('.settings',{})};for(const name in controls)controls[name].checked=!!prefs[name];sound.value=prefs.sound;volume.value=prefs.volume;if(!prefs.browser)pushReady=false;}});navigator.serviceWorker?.addEventListener('message',e=>{if(e.data?.type==='pageswiki-notification')poll();});window.addEventListener('pagehide',()=>{if(lastServerTime&&!document.hidden)write('.visit',lastServerTime);});
if(owner){poll();setInterval(()=>{if(!document.hidden||!pushReady)poll();},30000);if(prefs.browser)enablePush(false).catch(e=>{settingStatus.textContent=e.message;});}
});
})();