From 8daae764bf53b6f1c94b24aae2e50bdbbddfb6fe Mon Sep 17 00:00:00 2001 From: Jeffrey Alan Scudder Date: Sun, 4 Jan 2026 20:26:10 +0000 Subject: [PATCH] give: simplify slideshow - remove slow pixel effects, keep crispy fading --- system/backend/cache.mjs | 127 +++++++ system/netlify/functions/chat-messages.mjs | 124 ++++--- system/netlify/functions/kidlisp-count.mjs | 22 +- system/netlify/functions/metrics.mjs | 190 ++++++----- system/netlify/functions/tv.mjs | 31 +- .../public/give.aesthetic.computer/index.html | 318 +++++++++++++----- 6 files changed, 575 insertions(+), 237 deletions(-) create mode 100644 system/backend/cache.mjs diff --git a/system/backend/cache.mjs b/system/backend/cache.mjs new file mode 100644 index 0000000000..4011240ef5 --- /dev/null +++ b/system/backend/cache.mjs @@ -0,0 +1,127 @@ +// Cache, 2026.01.04 +// Redis-backed caching for expensive database operations. +// Uses TTL-based expiration to reduce load on MongoDB. + +import { createClient } from "redis"; + +const redisConnectionString = process.env.REDIS_CONNECTION_STRING; +const dev = process.env.NETLIFY_DEV; + +let client; + +async function connect() { + if (client && client.isOpen) { + return client; + } + client = !dev ? createClient({ url: redisConnectionString }) : createClient(); + client.on("error", (err) => console.log("🔴 Cache Redis error:", err)); + await client.connect(); + return client; +} + +async function disconnect() { + if (!client?.isOpen) return; + await client.quit(); +} + +/** + * Get a cached value, or compute and cache it if missing/expired. + * + * @param {string} key - Cache key (e.g., "metrics:handles") + * @param {function} computeFn - Async function to compute value if cache miss + * @param {number} ttlSeconds - Time to live in seconds (default: 30 minutes) + * @returns {Promise} - The cached or computed value + */ +async function getOrCompute(key, computeFn, ttlSeconds = 1800) { + try { + await connect(); + + // Try to get from cache + const cached = await client.get(key); + if (cached) { + console.log(`📦 Cache HIT: ${key}`); + return JSON.parse(cached); + } + + console.log(`📭 Cache MISS: ${key}`); + + // Compute the value + const value = await computeFn(); + + // Store in cache with TTL + await client.setEx(key, ttlSeconds, JSON.stringify(value)); + + return value; + } catch (err) { + console.error(`⚠️ Cache error for ${key}:`, err.message); + // On cache error, just compute without caching + return await computeFn(); + } +} + +/** + * Invalidate a cache key or pattern. + * + * @param {string} key - Exact key or pattern with * wildcard + */ +async function invalidate(key) { + try { + await connect(); + + if (key.includes('*')) { + // Pattern-based deletion + const keys = await client.keys(key); + if (keys.length > 0) { + await client.del(keys); + console.log(`🗑️ Cache invalidated ${keys.length} keys matching: ${key}`); + } + } else { + await client.del(key); + console.log(`🗑️ Cache invalidated: ${key}`); + } + } catch (err) { + console.error(`⚠️ Cache invalidate error:`, err.message); + } +} + +/** + * Get cache stats for debugging. + */ +async function stats() { + try { + await connect(); + const info = await client.info('memory'); + const keys = await client.dbSize(); + return { keys, memoryInfo: info }; + } catch (err) { + return { error: err.message }; + } +} + +// Pre-defined cache keys and TTLs +const CACHE_KEYS = { + METRICS: 'give:metrics', // 30 min - platform stats + KIDLISP_COUNT: 'give:kidlisp', // 30 min - kidlisp program count + TV_RECENT: 'give:tv:recent', // 5 min - recent tapes + CHAT_CLOCK: 'give:chat:clock', // 2 min - clock chat messages + CHAT_SYSTEM: 'give:chat:system', // 2 min - system chat messages + SHOP: 'give:shop', // 10 min - shop items +}; + +const CACHE_TTLS = { + METRICS: 30 * 60, // 30 minutes + KIDLISP_COUNT: 30 * 60, // 30 minutes + TV_RECENT: 5 * 60, // 5 minutes + CHAT: 2 * 60, // 2 minutes + SHOP: 10 * 60, // 10 minutes +}; + +export { + connect, + disconnect, + getOrCompute, + invalidate, + stats, + CACHE_KEYS, + CACHE_TTLS +}; diff --git a/system/netlify/functions/chat-messages.mjs b/system/netlify/functions/chat-messages.mjs index 13bba077a3..6aa072b928 100644 --- a/system/netlify/functions/chat-messages.mjs +++ b/system/netlify/functions/chat-messages.mjs @@ -1,6 +1,7 @@ // chat-messages, 25.11.21.18.30 // GET: Returns recent chat messages from a specific chat instance. // Examples: "clock" for Laer-Klokken, "system" for main chat +// Now with Redis caching (2 min TTL). /* #region 🏁 TODO - [] Add pagination support @@ -10,6 +11,7 @@ import { connect } from "../../backend/database.mjs"; import { respond } from "../../backend/http.mjs"; import { shell } from "../../backend/shell.mjs"; +import { getOrCompute, CACHE_TTLS } from "../../backend/cache.mjs"; export async function handler(event, context) { if (event.httpMethod === "OPTIONS") { @@ -29,73 +31,83 @@ export async function handler(event, context) { return respond(400, { message: "Limit cannot exceed 100" }); } - shell.log(`📨 Fetching ${limit} messages for chat instance: ${instance}`); + // Cache key includes instance and limit + const cacheKey = `give:chat:${instance}:${limit}`; - const database = await connect(); - - // Use different collections based on instance - const collectionName = instance === "clock" ? "chat-clock" : "chat-system"; - const collection = database.db.collection(collectionName); - - shell.log(`📂 Using collection: ${collectionName} for instance: ${instance}`); + const result = await getOrCompute( + cacheKey, + async () => { + shell.log(`📨 Fetching ${limit} messages for chat instance: ${instance}`); + + const database = await connect(); + + // Use different collections based on instance + const collectionName = instance === "clock" ? "chat-clock" : "chat-system"; + const collection = database.db.collection(collectionName); + + shell.log(`📂 Using collection: ${collectionName} for instance: ${instance}`); - // Query for messages, sorted by timestamp descending - const messages = await collection - .find({}) - .sort({ when: -1 }) - .limit(limit) - .toArray(); + // Query for messages, sorted by timestamp descending + const messages = await collection + .find({}) + .sort({ when: -1 }) + .limit(limit) + .toArray(); - // Reverse to get chronological order (oldest to newest) - messages.reverse(); + // Reverse to get chronological order (oldest to newest) + messages.reverse(); - // Resolve handles from user subs using the handle API - const messagesWithHandles = await Promise.all( - messages.map(async (msg) => { - let handle = "anon"; - - if (msg.user) { - try { - // Determine prefix based on instance - let prefix = ""; - if (instance === "sotce") prefix = "sotce-"; - - // Always use production URL for handle lookup (even in dev) - // This ensures we get real handles and avoids SSL issues with localhost - const handleUrl = `https://aesthetic.computer/handle?for=${prefix}${msg.user}`; - - const handleResponse = await fetch(handleUrl); + // Resolve handles from user subs using the handle API + const messagesWithHandles = await Promise.all( + messages.map(async (msg) => { + let handle = "anon"; - if (handleResponse.status === 200) { - const handleData = await handleResponse.json(); - if (handleData.handle) { - handle = "@" + handleData.handle; + if (msg.user) { + try { + // Determine prefix based on instance + let prefix = ""; + if (instance === "sotce") prefix = "sotce-"; + + // Always use production URL for handle lookup (even in dev) + const handleUrl = `https://aesthetic.computer/handle?for=${prefix}${msg.user}`; + + const handleResponse = await fetch(handleUrl); + + if (handleResponse.status === 200) { + const handleData = await handleResponse.json(); + if (handleData.handle) { + handle = "@" + handleData.handle; + } + } else { + shell.log(`⚠️ Handle lookup failed for user ${msg.user}: ${handleResponse.status}`); + } + } catch (error) { + shell.error(`❌ Handle lookup error for user ${msg.user}:`, error.message); } - } else { - shell.log(`⚠️ Handle lookup failed for user ${msg.user}: ${handleResponse.status}`); } - } catch (error) { - shell.error(`❌ Handle lookup error for user ${msg.user}:`, error.message); - } - } - + + return { + from: handle, + text: msg.text, + when: msg.when, + }; + }) + ); + + await database.disconnect(); + + shell.log(`✅ Found ${messagesWithHandles.length} messages for instance: ${instance}`); + return { - from: handle, - text: msg.text, - when: msg.when, + instance, + count: messagesWithHandles.length, + messages: messagesWithHandles, }; - }) + }, + CACHE_TTLS.CHAT // 2 minutes ); - await database.disconnect(); - - shell.log(`✅ Found ${messagesWithHandles.length} messages for instance: ${instance}`); - - return respond(200, { - instance, - count: messagesWithHandles.length, - messages: messagesWithHandles, - }); + return respond(200, result); } catch (error) { shell.error("Error fetching chat messages:", error); return respond(500, { message: error.message }); diff --git a/system/netlify/functions/kidlisp-count.mjs b/system/netlify/functions/kidlisp-count.mjs index f1c119c0b6..fe15da01cf 100644 --- a/system/netlify/functions/kidlisp-count.mjs +++ b/system/netlify/functions/kidlisp-count.mjs @@ -1,8 +1,10 @@ // api/kidlisp-count, 2026.01.03 // Returns total count of kidlisp programs in the database. +// Now with Redis caching (30 min TTL). import { respond } from "../../backend/http.mjs"; import { connect } from "../../backend/database.mjs"; +import { getOrCompute, CACHE_KEYS, CACHE_TTLS } from "../../backend/cache.mjs"; export async function handler(event, context) { if (event.httpMethod !== "GET") { @@ -10,15 +12,19 @@ export async function handler(event, context) { } try { - const database = await connect(); - const collection = database.db.collection("kidlisp"); - const count = await collection.countDocuments(); - await database.disconnect(); + const result = await getOrCompute( + CACHE_KEYS.KIDLISP_COUNT, + async () => { + const database = await connect(); + const collection = database.db.collection("kidlisp"); + const count = await collection.countDocuments(); + await database.disconnect(); + return { count, collection: "kidlisp" }; + }, + CACHE_TTLS.KIDLISP_COUNT + ); - return respond(200, { - count, - collection: "kidlisp" - }); + return respond(200, result); } catch (error) { console.error("Error fetching kidlisp count:", error); return respond(500, { error: "Failed to fetch count" }); diff --git a/system/netlify/functions/metrics.mjs b/system/netlify/functions/metrics.mjs index 5fb29b9423..972e962beb 100644 --- a/system/netlify/functions/metrics.mjs +++ b/system/netlify/functions/metrics.mjs @@ -1,5 +1,6 @@ // Metrics, 24.10.20.00.06 // Reports platform activity and statistics for Aesthetic Computer and Sotce Net. +// Now with Redis caching (30 min TTL) to reduce MongoDB load. // 1. GET `api/metrics` // Return JSON data. @@ -10,6 +11,7 @@ import { activeUsers } from "../../backend/authorization.mjs"; import { connect } from "../../backend/database.mjs"; import { respond } from "../../backend/http.mjs"; +import { getOrCompute, CACHE_KEYS, CACHE_TTLS } from "../../backend/cache.mjs"; const dev = process.env.CONTEXT === "dev"; import { shell } from "../../backend/shell.mjs"; @@ -17,96 +19,22 @@ import { shell } from "../../backend/shell.mjs"; export async function handler(event, context) { if (event.httpMethod === "GET") { try { - const { got } = await import("got"); - - // Get active users from `auth0`. - const active = await activeUsers("aesthetic"); - const sotceActive = await activeUsers("sotce"); - - // Pull some stats from the Mongo database. - const database = await connect(); - - const handlesCollection = database.db.collection("@handles"); - //const allHandles = await handlesCollection.countDocuments(); - - const handles = await handlesCollection.countDocuments(); - - // aesthetic-computer - // const handles = await handlesCollection.countDocuments({ - // _id: { $not: { $regex: "^sotce-" } }, - // }); - - // sotce-net - const sotceHandles = await handlesCollection.countDocuments({ - _id: { $regex: "^sotce-" }, - }); - - const pieces = await database.db.collection("pieces").countDocuments(); - const paintings = await database.db - .collection("paintings") - .countDocuments(); - const moods = await database.db.collection("moods").countDocuments(); - const logs = await database.db.collection("logs").countDocuments(); - const chatMessages = await database.db - .collection("chat-system") - .countDocuments(); - const tickets = await database.db.collection("tickets").countDocuments(); - const kidlisp = await database.db.collection("kidlisp").countDocuments(); - const pages = database.db.collection("sotce-pages"); - const pagesCrumpled = await pages.countDocuments({ state: "crumpled" }); - const pagesPublished = await pages.countDocuments({ state: "published" }); - const touches = await database.db - .collection("sotce-touches") - .countDocuments(); - await database.disconnect(); - - // Get sotce subscriptions. - let sotceSubscribers = null; - try { - sotceSubscribers = ( - await (await fetch("https://sotce.net/sotce-net/subscribers")).json() - ).subscribers; - } catch (err) { - shell.error("🔴 Could not retrieve `sotce-net` subscriber count:", err); + // Check if client wants fresh data (bypass cache) + const bypassCache = event.queryStringParameters?.fresh === 'true'; + + if (bypassCache) { + console.log("📊 Metrics: bypassing cache (fresh=true)"); + return respond(200, await computeMetrics()); } - - const printsOrdered = await getTotalPrintfulPrintQuantity(); - - // TODO: Add data from either Cloudflare or Google Analytics. 24.10.21.00.30 - // Cloudflare URL: https://dash.cloudflare.com/a23b54e8877a833a1cf8db7765bce3ca/aesthetic.computer/analytics/traffic - - const time = new Date().toLocaleString("en-US", { - weekday: "long", // Day of the week - year: "numeric", - month: "short", // Short month name - day: "numeric", - hour: "numeric", - minute: "numeric", - second: "numeric", - timeZoneName: "short", // Includes time zone - }); - - return respond(200, { - handles, // shared - // `aesthetic-computer` - active, - pieces, - paintings, - moods, - kidlisp, - chatMessages, - logs, - printsOrdered, - tickets, - // `sotce-net` - sotceActive, - sotceHandles, - sotceSubscribers, - pagesPublished, - pagesCrumpled, - touches, - time, - }); + + // Use cached metrics (30 min TTL) + const metrics = await getOrCompute( + CACHE_KEYS.METRICS, + computeMetrics, + CACHE_TTLS.METRICS + ); + + return respond(200, metrics); } catch (error) { shell.log(error); return respond(500, { message: error }); @@ -116,6 +44,90 @@ export async function handler(event, context) { } } +// Extracted metrics computation for caching +async function computeMetrics() { + const { got } = await import("got"); + + // Get active users from `auth0`. + const active = await activeUsers("aesthetic"); + const sotceActive = await activeUsers("sotce"); + + // Pull some stats from the Mongo database. + const database = await connect(); + + const handlesCollection = database.db.collection("@handles"); + + const handles = await handlesCollection.countDocuments(); + + // sotce-net + const sotceHandles = await handlesCollection.countDocuments({ + _id: { $regex: "^sotce-" }, + }); + + const pieces = await database.db.collection("pieces").countDocuments(); + const paintings = await database.db + .collection("paintings") + .countDocuments(); + const moods = await database.db.collection("moods").countDocuments(); + const logs = await database.db.collection("logs").countDocuments(); + const chatMessages = await database.db + .collection("chat-system") + .countDocuments(); + const tickets = await database.db.collection("tickets").countDocuments(); + const kidlisp = await database.db.collection("kidlisp").countDocuments(); + const pages = database.db.collection("sotce-pages"); + const pagesCrumpled = await pages.countDocuments({ state: "crumpled" }); + const pagesPublished = await pages.countDocuments({ state: "published" }); + const touches = await database.db + .collection("sotce-touches") + .countDocuments(); + await database.disconnect(); + + // Get sotce subscriptions. + let sotceSubscribers = null; + try { + sotceSubscribers = ( + await (await fetch("https://sotce.net/sotce-net/subscribers")).json() + ).subscribers; + } catch (err) { + shell.error("🔴 Could not retrieve `sotce-net` subscriber count:", err); + } + + const printsOrdered = await getTotalPrintfulPrintQuantity(); + + const time = new Date().toLocaleString("en-US", { + weekday: "long", + year: "numeric", + month: "short", + day: "numeric", + hour: "numeric", + minute: "numeric", + second: "numeric", + timeZoneName: "short", + }); + + return { + handles, + active, + pieces, + paintings, + moods, + kidlisp, + chatMessages, + logs, + printsOrdered, + tickets, + sotceActive, + sotceHandles, + sotceSubscribers, + pagesPublished, + pagesCrumpled, + touches, + time, + cached: true, // Indicate this may be cached + }; +} + const printfulKey = process.env.PRINTFUL_API_TOKEN; async function getTotalPrintfulPrintQuantity() { diff --git a/system/netlify/functions/tv.mjs b/system/netlify/functions/tv.mjs index 5c24f4b294..68fce260c6 100644 --- a/system/netlify/functions/tv.mjs +++ b/system/netlify/functions/tv.mjs @@ -1,8 +1,10 @@ // api/tv, 2025.10.02 // Returns feed data for the TV (For-You) experience. +// Now with Redis caching (5 min TTL for give page calls). import { respond } from "../../backend/http.mjs"; import { connect } from "../../backend/database.mjs"; +import { getOrCompute, CACHE_TTLS } from "../../backend/cache.mjs"; const DEFAULT_MEDIA_TYPES = ["painting"]; const MAX_LIMIT = 500; @@ -381,6 +383,26 @@ export async function handler(event) { const filter = params.filter?.toLowerCase() || "recent"; // "recent" or "sprinkle" const sort = params.sort?.toLowerCase(); // "hits" for all-time popularity + // Create cache key from query params + const cacheKey = `give:tv:${requestedTypes.join(',')}:${limit}:${filter}:${sort || 'default'}`; + + try { + // Use caching for TV feed (5 min TTL) + const result = await getOrCompute( + cacheKey, + () => fetchTVFeed({ requestedTypes, limit, filter, sort }), + CACHE_TTLS.TV_RECENT + ); + + return respond(200, result); + } catch (error) { + console.error("Failed to build TV feed", error); + return respond(500, { error: "Failed to build TV feed", details: error.message }); + } +} + +// Extracted TV feed fetching logic for caching +async function fetchTVFeed({ requestedTypes, limit, filter, sort }) { const media = {}; const pendingTypes = []; const unsupportedTypes = []; @@ -575,7 +597,8 @@ export async function handler(event) { console.log(`📺 Mixed feed created: ${mixedFeed.length} items (${mixedFeed.filter(i => i.type === 'kidlisp').length} kidlisp, ${mixedFeed.filter(i => i.type === 'painting').length} paintings, ${mixedFeed.filter(i => i.type === 'tape').length} tapes, ${mixedFeed.filter(i => i.type === 'clock').length} clocks)`); - return respond(200, { + // Return data (not respond) since this is called from cache wrapper + return { meta: { requestedTypes, limit, @@ -588,9 +611,9 @@ export async function handler(event) { }, media, mixed: mixedFeed, // Add mixed/interwoven feed - }); + }; } catch (error) { - console.error("Failed to build TV feed", error); - return respond(500, { error: "Failed to build TV feed", details: error.message }); + console.error("Failed to fetch TV feed data", error); + throw error; // Re-throw so cache wrapper can handle } } diff --git a/system/public/give.aesthetic.computer/index.html b/system/public/give.aesthetic.computer/index.html index 7b8000f1a5..1ed9783606 100644 --- a/system/public/give.aesthetic.computer/index.html +++ b/system/public/give.aesthetic.computer/index.html @@ -906,10 +906,10 @@ } @keyframes logo-shadow-1 { 0%, 100% { - filter: drop-shadow(0 3px 6px rgba(0,0,0,0.4)) drop-shadow(0 0 15px rgba(255,255,255,0.3)) brightness(1.2); + filter: drop-shadow(0 4px 8px rgba(0,0,0,0.5)) brightness(1.2); } 50% { - filter: drop-shadow(0 3px 6px rgba(0,0,0,0.4)) drop-shadow(0 0 25px rgba(255,255,255,0.5)) brightness(1.3); + filter: drop-shadow(0 4px 12px rgba(0,0,0,0.4)) brightness(1.3); } } @@ -920,10 +920,10 @@ } @keyframes logo-shadow-2 { 0%, 100% { - filter: drop-shadow(0 5px 12px rgba(0,0,0,0.6)) drop-shadow(-6px 0 12px rgba(255,215,0,0.4)) drop-shadow(6px 0 12px rgba(0,229,255,0.4)) brightness(1.1); + filter: drop-shadow(0 5px 12px rgba(0,0,0,0.5)) drop-shadow(0 0 15px rgba(255,215,0,0.3)) brightness(1.1); } 50% { - filter: drop-shadow(0 5px 12px rgba(0,0,0,0.6)) drop-shadow(6px 0 12px rgba(255,215,0,0.4)) drop-shadow(-6px 0 12px rgba(0,229,255,0.4)) brightness(1.15); + filter: drop-shadow(0 5px 12px rgba(0,0,0,0.5)) drop-shadow(0 0 20px rgba(0,229,255,0.3)) brightness(1.15); } } @@ -934,35 +934,35 @@ } @keyframes logo-shadow-3 { 0% { - filter: drop-shadow(0 8px 20px rgba(0,0,0,0.8)) drop-shadow(-10px -5px 18px #ff6b6b) drop-shadow(10px 0 18px #4ecdc4) drop-shadow(0 10px 18px #ffd93d) brightness(0.95); + filter: drop-shadow(0 6px 15px rgba(0,0,0,0.6)) drop-shadow(0 0 20px #ff6b6b) brightness(1); } 33% { - filter: drop-shadow(0 8px 20px rgba(0,0,0,0.8)) drop-shadow(10px -5px 18px #4ecdc4) drop-shadow(0 10px 18px #ff6b6b) drop-shadow(-10px 0 18px #ffd93d) brightness(0.95); + filter: drop-shadow(0 6px 15px rgba(0,0,0,0.6)) drop-shadow(0 0 20px #4ecdc4) brightness(1); } 66% { - filter: drop-shadow(0 8px 20px rgba(0,0,0,0.8)) drop-shadow(0 -10px 18px #ffd93d) drop-shadow(-10px 5px 18px #4ecdc4) drop-shadow(10px 5px 18px #ff6b6b) brightness(0.95); + filter: drop-shadow(0 6px 15px rgba(0,0,0,0.6)) drop-shadow(0 0 20px #ffd93d) brightness(1); } 100% { - filter: drop-shadow(0 8px 20px rgba(0,0,0,0.8)) drop-shadow(-10px -5px 18px #ff6b6b) drop-shadow(10px 0 18px #4ecdc4) drop-shadow(0 10px 18px #ffd93d) brightness(0.95); + filter: drop-shadow(0 6px 15px rgba(0,0,0,0.6)) drop-shadow(0 0 20px #ff6b6b) brightness(1); } } /* Intensity 4: Super bright pink electric saturated */ @keyframes logo-shadow-4 { 0% { - filter: drop-shadow(0 0 30px #ff0080) drop-shadow(-15px 0 35px #ff0080) drop-shadow(15px 0 35px #00e5ff) drop-shadow(0 -15px 35px #ffd700) drop-shadow(0 15px 35px #ff00ff) brightness(1.4) saturate(1.5); + filter: drop-shadow(0 0 25px #ff0080) drop-shadow(0 0 40px #ff00ff) brightness(1.4) saturate(1.5); } 25% { - filter: drop-shadow(0 0 35px #ff00ff) drop-shadow(0 -15px 35px #ff0080) drop-shadow(0 15px 35px #00e5ff) drop-shadow(15px 0 35px #ffd700) drop-shadow(-15px 0 35px #ff0080) brightness(1.5) saturate(1.6); + filter: drop-shadow(0 0 30px #ff00ff) drop-shadow(0 0 40px #00e5ff) brightness(1.5) saturate(1.6); } 50% { - filter: drop-shadow(0 0 30px #00e5ff) drop-shadow(15px 0 35px #ff0080) drop-shadow(-15px 0 35px #00e5ff) drop-shadow(0 15px 35px #ff00ff) drop-shadow(0 -15px 35px #ffd700) brightness(1.4) saturate(1.5); + filter: drop-shadow(0 0 25px #00e5ff) drop-shadow(0 0 40px #ffd700) brightness(1.4) saturate(1.5); } 75% { - filter: drop-shadow(0 0 35px #ff0080) drop-shadow(0 15px 35px #ff0080) drop-shadow(0 -15px 35px #00e5ff) drop-shadow(-15px 0 35px #ff00ff) drop-shadow(15px 0 35px #ffd700) brightness(1.5) saturate(1.6); + filter: drop-shadow(0 0 30px #ffd700) drop-shadow(0 0 40px #ff0080) brightness(1.5) saturate(1.6); } 100% { - filter: drop-shadow(0 0 30px #ff0080) drop-shadow(-15px 0 35px #ff0080) drop-shadow(15px 0 35px #00e5ff) drop-shadow(0 -15px 35px #ffd700) drop-shadow(0 15px 35px #ff00ff) brightness(1.4) saturate(1.5); + filter: drop-shadow(0 0 25px #ff0080) drop-shadow(0 0 40px #ff00ff) brightness(1.4) saturate(1.5); } } @@ -981,18 +981,18 @@ } @keyframes vegas-glow { - 0%, 100% { box-shadow: 0 0 10px rgba(255,215,0,0.5), 0 2px 8px rgba(0,0,0,0.4); } - 50% { box-shadow: 0 0 25px rgba(255,215,0,0.8), 0 0 40px rgba(255,100,100,0.4), 0 2px 8px rgba(0,0,0,0.4); } + 0%, 100% { box-shadow: 0 0 12px rgba(255,215,0,0.6); } + 50% { box-shadow: 0 0 20px rgba(255,215,0,0.8); } } @keyframes vegas-rainbow { - 0% { border-color: #ff6b6b; box-shadow: 0 0 20px #ff6b6b, 0 0 40px rgba(255,107,107,0.5); } - 16% { border-color: #ffd93d; box-shadow: 0 0 20px #ffd93d, 0 0 40px rgba(255,217,61,0.5); } - 33% { border-color: #6bcb77; box-shadow: 0 0 20px #6bcb77, 0 0 40px rgba(107,203,119,0.5); } - 50% { border-color: #4ecdc4; box-shadow: 0 0 20px #4ecdc4, 0 0 40px rgba(78,205,196,0.5); } - 66% { border-color: #9b59b6; box-shadow: 0 0 20px #9b59b6, 0 0 40px rgba(155,89,182,0.5); } - 83% { border-color: #ff6b9d; box-shadow: 0 0 20px #ff6b9d, 0 0 40px rgba(255,107,157,0.5); } - 100% { border-color: #ff6b6b; box-shadow: 0 0 20px #ff6b6b, 0 0 40px rgba(255,107,107,0.5); } + 0% { border-color: #ff6b6b; box-shadow: 0 0 15px #ff6b6b; } + 16% { border-color: #ffd93d; box-shadow: 0 0 15px #ffd93d; } + 33% { border-color: #6bcb77; box-shadow: 0 0 15px #6bcb77; } + 50% { border-color: #4ecdc4; box-shadow: 0 0 15px #4ecdc4; } + 66% { border-color: #9b59b6; box-shadow: 0 0 15px #9b59b6; } + 83% { border-color: #ff6b9d; box-shadow: 0 0 15px #ff6b9d; } + 100% { border-color: #ff6b6b; box-shadow: 0 0 15px #ff6b6b; } } @keyframes vegas-shake { @@ -1100,14 +1100,14 @@ } @keyframes vegas-rainbow-fast { - 0% { border-color: #ff6b6b; box-shadow: 0 0 25px #ff6b6b, 0 0 50px rgba(255,107,107,0.6); } - 14% { border-color: #ffd93d; box-shadow: 0 0 25px #ffd93d, 0 0 50px rgba(255,217,61,0.6); } - 28% { border-color: #6bcb77; box-shadow: 0 0 25px #6bcb77, 0 0 50px rgba(107,203,119,0.6); } - 42% { border-color: #4ecdc4; box-shadow: 0 0 25px #4ecdc4, 0 0 50px rgba(78,205,196,0.6); } - 57% { border-color: #9b59b6; box-shadow: 0 0 25px #9b59b6, 0 0 50px rgba(155,89,182,0.6); } - 71% { border-color: #ff6b9d; box-shadow: 0 0 25px #ff6b9d, 0 0 50px rgba(255,107,157,0.6); } - 85% { border-color: #00e5ff; box-shadow: 0 0 25px #00e5ff, 0 0 50px rgba(0,229,255,0.6); } - 100% { border-color: #ff6b6b; box-shadow: 0 0 25px #ff6b6b, 0 0 50px rgba(255,107,107,0.6); } + 0% { border-color: #ff6b6b; box-shadow: 0 0 20px #ff6b6b; } + 14% { border-color: #ffd93d; box-shadow: 0 0 20px #ffd93d; } + 28% { border-color: #6bcb77; box-shadow: 0 0 20px #6bcb77; } + 42% { border-color: #4ecdc4; box-shadow: 0 0 20px #4ecdc4; } + 57% { border-color: #9b59b6; box-shadow: 0 0 20px #9b59b6; } + 71% { border-color: #ff6b9d; box-shadow: 0 0 20px #ff6b9d; } + 85% { border-color: #00e5ff; box-shadow: 0 0 20px #00e5ff; } + 100% { border-color: #ff6b6b; box-shadow: 0 0 20px #ff6b6b; } } /* Flames effect for max monthly ($500/mo) */ @@ -4153,7 +4153,7 @@
- Aesthetic.Computer is a social software network supported by the full-time engineering practice of @jeffrey, who has been building experimental software instruments for over a decade. He lives in Echo Park with @fifi in a house full of musicians, and regularly does show and tell at the NELA Computer Club in Chinatown. The next meeting is at 7pm on Tuesday, January 6th at Plot. + Aesthetic.Computer is a social software network supported by the full-time engineering practice of @jeffrey, who has been building experimental software instruments for over a decade. He lives in Echo Park with @fifi in a house full of musicians, and regularly does show and tell at the NELA Computer Club in Chinatown. Their next meeting is at 7pm on Tuesday, January 6th at Plot.
Aesthetic.Computer er et socialt softwarenetværk understøttet af fuldtids ingeniørpraksis af @jeffrey, som har bygget eksperimentelle software-instrumenter i over et årti. Han bor i Echo Park med @fifi i et hus fuldt af musikere, og demonstrerer regelmæssigt softwaren ved NELA Computer Club i Chinatown. Det næste møde er kl. 19 tirsdag den 6. januar på Plot. @@ -4631,7 +4631,7 @@ const jeffreysImages = Object.keys(jeffreysData); const screenshotsImages = Object.keys(screenshotsData); const allImages = [...jeffreysImages, ...screenshotsImages]; - const DEBUG_FACES = true; // Set true to show POI boxes + const DEBUG_FACES = false; // Set true to show POI boxes const POI_GLOW = true; // Soft radial glow on detected faces/bodies function initJeffreysSlideshow() { @@ -4694,7 +4694,7 @@ } }); } - + // Resize canvas to container let canvasW = 0, canvasH = 0; function resizeCanvas() { @@ -4716,6 +4716,9 @@ let poiTimer = 0; // Timer for switching POIs let globalRotation = 0; // Slow global rotation let colorPhase = 0; // For color channel cycling + let verticalScrollPhase = 0; // For vertical Ken Burns scrolling (0 to 1) + let swingPhase = 0; // Swinging rope-like motion + let zoomPhase = 0; // Subtle zoom breathing // Easing function for smooth bouncy motion function easeInOutSine(t) { @@ -4730,7 +4733,9 @@ } // Draw POI with simple Ken Burns - just face/body with nice zoom and pan - function drawPoiWithContext(img, data, poi, destX, destY, destW, destH, alpha, rotation = 0, side = 'left') { + // verticalProgress is 0-1 for top-to-bottom scroll animation + // zoomBreath and swingOffset add organic swaying motion + function drawPoiWithContext(img, data, poi, destX, destY, destW, destH, alpha, rotation = 0, side = 'left', verticalProgress = 0.5, zoomBreath = 0, swingOffset = 0) { const imgW = img.width; const imgH = img.height; @@ -4745,17 +4750,32 @@ ctx.save(); // Calculate zoom to COVER the canvas (always fill entire viewport) + // Add subtle zoom breathing (±3%) for organic feel const scaleX = destW / imgW; const scaleY = destH / imgH; - const coverScale = Math.max(scaleX, scaleY) * 1.15; // 15% extra to ensure full coverage + const zoomPulse = 1.0 + zoomBreath * 0.03; // Subtle 3% zoom oscillation + const coverScale = Math.max(scaleX, scaleY) * 1.15 * zoomPulse; // 15% extra + breathing // Scaled image dimensions const scaledW = imgW * coverScale; const scaledH = imgH * coverScale; // Position POI at 30% or 70% horizontally (avoiding center where logo is) - const targetX = side === 'left' ? destW * 0.30 : destW * 0.70; - const targetY = destH * 0.45; // Slightly above center + // Add swing offset for rope-like delayed motion + const swingX = swingOffset * 8; // Subtle horizontal swing + const swingY = Math.sin(swingOffset * 0.7) * 5; // Delayed vertical bounce + const targetX = (side === 'left' ? destW * 0.30 : destW * 0.70) + swingX; + + // For vertical images (aspect < 0.8), use vertical scroll animation + const isVertical = data.aspect < 0.8; + let targetY; + if (isVertical) { + // Scroll from top (20%) to bottom (80%) based on verticalProgress - slower, dreamier + const easedProgress = (Math.sin((verticalProgress - 0.5) * Math.PI) + 1) / 2; // Ease in-out + targetY = destH * (0.15 + easedProgress * 0.7) + swingY; + } else { + targetY = destH * 0.45 + swingY; // Slightly above center with swing + } // Calculate offset to position POI center at target position let offsetX = targetX - (poiCenterX * coverScale); @@ -4794,6 +4814,26 @@ // Draw image covering entire canvas ctx.drawImage(img, 0, 0, imgW, imgH, offsetX, offsetY, scaledW, scaledH); + // Reset filter + ctx.filter = 'none'; + + // DEBUG: Draw POI box + if (DEBUG_FACES) { + const typeColors = { f: 'rgba(255, 0, 255, 0.9)', b: 'rgba(0, 255, 255, 0.7)', h: 'rgba(255, 255, 0, 0.5)' }; + ctx.strokeStyle = typeColors[poi.t] || 'white'; + ctx.lineWidth = 3; + // Map POI box to canvas coords + const canvasPoiX = offsetX + poiX * coverScale; + const canvasPoiY = offsetY + poiY * coverScale; + const canvasPoiW = poiW * coverScale; + const canvasPoiH = poiH * coverScale; + ctx.strokeRect(canvasPoiX, canvasPoiY, canvasPoiW, canvasPoiH); + // Label + ctx.font = 'bold 14px monospace'; + ctx.fillStyle = typeColors[poi.t]; + ctx.fillText(poi.t.toUpperCase() + ' ' + data.aspect.toFixed(2), canvasPoiX + 4, canvasPoiY + 16); + } + ctx.filter = 'none'; ctx.restore(); @@ -5027,6 +5067,8 @@ let isTransitioning = false; let currentPoiIndex = 0; let poiPhase = 0; // For slow progression through POIs + let initialFadeIn = 0; // 0 = invisible, 1 = fully visible (initial fade-in) + let isInitialized = false; // True once first images are loaded and ready // Two POIs always visible: left and right let leftPoi = null; @@ -5034,68 +5076,144 @@ let prevLeftPoi = null; let prevRightPoi = null; - // Build a flat list of all POIs across all images (faces and bodies only) - const allPois = []; - for (const name of allImages) { + // Build separate lists for jeffreys and screenshots POIs + const jeffreysPois = []; + const screenshotsPois = []; + + for (const name of jeffreysImages) { + const data = allImagesData[name]; + if (data.pois && data.pois.length > 0) { + for (const poi of data.pois) { + if (poi.t === 'h') continue; + if (poi.t === 'b' && poi.box[2] * poi.box[3] < 15) continue; + jeffreysPois.push({ name, poi, data }); + } + } else { + // No POIs - create virtual POI from focal point + const virtualPoi = { t: 'v', box: [data.focal[0] - 15, data.focal[1] - 15, 30, 30] }; + jeffreysPois.push({ name, poi: virtualPoi, data }); + } + } + + for (const name of screenshotsImages) { const data = allImagesData[name]; - if (data.pois) { + if (data.pois && data.pois.length > 0) { for (const poi of data.pois) { - // Only faces and bodies, skip hands and small bodies if (poi.t === 'h') continue; - if (poi.t === 'b' && poi.box[2] * poi.box[3] < 15) continue; // Skip tiny bodies - allPois.push({ name, poi, data }); + if (poi.t === 'b' && poi.box[2] * poi.box[3] < 15) continue; + screenshotsPois.push({ name, poi, data }); } + } else { + // Screenshots have no faces - create virtual POI from focal point for environmental shots + const virtualPoi = { t: 'v', box: [data.focal[0] - 20, data.focal[1] - 15, 40, 30] }; + screenshotsPois.push({ name, poi: virtualPoi, data }); } } - // Shuffle for variety - for (let i = allPois.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)); - [allPois[i], allPois[j]] = [allPois[j], allPois[i]]; + + // Shuffle both arrays + const shuffle = arr => { + for (let i = arr.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + return arr; + }; + shuffle(jeffreysPois); + shuffle(screenshotsPois); + + // Prioritize faces in each + jeffreysPois.sort((a, b) => (b.poi.t === 'f' ? 1 : 0) - (a.poi.t === 'f' ? 1 : 0)); + screenshotsPois.sort((a, b) => (b.poi.t === 'f' ? 1 : 0) - (a.poi.t === 'f' ? 1 : 0)); + + // Interleave/oscillate: jeffreys then screenshot, etc. + const allPois = []; + const maxLen = Math.max(jeffreysPois.length, screenshotsPois.length); + for (let i = 0; i < maxLen; i++) { + if (i < jeffreysPois.length) allPois.push(jeffreysPois[i]); + if (i < screenshotsPois.length) allPois.push(screenshotsPois[i]); } - // Prioritize faces - move them to front - allPois.sort((a, b) => (b.poi.t === 'f' ? 1 : 0) - (a.poi.t === 'f' ? 1 : 0)); function render() { const w = canvasW; const h = canvasH; - // Update phases slowly - globalRotation += 0.00003; - floatOffset += 0.00005; - poiPhase += 0.0001; // Slow POI progression + // Update phases - SLOW and dreamy + globalRotation += 0.000015; // Even slower rotation + floatOffset += 0.00003; // Slower float + poiPhase += 0.00005; // Slower POI progression + verticalScrollPhase += 0.0003; // Much slower vertical scroll (~55 sec full cycle) + if (verticalScrollPhase > 1) verticalScrollPhase = 0; + swingPhase += 0.00007; // Slow pendulum swing + zoomPhase += 0.00004; // Very slow zoom breathing + + // Swinging rope motion - delayed sinusoids for organic feel + const swing1 = Math.sin(swingPhase * Math.PI * 2); + const swing2 = Math.sin(swingPhase * Math.PI * 2 - 0.5); // Delayed follow + const swing3 = Math.sin(swingPhase * Math.PI * 1.3); // Different frequency - const rotation = Math.sin(globalRotation) * 0.008; // Gentle rotation - const wiggleX = Math.sin(floatOffset * Math.PI * 3) * 2; - const wiggleY = Math.cos(floatOffset * Math.PI * 2.5) * 1.5; + const rotation = swing1 * 0.006 + swing3 * 0.003; // Gentle compound rotation + const wiggleX = swing1 * 1.5 + swing2 * 0.8; // Swaying X + const wiggleY = swing2 * 1.2 + Math.sin(swingPhase * Math.PI * 1.7) * 0.6; // Bouncy Y // Clear completely each frame ctx.fillStyle = 'rgb(18, 14, 24)'; ctx.fillRect(0, 0, w, h); - if (allPois.length === 0 || (!leftPoi && !rightPoi)) { + // Don't render until initialized with loaded images + if (!isInitialized || allPois.length === 0 || (!leftPoi && !rightPoi)) { requestAnimationFrame(render); return; } + // Animate initial fade-in (slow, smooth) + if (initialFadeIn < 1) { + initialFadeIn += 0.008; // ~2 seconds to fully fade in + if (initialFadeIn > 1) initialFadeIn = 1; + } + const masterAlpha = easeInOutSine(initialFadeIn); // Smooth ease + ctx.save(); ctx.translate(w/2 + wiggleX, h/2 + wiggleY); ctx.rotate(rotation); ctx.translate(-w/2, -h/2); // Draw fading out previous POIs during transition (behind current) + // Use a smooth sine-based vertical progress for nice top-to-bottom scroll + const vp = (Math.sin(verticalScrollPhase * Math.PI * 2 - Math.PI/2) + 1) / 2; // 0→1→0 smooth + // Zoom breathing - slow and subtle + const zb = Math.sin(zoomPhase * Math.PI * 2); + // Swing offset for rope-like motion (different phase for left/right) + const swingL = Math.sin(swingPhase * Math.PI * 2); + const swingR = Math.sin(swingPhase * Math.PI * 2 - 0.3); // Slightly delayed for right + + // Screenshot shake - faster, jittery digital motion + const shakePhase = swingPhase * 8; // Faster shake for screenshots + const shakeX = Math.sin(shakePhase * Math.PI * 2) * 3 + Math.sin(shakePhase * Math.PI * 5.3) * 1.5; + const shakeY = Math.cos(shakePhase * Math.PI * 1.7) * 2 + Math.sin(shakePhase * Math.PI * 3.1) * 1; + + // Ease transition progress for smooth fade (no pop) + const easedTransition = easeInOutSine(transitionProgress); + // More dramatic fade curve - faster in middle + const dramaticFade = Math.pow(easedTransition, 0.7); // Faster fade-in + const dramaticFadeOut = Math.pow(1 - easedTransition, 0.7); // Faster fade-out + if (isTransitioning) { if (prevLeftPoi) { const prevImg = loadedImages[prevLeftPoi.name]; - if (prevImg) { - const fadeAlpha = (1 - transitionProgress) * 0.7; - drawPoiWithContext(prevImg, prevLeftPoi.data, prevLeftPoi.poi, 0, 0, w, h, fadeAlpha, 0, 'left'); + if (prevImg && prevImg.complete && prevImg.naturalWidth > 0) { + const isScreenshot = prevLeftPoi.data.src === 'screenshots'; + const fadeAlpha = dramaticFadeOut * (isScreenshot ? 0.65 : 0.75) * masterAlpha; + const swing = isScreenshot ? shakeX * 0.5 : swingL; + drawPoiWithContext(prevImg, prevLeftPoi.data, prevLeftPoi.poi, 0, 0, w, h, fadeAlpha, 0, 'left', vp, zb, swing); } } if (prevRightPoi) { const prevImg = loadedImages[prevRightPoi.name]; - if (prevImg) { - const fadeAlpha = (1 - transitionProgress) * 0.7; - drawPoiWithContext(prevImg, prevRightPoi.data, prevRightPoi.poi, 0, 0, w, h, fadeAlpha, 0, 'right'); + if (prevImg && prevImg.complete && prevImg.naturalWidth > 0) { + const isScreenshot = prevRightPoi.data.src === 'screenshots'; + const fadeAlpha = dramaticFadeOut * (isScreenshot ? 0.6 : 0.7) * masterAlpha; + const swing = isScreenshot ? shakeY * 0.5 : swingR; + drawPoiWithContext(prevImg, prevRightPoi.data, prevRightPoi.poi, 0, 0, w, h, fadeAlpha, 0, 'right', vp, zb, swing); } } } @@ -5103,18 +5221,24 @@ // Draw LEFT POI (always on left side) if (leftPoi) { const leftImg = loadedImages[leftPoi.name]; - if (leftImg) { - const alpha = isTransitioning ? transitionProgress * 0.75 : 0.75; - drawPoiWithContext(leftImg, leftPoi.data, leftPoi.poi, 0, 0, w, h, alpha, 0, 'left'); + if (leftImg && leftImg.complete && leftImg.naturalWidth > 0) { + const isScreenshot = leftPoi.data.src === 'screenshots'; + const baseAlpha = isScreenshot ? 0.7 : 0.8; // Faces brighter + const alpha = (isTransitioning ? dramaticFade * baseAlpha : baseAlpha) * masterAlpha; + const swing = isScreenshot ? shakeX : swingL; // Screenshots shake + drawPoiWithContext(leftImg, leftPoi.data, leftPoi.poi, 0, 0, w, h, alpha, 0, 'left', vp, zb, swing); } } // Draw RIGHT POI (always on right side) - slightly lower alpha for layering if (rightPoi) { const rightImg = loadedImages[rightPoi.name]; - if (rightImg) { - const alpha = isTransitioning ? transitionProgress * 0.7 : 0.7; - drawPoiWithContext(rightImg, rightPoi.data, rightPoi.poi, 0, 0, w, h, alpha, 0, 'right'); + if (rightImg && rightImg.complete && rightImg.naturalWidth > 0) { + const isScreenshot = rightPoi.data.src === 'screenshots'; + const baseAlpha = isScreenshot ? 0.65 : 0.75; // Faces brighter + const alpha = (isTransitioning ? dramaticFade * baseAlpha : baseAlpha) * masterAlpha; + const swing = isScreenshot ? shakeY : swingR; // Screenshots shake differently + drawPoiWithContext(rightImg, rightPoi.data, rightPoi.poi, 0, 0, w, h, alpha, 0, 'right', vp, zb, swing); } } @@ -5134,12 +5258,22 @@ const nextLeftPoi = allPois[nextLeftIdx]; const nextRightPoi = allPois[nextRightIdx]; - // Preload both images + // Preload both images and wait for them to be ready await Promise.all([ preloadImage(nextLeftPoi.name), preloadImage(nextRightPoi.name) ]); + // Verify images are actually loaded before transitioning + const nextLeftImg = loadedImages[nextLeftPoi.name]; + const nextRightImg = loadedImages[nextRightPoi.name]; + if (!nextLeftImg?.complete || !nextLeftImg?.naturalWidth || + !nextRightImg?.complete || !nextRightImg?.naturalWidth) { + // Images not ready, skip this transition + console.warn('Skipping transition - images not loaded'); + return; + } + // Store previous for crossfade prevLeftPoi = leftPoi; prevRightPoi = rightPoi; @@ -5150,9 +5284,13 @@ isTransitioning = true; transitionProgress = 0; - // Animate dissolve over ~3 seconds + // Check if current POIs have faces - hold them longer + const hasFaces = (leftPoi?.poi?.t === 'f') || (rightPoi?.poi?.t === 'f'); + const fadeSpeed = hasFaces ? 0.006 : 0.012; // Slower fades for smoothness + + // Animate dissolve - faces ~5s, screenshots ~2.5s const dissolveInterval = setInterval(() => { - transitionProgress += 0.015; + transitionProgress += fadeSpeed; if (transitionProgress >= 1) { clearInterval(dissolveInterval); transitionProgress = 1; @@ -5173,24 +5311,44 @@ // Load first TWO POIs for left + right simultaneously if (allPois.length >= 2) { - // Preload first pair + // Preload first pair - wait for them to fully load await Promise.all([ preloadImage(allPois[0].name), preloadImage(allPois[1].name) ]); - leftPoi = allPois[0]; - rightPoi = allPois[1]; - currentPoiIndex = 1; // Start at index 1 so next transition goes to 3,4 - // Preload a few more + // Verify images are actually loaded before setting POIs + const img0 = loadedImages[allPois[0].name]; + const img1 = loadedImages[allPois[1].name]; + if (img0?.complete && img0?.naturalWidth > 0 && + img1?.complete && img1?.naturalWidth > 0) { + leftPoi = allPois[0]; + rightPoi = allPois[1]; + currentPoiIndex = 1; + isInitialized = true; // NOW we can start rendering + } + + // Preload a few more in background for (let i = 2; i < Math.min(8, allPois.length); i++) { preloadImage(allPois[i].name); } + // Dynamic transition timing - faces held longer + let transitionTimer = null; + const scheduleNextTransition = () => { + // Check if current POIs have faces + const hasFaces = (leftPoi?.poi?.t === 'f') || (rightPoi?.poi?.t === 'f'); + const holdTime = hasFaces ? 7000 : 4000; // Faces: 7s, Screenshots: 4s + transitionTimer = setTimeout(async () => { + await transitionToNextPoi(); + scheduleNextTransition(); + }, holdTime); + }; + // Start transitions after first pair is showing setTimeout(() => { - setInterval(transitionToNextPoi, 5000); // Change POI pair every 5 seconds - }, 3000); + scheduleNextTransition(); + }, 4000); // Initial hold } else if (allPois.length === 1) { // Only one POI, show it on left await preloadImage(allPois[0].name); -- knotmirror 0.0.1