diff --git a/JS/login.js b/JS/login.js new file mode 100644 index 0000000..32e512d --- /dev/null +++ b/JS/login.js @@ -0,0 +1,81 @@ +const $ = id => document.getElementById(id); + +function tab(name) { + $('loginForm').hidden = name !== 'login'; + $('signupForm').hidden = name !== 'signup'; + $('loginTab').hidden = name === 'login'; + $('signupTab').hidden = name !== 'login'; + $('authMessage').textContent = ''; +} + +$('loginTab').onclick = () => tab('login'); +$('signupTab').onclick = () => tab('signup'); + +$('loginForm').onsubmit = async event => { + event.preventDefault(); + const response = await fetch('/api/auth/login', { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + credentials: 'same-origin', + body: JSON.stringify({ + login: $('loginName').value, + password: $('loginPassword').value, + }), + }); + const data = await response.json().catch(() => ({})); + if (!response.ok) { + $('authMessage').className = 'message error'; + $('authMessage').textContent = data.detail || data.error || 'Login failed.'; + return; + } + const wantsAdmin = new URLSearchParams(location.search).get('admin') === '1'; + location.replace(data.user?.isPlatformAdmin && wantsAdmin ? '/admin' : '/'); +}; + +function inviteToken(raw) { + const text=(raw||'').trim(); + if (!text)return ''; + try { const u=new URL(text);return u.searchParams.get('invite')||''; } + catch(_) {return text;} +} +async function previewInvite() { + const code=inviteToken($('signupInvite').value); + const room=$('signupRoom'); + if(!code){room.readOnly=false;return;} + const response=await fetch('/borg-chat/api/invites/preview?code='+encodeURIComponent(code),{cache:'no-store'}); + const data=await response.json().catch(()=>({})); + if(!response.ok){ + room.readOnly=false; + $('authMessage').className='message error'; + $('authMessage').textContent=data.detail||'Invitation invalid or expired.'; + return; + } + room.value=data.room;room.readOnly=true; + $('authMessage').className='message ok'; + $('authMessage').textContent='Invitation for '+data.displayName+'. Submit an account request below.'; +} +$('signupInvite').addEventListener('change',previewInvite); +$('signupInvite').addEventListener('paste',()=>setTimeout(previewInvite,0)); +const queryInvite=new URLSearchParams(location.search).get('invite'); +if(queryInvite){ + $('signupInvite').value=queryInvite; + tab('signup'); + history.replaceState(null,'',location.pathname); + previewInvite(); +} +$('signupForm').onsubmit = async event => { + event.preventDefault(); + const response=await fetch('/borg-chat/api/auth/signup',{ + method:'POST',headers:{'Content-Type':'application/json'}, + body:JSON.stringify({ + username:$('signupName').value,email:$('signupEmail').value, + password:$('signupPassword').value, + requested_room:$('signupRoom').value.trim(), + invite_code:inviteToken($('signupInvite').value), + }), + }); + const data=await response.json().catch(()=>({})); + $('authMessage').className='message '+(response.ok?'ok':'error'); + $('authMessage').textContent=response.ok?(data.message||'Account request submitted. Wait for room admin approval.'):(data.detail||data.error||'Signup failed.'); + if(response.ok)event.target.reset(); +}; diff --git a/JS/mobile-shell.js b/JS/mobile-shell.js new file mode 100644 index 0000000..b0d2a4d --- /dev/null +++ b/JS/mobile-shell.js @@ -0,0 +1,156 @@ +(() => { +'use strict'; +const $=id=>document.getElementById(id), wrap=$('borgWindowWrap'), frame=$('borgChatFrame'), ai=$('balrocWindow'); +const labels={room:'Room',chat:'Chat',media:'Media',ai:'AI Command',more:'More',libraries:'Libraries',movies:'Movies',shows:'TV Shows',music:'Music',iptv:'IPTV',youtube:'Tube',twitch:'Twitch',settings:'Manage Libraries'}; +const libraryKind={movies:'movies',shows:'tv',music:'music',iptv:'iptv',youtube:'tube',twitch:'twitch'}; +let permittedLibraries={}, currentSection='libraries', navigationBusy=false, loaded=false, navigateTrail=[], activeTab='room'; +let frameReady=false; +function roomCommand(action){frame.contentWindow?.postMessage({type:'KRONIC_ROOM_UI',action},location.origin);} +function chatMode(open){try{const k=frame.contentWindow.Kronick;if(open)k?.openChatWindow?.();else k?.closeChatWindow?.();}catch(e){console.warn('Room interface unavailable',e);}} +function tab(name){ + if(name==='ai' && $('balrocOpen').hidden)return; + if(name==='media' && $('mobileMediaTab').hidden)return; + activeTab=name; document.body.dataset.mobileTab=name; $('mobileTitle').textContent=labels[name]; + for(const b of document.querySelectorAll('#mobileNav [data-tab]')){if(b.dataset.tab===name)b.setAttribute('aria-current','page');else b.removeAttribute('aria-current');} + wrap.hidden=name!=='media'; $('mobileMore').hidden=name!=='more'; ai.hidden=name!=='ai'; + if(name==='chat')chatMode(true);else chatMode(false); + if(name!=='room')roomCommand('close-audio'); +} +async function refreshLibraryPermissions(){ + try{const c=await api('/api/auth/media-context');permittedLibraries=c.allowedLibraries||{}; + $('mobileManage').hidden=!c.canManageMedia;$('mobileAdmin').hidden=!c.isPlatformAdmin; + }catch(e){permittedLibraries={};$('mobileManage').hidden=true;$('mobileAdmin').hidden=true;} + const any=Object.values(libraryKind).some(k=>permittedLibraries[k]===true); + $('mobileMediaTab').hidden=!any; + for(const b of document.querySelectorAll('[data-borg]'))b.hidden=b.dataset.borg==='libraries'?!any:permittedLibraries[libraryKind[b.dataset.borg]]!==true; + if(activeTab==='media'&&(!any||(libraryKind[currentSection]&&permittedLibraries[libraryKind[currentSection]]!==true)))tab('room'); +} +window.addEventListener('focus',()=>void refreshLibraryPermissions()); +window.addEventListener('kronic:permissions-changed',()=>void refreshLibraryPermissions()); + async function showCategory(type) { + const sources = await api('/api/sources'); + const matches = sources.filter(s => s.library_type === type && s.enabled !== false && s.enabled !== 0); + if (matches.length === 1) return showLibrary(matches[0].id,matches[0].name,matches[0].library_type); + // Multiple libraries: use the existing library homepage and select a category + // using its existing card click handlers, rather than inventing a separate renderer. + await showLibraries(); + const content = document.getElementById('content'); + const section = document.createElement('div'); + section.className = 'borg-category-picks'; + const heading = document.createElement('h2'); + heading.textContent = type === 'movies' ? 'Movie Libraries' : 'TV Show Libraries'; + section.appendChild(heading); + if (!matches.length) { + const empty = document.createElement('p'); + empty.textContent = 'No enabled libraries in this category.'; + section.appendChild(empty); + } else { + for (const source of matches) { + const button=document.createElement('button'); + button.type='button'; button.className='borg-category-choice'; + button.textContent=source.name; + button.addEventListener('click',()=>showLibrary(source.id,source.name,source.library_type)); + section.appendChild(button); + } + } + content.replaceChildren(section); + } + + +async function navigate(kind){ + if(navigationBusy)throw Error('Media navigation is busy; retry shortly'); + navigationBusy=true; + try{ + await refreshLibraryPermissions(); + if(kind==='settings'?!canManageMedia():kind==='libraries'?$('mobileMediaTab').hidden:permittedLibraries[libraryKind[kind]]!==true)throw Error('Library access denied'); + if(kind==='settings'&&$('mobileMediaTab').hidden)throw Error('No media library access'); + tab('media'); $('borgWindowTitle').textContent=labels[kind]||'Media'; + for(const b of document.querySelectorAll('[data-borg]'))b.classList.toggle('borg-selected',b.dataset.borg===kind); + if(kind==='libraries')await showLibraries();else if(kind==='movies'||kind==='shows')await showCategory(kind);else if(kind==='music')await showMusicLibrary();else if(kind==='iptv')await showIptvLibrary('library');else if(kind==='youtube')await showYouTubeLibrary();else if(kind==='twitch')await showTwitchLibrary();else if(kind==='settings')await showManageLibraries();else throw Error('Unknown media category'); + currentSection=kind;loaded=true;wrap.scrollTop=0; + }finally{navigationBusy=false;} +} +function report(e){$('content').textContent='Could not open media: '+e.message;} +window.addEventListener('kronic:ai-media-navigate',async e=>{try{await navigate(e.detail.kind);e.detail.finish?.();}catch(err){e.detail.finish?.(err);}}); + window.addEventListener('kronic:ai-open-library', async event => { + const d=event.detail||{}; + try { + const sources=await api('/api/sources'); + const source=sources.find(x=>Number(x.id)===Number(d.source_id) && String(x.library_type)===String(d.kind) && x.enabled!==false && x.enabled!==0); + if(!source)throw Error('Requested media library unavailable'); + await refreshLibraryPermissions(); + const key=d.kind==='shows'?'tv':'movies'; + if(permittedLibraries?.[key]!==true)throw Error('Library access denied'); + tab('media');currentSection=d.kind;loaded=true; + await showLibrary(source.id,source.name,source.library_type); + if(d.show_name){ + // Only navigate into an actual series displayed by this library. + const media=await api('/api/media?source_id='+encodeURIComponent(source.id)); + const names=[...new Set(media.map(i=>getShowName(i)))]; + const show=names.find(x=>x.toLowerCase()===String(d.show_name).toLowerCase()); + if(show){ + await openShow(show); + if(d.season!==undefined && d.season!==null){ + const exists=media.some(i=>getShowName(i)===show && Number(getSeasonNumber(i))===Number(d.season)); + if(exists)await openSeason(show,'Season '+Number(d.season)); + } + } + } + d.finish?.(); + } catch(error){d.finish?.(error);} + }); + +for(const b of document.querySelectorAll('[data-borg]'))b.addEventListener('click',()=>navigate(b.dataset.borg).catch(report)); +for(const b of document.querySelectorAll('#mobileNav [data-tab]'))b.addEventListener('click',()=>{const name=b.dataset.tab;if(name==='media'&&!loaded){navigate('libraries').catch(report);return;}tab(name);}); +const back=document.createElement('button');back.type='button';back.textContent='← Back';back.id='borgWindowBack';$('borgWindowTitle').before(back); +back.addEventListener('click',async()=>{try{if(navigationBusy)return; + const bc=document.getElementById('breadcrumb')?.textContent?.trim() || ''; + // Native library navigation handles nested movie/show/episode breadcrumbs. + // Every category owns its history: never fall through to the global Libraries screen. + // We use the existing library functions so filters, sorting and selection remain intact. + const crumbs=bc.split('›').map(part=>part.trim()).filter(Boolean); + if(currentSection==='movies' || currentSection==='shows' || + (currentSection==='libraries' && typeof currentSourceId!=='undefined' && currentSourceId)) { + if(crumbs.length>=4 && typeof openShow==='function') { + await openShow(currentShowName || crumbs[2]); return; + } + if(crumbs.length>=3 && typeof showLibrary==='function') { + await showLibrary(currentSourceId,currentSourceName,currentSourceType); return; + } + // At the selected library's root, remain in its category's selection view. + if(crumbs.length>=2 && typeof showCategory==='function') { + await showCategory(currentSourceType==='shows'?'shows':'movies'); return; + } + return; + } + // Music, IPTV, Twitch and Tube are their own roots, not shortcuts to Libraries. + if(currentSection==='music'||currentSection==='iptv'||currentSection==='youtube'||currentSection==='twitch') return; + if(currentSection==='libraries' && navigateTrail.length) { + await navigate(navigateTrail.pop(),true); return; + } + if(currentSection==='libraries') return; + await navigate('libraries'); +}catch(e){report(e);}}); +$('balrocClose').addEventListener('click',()=>tab('room')); +$('borgRoomMute').addEventListener('click',()=>roomCommand('mute')); +$('borgRoomLeave').addEventListener('click',()=>roomCommand('leave')); +$('mobileAudio').addEventListener('click',()=>tab('more')); +for(const b of document.querySelectorAll('[data-mobile-audio]'))b.addEventListener('click',()=>{tab('room');roomCommand('open-audio-'+b.dataset.mobileAudio);}); +$('mobileManage').addEventListener('click',()=>navigate('settings').catch(report)); +const interfaceSelect = $('mobileInterfacePreference'); +if (interfaceSelect) { + interfaceSelect.value = getInterfacePreference(); + interfaceSelect.addEventListener('change', () => { + if (!setInterfacePreference(interfaceSelect.value)) interfaceSelect.value = getInterfacePreference(); + }); +} +$('mobileLogout').addEventListener('click',async()=>{try{await api('/api/auth/logout',{method:'POST'});location.replace('/login');}catch(e){alert(e.message);}}); +window.addEventListener('message',e=>{if(e.origin===location.origin&&e.source===frame.contentWindow&&e.data?.type==='KRONIC_ROOM_UI_STATUS')$('borgRoomVoiceState').textContent=e.data.label||'Not connected';}); +function styleRoom(){try{const d=frame.contentDocument;if(!d?.head||!d.getElementById('participant-container'))return;d.documentElement.classList.add('mobile-room-embedded');if(!d.getElementById('mobileRoomStyles')){const l=d.createElement('link');l.id='mobileRoomStyles';l.rel='stylesheet';l.href='/CSS/mobile-room.css?v=1';d.head.append(l);}if(activeTab==='chat')chatMode(true);}catch(e){console.warn(e);}} +frame.addEventListener('load',styleRoom);styleRoom(); +// Move lazy styles behind the compatibility layer, without loading the desktop shell. +const css=document.querySelector('link[href^="/CSS/mobile.css"]'); +new MutationObserver(records=>{if(records.some(r=>[...r.addedNodes].some(n=>n!==css&&n.tagName==='LINK'&&n.rel==='stylesheet')))document.head.append(css);}).observe(document.head,{childList:true}); +window.addEventListener('kronic:preferred-start-view',e=>{if(e.detail?.section==='libraries'&&activeTab==='room')navigate('libraries').catch(report);}); +void refreshLibraryPermissions(); +})(); diff --git a/JS/public-branding.js b/JS/public-branding.js new file mode 100644 index 0000000..6b2e144 --- /dev/null +++ b/JS/public-branding.js @@ -0,0 +1 @@ +(async()=>{try{const r=await fetch('/api/public/branding',{cache:'no-store'});if(!r.ok)return;const b=await r.json();const h=document.querySelector('.brand h1'),p=document.querySelector('.brand p');if(h)h.textContent=b.login_title||'Welcome';if(p)p.textContent=b.login_subtitle||'';if(b.name&&h){const s=document.createElement('div');s.textContent=b.name;h.before(s);}if(b.powered_by){const s=document.createElement('p');s.textContent='Powered by Kronic';s.style.textAlign='center';document.querySelector('.auth-card')?.append(s);}}catch(e){}})(); \ No newline at end of file diff --git a/JS/room-admin.js b/JS/room-admin.js new file mode 100644 index 0000000..8c99e16 --- /dev/null +++ b/JS/room-admin.js @@ -0,0 +1,175 @@ +/* Kronic room-owner controls. All actions verified again by the backend. */ +(() => { + const K = window.Kronick = window.Kronick || {}; + const byId = id => document.getElementById(id); + let allowed = []; + let currentRoom = null; + const api = async (path, options={}) => { + const headers = {'Accept':'application/json'}; + if (options.body) headers['Content-Type']='application/json'; + const res = await fetch(path, {...options,headers,credentials:'same-origin',cache:'no-store'}); + const data=await res.json().catch(()=>({})); + if (!res.ok) throw new Error(data.detail || `Request failed (${res.status})`); + return data; + }; + const status = message => { if (byId('roomAdminStatus')) byId('roomAdminStatus').textContent=message; }; + const element = (tag,text) => {const el=document.createElement(tag); if(text!==undefined) el.textContent=String(text); return el;}; + const button = (label,handler) => {const b=element('button',label);b.type='button';b.addEventListener('click',handler);return b;}; + const formatTime = unix => new Date(unix*1000).toLocaleString(); + async function refreshAvailable() { + const data=await api('/api/my/room-admin'); + allowed=data.rooms || []; + const gear=byId('roomAdminButton'); + if(gear) gear.hidden=allowed.length===0; + const select=byId('roomAdminSelect'); + if(!select) return; + const previous=select.value; + select.replaceChildren(); + for(const room of allowed){const option=element('option',room.display_name||room.room_name);option.value=room.id;select.append(option);} + const matching=allowed.find(room=>String(room.id)===previous); + const chosen=matching || allowed.find(room=>room.room_name===(K.state?.currentRoomName || byId('roomName')?.value)) || allowed[0]; + if(chosen)select.value=String(chosen.id); + if(!allowed.length && byId('roomAdminFrameWrap')?.style.display==='flex') K.hideToolWindow('roomAdminFrameWrap'); + } + async function loadRoom() { + const id=Number(byId('roomAdminSelect')?.value); + if(!id)return; + status('Loading room…'); + try { + const data=await api(`/api/room-admin/${id}`); + currentRoom=data; + renderMembers(data); + renderInvites(data); + await renderRequests(data); + status(''); + }catch(error){status(error.message);} + } + function renderMembers(data){ + const root=byId('roomAdminMembers');root.replaceChildren(); + for(const member of data.members){ + const row=element('div');row.className='room-admin-row'; + const name=element('div');name.append(element('strong',member.username),element('small',member.status));row.append(name); + const actions=element('div');actions.className='room-admin-actions'; + const select=element('select');select.setAttribute('aria-label',`Role for ${member.username}`); + ['member','moderator','admin','owner'].forEach(role=>{const opt=element('option',role);opt.value=role;select.append(opt);}); + select.value=member.role; + select.disabled=member.role==='owner' && data.myRole!=='owner'; + const save=button('Save',async()=>{ + try{await api(`/api/room-admin/${data.room.id}/members`,{method:'PUT',body:JSON.stringify({user_id:member.id,role:select.value})});await loadRoom();status('Role updated.');} + catch(error){status(error.message);} + }); + save.disabled=select.disabled; + const remove=button('Remove',async()=>{ + if(!confirm(`Remove ${member.username} from ${data.room.display_name || data.room.room_name}?`))return; + try{await api(`/api/room-admin/${data.room.id}/members/${member.id}`,{method:'DELETE'});await loadRoom();status('Member removed.');} + catch(error){status(error.message);} + }); + remove.disabled=select.disabled || member.id===K.account?.user?.id; + const permanent=button('Delete account',async()=>{ + const typed=prompt(`PERMANENTLY delete ${member.username} and their login? This affects the entire instance, not just ${data.room.room_name}.\nType the exact username to confirm:`); + if(typed!==member.username)return; + try { await api(`/api/room-admin/${data.room.id}/users/${member.id}`,{method:'DELETE'});await loadRoom();status('Account permanently deleted.'); } + catch(error){status(error.message);} + }); + permanent.disabled=member.id===K.account?.user?.id || (member.role==='owner' && data.myRole!=='owner') || member.isPlatformAdmin===true; + const reset=button('Require new password',async()=>{ + if(!confirm(`Require ${member.username} to set a new password on next login? Current sessions will be ended.`))return; + try{await api(`/api/room-admin/${data.room.id}/users/${member.id}/require-password-change`,{method:'POST'});status('Password change required on next sign-in.');} + catch(error){status(error.message);} + }); + reset.disabled=member.id===K.account?.user?.id; + const media=document.createElement('details');media.className='room-admin-media'; + const summary=element('summary','Media access');media.append(summary); + const grants={}; + const saved=data.mediaPermissions?.[member.id] || {}; + for(const key of data.mediaKeys || ['movies','tv','music','iptv','tube','twitch']){ + const entry=element('label');const check=element('input');check.type='checkbox'; + check.checked=saved[key]!==false;grants[key]=check;entry.append(check,document.createTextNode(' '+({'tv':'TV Shows','tube':'YouTube'}[key]||key.charAt(0).toUpperCase()+key.slice(1))));media.append(entry); + } + media.append(button('Save media access',async()=>{ + const libraries=Object.fromEntries(Object.entries(grants).map(([key,value])=>[key,value.checked])); + try{await api(`/api/room-admin/${data.room.id}/users/${member.id}/media`,{method:'PUT',body:JSON.stringify({libraries})});status('Media access saved.');} + catch(error){status(error.message);} + })); + actions.append(select,save,remove,permanent);row.append(actions,reset,media);root.append(row); + } + if(!data.members.length)root.append(element('p','No members assigned.')); + } + async function renderRequests(data){ + const root=byId('roomAdminRequests');if(!root)return; + root.replaceChildren(); + const response=await api(`/api/room-admin/${data.room.id}/requests`); + for(const user of response.requests){ + const row=element('div');row.className='room-admin-row'; + const name=element('div');name.append(element('strong',user.username),element('small',user.email)); + row.append(name); + for(const [label,approve] of [['Approve',true],['Deny',false]]){ + row.append(button(label,async()=>{ + if(!confirm(`${label} account ${user.username} for this room?`))return; + try{await api(`/api/room-admin/${data.room.id}/requests/decision`,{ + method:'POST',body:JSON.stringify({user_id:user.id,approve})}); + await loadRoom();status(`Request ${approve?'approved':'denied'}.`); + }catch(error){status(error.message);} + })); + } + root.append(row); + } + if(!response.requests.length)root.append(element('p','No pending room requests.')); + } + function renderInvites(data){ + const root=byId('roomAdminInvites');root.replaceChildren(); + for(const invite of data.invites){ + const row=element('div');row.className='room-admin-row'; + const info=element('div');info.append(element('strong',`Invite #${invite.id}`), + element('small',`${invite.uses}/${invite.max_uses} uses · expires ${formatTime(invite.expires_at)}`), + element('small',invite.revoked?'Revoked':(invite.expires_at*1000 < Date.now()?'Expired':'Active'))); + row.append(info); + if(!invite.revoked){row.append(button('Revoke',async()=>{ + if(!confirm('Revoke this invitation?'))return; + try{await api(`/api/room-admin/${data.room.id}/invites/${invite.id}`,{method:'DELETE'});await loadRoom();status('Invitation revoked.');} + catch(error){status(error.message);} + }));} + root.append(row); + } + if(!data.invites.length)root.append(element('p','No invitations yet.')); + } + K.redeemInvitePrompt=async function redeemInvitePrompt(){ + const code=prompt('Enter your room invitation code (or paste an invitation URL):'); + if(!code)return; + let token=code.trim(); + try {const url=new URL(token);token=url.searchParams.get('invite')||token;}catch(_){/* plain code */} + try{ + await api('/api/my/redeem-invite',{method:'POST',body:JSON.stringify({code:token})}); + alert('Room added to your account. Reloading your room list.'); + window.location.reload(); + }catch(error){alert(error.message);} + }; + K.openRoomAdmin=async function openRoomAdmin(){ + try{await refreshAvailable();if(!allowed.length){status('You do not manage any rooms.');return;} + K.showToolWindow('roomAdminFrameWrap');await loadRoom();} + catch(error){status(error.message);} + }; + document.addEventListener('DOMContentLoaded',()=>{ + byId('roomAdminSelect')?.addEventListener('change',loadRoom); + byId('roomAdminRefresh')?.addEventListener('click',async()=>{await refreshAvailable();await loadRoom();}); + byId('roomInviteCreate')?.addEventListener('click',async()=>{ + const id=Number(byId('roomAdminSelect')?.value); + try{ + const result=await api(`/api/room-admin/${id}/invites`,{method:'POST',body:JSON.stringify({hours:Number(byId('roomInviteHours').value),max_uses:Number(byId('roomInviteUses').value)})}); + // Generate a link to Chat signup, not the legacy Media signup screen. + const roomAdminScript=[...document.scripts].find(s=>/\/js\/room-admin\.js(?:\?|$)/.test(s.src)); + const scriptPath=roomAdminScript?new URL(roomAdminScript.src).pathname:''; + const prefix=scriptPath.includes('/borg-chat/')?'/borg-chat':''; + const url=new URL(`${prefix}/login`,location.origin); + url.searchParams.set('invite',result.code); + byId('roomInviteLink').value=url.toString();byId('roomInviteResult').hidden=false; + await loadRoom();status('Invite created; copy the link now.'); + }catch(error){status(error.message);} + }); + byId('roomInviteCopy')?.addEventListener('click',async()=>{ + try{await navigator.clipboard.writeText(byId('roomInviteLink').value);status('Invitation link copied.');} + catch(error){byId('roomInviteLink').focus();byId('roomInviteLink').select();status('Select and copy the link.');} + }); + refreshAvailable().catch(error=>console.warn('Room administration unavailable:',error)); + }); +})(); diff --git a/JS/tool-windows.js b/JS/tool-windows.js new file mode 100644 index 0000000..e760826 --- /dev/null +++ b/JS/tool-windows.js @@ -0,0 +1,481 @@ +window.Kronick = window.Kronick || {}; + +Kronick.showToolWindow = +function showToolWindow(elementId) { + const windowEl = + document.getElementById(elementId); + + if (!windowEl) { + return; + } + + windowEl.classList.remove('window-minimized'); + windowEl.style.display = 'flex'; + Kronick.removeWindowTaskTab?.(elementId); + + Kronick.bringToolWindowToFront( + windowEl + ); + + requestAnimationFrame(() => { + Kronick.keepWindowInViewport( + windowEl + ); + }); +}; + +Kronick.hideToolWindow = +function hideToolWindow(elementId) { + const windowEl = + document.getElementById(elementId); + + if (!windowEl) { + return; + } + + windowEl.classList.remove('window-minimized', 'window-maximized'); + windowEl.style.display = 'none'; + Kronick.removeWindowTaskTab?.(elementId); +}; + +Kronick.bringToolWindowToFront = +function bringToolWindowToFront(windowEl) { + if (!windowEl) { + return; + } + + Kronick.state.highestWindowZIndex += 1; + + windowEl.style.zIndex = + String( + Kronick.state + .highestWindowZIndex + ); +}; + +Kronick.keepWindowInViewport = +function keepWindowInViewport(windowEl) { + if ( + !windowEl + || windowEl.style.display === 'none' + ) { + return; + } + + const rect = + windowEl.getBoundingClientRect(); + + const maxLeft = Math.max( + 0, + window.innerWidth + - Math.min( + rect.width, + window.innerWidth + ) + ); + + const maxTop = Math.max( + 0, + window.innerHeight - 44 + ); + + const newLeft = Math.max( + 0, + Math.min(rect.left, maxLeft) + ); + + const newTop = Math.max( + 0, + Math.min(rect.top, maxTop) + ); + + windowEl.style.left = + `${newLeft}px`; + + windowEl.style.top = + `${newTop}px`; + + windowEl.style.right = 'auto'; + windowEl.style.bottom = 'auto'; + windowEl.style.transform = 'none'; +}; + +Kronick.keepVisibleWindowsInViewport = +function keepVisibleWindowsInViewport() { + document + .querySelectorAll( + '.tool-frame-wrap, ' + + '.shared-media-wrap' + ) + .forEach(windowEl => { + if ( + windowEl.style.display + !== 'none' + ) { + Kronick.keepWindowInViewport( + windowEl + ); + } + }); +}; + +Kronick.makeToolWindowDraggable = +function makeToolWindowDraggable( + windowEl, + headerEl, + storageKey +) { + if (!windowEl || !headerEl) { + return; + } + + const saved = + localStorage.getItem(storageKey); + + if (saved) { + try { + const pos = JSON.parse(saved); + + windowEl.style.left = + `${Number(pos.left || 0)}px`; + + windowEl.style.top = + `${Number(pos.top || 0)}px`; + + windowEl.style.right = 'auto'; + windowEl.style.bottom = 'auto'; + windowEl.style.transform = 'none'; + } catch { + localStorage.removeItem( + storageKey + ); + } + } + + let dragging = false; + let startX = 0; + let startY = 0; + let startLeft = 0; + let startTop = 0; + + headerEl.addEventListener( + 'mousedown', + event => { + if ( + event.button !== 0 + || event.target.closest( + 'button' + ) + ) { + return; + } + + dragging = true; + + const rect = + windowEl + .getBoundingClientRect(); + + startX = event.clientX; + startY = event.clientY; + startLeft = rect.left; + startTop = rect.top; + + windowEl.style.left = + `${startLeft}px`; + + windowEl.style.top = + `${startTop}px`; + + windowEl.style.right = 'auto'; + windowEl.style.bottom = 'auto'; + windowEl.style.transform = 'none'; + + Kronick.bringToolWindowToFront( + windowEl + ); + + document.body.classList.add( + 'window-dragging' + ); + + event.preventDefault(); + } + ); + + document.addEventListener( + 'mousemove', + event => { + if (!dragging) { + return; + } + + const rect = + windowEl + .getBoundingClientRect(); + + const maxLeft = Math.max( + 0, + window.innerWidth + - rect.width + ); + + const maxTop = Math.max( + 0, + window.innerHeight - 44 + ); + + const newLeft = Math.max( + 0, + Math.min( + maxLeft, + startLeft + + event.clientX + - startX + ) + ); + + const newTop = Math.max( + 0, + Math.min( + maxTop, + startTop + + event.clientY + - startY + ) + ); + + windowEl.style.left = + `${newLeft}px`; + + windowEl.style.top = + `${newTop}px`; + } + ); + + document.addEventListener( + 'mouseup', + () => { + if (!dragging) { + return; + } + + dragging = false; + + document.body.classList.remove( + 'window-dragging' + ); + + localStorage.setItem( + storageKey, + JSON.stringify({ + left: parseInt( + windowEl.style.left + || '0', + 10 + ), + + top: parseInt( + windowEl.style.top + || '0', + 10 + ) + }) + ); + } + ); +}; + +Kronick.openMusicBrowser = +function openMusicBrowser() { + Kronick.showToolWindow( + 'musicFrameWrap' + ); + Kronick.notifyMediaFrame?.(); +}; + +Kronick.closeMusicBrowser = +function closeMusicBrowser() { + Kronick.hideToolWindow( + 'musicFrameWrap' + ); +}; + +Kronick.openGiphyBrowser = +function openGiphyBrowser( + targetMode = 'room' +) { + Kronick.state.giphyTargetMode = + targetMode; + + Kronick.showToolWindow( + 'giphyFrameWrap' + ); + + const giphyFrame = + document.getElementById( + 'giphyFrame' + ); + + setTimeout(() => { + if (giphyFrame?.contentWindow) { + giphyFrame.contentWindow + .postMessage( + { + type: + 'KRONICK_GIPHY_MODE', + + mode: + Kronick.state + .giphyTargetMode + }, + Kronick.config.APP_ORIGIN + ); + } + }, 100); +}; + +Kronick.closeGiphyBrowser = +function closeGiphyBrowser() { + Kronick.hideToolWindow( + 'giphyFrameWrap' + ); + + Kronick.state.giphyTargetMode = + 'room'; +}; + +Kronick.openChatWindow = +function openChatWindow() { + Kronick.showToolWindow( + 'chatFrameWrap' + ); + + Kronick.sendChatHistoryToFrame(); + Kronick.clearChatUnreadCount(); +}; + +Kronick.closeChatWindow = +function closeChatWindow() { + Kronick.hideToolWindow( + 'chatFrameWrap' + ); +}; + + +/* Lightweight desktop-style window management. */ +Kronick.getWindowTaskbar = function getWindowTaskbar() { + return document.getElementById('windowTaskbar'); +}; + +Kronick.removeWindowTaskTab = function removeWindowTaskTab(elementId) { + document.querySelector(`[data-window-tab-for="${elementId}"]`)?.remove(); +}; + +Kronick.addWindowTaskTab = function addWindowTaskTab(windowEl) { + const taskbar = Kronick.getWindowTaskbar(); + if (!taskbar || !windowEl || !windowEl.id) return; + Kronick.removeWindowTaskTab(windowEl.id); + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'window-task-tab'; + button.dataset.windowTabFor = windowEl.id; + button.innerHTML = `${windowEl.dataset.windowIcon || '□'}${windowEl.dataset.windowTitle || 'Window'}`; + button.addEventListener('click', () => Kronick.restoreToolWindow(windowEl.id)); + taskbar.appendChild(button); +}; + +Kronick.minimizeToolWindow = function minimizeToolWindow(elementId) { + const windowEl = document.getElementById(elementId); + if (!windowEl) return; + windowEl.classList.add('window-minimized'); + windowEl.style.display = 'none'; + Kronick.addWindowTaskTab(windowEl); +}; + +Kronick.restoreToolWindow = function restoreToolWindow(elementId) { + const windowEl = document.getElementById(elementId); + if (!windowEl) return; + windowEl.classList.remove('window-minimized'); + windowEl.style.display = 'flex'; + Kronick.removeWindowTaskTab(elementId); + Kronick.bringToolWindowToFront(windowEl); + requestAnimationFrame(() => Kronick.keepWindowInViewport(windowEl)); + if (elementId === 'chatFrameWrap') Kronick.clearChatUnreadCount?.(); +}; + +Kronick.toggleMaximizeToolWindow = function toggleMaximizeToolWindow(elementId) { + const windowEl = document.getElementById(elementId); + if (!windowEl) return; + if (windowEl.classList.contains('window-maximized')) { + const saved = windowEl.dataset.normalBounds; + windowEl.classList.remove('window-maximized'); + if (saved) { + try { + const b = JSON.parse(saved); + for (const key of ['left','top','width','height']) { + if (b[key]) windowEl.style[key] = b[key]; + } + } catch {} + } + Kronick.keepWindowInViewport(windowEl); + return; + } + const r = windowEl.getBoundingClientRect(); + windowEl.dataset.normalBounds = JSON.stringify({left:`${r.left}px`,top:`${r.top}px`,width:`${r.width}px`,height:`${r.height}px`}); + windowEl.classList.add('window-maximized'); + windowEl.style.removeProperty('left'); + windowEl.style.removeProperty('top'); + windowEl.style.removeProperty('width'); + windowEl.style.removeProperty('height'); + Kronick.bringToolWindowToFront(windowEl); +}; + +Kronick.makeToolWindowResizable = function makeToolWindowResizable(windowEl) { + if (!windowEl || windowEl.querySelector(':scope > .window-resize-handle')) return; + const handle = document.createElement('div'); + handle.className = 'window-resize-handle'; + handle.setAttribute('aria-hidden', 'true'); + windowEl.appendChild(handle); + let active = false, sx = 0, sy = 0, sw = 0, sh = 0; + handle.addEventListener('pointerdown', event => { + if (windowEl.classList.contains('window-maximized')) return; + active = true; sx = event.clientX; sy = event.clientY; + const r = windowEl.getBoundingClientRect(); sw = r.width; sh = r.height; + handle.setPointerCapture?.(event.pointerId); + event.preventDefault(); event.stopPropagation(); + }); + handle.addEventListener('pointermove', event => { + if (!active) return; + const maxW = Math.max(260, window.innerWidth - windowEl.getBoundingClientRect().left - 4); + const maxH = Math.max(200, window.innerHeight - windowEl.getBoundingClientRect().top - 4); + windowEl.style.width = `${Math.min(maxW, Math.max(280, sw + event.clientX - sx))}px`; + windowEl.style.height = `${Math.min(maxH, Math.max(220, sh + event.clientY - sy))}px`; + }); + const stop = () => { active = false; }; + handle.addEventListener('pointerup', stop); + handle.addEventListener('pointercancel', stop); +}; + +Kronick.initializeWindowManager = function initializeWindowManager() { + document.querySelectorAll('.tool-frame-wrap, .shared-media-wrap').forEach(windowEl => { + const header = windowEl.querySelector('.tool-frame-header'); + if (!header || header.querySelector('.window-manager-actions')) { + Kronick.makeToolWindowResizable(windowEl); + return; + } + const existingClose = header.querySelector('.window-close-button'); + const actions = document.createElement('div'); + actions.className = 'window-manager-actions'; + const min = document.createElement('button'); + min.type = 'button'; min.className = 'window-control-button'; min.title = 'Minimize'; min.textContent = '−'; + min.addEventListener('click', e => { e.stopPropagation(); Kronick.minimizeToolWindow(windowEl.id); }); + const max = document.createElement('button'); + max.type = 'button'; max.className = 'window-control-button'; max.title = 'Maximize / restore'; max.textContent = '▢'; + max.addEventListener('click', e => { e.stopPropagation(); Kronick.toggleMaximizeToolWindow(windowEl.id); }); + actions.append(min, max); + if (existingClose) actions.appendChild(existingClose); + header.appendChild(actions); + Kronick.makeToolWindowResizable(windowEl); + }); +};