Skip to content

Commit

Permalink
💄 style: fix ms doc file preview (lobehub#3686)
Browse files Browse the repository at this point in the history
* 💄 style: improve msdoc relative file view

* update i18n
  • Loading branch information
arvinxx committed Aug 30, 2024
1 parent 9a5dd74 commit 2cd78cf
Show file tree
Hide file tree
Showing 29 changed files with 128 additions and 29 deletions.
3 changes: 2 additions & 1 deletion locales/ar/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "الوضع الحالي للنشر لا يدعم إدارة الملفات"
},
"preview": {
"unsupportedFile": "هذا التنسيق غير مدعوم للمعاينة عبر الإنترنت"
"downloadFile": "تحميل الملف",
"unsupportedFileAndContact": "هذا التنسيق من الملفات غير مدعوم للمعاينة عبر الإنترنت، إذا كان لديك طلب للمعاينة، فلا تتردد في <1>إبلاغنا</1>"
},
"searchFilePlaceholder": "بحث عن ملف",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/bg-BG/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "Текущият режим на инсталация не поддържа управление на файлове"
},
"preview": {
"unsupportedFile": "Този файлов формат не поддържа онлайн преглед"
"downloadFile": "Изтеглете файла",
"unsupportedFileAndContact": "Този формат на файла не поддържа онлайн преглед. Ако имате нужда от преглед, моля, <1>свържете се с нас</1>."
},
"searchFilePlaceholder": "Търсене на файл",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/de-DE/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "Der aktuelle Bereitstellungsmodus unterstützt keine Dateiverwaltung"
},
"preview": {
"unsupportedFile": "Dieses Dateiformat wird nicht für die Online-Vorschau unterstützt"
"downloadFile": "Datei herunterladen",
"unsupportedFileAndContact": "Dieses Dateiformat wird derzeit nicht für die Online-Vorschau unterstützt. Wenn Sie eine Vorschau wünschen, können Sie uns gerne <1>Feedback geben</1>."
},
"searchFilePlaceholder": "Datei suchen",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/en-US/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "The current deployment mode does not support file management"
},
"preview": {
"unsupportedFile": "This file format does not support online preview"
"downloadFile": "Download File",
"unsupportedFileAndContact": "This file format is not currently supported for online preview. If you have a request for previewing, feel free to <1>contact us</1>."
},
"searchFilePlaceholder": "Search Files",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/es-ES/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "El modo de despliegue actual no soporta la gestión de archivos"
},
"preview": {
"unsupportedFile": "Este formato de archivo no es compatible con la vista previa en línea"
"downloadFile": "Descargar archivo",
"unsupportedFileAndContact": "Este formato de archivo no es compatible con la vista previa en línea. Si desea solicitar una vista previa, no dude en <1>contactarnos</1>."
},
"searchFilePlaceholder": "Buscar archivo",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/fr-FR/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "Le mode de déploiement actuel ne prend pas en charge la gestion des fichiers"
},
"preview": {
"unsupportedFile": "Ce format de fichier ne prend pas en charge l'aperçu en ligne"
"downloadFile": "Télécharger le fichier",
"unsupportedFileAndContact": "Ce format de fichier n'est pas encore pris en charge pour l'aperçu en ligne. Si vous souhaitez un aperçu, n'hésitez pas à <1>nous contacter</1>."
},
"searchFilePlaceholder": "Rechercher un fichier",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/it-IT/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "La modalità di distribuzione attuale non supporta la gestione dei file"
},
"preview": {
"unsupportedFile": "Questo formato di file non supporta l'anteprima online"
"downloadFile": "Scarica file",
"unsupportedFileAndContact": "Questo formato di file non è attualmente supportato per la visualizzazione online. Se hai bisogno di una visualizzazione, ti preghiamo di <1>contattarci</1>."
},
"searchFilePlaceholder": "Cerca file",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/ja-JP/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "現在のデプロイメントモードはファイル管理をサポートしていません"
},
"preview": {
"unsupportedFile": "このファイル形式はオンラインプレビューをサポートしていません"
"downloadFile": "ファイルをダウンロード",
"unsupportedFileAndContact": "このファイル形式はオンラインプレビューをサポートしていません。プレビューのリクエストがある場合は、ぜひ<1>ご連絡ください</1>。"
},
"searchFilePlaceholder": "ファイルを検索",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/ko-KR/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "현재 배포 모드는 파일 관리를 지원하지 않습니다."
},
"preview": {
"unsupportedFile": "이 파일 형식은 온라인 미리보기를 지원하지 않습니다."
"downloadFile": "파일 다운로드",
"unsupportedFileAndContact": "이 파일 형식은 온라인 미리보기를 지원하지 않습니다. 미리보기가 필요하신 경우, <1>저희에게 피드백을 주시기 바랍니다</1>."
},
"searchFilePlaceholder": "파일 검색",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/nl-NL/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "De huidige implementatiemodus ondersteunt geen bestandsbeheer"
},
"preview": {
"unsupportedFile": "Dit bestandsformaat wordt niet ondersteund voor online preview"
"downloadFile": "Bestand downloaden",
"unsupportedFileAndContact": "Dit bestandsformaat wordt momenteel niet ondersteund voor online preview. Als u een preview wilt, neem dan gerust <1>contact met ons op</1>."
},
"searchFilePlaceholder": "Zoek bestand",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/pl-PL/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "Obecny tryb wdrożenia nie obsługuje zarządzania plikami"
},
"preview": {
"unsupportedFile": "Ten format pliku nie jest obsługiwany w podglądzie online"
"downloadFile": "Pobierz plik",
"unsupportedFileAndContact": "Ten format pliku nie jest obecnie obsługiwany w podglądzie online. Jeśli chcesz uzyskać podgląd, zachęcamy do <1>skontaktowania się z nami</1>."
},
"searchFilePlaceholder": "Szukaj pliku",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/pt-BR/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "O modo de implantação atual não suporta gerenciamento de arquivos"
},
"preview": {
"unsupportedFile": "Este formato de arquivo não suporta visualização online"
"downloadFile": "Baixar arquivo",
"unsupportedFileAndContact": "Este formato de arquivo não é suportado para visualização online. Se você tiver interesse em visualizar, sinta-se à vontade para <1>nos enviar um feedback</1>."
},
"searchFilePlaceholder": "Pesquisar arquivo",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/ru-RU/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "Текущий режим развертывания не поддерживает управление файлами"
},
"preview": {
"unsupportedFile": "Этот формат файла не поддерживает онлайн-просмотр"
"downloadFile": "Скачать файл",
"unsupportedFileAndContact": "Этот формат файла в настоящее время не поддерживает онлайн-просмотр. Если у вас есть запрос на просмотр, пожалуйста, <1>сообщите нам</1>."
},
"searchFilePlaceholder": "Поиск файла",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/tr-TR/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "Mevcut dağıtım modu dosya yönetimini desteklemiyor"
},
"preview": {
"unsupportedFile": "Bu dosya formatı çevrimiçi önizleme desteklenmiyor"
"downloadFile": "Dosyayı İndir",
"unsupportedFileAndContact": "Bu dosya formatı çevrimiçi önizleme için desteklenmiyor. Önizleme talebiniz varsa, lütfen <1>bize geri bildirimde bulunun</1>."
},
"searchFilePlaceholder": "Dosya Ara",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/vi-VN/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "Chế độ triển khai hiện tại không hỗ trợ quản lý tệp"
},
"preview": {
"unsupportedFile": "Định dạng tệp này không hỗ trợ xem trước trực tuyến"
"downloadFile": "Tải tệp",
"unsupportedFileAndContact": "Định dạng tệp này hiện không hỗ trợ xem trước trực tuyến. Nếu bạn có yêu cầu xem trước, vui lòng <1>phản hồi cho chúng tôi</1>"
},
"searchFilePlaceholder": "Tìm kiếm tệp",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/zh-CN/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "当前部署模式不支持文件管理"
},
"preview": {
"unsupportedFile": "此文件格式不支持在线预览"
"downloadFile": "下载文件",
"unsupportedFileAndContact": "此文件格式暂不支持在线预览,如有预览诉求,欢迎<1>反馈给我们</1>"
},
"searchFilePlaceholder": "搜索文件",
"tab": {
Expand Down
3 changes: 2 additions & 1 deletion locales/zh-TW/file.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"title": "當前部署模式不支持檔案管理"
},
"preview": {
"unsupportedFile": "此檔案格式不支持在線預覽"
"downloadFile": "下載檔案",
"unsupportedFileAndContact": "此檔案格式暫不支援線上預覽,如有預覽需求,歡迎<1>反饋給我們</1>"
},
"searchFilePlaceholder": "搜索檔案",
"tab": {
Expand Down
2 changes: 0 additions & 2 deletions src/components/FileParsingStatus/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,6 @@ const FileParsingStatus = memo<FileParsingStatusProps>(
}

case AsyncTaskStatus.Success: {
console.log(embeddingStatus);

// if no embedding status, it means that the embedding is not started
if (!embeddingStatus || preparingEmbedding)
return (
Expand Down
3 changes: 3 additions & 0 deletions src/const/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ export const PLUGINS_INDEX_URL = 'https://chat-plugins.lobehub.com';
export const MORE_MODEL_PROVIDER_REQUEST_URL =
'https://github.com/lobehub/lobe-chat/discussions/1284';

export const MORE_FILE_PREVIEW_REQUEST_URL =
'https://github.com/lobehub/lobe-chat/discussions/3684';

export const AGENTS_INDEX_GITHUB = 'https://github.com/lobehub/lobe-chat-agents';
export const AGENTS_INDEX_GITHUB_ISSUE = urlJoin(AGENTS_INDEX_GITHUB, 'issues/new');

Expand Down
19 changes: 15 additions & 4 deletions src/features/FileViewer/NotSupport/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { IDocument } from '@cyntler/react-doc-viewer';
import { FluentEmoji } from '@lobehub/ui';
import { Button } from 'antd';
import { createStyles } from 'antd-style';
import Link from 'next/link';
import React, { ComponentType, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Trans, useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';

import { MORE_FILE_PREVIEW_REQUEST_URL } from '@/const/url';
import { downloadFile } from '@/utils/client/downloadFile';

const useStyles = createStyles(({ css, token }) => ({
Expand All @@ -25,15 +28,23 @@ const NotSupport: ComponentType<{
}> = ({ fileName, document: doc }) => {
const { styles } = useStyles();

const { t } = useTranslation(['file', 'common']);
const { t } = useTranslation('file');

const [loading, setLoading] = useState(false);

return (
<Flexbox className={styles.page} id="txt-renderer">
<Center height={'100%'}>
<Flexbox align={'center'} gap={12}>
{t('preview.unsupportedFile')}
<FluentEmoji emoji={'👀'} size={64} />
<Flexbox style={{ textAlign: 'center' }}>
<Trans i18nKey="preview.unsupportedFileAndContact" ns={'file'}>
此文件格式暂不支持在线预览,如有预览诉求,欢迎
<Link aria-label={'todo'} href={MORE_FILE_PREVIEW_REQUEST_URL} target="_blank">
反馈给我们
</Link>
</Trans>
</Flexbox>
<Button
loading={loading}
onClick={async () => {
Expand All @@ -43,7 +54,7 @@ const NotSupport: ComponentType<{
setLoading(false);
}}
>
{t('download', { ns: 'common' })}
{t('preview.downloadFile')}
</Button>
</Flexbox>
</Center>
Expand Down
65 changes: 65 additions & 0 deletions src/features/FileViewer/Renderer/MSDoc/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { DocRenderer } from '@cyntler/react-doc-viewer';
import { css, cx } from 'antd-style';
import { Flexbox } from 'react-layout-kit';

const container = css`
position: relative;
overflow: hidden;
border-radius: 4px;
`;

const content = css`
position: absolute;
inset-block: -1px -1px;
inset-inline-start: -1px;
width: calc(100% + 2px);
height: calc(100% + 2px);
border: 0;
`;

const MSDocRenderer: DocRenderer = ({ mainState: { currentDocument } }) => {
if (!currentDocument) return null;

return (
<Flexbox className={cx(container)} height={'100%'} id="msdoc-renderer" width={'100%'}>
<iframe
className={cx(content)}
id="msdoc-iframe"
src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
currentDocument.uri,
)}`}
title="msdoc-iframe"
/>
</Flexbox>
);
};

export default MSDocRenderer;

const MSDocFTMaps = {
doc: ['doc', 'application/msword'],
docx: [
'docx',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/octet-stream',
],
odt: ['odt', 'application/vnd.oasis.opendocument.text'],
ppt: ['ppt', 'application/vnd.ms-powerpoint'],
pptx: ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
xls: ['xls', 'application/vnd.ms-excel'],
xlsx: ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
};

MSDocRenderer.fileTypes = [
...MSDocFTMaps.odt,
...MSDocFTMaps.doc,
...MSDocFTMaps.docx,
...MSDocFTMaps.xls,
...MSDocFTMaps.xlsx,
...MSDocFTMaps.ppt,
...MSDocFTMaps.pptx,
];
MSDocRenderer.weight = 0;
MSDocRenderer.fileLoader = ({ fileLoaderComplete }) => fileLoaderComplete();
File renamed without changes.
File renamed without changes.
File renamed without changes.
4 changes: 4 additions & 0 deletions src/features/FileViewer/Renderer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import MSDocRenderer from './MSDoc';
import TXTRenderer from './TXT';

export const FileViewRenderers = [TXTRenderer, MSDocRenderer];
10 changes: 5 additions & 5 deletions src/features/FileViewer/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use client';

import DocViewer, { MSDocRenderer } from '@cyntler/react-doc-viewer';
import DocViewer from '@cyntler/react-doc-viewer';
import { createStyles } from 'antd-style';
import { CSSProperties, memo } from 'react';

import { FileListItem } from '@/types/files';

import NotSupport from './NotSupport';
import PDFViewer from './PDFViewer';
import TXTViewer from './TXTViewer';
import { FileViewRenderers } from './Renderer';
import PDFRenderer from './Renderer/PDF';

const useStyles = createStyles(({ css, token }) => ({
container: css`
Expand All @@ -25,7 +25,7 @@ interface FileViewerProps extends FileListItem {
const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) => {
const { styles } = useStyles();
if (fileType === 'pdf' || name.endsWith('.pdf')) {
return <PDFViewer fileId={id} url={url} />;
return <PDFRenderer fileId={id} url={url} />;
}

return (
Expand All @@ -36,7 +36,7 @@ const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) =>
noRenderer: { overrideComponent: NotSupport },
}}
documents={[{ fileName: name, fileType, uri: url }]}
pluginRenderers={[TXTViewer, MSDocRenderer]}
pluginRenderers={FileViewRenderers}
style={style}
/>
);
Expand Down
3 changes: 2 additions & 1 deletion src/locales/default/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ export default {
title: '当前部署模式不支持文件管理',
},
preview: {
unsupportedFile: '此文件格式不支持在线预览',
downloadFile: '下载文件',
unsupportedFileAndContact: '此文件格式暂不支持在线预览,如有预览诉求,欢迎<1>反馈给我们</1>',
},
searchFilePlaceholder: '搜索文件',
tab: {
Expand Down

0 comments on commit 2cd78cf

Please sign in to comment.