Skip to content

Commit 922bd69

Browse files
juliusmarmingeJulius Marmingeclaude
authored
refactor(media): unify file and media previews across clients (pingdotgg#9253)
Co-authored-by: Julius Marminge <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
1 parent 31eeb44 commit 922bd69

52 files changed

Lines changed: 1582 additions & 1740 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts‎

Lines changed: 13 additions & 143 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,15 @@
11
import {
2+
fileBasename,
3+
formatFilePathPosition,
24
inlineCodeFilePathCandidate,
3-
isConventionalFilePosition,
5+
normalizeMarkdownLinkDestination,
6+
parseMarkdownFileLink,
47
} from "@t3tools/client-runtime/markdown-links";
58
import { videoMimeType } from "@t3tools/shared/video";
69

710
import type { MARKDOWN_FILE_ICON_SOURCES } from "./markdownFileIcons.generated";
811

9-
const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
10-
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
11-
const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
12-
const RELATIVE_FILE_PATH_PATTERN =
13-
/^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;
14-
const RELATIVE_FILE_NAME_PATTERN =
15-
/^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
1612
const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
17-
const POSIX_FILE_ROOT_PREFIXES = [
18-
"/Users/",
19-
"/home/",
20-
"/tmp/",
21-
"/var/",
22-
"/etc/",
23-
"/opt/",
24-
"/mnt/",
25-
"/Volumes/",
26-
"/private/",
27-
"/root/",
28-
] as const;
2913

3014
export type MarkdownLinkPresentation =
3115
| {
@@ -246,112 +230,13 @@ const FILE_ICON_BY_EXTENSION: Readonly<Record<string, MarkdownFileIcon>> = {
246230
zsh: "bash",
247231
};
248232

249-
function safeDecode(value: string): string {
250-
try {
251-
return decodeURIComponent(value);
252-
} catch {
253-
return value;
254-
}
255-
}
256-
257-
function normalizeDestination(value: string): string {
258-
const trimmed = value.trim();
259-
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
260-
}
261-
262233
/** Native link and media APIs have no document scheme to inherit from protocol-relative URLs. */
263234
export function normalizeNativeMarkdownUrl(value: string): string {
264235
return value.startsWith("//") ? `https:${value}` : value;
265236
}
266237

267-
function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
268-
try {
269-
const parsed = new URL(href);
270-
if (parsed.protocol.toLowerCase() !== "file:") {
271-
return null;
272-
}
273-
const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
274-
const rawPath = uncHostname
275-
? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
276-
: parsed.pathname;
277-
const path = /^\/[A-Za-z]:[\\/]/.test(rawPath) ? rawPath.slice(1) : rawPath;
278-
return { path, hash: parsed.hash };
279-
} catch {
280-
return null;
281-
}
282-
}
283-
284-
function stripSearchAndHash(value: string): { readonly path: string; readonly hash: string } {
285-
const hashIndex = value.indexOf("#");
286-
const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
287-
const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
288-
const queryIndex = pathWithSearch.indexOf("?");
289-
return {
290-
path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
291-
hash,
292-
};
293-
}
294-
295-
function splitFilePosition(
296-
path: string,
297-
hash: string,
298-
): { readonly path: string; readonly line?: number; readonly column?: number } {
299-
const suffixMatch = path.match(/:(\d+)(?::(\d+))?$/);
300-
const hashMatch = suffixMatch ? null : hash.match(/^#L(\d+)(?:C(\d+))?$/i);
301-
const match = suffixMatch ?? hashMatch;
302-
if (!match?.[1]) {
303-
return { path };
304-
}
305-
306-
const line = Number.parseInt(match[1], 10);
307-
const column = match[2] ? Number.parseInt(match[2], 10) : undefined;
308-
const pathWithoutPosition = suffixMatch ? path.slice(0, -suffixMatch[0].length) : path;
309-
return {
310-
path: pathWithoutPosition,
311-
...(line > 0 ? { line } : {}),
312-
...(column !== undefined && column > 0 ? { column } : {}),
313-
};
314-
}
315-
316-
function looksLikePosixFilesystemPath(path: string): boolean {
317-
if (!path.startsWith("/")) {
318-
return false;
319-
}
320-
if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) {
321-
return true;
322-
}
323-
if (POSITION_SUFFIX_PATTERN.test(path)) {
324-
return true;
325-
}
326-
const basename = path.slice(path.lastIndexOf("/") + 1);
327-
return /\.[A-Za-z0-9_-]+$/.test(basename);
328-
}
329-
330-
function looksLikeFilePath(value: string): boolean {
331-
if (WINDOWS_DRIVE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value)) {
332-
return true;
333-
}
334-
if (RELATIVE_PATH_PREFIX_PATTERN.test(value)) {
335-
return true;
336-
}
337-
if (value.startsWith("/")) {
338-
return looksLikePosixFilesystemPath(value);
339-
}
340-
if (FILE_ICON_BY_NAME[value.replace(POSITION_SUFFIX_PATTERN, "").toLowerCase()]) {
341-
return true;
342-
}
343-
if (isConventionalFilePosition(value)) return true;
344-
return RELATIVE_FILE_PATH_PATTERN.test(value) || RELATIVE_FILE_NAME_PATTERN.test(value);
345-
}
346-
347-
function fileLabel(value: string): string {
348-
const normalized = value.replaceAll("\\", "/");
349-
const basename = normalized.slice(normalized.lastIndexOf("/") + 1);
350-
return basename || normalized;
351-
}
352-
353238
export function resolveMarkdownFileIcon(value: string): MarkdownFileIcon {
354-
const basename = fileLabel(value).replace(POSITION_SUFFIX_PATTERN, "").toLowerCase();
239+
const basename = fileBasename(value).replace(POSITION_SUFFIX_PATTERN, "").toLowerCase();
355240
if (videoMimeType({ name: basename, mimeType: "" }) !== null) return "video";
356241
const exactIcon = FILE_ICON_BY_NAME[basename];
357242
if (exactIcon) return exactIcon;
@@ -367,7 +252,7 @@ export function resolveMarkdownFileIcon(value: string): MarkdownFileIcon {
367252
}
368253

369254
export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPresentation {
370-
const normalized = normalizeDestination(href);
255+
const normalized = normalizeMarkdownLinkDestination(href);
371256
try {
372257
const parsed = new URL(normalizeNativeMarkdownUrl(normalized));
373258
if (parsed.protocol === "http:" || parsed.protocol === "https:") {
@@ -381,31 +266,16 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
381266
// Relative paths and non-URL link destinations are handled below.
382267
}
383268

384-
const source = normalized.toLowerCase().startsWith("file:")
385-
? fileUrlTarget(normalized)
386-
: stripSearchAndHash(normalized);
387-
const decodedSource = source
388-
? { path: safeDecode(source.path.trim()), hash: safeDecode(source.hash.trim()) }
389-
: null;
390-
const fileTarget = decodedSource
391-
? splitFilePosition(decodedSource.path, decodedSource.hash)
392-
: null;
393-
const targetWithPosition = fileTarget
394-
? `${fileTarget.path}${
395-
fileTarget.line
396-
? `:${fileTarget.line}${fileTarget.column ? `:${fileTarget.column}` : ""}`
397-
: ""
398-
}`
399-
: null;
400-
if (fileTarget && targetWithPosition && looksLikeFilePath(targetWithPosition)) {
269+
const target = parseMarkdownFileLink(normalized);
270+
if (target) {
401271
return {
402272
kind: "file",
403273
href: normalized,
404-
icon: resolveMarkdownFileIcon(fileTarget.path),
405-
label: fileLabel(targetWithPosition),
406-
path: fileTarget.path,
407-
...(fileTarget.line ? { line: fileTarget.line } : {}),
408-
...(fileTarget.column ? { column: fileTarget.column } : {}),
274+
icon: resolveMarkdownFileIcon(target.path),
275+
label: fileBasename(formatFilePathPosition(target)),
276+
path: target.path,
277+
...(target.line ? { line: target.line } : {}),
278+
...(target.column ? { column: target.column } : {}),
409279
};
410280
}
411281

‎apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
144144
type = detectedType
145145
} else if CGPDFDocument(download as CFURL) != nil {
146146
type = .pdf
147+
} else if URL(fileURLWithPath: title).pathExtension.lowercased() == "svg" {
148+
type = .svg
147149
} else {
148150
throw URLError(.cannotDecodeContentData)
149151
}

‎apps/mobile/src/components/ComposerAttachmentStrip.tsx‎

Lines changed: 12 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import { SymbolView } from "../components/AppSymbol";
22
import { videoMimeType } from "@t3tools/shared/video";
3-
import { useEffect, useRef, useState } from "react";
4-
import { Alert, Image, Pressable, ScrollView, View } from "react-native";
3+
import { useMemo } from "react";
4+
import { Image, Pressable, ScrollView, View } from "react-native";
55

66
import { AppText as Text } from "./AppText";
77
import type { DraftComposerAttachment, DraftComposerFileAttachment } from "../lib/composerImages";
88
import { VideoAttachmentTile } from "./VideoAttachmentTile";
9-
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
9+
import type { MediaActionsSource } from "../lib/mediaActions";
1010
import { PresentationSource } from "./NativePresentation";
1111
import type { FilePreviewSource } from "./FilePreviewModal";
1212
import { isPdfFile } from "../lib/filePreview";
@@ -175,55 +175,24 @@ function ComposerVideoAttachment(props: {
175175
const { attachment } = props;
176176
const sourceIdentifier = `draft:${attachment.id}`;
177177
const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
178-
const shareRef = useRef<AbortController | null>(null);
179-
const [sharing, setSharing] = useState(false);
180-
useEffect(
181-
() => () => {
182-
shareRef.current?.abort();
183-
shareRef.current = null;
184-
},
185-
[],
178+
const actionsSource = useMemo<MediaActionsSource>(
179+
() => ({
180+
name: attachment.name,
181+
mimeType: videoMimeType(attachment) ?? attachment.mimeType,
182+
sourceIdentifier,
183+
attachment,
184+
}),
185+
[attachment, sourceIdentifier],
186186
);
187187

188-
const onShare = () => {
189-
if (shareRef.current) return;
190-
const controller = new AbortController();
191-
shareRef.current = controller;
192-
setSharing(true);
193-
void (async () => {
194-
const preview = await loadLocalAttachmentPreview(attachment, controller.signal);
195-
if (!preview) return;
196-
try {
197-
await preview.share(controller.signal, sourceIdentifier);
198-
} finally {
199-
preview.dispose();
200-
}
201-
})()
202-
.catch((error: unknown) => {
203-
if (!controller.signal.aborted) {
204-
Alert.alert(
205-
"Could not share video",
206-
error instanceof Error ? error.message : "Try again.",
207-
);
208-
}
209-
})
210-
.finally(() => {
211-
if (shareRef.current === controller) {
212-
shareRef.current = null;
213-
setSharing(false);
214-
}
215-
});
216-
};
217-
218188
return (
219189
<VideoAttachmentTile
220190
name={attachment.name}
221191
sourceIdentifier={sourceIdentifier}
222192
thumbnailSource={attachment}
223193
compact={props.compact}
224194
onPress={() => props.onPressVideo(attachment, sourceIdentifier)}
225-
onShare={onShare}
226-
disabled={sharing}
195+
actionsSource={actionsSource}
227196
style={style}
228197
/>
229198
);

‎apps/mobile/src/components/FilePreview.ios.tsx‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { useEffect, useEffectEvent, useId } from "react";
33
import { Alert } from "react-native";
44

55
import type { ResolvedFilePreviewSource } from "./FilePreviewModal";
6-
import { MediaImagePreview } from "./MediaImagePreview";
76

87
const NativeControls = requireNativeModule<{
98
presentFile(
@@ -47,9 +46,5 @@ export function FilePreview(props: {
4746
readonly source: ResolvedFilePreviewSource;
4847
readonly onRequestClose: () => void;
4948
}) {
50-
return props.source.kind === "image" && props.source.actionsSource ? (
51-
<MediaImagePreview {...props} />
52-
) : (
53-
<NativeFilePreview {...props} />
54-
);
49+
return <NativeFilePreview {...props} />;
5550
}

‎apps/mobile/src/components/MediaActionsMenu.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { MenuView } from "@react-native-menu/menu";
22
import type { ReactElement } from "react";
3-
import { Platform, View, type PressableProps } from "react-native";
3+
import { Platform, View, type PressableProps, type StyleProp, type ViewStyle } from "react-native";
44

55
import type { useMediaActions } from "../lib/mediaActions";
66
import { SymbolView } from "./AppSymbol";
@@ -10,6 +10,7 @@ export function MediaActionsMenu(props: {
1010
readonly media: ReturnType<typeof useMediaActions>;
1111
readonly inModal?: boolean;
1212
readonly children?: ReactElement<PressableProps>;
13+
readonly style?: StyleProp<ViewStyle>;
1314
}) {
1415
if (props.media.actions.length === 0) return props.children ?? null;
1516
// Android's normal anchored menu lives in the app-root portal, behind native modals.
@@ -18,6 +19,7 @@ export function MediaActionsMenu(props: {
1819
return (
1920
<Menu
2021
title={props.media.title}
22+
style={props.style}
2123
shouldOpenOnLongPress={props.children !== undefined}
2224
actions={props.media.actions.map(({ id, title, disabled }) => ({
2325
id,

‎apps/mobile/src/components/MediaImagePreview.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ function ImagePreviewHeader() {
4242
);
4343
}
4444

45-
/** Chat and workspace media retain source actions on both platforms; other files use native previews. */
45+
/** Android keeps media actions in its in-app image viewer. iOS uses Quick Look. */
4646
export function MediaImagePreview(props: MediaImagePreviewProps) {
4747
return (
4848
<ImagePreviewContext value={props}>

0 commit comments

Comments
 (0)