TagSpaces is an offline, open source, document manager with tagging support
feat: added taking photos functionality for mobile
Ilian Sapundshiev11338246a80c
diff --git a/src/renderer/components/CommonIcons.tsx b/src/renderer/components/CommonIcons.tsxindex 0feb30215..37bdc467c 100644--- a/src/renderer/components/CommonIcons.tsx+++ b/src/renderer/components/CommonIcons.tsx@@ -173,6 +173,8 @@ export { default as NewFolderIcon } from '@mui/icons-material/CreateNewFolderOutexport { default as AddExistingFileIcon } from '@mui/icons-material/ExitToApp';+export { default as TakePictureIcon } from '@mui/icons-material/AddAPhotoOutlined';+export { default as RecordIcon } from '@mui/icons-material/FiberManualRecord';export { default as StopIcon } from '@mui/icons-material/Stop';diff --git a/src/renderer/components/FileUploadContainer.tsx b/src/renderer/components/FileUploadContainer.tsxindex 2826cab16..05eb9c533 100644--- a/src/renderer/components/FileUploadContainer.tsx+++ b/src/renderer/components/FileUploadContainer.tsx@@ -21,6 +21,7 @@ import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';import { actions as AppActions, AppDispatch } from '-/reducers/app';+import { takePicture } from '-/services/utils-io';import { TS } from '-/tagspaces.namespace';import {ChangeEvent,@@ -38,6 +39,7 @@ interface Props {export interface FileUploadContainerRef {onFileUpload: (directoryPath: string) => void;+ onCameraCapture: (directoryPath: string) => void;onMetaUpload: () => void;setMetaUpload: (mUpload: () => void) => void;}@@ -70,6 +72,22 @@ const FileUploadContainer = forwardRef(directoryPath.current = dirPath;fileInput.current.click();},+ // Capacitor-only: the WebView file chooser can't open the camera, so this+ // captures a photo via the native camera plugin and runs it through the+ // same upload pipeline as a picked file.+ onCameraCapture(dirPath: string) {+ directoryPath.current = dirPath;+ takePicture()+ .then((file) => {+ if (file) {+ uploadFiles([file]);+ }+ return true;+ })+ .catch((error) => {+ console.log('takePicture', error);+ });+ },}));const fileInput = useRef<HTMLInputElement>(null);@@ -77,12 +95,16 @@ const FileUploadContainer = forwardRef(function handleFileInputChange(selection: ChangeEvent<HTMLInputElement>) {// console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0]));// const file = selection.currentTarget.files[0];+ uploadFiles(Array.from(selection.currentTarget.files));+ }++ function uploadFiles(selectedFiles: Array<File>) {dispatch(AppActions.resetProgress());// openFileUploadDialog();const localLocation = findLocalLocation();const sourceLocationId = localLocation ? localLocation.uuid : undefined;- let files = Array.from(selection.currentTarget.files);+ let files = selectedFiles;if (AppConfig.isElectron) {files = files.map((file) => {if (!file.path) {diff --git a/src/renderer/components/MobileNavigation.tsx b/src/renderer/components/MobileNavigation.tsxindex ee5f4c84c..87699f19a 100644--- a/src/renderer/components/MobileNavigation.tsx+++ b/src/renderer/components/MobileNavigation.tsx@@ -36,6 +36,7 @@ import {RecentThingsIcon,SettingsIcon,TagLibraryIcon,+ TakePictureIcon,TemplateFileIcon,ThemingIcon,WorkspacesIcon,@@ -109,7 +110,7 @@ function MobileNavigation(props: Props) {const { setSelectedLocation, currentLocation, locations } =useCurrentLocationContext();const { currentDirectoryPath } = useDirectoryContentContext();- const { openFileUpload } = useFileUploadContext();+ const { openFileUpload, openCameraCapture } = useFileUploadContext();const { openCreateEditLocationDialog } = useCreateEditLocationDialogContext();const { openCreateDirectoryDialog } = useCreateDirectoryDialogContext();const { openNewFileDialog } = useNewFileDialogContext();@@ -522,6 +523,25 @@ function MobileNavigation(props: Props) {</ListItemIcon><ListItemText primary={t('core:addFiles')} /></MenuItem>+ {/* Capacitor-only: the WebView file chooser can't open the+ camera, so offer a dedicated trigger for the native+ camera plugin. */}+ {AppConfig.isCapacitor && (+ <MenuItem+ key="cameraTakePicture"+ data-tid="cameraTakePictureTID"+ onClick={() => {+ openCameraCapture(currentDirectoryPath);+ setOpenCreateMenu(false);+ hideDrawer?.();+ }}+ >+ <ListItemIcon>+ <TakePictureIcon />+ </ListItemIcon>+ <ListItemText primary={t('core:cameraTakePicture')} />+ </MenuItem>+ )}{/* Web can't bypass browser CORS/CSP — only show the URLdownload where it saves into the location. Pro feature:enabled on Pro (BETA), disabled with a PRO badge on Lite,diff --git a/src/renderer/components/menus/DirectoryMenu.tsx b/src/renderer/components/menus/DirectoryMenu.tsxindex 5993f420c..245258d49 100644--- a/src/renderer/components/menus/DirectoryMenu.tsx+++ b/src/renderer/components/menus/DirectoryMenu.tsx@@ -90,7 +90,7 @@ function DirectoryMenu(props: Props) {useCurrentLocationContext();const { setThumbnailImageChange, getMetadataID } = useIOActionsContext();const { showNotification } = useNotificationContext();- const { openFileUpload } = useFileUploadContext();+ const { openFileUpload, openCameraCapture } = useFileUploadContext();const { openCreateDirectoryDialog } = useCreateDirectoryDialogContext();const {openDirectory,@@ -267,6 +267,14 @@ function DirectoryMenu(props: Props) {openFileUpload(directoryPath);}+ // The WebView file chooser behind "Add files" can't open the camera on+ // mobile, so on Capacitor we offer a dedicated "Take picture" entry that+ // drives the native camera plugin and feeds the photo into the same upload+ // pipeline.+ function cameraTakePicture() {+ openCameraCapture(directoryPath);+ }+function importMacTags() {openImportMacTagDialog(directoryPath);}@@ -372,7 +380,7 @@ function DirectoryMenu(props: Props) {importMacTags,switchPerspectives ? perspectiveSwitch : undefined,showProperties,- undefined, // cameraTakePicture removed — was using Cordova-only navigator.camera API+ AppConfig.isCapacitor ? cameraTakePicture : undefined,showAddRemoveTagsDialog,openInNewWindow,changeFolderThumbnail,diff --git a/src/renderer/hooks/FileUploadContextProvider.tsx b/src/renderer/hooks/FileUploadContextProvider.tsxindex 493c44c1d..0cc129a2b 100644--- a/src/renderer/hooks/FileUploadContextProvider.tsx+++ b/src/renderer/hooks/FileUploadContextProvider.tsx@@ -23,6 +23,7 @@ import FileUploadContainer, {type FileUploadContextData = {openFileUpload: (dPath: string) => void;+ openCameraCapture: (dPath: string) => void;uploadMeta: () => void;setMetaUpload: (mUpload: () => void) => void;transferMeta: boolean;@@ -30,6 +31,7 @@ type FileUploadContextData = {export const FileUploadContext = createContext<FileUploadContextData>({openFileUpload: undefined,+ openCameraCapture: undefined,uploadMeta: undefined,setMetaUpload: undefined,transferMeta: false,@@ -49,6 +51,10 @@ export const FileUploadContextProvider = ({fileUploadContainerRef.current?.onFileUpload(dPath);}+ function openCameraCapture(dPath: string) {+ fileUploadContainerRef.current?.onCameraCapture(dPath);+ }+function uploadMeta() {fileUploadContainerRef.current?.onMetaUpload();setTransferMeta(false);@@ -62,6 +68,7 @@ export const FileUploadContextProvider = ({const context = useMemo(() => {return {openFileUpload: openFileUpload,+ openCameraCapture: openCameraCapture,uploadMeta: uploadMeta,setMetaUpload: setMetaUpload,transferMeta,diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.jsonindex 5621176ca..66eb7af11 100644--- a/src/renderer/locales/en/core.json+++ b/src/renderer/locales/en/core.json@@ -309,7 +309,7 @@"createLinkFile": "New Link File","createNewFromTemplate": "New From Template","createDirectory": "New Folder",- "addFiles": "New From Device",+ "addFiles": "Import From Device","exitApp": "Exit","window": "Window","documentation": "Documentation",@@ -558,6 +558,7 @@"sharingLinkTooltip": "Link for sharing to other TagSpaces installation using the same location IDs","generateDownloadLink": "Generate link","copyLinkToClipboard": "Copy the link to the clipboard",+ "captureURL": "Capture URL as file","linkCopied": "Link copied to clipboard","downloadLink": "Link for downloading","downloadLinkTooltip": "Link and QR-code for time limited sharing on the Internet",@@ -884,7 +885,7 @@"upgrade": "Upgrade","urlValidationHelp": "Invalid URL","openSharingLink": "Open sharing links created with the TagSpaces (ts:// links)",- "newFromDownloadURL": "New From URL",+ "newFromDownloadURL": "Capture URL","invalidSharingLink": "Invalid Sharing Link","confirmSearchById": "Do you want to search for the file or folder by its ID?","uploadDirsNotSupported": "Uploading folders not supported!",diff --git a/src/renderer/perspectives/common/DirectoryMenuItems.tsx b/src/renderer/perspectives/common/DirectoryMenuItems.tsxindex 128b6dd7b..54e8781fc 100644--- a/src/renderer/perspectives/common/DirectoryMenuItems.tsx+++ b/src/renderer/perspectives/common/DirectoryMenuItems.tsx@@ -246,7 +246,8 @@ export function getDirectoryMenuItems((createNewFile ||createNewAudio ||showCreateDirectoryDialog ||- addExistingFile)+ addExistingFile ||+ cameraTakePicture)) {menuItems.push(<NewSubMenu@@ -257,6 +258,7 @@ export function getDirectoryMenuItems(createNewAudio={createNewAudio}showCreateDirectoryDialog={showCreateDirectoryDialog}addExistingFile={addExistingFile}+ cameraTakePicture={cameraTakePicture}/>,);}diff --git a/src/renderer/perspectives/common/NewSubMenu.tsx b/src/renderer/perspectives/common/NewSubMenu.tsxindex 2ae77ce3d..7ecf28da1 100644--- a/src/renderer/perspectives/common/NewSubMenu.tsx+++ b/src/renderer/perspectives/common/NewSubMenu.tsx@@ -26,6 +26,7 @@ import {NewFileIcon,NewFolderIcon,SmallArrowRightIcon,+ TakePictureIcon,TemplateFileIcon,} from '-/components/CommonIcons';import { useDownloadUrlDialogContext } from '-/components/dialogs/hooks/useDownloadUrlDialogContext';@@ -50,6 +51,7 @@ interface Props {createNewAudio?: () => void;showCreateDirectoryDialog?: () => void;addExistingFile?: () => void;+ cameraTakePicture?: () => void;}/**@@ -67,6 +69,7 @@ function NewSubMenu(props: Props) {createNewAudio,showCreateDirectoryDialog,addExistingFile,+ cameraTakePicture,} = props;const hideProFeatures: boolean = useSelector(isHideProFeatures);const { openDownloadUrl } = useDownloadUrlDialogContext();@@ -225,6 +228,21 @@ function NewSubMenu(props: Props) {<ListItemText primary={t('core:addFiles')} /></MenuItem>)}+ {/* Native mobile only: the WebView file chooser can't open the+ camera, so this is a dedicated trigger for the Capacitor camera+ plugin. Only wired in on Capacitor (see DirectoryMenu). */}+ {cameraTakePicture && (+ <MenuItem+ key="cameraTakePicture"+ data-tid="cameraTakePictureTID"+ onClick={() => run(() => cameraTakePicture())}+ >+ <ListItemIcon>+ <TakePictureIcon />+ </ListItemIcon>+ <ListItemText primary={t('core:cameraTakePicture')} />+ </MenuItem>+ )}{/* Web can't bypass browser CORS/CSP — the download only saves intothe location on desktop and native mobile, so hide it elsewhere.Pro feature: enabled on Pro (BETA), disabled with a PRO badge ondiff --git a/src/renderer/services/io-capacitor.ts b/src/renderer/services/io-capacitor.tsindex 7bc11128d..21af6bfb6 100644--- a/src/renderer/services/io-capacitor.ts+++ b/src/renderer/services/io-capacitor.ts@@ -42,6 +42,13 @@ try {console.warn('FilePicker plugin not available');}+let Camera, CameraResultType, CameraSource;+try {+ ({ Camera, CameraResultType, CameraSource } = require('@capacitor/camera'));+} catch (e) {+ console.warn('Camera plugin not available');+}+// Custom plugins registered in MainActivityconst { registerPlugin } = require('@capacitor/core');const StoragePermission = registerPlugin('StoragePermission');@@ -1186,6 +1193,54 @@ function selectDirectoryDialog() {return Promise.reject('FilePicker plugin not available');}+/**+ * Open the native camera to take a photo. The system file chooser that backs+ * `<input type="file">` in the Capacitor WebView can't reach the camera as a+ * capture source, so this is the dedicated "take a picture" trigger the file+ * picker is missing. Returns a browser File (image/<format>) that the caller+ * feeds through the normal uploadFilesAPI pipeline — its isNativeMobile branch+ * tags the generic name with a capture timestamp so repeated shots don't+ * collide. Resolves null when the user cancels the camera.+ */+function takePicture() {+ if (!Camera) {+ return Promise.reject('Camera plugin not available');+ }+ return Camera.getPhoto({+ source: CameraSource.Camera,+ resultType: CameraResultType.DataUrl,+ quality: 90,+ saveToGallery: false,+ // A file manager wants the full frame — cropping is for avatar pickers.+ allowEditing: false,+ })+ .then((photo) => {+ if (!photo || !photo.dataUrl) {+ return null;+ }+ const format = photo.format || 'jpeg';+ // Let the WebView decode the data URL into bytes — fetch() handles+ // base64 natively, sidestepping the manual base64→Blob conversion.+ return fetch(photo.dataUrl)+ .then((res) => res.blob())+ .then(+ (blob) =>+ new File([blob], 'image.' + format, {+ type: blob.type || 'image/' + format,+ }),+ );+ })+ .catch((err) => {+ // The plugin throws "User cancelled photos app" when the camera is+ // dismissed — treat that as a no-op rather than surfacing an error.+ const msg = err && err.message ? err.message : String(err);+ if (msg.toLowerCase().includes('cancel')) {+ return null;+ }+ throw err;+ });+}+function openDirectory(dirPath) {console.warn('function openDirectory not supported on Capacitor mobile');}@@ -1426,6 +1481,7 @@ export {selectDirectory,selectFile,selectDirectoryDialog,+ takePicture,openDirectory,openFile,openUrl,diff --git a/src/renderer/services/utils-io.ts b/src/renderer/services/utils-io.tsindex efa33e58f..1e3320a95 100644--- a/src/renderer/services/utils-io.ts+++ b/src/renderer/services/utils-io.ts@@ -1368,6 +1368,19 @@ export function selectDirectoryDialog(): Promise<any> {return Promise.reject(new Error('selectDirectoryDialog: not implemented'));}+/**+ * Capture a photo with the native camera and return it as a browser File.+ * Capacitor-only: the WebView's file chooser can't open the camera directly,+ * so this provides the missing capture trigger. Resolves null on cancel.+ */+export function takePicture(): Promise<File | null> {+ if (AppConfig.isCapacitor) {+ const ioAPI = require('-/services/io-capacitor');+ return ioAPI.takePicture();+ }+ return Promise.reject(new Error('takePicture: not implemented'));+}+export function removePrefix(str: string | null | undefined,prefix: string | null | undefined,