Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-3283]): reuse the shared media search matcher and widen auto-collection coverage

[._.]/ Adam Eivya4c7fa650f2e
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 5d705cb329..86c24283c7 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -103,7 +103,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `manuscriptAnchors.js` | `locateFind` / `locateAnchors` / `buildHighlightSegments` — resolve editorial-comment `anchorQuote`s to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Mirrors the nearest-occurrence `locateFind` in `server/services/pipeline/manuscriptFix.js`. |
| `manuscriptFormat.js` | `formatManuscript(text, stageId)` / `REFLOW_STAGES` — normalize a manuscript section's text for the editor's "Format" button: undo PDF-paste artifacts (stylized drop-cap split onto its own line, hyphen-split words, trailing whitespace, runaway blank lines) for every stage, and additionally reflow soft-wrapped lines back into paragraphs for `prose` only (scripts keep their structural line breaks). Pure/DOM-free. |
| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
-| `mediaCollectionList.js` | Search / sort / hide-empty helpers for the Media Collections grid (#3283): `applyCollectionView(collections, { query, sort, hideEmpty })` filters by AND-token name/description search and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value). `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (name prefix, `Auto-created for project …` description, `uc-`/`sc-` id, universe/series link) so pre-marker records still classify; `splitCollectionName(name)` lifts the shared `Creative Director: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. Pure — no React. |
+| `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. |
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image src (`imageUrl` → served `image:<file>` bytes → null). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
diff --git a/client/src/lib/mediaCollectionList.js b/client/src/lib/mediaCollectionList.js
index 6eacdebc3b..fb298a087a 100644
--- a/client/src/lib/mediaCollectionList.js
+++ b/client/src/lib/mediaCollectionList.js
@@ -1,42 +1,57 @@
-// Search / sort / hide-empty helpers for the Media Collections grid (#3283).
+// Search / sort ordering for the Media Collections grid (#3283).
//
// The grid is dominated by collections nothing created on purpose: every
-// Creative Director project and every universe/series render bucket auto-files
-// itself as a collection, so a user with a handful of real collections scrolls
-// past dozens of empty auto-generated ones to find them. These helpers give the
-// page one definition of "auto-generated", "empty", and the display ordering
-// that keeps real collections on top.
+// Creative Director project, Writers Room render batch, and universe/series
+// render bucket auto-files itself as a collection, so a user with a handful of
+// real collections scrolls past dozens of empty auto-generated ones to find
+// them. These helpers give the page one definition of "auto-generated" and the
+// display ordering that keeps real collections on top.
//
// Pure — no React, no I/O. The page and its tests share them.
+import { tokenizeQuery, matchHaystack } from './mediaSearch.js';
+
// Shared name prefixes that auto-creators stamp onto every collection they
-// make. Rendered as a badge above the card title instead of inside it, so the
-// distinguishing tail (usually a project name + date) isn't what gets clipped.
-// Keep in sync with the server-side creators
-// (`server/services/creativeDirector/projects{DB,File}.js`).
-export const AUTO_NAME_PREFIXES = ['Creative Director: '];
+// make, paired with the badge label the card renders above the title instead
+// of inside it — otherwise every auto-generated card shows the same clipped
+// prefix and the trailing project name/date that tells them apart is what gets
+// cut. Keep in sync with the server-side creators: `universeCollectionNameFor`
+// / `seriesCollectionNameFor` in `server/services/mediaCollections.js`,
+// `server/services/creativeDirector/projects{DB,File}.js`, and
+// `server/services/writersRoom/local.js`.
+export const AUTO_NAME_PREFIXES = [
+ 'Creative Director: ',
+ 'Writers Room: ',
+ 'Universe: ',
+ 'Series: ',
+].map((prefix) => ({ prefix, badge: prefix.replace(/[:\s]+$/, '') }));
-// Description stamped by the auto-creators. A user can't produce this by
+// Descriptions stamped by the auto-creators. A user can't produce these by
// accident through the UI (the create form takes a name only).
-const AUTO_DESCRIPTION_PREFIX = 'Auto-created for project ';
+const AUTO_DESCRIPTION_PREFIXES = ['Auto-created for project ', 'Auto-generated images for '];
// Deterministic id prefixes for the universe-/series-linked render buckets the
// pipeline files into (see `mediaCollections.js` — `uc-<universeId>` /
// `sc-<seriesId>`).
const AUTO_ID_PREFIXES = ['uc-', 'sc-'];
+// One collator for every name comparison — `String.localeCompare` rebuilds
+// collation state on each call, and these run per comparison during a sort.
+// `sensitivity: 'base'` makes it case- and accent-insensitive, so the sort key
+// needs no `toLowerCase()`.
+const collator = new Intl.Collator(undefined, { sensitivity: 'base' });
+
/**
- * Split a collection name into its auto-creator prefix and the remaining
+ * Split a collection name into its auto-creator badge label and the remaining
* title. Returns `{ badge: null, title: name }` for a user-named collection.
* @param {string} name
* @returns {{ badge: string|null, title: string }}
*/
export function splitCollectionName(name) {
const str = typeof name === 'string' ? name : '';
- for (const prefix of AUTO_NAME_PREFIXES) {
+ for (const { prefix, badge } of AUTO_NAME_PREFIXES) {
if (str.startsWith(prefix) && str.length > prefix.length) {
- // Trim the trailing separator off the badge label ("Creative Director").
- return { badge: prefix.replace(/[:\s]+$/, ''), title: str.slice(prefix.length) };
+ return { badge, title: str.slice(prefix.length) };
}
}
return { badge: null, title: str };
@@ -45,8 +60,8 @@ export function splitCollectionName(name) {
/**
* True when a collection was created by an automated flow rather than by the
* user. Any one of the four independent markers is sufficient — an install can
- * hold records from before a given marker existed, so this must not require all
- * of them to agree.
+ * hold records from before a given marker existed, so this must not require
+ * all of them to agree.
* @param {object} collection
* @returns {boolean}
*/
@@ -54,7 +69,7 @@ export function isAutoCollection(collection) {
if (!collection || collection.synthetic) return false;
if (splitCollectionName(collection.name).badge) return true;
const description = typeof collection.description === 'string' ? collection.description : '';
- if (description.startsWith(AUTO_DESCRIPTION_PREFIX)) return true;
+ if (AUTO_DESCRIPTION_PREFIXES.some((p) => description.startsWith(p))) return true;
const id = typeof collection.id === 'string' ? collection.id : '';
if (AUTO_ID_PREFIXES.some((p) => id.startsWith(p))) return true;
return Boolean(collection.universeId || collection.seriesId);
@@ -79,15 +94,6 @@ export function normalizeCollectionSort(raw) {
return COLLECTION_SORTS.some((s) => s.id === raw) ? raw : DEFAULT_COLLECTION_SORT;
}
-// Ordering bucket: synthetic ("Unsorted") is pinned first, then anything with
-// items or a user-chosen name, then the auto-generated empties that motivated
-// this. Within a bucket the caller's sort applies.
-const orderBucket = (collection) => {
- if (collection?.synthetic) return 0;
- if (collectionItemCount(collection) > 0) return 1;
- return isAutoCollection(collection) ? 2 : 1;
-};
-
// Sort timestamp. `null`/absent means "never stamped" — distinct from a real
// epoch-0 date — and sorts last rather than pretending to be the oldest record.
const updatedTime = (collection) => {
@@ -96,50 +102,55 @@ const updatedTime = (collection) => {
return Number.isFinite(ms) ? ms : null;
};
-// Name sorting uses the PREFIX-STRIPPED title, so the Creative Director
-// entries interleave by their real project names instead of all clumping under
-// "C" — the same reason the prefix moves to a badge in the card.
-const sortName = (collection) => splitCollectionName(collection?.name).title.toLowerCase();
-
-const compareBy = (sort) => (a, b) => {
- if (sort === 'name') return sortName(a).localeCompare(sortName(b));
- if (sort === 'count') {
- const delta = collectionItemCount(b) - collectionItemCount(a);
- if (delta !== 0) return delta;
- return sortName(a).localeCompare(sortName(b));
- }
- const ta = updatedTime(a);
- const tb = updatedTime(b);
- if (ta === tb) return sortName(a).localeCompare(sortName(b));
- if (ta === null) return 1;
- if (tb === null) return -1;
- return tb - ta;
+// Derive every sort/search key ONCE per record. Recomputing them inside the
+// comparator would re-run the prefix split, the auto-collection markers, and
+// Date.parse on both operands of every one of the O(n log n) comparisons.
+//
+// The name key is the PREFIX-STRIPPED title, so the auto-generated entries
+// interleave by their real project names instead of all clumping under "C"/"U"
+// — the same reason the prefix moves to a badge in the card.
+const decorate = (record) => {
+ const count = collectionItemCount(record);
+ return {
+ record,
+ // Ordering bucket: synthetic ("Unsorted") is pinned first, then anything
+ // with items or a user-chosen name, then the auto-generated empties that
+ // motivated this. Within a bucket the caller's sort applies.
+ bucket: record?.synthetic ? 0 : ((count === 0 && isAutoCollection(record)) ? 2 : 1),
+ nameKey: splitCollectionName(record?.name).title,
+ time: updatedTime(record),
+ count,
+ // Same AND-token semantics as the media search, over name + description.
+ haystack: `${record?.name || ''} ${record?.description || ''}`.toLowerCase(),
+ };
};
-// AND semantics across whitespace-separated tokens, matched against the name
-// and description (substring, any order) — same shape as `mediaSearch.js`, but
-// over collection records rather than normalized media items.
-const matchesQuery = (collection, tokens) => {
- if (tokens.length === 0) return true;
- const haystack = `${collection?.name || ''} ${collection?.description || ''}`.toLowerCase();
- return tokens.every((t) => haystack.includes(t));
+const compareBy = (sort) => (a, b) => {
+ if (sort === 'name') return collator.compare(a.nameKey, b.nameKey);
+ if (sort === 'count') return (b.count - a.count) || collator.compare(a.nameKey, b.nameKey);
+ if (a.time === b.time) return collator.compare(a.nameKey, b.nameKey);
+ if (a.time === null) return 1;
+ if (b.time === null) return -1;
+ return b.time - a.time;
};
/**
- * Filter + order the collection grid.
+ * Filter + order the collection grid. "Hide empty" is deliberately NOT applied
+ * here: the page needs both the full match set and the non-empty slice to say
+ * how many rows the toggle removed, so it owns that one predicate
+ * (`collectionItemCount(c) > 0`) rather than having two definitions of empty.
* @param {object[]} collections - Enriched collections (synthetic entry included)
* @param {object} view
* @param {string} [view.query] - Free-text name/description search
* @param {string} [view.sort] - One of COLLECTION_SORTS ids
- * @param {boolean} [view.hideEmpty] - Drop item-less collections
- * @returns {object[]} A new array; the input is not mutated
+ * @returns {object[]} A new array of the input records; the input is not mutated
*/
-export function applyCollectionView(collections, { query = '', sort = DEFAULT_COLLECTION_SORT, hideEmpty = false } = {}) {
- const tokens = String(query || '').trim().toLowerCase().split(/\s+/).filter(Boolean);
- const filtered = (collections || []).filter((c) => {
- if (hideEmpty && collectionItemCount(c) === 0) return false;
- return matchesQuery(c, tokens);
- });
+export function applyCollectionView(collections, { query = '', sort = DEFAULT_COLLECTION_SORT } = {}) {
+ const tokens = tokenizeQuery(query);
const comparator = compareBy(normalizeCollectionSort(sort));
- return filtered.sort((a, b) => (orderBucket(a) - orderBucket(b)) || comparator(a, b));
+ return (collections || [])
+ .map(decorate)
+ .filter((d) => matchHaystack(d.haystack, tokens))
+ .sort((a, b) => (a.bucket - b.bucket) || comparator(a, b))
+ .map((d) => d.record);
}
diff --git a/client/src/lib/mediaCollectionList.test.js b/client/src/lib/mediaCollectionList.test.js
index 0325a54857..c3ed2c88bb 100644
--- a/client/src/lib/mediaCollectionList.test.js
+++ b/client/src/lib/mediaCollectionList.test.js
@@ -26,6 +26,12 @@ describe('splitCollectionName', () => {
.toEqual({ badge: 'Creative Director', title: 'Nightly Surreal — 2026-08-01' });
});
+ it('covers every server-side auto-creator prefix', () => {
+ expect(splitCollectionName('Writers Room: The Deep').badge).toBe('Writers Room');
+ expect(splitCollectionName('Universe: Example Universe').badge).toBe('Universe');
+ expect(splitCollectionName('Series: Example Series').badge).toBe('Series');
+ });
+
it('leaves a user-named collection alone', () => {
expect(splitCollectionName('Concept Art')).toEqual({ badge: null, title: 'Concept Art' });
});
@@ -43,6 +49,10 @@ describe('isAutoCollection', () => {
it('recognizes each marker independently', () => {
expect(isAutoCollection({ id: 'x', name: 'Creative Director: Foo' })).toBe(true);
expect(isAutoCollection({ id: 'x', name: 'Foo', description: 'Auto-created for project x' })).toBe(true);
+ // Writers Room buckets carry a random uuid and no universe/series link, so
+ // the name + description markers are the only ones that can fire.
+ expect(isAutoCollection({ id: 'x', name: 'Writers Room: The Deep' })).toBe(true);
+ expect(isAutoCollection({ id: 'x', name: 'Foo', description: 'Auto-generated images for "The Deep"' })).toBe(true);
expect(isAutoCollection({ id: 'uc-universe-1', name: 'Foo' })).toBe(true);
expect(isAutoCollection({ id: 'sc-series-1', name: 'Foo' })).toBe(true);
expect(isAutoCollection({ id: 'x', name: 'Foo', universeId: 'u1' })).toBe(true);
@@ -79,7 +89,7 @@ describe('applyCollectionView', () => {
const all = [unsorted, userFull, userEmpty, autoFull, autoEmpty];
it('pins Unsorted first, then non-empty/user-created, then auto-generated empties', () => {
- const out = applyCollectionView(all, { hideEmpty: false });
+ const out = applyCollectionView(all);
expect(out[0].id).toBe('unsorted');
// autoEmpty is the newest by updatedAt but still sorts last — its bucket wins.
expect(out[out.length - 1].id).toBe('p2');
@@ -87,10 +97,6 @@ describe('applyCollectionView', () => {
expect(out.indexOf(userEmpty)).toBeLessThan(out.length - 1);
});
- it('drops every empty collection when hideEmpty is set', () => {
- expect(ids(applyCollectionView(all, { hideEmpty: true }))).toEqual(['unsorted', 'p1', 'u1']);
- });
-
it('does not mutate the input array', () => {
const input = [...all];
applyCollectionView(input, { sort: 'name' });
@@ -98,13 +104,13 @@ describe('applyCollectionView', () => {
});
it('searches name and description with AND-token semantics', () => {
- expect(ids(applyCollectionView(all, { query: 'nightly 08-01', hideEmpty: false }))).toEqual(['p2']);
- expect(ids(applyCollectionView(all, { query: 'project p1', hideEmpty: false }))).toEqual(['p1']);
+ expect(ids(applyCollectionView(all, { query: 'nightly 08-01' }))).toEqual(['p2']);
+ expect(ids(applyCollectionView(all, { query: 'project p1' }))).toEqual(['p1']);
expect(applyCollectionView(all, { query: 'nothing matches this' })).toEqual([]);
});
it('ignores case and surrounding whitespace in the query', () => {
- expect(ids(applyCollectionView(all, { query: ' CONCEPT ', hideEmpty: false }))).toEqual(['u1']);
+ expect(ids(applyCollectionView(all, { query: ' CONCEPT ' }))).toEqual(['u1']);
});
it('sorts by name using the prefix-stripped title so auto entries interleave', () => {
@@ -125,8 +131,8 @@ describe('applyCollectionView', () => {
});
it('falls back to the default sort for an unknown sort id', () => {
- expect(ids(applyCollectionView(all, { sort: 'bogus', hideEmpty: true })))
- .toEqual(ids(applyCollectionView(all, { sort: DEFAULT_COLLECTION_SORT, hideEmpty: true })));
+ expect(ids(applyCollectionView(all, { sort: 'bogus' })))
+ .toEqual(ids(applyCollectionView(all, { sort: DEFAULT_COLLECTION_SORT })));
});
it('handles an absent list', () => {
diff --git a/client/src/pages/MediaCollections.jsx b/client/src/pages/MediaCollections.jsx
index aa60d6f89d..40f267a6e2 100644
--- a/client/src/pages/MediaCollections.jsx
+++ b/client/src/pages/MediaCollections.jsx
@@ -147,7 +147,6 @@ export default function MediaCollections() {
// survives a back-navigation from a collection. `empty=1` OPTS IN to showing
// empty collections — the default (param absent) hides them, because an empty
// auto-created collection has nothing to open.
- const query = searchParams.get('q') || '';
const sort = normalizeCollectionSort(searchParams.get('sort'));
const hideEmpty = searchParams.get('empty') !== '1';
@@ -162,11 +161,38 @@ export default function MediaCollections() {
}, { replace });
}, [setSearchParams]);
+ // Two-stage search (same shape as Catalog): `query` is what the user is
+ // typing and drives the client-side filter instantly; `mirroredQuery` is the
+ // debounced copy written to the URL, so a shareable `?q=` doesn't cost a
+ // history write + full route re-render per keystroke.
+ const [query, setQuery] = useState(() => searchParams.get('q') || '');
+ const [mirroredQuery, setMirroredQuery] = useState(() => searchParams.get('q') || '');
+ useEffect(() => {
+ const t = setTimeout(() => {
+ const trimmed = query.trim();
+ setMirroredQuery(trimmed);
+ updateParams({ q: trimmed }, { replace: true });
+ }, 300);
+ return () => clearTimeout(t);
+ }, [query, updateParams]);
+
+ // Adopt an externally-changed `?q=` (Back/Forward, or a ⌘K/voice link while
+ // this page stays mounted). Our own debounced write lands `urlQuery ===
+ // mirroredQuery`, so this is a no-op for typing and only fires on a real
+ // external change.
+ const urlQuery = searchParams.get('q') || '';
+ useEffect(() => {
+ if (urlQuery !== mirroredQuery) {
+ setQuery(urlQuery);
+ setMirroredQuery(urlQuery);
+ }
+ }, [urlQuery, mirroredQuery]);
+
// Search + sort first, then apply "hide empty" as a slice of that result, so
// the "N empty hidden" count only ever names rows the toggle removed — not
// rows the search already dropped.
const matching = useMemo(
- () => applyCollectionView(enriched, { query, sort, hideEmpty: false }),
+ () => applyCollectionView(enriched, { query, sort }),
[enriched, query, sort],
);
const visible = useMemo(
@@ -206,7 +232,7 @@ export default function MediaCollections() {
id="collection-search"
type="search"
value={query}
- onChange={(e) => updateParams({ q: e.target.value }, { replace: true })}
+ onChange={(e) => setQuery(e.target.value)}
placeholder="Search collections…"
className="w-full pl-9 pr-3 py-2 bg-port-card border border-port-border rounded-lg text-white text-sm focus:outline-none focus:border-port-accent"
/>
@@ -239,25 +265,10 @@ export default function MediaCollections() {
<div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center">
No collections yet. Create one above, or use the folder icon on any image/video card to start a new collection.
</div>
- ) : visible.length === 0 ? (
- <div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center space-y-2">
- <div>
- {hiddenEmptyCount > 0
- ? `No collections with items match${query ? ' that search' : ''}.`
- : 'No collections match that search.'}
- </div>
- {hiddenEmptyCount > 0 && (
- <button
- type="button"
- onClick={() => updateParams({ empty: '1' })}
- className="text-port-accent hover:underline"
- >
- Show {hiddenEmptyCount} empty {hiddenEmptyCount === 1 ? 'collection' : 'collections'}
- </button>
- )}
- </div>
) : (
<div className="space-y-2">
+ {/* One notice for both the populated and the emptied-out grid, so the
+ "Show" escape hatch has a single implementation. */}
{hiddenEmptyCount > 0 && (
<div className="text-xs text-gray-500">
{hiddenEmptyCount} empty {hiddenEmptyCount === 1 ? 'collection' : 'collections'} hidden.{' '}
@@ -266,64 +277,70 @@ export default function MediaCollections() {
</button>
</div>
)}
+ {visible.length === 0 ? (
+ <div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center">
+ {query ? 'No collections match that search.' : 'No collections with items yet.'}
+ </div>
+ ) : (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
{visible.map((c) => (
<div
key={c.id}
- className={`bg-port-card border rounded-xl overflow-hidden flex flex-col ${c.synthetic ? 'border-port-accent/40' : 'border-port-border'}`}
+ className={`bg-port-card border rounded-xl overflow-hidden flex flex-col ${c.synthetic ? 'border-port-accent/40' : 'border-port-border'}`}
+ >
+ <Link
+ to={`/media/collections/${encodeURIComponent(c.id)}`}
+ className="block aspect-square bg-port-bg relative"
>
- <Link
- to={`/media/collections/${encodeURIComponent(c.id)}`}
- className="block aspect-square bg-port-bg relative"
- >
- {c.cover ? (
- // A cover can point at a pruned video thumbnail or an unpulled
- // peer asset; MediaImage degrades to the syncing tile instead
- // of the browser's broken-image icon.
- <MediaImage src={c.cover} alt={c.name} className="w-full h-full object-cover" loading="lazy" />
- ) : (
- <div className="w-full h-full flex items-center justify-center text-gray-600">
- {c.synthetic ? <Inbox className="w-12 h-12" /> : <FolderOpen className="w-12 h-12" />}
- </div>
- )}
+ {c.cover ? (
+ // A cover can point at a pruned video thumbnail or an unpulled
+ // peer asset; MediaImage degrades to the syncing tile instead
+ // of the browser's broken-image icon.
+ <MediaImage src={c.cover} alt={c.name} className="w-full h-full object-cover" loading="lazy" />
+ ) : (
+ <div className="w-full h-full flex items-center justify-center text-gray-600">
+ {c.synthetic ? <Inbox className="w-12 h-12" /> : <FolderOpen className="w-12 h-12" />}
+ </div>
+ )}
+ </Link>
+ <div className="p-2 space-y-1.5 flex-1 flex flex-col">
+ {c.badge && (
+ <span className="inline-block self-start text-[9px] uppercase tracking-wide text-gray-400 bg-port-bg border border-port-border rounded px-1.5 py-0.5">
+ {c.badge}
+ </span>
+ )}
+ <Link to={`/media/collections/${encodeURIComponent(c.id)}`} className="text-sm text-white hover:text-port-accent break-words" title={c.name}>
+ {c.displayTitle}
</Link>
- <div className="p-2 space-y-1.5 flex-1 flex flex-col">
- {c.badge && (
- <span className="inline-block self-start text-[9px] uppercase tracking-wide text-gray-400 bg-port-bg border border-port-border rounded px-1.5 py-0.5">
- {c.badge}
- </span>
+ <div className="flex items-center gap-2 text-[10px] text-gray-500">
+ {c.counts.image > 0 && <span className="flex items-center gap-1"><ImageIcon className="w-3 h-3" />{c.counts.image}</span>}
+ {c.counts.video > 0 && <span className="flex items-center gap-1"><Film className="w-3 h-3" />{c.counts.video}</span>}
+ {c.counts.image === 0 && c.counts.video === 0 && <span>Empty</span>}
+ </div>
+ <div className="flex-1" />
+ <div className="flex items-center justify-between gap-1">
+ {!c.synthetic && (
+ <SyncBadge
+ status={syncBadgeStatus(sync, c.id)}
+ onClick={() => navigate(`/media/collections/${encodeURIComponent(c.id)}/sync`)}
+ />
+ )}
+ {!c.synthetic && (
+ <button
+ type="button"
+ onClick={() => handleDelete(c)}
+ className="px-1.5 py-1 bg-port-error/20 hover:bg-port-error/40 text-port-error text-[10px] rounded flex items-center gap-1"
+ title="Delete collection"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
)}
- <Link to={`/media/collections/${encodeURIComponent(c.id)}`} className="text-sm text-white hover:text-port-accent break-words" title={c.name}>
- {c.displayTitle}
- </Link>
- <div className="flex items-center gap-2 text-[10px] text-gray-500">
- {c.counts.image > 0 && <span className="flex items-center gap-1"><ImageIcon className="w-3 h-3" />{c.counts.image}</span>}
- {c.counts.video > 0 && <span className="flex items-center gap-1"><Film className="w-3 h-3" />{c.counts.video}</span>}
- {c.counts.image === 0 && c.counts.video === 0 && <span>Empty</span>}
- </div>
- <div className="flex-1" />
- <div className="flex items-center justify-between gap-1">
- {!c.synthetic && (
- <SyncBadge
- status={syncBadgeStatus(sync, c.id)}
- onClick={() => navigate(`/media/collections/${encodeURIComponent(c.id)}/sync`)}
- />
- )}
- {!c.synthetic && (
- <button
- type="button"
- onClick={() => handleDelete(c)}
- className="px-1.5 py-1 bg-port-error/20 hover:bg-port-error/40 text-port-error text-[10px] rounded flex items-center gap-1"
- title="Delete collection"
- >
- <Trash2 className="w-3 h-3" />
- </button>
- )}
- </div>
</div>
</div>
- ))}
- </div>
+ </div>
+ ))}
+ </div>
+ )}
</div>
)}
</div>
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 8359a0e837..f4eb15fa87 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -399,19 +399,17 @@ export function nameFromImageFilename(filename, fallback = 'Untitled 3D model')
* the end collapses every row to the same visible text.
* @param {string} value - Source string (non-strings coerce; nullish → '')
* @param {number} [max=48] - Maximum length of the RESULT, ellipsis included
- * @param {string} [ellipsis='…'] - Joiner placed between head and tail
* @returns {string} `value` when it already fits, else `head…tail`
*/
-export function middleTruncate(value, max = 48, ellipsis = '…') {
+export function middleTruncate(value, max = 48) {
const str = value == null ? '' : String(value);
// A max that can't fit the ellipsis plus one char on each side has no
// meaningful middle-truncation; fall back to a plain head slice.
- if (!Number.isFinite(max) || max < ellipsis.length + 2) return str.slice(0, Math.max(0, max));
+ if (!Number.isFinite(max) || max < 3) return str.slice(0, Math.max(0, max));
if (str.length <= max) return str;
- const keep = max - ellipsis.length;
- const head = Math.ceil(keep / 2);
- const tail = keep - head;
- return `${str.slice(0, head)}${ellipsis}${tail > 0 ? str.slice(str.length - tail) : ''}`;
+ const head = Math.ceil((max - 1) / 2);
+ const tail = max - 1 - head;
+ return `${str.slice(0, head)}…${str.slice(str.length - tail)}`;
}
/**