Download app/renderer/plan-make.js from Devseis/Ora: direct link, hf CLI and curl.
- Browser
- Download file 25.9 kB
-
https://huggingface.co/spaces/Devseis/Ora/resolve/main/app/renderer/plan-make.js
- Command line
-
hf download hf://spaces/Devseis/Ora/app/renderer/plan-make.js
-
curl -L -o plan-make.js https://huggingface.co/spaces/Devseis/Ora/resolve/main/app/renderer/plan-make.js
25.9 kB
| ; | |
| /* global $, S, brand, plan, savePlan, cal, typeOf, renderCalendar, renderPersonas, renderCampaign, camp, parseYmd, runImageBatch, batchWhere, batchCost, | |
| POSTER_SPACE, NO_TEXT, drawPoster, loadImg, picSrc, offlineCaption, itemContext, results, cleanErr, closeDemo, renderPicCount, aiOn, needFields, queue, askCloudflare */ | |
| // Ora makes content itself: posters for planned days ("Make the month's posts" or one day), a picture for each | |
| // funnel step, one-click persona portraits, "Explain my results" (insights), and Remove the demo. Pictures go through | |
| // the picture queue (base.js), one by one on Cloudflare. | |
| const SCENES = { | |
| educational: w => `Close-up of ${w} on a clean wooden table, soft natural light, appetising, professional photo`, | |
| storytelling: w => `The welcoming inside of the small shop where ${w} is made, warm light, no people, professional photo`, | |
| 'behind-the-scenes': w => `Hands preparing ${w} at work, close-up, warm light, real atmosphere, professional photo`, | |
| community: w => `Friendly customers enjoying ${w} together, natural light, candid, professional photo`, | |
| lifestyle: w => `${w} as part of a calm everyday moment by a window, natural light, lifestyle photo`, | |
| promotion: w => `${w}, hero product photo, bright clean background, appetising`, | |
| }; | |
| const LAYOUT = { educational: 'card', storytelling: 'top', 'behind-the-scenes': 'band', community: 'top', lifestyle: 'card', promotion: 'band' }; | |
| const offerWhat = () => String((plan.brand || {}).offer || 'our product').split(/\s+(in|for|near|at)\s+/i)[0].toLowerCase(); | |
| async function newFolder(name) { return window.ora.createProject(name); } | |
| function imageJob({ prompt, shape = 'insta', poster, folder, index, total, title }) { | |
| const parts = [prompt]; | |
| if (brand.on) parts.push(brand.words, brand.colors && `colour palette: ${brand.colors}`); | |
| if (poster) parts.push(POSTER_SPACE[poster.layout] || POSTER_SPACE.top, NO_TEXT); | |
| return { shape, poster, prompt: parts.filter(Boolean).join(', ').slice(0, 2000), project: { folder, index, total, title: String(title).slice(0, 300) }, runOn: batchWhere() }; | |
| } | |
| // the poster as the brand wants it: its font, first colour and logo (when "Use this brand" is on) | |
| function brandPoster(spec) { | |
| const b = plan.brand || {}, on = b.use !== false; | |
| return { sub: '', details: '', cta: '', layout: 'top', format: 'insta', ...spec, font: on && b.font ? b.font : 'modern', accent: on && (b.colors || [])[0] ? b.colors[0] : '#1c1530', logo: on && b.logo ? b.logo : null }; | |
| } | |
| // pictures need Cloudflare: without it, the setup page; skipped, nothing is made | |
| async function needOnline() { | |
| if (batchWhere()) return; | |
| if (!(await askCloudflare('Ora makes pictures with your free Cloudflare account (a few seconds each). Connect it now to make this one.', 'Make pictures'))) throw new Error('Pictures need Cloudflare: connect it in Settings › Accounts (free).'); | |
| } | |
| // draws the poster's text over the new picture and saves it beside the picture and in Pictures/Ora | |
| async function savePosterOf(meta) { | |
| const img = await loadImg(picSrc(meta.id, meta.images[0])); | |
| const cv = document.createElement('canvas'); | |
| const logo = meta.poster.logo ? await loadImg(picSrc(meta.poster.logo.id, meta.poster.logo.file)).catch(() => null) : null; | |
| await drawPoster(cv, img, { ...meta.poster }, logo); | |
| const blob = await new Promise(r => cv.toBlob(r, 'image/png')); | |
| const next = await window.ora.savePoster(meta.id, 0, new Uint8Array(await blob.arrayBuffer()), meta.poster); | |
| Object.assign(meta, next); | |
| } | |
| // --- before a picture: Ora creates it from the topic, or the learner describes it --------------------------------------- | |
| let picAnswer = null; | |
| // o: { title, what, idea (Ora's picture idea), topic (for ✨ Another idea), headline (posters; null: none), cost, batch } | |
| // resolves { scene, headline } or null (cancelled); batch: scene is a look added to every picture ('' = Ora's own) | |
| function askPicture(o) { | |
| const D = $('picDlg'); | |
| $('picTitle').textContent = o.title; $('picWhat').textContent = o.what || ''; | |
| $('picOraTitle').textContent = o.batch ? 'Let Ora create each picture from its day\'s idea' : 'Let Ora create it from the topic'; | |
| $('picOraHint').textContent = o.batch ? 'Each poster gets a picture that fits its idea, in your brand\'s colours.' : 'Ora writes the picture idea from your plan, in your brand\'s colours.'; | |
| $('picOwnTitle').textContent = o.batch ? 'Describe one look for all the pictures' : 'Describe the picture myself'; | |
| $('picOwnHint').textContent = o.batch ? 'For example: bright flat lay on a white table, pastel colours. Each day\'s idea is added to it.' : 'Say what should be in it: the subject, the place, the light.'; | |
| $('picIdeaBox').hidden = !!o.batch; | |
| $('picIdea').textContent = o.idea || ''; $('picNote').textContent = ''; | |
| $('picOwn').value = ''; | |
| D.querySelector('input[value=ora]').checked = true; | |
| $('picHeadField').hidden = o.headline == null; $('picHead').value = o.headline || ''; | |
| $('picCost').textContent = o.cost ? `It takes ${o.cost}.` : ''; | |
| $('picMake').textContent = o.batch ? `✨ Make ${o.batch} posters` : '✨ Make picture'; | |
| $('picAnother').onclick = async e => { | |
| const b = e.currentTarget, label = b.textContent; b.disabled = true; b.textContent = 'Thinking…'; | |
| try { | |
| if (!aiOn()) throw new Error('offline'); | |
| $('picIdea').textContent = await window.ora.improvePrompt(o.topic, 'picture'); | |
| $('picNote').textContent = ''; | |
| } catch { $('picIdea').textContent = o.alt ? o.alt() : $('picIdea').textContent; $('picNote').textContent = aiOn() ? 'The AI did not answer: here is another idea of Ora\'s own.' : 'Connect Cloudflare for AI ideas: here is another idea of Ora\'s own.'; } | |
| finally { b.disabled = false; b.textContent = label; } | |
| }; | |
| $('picOwn').onfocus = $('picOwn').oninput = () => { D.querySelector('input[value=own]').checked = true; }; | |
| if (!D.open) D.showModal(); | |
| return new Promise(resolve => { | |
| if (picAnswer) picAnswer(null); | |
| picAnswer = resolve; | |
| $('picMake').onclick = () => { | |
| // a description typed in the box counts, even if the choice above was not changed | |
| const text = $('picOwn').value.trim(), own = D.querySelector('input[value=own]').checked || text.length >= 6; | |
| if (own && text.length < 6) { $('picOwn').focus(); $('picOwn').placeholder = 'Write a few words about the picture first'; return; } | |
| const r = { scene: own ? text : (o.batch ? '' : $('picIdea').textContent), headline: $('picHead').value.trim() || o.headline || '' }; | |
| picAnswer = null; D.close(); resolve(r); | |
| }; | |
| }); | |
| } | |
| $('picCancel').addEventListener('click', () => { const r = picAnswer; picAnswer = null; $('picDlg').close(); if (r) r(null); }); | |
| $('picDlg').addEventListener('cancel', e => { e.preventDefault(); $('picCancel').click(); }); | |
| // another of Ora's own picture ideas for a kind of post, when the AI cannot help (cycles through the scenes) | |
| let altTurn = 0; | |
| const altScene = (topic) => { const keys = Object.keys(SCENES); altTurn = (altTurn + 1) % keys.length; return `${SCENES[keys[altTurn]](offerWhat())}, theme: ${topic}`; }; | |
| // --- posters for planned days ------------------------------------------------------------------------------------------ | |
| // todo: [[date, entry]]; each day gets a poster with its idea as the headline, and captions for its platforms | |
| // Ora's own picture idea for a planned day | |
| const dayScene = e => `${(SCENES[e.type] || SCENES.educational)(offerWhat())}, theme: ${e.text}`; | |
| // pick: { scene, headline } for one day, or { scene: a look for every day } (from askPicture) | |
| async function makeDays(todo, folderName, pick = {}) { | |
| const note = $('calMakeNote'); | |
| const b = plan.brand || {}, cp = plan.campaign || {}; | |
| const folder = await newFolder(folderName); | |
| const one = todo.length === 1; | |
| const jobs = todo.map(([, e], i) => imageJob({ | |
| prompt: one && pick.scene ? pick.scene : pick.scene ? `${pick.scene}, showing: ${e.text}` : dayScene(e), | |
| poster: brandPoster({ title: (one && pick.headline ? pick.headline : e.text).slice(0, 90), sub: b.name || '', cta: e.type === 'promotion' ? (cp.cta || '') : '', layout: LAYOUT[e.type] || 'top' }), | |
| folder, index: i + 1, total: todo.length, title: e.text, | |
| })); | |
| let made = 0; | |
| const days = todo.map(([d]) => d); | |
| note.hidden = false; | |
| note.textContent = todo.length > 1 ? `Making ${todo.length} posts: 0 done. You can keep working; the progress shows at the top.` : `Making the picture for ${parseYmd(days[0]).toLocaleDateString(undefined, { day: 'numeric', month: 'long' })}…`; | |
| return new Promise((resolve, reject) => { | |
| try { | |
| runImageBatch(jobs, { | |
| onDone: async (meta, i) => { | |
| const d = days[i], e = cal().days[d]; | |
| try { await savePosterOf(meta); } catch (err) { console.error(err); } | |
| if (e) { | |
| e.item = { id: meta.id }; if (e.status === 'idea') e.status = 'made'; | |
| e.captions = e.captions || {}; | |
| const ctx = { ...itemContext(meta, { about: `${e.text}. ${b.offer || ''}` }), title: e.text }; | |
| for (const p of e.platforms && e.platforms.length ? e.platforms : ['instagram']) { | |
| if (e.captions[p]) continue; | |
| try { e.captions[p] = await window.ora.writeCaption(ctx, p); } catch { e.captions[p] = offlineCaption(ctx, p); } | |
| } | |
| } | |
| made++; | |
| savePlan(); | |
| if (todo.length > 1) note.textContent = `Making ${todo.length} posts: ${made} done${made < todo.length ? '…' : '.'}`; | |
| if (!$('paneCalendar').hidden) renderCalendar(); | |
| }, | |
| onFinish: q => { | |
| const failed = q.failed ? ` ${q.failed} could not be made${q.lastError ? ` (${q.lastError})` : ''}.` : ''; | |
| note.textContent = q.error ? `Stopped after ${made} of ${todo.length}: ${q.error}` : q.cancelled ? `Stopped after ${made} of ${todo.length}.` | |
| : todo.length > 1 ? `Done: ${made} posts made, each with its captions. Open a day to check it.${failed}` : made ? 'Done: the picture and its captions are ready.' : `Not made.${failed}`; | |
| if (!$('paneCalendar').hidden) renderCalendar(); | |
| resolve(q); | |
| }, | |
| }); | |
| } catch (err) { note.textContent = cleanErr(err); reject(err); } | |
| }); | |
| } | |
| async function makeMonth() { | |
| const note = $('calMakeNote'); | |
| const c = cal(), b = plan.brand || {}; | |
| const todo = Object.entries(c.days || {}).filter(([, e]) => e.text && !e.item).sort(([a], [z]) => a.localeCompare(z)).slice(0, 30); | |
| note.hidden = false; | |
| if (!todo.length) { note.textContent = Object.keys(c.days || {}).length ? 'Every planned day already has its picture.' : 'Fill the calendar first (✨ Suggest ideas, then Fill the month).'; return; } | |
| await needOnline(); | |
| const pick = await askPicture({ title: 'Make the month\'s posts', what: `${todo.length} posters for the planned days that have no picture yet, each with its captions.`, batch: todo.length, cost: batchCost(todo.length) }); | |
| if (!pick) { note.hidden = true; return; } | |
| await makeDays(todo, `${b.name || 'Plan'} month`, pick); | |
| } | |
| $('calMakeAll').addEventListener('click', () => makeMonth().catch(e => { $('calMakeNote').hidden = false; $('calMakeNote').textContent = cleanErr(e); })); | |
| // the day dialog's ✨ Make picture | |
| async function makeDayPicture(day) { | |
| await needOnline(); | |
| const e = cal().days[day]; | |
| const topic = [`Post idea: ${e.text}`, `Kind of post: ${typeOf(e.type)[1]}`, (plan.brand || {}).name && `Brand: ${plan.brand.name}`, (plan.brand || {}).offer && `Offers: ${plan.brand.offer}`].filter(Boolean).join('\n'); | |
| const pick = await askPicture({ title: 'Make a picture', what: `For ${parseYmd(day).toLocaleDateString(undefined, { weekday: 'long', day: 'numeric', month: 'long' })}: “${e.text}”`, idea: dayScene(e), topic, alt: () => altScene(e.text), headline: e.text, cost: batchCost(1) }); | |
| if (!pick) return; | |
| const was = e.item; e.item = null; | |
| const q = await makeDays([[day, e]], `${(plan.brand || {}).name || 'Plan'} ${day}`, pick); | |
| if (!q.done.length && was && !e.item) { e.item = was; savePlan(); } | |
| } | |
| // --- a picture for one funnel step ----------------------------------------------------------------------------------------- | |
| async function makeFunnelPicture(id, btn) { | |
| await needOnline(); | |
| const c = camp(), b = plan.brand || {}, w = offerWhat(); | |
| const msg = c.message || c.name || b.tagline || ''; | |
| const step = ((c.funnel || {})[id] || {}).what || ''; | |
| const spec = { | |
| awareness: { scene: `Hero shot of ${w}, bright inviting setting, professional photo`, poster: { title: msg || b.name || '', sub: b.name || '', layout: 'top' } }, | |
| engagement: { scene: SCENES.educational(w), poster: { title: (step.split(/[.:]\s/)[0] || c.name || 'Tips').slice(0, 90), sub: b.name || '', layout: 'card' } }, | |
| conversion: { scene: SCENES.promotion(w), poster: { title: c.offer || msg || c.name, sub: c.value || b.tagline || '', details: c.end ? `Until ${parseYmd(c.end).toLocaleDateString(undefined, { day: 'numeric', month: 'long' })}` : '', cta: c.cta || 'Order now', layout: 'band' } }, | |
| }[id]; | |
| const stepName = `${id.charAt(0).toUpperCase()}${id.slice(1)}`; | |
| const idea = step ? `${spec.scene}, showing: ${step}` : spec.scene; | |
| const topic = [`Funnel step: ${stepName}`, step && `Content: ${step}`, msg && `Key message: ${msg}`, b.offer && `Offers: ${b.offer}`].filter(Boolean).join('\n'); | |
| const pick = await askPicture({ title: `Make a picture: ${stepName}`, what: step || `The ${id} step of your campaign`, idea, topic, alt: () => altScene(step || msg || w), headline: spec.poster.title || '', cost: batchCost(1) }); | |
| if (!pick) return; | |
| spec.poster.title = pick.headline || spec.poster.title; | |
| const label = btn.textContent; btn.disabled = true; btn.textContent = 'Making…'; | |
| const folder = await newFolder(`${b.name || 'Plan'} funnel`); | |
| const title = `${stepName}: ${spec.poster.title || ''}`; | |
| try { | |
| runImageBatch([imageJob({ prompt: pick.scene, poster: brandPoster(spec.poster), folder, index: 1, total: 1, title })], { | |
| onDone: async meta => { try { await savePosterOf(meta); } catch (err) { console.error(err); } c.funnel[id] = { ...(c.funnel[id] || {}), item: { id: meta.id } }; savePlan(); }, | |
| onFinish: q => { btn.disabled = false; btn.textContent = label; if (!$('paneCampaign').hidden) renderCampaign(); if (q.error || (!q.done.length && q.lastError)) $('cNote').textContent = `Could not make the picture: ${q.error || q.lastError}`; }, | |
| }); | |
| } catch (e) { btn.disabled = false; btn.textContent = label; throw e; } | |
| } | |
| // --- one-click persona portraits ---------------------------------------------------------------------------------------- | |
| // personas whose portrait is being made (their card shows it, see renderPersonas) | |
| const portraitsMaking = new Set(); | |
| // The portrait shows a woman or a man as set on the persona. Not set: Cloudflare's text model says whether the name is | |
| // usually a woman's or a man's (kept as a guess, cleared if the name changes); unsure or offline: the field is marked. | |
| async function personaGender(p) { | |
| if (p.gender) return p.gender; | |
| if (p.name && aiOn()) { | |
| try { const g = await window.ora.improvePrompt(p.name, 'gender'); if (g === 'woman' || g === 'man') { p.gender = g; p.genderGuessed = true; savePlan(); return g; } } catch { } | |
| } | |
| const i = plan.personas.indexOf(p); | |
| needFields([`pGender${i}`], `Pick one so the portrait shows ${p.name || 'this persona'} as they are`); | |
| return null; | |
| } | |
| async function makePortraitNow(p, btn) { | |
| try { await needOnline(); } catch { return; } | |
| if (queue) { alert('Pictures are already being made. Wait until they are finished (see the top bar), then press Make portrait again.'); return; } | |
| const label = btn.textContent; | |
| btn.disabled = true; btn.textContent = 'Checking…'; | |
| const gender = await personaGender(p); | |
| btn.disabled = false; btn.textContent = label; | |
| if (!gender) { renderPersonas(); setTimeout(() => needFields([`pGender${plan.personas.indexOf(p)}`], `Pick one so the portrait shows ${p.name || 'this persona'} as they are`), 50); return; } | |
| const topic = `A portrait for a customer persona: ${[p.name, p.age && `${p.age} years old`, gender, p.job].filter(Boolean).join(', ')}. Needs: ${p.needs || ''}. Describe a head-and-shoulders photo of ONE ${gender}.`; | |
| const pick = await askPicture({ title: `Make a portrait of ${p.name || 'this persona'}`, what: [p.age, gender, p.job].filter(Boolean).join(' · '), idea: portraitIdea(p, gender), topic, alt: () => portraitIdea(p, gender).replace('soft daylight', ['warm window light', 'outdoor golden light', 'bright studio light'][altTurn++ % 3]), headline: null, cost: batchCost(1) }); | |
| if (!pick) return; | |
| portraitsMaking.add(p.id); renderPersonas(); | |
| try { | |
| const folder = await newFolder(`Portrait ${p.name || 'persona'}`); | |
| const own = pick.scene !== portraitIdea(p, gender) ? pick.scene : ''; | |
| runImageBatch([portraitJob(p, gender, folder, 1, 1, own)], { | |
| onDone: meta => { p.portrait = { id: meta.id, file: meta.images[0] }; savePlan(); }, | |
| onFinish: q => { portraitsMaking.delete(p.id); if (!$('panePersonas').hidden) renderPersonas(); if (q.error || (!q.done.length && q.lastError)) alert(`Could not make the portrait: ${q.error || q.lastError}`); }, | |
| }); | |
| } catch (e) { portraitsMaking.delete(p.id); renderPersonas(); alert(cleanErr(e)); } | |
| } | |
| const portraitIdea = (p, gender) => `Natural portrait photo of a friendly ${[p.age && `${p.age}-year-old`, gender, p.job && `who is a ${p.job.toLowerCase()}`].filter(Boolean).join(' ')}, head and shoulders, soft daylight, realistic, candid smile, softly blurred background`; | |
| // own: the learner's description (the gender is still added, so the portrait matches the persona) | |
| function portraitJob(p, gender, folder, index, total, own) { | |
| return imageJob({ prompt: own ? `${own}, one ${gender} only, realistic photo` : `${portraitIdea(p, gender)}, one ${gender} only`, shape: 'square', folder, index, total, title: `Portrait of ${p.name || 'persona'}` }); | |
| } | |
| // After ✨ Draft with AI: portraits for the new personas, in one go (their gender comes with the draft). Returns a note. | |
| async function makePortraits(list) { | |
| const todo = list.filter(p => !p.portrait && p.name && (p.gender === 'woman' || p.gender === 'man')); | |
| if (!todo.length || !batchWhere()) return ''; | |
| if (queue) return ' Their portraits were not made because other pictures are still being made: press ✨ Make portrait on each card later.'; | |
| const folder = await newFolder(`Portraits ${(plan.brand || {}).name || 'personas'}`); | |
| for (const p of todo) portraitsMaking.add(p.id); | |
| renderPersonas(); | |
| runImageBatch(todo.map((p, i) => portraitJob(p, p.gender, folder, i + 1, todo.length)), { | |
| onDone: (meta, i) => { const p = todo[i]; if (p) { p.portrait = { id: meta.id, file: meta.images[0] }; portraitsMaking.delete(p.id); savePlan(); if (!$('panePersonas').hidden) renderPersonas(); } }, | |
| onFinish: q => { for (const p of todo) portraitsMaking.delete(p.id); if (!$('panePersonas').hidden) renderPersonas(); if (q.error || (!q.done.length && q.lastError)) alert(`Could not make the portraits: ${q.error || q.lastError}`); }, | |
| }); | |
| return ' Their portraits are being made.'; | |
| } | |
| // --- Explain my results ----------------------------------------------------------------------------------------------------- | |
| function resultsSummary() { | |
| const rows = results().rows.filter(r => +r.reach > 0); | |
| const inter = r => (+r.likes || 0) + (+r.comments || 0) + (+r.shares || 0) + (+r.saves || 0); | |
| const group = key => { const g = {}; for (const r of rows) { const k = r[key] || 'other'; g[k] = g[k] || { i: 0, reach: 0, n: 0, followers: 0 }; g[k].i += inter(r); g[k].reach += +r.reach; g[k].n++; g[k].followers += +r.followers || 0; } return Object.entries(g).map(([k, v]) => ({ k, er: v.i / v.reach * 100, n: v.n, reach: v.reach, followers: v.followers })).sort((a, b) => b.er - a.er); }; | |
| return { rows, byType: group('type'), byPlatform: group('platform'), best: rows.slice().sort((a, b) => inter(b) / b.reach - inter(a) / a.reach)[0], inter }; | |
| } | |
| function offlineInsights(sm) { | |
| const t = sm.byType, p = sm.byPlatform, name = id => (typeOf(id) || [id, id])[1]; | |
| const out = { headline: '', insights: [], actions: [] }; | |
| if (t.length >= 2) { | |
| const hi = t[0], lo = t[t.length - 1], x = lo.er ? hi.er / lo.er : 0; | |
| out.headline = `${name(hi.k)} posts work best: ${hi.er.toFixed(1)}% engagement${x >= 1.3 ? `, ${x.toFixed(1)}× more than ${name(lo.k).toLowerCase()} (${lo.er.toFixed(1)}%)` : ''}.`; | |
| out.actions.push(`Plan two more ${name(hi.k).toLowerCase()} posts next month.`); | |
| if (x >= 1.3) out.actions.push(`Rework ${name(lo.k).toLowerCase()} posts: ${lo.k === 'storytelling' ? 'show a real person or moment, and end with a question' : 'try a question or a short story instead'}.`); | |
| } else if (t.length) out.headline = `${name(t[0].k)} posts reach ${t[0].er.toFixed(1)}% engagement.`; | |
| if (p.length >= 2) { out.insights.push(`${p[0].k} has the best engagement (${p[0].er.toFixed(1)}%), ${p[p.length - 1].k} the lowest (${p[p.length - 1].er.toFixed(1)}%).`); out.actions.push(`Put your best content on ${p[0].k} first.`); } | |
| if (sm.best) out.insights.push(`Best post: “${sm.best.title || 'untitled'}” on ${sm.best.platform} (${(sm.inter(sm.best) / sm.best.reach * 100).toFixed(1)}%, ${(+sm.best.reach).toLocaleString()} reached).`); | |
| const fol = sm.rows.reduce((a, r) => a + (+r.followers || 0), 0), target = +((((plan.campaign || {}).metrics || []).find(m => m.id === 'followers') || {}).target || 0); | |
| if (target) out.insights.push(`Followers: +${fol} of a ${target} target (${Math.round(fol / target * 100)}%).`); | |
| return out; | |
| } | |
| async function explainResults() { | |
| const body = $('rInsightsBody'), btn = $('rExplain'); | |
| const sm = resultsSummary(); | |
| if (sm.rows.length < 2) { body.innerHTML = '<p class="muted small">Add at least two posts with their reach and interactions first.</p>'; return; } | |
| if (!aiOn()) await askCloudflare('✨ Explain my results writes an analysis with your free Cloudflare account. Connect it now, or skip and Ora works it out from your numbers.', 'Explain my results'); | |
| btn.disabled = true; const label = btn.textContent; btn.textContent = 'Looking…'; | |
| let out = null, ai = true; | |
| const facts = [`Per kind of content: ${sm.byType.map(x => `${x.k}: engagement ${x.er.toFixed(1)}% over ${x.n} posts, reach ${x.reach}`).join('; ')}`, | |
| `Per platform: ${sm.byPlatform.map(x => `${x.k}: ${x.er.toFixed(1)}%, reach ${x.reach}`).join('; ')}`, | |
| ...sm.rows.map(r => `Post "${r.title}" (${r.type}, ${r.platform}): reach ${r.reach}, likes ${r.likes}, comments ${r.comments}, shares ${r.shares}, saves ${r.saves}, followers ${r.followers}`), | |
| `Targets: ${((plan.campaign || {}).metrics || []).map(m => `${m.id} ${m.target}`).join(', ')}`].join('\n'); | |
| try { out = await window.ora.planAi('insights', facts); } catch { ai = false; out = offlineInsights(sm); } | |
| btn.disabled = false; btn.textContent = label; | |
| results().insights = { ...out, ai }; savePlan(); | |
| showInsights(); | |
| } | |
| // the last explanation stays with the results (and goes into the presentation) | |
| function showInsights() { | |
| const body = $('rInsightsBody'), out = results().insights; | |
| body.innerHTML = ''; | |
| if (!out) return; | |
| const ai = out.ai; | |
| const h = document.createElement('p'); h.className = 'ins-head'; h.textContent = out.headline; body.appendChild(h); | |
| for (const [label2, list] of [['What the numbers say', out.insights], ['What to do next month', out.actions]]) { | |
| if (!list.length) continue; | |
| const l = document.createElement('div'); l.className = 'ins-label'; l.textContent = label2; body.appendChild(l); | |
| const ul = document.createElement('ul'); for (const t of list) { const li = document.createElement('li'); li.textContent = t; ul.appendChild(li); } body.appendChild(ul); | |
| } | |
| const n = document.createElement('p'); n.className = 'muted small'; n.textContent = ai ? 'Written by AI (Cloudflare) from your numbers: check them before acting.' : `Worked out by Ora from your numbers. ${aiOn() ? 'The AI did not answer this time: press Explain my results again for a written analysis.' : 'Connect Cloudflare for a written analysis.'}`; body.appendChild(n); | |
| } | |
| $('rExplain').addEventListener('click', () => explainResults().catch(e => { $('rInsightsBody').textContent = cleanErr(e); })); | |
| // --- Remove the demo ---------------------------------------------------------------------------------------------------------- | |
| $('demoRemove').addEventListener('click', async () => { | |
| if (!confirm('Remove the demo? Its pictures leave Ora and Pictures/Ora, and the demo plan is deleted. Your own plan and pictures stay as they are. You can open the demo again any time.')) return; | |
| try { | |
| const n = await window.ora.demoRemove(); | |
| S.pictures = (await window.ora.state()).pictures; | |
| renderPicCount(); | |
| closeDemo(); | |
| $('demoOpen').title = `Demo removed (${n} pictures). Press to open it again.`; | |
| } catch (e) { alert(`Could not remove the demo: ${cleanErr(e)}`); } | |
| }); | |