Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

refactor(frontend): add shared Cloudinary upload and config hook

spacesdriveb6735b526b22
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index a295ea8..9b180d8 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -117,8 +117,33 @@ keys are `label`, `category`, `accountId`, `manualViews`, and `imageUrl`. `manua
clear a previously set value.
`imageUrl` must already be a hosted `https:` URL. The Worker never accepts binary uploads, so
-the browser posts the file straight to Cloudinary with the unsigned preset from
-`getCloudinaryConfig()` and sends only the returned `secure_url`.
+the browser posts the file straight to Cloudinary with `api.uploadToCloudinary()` (below) and
+sends only the returned `secure_url`.
+
+## Cloudinary Uploads
+
+```js
+uploadToCloudinary(file, cloudConfig, { onProgress, resourceType })
+```
+
+The one call in `api.js` that does not go to the Worker. It posts `file` and the unsigned
+`upload_preset` from `getCloudinaryConfig()` to
+`https://api.cloudinary.com/v1_1/<cloudName>/<resourceType>/upload` with `XMLHttpRequest`, so
+upload progress is available, and resolves with the response's `secure_url`.
+
+- `cloudConfig`: the object from `getCloudinaryConfig()` (`cloudName`, `uploadPreset`). Callers check it is set first.
+- `onProgress(percent)`: optional; called with a whole number from 0 to 100. The progress listener is only attached when this is passed.
+- `resourceType`: optional; defaults to `video` for `video/*` files and `image` otherwise.
+
+Failures reject with an `Error` that carries a `reason` so each page keeps its own wording:
+
+| `reason` | When | Default `message` | Extra fields |
+|---|---|---|---|
+| `network` | The request lost its connection | `The upload lost its network connection` | none |
+| `rejected` | Cloudinary answered with a non-2xx status | `Upload failed` | `cloudinaryMessage` (Cloudinary's `error.message`, if any) or `parseMessage` (the body was not JSON) |
+
+The bulk upload shows the default messages. The single post flow and the Tracked Content image
+upload map the error to their own wording.
## Authentication
diff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.md
index 1725971..7691edc 100644
--- a/docs/architecture/frontend/CONTEXTS.md
+++ b/docs/architecture/frontend/CONTEXTS.md
@@ -101,6 +101,21 @@ All feature pages and layout components use `useAppContext()`:
---
+## Shared Hooks (`frontend/src/hooks/`)
+
+Hooks used by more than one feature. Hooks used by a single feature live in that feature folder instead (see `docs/guidelines/REACT.md`).
+
+| Hook | File | Purpose |
+|---|---|---|
+| `useIsMobile()` | `use-mobile.js` | True below the mobile breakpoint |
+| `useCommandPaletteShortcut(setOpen)` | `use-command-palette-shortcut.js` | Ctrl+K / Cmd+K toggle for the command palette |
+| `useSmoothTheme()` | `use-smooth-theme.js` | Theme switch as one cross-fade |
+| `useCloudinaryConfig(reloadKey)` | `use-cloudinary-config.js` | Loads `api.getCloudinaryConfig()`; returns the config or `null` |
+
+`useCloudinaryConfig` sets the config only when the response has `success: true`. A failed request keeps the previous value (initially `null`), and pages show a missing config as an alert or a disabled upload field. The request runs again whenever `reloadKey` changes: the Publish page passes `accounts`, Tracked Content passes nothing and loads once.
+
+---
+
## Context Rules
1. Never use `AuthContext` in feature pages - they should not care about auth state
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index 70264bf..60d83ae 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -80,6 +80,8 @@ frontend/src/
hooks/
use-mobile.js useIsMobile()
use-command-palette-shortcut.js Ctrl+K / Cmd+K toggle
+ use-smooth-theme.js useSmoothTheme(), theme cross-fade
+ use-cloudinary-config.js useCloudinaryConfig(reloadKey), shared by Publish and Tracked content
layout/
index.jsx AppShell: SidebarProvider + AppSidebar + TopBar + Outlet + CommandPalette
navigation.js NAV_GROUPS and route titles (single source for sidebar, top bar, palette)
@@ -115,7 +117,7 @@ frontend/src/
- Feature files: `PascalCase.jsx` (matches component name)
- Utility files: `camelCase.js`
- Context files: `PascalCaseContext.jsx`
-- Hook files: `use-kebab-case.js`
+- Hook files: `use-kebab-case.js` in `hooks/` when shared across features; `useCamelCase.js` inside the feature folder when only one feature uses it
- shadcn ui files: `kebab-case.jsx` (generated convention, do not rename)
## Adding a New Page
diff --git a/docs/guidelines/REACT.md b/docs/guidelines/REACT.md
index 6cc9e95..6a6f123 100644
--- a/docs/guidelines/REACT.md
+++ b/docs/guidelines/REACT.md
@@ -35,7 +35,12 @@ function MyComponent({ id }) {
}
```
-**Custom hooks** go in `frontend/src/hooks/`. Name them `use-kebab-case.js`. Export a single function named `useSomething`.
+**Custom hooks** live where they are used:
+
+- A hook used by one feature lives in that feature folder as `useCamelCase.js`, for example `features/analytics/videos/useChannelVideos.js` or `features/publishing/useBulkQueue.js`.
+- A hook shared across features lives in `frontend/src/hooks/` as `use-kebab-case.js`, for example `hooks/use-cloudinary-config.js`.
+
+Either way, export a single function named `useSomething`. Move a feature hook into `hooks/` (and rename it) once a second feature needs it.
## State Management
diff --git a/frontend/src/hooks/use-cloudinary-config.js b/frontend/src/hooks/use-cloudinary-config.js
new file mode 100644
index 0000000..3f10d6e
--- /dev/null
+++ b/frontend/src/hooks/use-cloudinary-config.js
@@ -0,0 +1,25 @@
+import { useEffect, useState } from 'react';
+import { api } from '../services/api';
+
+async function fetchCloudinaryConfig() {
+ try {
+ const res = await api.getCloudinaryConfig();
+ return res?.success ? res : null;
+ } catch {
+ // pages already show a missing config as an alert or a disabled upload field
+ return null;
+ }
+}
+
+// reloadKey lets a page fetch the config again when something it depends on changes
+export function useCloudinaryConfig(reloadKey) {
+ const [config, setConfig] = useState(null);
+
+ useEffect(() => {
+ fetchCloudinaryConfig().then(nextConfig => {
+ if (nextConfig) setConfig(nextConfig);
+ });
+ }, [reloadKey]);
+
+ return config;
+}
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 438b43e..54c7d5a 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -18,14 +18,58 @@ async function request(path, options = {}) {
return data;
}
+const CLOUDINARY_API = 'https://api.cloudinary.com/v1_1';
+
+const UPLOAD_ERROR_MESSAGES = {
+ network: 'The upload lost its network connection',
+ rejected: 'Upload failed',
+};
+
+// callers read the reason and details so each page keeps its own wording
+function uploadError(reason, details = {}) {
+ return Object.assign(new Error(UPLOAD_ERROR_MESSAGES[reason]), { reason, ...details });
+}
+
+function readUploadError(responseText) {
+ try {
+ return { cloudinaryMessage: JSON.parse(responseText).error?.message };
+ } catch (err) {
+ return { parseMessage: err.message };
+ }
+}
+
+// the browser posts the file straight to Cloudinary so the Worker never handles binary uploads
+function uploadToCloudinary(file, cloudConfig, { onProgress, resourceType } = {}) {
+ const formData = new FormData();
+ formData.append('file', file);
+ formData.append('upload_preset', cloudConfig.uploadPreset);
+ const type = resourceType || (file.type.startsWith('video/') ? 'video' : 'image');
+ const xhr = new XMLHttpRequest();
+ return new Promise((resolve, reject) => {
+ if (onProgress) {
+ xhr.upload.addEventListener('progress', e => {
+ if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));
+ });
+ }
+ xhr.addEventListener('load', () => {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ resolve(JSON.parse(xhr.responseText).secure_url);
+ return;
+ }
+ reject(uploadError('rejected', readUploadError(xhr.responseText)));
+ });
+ xhr.addEventListener('error', () => reject(uploadError('network')));
+ xhr.open('POST', `${CLOUDINARY_API}/${cloudConfig.cloudName}/${type}/upload`);
+ xhr.send(formData);
+ });
+}
+
export const api = {
- // Health
health: () => request('/health'),
// Server key status - all keys are env vars, this just returns configured: true/false
getKeys: () => request('/keys'),
- // Accounts
getAccounts: () => request('/accounts'),
addAccount: (input) => request('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),
deleteAccount: (id) => request(`/accounts/${id}`, { method: 'DELETE' }),
@@ -35,7 +79,6 @@ export const api = {
// Instagram OAuth - gets the auth URL to redirect the browser to
getInstagramAuthUrl: () => request('/auth/instagram/url'),
- // Instagram accounts
addInstagramAccount: (accessToken) => request('/accounts/instagram', { method: 'POST', body: JSON.stringify({ accessToken }) }),
refreshIGToken: (id) => request(`/accounts/${id}/refresh-ig-token`, { method: 'POST' }),
getIGAnalytics: (id) => request(`/accounts/${id}/ig-analytics`),
@@ -48,11 +91,10 @@ export const api = {
getAnalytics: (id) => request(`/accounts/${id}/analytics`),
getVideos: (id) => request(`/accounts/${id}/videos`),
- // Comparison
getComparison: () => request('/comparison'),
- // Cloudinary config
getCloudinaryConfig: () => request('/cloudinary-config'),
+ uploadToCloudinary,
// Instagram Publishing
getIGPublishingLimit: (id) => request(`/accounts/${id}/ig-publishing-limit`),
@@ -60,7 +102,6 @@ export const api = {
getIGContainerStatus: (containerId, accountId) => request(`/ig-container/${containerId}/status?accountId=${accountId}`),
publishIGContainer: (id, containerId) => request(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),
- // Reddit accounts
addRedditAccount: (username, cookie) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),
getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),
@@ -79,7 +120,6 @@ export const api = {
getGithubSettings: () => request('/settings/github'),
saveGithubSettings: (data) => request('/settings/github', { method: 'PUT', body: JSON.stringify(data) }),
- // Scheduled Posts
getScheduledPosts: () => request('/scheduled-posts'),
createScheduledPost: (data) => request('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),
updateScheduledPost: (id, data) => request(`/scheduled-posts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
diff --git a/frontend/src/utils/instagramContent.js b/frontend/src/utils/instagramContent.js
index a4d8ebe..010d26d 100644
--- a/frontend/src/utils/instagramContent.js
+++ b/frontend/src/utils/instagramContent.js
@@ -1,4 +1,4 @@
-import { fmtNum } from './formatters';
+import { fmtNum } from './formatters.js';
export const IG_CONTENT_TYPES = ['reel', 'post', 'video'];