← Files Sulekha EventsARCHIVED FILE
source/public/events-widget.js
9.31 KB · Nov 30, 2026 · 07:53 UTC
const grid = document.querySelector("#grid");
const empty = document.querySelector("#empty");
const searchNote = document.querySelector("#search-note");
const relatedSection = document.querySelector("#related-section");
const relatedGrid = document.querySelector("#related-grid");
const venueSection = document.querySelector("#venue-section");
const venueGrid = document.querySelector("#venue-grid");
const profileLabels = { artist: "Artist", tour: "Tour", venue: "Venue" };
const count = document.querySelector("#count");
let rpcId = 0;
const pendingRequests = new Map();
const linkModal = document.querySelector("#link-modal");
const eventUrl = document.querySelector("#event-url");
const modalStatus = document.querySelector("#modal-status");
let selectedEventUrl = "";
function showLinkModal(event) {
try {
const url = new URL(event.url);
selectedEventUrl = ["https:", "http:"].includes(url.protocol) ? url.href : "";
} catch { selectedEventUrl = ""; }
document.querySelector("#modal-title").textContent = event.kind ? `${profileLabels[event.kind] || "Profile"} link` : "Event link";
document.querySelector("#open-link").textContent = event.kind ? "Open page" : "Open event";
eventUrl.value = selectedEventUrl || "Event link unavailable";
modalStatus.textContent = selectedEventUrl ? "Share this page with anyone." : "This event does not have a public link.";
linkModal.showModal();
}
document.querySelector(".modal-close")?.addEventListener("click", () => linkModal?.close());
linkModal?.addEventListener("click", (event) => { if (event.target === linkModal) linkModal.close(); });
document.querySelector("#copy-link")?.addEventListener("click", async () => {
if (!selectedEventUrl) return;
try { await navigator.clipboard.writeText(selectedEventUrl); modalStatus.textContent = "Link copied."; }
catch { eventUrl.select(); modalStatus.textContent = "Select and copy the link above."; }
});
document.querySelector("#share-link")?.addEventListener("click", async () => {
if (!selectedEventUrl) return;
try {
if (navigator.share) await navigator.share({ title: "Sulekha event", url: selectedEventUrl });
else { await navigator.clipboard.writeText(selectedEventUrl); modalStatus.textContent = "Link copied."; }
} catch (error) {
if (error.name !== "AbortError") { eventUrl.select(); modalStatus.textContent = "Select and copy the link above."; }
}
});
document.querySelector("#open-link")?.addEventListener("click", () => { if (selectedEventUrl) openExternalLink(selectedEventUrl).catch(() => { modalStatus.textContent = "Could not open the event link."; }); });
const rpcNotify = (method, params) => window.parent.postMessage({ jsonrpc: "2.0", method, params }, "*");
const rpcRequest = (method, params) => {
return new Promise((resolve, reject) => {
const id = ++rpcId;
const timeout = setTimeout(() => {
pendingRequests.delete(id);
reject(new Error("The app did not respond. Please try again."));
}, 15000);
pendingRequests.set(id, {
resolve: (result) => { clearTimeout(timeout); resolve(result); },
reject: (error) => { clearTimeout(timeout); reject(error); }
});
window.parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*");
});
};
async function openExternalLink(url) {
if (window.openai?.openExternal) {
await window.openai.openExternal({ href: url });
return;
}
const result = await rpcRequest("ui/open-link", { url });
if (result?.isError) throw new Error("The host could not open the event link.");
}
function text(tag, className, value) {
const element = document.createElement(tag);
if (className) element.className = className;
element.textContent = value;
return element;
}
function eventImage(event, index) {
const frame = document.createElement("div");
frame.className = "event-image";
const fallback = document.querySelector("#default-artwork").content.cloneNode(true);
frame.append(fallback);
if (event.imageUrl) {
const image = document.createElement("img");
image.src = event.imageUrl;
image.alt = event.title || "Event poster";
image.loading = index < 2 ? "eager" : "lazy";
image.decoding = "async";
image.onerror = () => image.remove();
frame.append(image);
}
return frame;
}
let lastRenderKey;
function render(payload) {
if (!payload) {
if (lastRenderKey !== undefined) return;
resetDetailLayout();
empty.className = "loading";
empty.textContent = "Loading events…";
empty.hidden = false;
count.textContent = "";
grid.hidden = true;
grid.replaceChildren();
return;
}
const data = payload?.structuredContent ?? payload ?? {};
const items = Array.isArray(data.events) ? data.events : [];
const related = Array.isArray(data.related) ? data.related : [];
const renderKey = JSON.stringify({ events: items, related, isError: Boolean(payload.isError), message: data.message, locationFallback: data.locationFallback });
if (renderKey === lastRenderKey) return;
lastRenderKey = renderKey;
grid.className = "event-carousel";
grid.setAttribute("aria-label", "Events — scroll to browse");
grid.tabIndex = 0;
empty.className = "";
grid.hidden = items.length === 0;
searchNote.hidden = !data.locationFallback || items.length === 0;
searchNote.textContent = data.locationFallback ? data.message : "";
empty.textContent = payload.isError ? "Event search is temporarily unavailable. Please try again." : (data.message || "No matching events found.");
empty.hidden = items.length > 0;
count.textContent = items.length ? `${items.length} event${items.length === 1 ? "" : "s"}` : "";
grid.replaceChildren(...items.map((event, index) => resultCard(event, index)));
const profiles = related.filter(item => item.kind === "artist" || item.kind === "tour");
const venues = related.filter(item => item.kind === "venue");
relatedSection.hidden = profiles.length === 0;
relatedGrid.replaceChildren(...profiles.map((item, index) => resultCard(item, index, true)));
venueSection.hidden = venues.length === 0;
venueGrid.replaceChildren(...venues.map((item, index) => resultCard(item, index, true)));
}
function resultCard(event, index, isRelated = false) {
const article = document.createElement("article");
article.className = "event-card";
article.append(eventImage(event, index));
const content = document.createElement("div");
content.className = "content";
content.append(
text("div", "status", isRelated ? (profileLabels[event.kind] || "Profile") : event.soldOut === true ? "Sold out" : event.status || "Event"),
text("h2", "", event.title),
...(isRelated
? [text("div", "meta", Number.isInteger(event.eventCount)
? `${event.eventCount} listed event${event.eventCount === 1 ? "" : "s"}` : event.kind === "venue" ? "Explore venue events" : "Explore performances")]
: [text("div", "meta", [event.city, event.region].filter(Boolean).join(", ")),
text("div", "meta", event.dateTime || "Date to be announced"),
...(event.organizer && event.organizer.trim().toLowerCase() !== "hostedby"
? [text("div", "meta", `Organized by ${event.organizer}`)] : [])])
);
const footer = document.createElement("div");
footer.className = "footer";
if (!isRelated) {
const price = event.price;
if (price) footer.append(text("div", "price", price));
}
const links = text("button", "primary", isRelated ? `View ${profileLabels[event.kind] || "Profile"}` : "View Event");
links.type = "button";
links.onclick = () => showLinkModal(event);
footer.append(links);
content.append(footer);
article.append(content);
return article;
}
function resetDetailLayout() {
grid.className = "";
grid.removeAttribute("tabindex");
grid.setAttribute("aria-label", "Event details");
grid.scrollLeft = 0;
}
window.addEventListener("message", (event) => {
if (event.source !== window.parent) return;
const message = event.data;
if (message?.jsonrpc !== "2.0") return;
if (message.method && message.id !== undefined) {
const supported = message.method === "ping" || message.method === "ui/resource-teardown";
window.parent.postMessage({ jsonrpc: "2.0", id: message.id,
...(supported ? { result: {} } : { error: { code: -32601, message: "Method not found" } }) }, "*");
return;
}
if (message.id !== undefined) {
const pending = pendingRequests.get(message.id);
if (!pending) return;
pendingRequests.delete(message.id);
if (message.error) pending.reject(message.error);
else pending.resolve(message.result);
return;
}
if (message.method === "ui/notifications/tool-result") render(message.params);
}, { passive: true });
async function initializeBridge() {
await rpcRequest("ui/initialize", {
appInfo: { name: "sulekha-events-widget", version: "0.4.6" },
appCapabilities: {},
protocolVersion: "2026-01-26"
});
rpcNotify("ui/notifications/initialized", {});
const reportSize = () => rpcNotify("ui/notifications/size-changed", { height: Math.ceil(document.querySelector("main").getBoundingClientRect().height) });
new ResizeObserver(reportSize).observe(document.querySelector("main"));
reportSize();
}
window.addEventListener("openai:set_globals", (event) => {
const output = event.detail?.globals?.toolOutput;
if (output) render(output);
});
render(window.openai?.toolOutput);
initializeBridge().catch((error) => console.error("Failed to initialize MCP Apps bridge", error));
SHA-256: a277900838f229ab337669b072c0023b87a456e02f50e99bd5481da78305b097