'use strict';
/* global $, online, cleanErr, refreshOnline, aiOn, view, store, plan, renderConnDots, renderAutomations */
// Accounts (Settings): the user's own free Cloudflare account (AI text and pictures), and the setup page that asks for
// it when Ora starts and whenever a ✨ button needs it (it can be skipped: Ora then uses its own simple drafts); and the
// link to the user's own n8n Cloud account. The guides for each automation (Google Sheets, Gmail, LinkedIn) are here
// too, but the Automations page (automate.js) draws them.
const whenText = iso => new Date(iso).toLocaleString(undefined, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
function renderConnect() {
const cf = online.cloudflare || {}, u = online.usage || {};
$('cfOn').hidden = !cf.connected;
$('cfState').textContent = cf.connected ? `Connected · ${cf.account}` : 'Not connected';
$('cfState').classList.toggle('on', !!cf.connected);
$('cfOff').hidden = !cf.connected;
$('cfChecked').textContent = cf.checked ? `✓ Worked ${whenText(cf.checked)}` : 'Checks your Account ID and token (uses no Neurons).';
if (cf.connected && u.cloudflare) {
const used = u.cloudflare.today, left = u.cloudflare.left;
$('cfMeter').style.width = `${Math.min(100, used / 100)}%`;
$('cfUsage').textContent = `Today: ${used.toLocaleString()} of 10,000 free Neurons used, ${Math.round(left).toLocaleString()} left (about ${Math.floor(left / u.cloudflare.perImage)} pictures; AI text uses a few each). They reset at 00:00 UTC.`;
}
renderN8n();
}
// --- n8n -------------------------------------------------------------------------------------------------------------
// The accounts Ora's automation can use, in the order a course connects them; each with plain steps for n8n
const SHEET_HEAD = ['Date', 'Time', 'Platform', 'Title', 'Caption', 'Picture', 'ID'];
const N8N_ACCOUNTS = [
{ id: 'sheets', name: 'Google Sheets', does: 'adds a row for every post you send', guide: sheetsGuide },
{ id: 'gmail', name: 'Gmail reminders', does: 'an email on the morning of each post', guide: gmailGuide },
{ id: 'linkedin', name: 'LinkedIn', does: 'posts your poster and caption at the post time', guide: linkedinGuide },
];
function renderN8n() {
const n = online.n8n || {};
$('n8nOn').hidden = !n.connected;
renderAccountGuides();
$('n8nState').textContent = n.connected ? `Connected · ${n.host}` : 'Not connected';
$('n8nState').classList.toggle('on', !!n.connected);
$('n8nOff').hidden = !n.connected;
if (n.connected) {
$('n8nWhich').textContent = `Ora sends your posts to ${n.host}.`;
$('n8nChecked').textContent = n.checked ? `✓ Answered ${whenText(n.checked)}` : 'Checks that your automation in n8n answers.';
}
renderConnDots();
// the automations (Google Sheets, Gmail, LinkedIn) are drawn on their own page
if (view === 'automations') renderAutomations();
}
// --- connection guides: by place (Google Sheets, n8n, Ora), one action per numbered step, ticks, a map ----------------
const GUIDE_KEY = 'ora.n8nGuide';
const ticks = () => store(GUIDE_KEY) || {};
// the automation as the learner sees it in n8n, with the boxes to open highlighted
function automationMap(hi) {
const on = name => hi.includes(name);
const box = (x, y, w, label) => `${label}`;
const line = (x1, y1, x2, y2) => ``;
const rows = [[8, 'LinkedIn: check', 'Which accounts work'], [48, 'Gmail: check', ''], [88, 'Google Sheets: check', ''], [132, 'Google Sheets: add the rows', 'Count the posts'], [176, 'Answer: reminder set', 'Wait until the reminder time', 'Gmail: send the reminder'], [220, 'Answer: LinkedIn post set', 'Wait until the post time', 'LinkedIn: post'], [264, 'Google Sheets: find the rows', 'Which rows to delete', 'Google Sheets: delete the rows']];
let out = `${line(58, 128, 80, 128)}${box(4, 114, 54, 'Ora: …')}${box(80, 114, 132, 'What does Ora want?')}`;
for (const [y, a, b, c] of rows) {
out += line(212, 128, 236, y + 14) + box(236, y, 172, a);
if (b) out += line(408, y + 14, 428, y + 14) + box(428, y, 172, b);
if (c) out += line(600, y + 14, 616, y + 14) + box(616, y, 160, c);
}
out += line(408, 62, 428, 22) + line(408, 102, 428, 22); // every check leads to "Which accounts work"
return ``;
}
// parts: [{ where, cls, title, map: [box names], steps: [{ id, html, extra(), auto }] }]; st: what n8n reported
function guide(key, st, parts) {
const t = ticks(), done = s => !!st.ok || t[`${key}.${s.id}`] || !!s.auto;
const g = document.createElement('div'); g.className = 'guide';
let next = false;
for (const p of parts) {
const sec = document.createElement('section'); sec.className = 'g-part';
sec.innerHTML = '
';
sec.querySelector('.g-where').classList.add(p.cls); sec.querySelector('.g-where').textContent = p.where; sec.querySelector('h4 span:last-child').textContent = p.title;
if (p.map) { const m = document.createElement('div'); m.className = 'g-map'; m.innerHTML = automationMap(p.map); sec.querySelector('h4').after(m); }
for (const s of p.steps) {
const li = document.createElement('li'); li.className = `g-step${done(s) ? ' done' : ''}`;
li.innerHTML = '
';
li.querySelector('p').innerHTML = s.html;
const cb = li.querySelector('input'); cb.checked = done(s); cb.setAttribute('aria-label', 'Done');
cb.addEventListener('change', () => { const x = ticks(); x[`${key}.${s.id}`] = cb.checked; store(GUIDE_KEY, x); renderN8n(); });
if (s.extra) li.querySelector('.g-body').appendChild(s.extra());
if (!done(s) && !next) { next = true; li.classList.add('next'); }
sec.querySelector('ol').appendChild(li);
}
g.appendChild(sec);
}
return g;
}
const el = (html, cls) => { const d = document.createElement('div'); d.className = cls || 'g-extra'; d.innerHTML = html; return d; };
// a field saved in Ora (the sheet link, the email address)
function savedField(placeholder, value, save) {
const d = el(``);
const inp = d.querySelector('input'); inp.placeholder = placeholder; inp.value = value || '';
d.querySelector('button').addEventListener('click', async () => {
try { online = { ...online, ...(await save(inp.value)) }; renderN8n(); }
catch (e) { d.querySelector('.err').textContent = cleanErr(e); }
});
return d;
}
const testButton = () => {
const d = el('');
d.querySelector('button').addEventListener('click', async e => {
const b = e.currentTarget, err = d.querySelector('.err'); err.textContent = ''; b.disabled = true; b.textContent = 'Asking n8n…';
try { online = { ...online, ...(await window.ora.n8nTest()) }; renderN8n(); } catch (x) { err.textContent = cleanErr(x); }
finally { b.disabled = false; b.textContent = 'Test'; }
});
return d;
};
const switchOn = what => ({ id: 'on', html: `Switch both ${what} boxes on: click one, hold Shift and click the other, then press D. They change from faded to normal.` });
const publish = { id: 'pub', html: 'Press Save, then Publish (top right). n8n only runs the published version: do this after every change.' };
function sheetsGuide(n, st) {
return guide('sheets', st, [
{ where: 'Google Sheets', cls: 'gs', title: 'Make your sheet', steps: [
{ id: 'new', html: 'Open a new, empty Google Sheet.', extra: () => { const d = el(''); d.querySelector('button').addEventListener('click', () => window.ora.openOnline('googleSheets')); return d; } },
{ id: 'head', html: 'Click cell A1 (top left) and paste. Each heading lands in its own cell, like this:', extra: () => {
const d = el(`
${SHEET_HEAD.map((h, i) => `${h}`).join('')}
`);
d.querySelector('button').addEventListener('click', async e => { await navigator.clipboard.writeText(SHEET_HEAD.join('\t')); e.currentTarget.textContent = 'Copied ✓ Now paste in A1'; });
return d; } },
{ id: 'link', auto: !!n.sheetLink, html: 'Copy the sheet\'s link from your browser\'s address bar and paste it here:', extra: () => savedField('https://docs.google.com/spreadsheets/d/…', n.sheetLink, v => window.ora.n8nSetSheet(v)) },
] },
{ where: 'n8n', cls: 'n8', title: 'Let n8n use your Google account', map: ['Google Sheets: check', 'Google Sheets: add the rows', 'Google Sheets: find the rows', 'Google Sheets: delete the rows'], steps: [
{ id: 'cred', html: 'Double-click the box Google Sheets: check. Under Credential, choose Create new › Sign in with Google, pick your Google account and press Allow. Close the box.' },
{ id: 'rows', html: 'Double-click the box Google Sheets: add the rows. Under Credential, pick the one you just made. Check that Mapping Column Mode says Map Automatically. Close the box.' },
{ id: 'del', html: 'Do the same in Google Sheets: find the rows and Google Sheets: delete the rows: pick the same Credential. They let Ora delete a campaign\'s rows (Plan › Campaigns).' },
{ id: 'on', html: 'Switch the four Google Sheets boxes on: click one, hold Shift and click the other three, then press D. They change from faded to normal.' }, publish,
] },
{ where: 'Ora', cls: 'or', title: 'Check it', steps: [
{ id: 'test', html: st.ok ? '✓ Google Sheets works. Every post you send now adds a row to your sheet.' : 'Press Test. When it works, Google Sheets shows ✓ Connected.', extra: st.ok ? null : testButton },
] },
]);
}
function gmailGuide(n, st) {
const testMail = () => {
const d = el('');
d.querySelector('button').addEventListener('click', async e => {
const b = e.currentTarget, note = d.querySelector('span'); b.disabled = true; note.textContent = 'Asking n8n…';
try { await window.ora.n8nRemind([testReminder()]); note.textContent = `Sent: check ${n.email} in a minute (and the spam folder the first time).`; }
catch (err) { note.textContent = cleanErr(err); }
finally { b.disabled = false; }
});
return d;
};
return guide('gmail', st, [
{ where: 'Ora', cls: 'or', title: 'Where should reminders go?', steps: [
{ id: 'email', auto: !!n.email, html: 'Type the email address that should get the reminders:', extra: () => savedField('name@gmail.com', n.email, v => window.ora.n8nSetEmail(v)) },
] },
{ where: 'n8n', cls: 'n8', title: 'Let n8n send email from your Gmail', map: ['Gmail: check', 'Gmail: send the reminder'], steps: [
{ id: 'cred', html: 'Double-click the box Gmail: check. Under Credential, choose Create new › Sign in with Google, pick your Google account and press Allow. Close the box.' },
{ id: 'send', html: 'Double-click the box Gmail: send the reminder. Under Credential, pick the one you just made. Close the box.' },
switchOn('Gmail'), publish,
] },
{ where: 'Ora', cls: 'or', title: 'Check it', steps: [
{ id: 'test', html: st.ok ? '✓ Gmail works. When you send the month to n8n, each post gets a reminder on its morning.' : 'Press Test. When it works, Gmail reminders shows ✓ Connected.', extra: st.ok ? testMail : testButton },
] },
]);
}
function linkedinGuide(n, st) {
return guide('linkedin', st, [
{ where: 'n8n', cls: 'n8', title: 'Let n8n post on your LinkedIn', map: ['LinkedIn: check', 'LinkedIn: post'], steps: [
{ id: 'cred', html: 'Double-click the box LinkedIn: post. Under Credential, choose Create new › Connect my account, sign in to LinkedIn and press Allow.' },
{ id: 'post', html: 'In the same box, under Person, pick your name. Close the box. (LinkedIn: check needs no sign-in: it is only an on/off switch.)' },
switchOn('LinkedIn'), publish,
] },
{ where: 'Ora', cls: 'or', title: 'Check it', steps: [
{ id: 'test', html: st.ok ? '✓ LinkedIn works. When you send the month, each day with LinkedIn ticked and its picture made is posted at your post time.' : 'Press Test. When it works, LinkedIn shows ✓ Connected.', extra: st.ok ? null : testButton },
] },
]);
}
// a reminder for right now, so learners see what one looks like
function testReminder() {
const b = (typeof plan !== 'undefined' && plan.brand) || {};
return { remindAt: new Date(Date.now() + 5000).toISOString(), subject: 'Test from Ora: your post reminders work', text: `This is how Ora reminds you of a planned post${b.name ? ` for ${b.name}` : ''}.\n\nOn the morning of each post you will get an email like this one, with the idea, the time, the picture's name and the captions ready to copy.\n\nSent by Ora through your n8n.` };
}
// Ora stops using one account and forgets what it kept for it; the account itself stays in n8n until it is removed there
// Switching an automation to another account: a new sign-in (credential) in n8n with the other account, and in Ora
// the other sheet or email address. The old sign-in can stay in n8n or be deleted.
function switchGuide(id, n, st) {
const cred = (boxes, extra) => ({ id: 'cred', html: `Double-click the box ${boxes[0]}. Under Credential, choose Create new, then sign in with the other account${extra || ''} and press Allow. Close the box.` });
const same = (box, more) => ({ id: 'same', html: `Double-click the box ${box} and pick the new sign-in under Credential${more || ''}. Close the box.` });
const tidy = { id: 'tidy', html: 'Optional: delete the old sign-in in n8n › Overview › Credentials, if nothing else uses it.' };
const check = { where: 'Ora', cls: 'or', title: 'Check it', steps: [{ id: 'test', html: 'Press Test. It shows ✓ On when the new account works.', extra: testButton }] };
const google = ' (in Google\'s window, press Use another account if your usual one is shown)';
const parts = {
sheets: [
{ where: 'n8n', cls: 'n8', title: 'Sign in with the other Google account', map: ['Google Sheets: check', 'Google Sheets: add the rows'], steps: [cred(['Google Sheets: check'], google), same('Google Sheets: add the rows'), publish, tidy] },
{ where: 'Ora', cls: 'or', title: 'The sheet of that account', steps: [{ id: 'link', html: 'Paste the link of a sheet the other account can edit (make one with the same headings in A1 if needed):', extra: () => savedField('https://docs.google.com/spreadsheets/d/…', n.sheetLink, v => window.ora.n8nSetSheet(v)) }] },
check,
],
gmail: [
{ where: 'Ora', cls: 'or', title: 'Where should reminders go?', steps: [{ id: 'email', html: 'Change the address that gets the reminders, if you want:', extra: () => savedField('name@gmail.com', n.email, v => window.ora.n8nSetEmail(v)) }] },
{ where: 'n8n', cls: 'n8', title: 'Send from the other Gmail', map: ['Gmail: check', 'Gmail: send the reminder'], steps: [cred(['Gmail: check'], google), same('Gmail: send the reminder'), publish, tidy] },
check,
],
linkedin: [
{ where: 'LinkedIn', cls: 'li', title: 'Sign out first', steps: [{ id: 'out', html: 'n8n signs in with the LinkedIn account that is open in your browser. Sign out of LinkedIn first (or open n8n in a private window), so you can sign in with the other one.' }] },
{ where: 'n8n', cls: 'n8', title: 'Sign in with the other LinkedIn account', map: ['LinkedIn: post'], steps: [cred(['LinkedIn: post']), { id: 'same', html: 'In the same box, pick the new name under Person. Close the box.' }, publish, tidy] },
check,
],
}[id];
return guide(`switch-${id}`, {}, parts);
}
async function disconnectAccount(a) {
const kept = a.id === 'sheets' ? ' and forgets your sheet link (the sheet and its rows stay)' : a.id === 'gmail' ? ' and forgets the reminder email address. Reminders already waiting in n8n are still sent: stop them in n8n › Executions' : '';
if (!confirm(`Disconnect ${a.name}?\n\nOra stops using it${kept}. Its steps start again from 1. Later, Reconnect uses the same account again; Reset sets it up from step 1, with the same or a new account.\n\nTo remove your Google account from n8n too: in n8n, open Overview › Credentials and delete it, or switch its boxes off (select them, press D), then Save and Publish.`)) return;
online = { ...online, ...(await window.ora.n8nAccount(a.id, false)) };
const t = ticks(); for (const k of Object.keys(t)) if (k.startsWith(`${a.id}.`)) delete t[k]; store(GUIDE_KEY, t);
renderN8n();
}
async function n8nRun(btn, err, fn) {
$(err).textContent = '';
const label = btn.textContent; btn.disabled = true; btn.textContent = 'Asking n8n…';
try { online = { ...online, ...(await fn()) }; renderConnect(); }
catch (e) { $(err).textContent = cleanErr(e); if (err === 'n8nError2') $('n8nChecked').textContent = ''; } // no old ✓ next to an error
finally { btn.disabled = false; btn.textContent = label; }
}
$('n8nConnect').addEventListener('click', e => n8nRun(e.currentTarget, 'n8nError', () => window.ora.n8nTest($('n8nUrl').value)));
$('n8nRetest').addEventListener('click', e => n8nRun(e.currentTarget, 'n8nError2', () => window.ora.n8nTest()));
$('cfTest').addEventListener('click', async e => {
const btn = e.currentTarget; $('cfError2').textContent = ''; btn.disabled = true; btn.textContent = 'Checking…';
try { online = { ...online, ...(await window.ora.testCloudflare()) }; renderConnect(); }
catch (err) { $('cfError2').textContent = cleanErr(err); $('cfChecked').textContent = ''; }
finally { btn.disabled = false; btn.textContent = 'Test'; }
});
$('cfConnect').addEventListener('click', async e => {
const btn = e.currentTarget, label = btn.textContent;
$('cfError').textContent = '';
btn.disabled = true; btn.textContent = 'Checking…';
try { await window.ora.connectCloudflare($('cfAccount').value, $('cfToken').value); $('cfToken').value = ''; await refreshOnline(); renderConnect(); }
catch (err) { $('cfError').textContent = cleanErr(err); }
finally { btn.disabled = false; btn.textContent = label; }
});
for (const b of document.querySelectorAll('[data-open]')) b.addEventListener('click', () => window.ora.openOnline(b.dataset.open));
for (const b of document.querySelectorAll('[data-disconnect]')) b.addEventListener('click', async () => {
const which = b.dataset.disconnect;
if (!confirm(which === 'n8n' ? 'Disconnect n8n? Its link is removed from this computer; your automation stays in n8n.' : 'Disconnect Cloudflare? Its key is removed from this computer.')) return;
await window.ora.disconnectOnline(which); await refreshOnline(); renderConnect();
});
// --- Accounts: how to connect, step by step, with a sketch of each website page -----------------------------------
// A small drawing of a web page (not a screenshot: the real page may look a bit different), with the thing to press
// outlined. items: [x, y, w, h, text, kind ('btn' | 'field' | 'text' | 'side' | 'menu' | 'title'), outlined]
function pageSketch(url, items, color) {
const esc = t => String(t).replace(/&/g, '&').replace(/`
+ [14, 26, 38].map(x => ``).join('')
+ `${esc(url)}`;
for (const [x, y, w, h, t, kind, hi] of items) {
const fill = { btn: '#2b2b2b', field: '#fff', side: '#f6f4f0', menu: '#fff', title: 'none', text: 'none' }[kind] || 'none';
const ink = kind === 'btn' ? '#fff' : kind === 'title' ? '#1e1b18' : '#3d3832';
if (fill !== 'none') out += ``;
out += `${esc(t)}`;
if (hi) out += ``;
}
return el(`A sketch: the real page may look a bit different.`, 'g-extra g-shot-wrap');
}
const CF = '#f38020', N8 = '#ea4b71';
const cfSketch = which => () => pageSketch(...{
signup: ['dash.cloudflare.com/sign-up', [[150, 46, 220, 20, 'Create your free account', 'title'], [150, 76, 220, 24, 'Email', 'field'], [150, 108, 220, 24, 'Password', 'field'], [150, 144, 220, 28, 'Sign up', 'btn', true]]],
rest: ['dash.cloudflare.com › AI › Workers AI', [[12, 40, 110, 160, '', 'side'], [18, 50, 96, 20, 'AI', 'text'], [26, 72, 92, 20, 'Workers AI', 'text', true], [140, 46, 200, 20, 'Workers AI', 'title'], [360, 46, 140, 26, 'Use REST API', 'btn', true], [140, 86, 360, 20, 'Run AI models with a few lines of code.', 'text']]],
account: ['dash.cloudflare.com › Workers AI › REST API', [[24, 42, 300, 20, 'Get started with the REST API', 'title'], [24, 78, 90, 20, 'Account ID', 'text'], [120, 76, 300, 24, 'b4ae1c… (32 letters and numbers) ⧉', 'field', true], [24, 120, 250, 28, 'Create a Workers AI API Token', 'btn']]],
token: ['dash.cloudflare.com › API Tokens', [[24, 42, 300, 20, 'Create a Workers AI API Token', 'title'], [24, 74, 340, 24, 'Token name: Workers AI', 'field'], [24, 108, 140, 28, 'Create API Token', 'btn', true], [24, 152, 400, 24, 'Your token: Xy7… ⧉ Copy (shown only once)', 'field', true]]],
}[which], CF);
const n8nSketch = which => () => pageSketch(...{
signup: ['n8n.io', [[24, 46, 300, 20, 'Flexible AI workflow automation', 'title'], [24, 84, 170, 28, 'Get started for free', 'btn', true], [24, 130, 300, 20, 'Pick n8n Cloud (the free trial).', 'text']]],
import: ['yourname.app.n8n.cloud', [[12, 38, 110, 162, '', 'side'], [18, 48, 98, 24, 'Create workflow', 'btn', true], [140, 40, 200, 20, 'My workflow', 'title'], [470, 40, 30, 22, '⋯', 'btn', true], [330, 68, 170, 80, '', 'menu'], [336, 74, 160, 20, 'Download', 'text'], [336, 98, 160, 20, 'Import from File…', 'text', true], [336, 122, 160, 20, 'Settings', 'text']]],
publish: ['yourname.app.n8n.cloud › Ora · …', [[24, 40, 280, 20, 'Ora · Google Sheets log + … ', 'title'], [350, 38, 60, 24, 'Save', 'btn', true], [420, 38, 80, 24, 'Publish', 'btn', true], [40, 110, 120, 34, 'Ora: …', 'field'], [190, 110, 140, 34, 'What does Ora want?', 'field']]],
url: ['yourname.app.n8n.cloud › Ora: …', [[24, 40, 300, 20, 'Ora: Google Sheets log + …', 'title'], [24, 74, 90, 24, 'Test URL', 'text'], [120, 74, 110, 24, 'Production URL', 'field', true], [24, 112, 470, 26, 'https://yourname.app.n8n.cloud/webhook/ora-auto-… ⧉', 'field', true], [24, 156, 300, 20, 'POST · Respond: using Respond to Webhook node', 'text']]],
}[which], N8);
// Cloudflare's connect steps, in Accounts and on the setup page (the same ticks); last: the fields of the paste step
function cfGuide(ok, last, button) {
const g = guide('cloudflare', { ok }, [
{ where: 'Cloudflare', cls: 'cf', title: 'Make your free account and a key', steps: [
{ id: 'signup', html: 'Make a free Cloudflare account (or log in). ', extra: cfSketch('signup') },
{ id: 'rest', html: 'In the menu on the left, open AI › Workers AI, then press Use REST API. ', extra: cfSketch('rest') },
{ id: 'account', html: 'Copy your Account ID (the copy icon next to it).', extra: cfSketch('account') },
{ id: 'token', html: 'Press Create a Workers AI API Token, then Create API Token, and copy the token. Cloudflare shows it only once.', extra: cfSketch('token') },
] },
{ where: 'Ora', cls: 'or', title: 'Paste them here', steps: [
{ id: 'paste', html: `Paste the Account ID and the token below, and press ${button}. Ora checks them with Cloudflare.`, extra: last },
] },
]);
for (const b of g.querySelectorAll('[data-go]')) b.addEventListener('click', () => window.ora.openOnline(b.dataset.go));
return g;
}
// n8n's connect steps, in Accounts and on the n8n setup page (the same ticks); last: the fields of the paste step
function n8nGuide(ok, last) {
const g = guide('n8nacc', { ok }, [
{ where: 'n8n', cls: 'n8', title: 'Make your free account', steps: [
{ id: 'signup', html: 'Make a free n8n Cloud account (or log in). ', extra: n8nSketch('signup') },
] },
{ where: 'Ora', cls: 'or', title: 'Save Ora\'s automation', steps: [
{ id: 'save', html: 'Save Ora\'s automation file. It holds all of Ora\'s automations (Google Sheets, Gmail reminders, LinkedIn posts).', extra: () => fileSave('Save Ora\'s automation', 'ghost') },
] },
{ where: 'n8n', cls: 'n8', title: 'Bring it into n8n', steps: [
{ id: 'import', html: 'Press Create workflow, then ⋯ (top right) › Import from File…, and pick the file you saved.', extra: n8nSketch('import') },
{ id: 'publish', html: 'Press Save, then Publish (top right).', extra: n8nSketch('publish') },
{ id: 'url', html: 'Double-click the first box (Ora: …), open Production URL and copy the link.', extra: n8nSketch('url') },
] },
{ where: 'Ora', cls: 'or', title: 'Paste the link here', steps: [
{ id: 'paste', html: 'Paste the link below and press Connect n8n. Then set up what it does on the Automations page.', extra: last },
] },
]);
for (const b of g.querySelectorAll('[data-go]')) b.addEventListener('click', () => window.ora.openOnline(b.dataset.go));
return g;
}
const renderN8nSetupGuide = () => $('ndGuide').replaceChildren(n8nGuide(false, () => { const d = $('ndFields'); d.hidden = false; return d; }));
const renderSetupGuide = () => $('suGuide').replaceChildren(cfGuide(false, () => { const d = $('suFields'); d.hidden = false; return d; }, 'Connect Cloudflare'));
function renderAccountGuides() {
const cf = online.cloudflare || {}, n = online.n8n || {};
const fields = id => () => { const d = $(id); d.hidden = false; return d; };
const done = text => () => el(`✓ ${text}`);
$('cfGuide').replaceChildren(cfGuide(!!cf.connected, cf.connected ? done('Connected') : fields('cfFields'), 'Connect Cloudflare'));
$('n8nGuide').replaceChildren(n8nGuide(!!n.connected, n.connected ? done('Connected') : fields('n8nFields')));
if ($('setupDlg').open) renderSetupGuide(); // a tick there moves its next step too
if ($('n8nDlg').open) renderN8nSetupGuide();
for (const b of document.querySelectorAll('#cfGuide [data-go], #n8nGuide [data-go]')) b.addEventListener('click', () => window.ora.openOnline(b.dataset.go));
// closed by default: the learner opens the steps when wanted
for (const [k, on, n2] of [['cf', !!cf.connected, 5], ['n8n', !!n.connected, 6]]) $(`${k}Steps`).querySelector('summary').textContent = on ? 'Show the steps again' : `How to connect (${n2} steps)`;
}
// --- the setup page ---------------------------------------------------------------------------------------------------
let setupAnswer = null; // resolves the open askCloudflare: true once connected, false when skipped
const SETUP_START = 'Connect your free Cloudflare account to get AI drafts, captions and pictures. It takes about two minutes. You can also skip it and start with your plan.';
// true when Cloudflare is connected (now, or on this page); false when the person skips it
function askCloudflare(why, title) {
if (aiOn()) return Promise.resolve(true);
$('setupTitle').textContent = title || 'Connect Cloudflare';
$('setupWhy').textContent = why || SETUP_START;
$('suError').textContent = '';
renderSetupGuide();
if (!$('setupDlg').open) $('setupDlg').showModal();
// start at the top of the steps (no focus in the fields, which would scroll past steps 1-4)
setTimeout(() => { $('setupDlg').scrollTop = 0; const f = $('setupDlg').querySelector('.setup-form'); if (f) f.scrollTop = 0; }, 30);
return new Promise(resolve => { if (setupAnswer) setupAnswer(false); setupAnswer = resolve; });
}
function closeSetup(ok) { if ($('setupDlg').open) $('setupDlg').close(); const r = setupAnswer; setupAnswer = null; if (r) r(ok); }
$('suConnect').addEventListener('click', async e => {
const btn = e.currentTarget, label = btn.textContent;
$('suError').textContent = '';
btn.disabled = true; btn.textContent = 'Checking…';
try {
await window.ora.connectCloudflare($('suAccount').value, $('suToken').value);
$('suToken').value = '';
await refreshOnline();
if (view === 'connect') renderConnect();
closeSetup(true);
} catch (err) { $('suError').textContent = cleanErr(err); }
finally { btn.disabled = false; btn.textContent = label; }
});
$('suSkip').addEventListener('click', () => closeSetup(false));
$('setupDlg').addEventListener('cancel', e => { e.preventDefault(); closeSetup(false); });
// --- the n8n setup page: when it is needed (Send to n8n, the calendar's hint, later the Automate step) ---------------
let n8nAnswer = null; // resolves the open askN8n: true once connected, false when skipped
function askN8n(why) {
if (online.n8n && online.n8n.connected) return Promise.resolve(true);
$('n8nDlgWhy').textContent = why || 'Connect your own n8n account once: then Ora can send your posts to it.';
$('ndError').textContent = '';
renderN8nSetupGuide();
if (!$('n8nDlg').open) $('n8nDlg').showModal();
setTimeout(() => { $('n8nDlg').scrollTop = 0; }, 30); // start at step 1
return new Promise(resolve => { if (n8nAnswer) n8nAnswer(false); n8nAnswer = resolve; });
}
function closeN8n(ok) { if ($('n8nDlg').open) $('n8nDlg').close(); const r = n8nAnswer; n8nAnswer = null; if (r) r(ok); }
$('ndConnect').addEventListener('click', async e => {
const btn = e.currentTarget, label = btn.textContent;
$('ndError').textContent = ''; btn.disabled = true; btn.textContent = 'Asking n8n…';
try { online = { ...online, ...(await window.ora.n8nTest($('ndUrl').value)) }; renderConnDots(); if (view === 'connect') renderConnect(); closeN8n(true); }
catch (err) { $('ndError').textContent = cleanErr(err); }
finally { btn.disabled = false; btn.textContent = label; }
});
$('ndSkip').addEventListener('click', () => closeN8n(false));
$('n8nDlg').addEventListener('cancel', e => { e.preventDefault(); closeN8n(false); });