feat: add file preview modal (#945)

This commit is contained in:
Aman Harwara
2022-03-24 00:13:44 +05:30
committed by GitHub
parent 8715a8b8f4
commit 12e3bb0959
15 changed files with 445 additions and 135 deletions

View File

@@ -27,6 +27,7 @@ import { PremiumModalProvider } from './Premium';
import { ConfirmSignoutContainer } from './ConfirmSignoutModal';
import { TagsContextMenu } from './Tags/TagContextMenu';
import { ToastContainer } from '@standardnotes/stylekit';
import { FilePreviewModalProvider } from './Files/FilePreviewModalProvider';
type Props = {
application: WebApplication;
@@ -175,6 +176,7 @@ export class ApplicationView extends PureComponent<Props, State> {
const renderAppContents = !this.state.needsUnlock && this.state.launched;
return (
<FilePreviewModalProvider application={this.application}>
<PremiumModalProvider
application={this.application}
appState={this.appState}
@@ -186,40 +188,33 @@ export class ApplicationView extends PureComponent<Props, State> {
className={this.state.appClass + ' app app-column-container'}
>
<Navigation application={this.application} />
<NotesView
application={this.application}
appState={this.appState}
/>
<NoteGroupView application={this.application} />
</div>
)}
{renderAppContents && (
<>
<Footer
application={this.application}
applicationGroup={this.props.mainApplicationGroup}
/>
<SessionsModal
application={this.application}
appState={this.appState}
/>
<PreferencesViewWrapper
appState={this.appState}
application={this.application}
/>
<RevisionHistoryModalWrapper
application={this.application}
appState={this.appState}
/>
</>
)}
{this.state.challenges.map((challenge) => {
return (
<div className="sk-modal">
@@ -232,31 +227,27 @@ export class ApplicationView extends PureComponent<Props, State> {
</div>
);
})}
{renderAppContents && (
<>
<NotesContextMenu
application={this.application}
appState={this.appState}
/>
<TagsContextMenu appState={this.appState} />
<PurchaseFlowWrapper
application={this.application}
appState={this.appState}
/>
<ConfirmSignoutContainer
appState={this.appState}
application={this.application}
/>
<ToastContainer />
</>
)}
</div>
</PremiumModalProvider>
</FilePreviewModalProvider>
);
}
}

View File

@@ -10,10 +10,10 @@ import {
} from './PopoverFileItemAction';
import { PopoverFileSubmenu } from './PopoverFileSubmenu';
const getFileIconComponent = (iconType: string) => {
export const getFileIconComponent = (iconType: string, className: string) => {
const IconComponent = ICONS[iconType as keyof typeof ICONS];
return <IconComponent className="w-8 h-8 flex-shrink-0" />;
return <IconComponent className={className} />;
};
export type PopoverFileItemProps = {
@@ -69,7 +69,10 @@ export const PopoverFileItem: FunctionComponent<PopoverFileItemProps> = ({
return (
<div className="flex items-center justify-between p-3">
<div className="flex items-center">
{getFileIconComponent(getIconType(file.mimeType))}
{getFileIconComponent(
getIconType(file.mimeType),
'w-8 h-8 flex-shrink-0'
)}
<div className="flex flex-col mx-4">
{isRenamingFile ? (
<input
@@ -82,7 +85,7 @@ export const PopoverFileItem: FunctionComponent<PopoverFileItemProps> = ({
onBlur={handleFileNameInputBlur}
/>
) : (
<div className="text-sm mb-1">{file.name}</div>
<div className="text-sm mb-1 break-word">{file.name}</div>
)}
<div className="text-xs color-grey-0">
{file.created_at.toLocaleString()} ·{' '}

View File

@@ -19,6 +19,7 @@ import {
import { Icon } from '../Icon';
import { Switch } from '../Switch';
import { useCloseOnBlur } from '../utils';
import { useFilePreviewModal } from '../Files/FilePreviewModalProvider';
import { PopoverFileItemProps } from './PopoverFileItem';
import { PopoverFileItemActionType } from './PopoverFileItemAction';
@@ -32,6 +33,8 @@ export const PopoverFileSubmenu: FunctionComponent<Props> = ({
handleFileAction,
setIsRenamingFile,
}) => {
const filePreviewModal = useFilePreviewModal();
const menuContainerRef = useRef<HTMLDivElement>(null);
const menuButtonRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
@@ -99,6 +102,17 @@ export const PopoverFileSubmenu: FunctionComponent<Props> = ({
>
{isMenuOpen && (
<>
<button
onBlur={closeOnBlur}
className="sn-dropdown-item focus:bg-info-backdrop"
onClick={() => {
filePreviewModal.activate(file);
closeMenu();
}}
>
<Icon type="file" className="mr-2 color-neutral" />
Preview file
</button>
{isAttachedToNote ? (
<button
onBlur={closeOnBlur}

View File

@@ -0,0 +1,194 @@
import { WebApplication } from '@/ui_models/application';
import { concatenateUint8Arrays } from '@/utils/concatenateUint8Arrays';
import { DialogContent, DialogOverlay } from '@reach/dialog';
import { SNFile } from '@standardnotes/snjs';
import { NoPreviewIllustration } from '@standardnotes/stylekit';
import { FunctionComponent } from 'preact';
import { useCallback, useEffect, useRef, useState } from 'preact/hooks';
import { getFileIconComponent } from '../AttachedFilesPopover/PopoverFileItem';
import { Button } from '../Button';
import { Icon } from '../Icon';
import { isFileTypePreviewable } from './isFilePreviewable';
type Props = {
application: WebApplication;
file: SNFile;
onDismiss: () => void;
};
const getPreviewComponentForFile = (file: SNFile, objectUrl: string) => {
if (file.mimeType.startsWith('image/')) {
return <img src={objectUrl} />;
}
if (file.mimeType.startsWith('video/')) {
return <video className="w-full h-full" src={objectUrl} controls />;
}
if (file.mimeType.startsWith('audio/')) {
return <audio src={objectUrl} controls />;
}
return <object className="w-full h-full" data={objectUrl} />;
};
export const FilePreviewModal: FunctionComponent<Props> = ({
application,
file,
onDismiss,
}) => {
const [objectUrl, setObjectUrl] = useState<string>();
const [isFilePreviewable, setIsFilePreviewable] = useState(false);
const [isLoadingFile, setIsLoadingFile] = useState(false);
const closeButtonRef = useRef<HTMLButtonElement>(null);
const getObjectUrl = useCallback(async () => {
setIsLoadingFile(true);
try {
const chunks: Uint8Array[] = [];
await application.files.downloadFile(
file,
async (decryptedChunk: Uint8Array) => {
chunks.push(decryptedChunk);
}
);
const finalDecryptedBytes = concatenateUint8Arrays(chunks);
setObjectUrl(
URL.createObjectURL(
new Blob([finalDecryptedBytes], {
type: file.mimeType,
})
)
);
} catch (error) {
console.error(error);
} finally {
setIsLoadingFile(false);
}
}, [application.files, file]);
useEffect(() => {
const isPreviewable = isFileTypePreviewable(file.mimeType);
setIsFilePreviewable(isPreviewable);
if (!objectUrl && isPreviewable) {
getObjectUrl();
}
return () => {
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
}
};
}, [file.mimeType, getObjectUrl, objectUrl]);
return (
<DialogOverlay
className="sn-component"
aria-label="File preview modal"
onDismiss={onDismiss}
initialFocusRef={closeButtonRef}
>
<DialogContent
className="flex flex-col rounded shadow-overlay"
style={{
width: '90%',
maxWidth: '90%',
minHeight: '90%',
background: 'var(--sn-stylekit-background-color)',
}}
>
<div className="flex flex-shrink-0 justify-between items-center min-h-6 px-4 py-3 border-0 border-b-1 border-solid border-main">
<div className="flex items-center">
<div className="w-6 h-6">
{getFileIconComponent(
application.iconsController.getIconForFileType(file.mimeType),
'w-6 h-6 flex-shrink-0'
)}
</div>
<span className="ml-3 font-medium">{file.name}</span>
</div>
<div className="flex items-center">
{objectUrl && (
<Button
type="primary"
className="mr-4"
onClick={() => {
application
.getArchiveService()
.downloadData(objectUrl, file.name);
}}
>
Download
</Button>
)}
<button
ref={closeButtonRef}
onClick={onDismiss}
aria-label="Close modal"
className="flex p-1 bg-transparent border-0 cursor-pointer"
>
<Icon type="close" className="color-neutral" />
</button>
</div>
</div>
<div className="flex flex-grow items-center justify-center min-h-0 overflow-auto">
{objectUrl ? (
getPreviewComponentForFile(file, objectUrl)
) : isLoadingFile ? (
<div className="sk-spinner w-5 h-5 spinner-info"></div>
) : (
<div className="flex flex-col items-center">
<NoPreviewIllustration className="w-30 h-30 mb-4" />
<div className="font-bold text-base mb-2">
This file can't be previewed.
</div>
{isFilePreviewable ? (
<>
<div className="text-sm text-center color-grey-0 mb-4 max-w-35ch">
There was an error loading the file. Try again, or download
it and open it using another application.
</div>
<div className="flex items-center">
<Button
type="primary"
className="mr-3"
onClick={() => {
getObjectUrl();
}}
>
Try again
</Button>
<Button
type="normal"
onClick={() => {
application.getAppState().files.downloadFile(file);
}}
>
Download
</Button>
</div>
</>
) : (
<>
<div className="text-sm text-center color-grey-0 mb-4 max-w-35ch">
To view this file, download it and open it using another
application.
</div>
<Button
type="primary"
onClick={() => {
application.getAppState().files.downloadFile(file);
}}
>
Download
</Button>
</>
)}
</div>
)}
</div>
</DialogContent>
</DialogOverlay>
);
};

View File

@@ -0,0 +1,53 @@
import { WebApplication } from '@/ui_models/application';
import { SNFile } from '@standardnotes/snjs';
import { createContext, FunctionComponent } from 'preact';
import { useContext, useState } from 'preact/hooks';
import { FilePreviewModal } from './FilePreviewModal';
type FilePreviewModalContextData = {
activate: (file: SNFile) => void;
};
const FilePreviewModalContext =
createContext<FilePreviewModalContextData | null>(null);
export const useFilePreviewModal = (): FilePreviewModalContextData => {
const value = useContext(FilePreviewModalContext);
if (!value) {
throw new Error('FilePreviewModalProvider not found.');
}
return value;
};
export const FilePreviewModalProvider: FunctionComponent<{
application: WebApplication;
}> = ({ application, children }) => {
const [isOpen, setIsOpen] = useState(false);
const [file, setFile] = useState<SNFile>();
const activate = (file: SNFile) => {
setFile(file);
setIsOpen(true);
};
const close = () => {
setIsOpen(false);
};
return (
<>
{isOpen && file && (
<FilePreviewModal
application={application}
file={file}
onDismiss={close}
/>
)}
<FilePreviewModalContext.Provider value={{ activate }}>
{children}
</FilePreviewModalContext.Provider>
</>
);
};

View File

@@ -0,0 +1,12 @@
export const isFileTypePreviewable = (fileType: string) => {
const isImage = fileType.startsWith('image/');
const isVideo = fileType.startsWith('video/');
const isAudio = fileType.startsWith('audio/');
const isPdf = fileType === 'application/pdf';
if (isImage || isVideo || isAudio || isPdf) {
return true;
}
return false;
};

View File

@@ -27,9 +27,8 @@ import {
EmailIcon,
EyeIcon,
EyeOffIcon,
FileIcon,
FolderIcon,
FileDocIcon,
FileIcon,
FileImageIcon,
FileMovIcon,
FileMusicIcon,
@@ -38,6 +37,7 @@ import {
FilePptIcon,
FileXlsIcon,
FileZipIcon,
FolderIcon,
HashtagIcon,
HashtagOffIcon,
HelpIcon,
@@ -165,7 +165,6 @@ export const ICONS = {
settings: SettingsIcon,
signIn: SignInIcon,
signOut: SignOutIcon,
spellcheck: NotesIcon,
spreadsheets: SpreadsheetsIcon,
star: StarIcon,
sync: SyncIcon,

View File

@@ -161,7 +161,7 @@ const SpellcheckOptions: FunctionComponent<{
disabled={!spellcheckControllable}
>
<span className="flex items-center">
<Icon type="spellcheck" className={iconClass} />
<Icon type="notes" className={iconClass} />
Spellcheck
</span>
<Switch

View File

@@ -3,13 +3,7 @@ import { STRING_RESTORE_LOCKED_ATTEMPT } from '@/strings';
import { WebApplication } from '@/ui_models/application';
import { AppState } from '@/ui_models/app_state';
import { getPlatformString } from '@/utils';
import {
AlertDialogContent,
AlertDialogDescription,
AlertDialogLabel,
AlertDialogOverlay,
} from '@reach/alert-dialog';
import VisuallyHidden from '@reach/visually-hidden';
import { DialogContent, DialogOverlay } from '@reach/dialog';
import {
ButtonType,
ContentType,
@@ -240,24 +234,22 @@ export const RevisionHistoryModal: FunctionComponent<RevisionHistoryModalProps>
};
return (
<AlertDialogOverlay
<DialogOverlay
className={`sn-component ${getPlatformString()}`}
onDismiss={dismissModal}
leastDestructiveRef={closeButtonRef}
initialFocusRef={closeButtonRef}
aria-label="Note revision history"
>
<AlertDialogContent
<DialogContent
className="rounded shadow-overlay"
style={{
width: '90%',
maxWidth: '90%',
minHeight: '90%',
background: '#fff',
background: 'var(--sn-stylekit-background-color)',
}}
>
<AlertDialogLabel>
<VisuallyHidden>Note revision history</VisuallyHidden>
</AlertDialogLabel>
<AlertDialogDescription
<div
className={`bg-default flex flex-col h-full overflow-hidden ${
isDeletingRevision ? 'pointer-events-none cursor-not-allowed' : ''
}`}
@@ -333,9 +325,9 @@ export const RevisionHistoryModal: FunctionComponent<RevisionHistoryModalProps>
</div>
)}
</div>
</AlertDialogDescription>
</AlertDialogContent>
</AlertDialogOverlay>
</div>
</DialogContent>
</DialogOverlay>
);
});

View File

@@ -24,6 +24,8 @@ type ZippableData = {
content: Blob;
}[];
type ObjectURL = string;
export class ArchiveManager {
private readonly application: WebApplication;
private textFile?: string;
@@ -32,6 +34,10 @@ export class ArchiveManager {
this.application = application;
}
public async getMimeType(ext: string) {
return (await import('@zip.js/zip.js')).getMimeType(ext);
}
public async downloadBackup(encrypted: boolean): Promise<void> {
const intent = encrypted
? EncryptionIntent.FileEncrypted
@@ -150,10 +156,10 @@ export class ArchiveManager {
return this.textFile;
}
downloadData(data: Blob, fileName: string) {
downloadData(data: Blob | ObjectURL, fileName: string) {
const link = document.createElement('a');
link.setAttribute('download', fileName);
link.href = this.hrefForData(data);
link.href = typeof data === 'string' ? data : this.hrefForData(data);
document.body.appendChild(link);
link.click();
link.remove();

View File

@@ -1,8 +1,10 @@
import { concatenateUint8Arrays } from '@/utils/concatenateUint8Arrays';
import {
ClassicFileReader,
StreamingFileReader,
StreamingFileSaver,
ClassicFileSaver,
parseFileName,
} from '@standardnotes/filepicker';
import { ClientDisplayableError, SNFile } from '@standardnotes/snjs';
import { addToast, dismissToast, ToastType } from '@standardnotes/stylekit';
@@ -31,19 +33,24 @@ export class FilesState {
message: `Downloading file...`,
});
const decryptedBytesArray: Uint8Array[] = [];
await this.application.files.downloadFile(
file,
async (decryptedBytes: Uint8Array) => {
if (isUsingStreamingSaver) {
await saver.pushBytes(decryptedBytes);
} else {
saver.saveFile(file.name, decryptedBytes);
decryptedBytesArray.push(decryptedBytes);
}
}
);
if (isUsingStreamingSaver) {
await saver.finish();
} else {
const finalBytes = concatenateUint8Arrays(decryptedBytesArray);
saver.saveFile(file.name, finalBytes);
}
addToast({
@@ -85,6 +92,11 @@ export class FilesState {
const uploadedFiles: SNFile[] = [];
for (const file of selectedFiles) {
toastId = addToast({
type: ToastType.Loading,
message: `Uploading file "${file.name}"...`,
});
const operation = await this.application.files.beginNewFileUpload();
if (operation instanceof ClientDisplayableError) {
@@ -92,8 +104,7 @@ export class FilesState {
type: ToastType.Error,
message: `Unable to start upload session`,
});
return;
throw new Error(`Unable to start upload session`);
}
const onChunk = async (
@@ -109,20 +120,22 @@ export class FilesState {
);
};
toastId = addToast({
type: ToastType.Loading,
message: `Uploading file "${file.name}"...`,
});
const fileResult = await picker.readFile(
file,
minimumChunkSize,
onChunk
);
if (!fileResult.mimeType) {
const { ext } = parseFileName(file.name);
fileResult.mimeType = await this.application
.getArchiveService()
.getMimeType(ext);
}
const uploadedFile = await this.application.files.finishUpload(
operation,
{ name: fileResult.name, mimeType: fileResult.mimeType }
fileResult
);
if (uploadedFile instanceof ClientDisplayableError) {
@@ -130,8 +143,7 @@ export class FilesState {
type: ToastType.Error,
message: `Unable to close upload session`,
});
return;
throw new Error(`Unable to close upload session`);
}
uploadedFiles.push(uploadedFile);

View File

@@ -0,0 +1,14 @@
export const concatenateUint8Arrays = (arrays: Uint8Array[]) => {
const totalLength = arrays
.map((array) => array.length)
.reduce((prev, next) => prev + next, 0);
const concatenatedArray = new Uint8Array(totalLength);
let offset = 0;
arrays.forEach((array) => {
concatenatedArray.set(array, offset);
offset += array.length;
});
return concatenatedArray;
};

View File

@@ -16,6 +16,10 @@
width: 6.5rem;
}
.h-30 {
width: 7.5rem;
}
.h-33 {
height: 8.25rem;
}
@@ -318,6 +322,10 @@
max-width: 22.25rem;
}
.max-w-35ch {
max-width: 35ch;
}
.mb-4 {
margin-bottom: 1rem;
}
@@ -333,6 +341,10 @@
width: 0.75rem;
}
.w-6 {
width: 1.5rem;
}
.w-18 {
width: 4.5rem;
}
@@ -341,8 +353,8 @@
width: 6.5rem;
}
.max-w-200 {
max-width: 50rem;
.w-30 {
width: 7.5rem;
}
.w-92 {
@@ -405,6 +417,10 @@
min-width: 22.5rem;
}
.max-w-200 {
max-width: 50rem;
}
.min-h-1px {
min-height: 1px;
}
@@ -989,6 +1005,10 @@
color: var(--sn-stylekit-neutral-contrast-color);
}
.break-word {
word-break: break-word;
}
.transition {
transition-property: color, background-color, border-color,
text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter,

View File

@@ -33,7 +33,7 @@
"@standardnotes/stylekit": "5.17.0",
"@svgr/webpack": "^6.2.1",
"@types/jest": "^27.4.1",
"@types/react": "^17.0.41",
"@types/react": "^17.0.42",
"@types/wicg-file-system-access": "^2020.9.5",
"@typescript-eslint/eslint-plugin": "^5.16.0",
"@typescript-eslint/parser": "^5.16.0",
@@ -73,10 +73,10 @@
"@reach/tooltip": "^0.16.2",
"@standardnotes/components": "1.7.12",
"@standardnotes/features": "1.35.4",
"@standardnotes/filepicker": "1.10.1",
"@standardnotes/filepicker": "1.10.2",
"@standardnotes/settings": "1.13.1",
"@standardnotes/sncrypto-web": "1.8.0",
"@standardnotes/snjs": "2.90.0",
"@standardnotes/snjs": "2.91.0",
"@zip.js/zip.js": "^2.4.7",
"mobx": "^6.5.0",
"mobx-react-lite": "^3.3.0",

View File

@@ -2430,10 +2430,10 @@
"@standardnotes/auth" "^3.17.11"
"@standardnotes/common" "^1.17.0"
"@standardnotes/filepicker@1.10.1":
version "1.10.1"
resolved "https://registry.yarnpkg.com/@standardnotes/filepicker/-/filepicker-1.10.1.tgz#451e8b80a670c35f4de5a1a17535b26876d4b92b"
integrity sha512-7q535TdXT0vKaIPvFDRPgcACrPAEs6Rgbw4pi8jLGY/Rodfty0zCN3z4NeDb/IdOGPpM8QYhKMLpYoZcKDjIMQ==
"@standardnotes/filepicker@1.10.2":
version "1.10.2"
resolved "https://registry.yarnpkg.com/@standardnotes/filepicker/-/filepicker-1.10.2.tgz#4e2d76a327e61c5d864ce6e0597786caa83f2e20"
integrity sha512-+3LCaU7CH5gzZJBd6mXajx4ztdIVax8fqk49poHXRQd/mMIc36cOfCwbLlJeT4X6GL7UMLktieZZQqtG7hmRdw==
"@standardnotes/payloads@^1.4.18":
version "1.4.18"
@@ -2484,10 +2484,10 @@
buffer "^6.0.3"
libsodium-wrappers "^0.7.9"
"@standardnotes/snjs@2.90.0":
version "2.90.0"
resolved "https://registry.yarnpkg.com/@standardnotes/snjs/-/snjs-2.90.0.tgz#87f11c52d8511ee7c0939f021b5ce96f47748222"
integrity sha512-3AilDSB7FdqxPP25zf41PoHZ0iqd6dcuzT4qtYkLTGnAz/WaCLzJy0sS/e5x9tHW3sltoVRhXJsRRmQV5JZFCQ==
"@standardnotes/snjs@2.91.0":
version "2.91.0"
resolved "https://registry.yarnpkg.com/@standardnotes/snjs/-/snjs-2.91.0.tgz#53ab1100b6f4cacbdc4f3f779511ec0ed8cebe32"
integrity sha512-dt4K22eq1f/dNawto1hkiYrnTrV7wFu+QKlg18/TUAUnsdgpwMs+fznFB5UrKpW2BLzYPQPfjrVFKAsvkR91nQ==
dependencies:
"@standardnotes/applications" "^1.2.6"
"@standardnotes/auth" "^3.17.11"
@@ -2858,10 +2858,10 @@
resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.4.tgz#cd667bcfdd025213aafb7ca5915a932590acdcdc"
integrity sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==
"@types/react@^17.0.41":
version "17.0.41"
resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.41.tgz#6e179590d276394de1e357b3f89d05d7d3da8b85"
integrity sha512-chYZ9ogWUodyC7VUTRBfblysKLjnohhFY9bGLwvnUFFy48+vB9DikmB3lW0qTFmBcKSzmdglcvkHK71IioOlDA==
"@types/react@^17.0.42":
version "17.0.42"
resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.42.tgz#8242b9219bf8a911c47f248e327206fea3f4ee5a"
integrity sha512-nuab3x3CpJ7VFeNA+3HTUuEkvClYHXqWtWd7Ud6AZYW7Z3NH9WKtgU+tFB0ZLcHq+niB/HnzLcaZPqMJ95+k5Q==
dependencies:
"@types/prop-types" "*"
"@types/scheduler" "*"