diff --git a/kronic-chat/js/screenshare.js b/kronic-chat/js/screenshare.js new file mode 100644 index 0000000..c1377a5 --- /dev/null +++ b/kronic-chat/js/screenshare.js @@ -0,0 +1,1019 @@ +// screenshare.js + +window.Kronick = + window.Kronick || {}; + + +/* + * Screen-share-specific state. + */ +Kronick.screenShare = { + room: + null, + + initializedRoom: + null, + + activeVideoTrack: + null, + + activeAudioTrack: + null, + + activeParticipantSid: + null, + + activeParticipantName: + '', + + isLocalSharing: + false, + + listeners: + null +}; + + +/* + * Determine whether a publication is a screen-share + * video track. + */ +Kronick.isScreenShareVideoPublication = +function isScreenShareVideoPublication( + publication +) { + if (!publication) { + return false; + } + + const source = + publication.source; + + const screenShareSource = + window.LivekitClient + ?.Track + ?.Source + ?.ScreenShare; + + return ( + source === screenShareSource + || source === 'screen_share' + || source === 'screenshare' + ); +}; + + +/* + * Determine whether a publication is screen-share + * audio. + */ +Kronick.isScreenShareAudioPublication = +function isScreenShareAudioPublication( + publication +) { + if (!publication) { + return false; + } + + const source = + publication.source; + + const screenShareAudioSource = + window.LivekitClient + ?.Track + ?.Source + ?.ScreenShareAudio; + + return ( + source === screenShareAudioSource + || source === 'screen_share_audio' + || source === 'screenshareaudio' + ); +}; + + +/* + * Initialize screen-share listeners for a LiveKit room. + * + * Call this once each time a new Room instance is created. + */ +Kronick.initScreenShare = +function initScreenShare(room) { + if (!room) { + return; + } + + /* + * Do not register the same listeners twice on the + * same room. + */ + if ( + Kronick.screenShare + .initializedRoom === room + ) { + return; + } + + Kronick.cleanupScreenShareListeners(); + + Kronick.screenShare.room = + room; + + Kronick.screenShare.initializedRoom = + room; + + const { + RoomEvent + } = LivekitClient; + + + const handleTrackSubscribed = ( + track, + publication, + participant + ) => { + if ( + Kronick + .isScreenShareVideoPublication( + publication + ) + ) { + Kronick.showScreenShareVideo( + track, + participant, + false + ); + + return; + } + + if ( + Kronick + .isScreenShareAudioPublication( + publication + ) + ) { + Kronick.showScreenShareAudio( + track + ); + } + }; + + + const handleTrackUnsubscribed = ( + track, + publication, + participant + ) => { + if ( + Kronick + .isScreenShareVideoPublication( + publication + ) + ) { + Kronick.removeScreenShareVideo( + track + ); + + return; + } + + if ( + Kronick + .isScreenShareAudioPublication( + publication + ) + ) { + Kronick.removeScreenShareAudio( + track + ); + } + }; + + + const handleLocalTrackPublished = ( + publication, + participant + ) => { + const track = + publication?.track; + + if (!track) { + return; + } + + if ( + Kronick + .isScreenShareVideoPublication( + publication + ) + ) { + Kronick.screenShare + .isLocalSharing = true; + + Kronick.showScreenShareVideo( + track, + participant + || room.localParticipant, + true + ); + + Kronick.updateScreenShareControls(); + + return; + } + + if ( + Kronick + .isScreenShareAudioPublication( + publication + ) + ) { + Kronick.showScreenShareAudio( + track + ); + } + }; + + + const handleLocalTrackUnpublished = ( + publication + ) => { + if ( + Kronick + .isScreenShareVideoPublication( + publication + ) + ) { + Kronick.screenShare + .isLocalSharing = false; + + Kronick.removeScreenShareVideo( + publication.track + ); + + Kronick.updateScreenShareControls(); + + return; + } + + if ( + Kronick + .isScreenShareAudioPublication( + publication + ) + ) { + Kronick.removeScreenShareAudio( + publication.track + ); + } + }; + + + const handleDisconnected = () => { + Kronick.resetScreenShare(); + }; + + + room.on( + RoomEvent.TrackSubscribed, + handleTrackSubscribed + ); + + room.on( + RoomEvent.TrackUnsubscribed, + handleTrackUnsubscribed + ); + + room.on( + RoomEvent.LocalTrackPublished, + handleLocalTrackPublished + ); + + room.on( + RoomEvent.LocalTrackUnpublished, + handleLocalTrackUnpublished + ); + + room.on( + RoomEvent.Disconnected, + handleDisconnected + ); + + + Kronick.screenShare.listeners = { + handleTrackSubscribed, + handleTrackUnsubscribed, + handleLocalTrackPublished, + handleLocalTrackUnpublished, + handleDisconnected + }; + + Kronick.detectExistingScreenShares( + room + ); + + Kronick.updateScreenShareControls(); +}; + + +/* + * Remove listeners from the previous room. + */ +Kronick.cleanupScreenShareListeners = +function cleanupScreenShareListeners() { + const room = + Kronick.screenShare + .initializedRoom; + + const listeners = + Kronick.screenShare.listeners; + + if ( + !room + || !listeners + ) { + Kronick.screenShare + .initializedRoom = null; + + Kronick.screenShare + .listeners = null; + + return; + } + + const { + RoomEvent + } = LivekitClient; + + room.off( + RoomEvent.TrackSubscribed, + listeners.handleTrackSubscribed + ); + + room.off( + RoomEvent.TrackUnsubscribed, + listeners.handleTrackUnsubscribed + ); + + room.off( + RoomEvent.LocalTrackPublished, + listeners.handleLocalTrackPublished + ); + + room.off( + RoomEvent.LocalTrackUnpublished, + listeners.handleLocalTrackUnpublished + ); + + room.off( + RoomEvent.Disconnected, + listeners.handleDisconnected + ); + + Kronick.screenShare + .initializedRoom = null; + + Kronick.screenShare + .listeners = null; +}; + + +/* + * Check whether anyone was already sharing before this + * file initialized or before the local user joined. + */ +Kronick.detectExistingScreenShares = +function detectExistingScreenShares(room) { + if (!room) { + return; + } + + const participants = [ + room.localParticipant, + ...room.remoteParticipants.values() + ]; + + participants.forEach(participant => { + if (!participant) { + return; + } + + participant + .getTrackPublications() + .forEach(publication => { + const track = + publication.track; + + if (!track) { + return; + } + + if ( + Kronick + .isScreenShareVideoPublication( + publication + ) + ) { + const isLocal = + participant + === room.localParticipant; + + Kronick.showScreenShareVideo( + track, + participant, + isLocal + ); + } + + if ( + Kronick + .isScreenShareAudioPublication( + publication + ) + ) { + Kronick.showScreenShareAudio( + track + ); + } + }); + }); +}; + + +/* + * Start or stop the local user's screen share. + */ +Kronick.toggleScreenShare = +async function toggleScreenShare() { + const room = + Kronick.state.room; + + if (!room?.localParticipant) { + alert( + 'Join a room before sharing ' + + 'your screen.' + ); + + return; + } + + const button = + document.getElementById( + 'screenShareBtn' + ); + + if (button) { + button.disabled = true; + } + + try { + const currentlySharing = + Kronick.screenShare + .isLocalSharing + || Kronick + .localParticipantIsScreenSharing( + room.localParticipant + ); + + await room.localParticipant + .setScreenShareEnabled( + !currentlySharing, + { + audio: + true, + + resolution: { + width: + 1920, + + height: + 1080, + + frameRate: + 30 + } + } + ); + + Kronick.screenShare + .isLocalSharing = + !currentlySharing; + + if ( + Kronick.screenShare + .isLocalSharing + ) { + Kronick.openScreenShareWindow(); + } else { + Kronick.removeLocalScreenShare(); + } + } catch (err) { + console.error( + 'Could not change screen-share state:', + err + ); + + /* + * NotAllowedError normally means the user + * cancelled the browser share picker. + */ + if ( + err.name !== 'NotAllowedError' + ) { + alert( + 'Screen sharing failed. ' + + 'Check the browser console.' + ); + } + } finally { + if (button) { + button.disabled = false; + } + + Kronick.updateScreenShareControls(); + } +}; + + +/* + * Check the local participant's current publications. + */ +Kronick.localParticipantIsScreenSharing = +function localParticipantIsScreenSharing( + participant +) { + if (!participant) { + return false; + } + + let sharing = false; + + participant + .getTrackPublications() + .forEach(publication => { + if ( + publication.track + && Kronick + .isScreenShareVideoPublication( + publication + ) + ) { + sharing = true; + } + }); + + return sharing; +}; + + +/* + * Stop screen sharing explicitly. + */ +Kronick.stopScreenShare = +async function stopScreenShare() { + const room = + Kronick.state.room; + + if (!room?.localParticipant) { + return; + } + + try { + await room.localParticipant + .setScreenShareEnabled( + false + ); + } catch (err) { + console.error( + 'Could not stop screen sharing:', + err + ); + } + + Kronick.screenShare + .isLocalSharing = false; + + Kronick.removeLocalScreenShare(); + Kronick.updateScreenShareControls(); +}; + + +/* + * Attach a screen-share video track to the popup. + */ +Kronick.showScreenShareVideo = +function showScreenShareVideo( + track, + participant, + isLocal = false +) { + if (!track) { + return; + } + + const container = + document.getElementById( + 'screenShareVideoContainer' + ); + + const emptyMessage = + document.getElementById( + 'screenShareEmpty' + ); + + const title = + document.getElementById( + 'screenShareTitle' + ); + + if (!container) { + console.error( + 'Screen-share container ' + + 'was not found.' + ); + + return; + } + + Kronick.detachCurrentScreenShareVideo(); + + const attachedElement = + track.attach(); + + attachedElement.classList.add( + 'screen-share-video' + ); + + attachedElement.autoplay = true; + attachedElement.playsInline = true; + attachedElement.controls = false; + + if (isLocal) { + attachedElement.muted = true; + } + + container.innerHTML = ''; + container.appendChild( + attachedElement + ); + + if (emptyMessage) { + emptyMessage.style.display = + 'none'; + } + + const participantName = + participant?.identity + || ( + isLocal + ? 'You' + : 'Unknown participant' + ); + + Kronick.screenShare + .activeVideoTrack = track; + + Kronick.screenShare + .activeParticipantSid = + participant?.sid || null; + + Kronick.screenShare + .activeParticipantName = + participantName; + + if (title) { + title.textContent = + isLocal + ? 'Your Screen' + : `${participantName}'s Screen`; + } + + Kronick.openScreenShareWindow(); +}; + + +/* + * Attach screen-share audio separately. + */ +Kronick.showScreenShareAudio = +function showScreenShareAudio(track) { + if (!track) { + return; + } + + Kronick.detachCurrentScreenShareAudio(); + + const audioElement = + track.attach(); + + audioElement.autoplay = true; + audioElement.controls = false; + + audioElement.classList.add( + 'screen-share-audio' + ); + + document.body.appendChild( + audioElement + ); + + Kronick.screenShare + .activeAudioTrack = track; +}; + + +/* + * Remove a specific video track. + */ +Kronick.removeScreenShareVideo = +function removeScreenShareVideo(track) { + if ( + track + && Kronick.screenShare + .activeVideoTrack + && track + !== Kronick.screenShare + .activeVideoTrack + ) { + return; + } + + Kronick.detachCurrentScreenShareVideo(); + + const container = + document.getElementById( + 'screenShareVideoContainer' + ); + + const emptyMessage = + document.getElementById( + 'screenShareEmpty' + ); + + const title = + document.getElementById( + 'screenShareTitle' + ); + + if (container) { + container.innerHTML = ''; + } + + if (emptyMessage) { + emptyMessage.style.display = + 'flex'; + } + + if (title) { + title.textContent = + '🖥️ Screen Share 🖥️'; + } + + Kronick.screenShare + .activeParticipantSid = null; + + Kronick.screenShare + .activeParticipantName = ''; +}; + + +/* + * Remove a specific audio track. + */ +Kronick.removeScreenShareAudio = +function removeScreenShareAudio(track) { + if ( + track + && Kronick.screenShare + .activeAudioTrack + && track + !== Kronick.screenShare + .activeAudioTrack + ) { + return; + } + + Kronick.detachCurrentScreenShareAudio(); +}; + + +/* + * Detach the active screen-share video element. + */ +Kronick.detachCurrentScreenShareVideo = +function detachCurrentScreenShareVideo() { + const track = + Kronick.screenShare + .activeVideoTrack; + + if (track) { + try { + track.detach().forEach( + element => { + element.remove(); + } + ); + } catch (err) { + console.debug( + 'Could not detach ' + + 'screen-share video:', + err + ); + } + } + + Kronick.screenShare + .activeVideoTrack = null; +}; + + +/* + * Detach the active screen-share audio element. + */ +Kronick.detachCurrentScreenShareAudio = +function detachCurrentScreenShareAudio() { + const track = + Kronick.screenShare + .activeAudioTrack; + + if (track) { + try { + track.detach().forEach( + element => { + element.remove(); + } + ); + } catch (err) { + console.debug( + 'Could not detach ' + + 'screen-share audio:', + err + ); + } + } + + document + .querySelectorAll( + '.screen-share-audio' + ) + .forEach(element => { + element.remove(); + }); + + Kronick.screenShare + .activeAudioTrack = null; +}; + + +/* + * Remove only the local preview after stopping sharing. + */ +Kronick.removeLocalScreenShare = +function removeLocalScreenShare() { + const room = + Kronick.state.room; + + const activeSid = + Kronick.screenShare + .activeParticipantSid; + + if ( + room?.localParticipant + && activeSid + === room.localParticipant.sid + ) { + Kronick.removeScreenShareVideo(); + Kronick.removeScreenShareAudio(); + } +}; + + +/* + * Show the popup window. + */ +Kronick.openScreenShareWindow = +function openScreenShareWindow() { + Kronick.showToolWindow( + 'screenShareFrameWrap' + ); +}; + + +/* + * Hide the popup without stopping someone else's share. + * + * If the local user is sharing, this only hides the + * preview. The Stop Sharing button actually stops it. + */ +Kronick.closeScreenShareWindow = +function closeScreenShareWindow() { + Kronick.hideToolWindow( + 'screenShareFrameWrap' + ); +}; + + +/* + * Update buttons and status text. + */ +Kronick.updateScreenShareControls = +function updateScreenShareControls() { + const shareButton = + document.getElementById( + 'screenShareBtn' + ); + + const stopButton = + document.getElementById( + 'screenShareStopBtn' + ); + + const room = + Kronick.state.room; + + const isSharing = + Kronick.screenShare + .isLocalSharing + || Kronick + .localParticipantIsScreenSharing( + room?.localParticipant + ); + + Kronick.screenShare + .isLocalSharing = + isSharing; + + if (shareButton) { + shareButton.textContent = + isSharing + ? 'Stop Sharing' + : '🖥️🖥️'; + + shareButton.classList.toggle( + 'active', + isSharing + ); + + shareButton.disabled = + !room?.localParticipant; + } + + if (stopButton) { + stopButton.hidden = + !isSharing; + } +}; + + +/* + * Reset everything when leaving the room. + */ +Kronick.resetScreenShare = +function resetScreenShare() { + Kronick.detachCurrentScreenShareVideo(); + Kronick.detachCurrentScreenShareAudio(); + + Kronick.screenShare.room = null; + + Kronick.screenShare + .isLocalSharing = false; + + Kronick.screenShare + .activeParticipantSid = null; + + Kronick.screenShare + .activeParticipantName = ''; + + const container = + document.getElementById( + 'screenShareVideoContainer' + ); + + const emptyMessage = + document.getElementById( + 'screenShareEmpty' + ); + + const title = + document.getElementById( + 'screenShareTitle' + ); + + if (container) { + container.innerHTML = ''; + } + + if (emptyMessage) { + emptyMessage.style.display = + 'flex'; + } + + if (title) { + title.textContent = + '🖥️ Screen Share 🖥️'; + } + + Kronick.closeScreenShareWindow(); + Kronick.updateScreenShareControls(); +}; diff --git a/kronic-chat/js/storage.js b/kronic-chat/js/storage.js new file mode 100644 index 0000000..75bb538 --- /dev/null +++ b/kronic-chat/js/storage.js @@ -0,0 +1,219 @@ +window.Kronick = window.Kronick || {}; + +Kronick.saveJoinInfo = function saveJoinInfo( + roomName, + userName, + avatarUrl +) { + localStorage.setItem( + 'lastRoomName', + roomName + ); + + localStorage.setItem( + 'lastUserName', + userName + ); + + localStorage.setItem( + 'lastAvatarUrl', + avatarUrl + ); + + Kronick.addToSavedList( + 'savedRoomList', + roomName + ); + + Kronick.addToSavedList( + 'savedNameList', + userName + ); + + if (avatarUrl) { + Kronick.addToSavedList( + 'savedAvatarList', + avatarUrl + ); + } + + Kronick.populateSavedLists(); +}; + +Kronick.loadSavedJoinInfo = +function loadSavedJoinInfo() { + const roomInput = + document.getElementById('roomName'); + + const userInput = + document.getElementById('userName'); + + const avatarInput = + document.getElementById('avatarUrl'); + + if (roomInput) { + roomInput.value = + localStorage.getItem( + 'lastRoomName' + ) || ''; + } + + if (userInput) { + userInput.value = + localStorage.getItem( + 'lastUserName' + ) || ''; + } + + if (avatarInput) { + avatarInput.value = + localStorage.getItem( + 'lastAvatarUrl' + ) || ''; + } +}; + +Kronick.addToSavedList = +function addToSavedList(key, value) { + if (!value) { + return; + } + + let list = []; + + try { + list = JSON.parse( + localStorage.getItem(key) + ) || []; + } catch { + list = []; + } + + list = list.filter( + item => item !== value + ); + + list.unshift(value); + list = list.slice(0, 10); + + localStorage.setItem( + key, + JSON.stringify(list) + ); +}; + +Kronick.populateSavedLists = +function populateSavedLists() { + Kronick.populateDatalist( + 'savedRooms', + 'savedRoomList' + ); + + Kronick.populateDatalist( + 'savedNames', + 'savedNameList' + ); + + Kronick.populateDatalist( + 'savedAvatars', + 'savedAvatarList' + ); +}; + +Kronick.populateDatalist = +function populateDatalist( + datalistId, + storageKey +) { + const datalist = + document.getElementById( + datalistId + ); + + if (!datalist) { + return; + } + + let list = []; + + try { + list = JSON.parse( + localStorage.getItem( + storageKey + ) + ) || []; + } catch { + list = []; + } + + datalist.innerHTML = ''; + + list.forEach(value => { + const option = + document.createElement( + 'option' + ); + + option.value = value; + datalist.appendChild(option); + }); +}; + +Kronick.savePosition = +function savePosition(key, position) { + localStorage.setItem( + `position-${key}`, + JSON.stringify(position) + ); +}; + +Kronick.getSavedPosition = +function getSavedPosition(key) { + const saved = + localStorage.getItem( + `position-${key}` + ); + + if (!saved) { + return null; + } + + try { + const parsed = + JSON.parse(saved); + + if ( + typeof parsed.x !== 'number' + || typeof parsed.y !== 'number' + ) { + return null; + } + + return parsed; + } catch { + return null; + } +}; + +Kronick.getSavedVolume = +function getSavedVolume(participantKey) { + const saved = + localStorage.getItem( + `volume-${participantKey}` + ); + + if (saved === null) { + return 1; + } + + const volume = Number(saved); + + if (Number.isNaN(volume)) { + return 1; + } + + return Math.max( + 0, + Math.min(1, volume) + ); +}; diff --git a/kronic-chat/js/tool-windows.js b/kronic-chat/js/tool-windows.js new file mode 100644 index 0000000..411709f --- /dev/null +++ b/kronic-chat/js/tool-windows.js @@ -0,0 +1,480 @@ +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.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); + }); +}; diff --git a/kronic-chat/js/ui-fixes.js b/kronic-chat/js/ui-fixes.js new file mode 100644 index 0000000..ff56cb5 --- /dev/null +++ b/kronic-chat/js/ui-fixes.js @@ -0,0 +1,175 @@ +// ========================================================= +// Kronic UI fixes - 2026-10-31 +// ========================================================= + +window.Kronick = + window.Kronick || {}; + + +/* + * Flash only the top chat icon when a new chat notification + * arrives while chat is not visibly open. + */ +(function setupChatNotificationFlash() { + const chatButton = + document.getElementById( + 'chatToolButton' + ); + + const chatWrap = + document.getElementById( + 'chatFrameWrap' + ); + + const chatFrame = + document.getElementById( + 'chatFrame' + ); + + if (!chatButton) { + return; + } + + function chatIsVisible() { + if (!chatWrap) { + return false; + } + + const style = + window.getComputedStyle( + chatWrap + ); + + return ( + style.display !== 'none' + && style.visibility !== 'hidden' + && !chatWrap.classList.contains( + 'window-minimized' + ) + ); + } + + function clearChatFlash() { + chatButton.classList.remove( + 'chat-notification-pulse' + ); + } + + function flashChatIcon() { + if ( + !chatIsVisible() + ) { + chatButton.classList.add( + 'chat-notification-pulse' + ); + } + } + + chatButton.addEventListener( + 'click', + clearChatFlash + ); + + window.addEventListener( + 'message', + event => { + if ( + event.origin + !== Kronick.config?.APP_ORIGIN + && event.origin + !== window.location.origin + ) { + return; + } + + if ( + chatFrame?.contentWindow + && event.source + !== chatFrame.contentWindow + ) { + return; + } + + if ( + event.data?.type + === 'KRONICK_CHAT_NEW_MESSAGE' + ) { + flashChatIcon(); + } + } + ); + + /* + * Existing chat-controller code may maintain the unread + * badge. Observe it too, but display only the icon pulse. + */ + const unread = + document.getElementById( + 'chatUnreadCount' + ); + + if (unread) { + const observer = + new MutationObserver( + () => { + const count = + Number( + unread.dataset.count + || unread.textContent + || 0 + ); + + if ( + count > 0 + && !chatIsVisible() + ) { + flashChatIcon(); + } + } + ); + + observer.observe( + unread, + { + attributes: + true, + childList: + true, + characterData: + true, + subtree: + true + } + ); + } + + /* + * If another part of the app opens the chat window, + * clear the pulse as soon as it becomes visible. + */ + if (chatWrap) { + const observer = + new MutationObserver( + () => { + if ( + chatIsVisible() + ) { + clearChatFlash(); + } + } + ); + + observer.observe( + chatWrap, + { + attributes: + true, + attributeFilter: + [ + 'style', + 'class' + ] + } + ); + } +})(); diff --git a/kronic-chat/js/utils.js b/kronic-chat/js/utils.js new file mode 100644 index 0000000..383ddcf --- /dev/null +++ b/kronic-chat/js/utils.js @@ -0,0 +1,55 @@ +window.Kronick = window.Kronick || {}; +Kronick.state = Kronick.state || {}; + +Kronick.createId = function createId() { + if ( + window.crypto + && typeof window.crypto.randomUUID === 'function' + ) { + return window.crypto.randomUUID(); + } + + return [ + Date.now(), + Math.random().toString(36).slice(2) + ].join('-'); +}; + +Kronick.escapeHtml = function escapeHtml(value) { + return String(value) + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); +}; + +Kronick.escapeAttribute = function escapeAttribute(value) { + return Kronick.escapeHtml(value); +}; + +Kronick.setStatus = function setStatus( + message, + state = '' +) { + const statusBar = + document.getElementById('statusBar'); + + const statusIndicator = + document.getElementById('statusIndicator'); + + if (statusBar) { + statusBar.innerText = message; + } + + if (!statusIndicator) { + return; + } + + statusIndicator.className = + 'status-indicator'; + + if (state) { + statusIndicator.classList.add(state); + } +};