umer-wasim commited on
Commit
96f5313
·
verified ·
1 Parent(s): 7ce1491

0.3.0: Plan, Post and n8n, classroom guide

Browse files
CLASSROOM.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Running Ora in class
2
+
3
+ A guide for trainers using Ora in a marketing course, for example a three-day "Digital Marketing for Beginners" course. Each participant builds a campaign for their own brand in Ora: brand identity, personas, campaign, 30-day calendar, content, captions, results and a final presentation.
4
+
5
+ ## Before the course
6
+
7
+ **Each laptop** (macOS, Windows or Linux; 8 GB of memory is enough for the class setup below):
8
+
9
+ 1. Install Ora with one command from [the Ora page](https://devseis-ora.static.hf.space): Terminal on macOS/Linux, PowerShell on Windows.
10
+ - Windows may show "Windows protected your PC": click **More info › Run anyway** (Ora is not yet code-signed).
11
+ - On macOS, the first time Ora stores a password for an online service, macOS may ask for the login keychain password. That is normal.
12
+ 2. On the first screen, press **Skip: plan and make pictures online**. The video models (about 12 GB) are not needed for the course; they can be downloaded later in **Models**.
13
+ 3. Ask every participant to make a free **Cloudflare** account and connect it in **Online › Cloudflare Workers AI** (Account ID + an API token with the Workers AI permission). With it:
14
+ - pictures, posters and carousels take a few seconds;
15
+ - captions, content ideas, campaign names and taglines are written by an AI text model;
16
+ - each account has about 170 pictures a day for free, which is plenty for a class.
17
+ Without Cloudflare, Ora still works: it writes simpler captions and ideas itself, and pictures need the local image model (6.7 GB, slow on laptops without a graphics card).
18
+
19
+ **Trainer's laptop** (for the demos): download the **Fast** video model in **Models** the day before (6.5 GB), and set up n8n for the Day 3 demo (see below).
20
+
21
+ ## The three days in Ora
22
+
23
+ | Course | In Ora | Exercise output |
24
+ |---|---|---|
25
+ | **Day 1 · Brand** | **Plan › 1 · Brand**: name, offer, mission (✨ Suggest), values, personality, tone, tagline (✨ Suggest), colours, font, logo. No brand yet? **Start from an example** (café, fitness trainer, clothing brand, startup, personal brand). | **Save Brand Identity Summary** → PNG + PDF in Documents/Ora |
26
+ | **Day 1 · Audience** | **Plan › 2 · Personas**: two personas with needs, frustrations, motivations and where they are online. **Make a portrait in Create** makes a picture for each one (with Cloudflare: seconds). Mark one as **Main**. | Two persona cards (in the summary) |
27
+ | **Day 1 · Presence** | The personas' "where they find brands online" becomes the *Where we will be online* slide. | Digital presence map (slide) |
28
+ | **Day 2 · Campaign** | **Plan › 3 · Campaign**: name and key message (✨ Suggest), goal, value proposition, offer, call to action, channels. The **funnel** has one piece of content per step; **Make it in Create** prepares each one (video ad, carousel, offer poster). Pick **3 success metrics** with targets. | Campaign name, goal, message, funnel |
29
+ | **Day 2 · Content** | **Plan › 4 · Calendar**: **✨ Suggest ideas** (10+ ideas across the five content types), add your own, then **Fill the month**. Click a day to change it, **Make it in Create**, attach content and write captions. **Export** to Google Sheets (CSV) or a calendar (.ics). | 10 content ideas and a 30-day calendar |
30
+ | **Day 2/3 · Making** | **Create**: posters and carousels (Ora writes your exact text over the picture), pictures, and **Templates**. In Templates, choose **For: (persona)** so the shots and captions speak to them. Video: trainer demo, or Online (Kaggle/Colab) for participants who want it. | 2–3 finished posts |
31
+ | **Day 3 · Captions** | **Post…** on any picture, poster, carousel, video or ad: captions for Instagram, Facebook and LinkedIn in the brand's tone, for the chosen persona. | Two AI captions |
32
+ | **Day 3 · Automation** | **Online › n8n automation**: Ora sends each post (file, captions, time) to n8n, which waits until the post time and posts it, or logs it in a Google Sheet. | One task automated (demo) |
33
+ | **Day 3 · Analytics** | **Plan › 5 · Results**: add the posts (or **Add posts from the calendar**), type the numbers from Instagram/Facebook/LinkedIn insights or import a CSV. Ora works out engagement rate, progress to each target, the best post and the best kind of content. | Three success metrics, measured |
34
+ | **Day 3 · Presentation** | **Plan › 6 · Presentation**: one click makes the deck as **PDF** or **PowerPoint (.pptx)** to edit: title, brand identity, personas, presence, campaign and funnel, content plan, calendar, examples (including ads), metrics. | Final campaign presentation |
35
+
36
+ Participants can **Save my plan to a file** (Plan › 1 · Brand) to hand it in or continue on another computer, and **Open a plan file…** to load it again.
37
+
38
+ ## The n8n demo (Day 3)
39
+
40
+ 1. Run n8n on the trainer's laptop with Docker:
41
+ `docker run -it --rm -p 5678:5678 docker.n8n.io/n8nio/n8n`
42
+ then open http://localhost:5678 (or use an n8n Cloud trial).
43
+ 2. In Ora: **Online › n8n automation › Save the ready-made workflow**. In n8n: **Workflows › Import from file**, pick *Ora to social media (n8n workflow).json*.
44
+ 3. Read the yellow note in the workflow. For a demo you do not need any account: activate the workflow as it is, copy the **Production URL** of *Ora sends a post* into Ora and press **Test**.
45
+ 4. In Ora, press **Post…** on a poster, choose a time two minutes ahead and **Send to n8n**. In n8n › Executions, show the post *waiting*, then running at its time.
46
+ 5. To post for real, connect LinkedIn, a Facebook Page, Instagram (via a free Cloudinary account) or Google Sheets as the note explains, and switch those steps on.
47
+
48
+ ## Good to know
49
+
50
+ - **Speed:** with Cloudflare, a picture takes seconds. On a laptop's processor, a local picture takes minutes and a video much longer, so keep video for demos or Online.
51
+ - **Cloudflare's safety filter** refuses adult content. Ora shows a plain message; reword the prompt.
52
+ - **Privacy:** plans, pictures and videos stay on the laptop. Prompts sent to Cloudflare (pictures, captions, suggestions) go to Cloudflare; posts sent to n8n go to the trainer's or participant's own n8n.
53
+ - **Disk:** keep about 5 GB free for the class setup (more if video models are downloaded).
54
+ - Each participant's work is saved in Movies/Videos › Ora, Pictures › Ora and Documents › Ora.
NOTICE CHANGED
@@ -49,6 +49,10 @@ Enhance (Sharper / Smoother)
49
  runs with ONNX Runtime Web (MIT) on your computer.
50
  rife-ncnn-vulkan 20221029 — MIT (nihui), with the RIFE v4.6 model (MIT, hzwer/Practical-RIFE); ncnn — BSD-3-Clause.
51
 
 
 
 
 
52
  Online GPU (optional, your own accounts)
53
  The Ora GPU worker (space/worker/ora_worker.py, Apache-2.0) runs in Kaggle or Google Colab notebooks you start.
54
  Colab connections use a Cloudflare quick tunnel (cloudflared, Apache-2.0, downloaded inside the notebook).
 
49
  runs with ONNX Runtime Web (MIT) on your computer.
50
  rife-ncnn-vulkan 20221029 — MIT (nihui), with the RIFE v4.6 model (MIT, hzwer/Practical-RIFE); ncnn — BSD-3-Clause.
51
 
52
+ Plan and posting
53
+ pptxgenjs 4.0.1 — MIT (PowerPoint export), bundled as renderer/vendor/pptx.js with JSZip (MIT or GPL-3.0, used under MIT).
54
+ The n8n workflow (app/n8n/ora-social-posting.json) is part of Ora (Apache-2.0); n8n itself is under the Sustainable Use License.
55
+
56
  Online GPU (optional, your own accounts)
57
  The Ora GPU worker (space/worker/ora_worker.py, Apache-2.0) runs in Kaggle or Google Colab notebooks you start.
58
  Colab connections use a Cloudflare quick tunnel (cloudflared, Apache-2.0, downloaded inside the notebook).
README.md CHANGED
@@ -19,6 +19,8 @@ Ora is a free desktop app for **marketing content made with open AI models, on y
19
  - **Finished ads:** the Ad maker joins your shots into a 15 or 30 s ad with headline, offer and end card, background music composed on your computer and an optional voice-over, and saves it for Reels/TikTok (9:16), feeds and LinkedIn (4:5, 1:1) and YouTube (16:9).
20
  - **Enhance:** Sharper (upscale to HD) and Smoother (twice the frames) for any video.
21
  - **Helpers:** 9 ready-made templates, a brand kit, versions to choose from and ✨ Improve prompt.
 
 
22
 
23
  Nothing is uploaded unless you choose an online service, and no account is needed. The app downloads the models once (pinned revisions, SHA-256 checked) and then works offline.
24
 
@@ -31,6 +33,8 @@ Nothing is uploaded unless you choose an online service, and no account is neede
31
  - The app checks the computer and locks models it cannot run, with the reason.
32
  - **Online (beta):** connect your own Kaggle (API token), Google Colab or Lightning AI (one line + connection code), or Cloudflare Workers AI (images), and choose Run on › Online. The worker is [`worker/ora_worker.py`](worker/ora_worker.py); the CUDA engine is in the releases repo.
33
 
 
 
34
  ## Install
35
 
36
  | System | Command |
 
19
  - **Finished ads:** the Ad maker joins your shots into a 15 or 30 s ad with headline, offer and end card, background music composed on your computer and an optional voice-over, and saves it for Reels/TikTok (9:16), feeds and LinkedIn (4:5, 1:1) and YouTube (16:9).
20
  - **Enhance:** Sharper (upscale to HD) and Smoother (twice the frames) for any video.
21
  - **Helpers:** 9 ready-made templates, a brand kit, versions to choose from and ✨ Improve prompt.
22
+ - **Plan (new in 0.3):** the whole campaign, step by step: brand identity (with a one-page Brand Identity Summary), customer personas, campaign and funnel with success metrics, a 30-day content calendar (CSV and calendar export), results with engagement rate against targets, and a one-click PDF presentation. Five example businesses to practise with.
23
+ - **Post:** captions for Instagram, Facebook and LinkedIn in your brand's tone, a "Ready to post" folder, and a ready-made [n8n](https://n8n.io) workflow (`app/n8n/ora-social-posting.json`) that waits until the post time and posts to LinkedIn or a Facebook Page.
24
 
25
  Nothing is uploaded unless you choose an online service, and no account is needed. The app downloads the models once (pinned revisions, SHA-256 checked) and then works offline.
26
 
 
33
  - The app checks the computer and locks models it cannot run, with the reason.
34
  - **Online (beta):** connect your own Kaggle (API token), Google Colab or Lightning AI (one line + connection code), or Cloudflare Workers AI (images), and choose Run on › Online. The worker is [`worker/ora_worker.py`](worker/ora_worker.py); the CUDA engine is in the releases repo.
35
 
36
+ Teaching a course with Ora? See [Running Ora in class](CLASSROOM.md).
37
+
38
  ## Install
39
 
40
  | System | Command |
app/main.cjs CHANGED
@@ -25,6 +25,11 @@ const SETTINGS = path.join(DATA, 'settings.json');
25
  // ORA_SAVE_DIR (development only): where test runs save their MP4s instead of the user's Videos folder
26
  const SAVE_DIR = (!app.isPackaged && process.env.ORA_SAVE_DIR) || path.join(app.getPath('videos'), 'Ora');
27
  const IMAGE_DIR = (!app.isPackaged && process.env.ORA_SAVE_DIR) ? path.join(process.env.ORA_SAVE_DIR, 'images') : path.join(app.getPath('pictures'), 'Ora');
 
 
 
 
 
28
 
29
  const remote = createRemote(DATA);
30
  let win = null;
@@ -829,22 +834,49 @@ app.whenReady().then(() => {
829
  await writeMeta(dir, meta);
830
  return target;
831
  });
 
 
832
  // "Improve prompt": keywords -> one clean, professional prompt. Uses Cloudflare's text model when connected;
833
  // the renderer falls back to its own offline rewrite when this throws.
834
  ipcMain.handle('prompt:improve', async (_e, text, kind) => {
835
  text = String(text || '').slice(0, 600).trim();
836
  if (text.length < 2) throw new Error('Write a few words first.');
837
  if (!remote.status().cloudflare.connected) throw new Error('offline');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838
  if (kind === 'carousel') {
839
- const out = await remote.cfText('You write social media carousel slides (Instagram, LinkedIn) for marketing. Given the cover title, write 4 short slides that follow it: each one line of at most 12 words, concrete and useful, no numbering, no emojis, no hashtags, no quotes. The last slide is a short call to action. Reply with exactly 4 lines and nothing else.', text);
840
- const lines = out.split('\n').map(x => x.replace(/^\s*(\d+[.)]|[-•*])\s*/, '').replace(/^["“]|["”]$/g, '').trim()).filter(Boolean).slice(0, 5);
 
841
  if (lines.length < 2) throw new Error('offline');
842
  return lines.join('\n');
843
  }
844
  const system = kind === 'image'
845
  ? 'You write prompts for a text-to-image model used for marketing. Turn the user\'s keywords into ONE clear English prompt of 30 to 60 words: the subject, its setting and background, lighting, camera angle and lens, mood and colours, and a professional quality cue. Keep every product, brand, colour and detail the user gave and do not invent brand names. Never ask for written text, letters or logos in the picture. Reply with the prompt only, no quotes, no preface.'
846
  : 'You write prompts for a text-to-video model used for marketing. Turn the user\'s keywords into ONE clear English prompt of 30 to 60 words for a single shot of a few seconds: the subject, what moves and how, the camera movement, the setting, lighting, mood and colours. Keep every product, brand, colour and detail the user gave and do not invent brand names. One continuous shot only, no scene cuts, no written text. Reply with the prompt only, no quotes, no preface.';
847
- const out = (await remote.cfText(system, text)).replace(/^["'“]+|["'”]+$/g, '').replace(/^(here is|prompt:)[^:]*:\s*/i, '').trim();
 
 
848
  if (out.length < 10) throw new Error('offline');
849
  return out.slice(0, 600);
850
  });
@@ -917,6 +949,139 @@ app.whenReady().then(() => {
917
  return meta;
918
  });
919
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
920
  // Ad maker: the renderer joins shots, adds the text and encodes; save each format in the project's folder.
921
  ipcMain.handle('ad:save', async (_e, folder, name, bytes, ext) => {
922
  const sub = typeof folder === 'string' && folder && !/[\\/]|\.\./.test(folder) ? folder : 'Ads';
 
25
  // ORA_SAVE_DIR (development only): where test runs save their MP4s instead of the user's Videos folder
26
  const SAVE_DIR = (!app.isPackaged && process.env.ORA_SAVE_DIR) || path.join(app.getPath('videos'), 'Ora');
27
  const IMAGE_DIR = (!app.isPackaged && process.env.ORA_SAVE_DIR) ? path.join(process.env.ORA_SAVE_DIR, 'images') : path.join(app.getPath('pictures'), 'Ora');
28
+ // "Ready to post": one folder per post (media + captions + post.json), the hand-off to n8n or to posting by hand
29
+ const POSTS_DIR = path.join(SAVE_DIR, 'Ready to post');
30
+ // The marketing plan (brand, personas, campaign, calendar, results) the Plan tab edits: one JSON file per computer
31
+ const PLAN = path.join(DATA, 'plan.json');
32
+ const PLAN_DIR = path.join(app.getPath('documents'), 'Ora'); // exported summaries and presentations
33
 
34
  const remote = createRemote(DATA);
35
  let win = null;
 
834
  await writeMeta(dir, meta);
835
  return target;
836
  });
837
+ // A text model that declines answers with an apology instead of the text: never paste that into the form
838
+ const refused = t => /^(i('| a)m sorry|i can('|no)t|i cannot|sorry,|i'm not able|i am not able|i won't|as an ai)/i.test(String(t).trim());
839
  // "Improve prompt": keywords -> one clean, professional prompt. Uses Cloudflare's text model when connected;
840
  // the renderer falls back to its own offline rewrite when this throws.
841
  ipcMain.handle('prompt:improve', async (_e, text, kind) => {
842
  text = String(text || '').slice(0, 600).trim();
843
  if (text.length < 2) throw new Error('Write a few words first.');
844
  if (!remote.status().cloudflare.connected) throw new Error('offline');
845
+ if (kind === 'campaign') {
846
+ const outC = await remote.cfText('You plan marketing campaigns for small businesses. From the facts given, suggest 3 campaign ideas, each on one line as "Name | key message": the name at most 4 words, the message one sentence of at most 14 words. No numbering, no quotes, no emojis. Use only the facts given.', text);
847
+ if (refused(outC)) throw new Error('declined');
848
+ const lines = outC.split('\n').map(x => x.replace(/^\s*(\d+[.)]|[-•*])\s*/, '').replace(/["“”]/g, '').trim()).filter(x => x.includes('|')).slice(0, 3);
849
+ if (!lines.length) throw new Error('offline');
850
+ return lines.join('\n');
851
+ }
852
+ if (kind === 'ideas') {
853
+ const outI = await remote.cfText('You plan social media content for a small business. From the brand facts given, write 10 post ideas, one per line, as "type: idea". type is one of educational, storytelling, behind-the-scenes, community, lifestyle, promotion; use each type at least once. Each idea is at most 12 words, concrete and doable with a phone or simple pictures. No numbering, no emojis, no hashtags. Use only the facts given.', text);
854
+ if (refused(outI)) throw new Error('declined');
855
+ const lines = outI.split('\n').map(x => x.replace(/^\s*(\d+[.)]|[-•*])\s*/, '').trim()).filter(x => /^[a-z -]+:/i.test(x)).slice(0, 12);
856
+ if (lines.length < 3) throw new Error('offline');
857
+ return lines.join('\n');
858
+ }
859
+ if (kind === 'tagline' || kind === 'mission') {
860
+ const sys = kind === 'tagline'
861
+ ? 'You write brand taglines for small businesses. From the brand facts given, write 3 short taglines (at most 7 words each), one per line, no numbering, no quotes. Use only the facts given.'
862
+ : 'You write brand mission statements for small businesses. From the facts given, write one clear mission statement of at most 30 words: who the brand serves, what it does and why. Reply with the sentence only.';
863
+ const outT = await remote.cfText(sys, text);
864
+ if (refused(outT)) throw new Error('declined');
865
+ return outT.split('\n').map(x => x.replace(/^\s*(\d+[.)]|[-•*])\s*/, '').replace(/^["“]|["”]$/g, '').trim()).filter(Boolean).slice(0, 3).join('\n');
866
+ }
867
  if (kind === 'carousel') {
868
+ const out0 = await remote.cfText('You write social media carousel slides (Instagram, LinkedIn) for marketing. Given the cover title, write 4 short slides that follow it: each one line of at most 12 words, concrete and useful, no numbering, no emojis, no hashtags, no quotes. The last slide is a short call to action. Reply with exactly 4 lines and nothing else.', text);
869
+ if (refused(out0)) throw new Error('declined');
870
+ const lines = out0.split('\n').map(x => x.replace(/^\s*(\d+[.)]|[-•*])\s*/, '').replace(/^["“]|["”]$/g, '').trim()).filter(Boolean).slice(0, 5);
871
  if (lines.length < 2) throw new Error('offline');
872
  return lines.join('\n');
873
  }
874
  const system = kind === 'image'
875
  ? 'You write prompts for a text-to-image model used for marketing. Turn the user\'s keywords into ONE clear English prompt of 30 to 60 words: the subject, its setting and background, lighting, camera angle and lens, mood and colours, and a professional quality cue. Keep every product, brand, colour and detail the user gave and do not invent brand names. Never ask for written text, letters or logos in the picture. Reply with the prompt only, no quotes, no preface.'
876
  : 'You write prompts for a text-to-video model used for marketing. Turn the user\'s keywords into ONE clear English prompt of 30 to 60 words for a single shot of a few seconds: the subject, what moves and how, the camera movement, the setting, lighting, mood and colours. Keep every product, brand, colour and detail the user gave and do not invent brand names. One continuous shot only, no scene cuts, no written text. Reply with the prompt only, no quotes, no preface.';
877
+ const raw = await remote.cfText(system, text);
878
+ if (refused(raw)) throw new Error('declined');
879
+ const out = raw.replace(/^["'“]+|["'”]+$/g, '').replace(/^(here is|prompt:)[^:]*:\s*/i, '').trim();
880
  if (out.length < 10) throw new Error('offline');
881
  return out.slice(0, 600);
882
  });
 
949
  return meta;
950
  });
951
 
952
+ // Plan tab: read and write the whole plan (the renderer owns its shape; main only bounds its size)
953
+ ipcMain.handle('plan:get', async () => { try { return JSON.parse(await fsp.readFile(PLAN, 'utf8')); } catch { return {}; } });
954
+ ipcMain.handle('plan:set', async (_e, plan) => {
955
+ const text = JSON.stringify(plan && typeof plan === 'object' ? plan : {});
956
+ if (text.length > 2e6) throw new Error('The plan is too big to save.');
957
+ await fsp.mkdir(DATA, { recursive: true });
958
+ await fsp.writeFile(`${PLAN}.tmp`, text); await fsp.rename(`${PLAN}.tmp`, PLAN);
959
+ return true;
960
+ });
961
+ // exported PNG/PDF pages (Brand Identity Summary, presentation) go to Documents/Ora
962
+ ipcMain.handle('plan:export', async (_e, name, bytes, ext) => {
963
+ if (!['png', 'pdf', 'csv', 'ics', 'txt', 'json', 'pptx'].includes(ext) || !bytes || bytes.byteLength > 80e6) throw new Error('bad export');
964
+ const dir = (!app.isPackaged && process.env.ORA_SAVE_DIR) ? path.join(process.env.ORA_SAVE_DIR, 'documents') : PLAN_DIR;
965
+ await fsp.mkdir(dir, { recursive: true });
966
+ const base = core.folderName(String(name || 'Ora'), 60);
967
+ let target = path.join(dir, `${base}.${ext}`), n = 2;
968
+ while (fs.existsSync(target)) target = path.join(dir, `${base} ${n++}.${ext}`);
969
+ await fsp.writeFile(target, Buffer.from(bytes));
970
+ shell.showItemInFolder(target);
971
+ return target;
972
+ });
973
+
974
+ // Presentation: the renderer builds the slides as HTML; a hidden window prints them to a 16:9 PDF
975
+ ipcMain.handle('plan:pdf', async (_e, name, html, page) => {
976
+ if (typeof html !== 'string' || html.length > 5e6) throw new Error('bad slides');
977
+ const tmp = path.join(app.getPath('temp'), `ora-slides-${Date.now()}.html`);
978
+ await fsp.writeFile(tmp, html);
979
+ const a4 = page === 'a4';
980
+ const w = new BrowserWindow({ show: false, width: a4 ? 794 : 1280, height: a4 ? 1123 : 720, webPreferences: { sandbox: true, contextIsolation: true, javascript: false } });
981
+ try {
982
+ await w.loadFile(tmp);
983
+ await new Promise(r => setTimeout(r, 600)); // pictures (ora://) finish loading
984
+ const pdf = await w.webContents.printToPDF({ pageSize: a4 ? 'A4' : { width: 13.333, height: 7.5 }, printBackground: true, margins: { marginType: 'none' } });
985
+ const dir = (!app.isPackaged && process.env.ORA_SAVE_DIR) ? path.join(process.env.ORA_SAVE_DIR, 'documents') : PLAN_DIR;
986
+ await fsp.mkdir(dir, { recursive: true });
987
+ const base = core.folderName(String(name || 'Ora presentation'), 60);
988
+ let target = path.join(dir, `${base}.pdf`), n = 2;
989
+ while (fs.existsSync(target)) target = path.join(dir, `${base} ${n++}.pdf`);
990
+ await fsp.writeFile(target, pdf);
991
+ shell.showItemInFolder(target);
992
+ return target;
993
+ } finally { w.destroy(); fsp.rm(tmp, { force: true }).catch(() => { }); }
994
+ });
995
+
996
+ // Captions: one per platform, in the brand's tone (Cloudflare's text model; the renderer has an offline fallback)
997
+ const PLATFORM_RULES = {
998
+ instagram: 'Instagram: a strong first line (hook), 2 to 4 short lines, 1 to 3 fitting emojis, a clear call to action, then 8 to 12 relevant hashtags on the last line.',
999
+ facebook: 'Facebook: friendly and conversational, 2 to 4 sentences, at most 2 emojis, a clear call to action, at most 3 hashtags.',
1000
+ linkedin: 'LinkedIn: professional and useful, a first line that earns the click, 3 to 5 short sentences or a short list, no more than 1 emoji, a clear call to action, 3 to 5 hashtags at the end.',
1001
+ };
1002
+ ipcMain.handle('caption:write', async (_e, ctx, platform) => {
1003
+ if (!PLATFORM_RULES[platform]) throw new Error('Pick a platform.');
1004
+ if (!remote.status().cloudflare.connected) throw new Error('offline');
1005
+ const c = ctx && typeof ctx === 'object' ? ctx : {};
1006
+ const str = (v, n) => typeof v === 'string' ? v.trim().slice(0, n) : '';
1007
+ const facts = [
1008
+ ['What the post shows', str(c.about, 600)], ['Headline', str(c.title, 120)], ['Offer', str(c.offer, 120)],
1009
+ ['Call to action', str(c.cta, 60)], ['Website or handle', str(c.site, 80)], ['Brand', str(c.brand, 60)],
1010
+ ['Brand tone and words', str(c.tone, 200)], ['Audience', str(c.audience, 200)],
1011
+ ].filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`).join('\n');
1012
+ if (!facts) throw new Error('Nothing to write about yet.');
1013
+ const system = `You write social media captions for small businesses. ${PLATFORM_RULES[platform]} Use only the facts given; do not invent prices, dates, numbers or claims. Write in English. Reply with the caption only, no preface, no quotes.`;
1014
+ const out = await remote.cfText(system, facts);
1015
+ if (refused(out) || out.length < 10) throw new Error('declined');
1016
+ return out.replace(/^["“]|["”]$/g, '').trim().slice(0, 2200);
1017
+ });
1018
+
1019
+ // Ready to post: copy the media and the captions into a folder of its own, then (when set) send it to n8n
1020
+ const insideOutputs = f => typeof f === 'string' && path.isAbsolute(f) && [SAVE_DIR, IMAGE_DIR].some(d => path.resolve(f).startsWith(path.resolve(d) + path.sep)) && fs.existsSync(f);
1021
+ async function sendToN8n(url, post, dir) {
1022
+ const form = new FormData();
1023
+ form.append('post', JSON.stringify(post));
1024
+ for (const [i, m] of post.media.entries()) {
1025
+ const bytes = await fsp.readFile(path.join(dir, m.file));
1026
+ form.append(`media${i}`, new Blob([bytes], { type: m.type }), m.file);
1027
+ }
1028
+ const res = await net.fetch(url, { method: 'POST', body: form });
1029
+ if (!res.ok) throw new Error(`n8n answered ${res.status}${res.status === 404 ? ': is the workflow active (or the test URL listening)?' : ''}`);
1030
+ return true;
1031
+ }
1032
+ ipcMain.handle('post:save', async (_e, input) => {
1033
+ const p = input && typeof input === 'object' ? input : {};
1034
+ const files = (Array.isArray(p.files) ? p.files : []).filter(insideOutputs).slice(0, 10);
1035
+ if (!files.length) throw new Error('Save the video or image first.');
1036
+ const platforms = (Array.isArray(p.platforms) ? p.platforms : []).filter(x => PLATFORM_RULES[x]);
1037
+ if (!platforms.length) throw new Error('Pick at least one platform.');
1038
+ const captions = {};
1039
+ for (const k of platforms) captions[k] = typeof (p.captions || {})[k] === 'string' ? p.captions[k].slice(0, 3000) : '';
1040
+ const when = typeof p.when === 'string' && !Number.isNaN(Date.parse(p.when)) ? new Date(p.when).toISOString() : '';
1041
+ const title = core.folderName(String(p.title || 'Ora post'), 50);
1042
+ const day = new Date(when || Date.now()); // the folder is named after the local date of posting
1043
+ const ymd = `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`;
1044
+ const dir = path.join(POSTS_DIR, `${ymd} ${title}`);
1045
+ let d = dir, n = 2;
1046
+ while (fs.existsSync(d)) d = `${dir} ${n++}`;
1047
+ await fsp.mkdir(d, { recursive: true });
1048
+ const media = [];
1049
+ for (const [i, f] of files.entries()) {
1050
+ const ext = path.extname(f).toLowerCase();
1051
+ const file = `${String(i + 1).padStart(2, '0')}${ext}`;
1052
+ await fsp.copyFile(f, path.join(d, file));
1053
+ media.push({ file, type: { '.mp4': 'video/mp4', '.webm': 'video/webm', '.png': 'image/png', '.jpg': 'image/jpeg' }[ext] || 'application/octet-stream', kind: /\.(mp4|webm)$/.test(ext) ? 'video' : 'image' });
1054
+ }
1055
+ const post = { app: 'Ora', version: app.getVersion(), id: path.basename(d), title: String(p.title || '').slice(0, 120), created: new Date().toISOString(), when, platforms, captions, media };
1056
+ await fsp.writeFile(path.join(d, 'post.json'), JSON.stringify(post, null, 2));
1057
+ for (const k of platforms) await fsp.writeFile(path.join(d, `caption-${k}.txt`), captions[k]);
1058
+ const url = readSettings().n8nWebhook;
1059
+ let sent = false, sendError = '';
1060
+ if (url && p.send !== false) { try { sent = await sendToN8n(url, post, d); } catch (e) { sendError = e.message; } }
1061
+ return { dir: d, sent, sendError };
1062
+ });
1063
+ ipcMain.handle('n8n:set', (_e, url) => {
1064
+ url = String(url || '').trim();
1065
+ if (url && !/^https?:\/\/[^\s]+$/i.test(url)) throw new Error('Paste the full webhook URL from n8n (it starts with https:// or http://).');
1066
+ return writeSettings({ n8nWebhook: url || undefined });
1067
+ });
1068
+ ipcMain.handle('n8n:test', async () => {
1069
+ const url = readSettings().n8nWebhook;
1070
+ if (!url) throw new Error('Paste the webhook URL first.');
1071
+ const res = await net.fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ test: true, app: 'Ora', version: app.getVersion() }) });
1072
+ if (!res.ok) throw new Error(`n8n answered ${res.status}${res.status === 404 ? ': activate the workflow, or press "Listen for test event" in n8n first.' : ''}`);
1073
+ return true;
1074
+ });
1075
+ // the ready-made n8n workflow, saved where the person can import it (n8n › Workflows › Import from file)
1076
+ ipcMain.handle('n8n:workflow', async () => {
1077
+ await fsp.mkdir(POSTS_DIR, { recursive: true });
1078
+ const target = path.join(POSTS_DIR, 'Ora to social media (n8n workflow).json');
1079
+ await fsp.copyFile(path.join(__dirname, 'n8n', 'ora-social-posting.json'), target);
1080
+ shell.showItemInFolder(target);
1081
+ return target;
1082
+ });
1083
+ ipcMain.handle('open:posts', async () => { await fsp.mkdir(POSTS_DIR, { recursive: true }); return shell.openPath(POSTS_DIR); });
1084
+
1085
  // Ad maker: the renderer joins shots, adds the text and encodes; save each format in the project's folder.
1086
  ipcMain.handle('ad:save', async (_e, folder, name, bytes, ext) => {
1087
  const sub = typeof folder === 'string' && folder && !/[\\/]|\.\./.test(folder) ? folder : 'Ads';
app/n8n/ora-social-posting.json ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Ora to social media",
3
+ "nodes": [
4
+ {
5
+ "parameters": {
6
+ "httpMethod": "POST",
7
+ "path": "ora-post",
8
+ "responseMode": "onReceived",
9
+ "options": {}
10
+ },
11
+ "name": "Ora sends a post",
12
+ "type": "n8n-nodes-base.webhook",
13
+ "typeVersion": 2,
14
+ "position": [
15
+ 0,
16
+ 300
17
+ ],
18
+ "webhookId": "6f1f4c8e-0a5b-4b7e-9a0e-0a0000000001"
19
+ },
20
+ {
21
+ "parameters": {
22
+ "jsCode": "// Ora sends: field \"post\" (JSON) + files media0, media1\u2026 One item per platform comes out.\n// route: 0 LinkedIn image \u00b7 1 Facebook photo \u00b7 2 Facebook video \u00b7 3 Instagram picture \u00b7 4 post by hand (videos on LinkedIn/Instagram)\nconst out = [];\nfor (const item of $input.all()) {\n const body = item.json.body || {};\n if (body.test) continue; // \"Test\" button in Ora: nothing to post\n const post = typeof body.post === 'string' ? JSON.parse(body.post) : body.post;\n if (!post || !Array.isArray(post.platforms)) continue;\n const first = (post.media || [])[0] || {};\n const isVideo = first.kind === 'video';\n for (const platform of post.platforms) {\n let route = 4;\n if (platform === 'linkedin' && !isVideo) route = 0;\n if (platform === 'facebook') route = isVideo ? 2 : 1;\n if (platform === 'instagram' && !isVideo) route = 3;\n out.push({\n json: { platform, route, isVideo, caption: (post.captions || {})[platform] || '', when: post.when || new Date().toISOString(),\n title: post.title || '', id: post.id || '', file: first.file || '' },\n binary: item.binary,\n });\n }\n}\nreturn out;"
23
+ },
24
+ "name": "Read the post",
25
+ "type": "n8n-nodes-base.code",
26
+ "typeVersion": 2,
27
+ "position": [
28
+ 240,
29
+ 300
30
+ ]
31
+ },
32
+ {
33
+ "parameters": {
34
+ "jsCode": "// One row per post and platform for the content-calendar sheet.\n// Make a Google Sheet whose first row is: Date | Time | Platform | Title | Caption | File\nreturn $input.all().map(i => {\n const d = new Date(i.json.when);\n return { json: { Date: d.toISOString().slice(0, 10), Time: d.toISOString().slice(11, 16) + ' UTC', Platform: i.json.platform,\n Title: i.json.title, Caption: i.json.caption, File: i.json.file } };\n});"
35
+ },
36
+ "name": "Row for the sheet",
37
+ "type": "n8n-nodes-base.code",
38
+ "typeVersion": 2,
39
+ "position": [
40
+ 480,
41
+ 560
42
+ ]
43
+ },
44
+ {
45
+ "parameters": {
46
+ "resource": "sheet",
47
+ "operation": "append",
48
+ "documentId": {
49
+ "__rl": true,
50
+ "value": "",
51
+ "mode": "url"
52
+ },
53
+ "sheetName": {
54
+ "__rl": true,
55
+ "value": "gid=0",
56
+ "mode": "list",
57
+ "cachedResultName": "Sheet1"
58
+ },
59
+ "columns": {
60
+ "mappingMode": "autoMapInputData",
61
+ "value": {},
62
+ "matchingColumns": [],
63
+ "schema": []
64
+ },
65
+ "options": {}
66
+ },
67
+ "name": "Log to Google Sheets",
68
+ "type": "n8n-nodes-base.googleSheets",
69
+ "typeVersion": 4.5,
70
+ "position": [
71
+ 720,
72
+ 560
73
+ ],
74
+ "disabled": true
75
+ },
76
+ {
77
+ "parameters": {
78
+ "resume": "specificTime",
79
+ "dateTime": "={{ $json.when }}"
80
+ },
81
+ "name": "Wait until the post time",
82
+ "type": "n8n-nodes-base.wait",
83
+ "typeVersion": 1.1,
84
+ "position": [
85
+ 480,
86
+ 300
87
+ ],
88
+ "webhookId": "6f1f4c8e-0a5b-4b7e-9a0e-0a0000000002"
89
+ },
90
+ {
91
+ "parameters": {
92
+ "mode": "expression",
93
+ "numberOutputs": 5,
94
+ "output": "={{ $json.route }}"
95
+ },
96
+ "name": "Which platform?",
97
+ "type": "n8n-nodes-base.switch",
98
+ "typeVersion": 3.2,
99
+ "position": [
100
+ 720,
101
+ 300
102
+ ]
103
+ },
104
+ {
105
+ "parameters": {
106
+ "resource": "post",
107
+ "operation": "create",
108
+ "postAs": "person",
109
+ "person": "",
110
+ "text": "={{ $json.caption }}",
111
+ "shareMediaCategory": "IMAGE",
112
+ "binaryPropertyName": "media0",
113
+ "additionalFields": {
114
+ "visibility": "PUBLIC"
115
+ }
116
+ },
117
+ "name": "LinkedIn: image post",
118
+ "type": "n8n-nodes-base.linkedIn",
119
+ "typeVersion": 1,
120
+ "position": [
121
+ 1000,
122
+ 0
123
+ ],
124
+ "disabled": true
125
+ },
126
+ {
127
+ "parameters": {
128
+ "hostUrl": "graph.facebook.com",
129
+ "httpRequestMethod": "POST",
130
+ "graphApiVersion": "v23.0",
131
+ "node": "YOUR_PAGE_ID",
132
+ "edge": "photos",
133
+ "sendBinaryData": true,
134
+ "binaryPropertyName": "source:media0",
135
+ "options": {
136
+ "queryParameters": {
137
+ "parameter": [
138
+ {
139
+ "name": "message",
140
+ "value": "={{ $json.caption }}"
141
+ }
142
+ ]
143
+ }
144
+ }
145
+ },
146
+ "name": "Facebook Page: photo",
147
+ "type": "n8n-nodes-base.facebookGraphApi",
148
+ "typeVersion": 1,
149
+ "position": [
150
+ 1000,
151
+ 160
152
+ ],
153
+ "disabled": true
154
+ },
155
+ {
156
+ "parameters": {
157
+ "hostUrl": "graph-video.facebook.com",
158
+ "httpRequestMethod": "POST",
159
+ "graphApiVersion": "v23.0",
160
+ "node": "YOUR_PAGE_ID",
161
+ "edge": "videos",
162
+ "sendBinaryData": true,
163
+ "binaryPropertyName": "source:media0",
164
+ "options": {
165
+ "queryParameters": {
166
+ "parameter": [
167
+ {
168
+ "name": "description",
169
+ "value": "={{ $json.caption }}"
170
+ }
171
+ ]
172
+ }
173
+ }
174
+ },
175
+ "name": "Facebook Page: video",
176
+ "type": "n8n-nodes-base.facebookGraphApi",
177
+ "typeVersion": 1,
178
+ "position": [
179
+ 1000,
180
+ 320
181
+ ],
182
+ "disabled": true
183
+ },
184
+ {
185
+ "parameters": {
186
+ "method": "POST",
187
+ "url": "https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload",
188
+ "sendBody": true,
189
+ "contentType": "multipart-form-data",
190
+ "bodyParameters": {
191
+ "parameters": [
192
+ {
193
+ "parameterType": "formBinaryData",
194
+ "name": "file",
195
+ "inputDataFieldName": "media0"
196
+ },
197
+ {
198
+ "parameterType": "formData",
199
+ "name": "upload_preset",
200
+ "value": "YOUR_UNSIGNED_PRESET"
201
+ }
202
+ ]
203
+ },
204
+ "options": {}
205
+ },
206
+ "name": "Instagram 1: put the picture online",
207
+ "type": "n8n-nodes-base.httpRequest",
208
+ "typeVersion": 4.2,
209
+ "position": [
210
+ 1000,
211
+ 480
212
+ ],
213
+ "disabled": true
214
+ },
215
+ {
216
+ "parameters": {
217
+ "hostUrl": "graph.facebook.com",
218
+ "httpRequestMethod": "POST",
219
+ "graphApiVersion": "v23.0",
220
+ "node": "YOUR_INSTAGRAM_ACCOUNT_ID",
221
+ "edge": "media",
222
+ "options": {
223
+ "queryParameters": {
224
+ "parameter": [
225
+ {
226
+ "name": "image_url",
227
+ "value": "={{ $json.secure_url }}"
228
+ },
229
+ {
230
+ "name": "caption",
231
+ "value": "={{ $('Wait until the post time').item.json.caption }}"
232
+ }
233
+ ]
234
+ }
235
+ }
236
+ },
237
+ "name": "Instagram 2: create the post",
238
+ "type": "n8n-nodes-base.facebookGraphApi",
239
+ "typeVersion": 1,
240
+ "position": [
241
+ 1240,
242
+ 480
243
+ ],
244
+ "disabled": true
245
+ },
246
+ {
247
+ "parameters": {
248
+ "hostUrl": "graph.facebook.com",
249
+ "httpRequestMethod": "POST",
250
+ "graphApiVersion": "v23.0",
251
+ "node": "YOUR_INSTAGRAM_ACCOUNT_ID",
252
+ "edge": "media_publish",
253
+ "options": {
254
+ "queryParameters": {
255
+ "parameter": [
256
+ {
257
+ "name": "creation_id",
258
+ "value": "={{ $json.id }}"
259
+ }
260
+ ]
261
+ }
262
+ }
263
+ },
264
+ "name": "Instagram 3: publish",
265
+ "type": "n8n-nodes-base.facebookGraphApi",
266
+ "typeVersion": 1,
267
+ "position": [
268
+ 1480,
269
+ 480
270
+ ],
271
+ "disabled": true
272
+ },
273
+ {
274
+ "parameters": {},
275
+ "name": "Post by hand (videos on Instagram and LinkedIn)",
276
+ "type": "n8n-nodes-base.noOp",
277
+ "typeVersion": 1,
278
+ "position": [
279
+ 1000,
280
+ 660
281
+ ]
282
+ },
283
+ {
284
+ "parameters": {
285
+ "content": "## Ora \u2192 social media\n1. **Activate** this workflow, open *Ora sends a post* and copy the **Production URL**.\n2. In Ora: **Online \u203a n8n automation**, paste it and press **Test**.\n3. In Ora press **Post\u2026** on a video or image, write the captions, pick the time, **Send to n8n**. n8n waits until the post time, then posts.\n\n**Switch on only what you connect** (n8n will not run a workflow with an unfinished step). Double-click a step, set it up, then right-click \u203a **Activate** (or press D):\n- **LinkedIn: image post** \u2013 your LinkedIn credential and your name under *Person*.\n- **Facebook Page** \u2013 a Facebook Graph API credential with a **Page** token; your Page ID instead of YOUR_PAGE_ID.\n- **Instagram 1\u20133** \u2013 Instagram needs the picture at a public link: make a free **Cloudinary** account, create an *unsigned upload preset*, put your cloud name and preset in step 1; in steps 2\u20133 use the Facebook Graph credential and your **Instagram business account ID**.\n- **Log to Google Sheets** \u2013 a sheet whose first row is Date | Time | Platform | Title | Caption | File, your Google credential and the sheet's link.\n\nVideos for Instagram and LinkedIn arrive in *Post by hand*: the files and captions are in Ora's **Ready to post** folder.",
286
+ "height": 640,
287
+ "width": 460
288
+ },
289
+ "name": "How to use",
290
+ "type": "n8n-nodes-base.stickyNote",
291
+ "typeVersion": 1,
292
+ "position": [
293
+ -60,
294
+ -380
295
+ ]
296
+ }
297
+ ],
298
+ "connections": {
299
+ "Ora sends a post": {
300
+ "main": [
301
+ [
302
+ {
303
+ "node": "Read the post",
304
+ "type": "main",
305
+ "index": 0
306
+ }
307
+ ]
308
+ ]
309
+ },
310
+ "Read the post": {
311
+ "main": [
312
+ [
313
+ {
314
+ "node": "Wait until the post time",
315
+ "type": "main",
316
+ "index": 0
317
+ },
318
+ {
319
+ "node": "Row for the sheet",
320
+ "type": "main",
321
+ "index": 0
322
+ }
323
+ ]
324
+ ]
325
+ },
326
+ "Row for the sheet": {
327
+ "main": [
328
+ [
329
+ {
330
+ "node": "Log to Google Sheets",
331
+ "type": "main",
332
+ "index": 0
333
+ }
334
+ ]
335
+ ]
336
+ },
337
+ "Wait until the post time": {
338
+ "main": [
339
+ [
340
+ {
341
+ "node": "Which platform?",
342
+ "type": "main",
343
+ "index": 0
344
+ }
345
+ ]
346
+ ]
347
+ },
348
+ "Which platform?": {
349
+ "main": [
350
+ [
351
+ {
352
+ "node": "LinkedIn: image post",
353
+ "type": "main",
354
+ "index": 0
355
+ }
356
+ ],
357
+ [
358
+ {
359
+ "node": "Facebook Page: photo",
360
+ "type": "main",
361
+ "index": 0
362
+ }
363
+ ],
364
+ [
365
+ {
366
+ "node": "Facebook Page: video",
367
+ "type": "main",
368
+ "index": 0
369
+ }
370
+ ],
371
+ [
372
+ {
373
+ "node": "Instagram 1: put the picture online",
374
+ "type": "main",
375
+ "index": 0
376
+ }
377
+ ],
378
+ [
379
+ {
380
+ "node": "Post by hand (videos on Instagram and LinkedIn)",
381
+ "type": "main",
382
+ "index": 0
383
+ }
384
+ ]
385
+ ]
386
+ },
387
+ "Instagram 1: put the picture online": {
388
+ "main": [
389
+ [
390
+ {
391
+ "node": "Instagram 2: create the post",
392
+ "type": "main",
393
+ "index": 0
394
+ }
395
+ ]
396
+ ]
397
+ },
398
+ "Instagram 2: create the post": {
399
+ "main": [
400
+ [
401
+ {
402
+ "node": "Instagram 3: publish",
403
+ "type": "main",
404
+ "index": 0
405
+ }
406
+ ]
407
+ ]
408
+ }
409
+ },
410
+ "settings": {
411
+ "executionOrder": "v1"
412
+ },
413
+ "active": false,
414
+ "pinData": {},
415
+ "meta": {
416
+ "templateCredsSetupCompleted": false
417
+ }
418
+ }
app/package-lock.json CHANGED
@@ -1,12 +1,12 @@
1
  {
2
  "name": "devseis-ora",
3
- "version": "0.1.9",
4
  "lockfileVersion": 3,
5
  "requires": true,
6
  "packages": {
7
  "": {
8
  "name": "devseis-ora",
9
- "version": "0.1.9",
10
  "license": "Apache-2.0",
11
  "devDependencies": {
12
  "electron": "^44.9.3",
@@ -14,6 +14,7 @@
14
  "esbuild": "0.25.10",
15
  "kokoro-js": "1.2.1",
16
  "mp4-muxer": "^5.2.1",
 
17
  "webm-muxer": "^5.1.4"
18
  }
19
  },
@@ -3259,6 +3260,13 @@
3259
  "node": ">=10.19.0"
3260
  }
3261
  },
 
 
 
 
 
 
 
3262
  "node_modules/https-proxy-agent": {
3263
  "version": "7.0.6",
3264
  "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
@@ -3273,6 +3281,29 @@
3273
  "node": ">= 14"
3274
  }
3275
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3276
  "node_modules/inflight": {
3277
  "version": "1.0.6",
3278
  "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -3430,6 +3461,19 @@
3430
  "graceful-fs": "^4.1.6"
3431
  }
3432
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
3433
  "node_modules/keyv": {
3434
  "version": "4.5.4",
3435
  "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -3458,6 +3502,16 @@
3458
  "dev": true,
3459
  "license": "MIT"
3460
  },
 
 
 
 
 
 
 
 
 
 
3461
  "node_modules/lodash": {
3462
  "version": "4.18.1",
3463
  "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
@@ -3869,6 +3923,13 @@
3869
  "url": "https://github.com/sponsors/sindresorhus"
3870
  }
3871
  },
 
 
 
 
 
 
 
3872
  "node_modules/path-is-absolute": {
3873
  "version": "1.0.1",
3874
  "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
@@ -4004,6 +4065,36 @@
4004
  "node": "^12.20.0 || >=14"
4005
  }
4006
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4007
  "node_modules/proc-log": {
4008
  "version": "6.1.0",
4009
  "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz",
@@ -4112,6 +4203,16 @@
4112
  "node": ">=16.0.0"
4113
  }
4114
  },
 
 
 
 
 
 
 
 
 
 
4115
  "node_modules/quick-lru": {
4116
  "version": "5.1.1",
4117
  "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
@@ -4318,6 +4419,13 @@
4318
  "url": "https://github.com/sponsors/sindresorhus"
4319
  }
4320
  },
 
 
 
 
 
 
 
4321
  "node_modules/sharp": {
4322
  "version": "0.34.5",
4323
  "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
 
1
  {
2
  "name": "devseis-ora",
3
+ "version": "0.3.0",
4
  "lockfileVersion": 3,
5
  "requires": true,
6
  "packages": {
7
  "": {
8
  "name": "devseis-ora",
9
+ "version": "0.3.0",
10
  "license": "Apache-2.0",
11
  "devDependencies": {
12
  "electron": "^44.9.3",
 
14
  "esbuild": "0.25.10",
15
  "kokoro-js": "1.2.1",
16
  "mp4-muxer": "^5.2.1",
17
+ "pptxgenjs": "4.0.1",
18
  "webm-muxer": "^5.1.4"
19
  }
20
  },
 
3260
  "node": ">=10.19.0"
3261
  }
3262
  },
3263
+ "node_modules/https": {
3264
+ "version": "1.0.0",
3265
+ "resolved": "https://registry.npmjs.org/https/-/https-1.0.0.tgz",
3266
+ "integrity": "sha512-4EC57ddXrkaF0x83Oj8sM6SLQHAWXw90Skqu2M4AEWENZ3F02dFJE/GARA8igO79tcgYqGrD7ae4f5L3um2lgg==",
3267
+ "dev": true,
3268
+ "license": "ISC"
3269
+ },
3270
  "node_modules/https-proxy-agent": {
3271
  "version": "7.0.6",
3272
  "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
 
3281
  "node": ">= 14"
3282
  }
3283
  },
3284
+ "node_modules/image-size": {
3285
+ "version": "1.2.1",
3286
+ "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.1.tgz",
3287
+ "integrity": "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw==",
3288
+ "dev": true,
3289
+ "license": "MIT",
3290
+ "dependencies": {
3291
+ "queue": "6.0.2"
3292
+ },
3293
+ "bin": {
3294
+ "image-size": "bin/image-size.js"
3295
+ },
3296
+ "engines": {
3297
+ "node": ">=16.x"
3298
+ }
3299
+ },
3300
+ "node_modules/immediate": {
3301
+ "version": "3.0.6",
3302
+ "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
3303
+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
3304
+ "dev": true,
3305
+ "license": "MIT"
3306
+ },
3307
  "node_modules/inflight": {
3308
  "version": "1.0.6",
3309
  "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
 
3461
  "graceful-fs": "^4.1.6"
3462
  }
3463
  },
3464
+ "node_modules/jszip": {
3465
+ "version": "3.10.2",
3466
+ "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.2.tgz",
3467
+ "integrity": "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ==",
3468
+ "dev": true,
3469
+ "license": "(MIT OR GPL-3.0-or-later)",
3470
+ "dependencies": {
3471
+ "lie": "~3.3.0",
3472
+ "pako": "~1.0.2",
3473
+ "readable-stream": "~2.3.6",
3474
+ "setimmediate": "^1.0.5"
3475
+ }
3476
+ },
3477
  "node_modules/keyv": {
3478
  "version": "4.5.4",
3479
  "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
 
3502
  "dev": true,
3503
  "license": "MIT"
3504
  },
3505
+ "node_modules/lie": {
3506
+ "version": "3.3.0",
3507
+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
3508
+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
3509
+ "dev": true,
3510
+ "license": "MIT",
3511
+ "dependencies": {
3512
+ "immediate": "~3.0.5"
3513
+ }
3514
+ },
3515
  "node_modules/lodash": {
3516
  "version": "4.18.1",
3517
  "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
 
3923
  "url": "https://github.com/sponsors/sindresorhus"
3924
  }
3925
  },
3926
+ "node_modules/pako": {
3927
+ "version": "1.0.11",
3928
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
3929
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
3930
+ "dev": true,
3931
+ "license": "(MIT AND Zlib)"
3932
+ },
3933
  "node_modules/path-is-absolute": {
3934
  "version": "1.0.1",
3935
  "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
 
4065
  "node": "^12.20.0 || >=14"
4066
  }
4067
  },
4068
+ "node_modules/pptxgenjs": {
4069
+ "version": "4.0.1",
4070
+ "resolved": "https://registry.npmjs.org/pptxgenjs/-/pptxgenjs-4.0.1.tgz",
4071
+ "integrity": "sha512-TeJISr8wouAuXw4C1F/mC33xbZs/FuEG6nH9FG1Zj+nuPcGMP5YRHl6X+j3HSUnS1f3at6k75ZZXPMZlA5Lj9A==",
4072
+ "dev": true,
4073
+ "license": "MIT",
4074
+ "dependencies": {
4075
+ "@types/node": "^22.8.1",
4076
+ "https": "^1.0.0",
4077
+ "image-size": "^1.2.1",
4078
+ "jszip": "^3.10.1"
4079
+ }
4080
+ },
4081
+ "node_modules/pptxgenjs/node_modules/@types/node": {
4082
+ "version": "22.20.5",
4083
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
4084
+ "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
4085
+ "dev": true,
4086
+ "license": "MIT",
4087
+ "dependencies": {
4088
+ "undici-types": "~6.21.0"
4089
+ }
4090
+ },
4091
+ "node_modules/pptxgenjs/node_modules/undici-types": {
4092
+ "version": "6.21.0",
4093
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
4094
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
4095
+ "dev": true,
4096
+ "license": "MIT"
4097
+ },
4098
  "node_modules/proc-log": {
4099
  "version": "6.1.0",
4100
  "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz",
 
4203
  "node": ">=16.0.0"
4204
  }
4205
  },
4206
+ "node_modules/queue": {
4207
+ "version": "6.0.2",
4208
+ "resolved": "https://registry.npmjs.org/queue/-/queue-6.0.2.tgz",
4209
+ "integrity": "sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA==",
4210
+ "dev": true,
4211
+ "license": "MIT",
4212
+ "dependencies": {
4213
+ "inherits": "~2.0.3"
4214
+ }
4215
+ },
4216
  "node_modules/quick-lru": {
4217
  "version": "5.1.1",
4218
  "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
 
4419
  "url": "https://github.com/sponsors/sindresorhus"
4420
  }
4421
  },
4422
+ "node_modules/setimmediate": {
4423
+ "version": "1.0.5",
4424
+ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
4425
+ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",
4426
+ "dev": true,
4427
+ "license": "MIT"
4428
+ },
4429
  "node_modules/sharp": {
4430
  "version": "0.34.5",
4431
  "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
app/package.json CHANGED
@@ -1,7 +1,7 @@
1
  {
2
  "name": "devseis-ora",
3
  "productName": "Ora",
4
- "version": "0.2.1",
5
  "description": "Make videos from a prompt on your own computer with Wan2.1 1.3B and Wan2.2 5B.",
6
  "author": {
7
  "name": "Devseis",
@@ -23,6 +23,7 @@
23
  "esbuild": "0.25.10",
24
  "kokoro-js": "1.2.1",
25
  "mp4-muxer": "^5.2.1",
 
26
  "webm-muxer": "^5.1.4"
27
  },
28
  "license": "Apache-2.0",
@@ -41,7 +42,8 @@
41
  "models.json",
42
  "renderer/**",
43
  "package.json",
44
- "remote.cjs"
 
45
  ],
46
  "asar": true,
47
  "afterPack": "scripts/after-pack.cjs",
 
1
  {
2
  "name": "devseis-ora",
3
  "productName": "Ora",
4
+ "version": "0.3.0",
5
  "description": "Make videos from a prompt on your own computer with Wan2.1 1.3B and Wan2.2 5B.",
6
  "author": {
7
  "name": "Devseis",
 
23
  "esbuild": "0.25.10",
24
  "kokoro-js": "1.2.1",
25
  "mp4-muxer": "^5.2.1",
26
+ "pptxgenjs": "4.0.1",
27
  "webm-muxer": "^5.1.4"
28
  },
29
  "license": "Apache-2.0",
 
42
  "models.json",
43
  "renderer/**",
44
  "package.json",
45
+ "remote.cjs",
46
+ "n8n/**"
47
  ],
48
  "asar": true,
49
  "afterPack": "scripts/after-pack.cjs",
app/preload.cjs CHANGED
@@ -19,6 +19,16 @@ contextBridge.exposeInMainWorld('ora', {
19
  enhanceInterpolate: id => ipcRenderer.invoke('enhance:interpolate', id),
20
  enhanceCancel: id => ipcRenderer.invoke('enhance:cancel', id),
21
  enhanceImage: (id, index, bytes) => ipcRenderer.invoke('enhance:image', id, index, bytes),
 
 
 
 
 
 
 
 
 
 
22
  improvePrompt: (text, kind) => ipcRenderer.invoke('prompt:improve', text, kind),
23
  saveAd: (folder, name, bytes, ext) => ipcRenderer.invoke('ad:save', folder, name, bytes, ext),
24
  savePoster: (id, index, bytes, spec) => ipcRenderer.invoke('poster:save', id, index, bytes, spec),
 
19
  enhanceInterpolate: id => ipcRenderer.invoke('enhance:interpolate', id),
20
  enhanceCancel: id => ipcRenderer.invoke('enhance:cancel', id),
21
  enhanceImage: (id, index, bytes) => ipcRenderer.invoke('enhance:image', id, index, bytes),
22
+ planGet: () => ipcRenderer.invoke('plan:get'),
23
+ planSet: plan => ipcRenderer.invoke('plan:set', plan),
24
+ planPdf: (name, html, page) => ipcRenderer.invoke('plan:pdf', name, html, page),
25
+ planExport: (name, bytes, ext) => ipcRenderer.invoke('plan:export', name, bytes, ext),
26
+ writeCaption: (ctx, platform) => ipcRenderer.invoke('caption:write', ctx, platform),
27
+ savePost: post => ipcRenderer.invoke('post:save', post),
28
+ n8nSet: url => ipcRenderer.invoke('n8n:set', url),
29
+ n8nTest: () => ipcRenderer.invoke('n8n:test'),
30
+ n8nWorkflow: () => ipcRenderer.invoke('n8n:workflow'),
31
+ openPosts: () => ipcRenderer.invoke('open:posts'),
32
  improvePrompt: (text, kind) => ipcRenderer.invoke('prompt:improve', text, kind),
33
  saveAd: (folder, name, bytes, ext) => ipcRenderer.invoke('ad:save', folder, name, bytes, ext),
34
  savePoster: (id, index, bytes, spec) => ipcRenderer.invoke('poster:save', id, index, bytes, spec),
app/renderer-src/pptx.mjs ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ // PowerPoint export for Plan › Presentation: pptxgenjs (MIT), bundled into renderer/vendor/pptx.js.
2
+ import PptxGenJS from 'pptxgenjs';
3
+ export function newDeck() { return new PptxGenJS(); }
app/renderer/ad.js CHANGED
@@ -1,5 +1,5 @@
1
  'use strict';
2
- /* global Mp4Muxer, WebMMuxer, $, S, store, showView, POSTER_FONTS, wrapLines, roundRect, luminance, loadImg, cleanErr, MOODS, makeMusic, current */
3
  // Ad maker: joins a project's shots into one video, trims them to 15 or 30 s, writes the headline, offer and an
4
  // end card (button, website, logo) with real fonts, and encodes one MP4 per platform with WebCodecs.
5
 
@@ -538,11 +538,16 @@ async function saveAd() {
538
  saved.push(await window.ora.saveAd(folder, `${name} - ${f[3].replace(':', 'x')} ${f[4].split(' · ')[0]}`, out.bytes, out.ext));
539
  }
540
  $('adStatus').innerHTML = '';
 
541
  const p = document.createElement('span');
542
  p.textContent = `Saved ${saved.length} ad${saved.length > 1 ? 's' : ''} in your Videos folder (${folder}). `;
543
  const b = document.createElement('button'); b.className = 'link'; b.type = 'button'; b.textContent = 'Show in folder';
544
  b.addEventListener('click', () => window.ora.reveal(saved[0]));
545
- $('adStatus').append(p, b);
 
 
 
 
546
  } catch (e) {
547
  adError(`Could not make the ad: ${cleanErr(e)}`);
548
  } finally {
@@ -606,3 +611,13 @@ async function loadAdLogo() {
606
  if (ad.logo) { try { adLogoImg = await loadImg(`ora://video/${encodeURIComponent(ad.logo.id)}/${ad.logo.file}`); } catch { ad.logo = null; } }
607
  }
608
  (async () => { const saved = store('ora.ad') || {}; if (saved.logo) { ad.logo = saved.logo; await loadAdLogo(); } })();
 
 
 
 
 
 
 
 
 
 
 
1
  'use strict';
2
+ /* global Mp4Muxer, WebMMuxer, $, S, store, showView, openPost, plan, savePlan, POSTER_FONTS, wrapLines, roundRect, luminance, loadImg, cleanErr, MOODS, makeMusic, current */
3
  // Ad maker: joins a project's shots into one video, trims them to 15 or 30 s, writes the headline, offer and an
4
  // end card (button, website, logo) with real fonts, and encodes one MP4 per platform with WebCodecs.
5
 
 
538
  saved.push(await window.ora.saveAd(folder, `${name} - ${f[3].replace(':', 'x')} ${f[4].split(' · ')[0]}`, out.bytes, out.ext));
539
  }
540
  $('adStatus').innerHTML = '';
541
+ rememberAd(fmts[0], tl, saved).catch(() => { });
542
  const p = document.createElement('span');
543
  p.textContent = `Saved ${saved.length} ad${saved.length > 1 ? 's' : ''} in your Videos folder (${folder}). `;
544
  const b = document.createElement('button'); b.className = 'link'; b.type = 'button'; b.textContent = 'Show in folder';
545
  b.addEventListener('click', () => window.ora.reveal(saved[0]));
546
+ // Post…: the first size saved goes first (n8n posts that one); all sizes travel in the post folder
547
+ const pb = document.createElement('button'); pb.className = 'primary'; pb.type = 'button'; pb.textContent = 'Post this ad…';
548
+ const about = tl.segs.map(sg => { const m = S.videos.find(v => v.id === sg.id); return m ? (m.project ? m.project.title : m.prompt) : ''; }).filter(Boolean).join('. ');
549
+ pb.addEventListener('click', () => openPost({ files: saved, title: name.replace(/^Ad - /, ''), kind: 'ad', ctx: { about, title: ad.title, offer: ad.offer, cta: ad.cta, site: ad.site, brand: (brandVoice() || {}).brand || (brand.on ? brand.name : ''), tone: (brandVoice() || {}).tone || '', audience: mainPersona() } }));
550
+ $('adStatus').append(p, b, ' ', pb);
551
  } catch (e) {
552
  adError(`Could not make the ad: ${cleanErr(e)}`);
553
  } finally {
 
611
  if (ad.logo) { try { adLogoImg = await loadImg(`ora://video/${encodeURIComponent(ad.logo.id)}/${ad.logo.file}`); } catch { ad.logo = null; } }
612
  }
613
  (async () => { const saved = store('ora.ad') || {}; if (saved.logo) { ad.logo = saved.logo; await loadAdLogo(); } })();
614
+
615
+ // Plan › Presentation shows the ads made: keep a small picture of each (from the headline moment) in the plan
616
+ async function rememberAd(fmt, tl, files) {
617
+ if (typeof plan === 'undefined' || typeof savePlan !== 'function') return;
618
+ const k = 360 / Math.max(fmt[1], fmt[2]), W = Math.round(fmt[1] * k), H = Math.round(fmt[2] * k);
619
+ const cv = document.createElement('canvas'); cv.width = W; cv.height = H;
620
+ await drawAdFrame(cv.getContext('2d'), W, H, Math.min(1.5, tl.total / 2), tl);
621
+ plan.ads = [{ title: ad.title || 'Ad', files, formats: files.length, thumb: cv.toDataURL('image/jpeg', 0.82), ratio: fmt[3], created: new Date().toISOString() }, ...(plan.ads || [])].slice(0, 8);
622
+ savePlan();
623
+ }
app/renderer/app.js CHANGED
@@ -840,7 +840,11 @@ async function improveInto(ta, kind, btn, onDone) {
840
  btn.disabled = true; btn.textContent = 'Improving…';
841
  let out;
842
  try { out = await window.ora.improvePrompt(before, kind); }
843
- catch { out = polishOffline(before, kind); }
 
 
 
 
844
  btn.disabled = false; btn.textContent = label;
845
  ta.value = out; ta.dispatchEvent(new Event('input'));
846
  if (onDone) onDone(out);
@@ -994,13 +998,15 @@ function renderGrid() {
994
 
995
  let view = 'create';
996
  function showView(v) {
997
- view = ['create', 'library', 'models', 'online', 'ad'].includes(v) ? v : 'create';
998
  const setup = !$('setup').hidden && view === 'create';
999
  $('studio').hidden = view !== 'create' || setup || !S || !allReadyOrStarted();
1000
  $('libraryView').hidden = view !== 'library';
1001
  $('modelsView').hidden = view !== 'models';
1002
  $('onlineView').hidden = view !== 'online';
1003
  $('adView').hidden = view !== 'ad';
 
 
1004
  if (view !== 'create') $('setup').hidden = true; else if (S && !allReadyOrStarted()) $('setup').hidden = false;
1005
  for (const b of $('navTabs').children) b.toggleAttribute('aria-current', b.dataset.view === view), b.dataset.view === view && b.setAttribute('aria-current', 'page');
1006
  document.querySelector('main').scrollTop = 0;
@@ -1011,7 +1017,8 @@ function showView(v) {
1011
  refreshOnline();
1012
  }
1013
  }
1014
- function allReadyOrStarted() { return allReady(S.files) || (modelReady('fast') && store('ora.startedFast')); }
 
1015
 
1016
  // Example projects shown while the history is empty; clicking one fills the form.
1017
  const IDEAS = [
@@ -1062,10 +1069,10 @@ function useIdea(idea) {
1062
  // Video templates also set the Ad maker's text and music; poster and carousel templates set Ora's text fields.
1063
  const TEMPLATES = [
1064
  { title: 'Product launch', tag: 'Video ad · 9:16', mode: 'video', shape: 'portrait', styles: ['Product ad', 'Studio light'],
1065
- shots: ['Close-up of a matte black wireless earbud case on a dark reflective surface, the lid slowly opens, soft light sweeps across', 'The earbuds rise slightly out of the case, slow orbit around them, crisp reflections', 'The case alone in the centre on a clean dark background, gentle light, room for a logo'],
1066
  ad: { title: 'Meet the new Pulse Buds', offer: 'Launch price this week', cta: 'Pre-order now', music: 'upbeat' } },
1067
  { title: 'Sale / discount', tag: 'Video ad · 9:16', mode: 'video', shape: 'portrait', styles: ['Product ad', 'Golden hour'],
1068
- shots: ['A pair of white sneakers on a pastel orange background, the camera slowly pushes in', 'The sneakers turn slowly on a small round platform, warm light, soft shadow'],
1069
  ad: { title: 'The weekend sale is on', offer: '30% off everything', cta: 'Shop the sale', music: 'energetic' } },
1070
  { title: 'Event or training', tag: 'Poster · 4:5', mode: 'image', type: 'poster', shape: 'insta', styles: ['Studio light'],
1071
  image: 'A bright modern workspace with a laptop, a notebook and a coffee cup on a white desk, soft daylight, blue and orange accents',
@@ -1074,7 +1081,7 @@ const TEMPLATES = [
1074
  image: 'Soft abstract gradient background in calm blue and peach tones with gentle light, minimal, clean',
1075
  poster: { title: '5 ways AI saves you hours in marketing', sub: 'A quick guide for beginners', slides: 'Plan a month of posts in 10 minutes\nAutomate posting with n8n workflows\nWrite better ads with AI prompts\nJoin our free training on 15 November', cta: 'Register now', layout: 'card' } },
1076
  { title: 'Restaurant or food', tag: 'Video ad · 1:1', mode: 'video', shape: 'square', styles: ['Close-up', 'Golden hour'],
1077
- shots: ['A wood-fired pizza comes out of the oven, steam rising, warm firelight', 'Close-up of melted cheese stretching as a slice is lifted, slow motion', 'A cosy restaurant table with the pizza and two glasses, warm evening light'],
1078
  ad: { title: 'Fresh from the fire', offer: 'Free dessert this Friday', cta: 'Book a table', music: 'lofi' } },
1079
  { title: 'Real estate tour', tag: 'Video ad · 16:9', mode: 'video', shape: 'landscape', styles: ['Drone shot', 'Golden hour'],
1080
  shots: ['Aerial view of a modern white villa with a pool at sunset, the camera glides slowly forward', 'A bright open living room with large windows and a sea view, the camera moves slowly through', 'The terrace at dusk with soft lights turning on, calm water in the pool'],
@@ -1083,7 +1090,7 @@ const TEMPLATES = [
1083
  shots: ['A model in a flowing linen dress walks along a sunny stone street, slow motion, fabric moving in the wind', 'Close-up of the fabric and buttons, soft natural light', 'The model turns and smiles, warm sunset light'],
1084
  ad: { title: 'The summer linen edit', offer: 'New collection', cta: 'Discover now', music: 'cinematic' } },
1085
  { title: 'Customer testimonial', tag: 'Video ad · 16:9', mode: 'video', shape: 'landscape', styles: ['Handheld', 'Golden hour'],
1086
- shots: ['A smiling café owner wipes the counter of her small bakery in the morning, natural light', 'She hands a paper bag of fresh bread to a customer, friendly moment'],
1087
  ad: { title: 'We doubled our orders in a month', offer: 'Maria, Sunrise Bakery', cta: 'Start your free trial', music: 'corporate' } },
1088
  { title: 'Skincare product', tag: 'Poster · 1:1', mode: 'image', type: 'poster', shape: 'square', styles: ['Product ad', 'Studio light'],
1089
  image: 'A frosted glass serum bottle with a gold cap on a pale pink stone pedestal, soft shadows, water droplets, clean beige background, premium product photography',
@@ -1103,10 +1110,19 @@ function renderTemplates() {
1103
  g.appendChild(b);
1104
  }
1105
  }
 
 
 
 
 
 
 
1106
  function useTemplate(t) {
1107
  if (queue) return;
 
 
1108
  if (t.mode === 'video') {
1109
- useIdea({ ...t, scene: '' });
1110
  // the Ad maker picks these up when it opens
1111
  const a = store('ora.ad') || {};
1112
  store('ora.ad', { ...a, title: t.ad.title, offer: t.ad.offer, cta: t.ad.cta, music: t.ad.music, voiceText: '' });
@@ -1126,7 +1142,14 @@ function formNote(msg) {
1126
  n.textContent = msg; n.hidden = !msg;
1127
  clearTimeout(formNote.t); formNote.t = setTimeout(() => { n.hidden = true; }, 15000);
1128
  }
1129
- $('templatesBtn').addEventListener('click', () => { renderTemplates(); $('templateDlg').showModal(); });
 
 
 
 
 
 
 
1130
  $('templateClose').addEventListener('click', () => $('templateDlg').close());
1131
 
1132
  function formError(msg) { $('formError').hidden = !msg; $('formError').textContent = msg || ''; if (msg) $('formError').scrollIntoView({ block: 'center', behavior: 'smooth' }); }
@@ -1187,6 +1210,7 @@ async function submit(e) {
1187
  formError('');
1188
  if (queue) return;
1189
  if (mode === 'image') return submitImages();
 
1190
  const empty = shots.findIndex(t => t.trim().length < 3);
1191
  if (empty >= 0) return formError(shots.length > 1 ? `Shot ${empty + 1} is empty. Describe it or remove it.` : 'Describe the video first.');
1192
  const seedText = $('seed').value.trim();
@@ -1598,6 +1622,7 @@ async function init() {
1598
  renderIdeas();
1599
  $('stageHint').textContent = S.hardware.engine.gpu ? 'Tip: use Quick look to check a prompt fast, then make the full video with Fast or Quality.' : 'Tip: on the processor, use Quick look to check a prompt first. Full videos take much longer.';
1600
  if (allReady(S.files) || (modelReady('fast') && store('ora.startedFast'))) { showStudio(); if (!allReady(S.files) && !S.downloading) window.ora.downloadStart(); }
 
1601
  else showSetup(S.downloading);
1602
  showStage('empty');
1603
  if (S.running) window.ora.cancel(); // a run left over from a closed window cannot be followed: stop it
@@ -1618,6 +1643,11 @@ window.ora.onDownloadDone(p => {
1618
  S.files = p.status; setDownloading(false); renderSetup(p.status, 'All models are ready.');
1619
  if ($('studio').hidden) setTimeout(showStudio, 700); else sync();
1620
  });
 
 
 
 
 
1621
  $('startFastBtn').addEventListener('click', () => { store('ora.startedFast', true); if (!$('downloadBtn').dataset.on) window.ora.downloadStart(); showStudio(); });
1622
  window.ora.onDownloadError(p => {
1623
  if (p.set === 'voice') { S.files = p.status; return; } // the Ad maker shows this one
 
840
  btn.disabled = true; btn.textContent = 'Improving…';
841
  let out;
842
  try { out = await window.ora.improvePrompt(before, kind); }
843
+ catch (e) {
844
+ out = polishOffline(before, kind);
845
+ // the online helper said no (it follows Cloudflare's content rules): keep the person's words, tidied
846
+ if (/declined/.test(cleanErr(e))) formNote('The online prompt helper declined this prompt, so Ora only tidied your words.');
847
+ }
848
  btn.disabled = false; btn.textContent = label;
849
  ta.value = out; ta.dispatchEvent(new Event('input'));
850
  if (onDone) onDone(out);
 
998
 
999
  let view = 'create';
1000
  function showView(v) {
1001
+ view = ['create', 'plan', 'library', 'models', 'online', 'ad'].includes(v) ? v : 'create';
1002
  const setup = !$('setup').hidden && view === 'create';
1003
  $('studio').hidden = view !== 'create' || setup || !S || !allReadyOrStarted();
1004
  $('libraryView').hidden = view !== 'library';
1005
  $('modelsView').hidden = view !== 'models';
1006
  $('onlineView').hidden = view !== 'online';
1007
  $('adView').hidden = view !== 'ad';
1008
+ $('planView').hidden = view !== 'plan';
1009
+ if (view === 'plan' && typeof renderPlan === 'function') renderPlan();
1010
  if (view !== 'create') $('setup').hidden = true; else if (S && !allReadyOrStarted()) $('setup').hidden = false;
1011
  for (const b of $('navTabs').children) b.toggleAttribute('aria-current', b.dataset.view === view), b.dataset.view === view && b.setAttribute('aria-current', 'page');
1012
  document.querySelector('main').scrollTop = 0;
 
1017
  refreshOnline();
1018
  }
1019
  }
1020
+ // "Skip" on the download screen: a class can plan and make pictures online without the 12 GB of video models
1021
+ function allReadyOrStarted() { return allReady(S.files) || (modelReady('fast') && store('ora.startedFast')) || !!store('ora.skipModels'); }
1022
 
1023
  // Example projects shown while the history is empty; clicking one fills the form.
1024
  const IDEAS = [
 
1069
  // Video templates also set the Ad maker's text and music; poster and carousel templates set Ora's text fields.
1070
  const TEMPLATES = [
1071
  { title: 'Product launch', tag: 'Video ad · 9:16', mode: 'video', shape: 'portrait', styles: ['Product ad', 'Studio light'],
1072
+ shots: ['Close-up of a matte black wireless earbud case on a dark reflective surface, the lid slowly opens, soft light sweeps across', 'The earbuds rise slightly out of the case, slow orbit around them, crisp reflections', '{who} puts the earbuds in and smiles, walking through a bright city street, natural light'],
1073
  ad: { title: 'Meet the new Pulse Buds', offer: 'Launch price this week', cta: 'Pre-order now', music: 'upbeat' } },
1074
  { title: 'Sale / discount', tag: 'Video ad · 9:16', mode: 'video', shape: 'portrait', styles: ['Product ad', 'Golden hour'],
1075
+ shots: ['A pair of white sneakers on a pastel orange background, the camera slowly pushes in', 'The sneakers turn slowly on a small round platform, warm light, soft shadow', '{who} ties the laces and jogs off happily, golden light'],
1076
  ad: { title: 'The weekend sale is on', offer: '30% off everything', cta: 'Shop the sale', music: 'energetic' } },
1077
  { title: 'Event or training', tag: 'Poster · 4:5', mode: 'image', type: 'poster', shape: 'insta', styles: ['Studio light'],
1078
  image: 'A bright modern workspace with a laptop, a notebook and a coffee cup on a white desk, soft daylight, blue and orange accents',
 
1081
  image: 'Soft abstract gradient background in calm blue and peach tones with gentle light, minimal, clean',
1082
  poster: { title: '5 ways AI saves you hours in marketing', sub: 'A quick guide for beginners', slides: 'Plan a month of posts in 10 minutes\nAutomate posting with n8n workflows\nWrite better ads with AI prompts\nJoin our free training on 15 November', cta: 'Register now', layout: 'card' } },
1083
  { title: 'Restaurant or food', tag: 'Video ad · 1:1', mode: 'video', shape: 'square', styles: ['Close-up', 'Golden hour'],
1084
+ shots: ['A wood-fired pizza comes out of the oven, steam rising, warm firelight', 'Close-up of melted cheese stretching as a slice is lifted, slow motion', '{who} shares the pizza with a friend at a cosy restaurant table, warm evening light'],
1085
  ad: { title: 'Fresh from the fire', offer: 'Free dessert this Friday', cta: 'Book a table', music: 'lofi' } },
1086
  { title: 'Real estate tour', tag: 'Video ad · 16:9', mode: 'video', shape: 'landscape', styles: ['Drone shot', 'Golden hour'],
1087
  shots: ['Aerial view of a modern white villa with a pool at sunset, the camera glides slowly forward', 'A bright open living room with large windows and a sea view, the camera moves slowly through', 'The terrace at dusk with soft lights turning on, calm water in the pool'],
 
1090
  shots: ['A model in a flowing linen dress walks along a sunny stone street, slow motion, fabric moving in the wind', 'Close-up of the fabric and buttons, soft natural light', 'The model turns and smiles, warm sunset light'],
1091
  ad: { title: 'The summer linen edit', offer: 'New collection', cta: 'Discover now', music: 'cinematic' } },
1092
  { title: 'Customer testimonial', tag: 'Video ad · 16:9', mode: 'video', shape: 'landscape', styles: ['Handheld', 'Golden hour'],
1093
+ shots: ['A smiling café owner wipes the counter of her small bakery in the morning, natural light', 'She hands a paper bag of fresh bread to {who}, friendly moment'],
1094
  ad: { title: 'We doubled our orders in a month', offer: 'Maria, Sunrise Bakery', cta: 'Start your free trial', music: 'corporate' } },
1095
  { title: 'Skincare product', tag: 'Poster · 1:1', mode: 'image', type: 'poster', shape: 'square', styles: ['Product ad', 'Studio light'],
1096
  image: 'A frosted glass serum bottle with a gold cap on a pale pink stone pedestal, soft shadows, water droplets, clean beige background, premium product photography',
 
1110
  g.appendChild(b);
1111
  }
1112
  }
1113
+ // "For": the chosen persona becomes the person in the template's shots ({who}) and the audience of its captions
1114
+ function templateWho() {
1115
+ const id = $('tplFor').value;
1116
+ const p = (typeof plan !== 'undefined' && plan.personas || []).find(x => x.id === id);
1117
+ if (!p) return 'a happy customer';
1118
+ return `a ${p.age ? `${p.age}-year-old ` : ''}${(p.job || 'customer').toLowerCase()}`;
1119
+ }
1120
  function useTemplate(t) {
1121
  if (queue) return;
1122
+ const who = templateWho();
1123
+ store('ora.postFor', $('tplFor').value);
1124
  if (t.mode === 'video') {
1125
+ useIdea({ ...t, scene: '', shots: t.shots.map(x => x.replace('{who}', who).replace(/^a /, 'A ')) });
1126
  // the Ad maker picks these up when it opens
1127
  const a = store('ora.ad') || {};
1128
  store('ora.ad', { ...a, title: t.ad.title, offer: t.ad.offer, cta: t.ad.cta, music: t.ad.music, voiceText: '' });
 
1142
  n.textContent = msg; n.hidden = !msg;
1143
  clearTimeout(formNote.t); formNote.t = setTimeout(() => { n.hidden = true; }, 15000);
1144
  }
1145
+ $('templatesBtn').addEventListener('click', () => {
1146
+ const sel = $('tplFor'), ps = (typeof plan !== 'undefined' && plan.personas || []).filter(p => p.name);
1147
+ sel.innerHTML = '<option value="">Everyone</option>' + ps.map(p => `<option></option>`).join('');
1148
+ ps.forEach((p, i) => { sel.options[i + 1].value = p.id; sel.options[i + 1].textContent = `${p.name}${p.job ? ` · ${p.job}` : ''}`; });
1149
+ sel.value = store('ora.postFor') || (ps.find(p => p.main) || {}).id || '';
1150
+ $('tplForRow').hidden = !ps.length;
1151
+ renderTemplates(); $('templateDlg').showModal();
1152
+ });
1153
  $('templateClose').addEventListener('click', () => $('templateDlg').close());
1154
 
1155
  function formError(msg) { $('formError').hidden = !msg; $('formError').textContent = msg || ''; if (msg) $('formError').scrollIntoView({ block: 'center', behavior: 'smooth' }); }
 
1210
  formError('');
1211
  if (queue) return;
1212
  if (mode === 'image') return submitImages();
1213
+ if (runWhere() === 'local' && !modelReady(jobModel(form))) return formError('This computer has no video model yet. Download one in Models (Fast is 6.5 GB), or choose Run on › Online.');
1214
  const empty = shots.findIndex(t => t.trim().length < 3);
1215
  if (empty >= 0) return formError(shots.length > 1 ? `Shot ${empty + 1} is empty. Describe it or remove it.` : 'Describe the video first.');
1216
  const seedText = $('seed').value.trim();
 
1622
  renderIdeas();
1623
  $('stageHint').textContent = S.hardware.engine.gpu ? 'Tip: use Quick look to check a prompt fast, then make the full video with Fast or Quality.' : 'Tip: on the processor, use Quick look to check a prompt first. Full videos take much longer.';
1624
  if (allReady(S.files) || (modelReady('fast') && store('ora.startedFast'))) { showStudio(); if (!allReady(S.files) && !S.downloading) window.ora.downloadStart(); }
1625
+ else if (store('ora.skipModels')) showStudio();
1626
  else showSetup(S.downloading);
1627
  showStage('empty');
1628
  if (S.running) window.ora.cancel(); // a run left over from a closed window cannot be followed: stop it
 
1643
  S.files = p.status; setDownloading(false); renderSetup(p.status, 'All models are ready.');
1644
  if ($('studio').hidden) setTimeout(showStudio, 700); else sync();
1645
  });
1646
+ $('skipModelsBtn').addEventListener('click', () => {
1647
+ store('ora.skipModels', true);
1648
+ showStudio(); setMode('image');
1649
+ formNote('Video models are not downloaded. Connect Cloudflare in Online to make pictures in seconds, and use Plan for your campaign. Download video models any time in Models.');
1650
+ });
1651
  $('startFastBtn').addEventListener('click', () => { store('ora.startedFast', true); if (!$('downloadBtn').dataset.on) window.ora.downloadStart(); showStudio(); });
1652
  window.ora.onDownloadError(p => {
1653
  if (p.set === 'voice') { S.files = p.status; return; } // the Ad maker shows this one
app/renderer/calendar.js ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ /* global $, S, store, plan, savePlan, loadPlan, showView, setMode, imgForm, poster, renderPosterFields, renderImgShapes, shots, renderShots,
3
+ formNote, openPost, filesOf, itemContext, cleanErr, hexName, defaultStep, offlineCaption, loadImg */
4
+ // Plan › 3 Calendar: content ideas (the course's content types), a 30-day calendar filled from them, each day linked
5
+ // to something made in Ora and posted with Post… (Ready to post / n8n). Plan › 4 Presentation: a 16:9 PDF deck.
6
+
7
+ const CONTENT_TYPES = [
8
+ // validated categorical order (dataviz reference palette, light surface); always shown with a text label
9
+ ['educational', 'Educational', '#2a78d6'], ['storytelling', 'Storytelling', '#eb6834'], ['behind-the-scenes', 'Behind the scenes', '#1baf7a'],
10
+ ['community', 'Community', '#eda100'], ['lifestyle', 'Lifestyle', '#e87ba4'], ['promotion', 'Offer', '#008300'],
11
+ ];
12
+ const STATUSES = [['idea', 'Idea'], ['made', 'Made'], ['scheduled', 'Scheduled'], ['posted', 'Posted']];
13
+ const typeOf = id => CONTENT_TYPES.find(t => t[0] === id) || CONTENT_TYPES[0];
14
+ const ymd = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
15
+ const parseYmd = s => { const [y, m, d] = s.split('-').map(Number); return new Date(y, m - 1, d); };
16
+ let calDay = null; // date (YYYY-MM-DD) open in the day editor
17
+
18
+ function cal() {
19
+ if (!plan.calendar) {
20
+ const t = new Date(); t.setDate(t.getDate() + 1);
21
+ plan.calendar = { start: ymd(t), perWeek: 3, time: '09:00', ideas: [], days: {} };
22
+ }
23
+ return plan.calendar;
24
+ }
25
+ function calDays() {
26
+ const c = cal(), start = parseYmd(c.start), out = [];
27
+ for (let i = 0; i < 30; i++) { const d = new Date(start); d.setDate(start.getDate() + i); out.push(d); }
28
+ return out;
29
+ }
30
+
31
+ // --- ideas ---------------------------------------------------------------------------------------------------------
32
+
33
+ // Ora's own ideas (offline), from the brand and the main persona
34
+ function offlineIdeas() {
35
+ const b = plan.brand || {}, p = (plan.personas || []).find(x => x.main) || (plan.personas || [])[0] || {};
36
+ const name = b.name || 'our brand';
37
+ const what = (b.offer || 'what we make').split(/\s+(in|for|near|at)\s+/i)[0].toLowerCase();
38
+ return [
39
+ ['educational', `3 quick tips about ${what}`], ['educational', `How to choose good ${what}`], ['educational', `Myth or fact? Something people get wrong about ${what}`],
40
+ ['storytelling', `Why we started ${name}`], ['storytelling', `A customer story: how ${p.name || 'a regular'} uses ${what}`],
41
+ ['behind-the-scenes', `How we make our ${what}, step by step`], ['behind-the-scenes', 'Meet the team: who is behind the counter'],
42
+ ['community', `Ask us anything about ${what}`], ['community', 'Customer of the week'],
43
+ ['lifestyle', `${what.charAt(0).toUpperCase() + what.slice(1)} as part of a busy day`], ['lifestyle', `Weekend mood with ${name}`],
44
+ ['promotion', 'New this week, and a small offer to try it'],
45
+ ];
46
+ }
47
+ function renderIdeas() {
48
+ const c = cal(), list = $('ideaList');
49
+ list.innerHTML = '';
50
+ for (const [i, idea] of c.ideas.entries()) {
51
+ const t = typeOf(idea.type);
52
+ const row = document.createElement('div');
53
+ row.className = 'idea-row';
54
+ row.innerHTML = '<span class="dot"></span><span class="t"></span><button type="button" title="Remove">✕</button>';
55
+ row.querySelector('.dot').style.background = t[2];
56
+ row.querySelector('.dot').title = t[1];
57
+ row.querySelector('.t').textContent = idea.text;
58
+ row.querySelector('button').addEventListener('click', () => { c.ideas.splice(i, 1); renderIdeas(); savePlan(); });
59
+ list.appendChild(row);
60
+ }
61
+ $('ideaCount').textContent = c.ideas.length ? `· ${c.ideas.length}` : '';
62
+ $('calFill').disabled = !c.ideas.length;
63
+ }
64
+ function addIdeas(pairs) {
65
+ const c = cal(), have = new Set(c.ideas.map(x => x.text.toLowerCase()));
66
+ for (const [type, text] of pairs) if (text && !have.has(text.toLowerCase())) { c.ideas.push({ id: `i${Date.now()}${Math.random().toString(36).slice(2, 6)}`, type, text }); have.add(text.toLowerCase()); }
67
+ renderIdeas(); savePlan();
68
+ }
69
+
70
+ // spreads the ideas over the 30 days: N posts a week on fixed weekdays, mixing the content types
71
+ function fillMonth() {
72
+ const c = cal();
73
+ if (!c.ideas.length) return;
74
+ const pattern = { 3: [1, 3, 5], 5: [1, 2, 3, 4, 5], 7: [0, 1, 2, 3, 4, 5, 6] }[c.perWeek] || [1, 3, 5];
75
+ const byType = {};
76
+ for (const i of c.ideas) (byType[i.type] = byType[i.type] || []).push(i);
77
+ const order = CONTENT_TYPES.map(t => t[0]).filter(t => byType[t]);
78
+ let k = 0, filled = 0;
79
+ const used = new Map();
80
+ for (const d of calDays()) {
81
+ const key = ymd(d);
82
+ if (!pattern.includes(d.getDay())) continue;
83
+ if (c.days[key] && (c.days[key].item || c.days[key].status !== 'idea')) continue; // keep days already worked on
84
+ // rotate through the content types, and through the ideas inside each
85
+ const type = order[k % order.length]; k++;
86
+ const pool = byType[type], n = used.get(type) || 0; used.set(type, n + 1);
87
+ const idea = pool[n % pool.length];
88
+ c.days[key] = { type: idea.type, text: idea.text, platforms: store('ora.postPlatforms') || ['instagram', 'linkedin'], status: 'idea', item: null };
89
+ filled++;
90
+ }
91
+ $('ideaNote').textContent = `Placed ${filled} posts. Click a day to change it, make the content or post it.`;
92
+ renderCalendar(); savePlan();
93
+ }
94
+
95
+ // --- month grid ----------------------------------------------------------------------------------------------------------
96
+
97
+ function renderCalendar() {
98
+ const c = cal();
99
+ $('calStart').value = c.start; $('calTime').value = c.time || '09:00';
100
+ const pw = $('calPerWeek'); pw.innerHTML = '';
101
+ for (const n of [3, 5, 7]) {
102
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = String(n); b.setAttribute('aria-checked', String(c.perWeek === n));
103
+ b.addEventListener('click', () => { c.perWeek = n; renderCalendar(); savePlan(); });
104
+ pw.appendChild(b);
105
+ }
106
+ const sel = $('ideaType');
107
+ if (!sel.options.length) for (const [id, label] of CONTENT_TYPES) { const o = document.createElement('option'); o.value = id; o.textContent = label; sel.appendChild(o); }
108
+ renderIdeas();
109
+ const days = calDays(), g = $('calGrid');
110
+ g.innerHTML = '';
111
+ for (const n of ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']) { const h = document.createElement('div'); h.className = 'cal-dow'; h.textContent = n; g.appendChild(h); }
112
+ const lead = (days[0].getDay() + 6) % 7; // Monday-first
113
+ for (let i = 0; i < lead; i++) { const e = document.createElement('div'); e.className = 'cal-day out'; g.appendChild(e); }
114
+ const counts = {};
115
+ for (const d of days) {
116
+ const key = ymd(d), e = c.days[key];
117
+ const cell = document.createElement('button');
118
+ cell.type = 'button'; cell.className = 'cal-day';
119
+ cell.innerHTML = '<span class="d"></span>';
120
+ cell.querySelector('.d').textContent = d.toLocaleDateString(undefined, { day: 'numeric', month: d.getDate() === 1 || d === days[0] ? 'short' : undefined });
121
+ if (e) {
122
+ counts[e.type] = (counts[e.type] || 0) + 1;
123
+ const t = typeOf(e.type);
124
+ cell.style.borderLeft = `4px solid ${t[2]}`;
125
+ const meta = e.item && S.videos.find(v => v.id === e.item.id);
126
+ if (meta) { const im = document.createElement('img'); im.src = `ora://video/${encodeURIComponent(meta.id)}/${meta.kind === 'image' ? meta.images[0] : 'poster.png'}`; im.alt = ''; cell.appendChild(im); }
127
+ const tx = document.createElement('span'); tx.className = 'e'; tx.textContent = e.text; cell.appendChild(tx);
128
+ const st = document.createElement('span'); st.className = 's';
129
+ st.textContent = `${STATUSES.find(x => x[0] === e.status)[1]} · ${(e.platforms || []).map(p => ({ instagram: 'IG', facebook: 'FB', linkedin: 'IN' })[p]).join(' ')}`;
130
+ cell.appendChild(st);
131
+ }
132
+ cell.addEventListener('click', () => openDay(key));
133
+ g.appendChild(cell);
134
+ }
135
+ const end = days[days.length - 1];
136
+ $('calTitle').textContent = `${days[0].toLocaleDateString(undefined, { day: 'numeric', month: 'long' })} – ${end.toLocaleDateString(undefined, { day: 'numeric', month: 'long', year: 'numeric' })}`;
137
+ const total = Object.values(counts).reduce((a, n) => a + n, 0);
138
+ $('calMix').textContent = total ? `${total} posts · ${Object.entries(counts).map(([k, n]) => `${n} ${typeOf(k)[1].toLowerCase()}`).join(', ')}` : '';
139
+ $('calLegend').innerHTML = '';
140
+ for (const [, label, color] of CONTENT_TYPES) { const s = document.createElement('span'); s.innerHTML = '<i class="dot"></i>'; s.querySelector('i').style.background = color; s.append(label); $('calLegend').appendChild(s); }
141
+ }
142
+
143
+ // --- one day ---------------------------------------------------------------------------------------------------------------
144
+
145
+ function openDay(key) {
146
+ const c = cal();
147
+ calDay = key;
148
+ const e = c.days[key] || (c.days[key] = { type: 'educational', text: '', platforms: store('ora.postPlatforms') || ['instagram', 'linkedin'], status: 'idea', item: null });
149
+ $('dayTitle').textContent = parseYmd(key).toLocaleDateString(undefined, { weekday: 'long', day: 'numeric', month: 'long' });
150
+ const sel = $('dayType'); sel.innerHTML = '';
151
+ for (const [id, label] of CONTENT_TYPES) { const o = document.createElement('option'); o.value = id; o.textContent = label; sel.appendChild(o); }
152
+ sel.value = e.type; $('dayText').value = e.text;
153
+ const pl = $('dayPlatforms'); pl.innerHTML = '';
154
+ for (const [id, label] of [['instagram', 'Instagram'], ['facebook', 'Facebook'], ['linkedin', 'LinkedIn']]) {
155
+ const l = document.createElement('label'); l.innerHTML = '<input type="checkbox"><span></span>'; l.querySelector('span').textContent = label;
156
+ const cb = l.querySelector('input'); cb.checked = (e.platforms || []).includes(id);
157
+ cb.addEventListener('change', () => { e.platforms = cb.checked ? [...new Set([...(e.platforms || []), id])] : e.platforms.filter(x => x !== id); savePlan(); });
158
+ pl.appendChild(l);
159
+ }
160
+ const st = $('dayStatus'); st.innerHTML = '';
161
+ for (const [id, label] of STATUSES) {
162
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = label; b.setAttribute('aria-checked', String(e.status === id));
163
+ b.addEventListener('click', () => { e.status = id; openDay(key); savePlan(); });
164
+ st.appendChild(b);
165
+ }
166
+ const meta = e.item && S.videos.find(v => v.id === e.item.id);
167
+ $('dayItem').innerHTML = '';
168
+ if (meta) {
169
+ const im = document.createElement('img'); im.src = `ora://video/${encodeURIComponent(meta.id)}/${meta.kind === 'image' ? meta.images[0] : 'poster.png'}`; im.alt = '';
170
+ const t = document.createElement('span'); t.textContent = `${meta.kind === 'image' ? (meta.poster ? (meta.poster.carousel ? 'Carousel' : 'Poster') : 'Image') : 'Video'}: ${meta.project ? meta.project.title : meta.prompt.slice(0, 60)}`;
171
+ $('dayItem').append(im, t);
172
+ } else $('dayItem').innerHTML = '<span class="muted small">Nothing yet: make it in Create, or pick something you already made.</span>';
173
+ $('dayPost').disabled = !meta;
174
+ renderDayCaps(e);
175
+ $('dayPicker').hidden = true;
176
+ if (!$('dayDlg').open) $('dayDlg').showModal();
177
+ }
178
+ function dayEntry() { return cal().days[calDay]; }
179
+ // the day's captions, one per platform; Post… starts from them and saves back what was posted
180
+ function renderDayCaps(e) {
181
+ e.captions = e.captions || {};
182
+ const box = $('dayCaps'); box.innerHTML = '';
183
+ const pls = e.platforms && e.platforms.length ? e.platforms : [];
184
+ if (!pls.length) { box.innerHTML = '<span class="muted small">Pick where to post first.</span>'; return; }
185
+ for (const p of pls) {
186
+ const d = document.createElement('div'); d.className = 'post-cap';
187
+ d.innerHTML = '<div class="post-cap-head"><span></span></div><textarea maxlength="3000"></textarea>';
188
+ d.querySelector('span').textContent = { instagram: 'Instagram', facebook: 'Facebook', linkedin: 'LinkedIn' }[p];
189
+ const ta = d.querySelector('textarea'); ta.value = e.captions[p] || ''; ta.style.minHeight = '70px';
190
+ ta.addEventListener('input', () => { e.captions[p] = ta.value; savePlan(); });
191
+ box.appendChild(d);
192
+ }
193
+ }
194
+ function dayCtx(e) {
195
+ const meta = e.item && S.videos.find(v => v.id === e.item.id);
196
+ const base = meta ? itemContext(meta, { about: `${e.text}. ${meta.prompt || ''}`.slice(0, 600) }) : itemContext({ prompt: e.text }, { about: e.text });
197
+ return { ...base, title: e.text };
198
+ }
199
+ $('dayWrite').addEventListener('click', async ev => {
200
+ const e = dayEntry(), b = ev.currentTarget; if (!e || !e.text.trim()) { $('dayText').focus(); return; }
201
+ b.disabled = true; const label = b.textContent; b.textContent = 'Writing…';
202
+ const ctx = dayCtx(e); let online = 0, total = 0;
203
+ for (const p of e.platforms || []) {
204
+ total++;
205
+ try { e.captions[p] = await window.ora.writeCaption(ctx, p); online++; } catch { e.captions[p] = offlineCaption(ctx, p); }
206
+ }
207
+ savePlan(); renderDayCaps(e); b.disabled = false; b.textContent = label;
208
+ $('dayCapNote').textContent = online === total ? 'Written with Cloudflare\'s text model.' : 'Written by Ora offline from the idea. Connect Cloudflare for richer captions.';
209
+ });
210
+ $('dayType').addEventListener('change', e => { dayEntry().type = e.target.value; savePlan(); });
211
+ $('dayText').addEventListener('input', e => { dayEntry().text = e.target.value; savePlan(); });
212
+ $('dayClose').addEventListener('click', () => { $('dayDlg').close(); renderCalendar(); });
213
+ $('dayClear').addEventListener('click', () => { delete cal().days[calDay]; savePlan(); $('dayDlg').close(); renderCalendar(); });
214
+ $('dayLink').addEventListener('click', () => {
215
+ const box = $('dayPicker');
216
+ box.hidden = !box.hidden;
217
+ if (box.hidden) return;
218
+ box.innerHTML = '';
219
+ for (const m of S.videos.filter(v => v.status === 'done' || v.file || v.images).slice(0, 40)) {
220
+ const im = document.createElement('img');
221
+ im.src = `ora://video/${encodeURIComponent(m.id)}/${m.kind === 'image' ? m.images[0] : 'poster.png'}`;
222
+ im.title = m.project ? m.project.title : m.prompt;
223
+ im.addEventListener('click', () => { const e = dayEntry(); e.item = { id: m.id }; if (e.status === 'idea') e.status = 'made'; savePlan(); openDay(calDay); });
224
+ box.appendChild(im);
225
+ }
226
+ });
227
+ // Create, prefilled for this day: a poster for tips and offers, a video for stories and behind the scenes
228
+ $('dayMake').addEventListener('click', () => {
229
+ const e = dayEntry();
230
+ if (!e.text.trim()) { $('dayText').focus(); return; }
231
+ const video = ['storytelling', 'behind-the-scenes', 'lifestyle'].includes(e.type);
232
+ const what = (plan.brand && plan.brand.offer) || '';
233
+ if (video) {
234
+ shots.splice(0, shots.length, `${e.text}${what ? `, for ${what}` : ''}, natural light, realistic`);
235
+ renderShots(); showView('create'); setMode('video');
236
+ } else {
237
+ imgForm.type = 'poster'; imgForm.shape = 'insta'; store('ora.imgForm', imgForm);
238
+ poster.title = e.text; poster.sub = plan.brand && plan.brand.name ? plan.brand.name : ''; poster.details = ''; store('ora.poster', poster); renderPosterFields();
239
+ $('imgPrompt').value = what ? `A bright, appealing scene that shows ${what}` : '';
240
+ renderImgShapes(); showView('create'); setMode('image');
241
+ }
242
+ $('dayDlg').close();
243
+ formNote(`Calendar, ${parseYmd(calDay).toLocaleDateString()}: "${e.text}" is ready in the form. Press Make; then in Plan › Calendar open the day and press "Use something I made…".`);
244
+ });
245
+ $('dayPost').addEventListener('click', () => {
246
+ const e = dayEntry(), meta = e.item && S.videos.find(v => v.id === e.item.id);
247
+ if (!meta) return;
248
+ const [h, m] = (cal().time || '09:00').split(':').map(Number);
249
+ const when = parseYmd(calDay); when.setHours(h, m, 0, 0);
250
+ store('ora.postPlatforms', e.platforms && e.platforms.length ? e.platforms : ['instagram']);
251
+ const day = calDay;
252
+ $('dayDlg').close();
253
+ openPost({ files: filesOf(meta), title: e.text || (meta.project ? meta.project.title : ''), kind: meta.kind || 'video', when, ctx: dayCtx(e), captions: { ...(e.captions || {}) },
254
+ onSaved: r => { const x = cal().days[day]; if (x) { x.status = r.sent ? 'scheduled' : 'made'; x.captions = { ...(x.captions || {}), ...r.captions }; savePlan(); renderCalendar(); } } });
255
+ });
256
+
257
+ // --- calendar controls and exports ---------------------------------------------------------------------------------------
258
+
259
+ $('calStart').addEventListener('change', e => { if (e.target.value) { cal().start = e.target.value; renderCalendar(); savePlan(); } });
260
+ $('calTime').addEventListener('change', e => { cal().time = e.target.value || '09:00'; savePlan(); });
261
+ $('ideaAdd').addEventListener('click', () => { const t = $('ideaText').value.trim(); if (t) { addIdeas([[$('ideaType').value, t]]); $('ideaText').value = ''; } });
262
+ $('ideaText').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); $('ideaAdd').click(); } });
263
+ $('calFill').addEventListener('click', fillMonth);
264
+ $('ideaSuggest').addEventListener('click', async e => {
265
+ const b = e.currentTarget, label = b.textContent; b.disabled = true; b.textContent = 'Thinking…';
266
+ const facts = [plan.brand.name && `Brand: ${plan.brand.name}`, plan.brand.offer && `Offers: ${plan.brand.offer}`, plan.brand.values && `Values: ${plan.brand.values}`,
267
+ ...(plan.personas || []).filter(p => p.name).map(p => `Audience: ${p.name}, ${p.age || ''} ${p.job || ''}; needs ${p.needs || ''}`)].filter(Boolean).join('\n');
268
+ try {
269
+ if (!facts) throw new Error('nofacts');
270
+ const text = await window.ora.improvePrompt(facts, 'ideas');
271
+ addIdeas(text.split('\n').map(l => { const [t, ...rest] = l.split(':'); const id = CONTENT_TYPES.find(x => x[0] === t.trim().toLowerCase().replace(/\s+/g, '-')); return [id ? id[0] : 'educational', rest.join(':').trim()]; }));
272
+ $('ideaNote').textContent = 'Ideas from Cloudflare\'s text model. Keep the ones that fit and add your own.';
273
+ } catch (err) {
274
+ addIdeas(offlineIdeas());
275
+ $('ideaNote').textContent = /nofacts/.test(String(err)) ? 'Fill in Plan › Brand first for ideas that fit you. Here are some to start.' : 'Ora suggested ideas from your brand and persona (offline). Connect Cloudflare for more varied ones.';
276
+ } finally { b.disabled = false; b.textContent = label; }
277
+ });
278
+ const entries = () => Object.entries(cal().days).filter(([, e]) => e.text).sort(([a], [b]) => a.localeCompare(b));
279
+ $('calCsv').addEventListener('click', async () => {
280
+ const q = v => `"${String(v == null ? '' : v).replace(/"/g, '""')}"`;
281
+ const rows = [['Date', 'Time', 'Kind', 'Idea', 'Platforms', 'Status', 'File', 'Instagram caption', 'Facebook caption', 'LinkedIn caption'].map(q).join(',')];
282
+ for (const [d, e] of entries()) {
283
+ const meta = e.item && S.videos.find(v => v.id === e.item.id);
284
+ const cp = e.captions || {};
285
+ rows.push([d, cal().time, typeOf(e.type)[1], e.text, (e.platforms || []).join(' '), e.status, meta ? (filesOf(meta)[0] || '') : '', cp.instagram, cp.facebook, cp.linkedin].map(q).join(','));
286
+ }
287
+ const f = await window.ora.planExport(`${plan.brand.name || 'Ora'} - content calendar`, new TextEncoder().encode(`${rows.join('\r\n')}\r\n`), 'csv');
288
+ $('ideaNote').textContent = `Saved ${f.split(/[\\/]/).pop()} in Documents/Ora. In Google Sheets: File › Import › Upload.`;
289
+ });
290
+ $('calIcs').addEventListener('click', async () => {
291
+ const [h, m] = (cal().time || '09:00').split(':').map(Number);
292
+ const esc = t => String(t).replace(/[\\;,]/g, x => `\\${x}`).replace(/\n/g, '\\n');
293
+ const stamp = d => `${ymd(d).replace(/-/g, '')}T${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}00`;
294
+ const lines = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Devseis//Ora//EN', 'CALSCALE:GREGORIAN'];
295
+ for (const [d, e] of entries()) {
296
+ const s = parseYmd(d); s.setHours(h, m, 0, 0); const en = new Date(s.getTime() + 30 * 60000);
297
+ lines.push('BEGIN:VEVENT', `UID:ora-${d}-${Math.random().toString(36).slice(2, 8)}@devseis`, `DTSTAMP:${stamp(new Date())}`, `DTSTART:${stamp(s)}`, `DTEND:${stamp(en)}`,
298
+ `SUMMARY:${esc(`Post (${typeOf(e.type)[1]}): ${e.text}`)}`, `DESCRIPTION:${esc(`${(e.platforms || []).join(', ')} · ${e.status}`)}`,
299
+ 'BEGIN:VALARM', 'TRIGGER:-PT30M', 'ACTION:DISPLAY', 'DESCRIPTION:Post today', 'END:VALARM', 'END:VEVENT');
300
+ }
301
+ lines.push('END:VCALENDAR');
302
+ const f = await window.ora.planExport(`${plan.brand.name || 'Ora'} - posting calendar`, new TextEncoder().encode(lines.join('\r\n') + '\r\n'), 'ics');
303
+ $('ideaNote').textContent = `Saved ${f.split(/[\\/]/).pop()}: open it to add the posting days to your calendar, with a reminder.`;
304
+ });
305
+
306
+ // --- 4 · Presentation ----------------------------------------------------------------------------------------------------
307
+
308
+ function renderPresent() {
309
+ const b = plan.brand || {}, ps = (plan.personas || []).filter(p => p.name), n = entries().length, made = Object.values(cal().days).filter(e => e.item).length;
310
+ const items = [
311
+ [!!b.name, 'Title', b.name ? `${b.name}${b.tagline ? ` · “${b.tagline}”` : ''}` : 'add your brand in 1 · Brand'],
312
+ [!!(b.mission || b.values), 'Brand identity', b.mission ? 'mission, values, personality, tone, colours' : 'add a mission and values'],
313
+ [ps.length > 0, 'Personas', ps.length ? ps.map(p => p.name).join(', ') : 'add personas in 2 · Personas'],
314
+ [ps.some(p => (p.where || []).length), 'Digital presence', 'where your audience is online'],
315
+ [!!(plan.campaign && (plan.campaign.name || plan.campaign.message)), 'Campaign and funnel', plan.campaign && plan.campaign.name ? plan.campaign.name : 'plan it in 3 · Campaign'],
316
+ [n > 0, 'Content plan', n ? `${n} posts in 30 days, by kind of content` : 'fill the calendar in 4 · Calendar'],
317
+ [n > 0, 'Calendar', 'the 30 days at a glance'],
318
+ [made > 0 || S.videos.length > 0 || (plan.ads || []).length > 0, 'Content made with Ora', [(plan.ads || []).length && `${plan.ads.length} ad${plan.ads.length > 1 ? 's' : ''}`, made && `${made} linked to the calendar`].filter(Boolean).join(', ') || 'your latest pictures and videos'],
319
+ [!!(plan.campaign && plan.campaign.metrics && plan.campaign.metrics.length), 'Success metrics and results', plan.results && plan.results.rows && plan.results.rows.length ? `${plan.results.rows.length} posts measured` : 'targets now, numbers in 5 · Results'],
320
+ [true, 'Thank you', b.name || ''],
321
+ ];
322
+ const ol = $('presentList'); ol.innerHTML = '';
323
+ for (const [ok, title, note] of items) { const li = document.createElement('li'); li.className = ok ? '' : 'miss'; li.innerHTML = '<b></b> <span class="muted"></span>'; li.querySelector('b').textContent = title; li.querySelector('span').textContent = `— ${note}`; ol.appendChild(li); }
324
+ $('presentBy').value = plan.presentedBy || '';
325
+ }
326
+ $('presentBy').addEventListener('input', e => { plan.presentedBy = e.target.value; savePlan(); });
327
+
328
+ function slidesHtml() {
329
+ const b = plan.brand || {}, ps = (plan.personas || []).filter(p => p.name);
330
+ const e = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
331
+ const c1 = (b.colors || [])[0] || '#1c1530', c2 = (b.colors || [])[1] || '#f5efe0';
332
+ const fam = { modern: '"Helvetica Neue", Helvetica, Arial, sans-serif', serif: 'Georgia, "Times New Roman", serif', display: '"Avenir Next", "Helvetica Neue", Arial, sans-serif' }[b.font] || '"Helvetica Neue", Arial, sans-serif';
333
+ const img = (id, file) => `ora://video/${encodeURIComponent(id)}/${file}`;
334
+ const logo = b.logo ? `<img class="logo" src="${img(b.logo.id, b.logo.file)}">` : '';
335
+ const slide = (cls, inner) => `<section class="s ${cls}">${inner}<footer>${e(b.name || '')}${plan.presentedBy ? ` · ${e(plan.presentedBy)}` : ''}</footer></section>`;
336
+ const out = [];
337
+ out.push(`<section class="s title" style="background:${c1}">${logo}<div><p class="kicker">Campaign presentation</p><h1>${e(b.name || 'My brand')}</h1>${b.tagline ? `<p class="tag">${e(b.tagline)}</p>` : ''}${plan.presentedBy ? `<p class="by">${e(plan.presentedBy)}</p>` : ''}</div></section>`);
338
+ out.push(slide('', `<h2>Brand identity</h2><div class="cols"><div>${b.offer ? `<h3>What we offer</h3><p>${e(b.offer)}</p>` : ''}${b.mission ? `<h3>Mission</h3><p>${e(b.mission)}</p>` : ''}${b.values ? `<h3>Values</h3><p class="chips">${b.values.split(',').map(v => `<span>${e(v.trim())}</span>`).join('')}</p>` : ''}</div>
339
+ <div>${(b.personality || []).length || b.tone ? `<h3>Personality and tone</h3><p>${e((b.personality || []).join(', '))}${b.tone ? `<br><span class="muted">${e(b.tone)}</span>` : ''}</p>` : ''}<h3>Colours</h3><p class="sw">${(b.colors || []).map(h => `<span style="background:${h}"></span>`).join('')}</p><p class="muted">${(b.colors || []).map(h => `${h.toUpperCase()} ${hexName(h)}`).join(' · ')}</p></div></div>`));
340
+ if (ps.length) out.push(slide('', `<h2>Who we talk to</h2><div class="cards">${ps.map(p => `<div class="card">${p.portrait ? `<img class="face" src="${img(p.portrait.id, p.portrait.file)}">` : `<div class="face ph">${e(p.name[0])}</div>`}<h3>${e(p.name)}</h3><p class="muted">${e([p.age, p.job].filter(Boolean).join(' · '))}</p>${p.needs ? `<p><b>Needs:</b> ${e(p.needs)}</p>` : ''}${p.pains ? `<p><b>Frustrations:</b> ${e(p.pains)}</p>` : ''}${p.motivations ? `<p><b>Chooses a brand for:</b> ${e(p.motivations)}</p>` : ''}${p.quote ? `<p class="q">“${e(p.quote.replace(/^["“]|["”]$/g, ''))}”</p>` : ''}</div>`).join('')}</div>`));
341
+ const where = {};
342
+ for (const p of ps) for (const w of p.where || []) where[w] = [...(where[w] || []), p.name];
343
+ if (Object.keys(where).length) out.push(slide('', `<h2>Where we will be online</h2><div class="presence">${Object.entries(where).map(([w, who]) => `<div><b>${e(w)}</b><span class="muted">to reach ${e(who.join(' and '))}</span></div>`).join('')}</div>`));
344
+ const cp = plan.campaign;
345
+ if (cp && (cp.name || cp.message)) {
346
+ const goal = { awareness: 'Be known', engagement: 'Engagement', leads: 'Leads', sales: 'Sales', visits: 'Shop visits' }[cp.goal] || '';
347
+ const dates = [cp.start, cp.end].filter(Boolean).map(d => parseYmd(d).toLocaleDateString(undefined, { day: 'numeric', month: 'short' })).join(' – ');
348
+ const steps = [['awareness', 'Awareness'], ['engagement', 'Engagement'], ['conversion', 'Conversion']];
349
+ out.push(slide('', `<h2>${e(cp.name || 'Campaign')}</h2><div class="cols"><div>${cp.message ? `<p class="lead">${e(cp.message)}</p>` : ''}<h3>Goal</h3><p>${e(goal)}${dates ? ` · ${e(dates)}` : ''}</p>${cp.value ? `<h3>Why choose us</h3><p>${e(cp.value)}</p>` : ''}${cp.offer || cp.cta ? `<h3>Offer and call to action</h3><p>${e([cp.offer, cp.cta].filter(Boolean).join(' → '))}</p>` : ''}${(cp.channels || []).length ? `<h3>Channels</h3><p class="chips">${cp.channels.map(c => `<span>${e(c)}</span>`).join('')}</p>` : ''}</div>
350
+ <div class="funnelS">${steps.map(([k, l], i) => `<div class="fs" style="margin:0 ${i * 0.35}in"><b>${l}</b><span>${e(((cp.funnel || {})[k] || {}).what || defaultStep(k))}</span></div>`).join('')}</div></div>`));
351
+ }
352
+ const es = entries();
353
+ if (es.length) {
354
+ const counts = {};
355
+ for (const [, x] of es) counts[x.type] = (counts[x.type] || 0) + 1;
356
+ const max = Math.max(...Object.values(counts));
357
+ out.push(slide('', `<h2>Content plan</h2><p class="lead">${es.length} posts in 30 days, ${cal().perWeek} a week at ${e(cal().time)}.</p><div class="bars">${CONTENT_TYPES.filter(t => counts[t[0]]).map(t => `<div class="bar"><span class="l">${t[1]}</span><span class="b" style="width:${counts[t[0]] / max * 70}%;background:${t[2]}"></span><span class="n">${counts[t[0]]}</span></div>`).join('')}</div>`));
358
+ const days = calDays(), lead = (days[0].getDay() + 6) % 7;
359
+ const cells = [...Array(lead).fill('<div class="c out"></div>'), ...days.map(d => { const x = cal().days[ymd(d)]; return `<div class="c"${x && x.text ? ` style="border-left:5px solid ${typeOf(x.type)[2]}"` : ''}><span class="d">${d.getDate()}</span>${x && x.text ? `<span class="t">${e(x.text)}</span>` : ''}</div>`; })];
360
+ out.push(slide('', `<h2>Calendar · ${e(days[0].toLocaleDateString(undefined, { day: 'numeric', month: 'short' }))} – ${e(days[29].toLocaleDateString(undefined, { day: 'numeric', month: 'short' }))}</h2><div class="month">${['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map(d => `<div class="h">${d}</div>`).join('')}${cells.join('')}</div>`));
361
+ }
362
+ // examples: the calendar's linked items first, then the latest things made
363
+ const linked = Object.values(cal().days).filter(x => x.item).map(x => S.videos.find(v => v.id === x.item.id)).filter(Boolean);
364
+ const gal = galleryItems();
365
+ if (gal.length) out.push(slide('', `<h2>Content made with Ora</h2><div class="gallery">${gal.map(g => `<figure><img src="${g.src}"><figcaption>${e(g.label)}</figcaption></figure>`).join('')}</div>`));
366
+ if (cp && (cp.metrics || []).length) {
367
+ const rows = (plan.results || {}).rows || [];
368
+ const sum = k => rows.reduce((a, x) => a + (+x[k] || 0), 0);
369
+ const reach = sum('reach'), inter = ['likes', 'comments', 'shares', 'saves'].reduce((a, k) => a + sum(k), 0);
370
+ const val = { reach, impressions: sum('impressions'), followers: sum('followers'), clicks: sum('clicks'), er: reach ? inter / reach * 100 : null };
371
+ const lbl = { reach: 'Reach', impressions: 'Impressions', er: 'Engagement rate', followers: 'Follower growth', clicks: 'Clicks' };
372
+ const show = (id, v) => v == null ? '—' : id === 'er' ? `${v.toFixed(1)}%` : Math.round(v).toLocaleString();
373
+ out.push(slide('', `<h2>Success metrics${rows.length ? ' and results' : ''}</h2><div class="metricsS">${cp.metrics.map(m => `<div><span class="k">${e(lbl[m.id] || m.id)}</span><span class="v">${rows.length ? e(show(m.id, val[m.id])) : '—'}</span><span class="t">${m.target ? `target ${e(m.id === 'er' ? `${m.target}%` : (+m.target).toLocaleString())}` : 'no target set'}${rows.length && m.target && val[m.id] != null ? ` · ${Math.round(val[m.id] / m.target * 100)}% reached` : ''}</span></div>`).join('')}</div>${rows.length ? `<p class="muted">${rows.length} posts measured.</p>` : '<p class="muted">The numbers come in after the posts go out.</p>'}`));
374
+ }
375
+ out.push(`<section class="s title end" style="background:${c1}">${logo}<div><h1>Thank you</h1>${b.tagline ? `<p class="tag">${e(b.tagline)}</p>` : ''}</div></section>`);
376
+ const ink = hex => { const n = parseInt(hex.slice(1), 16); return (0.299 * (n >> 16) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255)) / 255 > 0.62 ? '#1c1530' : '#ffffff'; };
377
+ const onC1 = ink(c1), onC2 = ink(c2);
378
+ return `<!doctype html><html><head><meta charset="utf-8"><style>
379
+ @page { size: 13.333in 7.5in; margin: 0 }
380
+ * { box-sizing: border-box } body { margin: 0; font-family: -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; color: #1c1530 }
381
+ .s { width: 13.333in; height: 7.5in; padding: 0.6in 0.75in 0.5in; position: relative; page-break-after: always; overflow: hidden; background: #fbf8f3 }
382
+ .s h2 { font-family: ${fam}; font-size: 34pt; margin: 0 0 0.25in; color: ${c1} } .s h3 { font-size: 13pt; text-transform: uppercase; letter-spacing: .06em; color: ${c1}; margin: 0.18in 0 0.05in }
383
+ .s p { font-size: 15pt; line-height: 1.4; margin: 0 0 0.08in } .muted { color: #6b6478 } .lead { font-size: 18pt }
384
+ footer { position: absolute; left: 0.75in; bottom: 0.25in; font-size: 10pt; color: #9a93a6 }
385
+ .title { display: flex; flex-direction: column; justify-content: center; color: ${onC1} } .title h1 { font-family: ${fam}; font-size: 64pt; margin: 0 } .title .kicker { font-size: 14pt; letter-spacing: .12em; text-transform: uppercase; opacity: .8 }
386
+ .title .tag { font-size: 24pt; font-family: ${fam} } .title .by { font-size: 14pt; opacity: .85; margin-top: 0.3in } .title .logo { position: absolute; top: 0.6in; left: 0.75in; max-height: 1.1in; max-width: 3in } .end { text-align: left }
387
+ .cols { display: grid; grid-template-columns: 1fr 1fr; gap: 0.6in } .chips span { display: inline-block; background: ${c2}; color: ${onC2}; border-radius: 999px; padding: 2px 12px; margin: 0 6px 6px 0; font-size: 13pt }
388
+ .sw span { display: inline-block; width: 1in; height: 0.7in; border-radius: 10px; margin-right: 10px; border: 1px solid rgba(0,0,0,.08) }
389
+ .cards { display: grid; grid-template-columns: repeat(${Math.max(1, ps.length)}, 1fr); gap: 0.3in } .card { background: #fff; border-radius: 16px; padding: 0.25in; border: 1px solid rgba(28,21,48,.1) }
390
+ .card h3 { font-size: 18pt; text-transform: none; letter-spacing: 0; color: #1c1530; margin: 0.08in 0 0 } .card p { font-size: 12.5pt } .card .q { font-style: italic; color: ${c1} }
391
+ .face { width: 1in; height: 1in; border-radius: 50%; object-fit: cover; display: flex; align-items: center; justify-content: center; font-size: 30pt; background: ${c1}; color: ${onC1} }
392
+ .presence { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.25in } .presence div { background: #fff; border-radius: 14px; padding: 0.25in; border-top: 6px solid ${c1}; display: flex; flex-direction: column; gap: 6px; font-size: 16pt } .presence span { font-size: 12.5pt }
393
+ .bars { display: flex; flex-direction: column; gap: 0.18in; margin-top: 0.3in } .bar { display: flex; align-items: center; gap: 0.2in; font-size: 15pt } .bar .l { width: 2.4in } .bar .b { height: 0.36in; border-radius: 8px; display: inline-block } .bar .n { font-weight: 700 }
394
+ .month { display: grid; grid-template-columns: repeat(7, 1fr); gap: 5px } .month .h { font-size: 10pt; font-weight: 700; color: #6b6478; text-transform: uppercase } .month .c { background: #fff; border: 1px solid rgba(28,21,48,.1); border-radius: 8px; height: 0.95in; padding: 4px 6px; overflow: hidden; display: flex; flex-direction: column; gap: 2px }
395
+ .month .c.out { background: transparent; border: 0 } .month .d { font-size: 9pt; color: #6b6478; font-weight: 700 } .month .t { font-size: 8.5pt; line-height: 1.25 }
396
+ .funnelS { display: flex; flex-direction: column; gap: 0.15in; margin-top: 0.2in } .fs { background: ${c1}; color: ${onC1}; border-radius: 14px; padding: 0.18in 0.25in; display: flex; flex-direction: column; gap: 4px } .fs b { font-size: 15pt } .fs span { font-size: 12pt; opacity: .92 }
397
+ .metricsS { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.3in; margin: 0.2in 0 0.3in } .metricsS div { background: #fff; border-radius: 16px; padding: 0.3in; border-top: 8px solid ${c1}; display: flex; flex-direction: column; gap: 6px } .metricsS .k { font-size: 13pt; text-transform: uppercase; letter-spacing: .05em; color: #6b6478 } .metricsS .v { font-size: 40pt; font-weight: 700 } .metricsS .t { font-size: 12pt; color: #6b6478 }
398
+ .gallery { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.25in } figure { margin: 0 } figure img { width: 100%; height: 2.2in; object-fit: cover; border-radius: 12px; display: block } figcaption { font-size: 11pt; color: #6b6478; margin-top: 4px }
399
+ </style></head><body>${out.join('\n')}</body></html>`;
400
+ }
401
+ // examples for the deck: ads (from the Ad maker) first, then the calendar's linked items, then the latest made
402
+ function galleryItems() {
403
+ const out = (plan.ads || []).slice(0, 2).map(a => ({ src: a.thumb, label: `Ad · ${a.title}${a.formats > 1 ? ` · ${a.formats} sizes` : ''}` }));
404
+ const linked = Object.values(cal().days).filter(x => x.item).map(x => S.videos.find(v => v.id === x.item.id)).filter(Boolean);
405
+ for (const m of [...new Set([...linked, ...S.videos])]) {
406
+ if (out.length >= 6) break;
407
+ out.push({ src: `ora://video/${encodeURIComponent(m.id)}/${m.kind === 'image' ? ((m.hdImages || [])[0] || m.images[0]) : 'poster.png'}`,
408
+ label: `${m.kind === 'image' ? (m.poster ? (m.poster.carousel ? 'Carousel' : 'Poster') : 'Image') : 'Video'} · ${((m.poster && m.poster.title) || (m.project ? m.project.title : m.prompt || '')).slice(0, 48)}` });
409
+ }
410
+ return out;
411
+ }
412
+
413
+ // --- PowerPoint (.pptx): the same slides, editable -----------------------------------------------------------------------
414
+
415
+ async function dataUrl(src) {
416
+ if (src.startsWith('data:')) return src;
417
+ const blob = await (await fetch(src)).blob();
418
+ return new Promise(res => { const r = new FileReader(); r.onload = () => res(r.result); r.readAsDataURL(blob); });
419
+ }
420
+ async function imgSize(src) { const i = await loadImg(src); return [i.width, i.height]; }
421
+ async function buildPptx() {
422
+ const { newDeck } = await import('./vendor/pptx.js');
423
+ const deck = newDeck();
424
+ deck.layout = 'LAYOUT_WIDE'; // 13.33 x 7.5 in
425
+ const b = plan.brand || {}, ps = (plan.personas || []).filter(p => p.name), cp = plan.campaign;
426
+ const c1 = ((b.colors || [])[0] || '#1c1530').slice(1), c2 = ((b.colors || [])[1] || '#f5efe0').slice(1);
427
+ const lum = h => { const n = parseInt(h, 16); return (0.299 * (n >> 16) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255)) / 255; };
428
+ const on1 = lum(c1) > 0.62 ? '1C1530' : 'FFFFFF';
429
+ const face = { modern: 'Helvetica Neue', serif: 'Georgia', display: 'Avenir Next' }[b.font] || 'Helvetica Neue';
430
+ const foot = `${b.name || ''}${plan.presentedBy ? ` · ${plan.presentedBy}` : ''}`;
431
+ const base = () => { const s = deck.addSlide(); s.background = { color: 'FBF8F3' }; s.addText(foot, { x: 0.75, y: 7.0, w: 8, h: 0.3, fontSize: 10, color: '9A93A6', fontFace: 'Helvetica Neue' }); return s; };
432
+ const h2 = (s, t) => s.addText(t, { x: 0.75, y: 0.45, w: 11.8, h: 0.8, fontSize: 34, bold: true, color: c1, fontFace: face });
433
+ const label = (s, t, x, y, w) => s.addText(t.toUpperCase(), { x, y, w, h: 0.3, fontSize: 12, bold: true, color: c1, charSpacing: 1 });
434
+ const para = (s, t, x, y, w, h, o = {}) => s.addText(t, { x, y, w, h, fontSize: 15, color: '1C1530', valign: 'top', fit: 'shrink', ...o });
435
+ const logo = b.logo ? await dataUrl(`ora://video/${encodeURIComponent(b.logo.id)}/${b.logo.file}`).catch(() => null) : null;
436
+ const titleSlide = (big, small, by) => {
437
+ const s = deck.addSlide(); s.background = { color: c1 };
438
+ if (logo) s.addImage({ data: logo, x: 0.75, y: 0.6, h: 1.0, w: 2.2, sizing: { type: 'contain', w: 2.2, h: 1.0 } });
439
+ s.addText(big, { x: 0.75, y: 2.6, w: 11.8, h: 1.3, fontSize: 60, bold: true, color: on1, fontFace: face });
440
+ if (small) s.addText(small, { x: 0.75, y: 3.9, w: 11.8, h: 0.7, fontSize: 24, color: on1, fontFace: face });
441
+ if (by) s.addText(by, { x: 0.75, y: 4.8, w: 8, h: 0.5, fontSize: 14, color: on1 });
442
+ };
443
+ titleSlide(b.name || 'My brand', b.tagline, plan.presentedBy);
444
+ // brand identity
445
+ let s = base(); h2(s, 'Brand identity');
446
+ let y = 1.5;
447
+ for (const [k, v] of [['What we offer', b.offer], ['Mission', b.mission], ['Values', (b.values || '').split(',').map(x => x.trim()).filter(Boolean).join(' · ')]]) {
448
+ if (!v) continue; label(s, k, 0.75, y, 5.6); para(s, v, 0.75, y + 0.3, 5.6, 0.9); y += 1.35;
449
+ }
450
+ label(s, 'Personality and tone', 7, 1.5, 5.6); para(s, [(b.personality || []).join(', '), b.tone].filter(Boolean).join(' — '), 7, 1.8, 5.6, 0.9);
451
+ label(s, 'Colours', 7, 2.9, 5.6);
452
+ (b.colors || []).forEach((h, i) => { s.addShape(deck.ShapeType.roundRect, { x: 7 + i * 1.2, y: 3.25, w: 1.0, h: 0.7, fill: { color: h.slice(1) }, line: { color: 'DDDDDD', width: 0.5 }, rectRadius: 0.1 }); s.addText(`${h.toUpperCase()}\n${hexName(h)}`, { x: 7 + i * 1.2, y: 4.0, w: 1.15, h: 0.5, fontSize: 9, color: '6B6478' }); });
453
+ // personas
454
+ if (ps.length) {
455
+ s = base(); h2(s, 'Who we talk to');
456
+ const w = (11.8 - (ps.length - 1) * 0.3) / ps.length;
457
+ for (const [i, p] of ps.entries()) {
458
+ const x = 0.75 + i * (w + 0.3);
459
+ s.addShape(deck.ShapeType.roundRect, { x, y: 1.5, w, h: 4.9, fill: { color: 'FFFFFF' }, line: { color: 'E6E1EA', width: 0.75 }, rectRadius: 0.15 });
460
+ if (p.portrait) { const d = await dataUrl(`ora://video/${encodeURIComponent(p.portrait.id)}/${p.portrait.file}`).catch(() => null); if (d) s.addImage({ data: d, x: x + 0.25, y: 1.75, w: 1.0, h: 1.0, rounding: true, sizing: { type: 'cover', w: 1.0, h: 1.0 } }); }
461
+ s.addText(p.name, { x: x + 1.4, y: 1.8, w: w - 1.6, h: 0.45, fontSize: 20, bold: true, color: '1C1530' });
462
+ s.addText([p.age, p.job].filter(Boolean).join(' · '), { x: x + 1.4, y: 2.25, w: w - 1.6, h: 0.4, fontSize: 12, color: '6B6478' });
463
+ const lines = [['Needs', p.needs], ['Frustrations', p.pains], ['Chooses a brand for', p.motivations]].filter(l => l[1]).map(([k, v]) => [{ text: `${k}: `, options: { bold: true } }, { text: `${v}\n`, options: {} }]).flat();
464
+ if (p.quote) lines.push({ text: `“${p.quote.replace(/^["“]|["”]$/g, '')}”`, options: { italic: true, color: c1 } });
465
+ s.addText(lines, { x: x + 0.25, y: 3.0, w: w - 0.5, h: 3.2, fontSize: 12.5, color: '1C1530', valign: 'top', paraSpaceAfter: 6, fit: 'shrink' });
466
+ }
467
+ }
468
+ // campaign and funnel
469
+ if (cp && (cp.name || cp.message)) {
470
+ s = base(); h2(s, cp.name || 'Campaign');
471
+ y = 1.45;
472
+ if (cp.message) { para(s, cp.message, 0.75, y, 5.8, 0.6, { fontSize: 18 }); y += 0.8; }
473
+ const goal = { awareness: 'Be known', engagement: 'Engagement', leads: 'Leads', sales: 'Sales', visits: 'Shop visits' }[cp.goal] || '';
474
+ for (const [k, v] of [['Goal', goal], ['Why choose us', cp.value], ['Offer and call to action', [cp.offer, cp.cta].filter(Boolean).join(' → ')], ['Channels', (cp.channels || []).join(' · ')]]) {
475
+ if (!v) continue; label(s, k, 0.75, y, 5.8); para(s, v, 0.75, y + 0.3, 5.8, 0.6); y += 1.0;
476
+ }
477
+ [['awareness', 'Awareness'], ['engagement', 'Engagement'], ['conversion', 'Conversion']].forEach(([k, l], i) => {
478
+ s.addShape(deck.ShapeType.roundRect, { x: 7 + i * 0.35, y: 1.6 + i * 1.45, w: 5.6 - i * 0.7, h: 1.25, fill: { color: c1 }, line: { color: c1 }, rectRadius: 0.12 });
479
+ s.addText([{ text: `${l}\n`, options: { bold: true, fontSize: 15 } }, { text: ((cp.funnel || {})[k] || {}).what || defaultStep(k), options: { fontSize: 11.5 } }], { x: 7.2 + i * 0.35, y: 1.65 + i * 1.45, w: 5.2 - i * 0.7, h: 1.15, color: on1, valign: 'middle', fit: 'shrink' });
480
+ });
481
+ }
482
+ // content plan and calendar
483
+ const es = entries();
484
+ if (es.length) {
485
+ s = base(); h2(s, 'Content plan');
486
+ para(s, `${es.length} posts in 30 days, ${cal().perWeek} a week at ${cal().time}.`, 0.75, 1.4, 11, 0.5, { fontSize: 18 });
487
+ const counts = {}; for (const [, x] of es) counts[x.type] = (counts[x.type] || 0) + 1;
488
+ const max = Math.max(...Object.values(counts));
489
+ CONTENT_TYPES.filter(t => counts[t[0]]).forEach((t, i) => {
490
+ s.addText(t[1], { x: 0.75, y: 2.2 + i * 0.6, w: 2.4, h: 0.45, fontSize: 15, color: '1C1530' });
491
+ s.addShape(deck.ShapeType.rect, { x: 3.2, y: 2.27 + i * 0.6, w: Math.max(0.1, counts[t[0]] / max * 8), h: 0.32, fill: { color: t[2].slice(1) }, line: { color: t[2].slice(1) } });
492
+ s.addText(String(counts[t[0]]), { x: 3.3 + counts[t[0]] / max * 8, y: 2.2 + i * 0.6, w: 0.8, h: 0.45, fontSize: 15, bold: true, color: '1C1530' });
493
+ });
494
+ const days = calDays(), lead = (days[0].getDay() + 6) % 7;
495
+ s = base(); h2(s, `Calendar · ${days[0].toLocaleDateString(undefined, { day: 'numeric', month: 'short' })} – ${days[29].toLocaleDateString(undefined, { day: 'numeric', month: 'short' })}`);
496
+ const rows = [['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map(t => ({ text: t, options: { bold: true, color: '6B6478', fontSize: 10 } }))];
497
+ const cells = [...Array(lead).fill(null), ...days];
498
+ while (cells.length % 7) cells.push(null);
499
+ for (let i = 0; i < cells.length; i += 7) rows.push(cells.slice(i, i + 7).map(d => { if (!d) return { text: '' }; const x = cal().days[ymd(d)]; return { text: [{ text: `${d.getDate()}\n`, options: { bold: true, color: '6B6478', fontSize: 9 } }, { text: x && x.text ? x.text : '', options: { fontSize: 8.5, color: '1C1530' } }], options: x && x.text ? { border: [{ type: 'none' }, { type: 'none' }, { type: 'none' }, { pt: 4, color: typeOf(x.type)[2].slice(1) }] } : {} }; }));
500
+ s.addTable(rows, { x: 0.75, y: 1.35, w: 11.8, colW: Array(7).fill(11.8 / 7), rowH: [0.3, ...Array(rows.length - 1).fill(1.0)], fill: { color: 'FFFFFF' }, border: { type: 'solid', pt: 0.5, color: 'E6E1EA' }, valign: 'top' });
501
+ }
502
+ // examples
503
+ const gal = galleryItems();
504
+ if (gal.length) {
505
+ s = base(); h2(s, 'Content made with Ora');
506
+ for (const [i, g] of gal.entries()) {
507
+ const x = 0.75 + (i % 3) * 4.05, yy = 1.45 + Math.floor(i / 3) * 2.75;
508
+ const d = await dataUrl(g.src).catch(() => null);
509
+ if (d) { const [iw, ih] = await imgSize(d); s.addImage({ data: d, x, y: yy, w: 3.8, h: 2.2, sizing: { type: iw / ih > 3.8 / 2.2 ? 'cover' : 'contain', w: 3.8, h: 2.2 } }); }
510
+ s.addText(g.label, { x, y: yy + 2.22, w: 3.8, h: 0.3, fontSize: 10.5, color: '6B6478' });
511
+ }
512
+ }
513
+ // metrics
514
+ if (cp && (cp.metrics || []).length) {
515
+ s = base(); h2(s, (plan.results || {}).rows && plan.results.rows.length ? 'Success metrics and results' : 'Success metrics');
516
+ const rows = (plan.results || {}).rows || [], sum = k => rows.reduce((a, x) => a + (+x[k] || 0), 0);
517
+ const reach = sum('reach'), inter = ['likes', 'comments', 'shares', 'saves'].reduce((a, k) => a + sum(k), 0);
518
+ const val = { reach, impressions: sum('impressions'), followers: sum('followers'), clicks: sum('clicks'), er: reach ? inter / reach * 100 : null };
519
+ const lbl = { reach: 'Reach', impressions: 'Impressions', er: 'Engagement rate', followers: 'Follower growth', clicks: 'Clicks' };
520
+ cp.metrics.forEach((m, i) => {
521
+ const x = 0.75 + i * 4.0, v = val[m.id];
522
+ s.addShape(deck.ShapeType.roundRect, { x, y: 1.6, w: 3.7, h: 2.4, fill: { color: 'FFFFFF' }, line: { color: 'E6E1EA', width: 0.75 }, rectRadius: 0.15 });
523
+ s.addShape(deck.ShapeType.rect, { x, y: 1.6, w: 3.7, h: 0.12, fill: { color: c1 }, line: { color: c1 } });
524
+ s.addText((lbl[m.id] || m.id).toUpperCase(), { x: x + 0.3, y: 1.9, w: 3.2, h: 0.35, fontSize: 12, color: '6B6478' });
525
+ s.addText(rows.length && v != null ? (m.id === 'er' ? `${v.toFixed(1)}%` : Math.round(v).toLocaleString()) : '—', { x: x + 0.3, y: 2.3, w: 3.2, h: 0.9, fontSize: 40, bold: true, color: '1C1530' });
526
+ s.addText(m.target ? `target ${m.id === 'er' ? `${m.target}%` : (+m.target).toLocaleString()}${rows.length && v != null ? ` · ${Math.round(v / m.target * 100)}% reached` : ''}` : 'no target set', { x: x + 0.3, y: 3.3, w: 3.2, h: 0.4, fontSize: 12, color: '6B6478' });
527
+ });
528
+ }
529
+ titleSlide('Thank you', b.tagline, '');
530
+ return deck.write({ outputType: 'uint8array' });
531
+ }
532
+
533
+ $('presentPptx').addEventListener('click', async e => {
534
+ const btn = e.currentTarget; btn.disabled = true; $('presentNote').textContent = 'Making the PowerPoint…';
535
+ try {
536
+ const bytes = await buildPptx();
537
+ const f = await window.ora.planExport(`${plan.brand.name || 'Ora'} - campaign presentation`, bytes, 'pptx');
538
+ $('presentNote').textContent = `Saved ${f.split(/[\\/]/).pop()} in Documents/Ora: open it in PowerPoint, Keynote or Google Slides to edit.`;
539
+ } catch (err) { $('presentNote').textContent = `Could not make the PowerPoint: ${cleanErr(err)}`; }
540
+ finally { btn.disabled = false; }
541
+ });
542
+ $('presentMake').addEventListener('click', async e => {
543
+ const b = e.currentTarget; b.disabled = true; $('presentNote').textContent = 'Making the slides…';
544
+ try {
545
+ const f = await window.ora.planPdf(`${plan.brand.name || 'Ora'} - campaign presentation`, slidesHtml());
546
+ $('presentNote').textContent = `Saved ${f.split(/[\\/]/).pop()} in Documents/Ora.`;
547
+ } catch (err) { $('presentNote').textContent = cleanErr(err); }
548
+ finally { b.disabled = false; }
549
+ });
app/renderer/campaign.js ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ /* global $, S, store, plan, savePlan, showView, setMode, imgForm, poster, renderPosterFields, renderImgShapes, shots, renderShots,
3
+ formNote, cleanErr, cal, typeOf, CONTENT_TYPES, ymd, parseYmd */
4
+ // Plan › 3 Campaign: name, goal, message, offer, channels, a three-step funnel (each step can be made in Create) and
5
+ // three success metrics with targets. Plan › 5 Results: the numbers of each post, engagement rate, progress to targets.
6
+
7
+ const GOALS = [['awareness', 'Be known'], ['engagement', 'Engagement'], ['leads', 'Leads'], ['sales', 'Sales'], ['visits', 'Shop visits']];
8
+ const CHANNELS = ['Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'Google Business', 'Website', 'Email', 'Paid ads'];
9
+ const FUNNEL = [
10
+ ['awareness', 'Awareness', 'People who do not know you see you', 'A short video ad', 'video'],
11
+ ['engagement', 'Engagement', 'They like, comment, save and follow', 'A carousel of tips', 'carousel'],
12
+ ['conversion', 'Conversion', 'They buy, book or get in touch', 'A poster with the offer', 'poster'],
13
+ ];
14
+ const METRICS = [
15
+ ['reach', 'Reach', 'people reached', 'sum'], ['impressions', 'Impressions', 'times seen', 'sum'], ['er', 'Engagement rate', '% of people reached who interacted', 'rate'],
16
+ ['followers', 'Follower growth', 'new followers', 'sum'], ['clicks', 'Clicks', 'link and profile clicks', 'sum'],
17
+ ];
18
+ const NUM_COLS = [['reach', 'Reach'], ['impressions', 'Impr.'], ['likes', 'Likes'], ['comments', 'Comm.'], ['shares', 'Shares'], ['saves', 'Saves'], ['clicks', 'Clicks'], ['followers', 'Follows']];
19
+
20
+ function camp() {
21
+ if (!plan.campaign) plan.campaign = { name: '', goal: 'awareness', start: '', end: '', message: '', value: '', offer: '', cta: '', channels: [], funnel: {}, metrics: [{ id: 'reach', target: '' }, { id: 'er', target: '' }, { id: 'followers', target: '' }] };
22
+ return plan.campaign;
23
+ }
24
+ function results() { if (!plan.results) plan.results = { rows: [] }; return plan.results; }
25
+
26
+ // --- 3 · Campaign ----------------------------------------------------------------------------------------------------------
27
+
28
+ const C_FIELDS = [['cName', 'name'], ['cStart', 'start'], ['cEnd', 'end'], ['cMessage', 'message'], ['cValue', 'value'], ['cOffer', 'offer'], ['cCta', 'cta']];
29
+ function renderCampaign() {
30
+ const c = camp();
31
+ if (!c.start && plan.calendar) c.start = plan.calendar.start;
32
+ for (const [id, k] of C_FIELDS) $(id).value = c[k] || '';
33
+ const g = $('cGoal'); g.innerHTML = '';
34
+ for (const [id, label] of GOALS) { const b = document.createElement('button'); b.type = 'button'; b.textContent = label; b.setAttribute('aria-checked', String(c.goal === id)); b.addEventListener('click', () => { c.goal = id; renderCampaign(); savePlan(); }); g.appendChild(b); }
35
+ const ch = $('cChannels'); ch.innerHTML = '';
36
+ for (const w of CHANNELS) {
37
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = w; b.setAttribute('aria-pressed', String(c.channels.includes(w)));
38
+ b.addEventListener('click', () => { c.channels = c.channels.includes(w) ? c.channels.filter(x => x !== w) : [...c.channels, w]; b.setAttribute('aria-pressed', String(c.channels.includes(w))); savePlan(); });
39
+ ch.appendChild(b);
40
+ }
41
+ const f = $('cFunnel'); f.innerHTML = '';
42
+ for (const [id, label, who, asset] of FUNNEL) {
43
+ const step = document.createElement('div'); step.className = 'funnel-step';
44
+ step.innerHTML = '<b></b><span class="muted small"></span><textarea maxlength="300"></textarea><div class="ad-row"><span class="muted small"></span><button class="ghost improve-btn" type="button">Make it in Create</button></div>';
45
+ step.querySelector('b').textContent = label;
46
+ step.querySelector('.muted').textContent = who;
47
+ const ta = step.querySelector('textarea');
48
+ ta.placeholder = defaultStep(id); ta.value = (c.funnel[id] || {}).what || '';
49
+ ta.addEventListener('input', () => { c.funnel[id] = { ...(c.funnel[id] || {}), what: ta.value }; savePlan(); });
50
+ step.querySelector('.ad-row .muted').textContent = asset;
51
+ step.querySelector('button').addEventListener('click', () => makeStep(id));
52
+ f.appendChild(step);
53
+ }
54
+ const ml = $('cMetrics'); ml.innerHTML = '';
55
+ for (const [id, label, what] of METRICS) {
56
+ const m = c.metrics.find(x => x.id === id);
57
+ const row = document.createElement('div'); row.className = 'metric';
58
+ row.innerHTML = '<label><input type="checkbox"><span><b></b> <small class="muted"></small></span></label><input type="number" min="0" step="any" placeholder="target">';
59
+ row.querySelector('b').textContent = label; row.querySelector('small').textContent = what;
60
+ const cb = row.querySelector('input[type=checkbox]'), tg = row.querySelector('input[type=number]');
61
+ cb.checked = !!m; tg.disabled = !m; tg.value = m ? m.target : '';
62
+ if (id === 'er') tg.placeholder = 'target %';
63
+ cb.addEventListener('change', () => {
64
+ if (cb.checked && c.metrics.length >= 3) { cb.checked = false; $('cNote').textContent = 'Three metrics are enough: untick one first.'; return; }
65
+ c.metrics = cb.checked ? [...c.metrics, { id, target: '' }] : c.metrics.filter(x => x.id !== id);
66
+ renderCampaign(); savePlan();
67
+ });
68
+ tg.addEventListener('input', () => { const x = c.metrics.find(y => y.id === id); if (x) { x.target = tg.value; savePlan(); } });
69
+ ml.appendChild(row);
70
+ }
71
+ }
72
+ for (const [id, k] of C_FIELDS) $(id).addEventListener(id === 'cStart' || id === 'cEnd' ? 'change' : 'input', e => { camp()[k] = e.target.value; savePlan(); });
73
+
74
+ function what() { return (plan.brand && plan.brand.offer) ? plan.brand.offer.split(/\s+(in|for|near|at)\s+/i)[0].toLowerCase() : 'our product'; }
75
+ function defaultStep(id) {
76
+ const c = camp(), where = c.channels.length ? c.channels.slice(0, 2).join(' and ') : 'social media';
77
+ return {
78
+ awareness: `A 15-second video ad on ${where} that shows ${what()} to people who do not know us yet.`,
79
+ engagement: 'A carousel of practical tips, plus polls and questions in stories, to start conversations.',
80
+ conversion: `A poster with ${c.offer ? `the offer "${c.offer}"` : 'a clear offer'} and "${c.cta || 'Order now'}", linked to our website or shop.`,
81
+ }[id];
82
+ }
83
+ // Fills Create for one funnel step: a video (and the Ad maker's text), a carousel, or an offer poster
84
+ function makeStep(id) {
85
+ const c = camp(), b = plan.brand || {}, w = what();
86
+ const msg = c.message || c.name || b.tagline || '';
87
+ if (id === 'awareness') {
88
+ shots.splice(0, shots.length, `Hero shot of ${w}, slow push-in, clean bright setting`, `Close-up of ${w} with fine detail, soft light`, `A person enjoying ${w} in an everyday moment, natural light`);
89
+ renderShots();
90
+ store('ora.ad', { ...(store('ora.ad') || {}), title: msg.slice(0, 70), offer: c.offer || '', cta: c.cta || 'Find out more', music: 'upbeat' });
91
+ showView('create'); setMode('video');
92
+ formNote('Funnel · Awareness: three shots are ready. Make them, then press "Make an ad": the headline, offer and button come from your campaign.');
93
+ } else if (id === 'engagement') {
94
+ imgForm.type = 'carousel'; imgForm.shape = 'insta'; store('ora.imgForm', imgForm);
95
+ const lines = ((c.funnel.engagement || {}).what || '').split(/\n|\.\s+/).map(x => x.trim()).filter(x => x.length > 8).slice(0, 4);
96
+ Object.assign(poster, { title: c.name || msg || 'Tips', sub: b.name || '', slides: (lines.length >= 2 ? lines : [`Why ${w} matters`, `How to choose good ${w}`, `Our tip of the week`, c.cta ? `${c.cta}${c.offer ? `: ${c.offer}` : ''}` : 'Follow us for more']).join('\n'), cta: c.cta || '', layout: 'card' });
97
+ store('ora.poster', poster); renderPosterFields(); renderImgShapes();
98
+ $('imgPrompt').value = `Soft, bright background in the brand colours, minimal, with ${w} on one side`;
99
+ showView('create'); setMode('image');
100
+ formNote('Funnel · Engagement: a carousel is ready. Write one slide per line (or press ✨ Write slides for me), then Make.');
101
+ } else {
102
+ imgForm.type = 'poster'; imgForm.shape = 'insta'; store('ora.imgForm', imgForm);
103
+ Object.assign(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' });
104
+ store('ora.poster', poster); renderPosterFields(); renderImgShapes();
105
+ $('imgPrompt').value = `${w}, appetising product photo, bright and clean`;
106
+ showView('create'); setMode('image');
107
+ formNote('Funnel · Conversion: the offer poster is ready. Press Make poster.');
108
+ }
109
+ }
110
+ $('cSuggest').addEventListener('click', async e => {
111
+ const btn = e.currentTarget, label = btn.textContent; btn.disabled = true; btn.textContent = 'Thinking…';
112
+ const b = plan.brand || {}, c = camp();
113
+ const facts = [b.name && `Brand: ${b.name}`, b.offer && `Offers: ${b.offer}`, b.values && `Values: ${b.values}`, `Goal: ${GOALS.find(g => g[0] === c.goal)[1]}`, c.offer && `Offer: ${c.offer}`,
114
+ ...(plan.personas || []).filter(p => p.name).map(p => `Audience: ${p.name}; needs ${p.needs || ''}`)].filter(Boolean).join('\n');
115
+ const picks = $('cPicks'); picks.innerHTML = '';
116
+ try {
117
+ const out = await window.ora.improvePrompt(facts, 'campaign');
118
+ for (const line of out.split('\n')) {
119
+ const [n, m] = line.split('|').map(x => x.trim());
120
+ const p = document.createElement('button'); p.type = 'button'; p.textContent = n; p.title = m;
121
+ p.addEventListener('click', () => { c.name = n; c.message = m || c.message; renderCampaign(); savePlan(); picks.innerHTML = ''; });
122
+ picks.appendChild(p);
123
+ }
124
+ $('cNote').textContent = 'Click a name to use it with its message.';
125
+ } catch (err) {
126
+ $('cNote').textContent = /offline/.test(cleanErr(err)) ? 'Connect Cloudflare (free, in Online) for suggestions, or write your own.' : /declined/.test(cleanErr(err)) ? 'The online helper declined; write your own.' : cleanErr(err);
127
+ } finally { btn.disabled = false; btn.textContent = label; }
128
+ });
129
+
130
+ // --- 5 · Results -----------------------------------------------------------------------------------------------------------
131
+
132
+ const num = v => (Number.isFinite(+v) && v !== '' && v != null ? +v : 0);
133
+ const inter = r => num(r.likes) + num(r.comments) + num(r.shares) + num(r.saves);
134
+ const erOf = r => (num(r.reach) ? inter(r) / num(r.reach) * 100 : null);
135
+ const fmt = n => n >= 10000 ? `${(n / 1000).toFixed(n >= 100000 ? 0 : 1)}k` : Math.round(n).toLocaleString();
136
+ function totals() {
137
+ const rows = results().rows;
138
+ const t = { posts: rows.length };
139
+ for (const [k] of NUM_COLS) t[k] = rows.reduce((a, r) => a + num(r[k]), 0);
140
+ t.er = t.reach ? rows.reduce((a, r) => a + inter(r), 0) / t.reach * 100 : null;
141
+ return t;
142
+ }
143
+ function renderResults() {
144
+ const rows = results().rows, t = totals(), c = camp();
145
+ // tiles: the campaign's metrics first (with progress to target), then posts
146
+ const tiles = $('rTiles'); tiles.innerHTML = '';
147
+ const show = c.metrics.length ? c.metrics : [{ id: 'reach' }, { id: 'er' }, { id: 'followers' }];
148
+ for (const m of show) {
149
+ const def = METRICS.find(x => x[0] === m.id); if (!def) continue;
150
+ const v = t[m.id], target = num(m.target);
151
+ const el = document.createElement('div'); el.className = 'tile';
152
+ el.innerHTML = '<div class="k"></div><div class="v"></div><div class="t"></div>';
153
+ el.querySelector('.k').textContent = def[1];
154
+ el.querySelector('.v').textContent = v == null ? '—' : m.id === 'er' ? `${v.toFixed(1)}%` : fmt(v);
155
+ el.querySelector('.t').textContent = target ? `target ${m.id === 'er' ? `${target}%` : fmt(target)} · ${v == null ? 0 : Math.round(v / target * 100)}%` : def[2];
156
+ if (target) { const p = document.createElement('div'); p.className = 'prog'; p.innerHTML = '<span></span>'; p.querySelector('span').style.width = `${Math.min(100, (v || 0) / target * 100)}%`; el.appendChild(p); }
157
+ tiles.appendChild(el);
158
+ }
159
+ const pt = document.createElement('div'); pt.className = 'tile'; pt.innerHTML = `<div class="k">Posts measured</div><div class="v">${rows.length}</div><div class="t">${fmt(t.impressions)} impressions</div>`; tiles.appendChild(pt);
160
+ // table
161
+ const tb = $('rTable'); tb.innerHTML = '';
162
+ const head = document.createElement('tr');
163
+ for (const h of ['Date', 'Where', 'Post', 'Kind', ...NUM_COLS.map(x => x[1]), 'Eng. rate', '']) { const th = document.createElement('th'); th.textContent = h; head.appendChild(th); }
164
+ tb.appendChild(head);
165
+ for (const [i, r] of rows.entries()) {
166
+ const tr = document.createElement('tr');
167
+ const cell = el => { const td = document.createElement('td'); td.appendChild(el); tr.appendChild(td); return el; };
168
+ const inp = (k, type = 'text', w) => { const x = document.createElement('input'); x.type = type; x.value = r[k] || ''; if (w) x.style.width = w; if (type === 'number') x.min = '0'; x.addEventListener('input', () => { r[k] = x.value; if (type === 'number') { er.textContent = erOf(r) == null ? '—' : `${erOf(r).toFixed(1)}%`; } savePlan(); clearTimeout(renderResults.t); renderResults.t = setTimeout(renderSummary, 500); }); return x; };
169
+ cell(inp('date', 'date'));
170
+ const pl = document.createElement('select'); for (const p of ['Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'Other']) { const o = document.createElement('option'); o.textContent = p; pl.appendChild(o); } pl.value = r.platform || 'Instagram'; pl.addEventListener('change', () => { r.platform = pl.value; savePlan(); }); cell(pl);
171
+ cell(inp('title', 'text', '180px'));
172
+ const ty = document.createElement('select'); for (const [id, label] of CONTENT_TYPES) { const o = document.createElement('option'); o.value = id; o.textContent = label; ty.appendChild(o); } ty.value = r.type || 'educational'; ty.addEventListener('change', () => { r.type = ty.value; savePlan(); renderSummary(); }); cell(ty);
173
+ for (const [k] of NUM_COLS) cell(inp(k, 'number'));
174
+ const erTd = document.createElement('td'); erTd.className = 'er'; const er = document.createElement('span'); er.textContent = erOf(r) == null ? '—' : `${erOf(r).toFixed(1)}%`; erTd.appendChild(er); tr.appendChild(erTd);
175
+ const del = document.createElement('button'); del.type = 'button'; del.textContent = '✕'; del.title = 'Remove'; del.addEventListener('click', () => { rows.splice(i, 1); savePlan(); renderResults(); }); cell(del);
176
+ tb.appendChild(tr);
177
+ }
178
+ if (!rows.length) { const tr = document.createElement('tr'); tr.innerHTML = '<td colspan="14" class="muted">No posts yet. Add the posts you published, then type their numbers.</td>'; tb.appendChild(tr); }
179
+ renderSummary();
180
+ }
181
+ // only the parts that depend on the numbers (keeps focus while typing in the table)
182
+ function renderSummary() {
183
+ const rows = results().rows;
184
+ const by = {};
185
+ for (const r of rows) { if (!num(r.reach)) continue; const b = by[r.type || 'educational'] = by[r.type || 'educational'] || { i: 0, reach: 0, n: 0 }; b.i += inter(r); b.reach += num(r.reach); b.n++; }
186
+ const list = CONTENT_TYPES.filter(t => by[t[0]]).map(t => [t, by[t[0]].i / by[t[0]].reach * 100, by[t[0]].n]);
187
+ const max = Math.max(1, ...list.map(x => x[1]));
188
+ const box = $('rByType'); box.innerHTML = '';
189
+ if (!list.length) box.innerHTML = '<p class="muted small">The chart appears when posts have their reach and interactions.</p>';
190
+ for (const [[, label, color], er, n] of list.sort((a, b) => b[1] - a[1])) {
191
+ const row = document.createElement('div'); row.className = 'hbar';
192
+ row.title = `${label}: ${er.toFixed(1)}% engagement rate over ${n} post${n > 1 ? 's' : ''}`;
193
+ row.innerHTML = '<span></span><span class="track"><span class="fill"></span></span><span class="val"></span>';
194
+ row.firstChild.textContent = label;
195
+ row.querySelector('.fill').style.width = `${er / max * 100}%`; row.querySelector('.fill').style.background = color;
196
+ row.querySelector('.val').textContent = `${er.toFixed(1)}%`;
197
+ box.appendChild(row);
198
+ }
199
+ const best = rows.filter(r => erOf(r) != null).sort((a, b) => erOf(b) - erOf(a))[0];
200
+ $('rBest').textContent = best ? `Best post: "${best.title || 'untitled'}" (${best.platform || ''}, ${erOf(best).toFixed(1)}%). ${list.length > 1 ? `${list[0][0][1]} content works best so far: plan more of it.` : ''}` : '';
201
+ }
202
+ $('rAdd').addEventListener('click', () => { results().rows.push({ id: `r${Date.now()}`, date: ymd(new Date()), platform: 'Instagram', title: '', type: 'educational' }); savePlan(); renderResults(); });
203
+ $('rFromCal').addEventListener('click', () => {
204
+ const rows = results().rows, have = new Set(rows.map(r => `${r.date}|${r.title}`));
205
+ let n = 0;
206
+ for (const [d, e] of Object.entries((plan.calendar || {}).days || {})) {
207
+ if (!e.text || !['scheduled', 'posted'].includes(e.status)) continue;
208
+ for (const p of (e.platforms && e.platforms.length ? e.platforms : ['instagram'])) {
209
+ const platform = { instagram: 'Instagram', facebook: 'Facebook', linkedin: 'LinkedIn' }[p] || 'Other';
210
+ if (have.has(`${d}|${e.text}`) && rows.some(r => r.date === d && r.title === e.text && r.platform === platform)) continue;
211
+ rows.push({ id: `r${Date.now()}${n}`, date: d, platform, title: e.text, type: e.type }); n++;
212
+ }
213
+ }
214
+ $('rNote').textContent = n ? `Added ${n} post${n > 1 ? 's' : ''} from the calendar.` : 'No scheduled or posted days in the calendar yet (mark them in Plan › Calendar).';
215
+ savePlan(); renderResults();
216
+ });
217
+ const CSV_COLS = ['date', 'platform', 'title', 'type', ...NUM_COLS.map(x => x[0])];
218
+ $('rExport').addEventListener('click', async () => {
219
+ const q = v => `"${String(v == null ? '' : v).replace(/"/g, '""')}"`;
220
+ const lines = [[...CSV_COLS, 'engagement_rate'].map(q).join(',')];
221
+ for (const r of results().rows) lines.push([...CSV_COLS.map(k => r[k]), erOf(r) == null ? '' : erOf(r).toFixed(2)].map(q).join(','));
222
+ const f = await window.ora.planExport(`${(plan.brand || {}).name || 'Ora'} - results`, new TextEncoder().encode(`${lines.join('\r\n')}\r\n`), 'csv');
223
+ $('rNote').textContent = `Saved ${f.split(/[\\/]/).pop()} in Documents/Ora.`;
224
+ });
225
+ // CSV import: our own export, or any sheet with matching column names (date, platform, reach, likes…)
226
+ $('rImport').addEventListener('click', () => $('rFile').click());
227
+ $('rFile').addEventListener('change', async e => {
228
+ const file = e.target.files[0]; e.target.value = '';
229
+ if (!file) return;
230
+ const text = (await file.text()).replace(/^/, '');
231
+ const parse = line => { const out = []; let cur = '', q = false; for (let i = 0; i < line.length; i++) { const ch = line[i]; if (q) { if (ch === '"' && line[i + 1] === '"') { cur += '"'; i++; } else if (ch === '"') q = false; else cur += ch; } else if (ch === '"') q = true; else if (ch === ',' || ch === ';') { out.push(cur); cur = ''; } else cur += ch; } out.push(cur); return out; };
232
+ const lines = text.split(/\r?\n/).filter(l => l.trim());
233
+ if (lines.length < 2) { $('rNote').textContent = 'That file has no rows.'; return; }
234
+ const head = parse(lines[0]).map(h => h.trim().toLowerCase());
235
+ const col = names => head.findIndex(h => names.some(n => h === n || h.includes(n)));
236
+ const map = { date: col(['date', 'publish']), platform: col(['platform', 'network']), title: col(['title', 'post', 'description']), type: col(['type', 'kind']),
237
+ reach: col(['reach']), impressions: col(['impression', 'views']), likes: col(['like', 'reaction']), comments: col(['comment']), shares: col(['share']), saves: col(['save']), clicks: col(['click']), followers: col(['follow']) };
238
+ let n = 0;
239
+ for (const l of lines.slice(1)) {
240
+ const v = parse(l), r = { id: `r${Date.now()}${n}` };
241
+ for (const [k, i] of Object.entries(map)) if (i >= 0 && v[i] != null) r[k] = v[i].trim();
242
+ if (r.type && !CONTENT_TYPES.some(t => t[0] === r.type)) r.type = (CONTENT_TYPES.find(t => t[1].toLowerCase() === r.type.toLowerCase()) || CONTENT_TYPES[0])[0];
243
+ results().rows.push(r); n++;
244
+ }
245
+ $('rNote').textContent = `Imported ${n} row${n === 1 ? '' : 's'}.`;
246
+ savePlan(); renderResults();
247
+ });
app/renderer/index.html CHANGED
@@ -11,6 +11,7 @@
11
  <div class="brand"><span class="mark" aria-hidden="true"></span><span>Ora</span><small id="version"></small></div>
12
  <nav class="nav-tabs" id="navTabs" aria-label="Sections">
13
  <button type="button" data-view="create" aria-current="page">Create</button>
 
14
  <button type="button" data-view="library">Library</button>
15
  <button type="button" data-view="models">Models</button>
16
  <button type="button" data-view="online">Online</button>
@@ -31,6 +32,7 @@
31
  <div class="muted" id="setupDisk"></div>
32
  </div>
33
  <div class="spacer"></div>
 
34
  <button class="ghost" id="startFastBtn" type="button" hidden>Start with Fast now</button>
35
  <button class="primary" id="downloadBtn" type="button">Download</button>
36
  </div>
@@ -219,6 +221,7 @@
219
  </div>
220
  <div class="stage-images" id="stageImages" hidden>
221
  <div class="img-grid" id="imgGrid"></div>
 
222
  <div class="poster-bar" id="posterBar" hidden><span class="muted small" id="posterStatus"></span><span class="spacer"></span><button class="primary" id="posterSave" type="button">Save posters</button></div>
223
  <div class="video-bar">
224
  <div class="muted small" id="imagesInfo"></div>
@@ -236,6 +239,7 @@
236
  <button class="ghost" id="revealBtn" type="button">Show in folder</button>
237
  <button class="ghost" id="saveAsBtn" type="button">Save as…</button>
238
  <button class="ghost" id="reuseBtn" type="button">Use these settings</button>
 
239
  <button class="ghost" id="enhanceBtn" type="button">Enhance</button>
240
  <button class="primary" id="makeAdBtn" type="button">Make an ad</button>
241
  </div>
@@ -290,6 +294,144 @@
290
  </div>
291
  </section>
292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  <!-- library: everything made, videos and images -->
294
  <section id="libraryView" class="page" hidden>
295
  <div class="page-head">
@@ -385,6 +527,19 @@
385
  <div class="row-btns"><button class="ghost" id="cfOpen" type="button">Open Cloudflare</button><button class="link" id="cfRemove" type="button" hidden>Disconnect</button></div>
386
  <p class="muted small" id="cfUsage"></p>
387
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  </div>
389
  <p class="muted small mdl-foot">Tokens and connection codes are stored encrypted on this computer and sent only to that service or your own notebook; Ora never sees your passwords. With Kaggle, Colab and Lightning AI the models run in your own notebook; with Cloudflare, prompts go to Cloudflare's servers. Free allowances are set by each platform; check their terms of use.</p>
390
  </section>
@@ -402,6 +557,7 @@
402
  <dialog id="templateDlg" class="tpl-dlg">
403
  <h2>Start from a template</h2>
404
  <p class="muted small">Each template fills in the shots, style, shape and the text for the ad or poster. Change the product and the words to your own, then press Make.</p>
 
405
  <div class="idea-grid tpl-grid" id="templateGrid"></div>
406
  <div class="dlg-actions"><button class="ghost" id="templateClose" type="button">Close</button></div>
407
  </dialog>
@@ -417,6 +573,33 @@
417
  <div class="dlg-actions"><button class="ghost" id="enhClose" type="button">Close</button><button class="primary" id="enhGo" type="button">Enhance</button></div>
418
  </dialog>
419
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  <dialog id="clearDlg">
421
  <h2>Clear history</h2>
422
  <p>This removes Ora's list of past videos and the prompts saved with them.</p>
@@ -431,5 +614,9 @@
431
  <script src="music.js"></script>
432
  <script src="ad.js"></script>
433
  <script src="enhance.js"></script>
 
 
 
 
434
  </body>
435
  </html>
 
11
  <div class="brand"><span class="mark" aria-hidden="true"></span><span>Ora</span><small id="version"></small></div>
12
  <nav class="nav-tabs" id="navTabs" aria-label="Sections">
13
  <button type="button" data-view="create" aria-current="page">Create</button>
14
+ <button type="button" data-view="plan">Plan</button>
15
  <button type="button" data-view="library">Library</button>
16
  <button type="button" data-view="models">Models</button>
17
  <button type="button" data-view="online">Online</button>
 
32
  <div class="muted" id="setupDisk"></div>
33
  </div>
34
  <div class="spacer"></div>
35
+ <button class="link" id="skipModelsBtn" type="button" title="Plan your campaign and make pictures with Cloudflare (free); download video models later in Models">Skip: plan and make pictures online</button>
36
  <button class="ghost" id="startFastBtn" type="button" hidden>Start with Fast now</button>
37
  <button class="primary" id="downloadBtn" type="button">Download</button>
38
  </div>
 
221
  </div>
222
  <div class="stage-images" id="stageImages" hidden>
223
  <div class="img-grid" id="imgGrid"></div>
224
+ <div class="poster-bar"><span class="spacer"></span><button class="ghost" id="postImgBtn" type="button">Post…</button></div>
225
  <div class="poster-bar" id="posterBar" hidden><span class="muted small" id="posterStatus"></span><span class="spacer"></span><button class="primary" id="posterSave" type="button">Save posters</button></div>
226
  <div class="video-bar">
227
  <div class="muted small" id="imagesInfo"></div>
 
239
  <button class="ghost" id="revealBtn" type="button">Show in folder</button>
240
  <button class="ghost" id="saveAsBtn" type="button">Save as…</button>
241
  <button class="ghost" id="reuseBtn" type="button">Use these settings</button>
242
+ <button class="ghost" id="postBtn" type="button">Post…</button>
243
  <button class="ghost" id="enhanceBtn" type="button">Enhance</button>
244
  <button class="primary" id="makeAdBtn" type="button">Make an ad</button>
245
  </div>
 
294
  </div>
295
  </section>
296
 
297
+ <!-- plan: the marketing plan, in the order of the course: brand, personas, campaign, calendar, results -->
298
+ <section id="planView" class="page page-plan" hidden>
299
+ <div class="page-head">
300
+ <div><h1>Plan</h1><p class="muted small">Your marketing plan, step by step. Everything you write here shapes what Ora makes: prompts, posters, ads and captions.</p></div>
301
+ <div class="spacer"></div>
302
+ <div class="seg plan-tabs" id="planTabs" role="tablist">
303
+ <button type="button" data-tab="brand" aria-checked="true">1 · Brand</button>
304
+ <button type="button" data-tab="personas" aria-checked="false">2 · Personas</button>
305
+ <button type="button" data-tab="campaign" aria-checked="false">3 · Campaign</button>
306
+ <button type="button" data-tab="calendar" aria-checked="false">4 · Calendar</button>
307
+ <button type="button" data-tab="results" aria-checked="false">5 · Results</button>
308
+ <button type="button" data-tab="present" aria-checked="false">6 · Presentation</button>
309
+ </div>
310
+ </div>
311
+
312
+ <div class="plan-pane" id="paneBrand">
313
+ <div class="plan-grid">
314
+ <div class="panel plan-card">
315
+ <h3>Who you are</h3>
316
+ <label class="field"><span class="label">Brand name</span><input id="bName" maxlength="60" placeholder="Sunpress"></label>
317
+ <label class="field"><span class="label">What you offer, and where</span><input id="bOffer" maxlength="140" placeholder="Fresh-pressed juices and smoothies in Luxembourg City"></label>
318
+ <div class="field"><span class="label">Mission</span><textarea id="bMission" rows="3" maxlength="400" placeholder="We make healthy eating easy for busy people in Luxembourg, with juices pressed every morning from local fruit."></textarea>
319
+ <div class="improve-row"><button class="ghost improve-btn" id="bMissionAi" type="button">✨ Suggest</button></div></div>
320
+ <label class="field"><span class="label">Values <small class="muted">(comma between)</small></span><input id="bValues" maxlength="160" placeholder="fresh, local, honest, no added sugar"></label>
321
+ </div>
322
+ <div class="panel plan-card">
323
+ <h3>How you sound</h3>
324
+ <div class="field"><span class="label">Personality <small class="muted">(pick up to 3)</small></span><div class="chips" id="bPersonality"></div></div>
325
+ <label class="field"><span class="label">Tone of voice</span><input id="bTone" maxlength="160" placeholder="short, warm and cheerful; no jargon"></label>
326
+ <div class="field"><span class="label">Tagline</span><input id="bTagline" maxlength="80" placeholder="Pressed this morning. Gone by noon.">
327
+ <div class="improve-row"><span class="tag-picks" id="bTagPicks"></span><button class="ghost improve-btn" id="bTaglineAi" type="button">✨ Suggest</button></div></div>
328
+ <label class="field"><span class="label">Always avoid <small class="muted">(in pictures and text)</small></span><input id="bAvoid" maxlength="160" placeholder="plastic bottles, people's faces"></label>
329
+ </div>
330
+ <div class="panel plan-card">
331
+ <h3>How you look</h3>
332
+ <div class="field"><span class="label">Colours</span><div class="swatches" id="bColors"></div></div>
333
+ <div class="field"><span class="label">Font</span><div class="seg" id="bFontSeg"></div></div>
334
+ <div class="field"><span class="label">Logo</span><div class="logo-row"><img id="bLogoImg" alt="" hidden><button class="ghost" id="bLogoBtn" type="button">Add logo…</button><button class="link" id="bLogoRemove" type="button" hidden>Remove</button></div></div>
335
+ <label class="check"><input type="checkbox" id="bUse" checked> <span>Use this brand in Create <small class="muted">(prompts, posters, ads and captions)</small></span></label>
336
+ </div>
337
+ </div>
338
+ <div class="plan-actions"><span class="muted small" id="bSaved"></span><span class="spacer"></span><button class="primary" id="bExport" type="button">Save Brand Identity Summary (PNG + PDF)</button></div>
339
+ <div class="panel plan-card starter-card">
340
+ <h3>Start from an example <small class="muted">(for practice)</small></h3>
341
+ <p class="muted small">Fills the whole plan (brand, two personas and a campaign) for an example business. It replaces what is in the plan now, so save yours first.</p>
342
+ <div class="chips" id="starterList"></div>
343
+ <div class="ad-row"><button class="ghost" id="planSaveFile" type="button">Save my plan to a file</button><button class="ghost" id="planOpenFile" type="button">Open a plan file…</button><input type="file" id="planFile" accept=".json,application/json" hidden><span class="muted small" id="planFileNote"></span></div>
344
+ <p class="muted small">In class, connect <b>Cloudflare</b> (free, in Online) on each laptop: pictures take seconds, and captions and ✨ suggestions get richer. Trainers: <a href="https://huggingface.co/spaces/Devseis/Ora/blob/main/CLASSROOM.md" target="_blank" rel="noopener">Running Ora in class</a>.</p>
345
+ </div>
346
+ </div>
347
+
348
+ <div class="plan-pane" id="panePersonas" hidden>
349
+ <p class="muted small">Who you are talking to. Two personas are a good start. The one marked <b>Main</b> is used when Ora writes captions.</p>
350
+ <div class="persona-grid" id="personaGrid"></div>
351
+ <div class="plan-actions"><button class="ghost" id="addPersona" type="button">Add persona</button><span class="spacer"></span><button class="primary" id="pExport" type="button">Save Brand Identity Summary (PNG + PDF)</button></div>
352
+ </div>
353
+
354
+ <div class="plan-pane" id="paneCampaign" hidden>
355
+ <div class="plan-grid">
356
+ <div class="panel plan-card">
357
+ <h3>The campaign</h3>
358
+ <label class="field"><span class="label">Campaign name</span><input id="cName" maxlength="70" placeholder="Fresh Start January"></label>
359
+ <div class="field"><span class="label">Goal</span><div class="seg seg-wrap" id="cGoal"></div></div>
360
+ <div class="persona-row"><label class="field"><span class="label">From</span><input type="date" id="cStart"></label><label class="field"><span class="label">To</span><input type="date" id="cEnd"></label></div>
361
+ <div class="field"><span class="label">Key message</span><textarea id="cMessage" rows="2" maxlength="200" placeholder="Start the year with a fresh juice every morning."></textarea></div>
362
+ <label class="field"><span class="label">Why choose us <small class="muted">(value proposition)</small></span><input id="cValue" maxlength="160" placeholder="Pressed every morning from local fruit, never with added sugar"></label>
363
+ <div class="persona-row"><label class="field"><span class="label">Offer <small class="muted">(optional)</small></span><input id="cOffer" maxlength="80" placeholder="2nd juice half price"></label><label class="field"><span class="label">Call to action</span><input id="cCta" maxlength="40" placeholder="Order now"></label></div>
364
+ <div class="field"><span class="label">Channels</span><div class="chips" id="cChannels"></div></div>
365
+ <div class="improve-row"><span class="tag-picks" id="cPicks"></span><button class="ghost improve-btn" id="cSuggest" type="button">✨ Suggest name and message</button></div>
366
+ </div>
367
+ <div class="panel plan-card">
368
+ <h3>Funnel</h3>
369
+ <p class="muted small">How people move from first seeing you to buying. One piece of content per step to start; Ora can make each one.</p>
370
+ <div class="funnel" id="cFunnel"></div>
371
+ </div>
372
+ <div class="panel plan-card">
373
+ <h3>Success metrics <small class="muted">(pick 3, with a target)</small></h3>
374
+ <div class="metric-list" id="cMetrics"></div>
375
+ <p class="muted small">Results (step 5) measures each one against its target.</p>
376
+ </div>
377
+ </div>
378
+ <p class="muted small" id="cNote"></p>
379
+ </div>
380
+
381
+ <div class="plan-pane" id="paneCalendar" hidden>
382
+ <div class="cal-bar">
383
+ <label class="field"><span class="label">Starts</span><input type="date" id="calStart"></label>
384
+ <div class="field"><span class="label">Posts a week</span><div class="seg" id="calPerWeek"></div></div>
385
+ <label class="field"><span class="label">Post time</span><input type="time" id="calTime" value="09:00"></label>
386
+ <span class="spacer"></span>
387
+ <button class="ghost" id="calCsv" type="button">Export for Google Sheets (CSV)</button>
388
+ <button class="ghost" id="calIcs" type="button">Add to my calendar (.ics)</button>
389
+ </div>
390
+ <div class="cal-layout">
391
+ <div class="panel plan-card cal-ideas">
392
+ <h3>Content ideas <small class="muted" id="ideaCount"></small></h3>
393
+ <p class="muted small">The five kinds of content from the course, plus offers. Aim for at least 10 ideas.</p>
394
+ <div class="idea-list" id="ideaList"></div>
395
+ <div class="idea-add"><select id="ideaType" aria-label="Kind of content"></select><input id="ideaText" maxlength="120" placeholder="New idea…"><button class="ghost" id="ideaAdd" type="button">Add</button></div>
396
+ <div class="ad-row"><button class="ghost improve-btn" id="ideaSuggest" type="button">✨ Suggest ideas</button><button class="primary" id="calFill" type="button">Fill the month</button></div>
397
+ <p class="muted small" id="ideaNote"></p>
398
+ </div>
399
+ <div class="panel plan-card cal-month">
400
+ <div class="cal-head"><h3 id="calTitle">Next 30 days</h3><span class="muted small" id="calMix"></span></div>
401
+ <div class="cal-grid" id="calGrid"></div>
402
+ <div class="cal-legend" id="calLegend"></div>
403
+ </div>
404
+ </div>
405
+ </div>
406
+
407
+ <div class="plan-pane" id="paneResults" hidden>
408
+ <div class="tiles" id="rTiles"></div>
409
+ <div class="plan-grid results-grid">
410
+ <div class="panel plan-card results-table-card">
411
+ <div class="cal-head"><h3>Posts and their numbers</h3><span class="spacer"></span><button class="ghost" id="rFromCal" type="button">Add posts from the calendar</button><button class="ghost" id="rAdd" type="button">Add a post</button></div>
412
+ <p class="muted small">Copy the numbers from each platform's insights (Instagram › Insights, Facebook › Meta Business Suite, LinkedIn › Analytics). Ora works out the engagement rate.</p>
413
+ <div class="rtable-wrap"><table class="rtable" id="rTable"></table></div>
414
+ <div class="ad-row"><button class="ghost" id="rImport" type="button">Import CSV…</button><button class="ghost" id="rExport" type="button">Export CSV</button><input type="file" id="rFile" accept=".csv,text/csv" hidden><span class="muted small" id="rNote"></span></div>
415
+ </div>
416
+ <div class="panel plan-card">
417
+ <h3>Engagement rate by kind of content</h3>
418
+ <div class="hbars" id="rByType"></div>
419
+ <p class="muted small" id="rBest"></p>
420
+ </div>
421
+ </div>
422
+ </div>
423
+
424
+ <div class="plan-pane" id="panePresent" hidden>
425
+ <div class="panel plan-card present-card">
426
+ <h3>Final campaign presentation</h3>
427
+ <p class="muted small">One click makes a slide deck (PDF, or PowerPoint to edit; 16:9) from your plan: brand identity, personas, where you will be online, the content mix and calendar, and examples you made with Ora.</p>
428
+ <ol class="present-list" id="presentList"></ol>
429
+ <label class="field"><span class="label">Presented by <small class="muted">(optional)</small></span><input id="presentBy" maxlength="80" placeholder="Your name"></label>
430
+ <div class="ad-row"><button class="primary" id="presentMake" type="button">Make the presentation (PDF)</button><button class="ghost" id="presentPptx" type="button">PowerPoint (.pptx)</button><span class="muted small" id="presentNote"></span></div>
431
+ </div>
432
+ </div>
433
+ </section>
434
+
435
  <!-- library: everything made, videos and images -->
436
  <section id="libraryView" class="page" hidden>
437
  <div class="page-head">
 
527
  <div class="row-btns"><button class="ghost" id="cfOpen" type="button">Open Cloudflare</button><button class="link" id="cfRemove" type="button" hidden>Disconnect</button></div>
528
  <p class="muted small" id="cfUsage"></p>
529
  </div>
530
+ <div class="mdl" id="n8nCard">
531
+ <div class="mdl-top"><span class="mdl-title">n8n automation</span><span class="mdl-tag">Schedule posts</span></div>
532
+ <div class="mdl-made">Ora sends each post (file + captions + time) to your n8n, which waits until the post time and posts it to LinkedIn, your Facebook Page or Instagram, and can log every post in a Google Sheet.</div>
533
+ <ol class="steps-list">
534
+ <li><button class="link" id="n8nGetWf" type="button">Save the ready-made workflow</button>, then in n8n: <b>Workflows › Import from file</b>.</li>
535
+ <li>Connect the accounts you use (LinkedIn, Facebook Page, Instagram, Google Sheets), switch those steps on, and <b>activate</b> it. The note in the workflow explains each one.</li>
536
+ <li>Open the <b>Ora sends a post</b> step, copy its <b>Production URL</b> and paste it here.</li>
537
+ </ol>
538
+ <div class="paste-row"><input id="n8nUrl" placeholder="https://your-n8n…/webhook/ora-post" autocomplete="off" spellcheck="false"><button class="primary" id="n8nSave" type="button">Save</button></div>
539
+ <div class="mdl-status" id="n8nStatus"></div>
540
+ <div class="row-btns"><button class="ghost" id="n8nTest" type="button">Test</button><button class="ghost" id="openPosts" type="button">Ready to post folder</button></div>
541
+ <p class="muted small">Without n8n, Post… still saves each post in the <b>Ready to post</b> folder: the file and a caption for each platform, ready to copy.</p>
542
+ </div>
543
  </div>
544
  <p class="muted small mdl-foot">Tokens and connection codes are stored encrypted on this computer and sent only to that service or your own notebook; Ora never sees your passwords. With Kaggle, Colab and Lightning AI the models run in your own notebook; with Cloudflare, prompts go to Cloudflare's servers. Free allowances are set by each platform; check their terms of use.</p>
545
  </section>
 
557
  <dialog id="templateDlg" class="tpl-dlg">
558
  <h2>Start from a template</h2>
559
  <p class="muted small">Each template fills in the shots, style, shape and the text for the ad or poster. Change the product and the words to your own, then press Make.</p>
560
+ <div class="ad-row" id="tplForRow" hidden><span class="label">For</span><select id="tplFor" aria-label="Which persona"></select><span class="muted small">Your persona appears in the shots, and captions are written for them.</span></div>
561
  <div class="idea-grid tpl-grid" id="templateGrid"></div>
562
  <div class="dlg-actions"><button class="ghost" id="templateClose" type="button">Close</button></div>
563
  </dialog>
 
573
  <div class="dlg-actions"><button class="ghost" id="enhClose" type="button">Close</button><button class="primary" id="enhGo" type="button">Enhance</button></div>
574
  </dialog>
575
 
576
+ <dialog id="postDlg" class="post-dlg">
577
+ <h2>Post</h2>
578
+ <p class="muted small" id="postWhat"></p>
579
+ <div class="field"><span class="label">Where</span><div class="post-platforms" id="postPlatforms"></div></div>
580
+ <div class="ad-row" id="postForRow" hidden><span class="label">For</span><select id="postFor" aria-label="Which persona"></select></div>
581
+ <div class="post-caps" id="postCaps"></div>
582
+ <div class="ad-row"><button class="ghost improve-btn" id="postWriteAll" type="button">✨ Write captions</button><span class="muted small" id="postWriteNote"></span></div>
583
+ <div class="field"><span class="label">When</span>
584
+ <div class="ad-row"><label class="check"><input type="radio" name="postWhen" value="now" checked> As soon as possible</label><label class="check"><input type="radio" name="postWhen" value="at"> At</label><input type="datetime-local" id="postAt"></div></div>
585
+ <p class="small" id="postStatus"></p>
586
+ <p class="error" id="postError" role="alert" hidden></p>
587
+ <div class="dlg-actions"><button class="ghost" id="postClose" type="button">Close</button><button class="ghost" id="postSave" type="button">Save to Ready to post</button><button class="primary" id="postSend" type="button">Send to n8n</button></div>
588
+ </dialog>
589
+
590
+ <dialog id="dayDlg" class="post-dlg">
591
+ <h2 id="dayTitle">Day</h2>
592
+ <div class="field"><span class="label">Kind of content</span><select id="dayType"></select></div>
593
+ <label class="field"><span class="label">Idea</span><input id="dayText" maxlength="140"></label>
594
+ <div class="field"><span class="label">Where</span><div class="post-platforms" id="dayPlatforms"></div></div>
595
+ <div class="field"><span class="label">Status</span><div class="seg" id="dayStatus"></div></div>
596
+ <div class="field"><span class="label">Content</span><div class="day-item" id="dayItem"></div></div>
597
+ <div class="field"><span class="label">Captions <small class="muted">(used when you press Post…)</small></span><div class="post-caps" id="dayCaps"></div>
598
+ <div class="ad-row"><button class="ghost improve-btn" id="dayWrite" type="button">✨ Write captions</button><span class="muted small" id="dayCapNote"></span></div></div>
599
+ <div class="pic-picker" id="dayPicker" hidden></div>
600
+ <div class="dlg-actions"><button class="link" id="dayClear" type="button">Clear this day</button><span class="spacer"></span><button class="ghost" id="dayMake" type="button">Make it in Create</button><button class="ghost" id="dayLink" type="button">Use something I made…</button><button class="primary" id="dayPost" type="button">Post…</button><button class="ghost" id="dayClose" type="button">Done</button></div>
601
+ </dialog>
602
+
603
  <dialog id="clearDlg">
604
  <h2>Clear history</h2>
605
  <p>This removes Ora's list of past videos and the prompts saved with them.</p>
 
614
  <script src="music.js"></script>
615
  <script src="ad.js"></script>
616
  <script src="enhance.js"></script>
617
+ <script src="post.js"></script>
618
+ <script src="plan.js"></script>
619
+ <script src="calendar.js"></script>
620
+ <script src="campaign.js"></script>
621
  </body>
622
  </html>
app/renderer/plan.js ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ /* global $, S, store, brand, poster, renderBrand, renderMoreSummary, renderPosterFields, showView, setMode, imgForm, cleanErr,
3
+ POSTER_FONTS, wrapLines, roundRect, luminance, loadImg, formNote, renderCalendar, renderPresent, renderCampaign, renderResults */
4
+ // Plan tab (course order): 1 Brand, 2 Personas, 3 Campaign and 5 Results (renderer/campaign.js), 4 Calendar and
5
+ // 6 Presentation (renderer/calendar.js). The plan lives in userData/plan.json; "Use this brand in Create"
6
+ // feeds the brand kit (prompts), the poster and ad defaults (colour, logo, font) and the captions (tone, audience).
7
+
8
+ const PERSONALITIES = ['Friendly', 'Premium', 'Playful', 'Bold', 'Calm', 'Expert', 'Warm', 'Modern', 'Natural', 'Trustworthy', 'Creative', 'Energetic'];
9
+ const WHERE_ONLINE = ['Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'YouTube', 'Google', 'Email', 'WhatsApp'];
10
+ // a few colour names so image prompts get words instead of hex codes
11
+ const COLOR_NAMES = [['black', '#111111'], ['charcoal', '#36454f'], ['grey', '#8a8a8a'], ['white', '#ffffff'], ['cream', '#f5efe0'], ['beige', '#d9c7a6'], ['brown', '#7b4a2a'],
12
+ ['red', '#d32f2f'], ['coral', '#ff6f61'], ['pink', '#f48fb1'], ['blush pink', '#f6d1d1'], ['orange', '#f57c00'], ['peach', '#ffcc9e'], ['gold', '#d4a72c'], ['yellow', '#fdd835'],
13
+ ['olive green', '#6b7b2a'], ['green', '#2e7d32'], ['mint green', '#a8e6cf'], ['teal', '#00897b'], ['turquoise', '#26c6da'], ['sky blue', '#81d4fa'], ['blue', '#1e5bd8'],
14
+ ['navy blue', '#1a2a5a'], ['purple', '#6a1b9a'], ['lavender', '#c7b8ea'], ['burgundy', '#7b1f3a']];
15
+
16
+ let plan = { brand: {}, personas: [] };
17
+ let planLoaded = false, planTab = 'brand';
18
+
19
+ function hexName(hex) {
20
+ const n = h => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16));
21
+ const [r, g, b] = n(hex);
22
+ let best = COLOR_NAMES[0], d0 = Infinity;
23
+ for (const c of COLOR_NAMES) { const [r2, g2, b2] = n(c[1]); const d = (r - r2) ** 2 * 0.3 + (g - g2) ** 2 * 0.59 + (b - b2) ** 2 * 0.11; if (d < d0) { d0 = d; best = c; } }
24
+ return best[0];
25
+ }
26
+
27
+ // --- load / save ---------------------------------------------------------------------------------------------------
28
+
29
+ async function loadPlan() {
30
+ if (planLoaded) return;
31
+ try { plan = { brand: {}, personas: [], ...(await window.ora.planGet()) }; } catch { }
32
+ plan.brand = { name: '', offer: '', mission: '', values: '', personality: [], tone: '', tagline: '', avoid: '', colors: ['#1c6b4f', '#f5efe0'], font: 'modern', logo: null, use: true, ...plan.brand };
33
+ plan.personas = Array.isArray(plan.personas) ? plan.personas : [];
34
+ planLoaded = true;
35
+ }
36
+ let saveTimer = null;
37
+ function savePlan() {
38
+ clearTimeout(saveTimer);
39
+ saveTimer = setTimeout(async () => {
40
+ try { await window.ora.planSet(plan); $('bSaved').textContent = 'Saved on this computer.'; } catch (e) { $('bSaved').textContent = cleanErr(e); }
41
+ applyBrand();
42
+ }, 400);
43
+ }
44
+
45
+ // The brand reaches Create: the brand kit words (prompts), poster/ad colour, font and logo
46
+ function applyBrand() {
47
+ const b = plan.brand;
48
+ if (!b.use || !b.name) return;
49
+ brand.on = true;
50
+ brand.name = b.name;
51
+ brand.words = [...(b.personality || []).map(x => x.toLowerCase()), b.values].filter(Boolean).join(', ');
52
+ brand.colors = (b.colors || []).map(hexName).filter((x, i, a) => a.indexOf(x) === i).join(' and ');
53
+ brand.avoid = b.avoid || '';
54
+ store('ora.brand', brand);
55
+ renderBrand(); renderMoreSummary();
56
+ if (b.colors && b.colors[0]) poster.accent = b.colors[0];
57
+ poster.font = b.font || poster.font;
58
+ if (b.logo) poster.logo = b.logo;
59
+ store('ora.poster', poster); renderPosterFields();
60
+ const a = store('ora.ad') || {};
61
+ store('ora.ad', { ...a, accent: b.colors && b.colors[0] ? b.colors[0] : a.accent, font: b.font || a.font, logo: b.logo || a.logo });
62
+ }
63
+ // Used by post.js for captions
64
+ function brandVoice() {
65
+ const b = plan.brand || {};
66
+ if (!b.use || !b.name) return null;
67
+ return { brand: b.name, tone: [b.tone, (b.personality || []).join(', ').toLowerCase(), b.tagline && `tagline: ${b.tagline}`].filter(Boolean).join('; ') };
68
+ }
69
+ function personaDesc(p) {
70
+ if (!p || !p.name) return '';
71
+ return [`${p.name}${p.age ? `, ${p.age}` : ''}${p.job ? `, ${p.job}` : ''}`, p.needs && `needs: ${p.needs}`, p.motivations && `cares about: ${p.motivations}`].filter(Boolean).join('; ');
72
+ }
73
+ function mainPersona() { return personaDesc(plan.personas.find(x => x.main) || plan.personas[0]); }
74
+
75
+ // --- Brand ---------------------------------------------------------------------------------------------------------
76
+
77
+ function renderPlan() {
78
+ loadPlan().then(() => {
79
+ for (const b of $('planTabs').children) b.setAttribute('aria-checked', String(b.dataset.tab === planTab));
80
+ for (const [tab, id] of [['brand', 'paneBrand'], ['personas', 'panePersonas'], ['campaign', 'paneCampaign'], ['calendar', 'paneCalendar'], ['results', 'paneResults'], ['present', 'panePresent']]) $(id).hidden = planTab !== tab;
81
+ ({ brand: renderBrandPane, personas: renderPersonas, campaign: renderCampaign, calendar: renderCalendar, results: renderResults, present: renderPresent })[planTab]();
82
+ });
83
+ }
84
+ const BRAND_FIELDS = [['bName', 'name'], ['bOffer', 'offer'], ['bMission', 'mission'], ['bValues', 'values'], ['bTone', 'tone'], ['bTagline', 'tagline'], ['bAvoid', 'avoid']];
85
+ function renderBrandPane() {
86
+ renderStarters();
87
+ const b = plan.brand;
88
+ for (const [id, k] of BRAND_FIELDS) $(id).value = b[k] || '';
89
+ $('bUse').checked = b.use !== false;
90
+ const chips = $('bPersonality');
91
+ chips.innerHTML = '';
92
+ for (const p of PERSONALITIES) {
93
+ const c = document.createElement('button');
94
+ c.type = 'button'; c.textContent = p; c.setAttribute('aria-pressed', String(b.personality.includes(p)));
95
+ c.addEventListener('click', () => {
96
+ const on = b.personality.includes(p);
97
+ if (!on && b.personality.length >= 3) return;
98
+ b.personality = on ? b.personality.filter(x => x !== p) : [...b.personality, p];
99
+ renderBrandPane(); savePlan();
100
+ });
101
+ chips.appendChild(c);
102
+ }
103
+ const sw = $('bColors');
104
+ sw.innerHTML = '';
105
+ b.colors.forEach((hex, i) => {
106
+ const inp = document.createElement('input'); inp.type = 'color'; inp.value = hex; inp.title = hexName(hex);
107
+ inp.addEventListener('input', () => { b.colors[i] = inp.value; inp.title = hexName(inp.value); savePlan(); });
108
+ sw.appendChild(inp);
109
+ });
110
+ if (b.colors.length < 4) { const add = document.createElement('button'); add.className = 'link'; add.type = 'button'; add.textContent = '+ colour'; add.addEventListener('click', () => { b.colors.push('#d4a72c'); renderBrandPane(); savePlan(); }); sw.appendChild(add); }
111
+ if (b.colors.length > 1) { const rm = document.createElement('button'); rm.className = 'link'; rm.type = 'button'; rm.textContent = '− colour'; rm.addEventListener('click', () => { b.colors.pop(); renderBrandPane(); savePlan(); }); sw.appendChild(rm); }
112
+ const fs = $('bFontSeg');
113
+ fs.innerHTML = '';
114
+ for (const [v, l] of [['modern', 'Modern'], ['serif', 'Elegant'], ['display', 'Bold']]) {
115
+ const x = document.createElement('button'); x.type = 'button'; x.textContent = l; x.setAttribute('aria-checked', String(b.font === v));
116
+ x.style.fontFamily = POSTER_FONTS[v].family;
117
+ x.addEventListener('click', () => { b.font = v; renderBrandPane(); savePlan(); });
118
+ fs.appendChild(x);
119
+ }
120
+ $('bLogoImg').hidden = !b.logo; $('bLogoRemove').hidden = !b.logo;
121
+ if (b.logo) $('bLogoImg').src = `ora://video/${encodeURIComponent(b.logo.id)}/${b.logo.file}`;
122
+ $('bLogoBtn').textContent = b.logo ? 'Change logo…' : 'Add logo…';
123
+ }
124
+ for (const [id, k] of BRAND_FIELDS) $(id).addEventListener('input', e => { plan.brand[k] = e.target.value; savePlan(); });
125
+ $('bUse').addEventListener('change', e => { plan.brand.use = e.target.checked; if (!e.target.checked) { brand.on = false; store('ora.brand', brand); renderBrand(); renderMoreSummary(); } savePlan(); });
126
+ $('bLogoBtn').addEventListener('click', async () => {
127
+ try { const p = await window.ora.pickPhoto('logo'); if (!p) return; plan.brand.logo = { id: p.id, file: p.file }; renderBrandPane(); savePlan(); } catch (e) { $('bSaved').textContent = cleanErr(e); }
128
+ });
129
+ $('bLogoRemove').addEventListener('click', () => { plan.brand.logo = null; renderBrandPane(); savePlan(); });
130
+ function brandFacts() {
131
+ const b = plan.brand;
132
+ return [b.name && `Brand: ${b.name}`, b.offer && `Offers: ${b.offer}`, b.values && `Values: ${b.values}`, b.personality.length && `Personality: ${b.personality.join(', ')}`, b.tone && `Tone: ${b.tone}`, b.mission && `Mission: ${b.mission}`].filter(Boolean).join('\n');
133
+ }
134
+ async function suggest(kind, btn) {
135
+ if (!plan.brand.name || !plan.brand.offer) { $('bSaved').textContent = 'Fill in the brand name and what you offer first.'; return null; }
136
+ const label = btn.textContent; btn.disabled = true; btn.textContent = 'Thinking…';
137
+ try { return await window.ora.improvePrompt(brandFacts(), kind); }
138
+ catch (e) {
139
+ const m = cleanErr(e);
140
+ $('bSaved').textContent = /offline/.test(m) ? 'Connect Cloudflare (free, in Online) for suggestions, or write your own.' : /declined/.test(m) ? 'The online helper declined; write your own.' : m;
141
+ return null;
142
+ } finally { btn.disabled = false; btn.textContent = label; }
143
+ }
144
+ $('bMissionAi').addEventListener('click', async e => { const t = await suggest('mission', e.currentTarget); if (t) { plan.brand.mission = t.split('\n')[0]; $('bMission').value = plan.brand.mission; savePlan(); } });
145
+ $('bTaglineAi').addEventListener('click', async e => {
146
+ const t = await suggest('tagline', e.currentTarget); if (!t) return;
147
+ const picks = $('bTagPicks'); picks.innerHTML = '';
148
+ for (const line of t.split('\n')) {
149
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = line;
150
+ b.addEventListener('click', () => { plan.brand.tagline = line; $('bTagline').value = line; picks.innerHTML = ''; savePlan(); });
151
+ picks.appendChild(b);
152
+ }
153
+ });
154
+
155
+ // --- Personas ------------------------------------------------------------------------------------------------------
156
+
157
+ const PERSONA_FIELDS = [['name', 'Name', 'Léa'], ['age', 'Age', '29'], ['job', 'Job or situation', 'Office worker in Kirchberg'], ['needs', 'Needs and goals', 'A quick, healthy lunch she can grab on the way'],
158
+ ['pains', 'Frustrations', 'Sandwiches all week; no time to cook'], ['motivations', 'What makes her choose a brand', 'Fresh, local, looks good on Instagram'], ['quote', 'In her words', '"I want healthy to be the easy choice."']];
159
+ function renderPersonas() {
160
+ const g = $('personaGrid');
161
+ g.innerHTML = '';
162
+ if (!plan.personas.length) { plan.personas.push(newPersona()); plan.personas[0].main = true; }
163
+ plan.personas.forEach((p, i) => {
164
+ const c = document.createElement('div');
165
+ c.className = 'panel persona';
166
+ c.innerHTML = `<div class="persona-top"><div class="persona-pic"></div><label class="field"><span class="label">Name</span><input data-k="name" maxlength="40"></label></div>
167
+ <div class="persona-row"><label class="field"><span class="label">Age</span><input data-k="age" maxlength="20"></label><label class="field"><span class="label">Job or situation</span><input data-k="job" maxlength="80"></label></div>
168
+ <label class="field"><span class="label">Needs and goals</span><textarea data-k="needs" rows="2" maxlength="300"></textarea></label>
169
+ <label class="field"><span class="label">Frustrations</span><textarea data-k="pains" rows="2" maxlength="300"></textarea></label>
170
+ <label class="field"><span class="label">What makes them choose a brand</span><input data-k="motivations" maxlength="200"></label>
171
+ <div class="field"><span class="label">Where they find brands online</span><div class="chips" data-k="where"></div></div>
172
+ <label class="field"><span class="label">In their words</span><input data-k="quote" maxlength="140"></label>
173
+ <div class="persona-foot"><button class="ghost" data-a="pic" type="button">Picture…</button><button class="link" data-a="make" type="button">Make a portrait in Create</button><span class="spacer"></span><label class="check"><input type="radio" name="mainPersona"> Main</label><button class="link" data-a="del" type="button">Remove</button></div>
174
+ <div class="pic-picker" hidden></div>`;
175
+ for (const el of c.querySelectorAll('[data-k]')) {
176
+ const k = el.dataset.k;
177
+ if (k === 'where') continue;
178
+ const ph = (PERSONA_FIELDS.find(f => f[0] === k) || [])[2];
179
+ if (ph && i === 0) el.placeholder = ph;
180
+ el.value = p[k] || '';
181
+ el.addEventListener('input', () => { p[k] = el.value; savePlan(); });
182
+ }
183
+ const where = c.querySelector('[data-k=where]');
184
+ for (const w of WHERE_ONLINE) {
185
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = w; b.setAttribute('aria-pressed', String((p.where || []).includes(w)));
186
+ b.addEventListener('click', () => { const on = (p.where || []).includes(w); p.where = on ? p.where.filter(x => x !== w) : [...(p.where || []), w]; b.setAttribute('aria-pressed', String(!on)); savePlan(); });
187
+ where.appendChild(b);
188
+ }
189
+ const pic = c.querySelector('.persona-pic');
190
+ if (p.portrait) { const im = document.createElement('img'); im.src = `ora://video/${encodeURIComponent(p.portrait.id)}/${p.portrait.file}`; pic.appendChild(im); } else pic.textContent = (p.name || '?')[0].toUpperCase();
191
+ const main = c.querySelector('input[type=radio]');
192
+ main.checked = !!p.main;
193
+ main.addEventListener('change', () => { plan.personas.forEach(x => { x.main = x === p; }); savePlan(); });
194
+ c.querySelector('[data-a=del]').addEventListener('click', () => { if (!confirm(`Remove ${p.name || 'this persona'}?`)) return; plan.personas.splice(i, 1); if (plan.personas.length && !plan.personas.some(x => x.main)) plan.personas[0].main = true; renderPersonas(); savePlan(); });
195
+ c.querySelector('[data-a=pic]').addEventListener('click', () => pickPortrait(p, c.querySelector('.pic-picker')));
196
+ c.querySelector('[data-a=make]').addEventListener('click', () => makePortrait(p));
197
+ g.appendChild(c);
198
+ });
199
+ $('addPersona').hidden = plan.personas.length >= 3;
200
+ }
201
+ function newPersona() { return { id: `p${Date.now()}`, name: '', age: '', job: '', needs: '', pains: '', motivations: '', where: [], quote: '', portrait: null, main: false }; }
202
+ function pickPortrait(p, box) {
203
+ box.hidden = !box.hidden;
204
+ if (box.hidden) return;
205
+ box.innerHTML = '';
206
+ const own = document.createElement('button'); own.className = 'ghost'; own.type = 'button'; own.textContent = 'Choose a photo…';
207
+ own.addEventListener('click', async () => { const r = await window.ora.pickPhoto('photo'); if (r) { p.portrait = { id: r.id, file: r.file }; renderPersonas(); savePlan(); } });
208
+ box.appendChild(own);
209
+ for (const m of S.videos.filter(v => v.kind === 'image').slice(0, 40)) {
210
+ for (const f of (m.images || []).slice(0, 4)) {
211
+ const im = document.createElement('img'); im.src = `ora://video/${encodeURIComponent(m.id)}/${f}`; im.title = m.prompt;
212
+ im.addEventListener('click', () => { p.portrait = { id: m.id, file: f }; renderPersonas(); savePlan(); });
213
+ box.appendChild(im);
214
+ }
215
+ }
216
+ }
217
+ // Fills Create with a portrait prompt; the finished image is then picked with "Picture…"
218
+ function makePortrait(p) {
219
+ const who = [p.age && `${p.age}-year-old`, p.job].filter(Boolean).join(' ') || 'young adult';
220
+ $('imgPrompt').value = `Natural portrait photo of a friendly ${who}, head and shoulders, soft daylight, realistic, candid smile, plain softly blurred background`;
221
+ imgForm.type = 'picture'; imgForm.shape = 'square'; store('ora.imgForm', imgForm);
222
+ showView('create'); setMode('image');
223
+ formNote(`Portrait prompt for ${p.name || 'your persona'} is ready: press Make image. Then in Plan › Personas, press Picture… and pick it.`);
224
+ }
225
+ $('addPersona').addEventListener('click', () => { plan.personas.push(newPersona()); renderPersonas(); savePlan(); });
226
+ for (const b of $('planTabs').children) b.addEventListener('click', () => { planTab = b.dataset.tab; renderPlan(); });
227
+
228
+ // --- Brand Identity Summary (A4 PNG) ---------------------------------------------------------------------------------
229
+
230
+ async function exportSummary() {
231
+ await loadPlan();
232
+ const b = plan.brand;
233
+ if (!b.name) { planTab = 'brand'; renderPlan(); $('bSaved').textContent = 'Write the brand name first.'; return; }
234
+ const W = 1240, H = 1754, m = 80;
235
+ const cv = document.createElement('canvas'); cv.width = W; cv.height = H;
236
+ const x = cv.getContext('2d');
237
+ const F = POSTER_FONTS[b.font] || POSTER_FONTS.modern;
238
+ const font = (s, w = 500) => `${w} ${s}px ${F.family}`;
239
+ const body = (s, w = 400) => `${w} ${s}px -apple-system, "Segoe UI", Helvetica, Arial, sans-serif`;
240
+ const c1 = b.colors[0] || '#1c1530', onC1 = luminance(c1) > 0.62 ? '#1c1530' : '#ffffff';
241
+ x.fillStyle = '#fbf8f3'; x.fillRect(0, 0, W, H);
242
+ // header band
243
+ x.fillStyle = c1; x.fillRect(0, 0, W, 380);
244
+ let logo = null;
245
+ if (b.logo) { try { logo = await loadImg(`ora://video/${encodeURIComponent(b.logo.id)}/${b.logo.file}`); } catch { } }
246
+ if (logo) { const lh = 110, lw = Math.min(260, lh * logo.width / logo.height); x.drawImage(logo, m, 70, lw, lw * logo.height / logo.width); }
247
+ x.fillStyle = onC1; x.textBaseline = 'top';
248
+ x.font = body(22, 600); x.globalAlpha = 0.75; x.fillText('BRAND IDENTITY SUMMARY', m, logo ? 200 : 80); x.globalAlpha = 1;
249
+ x.font = font(76, F.weight); x.fillText(b.name, m, logo ? 232 : 118, W - 2 * m);
250
+ if (b.tagline) { x.font = font(34, 500); x.fillText(b.tagline, m, logo ? 322 : 214, W - 2 * m); }
251
+ let y = 430;
252
+ const section = (title, text, h) => {
253
+ x.fillStyle = c1; x.font = body(20, 700); x.fillText(title.toUpperCase(), m, y); y += 34;
254
+ x.fillStyle = '#1c1530'; x.font = body(27);
255
+ for (const line of wrapLines(x, text, W - 2 * m).slice(0, h || 4)) { x.fillText(line, m, y); y += 38; }
256
+ y += 26;
257
+ };
258
+ if (b.offer) section('What we offer', b.offer, 2);
259
+ if (b.mission) section('Mission', b.mission, 4);
260
+ if (b.values) section('Values', b.values.split(',').map(v => v.trim()).filter(Boolean).join(' · '), 2);
261
+ if (b.personality.length || b.tone) section('Personality and tone', [b.personality.join(', '), b.tone].filter(Boolean).join(' — '), 3);
262
+ // colours and font
263
+ x.fillStyle = c1; x.font = body(20, 700); x.fillText('COLOURS AND TYPE', m, y); y += 40;
264
+ b.colors.forEach((hex, i) => {
265
+ const sx = m + i * 170;
266
+ x.fillStyle = hex; roundRect(x, sx, y, 140, 110, 16); x.fill(); x.strokeStyle = 'rgba(0,0,0,.08)'; x.stroke();
267
+ x.fillStyle = '#1c1530'; x.font = body(19, 600); x.fillText(hex.toUpperCase(), sx, y + 122); x.font = body(18); x.fillStyle = '#6b6478'; x.fillText(hexName(hex), sx, y + 148);
268
+ });
269
+ x.fillStyle = '#1c1530'; x.font = font(46, F.weight); x.fillText('Aa', m + 4 * 170 + 20, y + 10);
270
+ x.font = body(18); x.fillStyle = '#6b6478'; x.fillText({ modern: 'Modern', serif: 'Elegant', display: 'Bold' }[b.font] || 'Modern', m + 4 * 170 + 22, y + 72);
271
+ y += 210;
272
+ if (b.avoid) section('We avoid', b.avoid, 2);
273
+ // personas
274
+ const ps = plan.personas.filter(p => p.name).slice(0, 3);
275
+ if (ps.length) {
276
+ x.fillStyle = c1; x.font = body(20, 700); x.fillText('WHO WE TALK TO', m, y); y += 40;
277
+ const cw = (W - 2 * m - (ps.length - 1) * 24) / ps.length, ch = Math.min(420, H - y - 110);
278
+ for (const [i, p] of ps.entries()) {
279
+ const cx = m + i * (cw + 24);
280
+ x.fillStyle = '#ffffff'; roundRect(x, cx, y, cw, ch, 20); x.fill(); x.strokeStyle = 'rgba(28,21,48,.1)'; x.stroke();
281
+ let im = null;
282
+ if (p.portrait) { try { im = await loadImg(`ora://video/${encodeURIComponent(p.portrait.id)}/${p.portrait.file}`); } catch { } }
283
+ x.save(); x.beginPath(); x.arc(cx + 70, y + 70, 46, 0, Math.PI * 2); x.closePath(); x.clip();
284
+ if (im) { const s = Math.max(92 / im.width, 92 / im.height); x.drawImage(im, cx + 70 - im.width * s / 2, y + 70 - im.height * s / 2, im.width * s, im.height * s); } else { x.fillStyle = '#eee6dc'; x.fillRect(cx + 24, y + 24, 92, 92); }
285
+ x.restore();
286
+ x.fillStyle = '#1c1530'; x.font = body(26, 700); x.fillText(p.name, cx + 130, y + 40, cw - 150);
287
+ x.font = body(18); x.fillStyle = '#6b6478'; x.fillText([p.age, p.job].filter(Boolean).join(' · '), cx + 130, y + 76, cw - 150);
288
+ let py = y + 140;
289
+ for (const [k, label] of [['needs', 'Needs'], ['pains', 'Frustrations'], ['motivations', 'Chooses a brand for']]) {
290
+ if (!p[k]) continue;
291
+ x.fillStyle = c1; x.font = body(15, 700); x.fillText(label.toUpperCase(), cx + 24, py); py += 22;
292
+ x.fillStyle = '#1c1530'; x.font = body(18);
293
+ for (const line of wrapLines(x, p[k], cw - 48).slice(0, 3)) { if (py > y + ch - 60) break; x.fillText(line, cx + 24, py); py += 25; }
294
+ py += 10;
295
+ }
296
+ if (p.where && p.where.length && py < y + ch - 30) { x.fillStyle = '#6b6478'; x.font = body(16); x.fillText(p.where.join(' · '), cx + 24, y + ch - 40, cw - 48); }
297
+ }
298
+ }
299
+ x.fillStyle = '#9a93a6'; x.font = body(16); x.fillText(`Made with Ora · ${new Date().toLocaleDateString()}`, m, H - 50);
300
+ const blob = await new Promise(r => cv.toBlob(r, 'image/png'));
301
+ const target = await window.ora.planExport(`${b.name} - Brand Identity Summary`, new Uint8Array(await blob.arrayBuffer()), 'png');
302
+ // the same page as an A4 PDF, for printing and handing in
303
+ const html = `<!doctype html><html><head><meta charset="utf-8"><style>@page{size:A4;margin:0}html,body{margin:0}img{width:210mm;height:297mm;display:block}</style></head><body><img src="${cv.toDataURL('image/png')}"></body></html>`;
304
+ const pdf = await window.ora.planPdf(`${b.name} - Brand Identity Summary`, html, 'a4');
305
+ $('bSaved').textContent = `Saved in Documents/Ora: ${target.split(/[\\/]/).pop()} and ${pdf.split(/[\\/]/).pop()}`;
306
+ return target;
307
+ }
308
+ $('bExport').addEventListener('click', () => exportSummary().catch(e => { $('bSaved').textContent = cleanErr(e); }));
309
+ $('pExport').addEventListener('click', async e => {
310
+ const b = e.currentTarget, label = b.textContent;
311
+ try { await exportSummary(); b.textContent = 'Saved ✓ (Documents/Ora)'; } catch (err) { b.textContent = cleanErr(err); }
312
+ setTimeout(() => { b.textContent = label; }, 4000);
313
+ });
314
+ loadPlan().then(applyBrand);
315
+
316
+ // --- classroom pack: example businesses, and the plan as a file -----------------------------------------------------
317
+
318
+ const STARTERS = [
319
+ { label: 'Café', brand: { name: 'Bean & Bloom', offer: 'Specialty coffee and homemade cakes in Esch-sur-Alzette', mission: 'A warm corner where neighbours meet over great coffee and cakes baked every morning.', values: 'local, homemade, welcoming, fair trade', personality: ['Warm', 'Friendly', 'Natural'], tone: 'warm and chatty, like a friendly barista', tagline: 'Your daily cup of calm.', avoid: 'paper cups piled up', colors: ['#7b4a2a', '#f5efe0', '#d4a72c'], font: 'serif' },
320
+ personas: [{ name: 'Sofia', age: '34', job: 'Remote designer', needs: 'A calm place to work for a few hours with good wifi', pains: 'Noisy chains and rushed service', motivations: 'Atmosphere, good coffee, friendly staff', where: ['Instagram', 'Google'] }, { name: 'Jean', age: '67', job: 'Retired teacher', needs: 'Somewhere to meet friends in the afternoon', pains: 'Modern places feel cold', motivations: 'Homemade cakes and a personal welcome', where: ['Facebook', 'Google'] }],
321
+ campaign: { name: 'Autumn Cake Week', goal: 'visits', message: 'A new homemade cake every day this week.', value: 'Baked in our kitchen every morning', offer: 'Free cake with your second coffee', cta: 'Visit us today', channels: ['Instagram', 'Facebook', 'Google Business'] } },
322
+ { label: 'Fitness trainer', brand: { name: 'MoveWithMia', offer: 'Personal training and small group classes in Luxembourg City', mission: 'Help busy people feel strong and confident with short, effective workouts.', values: 'energy, consistency, no judgement', personality: ['Energetic', 'Friendly', 'Expert'], tone: 'motivating, direct and positive', tagline: 'Thirty minutes. Stronger every week.', avoid: 'extreme diets, before-and-after photos', colors: ['#e34948', '#1a2a5a', '#f5efe0'], font: 'display' },
323
+ personas: [{ name: 'Tom', age: '38', job: 'Bank employee, father of two', needs: 'Get fit with little time', pains: 'Gyms feel intimidating; no time', motivations: 'Clear plan, quick results, flexible times', where: ['Instagram', 'LinkedIn'] }, { name: 'Ana', age: '27', job: 'Nurse working shifts', needs: 'Workouts that fit irregular hours', pains: 'Classes always at the wrong time', motivations: 'Community and encouragement', where: ['Instagram', 'TikTok'] }],
324
+ campaign: { name: '30-Day Kickstart', goal: 'leads', message: 'Thirty days, three short sessions a week, real results.', value: 'Coaching that fits your calendar', offer: 'First session free', cta: 'Book your free session', channels: ['Instagram', 'Facebook', 'Website'] } },
325
+ { label: 'Clothing brand', brand: { name: 'Lumo Wear', offer: 'Sustainable everyday clothing made in Europe', mission: 'Make simple, durable clothes people love wearing for years.', values: 'sustainable, timeless, transparent', personality: ['Modern', 'Calm', 'Trustworthy'], tone: 'calm, clear and honest', tagline: 'Made to stay.', avoid: 'fast-fashion hauls', colors: ['#36454f', '#d9c7a6', '#ffffff'], font: 'modern' },
326
+ personas: [{ name: 'Clara', age: '31', job: 'Architect', needs: 'A small wardrobe that works for office and weekend', pains: 'Clothes that fall apart after a season', motivations: 'Quality, origin, simple design', where: ['Instagram', 'Email'] }, { name: 'Max', age: '24', job: 'Student', needs: 'Affordable basics that last', pains: 'Not sure what is really sustainable', motivations: 'Honest information and fair prices', where: ['TikTok', 'Instagram'] }],
327
+ campaign: { name: 'The Lasting Basics', goal: 'sales', message: 'Five basics you will wear for years.', value: 'Made in Europe from organic cotton', offer: '15% off the basics set', cta: 'Shop the set', channels: ['Instagram', 'Website', 'Email'] } },
328
+ { label: 'Startup', brand: { name: 'Taskly', offer: 'A simple planning app for small teams', mission: 'Help small teams plan their week in ten minutes and get back to real work.', values: 'simple, fast, helpful', personality: ['Modern', 'Friendly', 'Expert'], tone: 'clear, friendly and practical; no buzzwords', tagline: 'Plan less. Do more.', avoid: 'stock photos of handshakes', colors: ['#6250d6', '#1baf7a', '#f5efe0'], font: 'display' },
329
+ personas: [{ name: 'Nadia', age: '36', job: 'Runs a 6-person agency', needs: 'See who is doing what this week', pains: 'Too many tools, meetings to plan meetings', motivations: 'Time saved, easy to learn', where: ['LinkedIn', 'Email'] }, { name: 'Luca', age: '29', job: 'Freelance developer', needs: 'Keep client work on track', pains: 'Forgets small tasks', motivations: 'Free plan, works on phone', where: ['LinkedIn', 'YouTube'] }],
330
+ campaign: { name: 'Ten-Minute Monday', goal: 'leads', message: 'Plan your team\'s week in ten minutes, every Monday.', value: 'Set up in 5 minutes, free for small teams', offer: 'Free for teams up to 5', cta: 'Try it free', channels: ['LinkedIn', 'Website', 'Email'] } },
331
+ { label: 'Personal brand', brand: { name: 'Sara Haddad', offer: 'Career coaching for young professionals in Luxembourg', mission: 'Help young professionals find work they enjoy and grow with confidence.', values: 'honest, practical, encouraging', personality: ['Warm', 'Expert', 'Trustworthy'], tone: 'personal, encouraging and practical', tagline: 'Your next step, with confidence.', avoid: 'empty motivational quotes', colors: ['#1e5bd8', '#f6d1d1', '#ffffff'], font: 'serif' },
332
+ personas: [{ name: 'Yanis', age: '26', job: 'Junior analyst, two years in', needs: 'Decide whether to change job or ask for a promotion', pains: 'Feels stuck, unsure how to negotiate', motivations: 'Concrete advice from someone who has done it', where: ['LinkedIn', 'Instagram'] }, { name: 'Emma', age: '23', job: 'New graduate', needs: 'Land a first job in Luxembourg', pains: 'Applications without answers', motivations: 'CV and interview tips that work', where: ['LinkedIn', 'TikTok'] }],
333
+ campaign: { name: 'Career Clarity Month', goal: 'engagement', message: 'One practical career tip every week this month.', value: 'Real advice from ten years in hiring', offer: 'Free 20-minute CV check', cta: 'Book your CV check', channels: ['LinkedIn', 'Instagram'] } },
334
+ ];
335
+ function useStarter(st) {
336
+ if ((plan.brand && plan.brand.name) && !confirm(`Replace your plan with the example "${st.brand.name}"? Save yours to a file first if you want to keep it.`)) return;
337
+ plan = { brand: { ...plan.brand, ...st.brand, logo: null, use: true }, personas: st.personas.map((p, i) => ({ ...newPersona(), id: `p${Date.now()}${i}`, ...p, main: i === 0 })),
338
+ campaign: { start: '', end: '', funnel: {}, metrics: [{ id: 'reach', target: '2000' }, { id: 'er', target: '4' }, { id: 'followers', target: '50' }], ...st.campaign } };
339
+ savePlan(); renderPlan();
340
+ $('planFileNote').textContent = `Example loaded: ${st.brand.name}. Next: 3 · Campaign, then 4 · Calendar › ✨ Suggest ideas › Fill the month.`;
341
+ }
342
+ function renderStarters() {
343
+ const box = $('starterList');
344
+ if (box.childElementCount) return;
345
+ for (const st of STARTERS) { const b = document.createElement('button'); b.type = 'button'; b.textContent = `${st.label} · ${st.brand.name}`; b.addEventListener('click', () => useStarter(st)); box.appendChild(b); }
346
+ }
347
+ $('planSaveFile').addEventListener('click', async () => {
348
+ try {
349
+ const f = await window.ora.planExport(`${plan.brand.name || 'My'} plan`, new TextEncoder().encode(JSON.stringify({ app: 'Ora', kind: 'plan', version: 1, plan }, null, 2)), 'json');
350
+ $('planFileNote').textContent = `Saved ${f.split(/[\\/]/).pop()} in Documents/Ora.`;
351
+ } catch (e) { $('planFileNote').textContent = cleanErr(e); }
352
+ });
353
+ $('planOpenFile').addEventListener('click', () => $('planFile').click());
354
+ $('planFile').addEventListener('change', async e => {
355
+ const file = e.target.files[0]; e.target.value = '';
356
+ if (!file) return;
357
+ try {
358
+ const data = JSON.parse(await file.text());
359
+ const p = data && data.kind === 'plan' ? data.plan : data;
360
+ if (!p || typeof p !== 'object' || !p.brand) throw new Error('This is not an Ora plan file.');
361
+ if (plan.brand && plan.brand.name && !confirm(`Replace your plan with "${p.brand.name || 'this plan'}"?`)) return;
362
+ // pictures (logo, portraits) point to this computer's library; drop the ones that are not here
363
+ const here = id => S.videos.some(v => v.id === id) || /^upload-/.test(id);
364
+ if (p.brand.logo && !here(p.brand.logo.id)) p.brand.logo = null;
365
+ for (const x of p.personas || []) if (x.portrait && !here(x.portrait.id)) x.portrait = null;
366
+ plan = { brand: {}, personas: [], ...p };
367
+ planLoaded = false; await window.ora.planSet(plan); await loadPlan(); savePlan(); renderPlan();
368
+ $('planFileNote').textContent = `Opened the plan for ${plan.brand.name || 'your brand'}.`;
369
+ } catch (err) { $('planFileNote').textContent = cleanErr(err); }
370
+ });
app/renderer/post.js ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ /* global $, S, current, brand, store, cleanErr, brandVoice, mainPersona, plan, personaDesc */
3
+ // Post…: a caption for each platform (Cloudflare's text model, or Ora's own offline writer), a time, then the post
4
+ // goes to the "Ready to post" folder and, when a webhook is set, to n8n (app/n8n/ora-social-posting.json).
5
+
6
+ const PLATFORMS = [['instagram', 'Instagram'], ['facebook', 'Facebook'], ['linkedin', 'LinkedIn']];
7
+ const TAG_COUNT = { instagram: 10, facebook: 3, linkedin: 4 };
8
+ 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 video frame scene shows show using use new one two three'.split(' '));
9
+ let postItem = null; // { files, title, ctx, kind }
10
+
11
+ // --- what is being posted ------------------------------------------------------------------------------------------------
12
+
13
+ // The text Ora knows about an item: its prompt (without the style words Ora added), the poster or ad text, the brand
14
+ function itemContext(meta, extra = {}) {
15
+ // the person's own words: the prompt up to the style phrases Ora appends, and the project's name
16
+ const firstPart = String(meta.prompt || '').split(/,\s*(cinematic film|premium product|professional studio|warm golden|slow motion|aerial drone|macro close|handheld camera|with a clean, empty|no text, no letters)/i)[0];
17
+ const p = meta.poster || {};
18
+ return {
19
+ 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 || '',
20
+ // Plan › Brand and the main persona, when set, give the captions their voice and audience
21
+ site: extra.site || '', brand: (brandVoice() || {}).brand || (brand.on ? brand.name : ''), tone: (brandVoice() || {}).tone || (brand.on ? brand.words : ''), audience: extra.audience || mainPersona(),
22
+ };
23
+ }
24
+ function filesOf(meta) {
25
+ if ((meta.kind || 'video') === 'video') return meta.savedTo ? [meta.savedTo] : [];
26
+ if (meta.poster && meta.posterFiles && meta.posterFiles.length) return meta.posterFiles.filter(Boolean);
27
+ return (meta.images || []).map((_, i) => (meta.hdFiles || [])[i] || (meta.savedFiles || [])[i]).filter(Boolean);
28
+ }
29
+ function openPost(item) {
30
+ postItem = item;
31
+ $('postError').hidden = true; $('postStatus').textContent = ''; $('postWriteNote').textContent = '';
32
+ const n = item.files.length;
33
+ $('postWhat').textContent = `${item.title || 'This post'} · ${n} file${n > 1 ? 's' : ''}${item.kind === 'carousel' ? ' (carousel)' : ''}`;
34
+ const chosen = store('ora.postPlatforms') || ['instagram', 'linkedin'];
35
+ $('postPlatforms').innerHTML = '';
36
+ for (const [id, label] of PLATFORMS) {
37
+ const l = document.createElement('label');
38
+ l.innerHTML = '<input type="checkbox"><span></span>';
39
+ l.querySelector('span').textContent = label;
40
+ const cb = l.querySelector('input'); cb.value = id; cb.checked = chosen.includes(id);
41
+ cb.addEventListener('change', () => { store('ora.postPlatforms', selectedPlatforms()); renderCaps(); });
42
+ $('postPlatforms').appendChild(l);
43
+ }
44
+ item.captions = item.captions || {};
45
+ // For: which persona the captions speak to (the main one unless chosen)
46
+ const ps = (plan.personas || []).filter(p => p.name);
47
+ const sel = $('postFor');
48
+ sel.innerHTML = '<option value="">Everyone</option>' + ps.map(() => '<option></option>').join('');
49
+ ps.forEach((p, i) => { sel.options[i + 1].value = p.id; sel.options[i + 1].textContent = `${p.name}${p.job ? ` · ${p.job}` : ''}`; });
50
+ sel.value = ps.some(p => p.id === store('ora.postFor')) ? store('ora.postFor') : (ps.find(p => p.main) || { id: '' }).id;
51
+ $('postForRow').hidden = !ps.length;
52
+ item.ctx.audience = personaDesc(ps.find(p => p.id === sel.value));
53
+ renderCaps();
54
+ // default time: the calendar day when it comes from there, otherwise tomorrow 09:00 local
55
+ const t = item.when ? new Date(item.when) : new Date(); if (!item.when) { t.setDate(t.getDate() + 1); t.setHours(9, 0, 0, 0); }
56
+ document.querySelector(`input[name=postWhen][value=${item.when && t > new Date() ? 'at' : 'now'}]`).checked = true;
57
+ $('postAt').value = new Date(t.getTime() - t.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
58
+ const hasN8n = !!(S.settings && S.settings.n8nWebhook);
59
+ $('postSend').hidden = !hasN8n;
60
+ $('postSave').className = hasN8n ? 'ghost' : 'primary';
61
+ $('postDlg').showModal();
62
+ if (!PLATFORMS.some(([id]) => item.captions[id])) writeAll();
63
+ }
64
+ const selectedPlatforms = () => [...$('postPlatforms').querySelectorAll('input:checked')].map(i => i.value);
65
+
66
+ function renderCaps() {
67
+ const box = $('postCaps');
68
+ box.innerHTML = '';
69
+ for (const id of selectedPlatforms()) {
70
+ const label = PLATFORMS.find(p => p[0] === id)[1];
71
+ const d = document.createElement('div');
72
+ d.className = 'post-cap';
73
+ d.innerHTML = '<div class="post-cap-head"><span></span><span class="muted small n"></span><span class="spacer"></span><button class="link" type="button" data-a="write">✨ Rewrite</button><button class="link" type="button" data-a="copy">Copy</button></div><textarea maxlength="3000"></textarea>';
74
+ d.querySelector('span').textContent = label;
75
+ const ta = d.querySelector('textarea');
76
+ ta.value = postItem.captions[id] || '';
77
+ const count = () => { d.querySelector('.n').textContent = `${ta.value.length} characters`; };
78
+ count();
79
+ ta.addEventListener('input', () => { postItem.captions[id] = ta.value; count(); });
80
+ d.querySelector('[data-a=write]').addEventListener('click', async e => { await writeOne(id, e.target); ta.value = postItem.captions[id]; count(); });
81
+ d.querySelector('[data-a=copy]').addEventListener('click', async e => { await navigator.clipboard.writeText(ta.value); e.target.textContent = 'Copied'; setTimeout(() => { e.target.textContent = 'Copy'; }, 1500); });
82
+ box.appendChild(d);
83
+ }
84
+ }
85
+
86
+ // --- captions --------------------------------------------------------------------------------------------------------------
87
+
88
+ function hashtags(ctx, n) {
89
+ const words = `${ctx.brand} ${ctx.title} ${ctx.about} ${ctx.offer}`.toLowerCase().replace(/[^a-z0-9à-ÿ\s-]/g, ' ').split(/\s+/);
90
+ const seen = new Set(), out = [];
91
+ if (ctx.brand) { const b = ctx.brand.replace(/[^A-Za-z0-9]/g, ''); if (b) { out.push(`#${b}`); seen.add(b.toLowerCase()); } }
92
+ // the headline as one tag when it is short (#FreshOrangeJuice)
93
+ const t = String(ctx.title || '').split(/\s+/).filter(Boolean);
94
+ if (t.length >= 2 && t.length <= 3) { const tag = t.map(w => w.replace(/[^A-Za-z0-9]/g, '')).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(''); if (tag.length > 5) { out.push(`#${tag}`); seen.add(tag.toLowerCase()); } }
95
+ for (const w of words) {
96
+ const k = w.replace(/-/g, '');
97
+ if (k.length < 4 || STOP.has(k) || seen.has(k) || /^\d+$/.test(k)) continue;
98
+ seen.add(k); out.push(`#${k.charAt(0).toUpperCase()}${k.slice(1)}`);
99
+ if (out.length >= n) break;
100
+ }
101
+ return out.join(' ');
102
+ }
103
+ // Ora's own caption, used offline or when the online writer declines: built only from the facts it has
104
+ function offlineCaption(ctx, platform) {
105
+ const sentence = t => { t = String(t || '').trim(); if (!t) return ''; t = t.charAt(0).toUpperCase() + t.slice(1); return /[.!?]$/.test(t) ? t : `${t}.`; };
106
+ const hook = sentence(ctx.title) || sentence(ctx.about.split(/[.;]/)[0]);
107
+ // the description adds to the headline only when it says more than it
108
+ const desc = ctx.about.split(/[.;]/)[0].trim();
109
+ const more = ctx.title && desc && !desc.toLowerCase().startsWith(ctx.title.toLowerCase().replace(/[.!?]$/, '')) ? sentence(desc.slice(0, 180)) : '';
110
+ const body = [ctx.offer && sentence(ctx.offer), more].filter(Boolean).join(' ');
111
+ const cta = ctx.cta ? `${ctx.cta.replace(/[.!]$/, '')}${ctx.site ? `: ${ctx.site}` : ''}` : ctx.site ? `More at ${ctx.site}` : '';
112
+ const tags = hashtags(ctx, TAG_COUNT[platform]);
113
+ if (platform === 'instagram') return [`${hook} ✨`, body, cta && `👉 ${cta}`, tags].filter(Boolean).join('\n\n');
114
+ if (platform === 'facebook') return [hook, [body, cta && `${cta}.`].filter(Boolean).join(' '), tags].filter(Boolean).join('\n\n');
115
+ return [hook, body, cta && `${cta}.`, tags].filter(Boolean).join('\n\n');
116
+ }
117
+ async function captionFor(platform) {
118
+ try { return { text: await window.ora.writeCaption(postItem.ctx, platform), online: true }; }
119
+ catch (e) { return { text: offlineCaption(postItem.ctx, platform), online: false, why: cleanErr(e) }; }
120
+ }
121
+ async function writeOne(platform, btn) {
122
+ const label = btn.textContent; btn.textContent = 'Writing…'; btn.disabled = true;
123
+ const r = await captionFor(platform);
124
+ postItem.captions[platform] = r.text;
125
+ btn.textContent = label; btn.disabled = false;
126
+ noteFor([r]);
127
+ }
128
+ async function writeAll() {
129
+ const b = $('postWriteAll'); b.disabled = true; b.textContent = 'Writing…';
130
+ const results = [];
131
+ for (const id of selectedPlatforms()) { const r = await captionFor(id); postItem.captions[id] = r.text; results.push(r); }
132
+ b.disabled = false; b.textContent = '✨ Write captions';
133
+ renderCaps(); noteFor(results);
134
+ }
135
+ function noteFor(results) {
136
+ const off = results.filter(r => !r.online);
137
+ $('postWriteNote').textContent = !off.length ? 'Written with Cloudflare\'s text model. Check the facts before posting.'
138
+ : off.some(r => /declined/.test(r.why)) ? 'The online writer declined this one, so Ora wrote a simple caption from your text.'
139
+ : 'Written by Ora offline from your text. Connect Cloudflare (free, in Online) for richer captions.';
140
+ }
141
+
142
+ // --- save / send -------------------------------------------------------------------------------------------------------
143
+
144
+ async function savePost(send) {
145
+ $('postError').hidden = true;
146
+ const platforms = selectedPlatforms();
147
+ if (!platforms.length) return postError('Pick at least one platform.');
148
+ if (platforms.some(p => !(postItem.captions[p] || '').trim())) return postError('Write a caption for every platform you picked (or untick it).');
149
+ const at = document.querySelector('input[name=postWhen]:checked').value === 'at' ? $('postAt').value : '';
150
+ if (at && new Date(at).getTime() < Date.now() - 60000) return postError('That time has passed. Pick a time later than now.');
151
+ $('postSave').disabled = $('postSend').disabled = true;
152
+ $('postStatus').textContent = send ? 'Sending to n8n…' : 'Saving…';
153
+ try {
154
+ const r = await window.ora.savePost({ title: postItem.title, files: postItem.files, platforms, captions: postItem.captions, when: at ? new Date(at).toISOString() : '', send });
155
+ $('postStatus').innerHTML = '';
156
+ const msg = document.createElement('span');
157
+ msg.textContent = send && r.sent ? `Sent to n8n${at ? `: it will post on ${new Date(at).toLocaleString()}` : ''}. A copy is in Ready to post. `
158
+ : send ? `Saved in Ready to post, but not sent: ${r.sendError}. ` : 'Saved in Ready to post. ';
159
+ const b = document.createElement('button'); b.className = 'link'; b.type = 'button'; b.textContent = 'Show folder';
160
+ b.addEventListener('click', () => window.ora.reveal(r.dir));
161
+ $('postStatus').append(msg, b);
162
+ if (send && !r.sent) postError(`n8n: ${r.sendError}`);
163
+ if (postItem.onSaved) postItem.onSaved({ sent: !!r.sent, dir: r.dir, captions: { ...postItem.captions }, platforms });
164
+ } catch (e) { postError(cleanErr(e)); $('postStatus').textContent = ''; }
165
+ finally { $('postSave').disabled = $('postSend').disabled = false; }
166
+ }
167
+ function postError(m) { $('postError').hidden = !m; $('postError').textContent = m || ''; }
168
+
169
+ // --- n8n card on the Online page ---------------------------------------------------------------------------------------
170
+
171
+ function renderN8n() {
172
+ const url = S.settings && S.settings.n8nWebhook;
173
+ $('n8nUrl').value = url || '';
174
+ $('n8nStatus').textContent = url ? 'Connected: posts go to this webhook.' : 'Not set up.';
175
+ $('n8nStatus').className = `mdl-status${url ? ' ok' : ''}`;
176
+ }
177
+ $('n8nSave').addEventListener('click', async () => {
178
+ try { S.settings = await window.ora.n8nSet($('n8nUrl').value); renderN8n(); }
179
+ catch (e) { $('n8nStatus').textContent = cleanErr(e); }
180
+ });
181
+ $('n8nTest').addEventListener('click', async () => {
182
+ $('n8nStatus').textContent = 'Testing…';
183
+ try { await window.ora.n8nTest(); $('n8nStatus').textContent = 'n8n answered: the link works.'; }
184
+ catch (e) { $('n8nStatus').textContent = cleanErr(e); }
185
+ });
186
+ $('n8nGetWf').addEventListener('click', () => window.ora.n8nWorkflow().catch(e => { $('n8nStatus').textContent = cleanErr(e); }));
187
+ $('openPosts').addEventListener('click', () => window.ora.openPosts());
188
+
189
+ // --- buttons ---------------------------------------------------------------------------------------------------------------
190
+
191
+ $('postBtn').addEventListener('click', () => {
192
+ if (!current) return;
193
+ const ad = store('ora.ad') || {};
194
+ openPost({ files: filesOf(current), title: current.project ? current.project.title : current.prompt.slice(0, 60), kind: 'video', ctx: itemContext(current, { cta: ad.cta, site: ad.site }) });
195
+ });
196
+ $('postImgBtn').addEventListener('click', () => {
197
+ if (!current) return;
198
+ const p = current.poster || {};
199
+ openPost({ files: filesOf(current), title: p.title || (current.project ? current.project.title : current.prompt.slice(0, 60)), kind: p.carousel ? 'carousel' : 'image', ctx: itemContext(current, p.carousel ? { about: (p.slides || []).join('. ') } : {}) });
200
+ });
201
+ $('postWriteAll').addEventListener('click', writeAll);
202
+ $('postFor').addEventListener('change', e => {
203
+ store('ora.postFor', e.target.value);
204
+ if (postItem) { postItem.ctx.audience = personaDesc((plan.personas || []).find(p => p.id === e.target.value)); $('postWriteNote').textContent = 'Press ✨ Write captions to write them for this person.'; }
205
+ });
206
+ $('postSave').addEventListener('click', () => savePost(false));
207
+ $('postSend').addEventListener('click', () => savePost(true));
208
+ $('postClose').addEventListener('click', () => $('postDlg').close());
209
+ $('postAt').addEventListener('focus', () => { document.querySelector('input[name=postWhen][value=at]').checked = true; });
210
+ renderN8n();
app/renderer/styles.css CHANGED
@@ -390,3 +390,113 @@ body { background-image: none; }
390
  .enh-opt input { margin-top: 3px; }
391
  .enh-bar { height: 8px; border-radius: 99px; background: var(--panel-2); overflow: hidden; margin: 8px 0 4px; }
392
  .enh-bar span { display: block; height: 100%; width: 0; background: #1c1530; transition: width .3s; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
  .enh-opt input { margin-top: 3px; }
391
  .enh-bar { height: 8px; border-radius: 99px; background: var(--panel-2); overflow: hidden; margin: 8px 0 4px; }
392
  .enh-bar span { display: block; height: 100%; width: 0; background: #1c1530; transition: width .3s; }
393
+
394
+ /* post */
395
+ .post-dlg { max-width: 640px; }
396
+ .post-platforms { display: flex; gap: 8px; flex-wrap: wrap; }
397
+ .post-platforms label { display: flex; align-items: center; gap: 6px; background: var(--panel-2); border-radius: 10px; padding: 7px 12px; font-size: 13.5px; cursor: pointer; }
398
+ .post-platforms input { width: auto; }
399
+ .post-caps { display: flex; flex-direction: column; gap: 10px; margin: 10px 0; }
400
+ .post-cap { display: flex; flex-direction: column; gap: 4px; }
401
+ .post-cap-head { display: flex; align-items: center; gap: 8px; font-size: 12.5px; font-weight: 600; }
402
+ .post-cap-head .spacer { flex: 1; }
403
+ .post-cap textarea { min-height: 96px; font-size: 13px; }
404
+ .post-dlg input[type=datetime-local] { width: auto; padding: 5px 8px; border-radius: 8px; border: 1px solid var(--line-2); }
405
+
406
+ /* plan */
407
+ .plan-tabs { flex: 0 1 auto; }
408
+ .plan-tabs button { padding: 7px 14px; }
409
+ .plan-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; align-items: start; }
410
+ .plan-card { padding: 18px; display: flex; flex-direction: column; gap: 12px; }
411
+ .plan-card h3 { margin: 0; font-size: 15px; }
412
+ .plan-actions { display: flex; align-items: center; gap: 10px; margin-top: 16px; flex-wrap: wrap; }
413
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; }
414
+ .chips button { border: 1px solid var(--line-2); background: #fff; border-radius: 999px; padding: 5px 11px; font-size: 12.5px; cursor: pointer; color: var(--text); }
415
+ .chips button[aria-pressed="true"] { background: #1c1530; color: #fff; border-color: #1c1530; }
416
+ .swatches { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
417
+ .swatches input[type=color] { width: 44px; height: 34px; padding: 2px; border-radius: 8px; border: 1px solid var(--line-2); background: #fff; }
418
+ .logo-row { display: flex; align-items: center; gap: 10px; }
419
+ .logo-row img { height: 44px; max-width: 140px; object-fit: contain; background: var(--panel-2); border-radius: 8px; padding: 4px; }
420
+ .tag-picks { display: flex; gap: 6px; flex-wrap: wrap; margin-right: auto; }
421
+ .tag-picks button { border: 1px dashed var(--line-2); background: none; border-radius: 8px; padding: 4px 8px; font-size: 12px; cursor: pointer; color: var(--text); }
422
+ .persona-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 16px; margin-top: 12px; }
423
+ .persona { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
424
+ .persona-top { display: flex; gap: 12px; align-items: center; }
425
+ .persona-pic { width: 72px; height: 72px; border-radius: 50%; object-fit: cover; background: var(--panel-2); flex: none; display: flex; align-items: center; justify-content: center; font-size: 26px; color: var(--muted); overflow: hidden; }
426
+ .persona-pic img { width: 100%; height: 100%; object-fit: cover; }
427
+ .persona-top .field { flex: 1; }
428
+ .persona-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
429
+ .persona-foot { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
430
+ .persona-foot .spacer { flex: 1; }
431
+ .pic-picker { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; max-height: 180px; overflow: auto; }
432
+ .pic-picker img { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 8px; cursor: pointer; }
433
+
434
+ .plan-tabs button { white-space: nowrap; }
435
+
436
+ /* calendar */
437
+ .cal-bar { display: flex; gap: 14px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 14px; }
438
+ .cal-bar .field { gap: 4px; }
439
+ .cal-bar input[type=date], .cal-bar input[type=time] { width: auto; padding: 6px 10px; }
440
+ .cal-layout { display: grid; grid-template-columns: minmax(280px, 360px) 1fr; gap: 16px; align-items: start; }
441
+ .idea-list { display: flex; flex-direction: column; gap: 6px; max-height: 420px; overflow: auto; }
442
+ .idea-row { display: flex; align-items: center; gap: 8px; font-size: 13px; background: var(--panel-2); border-radius: 9px; padding: 6px 8px; }
443
+ .idea-row .t { flex: 1; min-width: 0; }
444
+ .idea-row button { background: none; border: 0; color: var(--muted); cursor: pointer; }
445
+ .idea-add { display: flex; gap: 6px; }
446
+ .idea-add select { width: auto; padding: 6px; border-radius: 8px; border: 1px solid var(--line-2); background: #fff; font-size: 12.5px; }
447
+ .dot { width: 9px; height: 9px; border-radius: 50%; flex: none; display: inline-block; }
448
+ .cal-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
449
+ .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 6px; }
450
+ .cal-dow { font-size: 11px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; padding: 0 4px; }
451
+ .cal-day { min-height: 92px; border: 1px solid var(--line); border-radius: 10px; padding: 6px; display: flex; flex-direction: column; gap: 4px; cursor: pointer; background: #fff; text-align: left; font: inherit; color: inherit; }
452
+ .cal-day:hover { border-color: var(--line-2); box-shadow: 0 6px 16px -12px rgba(28,21,48,.4); }
453
+ .cal-day.out { background: transparent; border-style: dashed; cursor: default; opacity: .45; }
454
+ .cal-day .d { font-size: 11.5px; color: var(--muted); font-weight: 600; }
455
+ .cal-day .e { font-size: 11.5px; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
456
+ .cal-day .s { margin-top: auto; font-size: 10.5px; color: var(--muted); display: flex; gap: 4px; align-items: center; }
457
+ .cal-day img { width: 100%; height: 34px; object-fit: cover; border-radius: 6px; }
458
+ .cal-legend { display: flex; gap: 12px; flex-wrap: wrap; font-size: 12px; color: var(--muted); margin-top: 10px; }
459
+ .cal-legend span { display: flex; align-items: center; gap: 5px; }
460
+ .day-item { display: flex; align-items: center; gap: 10px; font-size: 13px; }
461
+ .day-item img { width: 90px; height: 60px; object-fit: cover; border-radius: 8px; }
462
+ .dlg-actions .spacer { flex: 1; }
463
+ .present-card { max-width: 720px; }
464
+ .present-list { margin: 0; padding-left: 20px; font-size: 13.5px; display: flex; flex-direction: column; gap: 4px; }
465
+ .present-list .miss { color: var(--muted); }
466
+ @media (max-width: 1000px) { .cal-layout { grid-template-columns: 1fr; } }
467
+
468
+ /* campaign */
469
+ .funnel { display: flex; flex-direction: column; gap: 10px; }
470
+ .funnel-step { border-radius: 12px; background: var(--panel-2); padding: 12px; display: flex; flex-direction: column; gap: 6px; }
471
+ .funnel-step:nth-child(1) { margin: 0; } .funnel-step:nth-child(2) { margin: 0 14px; } .funnel-step:nth-child(3) { margin: 0 28px; }
472
+ .funnel-step b { font-size: 13px; } .funnel-step textarea { min-height: 54px; font-size: 13px; background: #fff; }
473
+ .funnel-step .ad-row { justify-content: space-between; }
474
+ .metric-list { display: flex; flex-direction: column; gap: 6px; }
475
+ .metric { display: flex; align-items: center; gap: 8px; font-size: 13.5px; background: var(--panel-2); border-radius: 10px; padding: 6px 10px; }
476
+ .metric label { flex: 1; display: flex; gap: 8px; align-items: center; cursor: pointer; } .metric input[type=checkbox] { width: auto; }
477
+ .metric input[type=number] { width: 110px; padding: 4px 8px; background: #fff; }
478
+ /* results */
479
+ .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin-bottom: 16px; }
480
+ .tile { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px; }
481
+ .tile .k { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; font-weight: 700; }
482
+ .tile .v { font-size: 26px; font-weight: 700; margin-top: 4px; font-variant-numeric: tabular-nums; }
483
+ .tile .t { font-size: 12px; color: var(--muted); margin-top: 2px; }
484
+ .tile .prog { height: 6px; background: var(--panel-2); border-radius: 99px; margin-top: 8px; overflow: hidden; } .tile .prog span { display: block; height: 100%; background: #1c1530; border-radius: 99px; }
485
+ .results-grid { grid-template-columns: minmax(0, 2fr) minmax(280px, 1fr); }
486
+ .rtable-wrap { overflow: auto; max-height: 420px; }
487
+ .rtable { border-collapse: collapse; width: 100%; font-size: 12.5px; }
488
+ .rtable th { text-align: left; font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; padding: 6px 4px; position: sticky; top: 0; background: var(--panel); }
489
+ .rtable td { padding: 3px 4px; border-top: 1px solid var(--line); white-space: nowrap; }
490
+ .rtable input, .rtable select { padding: 4px 6px; font-size: 12.5px; background: #fff; border-radius: 6px; }
491
+ .rtable input[type=number] { width: 72px; text-align: right; font-variant-numeric: tabular-nums; }
492
+ .rtable .er { font-weight: 700; text-align: right; font-variant-numeric: tabular-nums; }
493
+ .rtable button { background: none; border: 0; color: var(--muted); cursor: pointer; }
494
+ .hbars { display: flex; flex-direction: column; gap: 10px; }
495
+ .hbar { display: grid; grid-template-columns: 120px 1fr 52px; align-items: center; gap: 8px; font-size: 13px; }
496
+ .hbar .track { height: 14px; }
497
+ .hbar .fill { display: block; height: 100%; border-radius: 0 4px 4px 0; min-width: 2px; }
498
+ .hbar .val { text-align: right; font-variant-numeric: tabular-nums; color: var(--text); }
499
+ @media (max-width: 1000px) { .results-grid { grid-template-columns: 1fr; } }
500
+ .rtable select { min-width: 112px; }
501
+ .rtable input[type=date] { width: 132px; }
502
+ .starter-card { margin-top: 16px; }
app/renderer/vendor/pptx.js ADDED
The diff for this file is too large to render. See raw diff
 
app/renderer/vendor/pptx.js.LEGAL.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Bundled license information:
2
+
3
+ jszip/dist/jszip.min.js:
4
+ /*!
5
+
6
+ JSZip v3.10.2 - A JavaScript class for generating and reading zip files
7
+ <http://stuartk.com/jszip>
8
+
9
+ (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
10
+ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
11
+
12
+ JSZip uses the library pako released under the MIT license :
13
+ https://github.com/nodeca/pako/blob/main/LICENSE
14
+ */
app/scripts/build-voice.cjs CHANGED
@@ -1,5 +1,5 @@
1
  // Bundles the voice-over library (kokoro-js + transformers.js) into renderer/vendor/voice.js, the upscaler into
2
- // renderer/vendor/upscale.js, and copies the
3
  // ONNX Runtime WebAssembly files it loads. Run after npm install: node scripts/build-voice.cjs
4
  const path = require('path');
5
  const fs = require('fs');
@@ -18,6 +18,11 @@ esbuild.buildSync({
18
  entryPoints: [path.join(root, 'renderer-src', 'upscale.mjs')], bundle: true, format: 'esm', platform: 'browser',
19
  target: 'chrome120', minify: true, outfile: path.join(out, 'upscale.js'), legalComments: 'linked',
20
  });
 
 
 
 
 
21
  // voices load from Ora's models folder, never from the internet
22
  let js = fs.readFileSync(path.join(out, 'voice.js'), 'utf8');
23
  if (!js.includes(HF_VOICES)) throw new Error('kokoro-js voice URL not found: check the bundle');
 
1
  // Bundles the voice-over library (kokoro-js + transformers.js) into renderer/vendor/voice.js, the upscaler into
2
+ // renderer/vendor/upscale.js, PowerPoint export into renderer/vendor/pptx.js, and copies the
3
  // ONNX Runtime WebAssembly files it loads. Run after npm install: node scripts/build-voice.cjs
4
  const path = require('path');
5
  const fs = require('fs');
 
18
  entryPoints: [path.join(root, 'renderer-src', 'upscale.mjs')], bundle: true, format: 'esm', platform: 'browser',
19
  target: 'chrome120', minify: true, outfile: path.join(out, 'upscale.js'), legalComments: 'linked',
20
  });
21
+ esbuild.buildSync({
22
+ entryPoints: [path.join(root, 'renderer-src', 'pptx.mjs')], bundle: true, format: 'esm', platform: 'browser',
23
+ target: 'chrome120', minify: true, outfile: path.join(out, 'pptx.js'), legalComments: 'linked',
24
+ external: ['node:fs', 'node:https', 'fs', 'https', 'image-size'],
25
+ });
26
  // voices load from Ora's models folder, never from the internet
27
  let js = fs.readFileSync(path.join(out, 'voice.js'), 'utf8');
28
  if (!js.includes(HF_VOICES)) throw new Error('kokoro-js voice URL not found: check the bundle');
index.html CHANGED
@@ -37,7 +37,7 @@
37
  <!-- hero -->
38
  <section class="hero">
39
  <div class="hero-copy">
40
- <a class="pill" href="#how"><span class="dot"></span>New: Enhance to HD &amp; smoother motion · ads with music &amp; voice-over · carousels · templates</a>
41
  <h1>Turn words into <span class="grad">scroll-stopping</span> videos, images and ads.</h1>
42
  <p class="sub">Make video shots, product images, posters and carousels with your exact text, then join them into a finished ad with music and voice-over for Reels, TikTok, LinkedIn and YouTube. All on your own computer: no account, no upload, no monthly fee.</p>
43
  <div class="hero-install" id="heroInstall">
@@ -319,7 +319,7 @@
319
 
320
  <footer>
321
  <span><span class="mark sm" aria-hidden="true"></span> Ora by <a href="https://huggingface.co/Devseis" rel="noopener">Devseis</a> · Apache-2.0</span>
322
- <span>Built on Wan (Alibaba), umT5 (Google), TAEHV and stable-diffusion.cpp · <a href="NOTICE">NOTICE</a> · <a href="https://huggingface.co/datasets/Devseis/ora-releases" rel="noopener">Releases</a></span>
323
  </footer>
324
  <div class="toast" id="toast" role="status" aria-live="polite"></div>
325
  <script src="site/site.js"></script>
 
37
  <!-- hero -->
38
  <section class="hero">
39
  <div class="hero-copy">
40
+ <a class="pill" href="#how"><span class="dot"></span>New in 0.3: plan your whole campaign (brand, personas, calendar, results) and post through n8n</a>
41
  <h1>Turn words into <span class="grad">scroll-stopping</span> videos, images and ads.</h1>
42
  <p class="sub">Make video shots, product images, posters and carousels with your exact text, then join them into a finished ad with music and voice-over for Reels, TikTok, LinkedIn and YouTube. All on your own computer: no account, no upload, no monthly fee.</p>
43
  <div class="hero-install" id="heroInstall">
 
319
 
320
  <footer>
321
  <span><span class="mark sm" aria-hidden="true"></span> Ora by <a href="https://huggingface.co/Devseis" rel="noopener">Devseis</a> · Apache-2.0</span>
322
+ <span>Built on open models and stable-diffusion.cpp · <a href="https://huggingface.co/spaces/Devseis/Ora/blob/main/CLASSROOM.md" rel="noopener">Teaching with Ora</a> · <a href="NOTICE">NOTICE</a> · <a href="https://huggingface.co/datasets/Devseis/ora-releases" rel="noopener">Releases</a></span>
323
  </footer>
324
  <div class="toast" id="toast" role="status" aria-live="polite"></div>
325
  <script src="site/site.js"></script>
tools/make-n8n-workflow.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Writes app/n8n/ora-social-posting.json, the n8n workflow Ora ships (tested on n8n 2.7.5).
2
+ # Platform steps are disabled: n8n 2.x will not run a workflow that has an unconfigured step.
3
+ import json, os
4
+ code = r"""// Ora sends: field "post" (JSON) + files media0, media1… One item per platform comes out.
5
+ // route: 0 LinkedIn image · 1 Facebook photo · 2 Facebook video · 3 Instagram picture · 4 post by hand (videos on LinkedIn/Instagram)
6
+ const out = [];
7
+ for (const item of $input.all()) {
8
+ const body = item.json.body || {};
9
+ if (body.test) continue; // "Test" button in Ora: nothing to post
10
+ const post = typeof body.post === 'string' ? JSON.parse(body.post) : body.post;
11
+ if (!post || !Array.isArray(post.platforms)) continue;
12
+ const first = (post.media || [])[0] || {};
13
+ const isVideo = first.kind === 'video';
14
+ for (const platform of post.platforms) {
15
+ let route = 4;
16
+ if (platform === 'linkedin' && !isVideo) route = 0;
17
+ if (platform === 'facebook') route = isVideo ? 2 : 1;
18
+ if (platform === 'instagram' && !isVideo) route = 3;
19
+ out.push({
20
+ json: { platform, route, isVideo, caption: (post.captions || {})[platform] || '', when: post.when || new Date().toISOString(),
21
+ title: post.title || '', id: post.id || '', file: first.file || '' },
22
+ binary: item.binary,
23
+ });
24
+ }
25
+ }
26
+ return out;"""
27
+ row = r"""// One row per post and platform for the content-calendar sheet.
28
+ // Make a Google Sheet whose first row is: Date | Time | Platform | Title | Caption | File
29
+ return $input.all().map(i => {
30
+ const d = new Date(i.json.when);
31
+ return { json: { Date: d.toISOString().slice(0, 10), Time: d.toISOString().slice(11, 16) + ' UTC', Platform: i.json.platform,
32
+ Title: i.json.title, Caption: i.json.caption, File: i.json.file } };
33
+ });"""
34
+ wait_ref = "$('Wait until the post time').item.json"
35
+ nodes = [
36
+ {"parameters":{"httpMethod":"POST","path":"ora-post","responseMode":"onReceived","options":{}},"name":"Ora sends a post","type":"n8n-nodes-base.webhook","typeVersion":2,"position":[0,300],"webhookId":"6f1f4c8e-0a5b-4b7e-9a0e-0a0000000001"},
37
+ {"parameters":{"jsCode":code},"name":"Read the post","type":"n8n-nodes-base.code","typeVersion":2,"position":[240,300]},
38
+ {"parameters":{"jsCode":row},"name":"Row for the sheet","type":"n8n-nodes-base.code","typeVersion":2,"position":[480,560]},
39
+ {"parameters":{"resource":"sheet","operation":"append","documentId":{"__rl":True,"value":"","mode":"url"},"sheetName":{"__rl":True,"value":"gid=0","mode":"list","cachedResultName":"Sheet1"},
40
+ "columns":{"mappingMode":"autoMapInputData","value":{},"matchingColumns":[],"schema":[]},"options":{}},
41
+ "name":"Log to Google Sheets","type":"n8n-nodes-base.googleSheets","typeVersion":4.5,"position":[720,560],"disabled":True},
42
+ {"parameters":{"resume":"specificTime","dateTime":"={{ $json.when }}"},"name":"Wait until the post time","type":"n8n-nodes-base.wait","typeVersion":1.1,"position":[480,300],"webhookId":"6f1f4c8e-0a5b-4b7e-9a0e-0a0000000002"},
43
+ {"parameters":{"mode":"expression","numberOutputs":5,"output":"={{ $json.route }}"},"name":"Which platform?","type":"n8n-nodes-base.switch","typeVersion":3.2,"position":[720,300]},
44
+ {"parameters":{"resource":"post","operation":"create","postAs":"person","person":"","text":"={{ $json.caption }}","shareMediaCategory":"IMAGE","binaryPropertyName":"media0","additionalFields":{"visibility":"PUBLIC"}},
45
+ "name":"LinkedIn: image post","type":"n8n-nodes-base.linkedIn","typeVersion":1,"position":[1000,0],"disabled":True},
46
+ {"parameters":{"hostUrl":"graph.facebook.com","httpRequestMethod":"POST","graphApiVersion":"v23.0","node":"YOUR_PAGE_ID","edge":"photos","sendBinaryData":True,"binaryPropertyName":"source:media0","options":{"queryParameters":{"parameter":[{"name":"message","value":"={{ $json.caption }}"}]}}},
47
+ "name":"Facebook Page: photo","type":"n8n-nodes-base.facebookGraphApi","typeVersion":1,"position":[1000,160],"disabled":True},
48
+ {"parameters":{"hostUrl":"graph-video.facebook.com","httpRequestMethod":"POST","graphApiVersion":"v23.0","node":"YOUR_PAGE_ID","edge":"videos","sendBinaryData":True,"binaryPropertyName":"source:media0","options":{"queryParameters":{"parameter":[{"name":"description","value":"={{ $json.caption }}"}]}}},
49
+ "name":"Facebook Page: video","type":"n8n-nodes-base.facebookGraphApi","typeVersion":1,"position":[1000,320],"disabled":True},
50
+ {"parameters":{"method":"POST","url":"https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload","sendBody":True,"contentType":"multipart-form-data",
51
+ "bodyParameters":{"parameters":[{"parameterType":"formBinaryData","name":"file","inputDataFieldName":"media0"},{"parameterType":"formData","name":"upload_preset","value":"YOUR_UNSIGNED_PRESET"}]},"options":{}},
52
+ "name":"Instagram 1: put the picture online","type":"n8n-nodes-base.httpRequest","typeVersion":4.2,"position":[1000,480],"disabled":True},
53
+ {"parameters":{"hostUrl":"graph.facebook.com","httpRequestMethod":"POST","graphApiVersion":"v23.0","node":"YOUR_INSTAGRAM_ACCOUNT_ID","edge":"media",
54
+ "options":{"queryParameters":{"parameter":[{"name":"image_url","value":"={{ $json.secure_url }}"},{"name":"caption","value":"={{ "+wait_ref+".caption }}"}]}}},
55
+ "name":"Instagram 2: create the post","type":"n8n-nodes-base.facebookGraphApi","typeVersion":1,"position":[1240,480],"disabled":True},
56
+ {"parameters":{"hostUrl":"graph.facebook.com","httpRequestMethod":"POST","graphApiVersion":"v23.0","node":"YOUR_INSTAGRAM_ACCOUNT_ID","edge":"media_publish",
57
+ "options":{"queryParameters":{"parameter":[{"name":"creation_id","value":"={{ $json.id }}"}]}}},
58
+ "name":"Instagram 3: publish","type":"n8n-nodes-base.facebookGraphApi","typeVersion":1,"position":[1480,480],"disabled":True},
59
+ {"parameters":{},"name":"Post by hand (videos on Instagram and LinkedIn)","type":"n8n-nodes-base.noOp","typeVersion":1,"position":[1000,660]},
60
+ {"parameters":{"content":"## Ora → social media\n1. **Activate** this workflow, open *Ora sends a post* and copy the **Production URL**.\n2. In Ora: **Online › n8n automation**, paste it and press **Test**.\n3. In Ora press **Post…** on a video or image, write the captions, pick the time, **Send to n8n**. n8n waits until the post time, then posts.\n\n**Switch on only what you connect** (n8n will not run a workflow with an unfinished step). Double-click a step, set it up, then right-click › **Activate** (or press D):\n- **LinkedIn: image post** – your LinkedIn credential and your name under *Person*.\n- **Facebook Page** – a Facebook Graph API credential with a **Page** token; your Page ID instead of YOUR_PAGE_ID.\n- **Instagram 1–3** – Instagram needs the picture at a public link: make a free **Cloudinary** account, create an *unsigned upload preset*, put your cloud name and preset in step 1; in steps 2–3 use the Facebook Graph credential and your **Instagram business account ID**.\n- **Log to Google Sheets** – a sheet whose first row is Date | Time | Platform | Title | Caption | File, your Google credential and the sheet's link.\n\nVideos for Instagram and LinkedIn arrive in *Post by hand*: the files and captions are in Ora's **Ready to post** folder.","height":640,"width":460},
61
+ "name":"How to use","type":"n8n-nodes-base.stickyNote","typeVersion":1,"position":[-60,-380]},
62
+ ]
63
+ c = lambda n: {"node":n,"type":"main","index":0}
64
+ connections = {
65
+ "Ora sends a post":{"main":[[c("Read the post")]]},
66
+ "Read the post":{"main":[[c("Wait until the post time"), c("Row for the sheet")]]},
67
+ "Row for the sheet":{"main":[[c("Log to Google Sheets")]]},
68
+ "Wait until the post time":{"main":[[c("Which platform?")]]},
69
+ "Which platform?":{"main":[[c("LinkedIn: image post")],[c("Facebook Page: photo")],[c("Facebook Page: video")],[c("Instagram 1: put the picture online")],[c("Post by hand (videos on Instagram and LinkedIn)")]]},
70
+ "Instagram 1: put the picture online":{"main":[[c("Instagram 2: create the post")]]},
71
+ "Instagram 2: create the post":{"main":[[c("Instagram 3: publish")]]},
72
+ }
73
+ wf = {"name":"Ora to social media","nodes":nodes,"connections":connections,"settings":{"executionOrder":"v1"},"active":False,"pinData":{},"meta":{"templateCredsSetupCompleted":False}}
74
+ out = os.path.join(os.path.dirname(__file__), '..', 'app', 'n8n', 'ora-social-posting.json')
75
+ json.dump(wf, open(out, 'w'), indent=2)
76
+ print('wrote', os.path.normpath(out), len(nodes), 'nodes')
worker/ora_worker.py CHANGED
@@ -12,7 +12,7 @@ only requests carrying that code's secret are accepted. Standard library only.
12
  import argparse, base64, hashlib, json, os, re, secrets, shutil, subprocess, sys, tarfile, threading, time, urllib.request
13
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
14
 
15
- VERSION = '0.2.1'
16
  SITE = 'https://devseis-ora.static.hf.space'
17
  RELEASES = 'https://huggingface.co/datasets/Devseis/ora-releases/resolve/main'
18
  ENGINE_FILE = 'ora-engine-linux-cuda.tar.gz'
 
12
  import argparse, base64, hashlib, json, os, re, secrets, shutil, subprocess, sys, tarfile, threading, time, urllib.request
13
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
14
 
15
+ VERSION = '0.3.0'
16
  SITE = 'https://devseis-ora.static.hf.space'
17
  RELEASES = 'https://huggingface.co/datasets/Devseis/ora-releases/resolve/main'
18
  ENGINE_FILE = 'ora-engine-linux-cuda.tar.gz'