89 lines
2.0 KiB
TypeScript
89 lines
2.0 KiB
TypeScript
import type { ImageSource } from "expo-image";
|
|
import type { ContentMediaItem } from "../types/media.types";
|
|
|
|
/**
|
|
* Resolve the final media URI using only primitive fields.
|
|
*
|
|
* Keeping URI resolution separate from ImageSource creation allows callers
|
|
* to memoize against stable primitive values rather than the entire media
|
|
* object returned by React Query.
|
|
*/
|
|
export function resolveMediaUri(
|
|
url?: string | null,
|
|
storageKey?: string | null,
|
|
): string | null {
|
|
const directUrl = url?.trim() ?? "";
|
|
|
|
if (directUrl) {
|
|
return directUrl;
|
|
}
|
|
|
|
const mediaBaseUrl = (process.env.EXPO_PUBLIC_MEDIA_BASE_URL ?? "")
|
|
.trim()
|
|
.replace(/\/+$/, "");
|
|
|
|
const normalizedStorageKey = (storageKey ?? "")
|
|
.trim()
|
|
.replace(/^\/+/, "");
|
|
|
|
if (!mediaBaseUrl || !normalizedStorageKey) {
|
|
return null;
|
|
}
|
|
|
|
return `${mediaBaseUrl}/${normalizedStorageKey}`;
|
|
}
|
|
|
|
/**
|
|
* Build an image source without throwing during render.
|
|
*
|
|
* IMPORTANT: callers should memoize this using primitive dependencies:
|
|
* `url`, `storage_key`, `requires_auth`, and `accessToken`.
|
|
*/
|
|
export function buildMediaImageSourceFromValues(
|
|
url: string | null | undefined,
|
|
storageKey: string | null | undefined,
|
|
requiresAuth: boolean | null | undefined,
|
|
accessToken: string | null,
|
|
): ImageSource | null {
|
|
const uri = resolveMediaUri(url, storageKey);
|
|
|
|
if (!uri) {
|
|
return null;
|
|
}
|
|
|
|
if (requiresAuth && accessToken) {
|
|
return {
|
|
uri,
|
|
headers: {
|
|
Authorization: `Bearer ${accessToken}`,
|
|
},
|
|
};
|
|
}
|
|
|
|
return { uri };
|
|
}
|
|
|
|
/**
|
|
* Backward-compatible helper.
|
|
*/
|
|
export function buildMediaImageSource(
|
|
item: ContentMediaItem,
|
|
accessToken: string | null,
|
|
): ImageSource | null {
|
|
return buildMediaImageSourceFromValues(
|
|
item.url,
|
|
item.storage_key,
|
|
item.requires_auth,
|
|
accessToken,
|
|
);
|
|
}
|
|
|
|
export function mediaLabel(item: ContentMediaItem, index: number): string {
|
|
return (
|
|
item.alt_text?.trim() ||
|
|
item.caption?.trim() ||
|
|
(item.usage_type ? item.usage_type.replace(/_/g, " ").trim() : "") ||
|
|
`Image ${index + 1}`
|
|
);
|
|
}
|