Files
Kronic-Krusaders/kronic-chat/js/giphy.js
T

1179 lines
21 KiB
JavaScript
Raw 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.
// =====================================================
// Kronick GIPHY Browser
// =====================================================
const GIPHY_SEARCH_ENDPOINT =
window.location.pathname.startsWith('/borg-chat/')
? '/borg-chat/api/giphy/search'
: '/api/giphy/search';
const PARENT_ORIGIN =
window.location.origin;
const GIPHY_HISTORY_STORAGE_KEY =
'kronickGiphyHistory';
const MAX_GIPHY_HISTORY_ITEMS = 75;
// =====================================================
// DOM elements
// =====================================================
const searchInput =
document.getElementById(
'giphySearchInput'
);
const searchBtn =
document.getElementById(
'giphySearchBtn'
);
const results =
document.getElementById(
'giphyResults'
);
const statusBox =
document.getElementById(
'giphyStatus'
);
const closeBtn =
document.getElementById(
'giphyCloseBtn'
);
const historyList =
document.getElementById(
'giphyHistoryList'
);
const historyCount =
document.getElementById(
'giphyHistoryCount'
);
const clearHistoryBtn =
document.getElementById(
'clearGiphyHistoryBtn'
);
// =====================================================
// State
// =====================================================
let giphyAbortController = null;
let giphySearchSeq = 0;
let giphyHistory =
loadGiphyHistory();
// =====================================================
// Startup
// =====================================================
init();
function init() {
bindEvents();
renderGiphyHistory();
renderInitialResults();
searchInput?.focus();
console.log(
'Kronick GIPHY browser initialized',
{
origin:
window.location.origin,
parentAvailable:
window.parent !== window
}
);
}
// =====================================================
// Event bindings
// =====================================================
function bindEvents() {
searchBtn?.addEventListener(
'click',
() => {
searchGiphy(false);
}
);
searchInput?.addEventListener(
'keydown',
event => {
if (event.key !== 'Enter') {
return;
}
event.preventDefault();
searchGiphy(false);
}
);
closeBtn?.addEventListener(
'click',
() => {
postToParent({
type:
'KRONICK_GIPHY_CLOSE'
});
}
);
clearHistoryBtn?.addEventListener(
'click',
clearGiphyHistory
);
}
// =====================================================
// GIPHY search
// =====================================================
async function searchGiphy(
refresh = false
) {
const query =
searchInput?.value
.trim()
|| '';
if (!query) {
setStatus(
'Type something to search.'
);
renderEmptyResults(
'Enter a search above to browse results.'
);
searchInput?.focus();
return;
}
if (giphyAbortController) {
giphyAbortController.abort();
}
giphyAbortController =
new AbortController();
const requestSequence =
++giphySearchSeq;
setStatus('Searching...');
if (results) {
results.innerHTML = '';
}
if (searchBtn) {
searchBtn.disabled = true;
searchBtn.textContent =
'Searching...';
}
try {
const url =
GIPHY_SEARCH_ENDPOINT
+ '?q='
+ encodeURIComponent(query)
+ '&refresh='
+ String(refresh);
const response =
await fetch(
url,
{
signal:
giphyAbortController
.signal
}
);
if (!response.ok) {
let detail = '';
try {
const responseText =
await response.text();
if (responseText) {
detail =
': '
+ responseText;
}
} catch {
// Ignore unreadable response bodies.
}
throw new Error(
'GIPHY search returned '
+ response.status
+ detail
);
}
const data =
await response.json();
/*
* Ignore an older response if a newer
* search has already started.
*/
if (
requestSequence
!== giphySearchSeq
) {
return;
}
// Embedded Chat backend returns { items: [...] }.
// Keep compatibility with the original GIPHY { data: [...] } shape.
const gifs =
Array.isArray(data?.items)
? data.items
: Array.isArray(data?.data)
? data.data
: [];
if (results) {
results.innerHTML = '';
}
if (!gifs.length) {
setStatus(
'No GIFs found.'
);
renderEmptyResults(
'Try a different search.'
);
return;
}
setStatus(
`${gifs.length} GIFs found`
);
const fragment =
document.createDocumentFragment();
gifs.forEach(gif => {
fragment.appendChild(
createGifResultCard(gif)
);
});
results?.appendChild(
fragment
);
} catch (error) {
if (
error?.name
=== 'AbortError'
) {
return;
}
console.error(
'GIPHY SEARCH ERROR:',
error
);
setStatus(
'GIPHY search failed.'
);
renderEmptyResults(
'The GIF service could not complete the search.'
);
} finally {
if (
requestSequence
=== giphySearchSeq
) {
if (searchBtn) {
searchBtn.disabled = false;
searchBtn.textContent =
'Search';
}
}
}
}
// =====================================================
// Result cards
// =====================================================
function createGifResultCard(gif) {
const normalizedGif =
normalizeGif(gif);
const itemWrap =
document.createElement(
'article'
);
itemWrap.className =
'gif-item-wrap';
itemWrap.dataset.gifId =
normalizedGif.id;
const imageButton =
document.createElement(
'button'
);
imageButton.type =
'button';
imageButton.className =
'giphy-image-button';
imageButton.title =
'Send GIF';
imageButton.setAttribute(
'aria-label',
'Send '
+ normalizedGif.title
);
const image =
document.createElement(
'img'
);
image.src =
normalizedGif.thumb
|| normalizedGif.url;
image.alt =
normalizedGif.title
|| 'GIPHY result';
image.title =
normalizedGif.title
|| 'GIPHY result';
image.className =
'giphy-result';
image.loading =
'lazy';
image.addEventListener(
'error',
() => {
image.style.visibility =
'hidden';
itemWrap.classList.add(
'gif-load-error'
);
}
);
imageButton.appendChild(
image
);
imageButton.addEventListener(
'click',
() => {
sendGif(
normalizedGif
);
}
);
const title =
document.createElement(
'div'
);
title.className =
'giphy-result-title';
title.textContent =
normalizedGif.title
|| 'GIPHY';
const actions =
document.createElement(
'div'
);
actions.className =
'giphy-result-actions';
const sendButton =
createActionButton(
'Send',
'send-gif-btn',
() => {
sendGif(
normalizedGif
);
}
);
const avatarButton =
createActionButton(
'Set Avatar',
'set-avatar-btn',
() => {
setGifAsAvatar(
normalizedGif
);
}
);
actions.append(
sendButton,
avatarButton
);
itemWrap.append(
imageButton,
title,
actions
);
return itemWrap;
}
function createActionButton(
text,
className,
handler
) {
const button =
document.createElement(
'button'
);
button.type =
'button';
button.className =
'giphy-action-button '
+ className;
button.textContent =
text;
button.addEventListener(
'click',
event => {
event.stopPropagation();
handler();
}
);
return button;
}
// =====================================================
// Sending GIFs
// =====================================================
function sendGif(gif) {
const normalizedGif =
normalizeGif(gif);
if (!normalizedGif.url) {
setStatus(
'GIF has no usable URL.'
);
return;
}
const message = {
type:
'KRONICK_GIPHY_SELECTED',
url:
normalizedGif.url,
title:
normalizedGif.title
|| 'GIPHY',
gif: {
id:
normalizedGif.id,
title:
normalizedGif.title,
url:
normalizedGif.url,
thumb:
normalizedGif.thumb
}
};
console.log(
'Sending selected GIF to parent:',
message
);
const sent =
postToParent(message);
if (!sent) {
setStatus(
'Could not send GIF. Open this from the main window.'
);
return;
}
addGifToHistory(
normalizedGif,
'sent'
);
setStatus(
'GIF selected.'
);
// Auto-dismiss floating frame/modal in the host application
postToParent({
type:
'KRONICK_GIPHY_CLOSE'
});
}
/*
* Compatibility alias for older code that may
* still call sendGifToChatRoom().
*/
function sendGifToChatRoom(gif) {
sendGif(gif);
}
// =====================================================
// Avatar selection
// =====================================================
function setGifAsAvatar(gif) {
const normalizedGif =
normalizeGif(gif);
if (!normalizedGif.url) {
setStatus(
'GIF has no usable URL.'
);
return;
}
const message = {
type:
'KRONICK_GIPHY_AVATAR_SET',
url:
normalizedGif.url,
title:
normalizedGif.title
|| 'GIPHY',
gif: {
id:
normalizedGif.id,
title:
normalizedGif.title,
url:
normalizedGif.url,
thumb:
normalizedGif.thumb
}
};
console.log(
'Sending avatar GIF to parent:',
message
);
const sent =
postToParent(message);
if (!sent) {
setStatus(
'Could not set avatar from a standalone window.'
);
return;
}
addGifToHistory(
normalizedGif,
'avatar'
);
setStatus(
'Avatar updated!'
);
// Auto-dismiss floating frame/modal in the host application
postToParent({
type:
'KRONICK_GIPHY_CLOSE'
});
}
// =====================================================
// Parent communication
// =====================================================
function postToParent(message) {
if (
!window.parent
|| window.parent === window
) {
console.warn(
'Cannot post GIPHY message: no parent window.',
message
);
return false;
}
try {
window.parent.postMessage(
message,
PARENT_ORIGIN
);
return true;
} catch (error) {
console.error(
'Failed to post GIPHY message:',
error
);
return false;
}
}
// =====================================================
// GIF normalization
// =====================================================
function normalizeGif(gif) {
const rawId =
gif?.id
|| gif?.url
|| gif?.images?.original?.url
|| '';
const fullUrl =
gif?.url
|| gif?.images?.original?.url
|| gif?.images?.downsized?.url
|| '';
const thumbnailUrl =
gif?.thumb
|| gif?.thumbnail
|| gif?.images?.fixed_width_small?.url
|| gif?.images?.fixed_width?.url
|| fullUrl;
return {
id:
String(
rawId
|| crypto.randomUUID()
),
title:
String(
gif?.title
|| 'GIPHY'
),
url:
String(
fullUrl
|| ''
),
thumb:
String(
thumbnailUrl
|| ''
)
};
}
// =====================================================
// History storage
// =====================================================
function loadGiphyHistory() {
try {
const storedValue =
localStorage.getItem(
GIPHY_HISTORY_STORAGE_KEY
);
if (!storedValue) {
return [];
}
const parsed =
JSON.parse(
storedValue
);
return Array.isArray(parsed)
? parsed
: [];
} catch (error) {
console.warn(
'Could not load GIPHY history:',
error
);
return [];
}
}
function saveGiphyHistory() {
try {
localStorage.setItem(
GIPHY_HISTORY_STORAGE_KEY,
JSON.stringify(
giphyHistory
)
);
} catch (error) {
console.warn(
'Could not save GIPHY history:',
error
);
}
}
function addGifToHistory(
gif,
action
) {
const normalizedGif =
normalizeGif(gif);
/*
* Remove an older occurrence of the same GIF,
* then place the newest use at the top.
*/
giphyHistory =
giphyHistory.filter(
item =>
item.url
!== normalizedGif.url
);
giphyHistory.unshift({
historyId:
crypto.randomUUID(),
...normalizedGif,
action:
action === 'avatar'
? 'avatar'
: 'sent',
usedAt:
Date.now()
});
giphyHistory =
giphyHistory.slice(
0,
MAX_GIPHY_HISTORY_ITEMS
);
saveGiphyHistory();
renderGiphyHistory();
}
function clearGiphyHistory() {
giphyHistory = [];
saveGiphyHistory();
renderGiphyHistory();
setStatus(
'GIF history cleared.'
);
}
function removeGiphyHistoryItem(
historyId
) {
giphyHistory =
giphyHistory.filter(
item =>
item.historyId
!== historyId
);
saveGiphyHistory();
renderGiphyHistory();
}
// =====================================================
// History rendering
// =====================================================
function renderGiphyHistory() {
if (!historyList) {
return;
}
historyList.innerHTML = '';
if (historyCount) {
historyCount.textContent =
String(
giphyHistory.length
);
}
if (!giphyHistory.length) {
historyList.innerHTML = `
<div class="giphy-history-empty">
GIFs you send or use as avatars
will appear here.
</div>
`;
return;
}
const fragment =
document.createDocumentFragment();
giphyHistory.forEach(item => {
fragment.appendChild(
createHistoryCard(item)
);
});
historyList.appendChild(
fragment
);
}
function createHistoryCard(item) {
const normalizedGif =
normalizeGif(item);
const card =
document.createElement(
'article'
);
card.className =
'giphy-history-item';
const image =
document.createElement(
'img'
);
image.className =
'giphy-history-image';
image.src =
normalizedGif.thumb
|| normalizedGif.url;
image.alt =
normalizedGif.title
|| 'GIF history';
image.title =
'Send again';
image.loading =
'lazy';
image.addEventListener(
'error',
() => {
image.style.visibility =
'hidden';
}
);
image.addEventListener(
'click',
() => {
sendGif(item);
}
);
const info =
document.createElement(
'div'
);
info.className =
'giphy-history-info';
const title =
document.createElement(
'div'
);
title.className =
'giphy-history-item-title';
title.textContent =
normalizedGif.title
|| 'GIPHY';
const meta =
document.createElement(
'div'
);
meta.className =
'giphy-history-meta';
meta.textContent =
item.action === 'avatar'
? 'Used as avatar'
: 'Sent';
info.append(
title,
meta
);
const actions =
document.createElement(
'div'
);
actions.className =
'giphy-history-actions';
actions.append(
createHistoryButton(
'▶',
'Send again',
() => {
sendGif(item);
}
),
createHistoryButton(
'A',
'Set as avatar',
() => {
setGifAsAvatar(item);
}
),
createHistoryButton(
'×',
'Remove from history',
() => {
removeGiphyHistoryItem(
item.historyId
);
}
)
);
card.append(
image,
info,
actions
);
return card;
}
function createHistoryButton(
text,
title,
handler
) {
const button =
document.createElement(
'button'
);
button.type =
'button';
button.className =
'giphy-history-action';
button.textContent =
text;
button.title =
title;
button.setAttribute(
'aria-label',
title
);
button.addEventListener(
'click',
event => {
event.stopPropagation();
handler();
}
);
return button;
}
// =====================================================
// Empty states and status
// =====================================================
function renderInitialResults() {
if (
!results
|| results.children.length
) {
return;
}
renderEmptyResults(
'Enter a search above to browse results.'
);
}
function renderEmptyResults(message) {
if (!results) {
return;
}
results.innerHTML = `
<div class="giphy-empty">
<div class="giphy-empty-icon">
GIF
</div>
<div class="giphy-empty-title">
No GIFs loaded
</div>
<div class="giphy-empty-text">
${escapeHtml(message)}
</div>
</div>
`;
}
function setStatus(text) {
if (!statusBox) {
return;
}
statusBox.textContent =
text || '';
}
// =====================================================
// Escaping
// =====================================================
function escapeHtml(value) {
return String(value || '')
.replaceAll(
'&',
'&amp;'
)
.replaceAll(
'<',
'&lt;'
)
.replaceAll(
'>',
'&gt;'
)
.replaceAll(
'"',
'&quot;'
)
.replaceAll(
"'",
'&#039;'
);
}