Upload files to "kronic-chat/js"

This commit is contained in:
2026-11-25 20:26:42 -06:00
parent 9ad6c44a84
commit e3157104a4
5 changed files with 3530 additions and 0 deletions
+397
View File
@@ -0,0 +1,397 @@
// chat-notifications.js
//
// Reliable parent-level unread notification handling.
// Incoming LiveKit chat is observed directly in the host app instead
// of depending on the chat iframe to echo a notification back.
window.Kronick =
window.Kronick || {};
(() => {
const seenMessageKeys =
new Map();
const MESSAGE_DEDUPE_MS =
15000;
let unreadCount =
0;
function getChatButton() {
return document.getElementById(
'chatToolButton'
);
}
function getUnreadBadge() {
return document.getElementById(
'chatUnreadCount'
);
}
function getChatWindow() {
return document.getElementById(
'chatFrameWrap'
);
}
function getMessageKey(message) {
if (!message) {
return '';
}
if (message.id) {
return String(
message.id
);
}
return [
message.sender || '',
message.createdAt || '',
message.text || '',
message.gifUrl || '',
message.imageUrl || ''
].join('|');
}
function pruneSeenMessages() {
const cutoff =
Date.now()
- MESSAGE_DEDUPE_MS;
for (
const [key, timestamp]
of seenMessageKeys
) {
if (timestamp < cutoff) {
seenMessageKeys.delete(
key
);
}
}
}
function markMessageSeen(message) {
const key =
getMessageKey(
message
);
if (!key) {
return false;
}
pruneSeenMessages();
if (
seenMessageKeys.has(
key
)
) {
return false;
}
seenMessageKeys.set(
key,
Date.now()
);
return true;
}
function chatIsVisible() {
const chatWindow =
getChatWindow();
if (!chatWindow) {
return false;
}
if (
chatWindow.classList.contains(
'window-minimized'
)
) {
return false;
}
const style =
window.getComputedStyle(
chatWindow
);
return (
style.display !== 'none'
&& style.visibility !== 'hidden'
&& style.opacity !== '0'
);
}
function isOwnMessage(message) {
const localIdentity =
Kronick.state
?.room
?.localParticipant
?.identity
|| '';
if (!localIdentity) {
return false;
}
return (
String(
message?.sender
|| ''
)
=== String(
localIdentity
)
);
}
function renderUnreadState() {
const button =
getChatButton();
const badge =
getUnreadBadge();
if (!button || !badge) {
return;
}
const hasUnread =
unreadCount > 0;
button.classList.toggle(
'chat-alert',
hasUnread
);
badge.dataset.count =
String(
unreadCount
);
badge.textContent =
unreadCount > 99
? '99+'
: String(
unreadCount
);
badge.hidden =
!hasUnread;
button.setAttribute(
'aria-label',
hasUnread
? `Open chat, ${unreadCount} unread message${
unreadCount === 1
? ''
: 's'
}`
: 'Open chat'
);
}
function clearUnread() {
unreadCount =
0;
renderUnreadState();
}
function notifyForMessage(
message
) {
if (!message) {
return;
}
if (
isOwnMessage(
message
)
) {
return;
}
if (
!markMessageSeen(
message
)
) {
return;
}
if (
chatIsVisible()
) {
clearUnread();
return;
}
unreadCount +=
1;
renderUnreadState();
}
function installReceiveHook() {
const originalReceive =
Kronick.receiveChatMessage;
if (
typeof originalReceive
!== 'function'
) {
return false;
}
if (
originalReceive
.__kronickUnreadWrapped
) {
return true;
}
const wrappedReceive =
function wrappedReceiveChatMessage(
message
) {
const result =
originalReceive.apply(
this,
arguments
);
notifyForMessage(
message
);
return result;
};
wrappedReceive
.__kronickUnreadWrapped =
true;
Kronick.receiveChatMessage =
wrappedReceive;
return true;
}
function installUiHooks() {
const chatButton =
getChatButton();
const chatWindow =
getChatWindow();
chatButton?.addEventListener(
'click',
() => {
window.setTimeout(
() => {
if (
chatIsVisible()
) {
clearUnread();
}
},
0
);
}
);
if (chatWindow) {
const observer =
new MutationObserver(
() => {
if (
chatIsVisible()
) {
clearUnread();
}
}
);
observer.observe(
chatWindow,
{
attributes:
true,
attributeFilter:
[
'class',
'style',
'hidden'
]
}
);
}
window.addEventListener(
'focus',
() => {
if (
chatIsVisible()
) {
clearUnread();
}
}
);
}
// Keep old iframe notification calls compatible,
// but funnel them through the same deduped handler.
Kronick
.handleIncomingChatNotification =
notifyForMessage;
Kronick
.clearChatNotification =
clearUnread;
function init() {
installReceiveHook();
installUiHooks();
renderUnreadState();
if (
typeof Kronick.receiveChatMessage
!== 'function'
) {
window.setTimeout(
installReceiveHook,
0
);
window.setTimeout(
installReceiveHook,
250
);
}
}
if (
document.readyState
=== 'loading'
) {
document.addEventListener(
'DOMContentLoaded',
init,
{
once:
true
}
);
} else {
init();
}
})();
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
// ---------------------------------------------------------
// Kronic Krusaders browser installation configuration
//
// Generated automatically by setup.sh.
//
// PUBLIC VALUES ONLY.
// Never place passwords, API secrets, session secrets,
// admin credentials, or other private values in this file.
// ---------------------------------------------------------
window.KRONICK_INSTALL_CONFIG = {
PUBLIC_BASE_URL: "https://kronickrusaders.ca",
LIVEKIT_URL: "wss://lvkt.kronickrusaders.ca",
TOKEN_URL: "https://kronickrusaders.ca/get-token"
};
File diff suppressed because it is too large Load Diff
+735
View File
@@ -0,0 +1,735 @@
// message-router.js
window.Kronick =
window.Kronick || {};
/*
* Central message router for the music, Giphy and
* chat iframes.
*/
Kronick.handleWindowMessage =
function handleWindowMessage(event) {
if (
event.origin
!== Kronick.config.APP_ORIGIN
) {
console.warn(
'Rejected cross-origin '
+ 'window message:',
event.origin
);
return;
}
const data =
event.data;
if (
!data
|| typeof data !== 'object'
) {
return;
}
const musicFrame =
document.getElementById(
'musicFrame'
);
const giphyFrame =
document.getElementById(
'giphyFrame'
);
const chatFrame =
document.getElementById(
'chatFrame'
);
const fromMusicFrame =
Boolean(
musicFrame?.contentWindow
&& event.source
=== musicFrame.contentWindow
);
const fromGiphyFrame =
Boolean(
giphyFrame?.contentWindow
&& event.source
=== giphyFrame.contentWindow
);
const fromChatFrame =
Boolean(
chatFrame?.contentWindow
&& event.source
=== chatFrame.contentWindow
);
switch (data.type) {
case 'KRONICK_CHAT_HISTORY_REQUEST':
if (!fromChatFrame) {
return;
}
Kronick.sendChatHistoryToFrame();
return;
case 'KRONICK_CHAT_NEW_MESSAGE':
if (!fromChatFrame) {
return;
}
Kronick
.handleIncomingChatNotification(
data.message
);
return;
case 'KRONICK_MUSIC_CLOSE':
if (!fromMusicFrame) {
return;
}
Kronick.closeMusicBrowser();
return;
case 'KRONICK_GIPHY_CLOSE':
if (!fromGiphyFrame) {
return;
}
Kronick.closeGiphyBrowser();
return;
case 'KRONICK_CHAT_GIF_PICK':
if (!fromChatFrame) {
return;
}
Kronick.openGiphyBrowser(
'chat'
);
return;
case 'KRONICK_GIPHY_SELECTED':
if (
!fromGiphyFrame
) {
console.warn(
'Rejected GIPHY selection: '
+ 'message did not come from '
+ 'the GIPHY frame.'
);
return;
}
{
const gifUrl =
Kronick.getGiphyMessageUrl(
data
);
if (!gifUrl) {
console.warn(
'Rejected GIPHY selection: '
+ 'no usable GIF URL.',
data
);
return;
}
if (
Kronick.state
.giphyTargetMode
=== 'chat'
) {
chatFrame?.contentWindow
?.postMessage(
{
type:
'CHAT_INSERT_AND_SEND_URL',
url:
gifUrl
},
Kronick.config
.APP_ORIGIN
);
Kronick.state
.giphyTargetMode =
'room';
Kronick.closeGiphyBrowser();
return;
}
if (
typeof Kronick.sendMediaToRoom
!== 'function'
) {
console.error(
'Kronick.sendMediaToRoom '
+ 'is not available.'
);
return;
}
Kronick.sendMediaToRoom({
mediaType:
'gif',
url:
gifUrl,
title:
data.title || 'GIF'
});
Kronick.closeGiphyBrowser();
return;
}
case 'KRONICK_GIPHY_AVATAR_SET':
if (!fromGiphyFrame) {
console.warn(
'Rejected GIPHY avatar: '
+ 'message did not come from '
+ 'the GIPHY frame.'
);
return;
}
{
const avatarUrl =
Kronick.getGiphyMessageUrl(
data
);
if (!avatarUrl) {
console.warn(
'Rejected GIPHY avatar: '
+ 'no usable GIF URL.',
data
);
return;
}
console.log(
'GIPHY AVATAR RECEIVED:',
{
url:
avatarUrl,
title:
data.title
|| data.gif?.title
|| ''
}
);
Kronick
.setLocalAvatar(
avatarUrl
)
.catch(
err => {
console.error(
'Could not set '
+ 'GIPHY avatar:',
err
);
}
);
return;
}
case 'KRONICK_MEDIA_SHARE':
if (
!fromMusicFrame
|| typeof data.url
!== 'string'
|| !data.url
) {
console.warn(
'Rejected media share:',
{
fromMusicFrame,
url:
data.url
}
);
return;
}
console.log(
'MEDIA SHARE RECEIVED '
+ 'FROM MUSIC BROWSER:',
{
mediaType:
data.mediaType,
url:
data.url,
title:
data.title,
thumbnail:
data.thumbnail
}
);
/*
* Do NOT close the music browser here.
*
* Keeping it open lets the user continue
* searching, adding tracks to the queue,
* and selecting additional media while the
* shared player is active.
*/
if (
typeof Kronick.sendMediaToRoom
!== 'function'
) {
console.error(
'Kronick.sendMediaToRoom '
+ 'is not available. '
+ 'Check media-controller.js '
+ 'for syntax/load errors.'
);
return;
}
/*
* Send the media selection to LiveKit
* and play it locally.
*/
Kronick.sendMediaToRoom(
data
);
/*
* Bring the shared media window above
* the other floating tool windows.
*/
requestAnimationFrame(
() => {
const sharedMediaWrap =
document.getElementById(
'sharedMediaWrap'
);
if (!sharedMediaWrap) {
console.warn(
'sharedMediaWrap '
+ 'was not found.'
);
return;
}
sharedMediaWrap.style.display =
'flex';
if (
typeof Kronick
.bringToolWindowToFront
=== 'function'
) {
Kronick
.bringToolWindowToFront(
sharedMediaWrap
);
}
if (
typeof Kronick
.keepWindowInViewport
=== 'function'
) {
Kronick
.keepWindowInViewport(
sharedMediaWrap
);
}
}
);
return;
case 'KRONICK_CHAT_SEND':
if (
!fromChatFrame
|| !data.payload
|| typeof data.payload
!== 'object'
) {
return;
}
Kronick.sendChatToRoom(
data.payload
);
return;
default:
console.warn(
'Unhandled window message:',
data.type
);
}
};
/*
* Extract a usable GIF URL from a GIPHY iframe message.
*
* Current giphy.js sends both data.url and data.gif.url.
* Prefer the nested GIF URL first so this remains compatible
* if the outer message structure changes again later.
*/
Kronick.getGiphyMessageUrl =
function getGiphyMessageUrl(data) {
const candidates = [
data?.gif?.url,
data?.url,
data?.gif?.thumb
];
for (
const candidate
of candidates
) {
if (
typeof candidate
!== 'string'
) {
continue;
}
const url =
candidate.trim();
if (!url) {
continue;
}
/*
* The avatar must be an actual image/media URL,
* not a GIPHY landing page.
*/
try {
const parsed =
new URL(
url,
window.location.origin
);
if (
parsed.hostname
=== 'giphy.com'
|| parsed.hostname
=== 'www.giphy.com'
) {
console.warn(
'Ignoring GIPHY page URL '
+ 'instead of media URL:',
url
);
continue;
}
return parsed.href;
} catch (
error
) {
console.warn(
'Ignoring invalid GIPHY URL:',
{
url,
error:
error?.message
|| String(error)
}
);
}
}
return '';
};
/*
* Set the selected Giphy image as the local avatar.
*
* This updates:
* 1. the avatar input
* 2. localStorage
* 3. LiveKit participant metadata
* 4. the local participant tile immediately
*
* The GIPHY browser is only closed after the local update
* has been attempted.
*/
Kronick.setLocalAvatar =
async function setLocalAvatar(url) {
if (
typeof url !== 'string'
|| !url.trim()
) {
throw new Error(
'Avatar URL is empty.'
);
}
const avatarUrl =
url.trim();
/*
* Reject a normal giphy.com landing page. Those URLs
* cannot be used directly as an <img> avatar.
*/
try {
const parsed =
new URL(
avatarUrl,
window.location.origin
);
if (
parsed.hostname
=== 'giphy.com'
|| parsed.hostname
=== 'www.giphy.com'
) {
throw new Error(
'Received a GIPHY page URL '
+ 'instead of an image URL.'
);
}
} catch (
error
) {
console.error(
'Invalid avatar URL:',
{
url:
avatarUrl,
error:
error?.message
|| String(error)
}
);
throw error;
}
const avatarInput =
document.getElementById(
'avatarUrl'
);
if (avatarInput) {
avatarInput.value =
avatarUrl;
/*
* Notify any code listening to the avatar field.
*/
avatarInput.dispatchEvent(
new Event(
'input',
{
bubbles:
true
}
)
);
avatarInput.dispatchEvent(
new Event(
'change',
{
bubbles:
true
}
)
);
}
localStorage.setItem(
'lastAvatarUrl',
avatarUrl
);
const room =
Kronick.state?.room;
const participant =
room?.localParticipant;
if (!participant) {
console.log(
'Avatar saved locally. '
+ 'No active LiveKit participant '
+ 'is connected yet.',
avatarUrl
);
Kronick.closeGiphyBrowser();
return;
}
let metaObj = {};
try {
metaObj =
participant.metadata
? JSON.parse(
participant.metadata
)
: {};
if (
!metaObj
|| typeof metaObj
!== 'object'
|| Array.isArray(
metaObj
)
) {
metaObj = {};
}
} catch (
error
) {
console.warn(
'Could not parse existing '
+ 'participant metadata. '
+ 'Starting with a new object.',
{
metadata:
participant.metadata,
error:
error?.message
|| String(error)
}
);
metaObj = {};
}
metaObj.avatar =
avatarUrl;
const newMetadata =
JSON.stringify(
metaObj
);
console.log(
'UPDATING LOCAL AVATAR METADATA:',
{
identity:
participant.identity,
avatar:
avatarUrl,
metadata:
newMetadata
}
);
/*
* LiveKit publishes the new metadata to the room.
*/
await participant
.setMetadata(
newMetadata
);
console.log(
'LOCAL AVATAR METADATA UPDATED:',
{
identity:
participant.identity,
avatar:
avatarUrl,
metadata:
participant.metadata
}
);
/*
* Do not wait for ParticipantMetadataChanged to redraw
* our own tile. Update it immediately as well.
*/
if (
typeof Kronick
.updateParticipantAvatar
=== 'function'
) {
Kronick.updateParticipantAvatar(
participant
);
} else {
console.warn(
'Kronick.updateParticipantAvatar '
+ 'is not available.'
);
}
Kronick.closeGiphyBrowser();
};