Add DOCX viewer support in public file viewer

This commit is contained in:
Leon Bösche
2026-01-25 15:44:32 +01:00
parent 532848ebdf
commit 7582f27899

View File

@@ -27,6 +27,7 @@ class _PublicFileViewerState extends State<PublicFileViewer> {
Map<String, dynamic>? _fileData;
VideoPlayerController? _videoController;
String? _videoViewType;
String? _docxViewType;
@override
void initState() {
@@ -54,6 +55,15 @@ class _PublicFileViewerState extends State<PublicFileViewer> {
if (_isVideoFile()) {
await _initializeVideoPlayer();
}
// Register DOCX viewer if it's a document file
if (_isDocumentFile()) {
final url = _fileData?['viewUrl'] ?? _fileData?['downloadUrl'];
if (url != null) {
_docxViewType = 'public-docx-viewer-${widget.token.hashCode}';
_registerDocxViewFactory(url);
}
}
} catch (e) {
setState(() {
_error = 'This link is invalid or has expired.';
@@ -108,6 +118,29 @@ class _PublicFileViewerState extends State<PublicFileViewer> {
});
}
void _registerDocxViewFactory(String docxUrl) {
ui_web.platformViewRegistry.registerViewFactory(_docxViewType!, (
int viewId,
) {
final iframeElement = web.HTMLIFrameElement()
..src =
'https://docs.google.com/viewer?url=${Uri.encodeComponent(docxUrl)}&embedded=true'
..style.width = '100%'
..style.height = '100%'
..style.border = 'none';
iframeElement.onError.listen((event) {
if (mounted) {
setState(() {
_error = 'Document could not be loaded. Please download the file.';
});
}
});
return iframeElement;
});
}
String? _getViewUrl() {
return _fileData?['viewUrl'] ?? _fileData?['downloadUrl'];
}
@@ -229,35 +262,45 @@ class _PublicFileViewerState extends State<PublicFileViewer> {
),
);
} else if (_isDocumentFile()) {
return Expanded(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.description,
size: 80,
color: AppTheme.primaryText.withValues(alpha: 0.7),
),
const SizedBox(height: 16),
Text(
'Document Preview',
style: TextStyle(
color: AppTheme.primaryText,
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 8),
Text(
'This document type requires download to view',
style: TextStyle(color: AppTheme.secondaryText, fontSize: 14),
textAlign: TextAlign.center,
),
],
if (kIsWeb && _docxViewType != null) {
// Use Google Docs viewer for web
return Expanded(
child: Container(
color: Colors.white,
child: HtmlElementView(viewType: _docxViewType!),
),
),
);
);
} else {
return Expanded(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.description,
size: 80,
color: AppTheme.primaryText.withValues(alpha: 0.7),
),
const SizedBox(height: 16),
Text(
'Document Preview',
style: TextStyle(
color: AppTheme.primaryText,
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 8),
Text(
'This document type requires download to view',
style: TextStyle(color: AppTheme.secondaryText, fontSize: 14),
textAlign: TextAlign.center,
),
],
),
),
);
}
} else {
return Expanded(
child: Center(