Ora / app /renderer /base.js
umer-wasim's picture
Ora 0.6.0: Automations with your own n8n, Campaigns, step-by-step setup
6acd609 verified
Raw History Blame Contribute Delete
19.6 kB
'use strict';
/* global renderPlan, renderPictures, renderConnect, renderAutomations, renderCourseSteps, brandVoice, mainPersona */
// Ora renderer, shared parts: helpers, the poster drawer, caption helpers, views, and the picture queue
// (one picture at a time on Cloudflare).
const $ = id => document.getElementById(id);
const MIN = s => s < 90 ? `${Math.round(s)} s` : s < 5400 ? `${Math.round(s / 60)} min` : `${(s / 3600).toFixed(1)} h`;
const cleanErr = e => String(e && e.message || e).replace(/^Error invoking remote method '[^']+': (Error: )?/, '');
function store(k, v) { try { if (v === undefined) return JSON.parse(localStorage.getItem(k)); localStorage.setItem(k, JSON.stringify(v)); } catch { return undefined; } }
let S = { pictures: [], version: '', picDir: '', docDir: '' }; // state from main
let online = { cloudflare: { connected: false }, n8n: { connected: false }, usage: {} };
// the brand as pictures and captions use it (from Plan › Brand, see applyBrand in plan.js)
let brand = { on: false, name: '', words: '', colors: '', avoid: '' };
const picSrc = (id, file) => `ora://pic/${encodeURIComponent(id)}/${encodeURIComponent(file)}`;
const findPic = id => S.pictures.find(p => p.id === id);
// the finished poster (with its text) when there is one, else the picture itself
const thumbOf = meta => picSrc(meta.id, (meta.posterImages || [])[0] || meta.images[0]);
const picLabel = meta => `${meta.poster ? (meta.poster.carousel ? 'Carousel' : 'Poster') : 'Picture'}: ${((meta.poster && meta.poster.title) || (meta.project ? meta.project.title : meta.prompt || '')).slice(0, 60)}`;
// --- posters: the text drawn over a picture -------------------------------------------------------------------------
const POSTER_SIZES = { linkedin: [1200, 627], insta: [1080, 1350], portrait: [1080, 1920], square: [1080, 1080], landscape: [1920, 1080] };
const POSTER_FONTS = {
modern: { family: '"Helvetica Neue", Helvetica, Arial, sans-serif', weight: 800 },
serif: { family: 'Georgia, "Times New Roman", serif', weight: 700 },
display: { family: '"Space Grotesk", "Helvetica Neue", Arial, sans-serif', weight: 700 },
};
// where the picture should leave room for the words (added to the picture prompt)
const POSTER_SPACE = {
top: 'with a clean, empty, uncluttered area across the top third for a headline',
band: 'with the main subject in the upper part and calm empty space along the bottom',
card: 'with a soft, uncluttered background around the centre',
left: 'with the main subject on the right side and empty space on the left',
};
const NO_TEXT = 'no text, no letters, no words, no numbers, no typography, no logos, no watermark';
function loadImg(src) {
return new Promise((resolve, reject) => { const i = new Image(); i.crossOrigin = 'anonymous'; i.onload = () => resolve(i); i.onerror = reject; i.src = src; });
}
function wrapLines(ctx, text, maxW) {
const out = [];
for (const para of String(text).split(/\n/)) {
let line = '';
for (const word of para.split(/\s+/).filter(Boolean)) {
const t = line ? `${line} ${word}` : word;
if (ctx.measureText(t).width > maxW && line) { out.push(line); line = word; } else line = t;
}
if (line) out.push(line);
}
return out;
}
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath();
}
function luminance(hex) { const n = parseInt(hex.slice(1), 16); const [r, g, b] = [n >> 16, (n >> 8) & 255, n & 255]; return (0.299 * r + 0.587 * g + 0.114 * b) / 255; }
// Draws one poster: picture (cover-cropped), a layer that keeps text readable, title (auto-sized, at most 3 lines),
// subtitle, details, a button and the logo.
async function drawPoster(canvas, img, spec, logoImg) {
const [W, H] = POSTER_SIZES[spec.format] || POSTER_SIZES.insta;
canvas.width = W; canvas.height = H;
const ctx = canvas.getContext('2d');
const sc = Math.max(W / img.width, H / img.height);
ctx.drawImage(img, (W - img.width * sc) / 2, (H - img.height * sc) / 2, img.width * sc, img.height * sc);
if (spec.font === 'display') { try { await document.fonts.load('700 40px "Space Grotesk"'); } catch { } }
const F = POSTER_FONTS[spec.font] || POSTER_FONTS.modern;
const font = (size, w = F.weight) => `${w} ${Math.round(size)}px ${F.family}`;
const m = Math.round(Math.min(W, H) * 0.07);
const L = spec.layout || 'top';
const boxW = L === 'left' ? W * 0.5 : L === 'card' ? W * 0.74 : W - 2 * m;
const align = L === 'left' ? 'left' : 'center';
// title: start large and shrink until it fits
let ts = Math.min(W, H) * (W > H ? 0.075 : 0.095), tl;
const maxLines = spec.maxLines || 3;
for (;;) { ctx.font = font(ts); tl = wrapLines(ctx, spec.title || '', boxW); if (tl.length <= maxLines || ts < 24) break; ts *= 0.9; }
const blocks = [];
if (tl.length) blocks.push({ lines: tl, size: ts, weight: F.weight, gap: ts * 0.35, lh: 1.08 });
if (spec.sub) { ctx.font = font(ts * 0.46, 500); blocks.push({ lines: wrapLines(ctx, spec.sub, boxW), size: ts * 0.46, weight: 500, gap: ts * 0.4, lh: 1.25 }); }
if (spec.details) { ctx.font = font(ts * 0.33, 500); blocks.push({ lines: wrapLines(ctx, spec.details, boxW), size: ts * 0.33, weight: 500, gap: ts * 0.45, lh: 1.4 }); }
const ctaSize = ts * 0.34, ctaH = spec.cta ? ctaSize * 2.3 : 0;
const textH = blocks.reduce((a, b) => a + b.lines.length * b.size * b.lh + b.gap, 0) + ctaH;
// readability layer + where the text block starts
let x0 = L === 'left' ? m : (W - boxW) / 2, y0, color = '#ffffff';
if (L === 'top') {
const g = ctx.createLinearGradient(0, 0, 0, H * 0.62); g.addColorStop(0, 'rgba(10,8,20,.72)'); g.addColorStop(1, 'rgba(10,8,20,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H * 0.62); y0 = m * 1.2;
} else if (L === 'band') {
const bh = Math.max(H * 0.3, textH + m * 1.6), by = H - bh;
ctx.fillStyle = spec.accent; ctx.globalAlpha = 0.94; ctx.fillRect(0, by, W, bh); ctx.globalAlpha = 1;
color = luminance(spec.accent) > 0.62 ? '#1c1530' : '#ffffff'; y0 = by + (bh - textH) / 2;
} else if (L === 'card') {
const ch = textH + m * 1.6, cy = (H - ch) / 2;
ctx.fillStyle = 'rgba(255,255,255,.92)'; roundRect(ctx, x0 - m * 0.8, cy, boxW + m * 1.6, ch, m * 0.5); ctx.fill();
color = '#1c1530'; y0 = cy + m * 0.8;
} else {
const g = ctx.createLinearGradient(0, 0, W * 0.75, 0); g.addColorStop(0, 'rgba(10,8,20,.78)'); g.addColorStop(1, 'rgba(10,8,20,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, W * 0.75, H); y0 = (H - textH) / 2;
}
ctx.textAlign = align; ctx.textBaseline = 'top'; ctx.fillStyle = color;
if (color === '#ffffff' && L !== 'band') { ctx.shadowColor = 'rgba(0,0,0,.35)'; ctx.shadowBlur = ts * 0.15; }
const tx = align === 'center' ? W / 2 : x0;
let y = y0;
for (const b of blocks) {
ctx.font = font(b.size, b.weight);
for (const line of b.lines) { ctx.fillText(line, tx, y); y += b.size * b.lh; }
y += b.gap;
}
ctx.shadowBlur = 0;
if (spec.cta) {
ctx.font = font(ctaSize, 700);
const tw = ctx.measureText(spec.cta).width, bw = tw + ctaSize * 2, bx = align === 'center' ? (W - bw) / 2 : x0;
const onBand = L === 'band';
ctx.fillStyle = onBand ? color : spec.accent; roundRect(ctx, bx, y, bw, ctaH * 0.82, ctaH * 0.41); ctx.fill();
ctx.fillStyle = onBand ? spec.accent : (luminance(spec.accent) > 0.62 ? '#1c1530' : '#ffffff');
ctx.textAlign = 'center'; ctx.fillText(spec.cta, bx + bw / 2, y + (ctaH * 0.82 - ctaSize) / 2);
}
if (spec.page) {
// carousel: "2/5" in the top corner and a swipe hint on every slide but the last
const ps = Math.min(W, H) * 0.032;
ctx.font = font(ps, 700); ctx.textBaseline = 'middle'; ctx.textAlign = 'center'; ctx.shadowBlur = 0;
const pw = ctx.measureText(spec.page).width + ps * 1.6, ph = ps * 2;
ctx.fillStyle = 'rgba(20,14,34,.55)'; roundRect(ctx, W - m * 0.6 - pw, m * 0.6, pw, ph, ph / 2); ctx.fill();
ctx.fillStyle = '#fff'; ctx.fillText(spec.page, W - m * 0.6 - pw / 2, m * 0.6 + ph / 2);
if (spec.swipe) {
const sw = ctx.measureText('Swipe →').width + ps * 1.6;
const sy = L === 'band' ? m * 0.6 + ph * 1.4 : H - m * 0.6 - ph;
ctx.fillStyle = spec.accent; roundRect(ctx, W - m * 0.6 - sw, sy, sw, ph, ph / 2); ctx.fill();
ctx.fillStyle = luminance(spec.accent) > 0.62 ? '#1c1530' : '#fff'; ctx.fillText('Swipe →', W - m * 0.6 - sw / 2, sy + ph / 2);
}
}
if (logoImg) {
const lw = Math.min(W, H) * 0.16, lh = lw * logoImg.height / logoImg.width;
const lx = L === 'left' ? m : W - m - lw, ly = L === 'top' || L === 'left' ? H - m - lh : m;
ctx.drawImage(logoImg, lx, ly, lw, lh);
}
}
// one slide of a carousel: the cover keeps the subtitle, the last slide gets the button; all show "2/5"
function slideSpec(spec, i, n) {
if (!spec.carousel) return spec;
const slides = spec.slides || [];
return { ...spec, title: slides[i] || '', sub: i === 0 ? spec.sub : '', details: '', cta: i === n - 1 ? spec.cta : '', page: `${i + 1}/${n}`, swipe: i < n - 1, maxLines: i === 0 ? 3 : 5 };
}
// --- captions ------------------------------------------------------------------------------------------------------
const TAG_COUNT = { instagram: 10, facebook: 3, linkedin: 4 };
const STOP = new Set('a an the and or but with for from into onto over under on in at to of by as is are be this that these those your our their its it you we they very more most slow slowly soft clean close shot camera light lighting background style look premium professional high detail details photography product photo image picture frame scene shows show using use new one two three'.split(' '));
// the text Ora knows about a picture: its prompt (without the poster and style phrases), the poster text, the brand
function itemContext(meta, extra = {}) {
const firstPart = String(meta.prompt || '').split(/,\s*(with a clean, empty|with the main subject|with a soft, uncluttered|no text, no letters)/i)[0];
const p = meta.poster || {};
const v = brandVoice() || {};
return {
about: (extra.about || firstPart).slice(0, 600), title: extra.title || p.title || (meta.project ? meta.project.title : ''), offer: extra.offer || p.sub || '', cta: extra.cta || p.cta || '',
brand: v.brand || (brand.on ? brand.name : ''), tone: v.tone || (brand.on ? brand.words : ''), audience: extra.audience || mainPersona(),
};
}
function filesOf(meta) {
if (meta.poster && meta.posterFiles && meta.posterFiles.length) return meta.posterFiles.filter(Boolean);
return (meta.savedFiles || []).filter(Boolean);
}
function hashtags(ctx, n) {
const words = `${ctx.brand} ${ctx.title} ${ctx.about}`.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, ' ').split(/\s+/).filter(w => w.length > 3 && !STOP.has(w));
const out = [];
if (ctx.brand) out.push(`#${ctx.brand.replace(/[^\p{L}\p{N}]/gu, '')}`);
for (const w of words) { const t = `#${w.replace(/-/g, '')}`; if (!out.includes(t)) out.push(t); if (out.length >= n) break; }
return out.join(' ');
}
// Ora's own caption, used offline or when the online writer declines: built only from the facts it has
function offlineCaption(ctx, platform) {
const sentence = t => { t = String(t || '').trim(); if (!t) return ''; t = t.charAt(0).toUpperCase() + t.slice(1); return /[.!?]$/.test(t) ? t : `${t}.`; };
const hook = sentence(ctx.title) || sentence(ctx.about.split(/[.;]/)[0]);
const desc = ctx.about.split(/[.;]/)[0].trim();
const more = ctx.title && desc && !desc.toLowerCase().startsWith(ctx.title.toLowerCase().replace(/[.!?]$/, '')) ? sentence(desc.slice(0, 180)) : '';
const body = [ctx.offer && sentence(ctx.offer), more].filter(Boolean).join(' ');
const cta = ctx.cta ? ctx.cta.replace(/[.!]$/, '') : '';
const tags = hashtags(ctx, TAG_COUNT[platform]);
if (platform === 'instagram') return [`${hook} ✨`, body, cta && `👉 ${cta}`, tags].filter(Boolean).join('\n\n');
if (platform === 'facebook') return [hook, [body, cta && `${cta}.`].filter(Boolean).join(' '), tags].filter(Boolean).join('\n\n');
return [hook, body, cta && `${cta}.`, tags].filter(Boolean).join('\n\n');
}
// --- views ---------------------------------------------------------------------------------------------------------
let view = 'plan';
const VIEW_TITLES = { pictures: ['Your work', 'Pictures'], connect: ['Settings', 'Accounts'], automations: ['Settings', 'Automations'] };
function showView(v) {
view = v;
for (const [name, id] of [['plan', 'planView'], ['pictures', 'picturesView'], ['connect', 'connectView'], ['automations', 'automationsView']]) $(id).hidden = name !== v;
for (const b of document.querySelectorAll('.side-nav [data-view]')) b.setAttribute('aria-current', String(b.dataset.view === v));
$('demoBar').hidden = v !== 'plan';
if (VIEW_TITLES[v]) { $('topKicker').textContent = VIEW_TITLES[v][0]; $('topTitle').textContent = VIEW_TITLES[v][1]; }
if (v === 'plan') renderPlan(); else if (typeof renderCourseSteps === 'function') renderCourseSteps();
if (v === 'pictures') renderPictures();
if (v === 'connect') { renderConnect(); refreshOnline().then(renderConnect); } // fresh Neurons count
if (v === 'automations') renderAutomations();
$('main').scrollTop = 0;
}
for (const b of document.querySelectorAll('[data-view]')) b.addEventListener('click', () => showView(b.dataset.view));
document.addEventListener('click', e => { const g = e.target.closest('[data-go]'); if (g) showView(g.dataset.go); });
// --- online state --------------------------------------------------------------------------------------------------
async function refreshOnline() {
try { online = await window.ora.onlineStatus(); } catch { }
renderConnDots();
return online;
}
function renderConnDots() {
const box = $('connDots'); box.innerHTML = '';
for (const [w, label] of [['cloudflare', 'Cloudflare'], ['n8n', 'n8n']]) {
const d = document.createElement('i'); d.className = online[w] && online[w].connected ? 'on' : ''; d.title = `${label}: ${online[w] && online[w].connected ? 'connected' : 'not connected'}`; box.appendChild(d);
}
// one dot per automation: on when it works (and is not disconnected in Ora)
const auto = $('autoDots'); auto.innerHTML = '';
const n = online.n8n || {};
for (const [id, label] of [['sheets', 'Google Sheets'], ['gmail', 'Gmail reminders'], ['linkedin', 'LinkedIn posts']]) {
const on = n.connected && ((n.accounts || {})[id] || {}).ok && !(n.off || {})[id];
const d = document.createElement('i'); d.className = on ? 'on' : ''; d.title = `${label}: ${on ? 'on' : 'not set up'}`; auto.appendChild(d);
}
}
const aiOn = () => !!(online.cloudflare && online.cloudflare.connected);
// Marks the fields that must be filled first (a red outline and a note under each, cleared as soon as one is typed
// in) and moves to the first one.
function needFields(ids, why) {
for (const el of document.querySelectorAll('.need')) el.classList.remove('need');
for (const el of document.querySelectorAll('.need-note')) el.remove();
for (const id of ids) {
const el = $(id), field = el.closest('.field') || el.parentNode;
const note = document.createElement('span'); note.className = 'need-note'; note.textContent = why;
field.classList.add('need'); field.appendChild(note);
el.addEventListener('input', () => { field.classList.remove('need'); note.remove(); }, { once: true });
}
const first = $(ids[0]);
first.scrollIntoView({ behavior: 'smooth', block: 'center' });
first.focus({ preventScroll: true });
}
// --- the picture queue ---------------------------------------------------------------------------------------------
let queue = null; // { jobs, where, index, done, failed, cancelled, error, onDone, onFinish } while pictures are made
// pictures are made on Cloudflare when it is connected
function batchWhere() { return online.cloudflare.connected ? 'cloudflare' : null; }
// time before starting: seconds each, and the free Neurons they use
function batchCost(n) { return `about ${MIN(Math.max(10, n * 8))} on Cloudflare, using about ${Math.round(n * 58)} of your 10,000 free Neurons today`; }
// jobs: picture jobs (plan-make.js imageJob); onDone(meta, i) after each picture, onFinish(q) at the end
function runImageBatch(jobs, { onDone, onFinish } = {}) {
if (queue) throw new Error('Pictures are already being made. Wait until they are finished, or press Stop at the top.');
const where = jobs[0] && jobs[0].runOn;
if (!where) throw new Error('Connect Cloudflare (free, in Settings › Accounts) to make pictures.');
queue = { jobs, where, index: 0, done: [], failed: 0, cancelled: false, error: null, onDone, onFinish };
renderActivity();
window.ora.startImages(jobs[0]);
return queue;
}
function renderActivity() {
const q = queue;
$('activity').hidden = !q;
if (!q) return;
const n = q.jobs.length, k = q.done.length;
$('activityText').textContent = `Making picture ${Math.min(k + q.failed + 1, n)} of ${n} · Cloudflare`;
$('activityStop').disabled = q.cancelled;
}
$('activityStop').addEventListener('click', () => { if (!queue) return; queue.cancelled = true; window.ora.cancel(); renderActivity(); $('activityText').textContent = 'Stopping…'; });
// job:end messages are handled one after another, so onDone (which saves posters) finishes before the next starts
let endChain = Promise.resolve();
window.ora.onJobEnd(r => { endChain = endChain.then(() => onJobEnd(r)).catch(e => console.error(e)); });
const FATAL = /Neurons|allowance|did not accept|not connected|already being made/i;
async function onJobEnd(r) {
const q = queue;
if (!q) return;
if (r.meta && r.done) {
S.pictures.unshift(r.meta);
q.done.push(r.meta);
const i = (r.meta.project ? r.meta.project.index : q.done.length) - 1;
if (q.onDone) { try { await q.onDone(r.meta, i); } catch (e) { console.error(e); } }
} else if (r.cancelled) q.cancelled = true;
else if (r.error) { if (FATAL.test(r.error)) q.error = r.error; else { q.failed++; q.lastError = r.error; } }
q.index++;
if (q.cancelled || q.error || q.index >= q.jobs.length) finishQueue();
else { renderActivity(); window.ora.startImages(q.jobs[q.index]); }
}
function finishQueue() {
const q = queue;
queue = null;
renderActivity(); renderPicCount();
if (q && !q.error && q.failed && !q.done.length) q.error = q.lastError;
if (q && q.onFinish) q.onFinish(q);
if (view === 'pictures') renderPictures();
}
// a ✕ after suggestion chips that clears them without picking one
function addDismiss(box) {
const x = document.createElement('button'); x.type = 'button'; x.className = 'dismiss'; x.textContent = '✕'; x.title = 'None of these'; x.setAttribute('aria-label', 'Clear these suggestions');
x.addEventListener('click', () => { box.innerHTML = ''; });
box.appendChild(x);
}
function renderPicCount() { const n = S.pictures.filter(p => !/^upload-/.test(p.id)).length; $('picCount').textContent = n ? String(n) : ''; }