Files

78 lines
2.6 KiB
Dart

import '../../artifacts/domain/artifact_kind.dart';
/// The media type the files endpoint serves for [name], from its extension.
///
/// The server sets the real `Content-Type` on the wire; this is the client's
/// own classification for choosing a viewer, a thumbnail and a download type.
String fileContentType(String name) {
final dot = name.lastIndexOf('.');
final ext = dot == -1 ? '' : name.substring(dot + 1).toLowerCase();
return _types[ext] ?? 'application/octet-stream';
}
const Map<String, String> _types = {
'svg': 'image/svg+xml',
'ico': 'image/x-icon',
'bmp': 'image/bmp',
'avif': 'image/avif',
'dart': 'text/plain',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'webp': 'image/webp',
'mp4': 'video/mp4',
'webm': 'video/webm',
'mov': 'video/quicktime',
'mp3': 'audio/mpeg',
'wav': 'audio/wav',
'm4a': 'audio/mp4',
'pdf': 'application/pdf',
'json': 'application/json',
'csv': 'text/csv',
'tsv': 'text/tab-separated-values',
'html': 'text/html',
'htm': 'text/html',
'md': 'text/markdown',
'markdown': 'text/markdown',
'txt': 'text/plain',
'log': 'text/plain',
'zip': 'application/zip',
'gz': 'application/gzip',
'tar': 'application/x-tar',
};
/// How the Files panel's viewer presents [name].
///
/// Unlike the artifact gallery, which keeps a turn's `session.html` export (and
/// its repairs) external-only, every HTML document in a working directory
/// previews inertly here: a file called `session.html` in a folder is just a
/// web page. Everything else follows the shared [artifactPreviewFormat] rule.
ArtifactPreviewFormat filePreviewFormat(String contentType, String name) {
final mime = contentType.split(';').first.trim().toLowerCase();
final lower = name.toLowerCase();
if (mime == 'image/svg+xml' ||
mime == 'text/html' ||
lower.endsWith('.html') ||
lower.endsWith('.htm')) {
return ArtifactPreviewFormat.html;
}
if (mime == 'text/plain' &&
!lower.endsWith('.md') &&
!lower.endsWith('.markdown')) {
return ArtifactPreviewFormat.text;
}
return artifactPreviewFormat(contentType, name);
}
/// Whether the Files panel opens [name] in the in-app viewer rather than the
/// unviewable sheet (PDFs open externally and are not previewable here).
bool isPreviewableFile(String name) =>
filePreviewFormat(fileContentType(name), name) !=
ArtifactPreviewFormat.none;
/// Whether [name] is an image the grid draws as a thumbnail.
bool isThumbnailFile(String name) =>
filePreviewFormat(fileContentType(name), name) ==
ArtifactPreviewFormat.image;