WIP replace image selector

This commit is contained in:
Patrick Fic
2025-10-07 13:40:37 -07:00
parent f95b0e1263
commit 83fe7059e9
3 changed files with 134 additions and 451 deletions

View File

@@ -1,7 +1,7 @@
import { Ionicons } from "@expo/vector-icons";
//import { AssetsSelector } from "expo-images-picker";
import { MediaType } from "expo-media-library";
import React, { useCallback, useMemo, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, Text, View } from "react-native";
import { connect } from "react-redux";
@@ -20,7 +20,7 @@ import UploadDeleteSwitch from "../upload-delete-switch/upload-delete-switch.com
import UploadProgress from "../upload-progress/upload-progress.component";
import { SegmentedButtons } from "react-native-paper";
import * as ImagePicker from "expo-image-picker";
import { Button } from "react-native-paper";
import { Button } from "react-native-paper";
// import * as MediaLibrary from "expo-media-library";
const mapStateToProps = createStructuredSelector({
@@ -50,120 +50,39 @@ export function ImageBrowserScreen({
setTick((tick) => tick + 1);
}, []);
const [percentage, setPercentage] = useState(0);
useEffect(() => {
(async () => {
if (Constants.platform.ios) {
const cameraRollStatus =
await ImagePicker.requestMediaLibraryPermissionsAsync();
const cameraStatus = await ImagePicker.requestCameraPermissionsAsync();
if (
cameraRollStatus.status !== "granted" ||
cameraStatus.status !== "granted"
) {
alert("Sorry, we need these permissions to make this work!");
}
}
})();
}, []);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ["images", "videos"],
aspect: [4, 3],
quality: 1,
allowsMultipleSelection: true,
});
setUploads(result.assets);
};
const onDone = (data) => {
logImEXEvent("imexmobile_upload_documents", { count: data.length });
// const uploads = await Promise.all(
// data.map(async (item) => {
// let id = item.id || item.fileName;
// if (!item.id && item.uri) {
// id = await getAssetIdFromUri(item.uri, item.fileName);
// }
// return {
// ...item,
// localUri: item.uri,
// id,
// };
// })
// );
// console.log("onDone", uploads);
if (data.length !== 0) setUploads(data);
};
const widgetErrors = useMemo(
() => ({
errorTextColor: "black",
errorMessages: {
hasErrorWithPermissions: "Please Allow media gallery permissions.",
hasErrorWithLoading: "There was an error while loading images.",
hasErrorWithResizing: "There was an error while loading images.",
hasNoAssets: "No images found.",
},
}),
[]
);
const widgetSettings = useMemo(
() => ({
getImageMetaData: false, // true might perform slower results but gives meta data and absolute path for ios users
initialLoad: 50,
assetsType: [MediaType.photo, MediaType.video],
minSelection: 1,
// maxSelection: 3,
portraitCols: density,
landscapeCols: density,
}),
[density]
);
const widgetNavigator = useMemo(
() => ({
Texts: {
finish: t("mediabrowser.actions.upload"),
back: t("mediabrowser.actions.refresh"),
selected: "selected",
},
midTextColor: "black",
minSelection: 1,
buttonTextStyle: styles.textStyle,
buttonStyle: styles.buttonStyle,
onBack: () => {
forceRerender();
},
onSuccess: onDone,
}),
[]
);
const widgetStyles = useMemo(
() => ({
margin: 2,
bgColor: "white",
spinnerColor: "blue",
widgetWidth: 99,
videoIcon: {
Component: Ionicons,
iconName: "videocam",
color: "white",
size: 20,
},
selectedIcon: {
Component: Ionicons,
iconName: "checkmark-circle-outline",
color: "white",
bg: "rgba(35,35,35, 0.75)",
size: 32,
},
}),
[]
);
// const handleSelectPhotos = async () => {
// let result = await ImagePicker.launchImageLibraryAsync({
// mediaTypes: ["images", "videos"],
// allowsMultipleSelection: true,
// // aspect: [4, 3],
// });
// console.log("*** ~ handleSelectPhotos ~ result:", result);
// if (!result.canceled) {
// const uploads = await Promise.all(
// result.assets.map(async (item) => {
// let id = item.id || item.fileName;
// if (!item.id && item.uri) {
// id = await getAssetIdFromUri(item.uri);
// }
// return {
// ...item,
// localUri: item.uri,
// id,
// };
// })
// );
// console.log("Uploads from handleSelectPhotos", uploads);
// setUploads(uploads);
// }
// };
return (
<View style={[styles.flex, styles.container]}>
<CameraSelectJob />
@@ -208,18 +127,7 @@ export function ImageBrowserScreen({
<Text>{t("mediabrowser.labels.selectjobassetselector")}</Text>
</View>
)}
{/* {selectedCameraJobId && (
<AssetsSelector
style={{ flex: 1 }}
key={tick}
Settings={widgetSettings}
Errors={widgetErrors}
Styles={widgetStyles}
Navigator={widgetNavigator}
/>
)} */}
<Button>Media Select</Button>
<Button onPress={pickImage}>Media Select</Button>
{bodyshop.uselocalmediaserver ? (
<UploadProgressLocal
uploads={uploads}
@@ -256,63 +164,6 @@ const styles = StyleSheet.create({
export default connect(mapStateToProps, mapDispatchToProps)(ImageBrowserScreen);
// options={{
// assetsType: ["photo", "video"],
// margin: 3,
// portraitCols: 4,
// landscapeCols: 6,
// widgetWidth: 100,
// widgetBgColor: "white",
// selectedBgColor: "#adadad",
// spinnerColor: "#c8c8c8",
// videoIcon: {
// Component: Ionicons,
// iconName: "ios-videocam",
// color: "white",
// size: 20,
// },
// selectedIcon: {
// Component: Ionicons,
// iconName: "ios-checkmark-circle-outline",
// color: "white",
// bg: "rgba(35,35,35, 0.75)",
// size: 32,
// },
// defaultTopNavigator: {
// continueText: t("mediabrowser.actions.upload"),
// goBackText: t("mediabrowser.actions.refresh"),
// buttonStyle: styles.buttonStyle,
// textStyle: styles.textStyle,
// backFunction: () => {
// forceRerender();
// },
// doneFunction: onDone,
// },
// noAssets: {
// Component: function NoAsset() {
// return (
// <View
// style={{
// display: "flex",
// flex: 1,
// height: 200,
// marginHorizontal: 20,
// alignItems: "center",
// justifyContent: "center",
// }}
// >
// <Ionicons name="ios-camera" size={72} />
// <Text style={{ textAlign: "center", marginTop: 10 }}>
// {t("mediabrowser.labels.nomedia")}
// </Text>
// </View>
// );
// },
// },
// }}
// // Utility to get asset ID from URI if missing
// async function getAssetIdFromUri(uri, filename = null, maxPages = 10) {
// let after = null;

View File

@@ -1,5 +1,5 @@
import { useApolloClient } from "@apollo/client";
import * as FileSystem from "expo-file-system";
import { File } from "expo-file-system";
import * as MediaLibrary from "expo-media-library";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -127,81 +127,97 @@ export function UploadProgress({
statusText: "Preparing upload...",
};
});
try {
//Validate to make sure the totals for the file sizes do not exceed the total on the job.
const data = [];
const totalOfUploads = await selectedFiles.reduce(async (acc, val) => {
//Get the size of the file based on URI.
if (acc.fileSize) {
return acc + acc.fileSize;
} else {
const info = new File(val.uri).size;
data.push({ ...info, ...val }); //Add in the size.
val.albumId && MediaLibrary.migrateAlbumIfNeededAsync(val.albumId);
return (await acc) + info.size;
}
}, 0);
//Validate to make sure the totals for the file sizes do not exceed the total on the job.
const data = [];
const totalOfUploads = await selectedFiles.reduce(async (acc, val) => {
//Get the size of the file based on URI.
if (acc.fileSize) {
return acc + acc.fileSize;
} else {
const info = await FileSystem.getInfoAsync(val.uri, { size: true });
data.push({ ...info, ...val }); //Add in the size.
val.albumId && MediaLibrary.migrateAlbumIfNeededAsync(val.albumId);
return (await acc) + info.size;
}
}, 0);
if (selectedCameraJobId !== "temp") {
const queryData = await client.query({
query: GET_DOC_SIZE_TOTALS,
fetchPolicy: "network-only",
variables: {
jobId: selectedCameraJobId,
},
});
if (selectedCameraJobId !== "temp") {
const queryData = await client.query({
query: GET_DOC_SIZE_TOTALS,
fetchPolicy: "network-only",
variables: {
jobId: selectedCameraJobId,
},
});
if (
bodyshop.jobsizelimit -
queryData.data.documents_aggregate.aggregate.sum.size <=
totalOfUploads
) {
//No more room... abandon ship.
if (
bodyshop.jobsizelimit -
queryData.data.documents_aggregate.aggregate.sum.size <=
totalOfUploads
) {
//No more room... abandon ship.
setProgress((progress) => ({
...progress,
speed: 0,
action: null,
statusText: null,
uploadInProgress: false,
}));
Alert.alert(
t("mediabrowser.labels.storageexceeded_title"),
t("mediabrowser.labels.storageexceeded")
);
return;
}
//We made it this far. We have enough space, so let's start uploading.
setProgress((progress) => ({
...progress,
speed: 0,
action: null,
totalToUpload: totalOfUploads,
totalUploaded: 0,
totalFilesCompleted: 0,
startTime: new Date(),
totalFiles: data.length,
currentFile: null,
statusText: null,
uploadInProgress: false,
files: {}, //uri is the key, value is progress
}));
Alert.alert(
t("mediabrowser.labels.storageexceeded_title"),
t("mediabrowser.labels.storageexceeded")
);
return;
}
}
//We made it this far. We have enough space, so let's start uploading.
setProgress((progress) => ({
...progress,
totalToUpload: totalOfUploads,
totalUploaded: 0,
totalFilesCompleted: 0,
startTime: new Date(),
totalFiles: data.length,
currentFile: null,
statusText: null,
files: {}, //uri is the key, value is progress
}));
for (var i = 0; i < data.length + 4; i = i + 4) {
//Reset the files.
setProgress((progress) => ({ ...progress, files: {} }));
let proms = [];
if (data[i]) {
proms.push(CreateUploadProm(data[i]));
}
if (data[i + 1]) {
proms.push(CreateUploadProm(data[i + 1]));
}
if (data[i + 2]) {
proms.push(CreateUploadProm(data[i + 2]));
}
if (data[i + 3]) {
proms.push(CreateUploadProm(data[i + 3]));
}
await Promise.all(proms);
for (var i = 0; i < data.length + 4; i = i + 4) {
//Reset the files.
setProgress((progress) => ({ ...progress, files: {} }));
let proms = [];
if (data[i]) {
proms.push(CreateUploadProm(data[i]));
}
if (data[i + 1]) {
proms.push(CreateUploadProm(data[i + 1]));
}
if (data[i + 2]) {
proms.push(CreateUploadProm(data[i + 2]));
}
if (data[i + 3]) {
proms.push(CreateUploadProm(data[i + 3]));
}
await Promise.all(proms);
}
} catch (error) {
console.log("Error during upload.", error, error.stack);
Sentry.captureException(error);
setProgress((progress) => ({
...progress,
speed: 0,
action: null,
statusText: null,
uploadInProgress: false,
}));
Alert.alert(
t("mediabrowser.labels.uploaderror_title"),
t("mediabrowser.labels.uploaderror")
);
return;
}
//Everything is uploaded, delete the succesful ones.