From 4182edfd7e3333fcf31b94f2f091fe143945b809 Mon Sep 17 00:00:00 2001 From: Paul Frazee Date: Thu, 23 Feb 2023 16:02:31 -0600 Subject: Implement image uploading in the web composer --- src/lib/api/index.ts | 52 ++++++++++--- src/lib/constants.ts | 4 + src/lib/images.ts | 166 ---------------------------------------- src/lib/images.web.ts | 68 ----------------- src/lib/media/manip.ts | 178 +++++++++++++++++++++++++++++++++++++++++++ src/lib/media/manip.web.ts | 88 +++++++++++++++++++++ src/lib/media/picker.tsx | 141 ++++++++++++++++++++++++++++++++++ src/lib/media/picker.web.tsx | 143 ++++++++++++++++++++++++++++++++++ src/lib/media/types.ts | 31 ++++++++ 9 files changed, 628 insertions(+), 243 deletions(-) delete mode 100644 src/lib/images.ts delete mode 100644 src/lib/images.web.ts create mode 100644 src/lib/media/manip.ts create mode 100644 src/lib/media/manip.web.ts create mode 100644 src/lib/media/picker.tsx create mode 100644 src/lib/media/picker.web.tsx create mode 100644 src/lib/media/types.ts (limited to 'src/lib') diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index d800c376c..ae156928e 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -1,11 +1,16 @@ -import {AppBskyEmbedImages, AppBskyEmbedExternal} from '@atproto/api' +import { + AppBskyEmbedImages, + AppBskyEmbedExternal, + ComAtprotoBlobUpload, +} from '@atproto/api' import {AtUri} from '../../third-party/uri' import {RootStoreModel} from 'state/models/root-store' import {extractEntities} from 'lib/strings/rich-text-detection' import {isNetworkError} from 'lib/strings/errors' import {LinkMeta} from '../link-meta/link-meta' -import {Image} from '../images' +import {Image} from '../media/manip' import {RichText} from '../strings/rich-text' +import {isWeb} from 'platform/detection' export interface ExternalEmbedDraft { uri: string @@ -27,6 +32,25 @@ export async function resolveName(store: RootStoreModel, didOrHandle: string) { return res.data.did } +export async function uploadBlob( + store: RootStoreModel, + blob: string, + encoding: string, +): Promise { + if (isWeb) { + // `blob` should be a data uri + return store.api.com.atproto.blob.upload(convertDataURIToUint8Array(blob), { + encoding, + }) + } else { + // `blob` should be a path to a file in the local FS + return store.api.com.atproto.blob.upload( + blob, // this will be special-cased by the fetch monkeypatch in /src/state/lib/api.ts + {encoding}, + ) + } +} + export async function post( store: RootStoreModel, rawText: string, @@ -61,10 +85,7 @@ export async function post( let i = 1 for (const image of images) { onStateChange?.(`Uploading image #${i++}...`) - const res = await store.api.com.atproto.blob.upload( - image, // this will be special-cased by the fetch monkeypatch in /src/state/lib/api.ts - {encoding: 'image/jpeg'}, - ) + const res = await uploadBlob(store, image, 'image/jpeg') embed.images.push({ image: { cid: res.data.cid, @@ -94,9 +115,10 @@ export async function post( ) } if (encoding) { - const thumbUploadRes = await store.api.com.atproto.blob.upload( - extLink.localThumb.path, // this will be special-cased by the fetch monkeypatch in /src/state/lib/api.ts - {encoding}, + const thumbUploadRes = await uploadBlob( + store, + extLink.localThumb.path, + encoding, ) thumb = { cid: thumbUploadRes.data.cid, @@ -199,3 +221,15 @@ export async function unfollow(store: RootStoreModel, followUri: string) { rkey: followUrip.rkey, }) } + +// helpers +// = + +function convertDataURIToUint8Array(uri: string): Uint8Array { + var raw = window.atob(uri.substring(uri.indexOf(';base64,') + 8)) + var binary = new Uint8Array(new ArrayBuffer(raw.length)) + for (let i = 0; i < raw.length; i++) { + binary[i] = raw.charCodeAt(i) + } + return binary +} diff --git a/src/lib/constants.ts b/src/lib/constants.ts index 2a3043c06..72cba0b63 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -63,3 +63,7 @@ export const STAGING_SUGGESTED_FOLLOWS = ['arcalinea', 'paul', 'paul2'].map( export const DEV_SUGGESTED_FOLLOWS = ['alice', 'bob', 'carla'].map( handle => `${handle}.test`, ) + +export const POST_IMG_MAX_WIDTH = 2000 +export const POST_IMG_MAX_HEIGHT = 2000 +export const POST_IMG_MAX_SIZE = 1000000 diff --git a/src/lib/images.ts b/src/lib/images.ts deleted file mode 100644 index 609e03bda..000000000 --- a/src/lib/images.ts +++ /dev/null @@ -1,166 +0,0 @@ -import RNFetchBlob from 'rn-fetch-blob' -import ImageResizer from '@bam.tech/react-native-image-resizer' -import {Share} from 'react-native' -import RNFS from 'react-native-fs' -import uuid from 'react-native-uuid' -import * as Toast from 'view/com/util/Toast' - -export interface DownloadAndResizeOpts { - uri: string - width: number - height: number - mode: 'contain' | 'cover' | 'stretch' - maxSize: number - timeout: number -} - -export interface Image { - path: string - mime: string - size: number - width: number - height: number -} - -export async function downloadAndResize(opts: DownloadAndResizeOpts) { - let appendExt = 'jpeg' - try { - const urip = new URL(opts.uri) - const ext = urip.pathname.split('.').pop() - if (ext === 'png') { - appendExt = 'png' - } - } catch (e: any) { - console.error('Invalid URI', opts.uri, e) - return - } - - let downloadRes - try { - const downloadResPromise = RNFetchBlob.config({ - fileCache: true, - appendExt, - }).fetch('GET', opts.uri) - const to1 = setTimeout(() => downloadResPromise.cancel(), opts.timeout) - downloadRes = await downloadResPromise - clearTimeout(to1) - - let localUri = downloadRes.path() - if (!localUri.startsWith('file://')) { - localUri = `file://${localUri}` - } - - return await resize(localUri, opts) - } finally { - if (downloadRes) { - downloadRes.flush() - } - } -} - -export interface ResizeOpts { - width: number - height: number - mode: 'contain' | 'cover' | 'stretch' - maxSize: number -} - -export async function resize( - localUri: string, - opts: ResizeOpts, -): Promise { - for (let i = 0; i < 9; i++) { - const quality = 100 - i * 10 - const resizeRes = await ImageResizer.createResizedImage( - localUri, - opts.width, - opts.height, - 'JPEG', - quality, - undefined, - undefined, - undefined, - {mode: opts.mode}, - ) - if (resizeRes.size < opts.maxSize) { - return { - path: resizeRes.path, - mime: 'image/jpeg', - size: resizeRes.size, - width: resizeRes.width, - height: resizeRes.height, - } - } - } - throw new Error( - `This image is too big! We couldn't compress it down to ${opts.maxSize} bytes`, - ) -} - -export async function compressIfNeeded( - img: Image, - maxSize: number, -): Promise { - const origUri = `file://${img.path}` - if (img.size < maxSize) { - return img - } - const resizedImage = await resize(origUri, { - width: img.width, - height: img.height, - mode: 'stretch', - maxSize, - }) - const finalImageMovedPath = await moveToPremanantPath(resizedImage.path) - const finalImg = { - ...resizedImage, - path: finalImageMovedPath, - } - return finalImg -} - -export interface Dim { - width: number - height: number -} -export function scaleDownDimensions(dim: Dim, max: Dim): Dim { - if (dim.width < max.width && dim.height < max.height) { - return dim - } - let wScale = dim.width > max.width ? max.width / dim.width : 1 - let hScale = dim.height > max.height ? max.height / dim.height : 1 - if (wScale < hScale) { - return {width: dim.width * wScale, height: dim.height * wScale} - } - return {width: dim.width * hScale, height: dim.height * hScale} -} - -export const saveImageModal = async ({uri}: {uri: string}) => { - const downloadResponse = await RNFetchBlob.config({ - fileCache: true, - }).fetch('GET', uri) - - const imagePath = downloadResponse.path() - const base64Data = await downloadResponse.readFile('base64') - const result = await Share.share({ - url: 'data:image/png;base64,' + base64Data, - }) - if (result.action === Share.sharedAction) { - Toast.show('Image saved to gallery') - } else if (result.action === Share.dismissedAction) { - // dismissed - } - RNFS.unlink(imagePath) -} - -export const moveToPremanantPath = async (path: string) => { - /* - Since this package stores images in a temp directory, we need to move the file to a permanent location. - Relevant: IOS bug when trying to open a second time: - https://github.com/ivpusic/react-native-image-crop-picker/issues/1199 - */ - const filename = uuid.v4() - const destinationPath = `${RNFS.TemporaryDirectoryPath}/${filename}` - RNFS.moveFile(path, destinationPath) - return destinationPath -} diff --git a/src/lib/images.web.ts b/src/lib/images.web.ts deleted file mode 100644 index 4b6d93af2..000000000 --- a/src/lib/images.web.ts +++ /dev/null @@ -1,68 +0,0 @@ -// import {Share} from 'react-native' -// import * as Toast from 'view/com/util/Toast' - -export interface DownloadAndResizeOpts { - uri: string - width: number - height: number - mode: 'contain' | 'cover' | 'stretch' - maxSize: number - timeout: number -} - -export interface Image { - path: string - mime: string - size: number - width: number - height: number -} - -export async function downloadAndResize(_opts: DownloadAndResizeOpts) { - // TODO - throw new Error('TODO') -} - -export interface ResizeOpts { - width: number - height: number - mode: 'contain' | 'cover' | 'stretch' - maxSize: number -} - -export async function resize( - _localUri: string, - _opts: ResizeOpts, -): Promise { - // TODO - throw new Error('TODO') -} - -export async function compressIfNeeded( - _img: Image, - _maxSize: number, -): Promise { - // TODO - throw new Error('TODO') -} - -export interface Dim { - width: number - height: number -} -export function scaleDownDimensions(dim: Dim, max: Dim): Dim { - if (dim.width < max.width && dim.height < max.height) { - return dim - } - let wScale = dim.width > max.width ? max.width / dim.width : 1 - let hScale = dim.height > max.height ? max.height / dim.height : 1 - if (wScale < hScale) { - return {width: dim.width * wScale, height: dim.height * wScale} - } - return {width: dim.width * hScale, height: dim.height * hScale} -} - -export const saveImageModal = async (_opts: {uri: string}) => { - // TODO - throw new Error('TODO') -} diff --git a/src/lib/media/manip.ts b/src/lib/media/manip.ts new file mode 100644 index 000000000..e44ee3907 --- /dev/null +++ b/src/lib/media/manip.ts @@ -0,0 +1,178 @@ +import RNFetchBlob from 'rn-fetch-blob' +import ImageResizer from '@bam.tech/react-native-image-resizer' +import {Image as RNImage, Share} from 'react-native' +import RNFS from 'react-native-fs' +import uuid from 'react-native-uuid' +import * as Toast from 'view/com/util/Toast' + +export interface DownloadAndResizeOpts { + uri: string + width: number + height: number + mode: 'contain' | 'cover' | 'stretch' + maxSize: number + timeout: number +} + +export interface Image { + path: string + mime: string + size: number + width: number + height: number +} + +export async function downloadAndResize(opts: DownloadAndResizeOpts) { + let appendExt = 'jpeg' + try { + const urip = new URL(opts.uri) + const ext = urip.pathname.split('.').pop() + if (ext === 'png') { + appendExt = 'png' + } + } catch (e: any) { + console.error('Invalid URI', opts.uri, e) + return + } + + let downloadRes + try { + const downloadResPromise = RNFetchBlob.config({ + fileCache: true, + appendExt, + }).fetch('GET', opts.uri) + const to1 = setTimeout(() => downloadResPromise.cancel(), opts.timeout) + downloadRes = await downloadResPromise + clearTimeout(to1) + + let localUri = downloadRes.path() + if (!localUri.startsWith('file://')) { + localUri = `file://${localUri}` + } + + return await resize(localUri, opts) + } finally { + if (downloadRes) { + downloadRes.flush() + } + } +} + +export interface ResizeOpts { + width: number + height: number + mode: 'contain' | 'cover' | 'stretch' + maxSize: number +} + +export async function resize( + localUri: string, + opts: ResizeOpts, +): Promise { + for (let i = 0; i < 9; i++) { + const quality = 100 - i * 10 + const resizeRes = await ImageResizer.createResizedImage( + localUri, + opts.width, + opts.height, + 'JPEG', + quality, + undefined, + undefined, + undefined, + {mode: opts.mode}, + ) + if (resizeRes.size < opts.maxSize) { + return { + path: resizeRes.path, + mime: 'image/jpeg', + size: resizeRes.size, + width: resizeRes.width, + height: resizeRes.height, + } + } + } + throw new Error( + `This image is too big! We couldn't compress it down to ${opts.maxSize} bytes`, + ) +} + +export async function compressIfNeeded( + img: Image, + maxSize: number, +): Promise { + const origUri = `file://${img.path}` + if (img.size < maxSize) { + return img + } + const resizedImage = await resize(origUri, { + width: img.width, + height: img.height, + mode: 'stretch', + maxSize, + }) + const finalImageMovedPath = await moveToPremanantPath(resizedImage.path) + const finalImg = { + ...resizedImage, + path: finalImageMovedPath, + } + return finalImg +} + +export interface Dim { + width: number + height: number +} +export function scaleDownDimensions(dim: Dim, max: Dim): Dim { + if (dim.width < max.width && dim.height < max.height) { + return dim + } + let wScale = dim.width > max.width ? max.width / dim.width : 1 + let hScale = dim.height > max.height ? max.height / dim.height : 1 + if (wScale < hScale) { + return {width: dim.width * wScale, height: dim.height * wScale} + } + return {width: dim.width * hScale, height: dim.height * hScale} +} + +export async function saveImageModal({uri}: {uri: string}) { + const downloadResponse = await RNFetchBlob.config({ + fileCache: true, + }).fetch('GET', uri) + + const imagePath = downloadResponse.path() + const base64Data = await downloadResponse.readFile('base64') + const result = await Share.share({ + url: 'data:image/png;base64,' + base64Data, + }) + if (result.action === Share.sharedAction) { + Toast.show('Image saved to gallery') + } else if (result.action === Share.dismissedAction) { + // dismissed + } + RNFS.unlink(imagePath) +} + +export async function moveToPremanantPath(path: string) { + /* + Since this package stores images in a temp directory, we need to move the file to a permanent location. + Relevant: IOS bug when trying to open a second time: + https://github.com/ivpusic/react-native-image-crop-picker/issues/1199 + */ + const filename = uuid.v4() + const destinationPath = `${RNFS.TemporaryDirectoryPath}/${filename}` + RNFS.moveFile(path, destinationPath) + return destinationPath +} + +export function getImageDim(path: string): Promise { + return new Promise((resolve, reject) => { + RNImage.getSize( + path, + (width, height) => { + resolve({width, height}) + }, + reject, + ) + }) +} diff --git a/src/lib/media/manip.web.ts b/src/lib/media/manip.web.ts new file mode 100644 index 000000000..e617d01af --- /dev/null +++ b/src/lib/media/manip.web.ts @@ -0,0 +1,88 @@ +// import {Share} from 'react-native' +// import * as Toast from 'view/com/util/Toast' + +export interface DownloadAndResizeOpts { + uri: string + width: number + height: number + mode: 'contain' | 'cover' | 'stretch' + maxSize: number + timeout: number +} + +export interface Image { + path: string + mime: string + size: number + width: number + height: number +} + +export async function downloadAndResize(_opts: DownloadAndResizeOpts) { + // TODO + throw new Error('TODO') +} + +export interface ResizeOpts { + width: number + height: number + mode: 'contain' | 'cover' | 'stretch' + maxSize: number +} + +export async function resize( + _localUri: string, + _opts: ResizeOpts, +): Promise { + // TODO + throw new Error('TODO') +} + +export async function compressIfNeeded( + img: Image, + maxSize: number, +): Promise { + if (img.size > maxSize) { + // TODO + throw new Error( + "This image is too large and we haven't implemented compression yet -- sorry!", + ) + } + return img +} + +export interface Dim { + width: number + height: number +} +export function scaleDownDimensions(dim: Dim, max: Dim): Dim { + if (dim.width < max.width && dim.height < max.height) { + return dim + } + let wScale = dim.width > max.width ? max.width / dim.width : 1 + let hScale = dim.height > max.height ? max.height / dim.height : 1 + if (wScale < hScale) { + return {width: dim.width * wScale, height: dim.height * wScale} + } + return {width: dim.width * hScale, height: dim.height * hScale} +} + +export async function saveImageModal(_opts: {uri: string}) { + // TODO + throw new Error('TODO') +} + +export async function moveToPremanantPath(path: string) { + return path +} + +export async function getImageDim(path: string): Promise { + var img = document.createElement('img') + const promise = new Promise((resolve, reject) => { + img.onload = resolve + img.onerror = reject + }) + img.src = path + await promise + return {width: img.width, height: img.height} +} diff --git a/src/lib/media/picker.tsx b/src/lib/media/picker.tsx new file mode 100644 index 000000000..940366035 --- /dev/null +++ b/src/lib/media/picker.tsx @@ -0,0 +1,141 @@ +import { + openPicker as openPickerFn, + openCamera as openCameraFn, + openCropper as openCropperFn, + ImageOrVideo, +} from 'react-native-image-crop-picker' +import {RootStoreModel} from 'state/index' +import {PickerOpts, CameraOpts, CropperOpts, PickedMedia} from './types' +import { + scaleDownDimensions, + Dim, + compressIfNeeded, + moveToPremanantPath, +} from 'lib/media/manip' +export type {PickedMedia} from './types' + +/** + * NOTE + * These methods all include the RootStoreModel as the first param + * because the web versions require it. The signatures have to remain + * equivalent between the different forms, but the store param is not + * used here. + * -prf + */ + +export async function openPicker( + _store: RootStoreModel, + opts: PickerOpts, +): Promise { + const mediaType = opts.mediaType || 'photo' + const items = await openPickerFn({ + mediaType, + multiple: opts.multiple, + maxFiles: opts.maxFiles, + }) + const toMedia = (item: ImageOrVideo) => ({ + mediaType, + path: item.path, + mime: item.mime, + size: item.size, + width: item.width, + height: item.height, + }) + if (Array.isArray(items)) { + return items.map(toMedia) + } + return [toMedia(items)] +} + +export async function openCamera( + _store: RootStoreModel, + opts: CameraOpts, +): Promise { + const mediaType = opts.mediaType || 'photo' + const item = await openCameraFn({ + mediaType, + width: opts.width, + height: opts.height, + freeStyleCropEnabled: opts.freeStyleCropEnabled, + cropperCircleOverlay: opts.cropperCircleOverlay, + cropping: true, + forceJpg: true, // ios only + compressImageQuality: 1.0, + }) + return { + mediaType, + path: item.path, + mime: item.mime, + size: item.size, + width: item.width, + height: item.height, + } +} + +export async function openCropper( + _store: RootStoreModel, + opts: CropperOpts, +): Promise { + const mediaType = opts.mediaType || 'photo' + const item = await openCropperFn({ + path: opts.path, + mediaType: opts.mediaType || 'photo', + width: opts.width, + height: opts.height, + freeStyleCropEnabled: opts.freeStyleCropEnabled, + cropperCircleOverlay: opts.cropperCircleOverlay, + forceJpg: true, // ios only + compressImageQuality: 1.0, + }) + return { + mediaType, + path: item.path, + mime: item.mime, + size: item.size, + width: item.width, + height: item.height, + } +} + +export async function pickImagesFlow( + store: RootStoreModel, + maxFiles: number, + maxDim: Dim, + maxSize: number, +) { + const items = await openPicker(store, { + multiple: true, + maxFiles, + mediaType: 'photo', + }) + const result = [] + for (const image of items) { + result.push( + await cropAndCompressFlow(store, image.path, image, maxDim, maxSize), + ) + } + return result +} + +export async function cropAndCompressFlow( + store: RootStoreModel, + path: string, + imgDim: Dim, + maxDim: Dim, + maxSize: number, +) { + // choose target dimensions based on the original + // this causes the photo cropper to start with the full image "selected" + const {width, height} = scaleDownDimensions(imgDim, maxDim) + const cropperRes = await openCropper(store, { + mediaType: 'photo', + path, + freeStyleCropEnabled: true, + width, + height, + }) + + const img = await compressIfNeeded(cropperRes, maxSize) + const permanentPath = await moveToPremanantPath(img.path) + return permanentPath +} diff --git a/src/lib/media/picker.web.tsx b/src/lib/media/picker.web.tsx new file mode 100644 index 000000000..aaa084634 --- /dev/null +++ b/src/lib/media/picker.web.tsx @@ -0,0 +1,143 @@ +/// + +import {CropImageModal} from 'state/models/shell-ui' +import {PickerOpts, CameraOpts, CropperOpts, PickedMedia} from './types' +export type {PickedMedia} from './types' +import {RootStoreModel} from 'state/index' +import { + scaleDownDimensions, + getImageDim, + Dim, + compressIfNeeded, + moveToPremanantPath, +} from 'lib/media/manip' + +interface PickedFile { + uri: string + path: string + size: number +} + +export async function openPicker( + _store: RootStoreModel, + opts: PickerOpts, +): Promise { + const res = await selectFile(opts) + const dim = await getImageDim(res.uri) + const mime = extractDataUriMime(res.uri) + return [ + { + mediaType: 'photo', + path: res.uri, + mime, + size: res.size, + width: dim.width, + height: dim.height, + }, + ] +} + +export async function openCamera( + _store: RootStoreModel, + _opts: CameraOpts, +): Promise { + // const mediaType = opts.mediaType || 'photo' TODO + throw new Error('TODO') +} + +export async function openCropper( + store: RootStoreModel, + opts: CropperOpts, +): Promise { + // TODO handle more opts + return new Promise((resolve, reject) => { + store.shell.openModal( + new CropImageModal(opts.path, (img?: PickedMedia) => { + if (img) { + resolve(img) + } else { + reject(new Error('Canceled')) + } + }), + ) + }) +} + +export async function pickImagesFlow( + store: RootStoreModel, + maxFiles: number, + maxDim: Dim, + maxSize: number, +) { + const items = await openPicker(store, { + multiple: true, + maxFiles, + mediaType: 'photo', + }) + const result = [] + for (const image of items) { + result.push( + await cropAndCompressFlow(store, image.path, image, maxDim, maxSize), + ) + } + return result +} + +export async function cropAndCompressFlow( + store: RootStoreModel, + path: string, + imgDim: Dim, + maxDim: Dim, + maxSize: number, +) { + // choose target dimensions based on the original + // this causes the photo cropper to start with the full image "selected" + const {width, height} = scaleDownDimensions(imgDim, maxDim) + const cropperRes = await openCropper(store, { + mediaType: 'photo', + path, + freeStyleCropEnabled: true, + width, + height, + }) + + const img = await compressIfNeeded(cropperRes, maxSize) + const permanentPath = await moveToPremanantPath(img.path) + return permanentPath +} + +// helpers +// = + +function selectFile(opts: PickerOpts): Promise { + return new Promise((resolve, reject) => { + var input = document.createElement('input') + input.type = 'file' + input.accept = opts.mediaType === 'photo' ? 'image/*' : '*/*' + input.onchange = e => { + const target = e.target as HTMLInputElement + const file = target?.files?.[0] + if (!file) { + return reject(new Error('Canceled')) + } + + var reader = new FileReader() + reader.readAsDataURL(file) + reader.onload = readerEvent => { + if (!readerEvent.target) { + return reject(new Error('Canceled')) + } + resolve({ + uri: readerEvent.target.result as string, + path: file.name, + size: file.size, + }) + } + } + input.click() + }) +} + +function extractDataUriMime(uri: string): string { + return uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')) +} diff --git a/src/lib/media/types.ts b/src/lib/media/types.ts new file mode 100644 index 000000000..3197b4d3e --- /dev/null +++ b/src/lib/media/types.ts @@ -0,0 +1,31 @@ +export interface PickerOpts { + mediaType?: 'photo' + multiple?: boolean + maxFiles?: number +} + +export interface CameraOpts { + mediaType?: 'photo' + width: number + height: number + freeStyleCropEnabled?: boolean + cropperCircleOverlay?: boolean +} + +export interface CropperOpts { + path: string + mediaType?: 'photo' + width: number + height: number + freeStyleCropEnabled?: boolean + cropperCircleOverlay?: boolean +} + +export interface PickedMedia { + mediaType: 'photo' + path: string + mime: string + size: number + width: number + height: number +} -- cgit 1.4.1 From 154c34e915231a03e289dd36294592911d9c9900 Mon Sep 17 00:00:00 2001 From: Paul Frazee Date: Thu, 23 Feb 2023 17:22:03 -0600 Subject: Rework modals to support multiple active --- src/lib/media/picker.web.tsx | 11 +-- src/state/models/shell-ui.ts | 117 ++++++++++----------------- src/view/com/lightbox/ImageViewing/index.tsx | 4 +- src/view/com/login/CreateAccount.tsx | 7 +- src/view/com/login/Signin.tsx | 6 +- src/view/com/modals/Modal.tsx | 51 ++++-------- src/view/com/modals/Modal.web.tsx | 73 ++++++++--------- src/view/com/profile/ProfileHeader.tsx | 17 ++-- src/view/com/util/UserAvatar.tsx | 3 +- src/view/com/util/UserBanner.tsx | 3 +- src/view/com/util/forms/DropdownButton.tsx | 30 ++++--- src/view/shell/mobile/index.tsx | 6 +- src/view/shell/web/index.tsx | 6 +- 13 files changed, 147 insertions(+), 187 deletions(-) (limited to 'src/lib') diff --git a/src/lib/media/picker.web.tsx b/src/lib/media/picker.web.tsx index aaa084634..746feaedd 100644 --- a/src/lib/media/picker.web.tsx +++ b/src/lib/media/picker.web.tsx @@ -1,6 +1,5 @@ /// -import {CropImageModal} from 'state/models/shell-ui' import {PickerOpts, CameraOpts, CropperOpts, PickedMedia} from './types' export type {PickedMedia} from './types' import {RootStoreModel} from 'state/index' @@ -51,15 +50,17 @@ export async function openCropper( ): Promise { // TODO handle more opts return new Promise((resolve, reject) => { - store.shell.openModal( - new CropImageModal(opts.path, (img?: PickedMedia) => { + store.shell.openModal({ + name: 'crop-image', + uri: opts.path, + onSelect: (img?: PickedMedia) => { if (img) { resolve(img) } else { reject(new Error('Canceled')) } - }), - ) + }, + }) }) } diff --git a/src/state/models/shell-ui.ts b/src/state/models/shell-ui.ts index b9f480ecd..640bed0b3 100644 --- a/src/state/models/shell-ui.ts +++ b/src/state/models/shell-ui.ts @@ -2,75 +2,57 @@ import {RootStoreModel} from './root-store' import {makeAutoObservable} from 'mobx' import {ProfileViewModel} from './profile-view' import {isObj, hasProp} from 'lib/type-guards' -import {PickedMedia} from 'view/com/util/images/image-crop-picker/types' +import {PickedMedia} from 'lib/media/types' -export class ConfirmModal { - name = 'confirm' - - constructor( - public title: string, - public message: string | (() => JSX.Element), - public onPressConfirm: () => void | Promise, - ) { - makeAutoObservable(this) - } +export interface ConfirmModal { + name: 'confirm' + title: string + message: string | (() => JSX.Element) + onPressConfirm: () => void | Promise } -export class EditProfileModal { - name = 'edit-profile' - - constructor( - public profileView: ProfileViewModel, - public onUpdate?: () => void, - ) { - makeAutoObservable(this) - } +export interface EditProfileModal { + name: 'edit-profile' + profileView: ProfileViewModel + onUpdate?: () => void } -export class ServerInputModal { - name = 'server-input' - - constructor( - public initialService: string, - public onSelect: (url: string) => void, - ) { - makeAutoObservable(this) - } +export interface ServerInputModal { + name: 'server-input' + initialService: string + onSelect: (url: string) => void } -export class ReportPostModal { - name = 'report-post' - - constructor(public postUri: string, public postCid: string) { - makeAutoObservable(this) - } +export interface ReportPostModal { + name: 'report-post' + postUri: string + postCid: string } -export class ReportAccountModal { - name = 'report-account' - - constructor(public did: string) { - makeAutoObservable(this) - } +export interface ReportAccountModal { + name: 'report-account' + did: string } -export class CropImageModal { - name = 'crop-image' - - constructor( - public uri: string, - public onSelect: (img?: PickedMedia) => void, - ) {} +export interface CropImageModal { + name: 'crop-image' + uri: string + onSelect: (img?: PickedMedia) => void } -export class DeleteAccountModal { - name = 'delete-account' - - constructor() { - makeAutoObservable(this) - } +export interface DeleteAccountModal { + name: 'delete-account' } +export type Modal = + | ConfirmModal + | EditProfileModal + | ServerInputModal + | ReportPostModal + | ReportAccountModal + | CropImageModal + | DeleteAccountModal + interface LightboxModel {} export class ProfileImageLightbox implements LightboxModel { @@ -111,15 +93,7 @@ export class ShellUiModel { minimalShellMode = false isMainMenuOpen = false isModalActive = false - activeModal: - | ConfirmModal - | EditProfileModal - | ServerInputModal - | ReportPostModal - | ReportAccountModal - | CropImageModal - | DeleteAccountModal - | undefined + activeModals: Modal[] = [] isLightboxActive = false activeLightbox: ProfileImageLightbox | ImagesLightbox | undefined isComposerActive = false @@ -159,24 +133,15 @@ export class ShellUiModel { this.isMainMenuOpen = v } - openModal( - modal: - | ConfirmModal - | EditProfileModal - | ServerInputModal - | ReportPostModal - | ReportAccountModal - | CropImageModal - | DeleteAccountModal, - ) { + openModal(modal: Modal) { this.rootStore.emitNavigation() this.isModalActive = true - this.activeModal = modal + this.activeModals.push(modal) } closeModal() { - this.isModalActive = false - this.activeModal = undefined + this.activeModals.pop() + this.isModalActive = this.activeModals.length > 0 } openLightbox(lightbox: ProfileImageLightbox | ImagesLightbox) { diff --git a/src/view/com/lightbox/ImageViewing/index.tsx b/src/view/com/lightbox/ImageViewing/index.tsx index 83259330f..722540a58 100644 --- a/src/view/com/lightbox/ImageViewing/index.tsx +++ b/src/view/com/lightbox/ImageViewing/index.tsx @@ -17,7 +17,7 @@ import { VirtualizedList, ModalProps, } from 'react-native' -import {Modal} from '../../modals/Modal' +import {ModalsContainer} from '../../modals/Modal' import ImageItem from './components/ImageItem/ImageItem' import ImageDefaultHeader from './components/ImageDefaultHeader' @@ -98,7 +98,7 @@ function ImageViewing({ return ( - + {typeof HeaderComponent !== 'undefined' ? ( diff --git a/src/view/com/login/CreateAccount.tsx b/src/view/com/login/CreateAccount.tsx index 6dc93f5e3..870013f3b 100644 --- a/src/view/com/login/CreateAccount.tsx +++ b/src/view/com/login/CreateAccount.tsx @@ -25,7 +25,6 @@ import {makeValidHandle, createFullHandle} from 'lib/strings/handles' import {toNiceDomain} from 'lib/strings/url-helpers' import {useStores, DEFAULT_SERVICE} from 'state/index' import {ServiceDescription} from 'state/models/session' -import {ServerInputModal} from 'state/models/shell-ui' import {usePalette} from 'lib/hooks/usePalette' import {cleanError} from 'lib/strings/errors' @@ -84,7 +83,11 @@ export const CreateAccount = ({onPressBack}: {onPressBack: () => void}) => { const onPressRetryConnect = () => setRetryDescribeTrigger({}) const onPressSelectService = () => { - store.shell.openModal(new ServerInputModal(serviceUrl, setServiceUrl)) + store.shell.openModal({ + name: 'server-input', + initialService: serviceUrl, + onSelect: setServiceUrl, + }) Keyboard.dismiss() } diff --git a/src/view/com/login/Signin.tsx b/src/view/com/login/Signin.tsx index eed173119..a311e2999 100644 --- a/src/view/com/login/Signin.tsx +++ b/src/view/com/login/Signin.tsx @@ -279,7 +279,11 @@ const LoginForm = ({ const [password, setPassword] = useState('') const onPressSelectService = () => { - store.shell.openModal(new ServerInputModal(serviceUrl, setServiceUrl)) + store.shell.openModal({ + name: 'server-input', + initialService: serviceUrl, + onSelect: setServiceUrl, + }) Keyboard.dismiss() track('Signin:PressedSelectService') } diff --git a/src/view/com/modals/Modal.tsx b/src/view/com/modals/Modal.tsx index 2529d0d5b..d4c8ada69 100644 --- a/src/view/com/modals/Modal.tsx +++ b/src/view/com/modals/Modal.tsx @@ -5,8 +5,6 @@ import BottomSheet from '@gorhom/bottom-sheet' import {useStores} from 'state/index' import {createCustomBackdrop} from '../util/BottomSheetCustomBackdrop' -import * as models from 'state/models/shell-ui' - import * as ConfirmModal from './Confirm' import * as EditProfileModal from './EditProfile' import * as ServerInputModal from './ServerInput' @@ -32,52 +30,37 @@ export const Modal = observer(function Modal() { store.shell.closeModal() } + const activeModal = React.useMemo( + () => store.shell.activeModals.at(-1), + [store.shell.activeModals], + ) + useEffect(() => { if (store.shell.isModalActive) { bottomSheetRef.current?.expand() } else { bottomSheetRef.current?.close() } - }, [store.shell.isModalActive, bottomSheetRef, store.shell.activeModal?.name]) + }, [store.shell.isModalActive, bottomSheetRef, activeModal?.name]) let snapPoints: (string | number)[] = CLOSED_SNAPPOINTS let element - if (store.shell.activeModal?.name === 'confirm') { + if (activeModal?.name === 'confirm') { snapPoints = ConfirmModal.snapPoints - element = ( - - ) - } else if (store.shell.activeModal?.name === 'edit-profile') { + element = + } else if (activeModal?.name === 'edit-profile') { snapPoints = EditProfileModal.snapPoints - element = ( - - ) - } else if (store.shell.activeModal?.name === 'server-input') { + element = + } else if (activeModal?.name === 'server-input') { snapPoints = ServerInputModal.snapPoints - element = ( - - ) - } else if (store.shell.activeModal?.name === 'report-post') { + element = + } else if (activeModal?.name === 'report-post') { snapPoints = ReportPostModal.snapPoints - element = ( - - ) - } else if (store.shell.activeModal?.name === 'report-account') { + element = + } else if (activeModal?.name === 'report-account') { snapPoints = ReportAccountModal.snapPoints - element = ( - - ) - } else if (store.shell.activeModal?.name === 'delete-account') { + element = + } else if (activeModal?.name === 'delete-account') { snapPoints = DeleteAccountModal.snapPoints element = } else { diff --git a/src/view/com/modals/Modal.web.tsx b/src/view/com/modals/Modal.web.tsx index 2af02695a..38b526d29 100644 --- a/src/view/com/modals/Modal.web.tsx +++ b/src/view/com/modals/Modal.web.tsx @@ -3,8 +3,7 @@ import {TouchableWithoutFeedback, StyleSheet, View} from 'react-native' import {observer} from 'mobx-react-lite' import {useStores} from 'state/index' import {usePalette} from 'lib/hooks/usePalette' - -import * as models from 'state/models/shell-ui' +import type {Modal as ModalIface} from 'state/models/shell-ui' import * as ConfirmModal from './Confirm' import * as EditProfileModal from './EditProfile' @@ -13,7 +12,23 @@ import * as ReportPostModal from './ReportPost' import * as ReportAccountModal from './ReportAccount' import * as CropImageModal from './crop-image/CropImage.web' -export const Modal = observer(function Modal() { +export const ModalsContainer = observer(function ModalsContainer() { + const store = useStores() + + if (!store.shell.isModalActive) { + return null + } + + return ( + <> + {store.shell.activeModals.map((modal, i) => ( + + ))} + + ) +}) + +function Modal({modal}: {modal: ModalIface}) { const store = useStores() const pal = usePalette('default') @@ -22,7 +37,7 @@ export const Modal = observer(function Modal() { } const onPressMask = () => { - if (store.shell.activeModal?.name === 'crop-image') { + if (modal.name === 'crop-image') { return // dont close on mask presses during crop } store.shell.closeModal() @@ -32,42 +47,18 @@ export const Modal = observer(function Modal() { } let element - if (store.shell.activeModal?.name === 'confirm') { - element = ( - - ) - } else if (store.shell.activeModal?.name === 'edit-profile') { - element = ( - - ) - } else if (store.shell.activeModal?.name === 'server-input') { - element = ( - - ) - } else if (store.shell.activeModal?.name === 'report-post') { - element = ( - - ) - } else if (store.shell.activeModal?.name === 'report-account') { - element = ( - - ) - } else if (store.shell.activeModal?.name === 'crop-image') { - element = ( - - ) + if (modal.name === 'confirm') { + element = + } else if (modal.name === 'edit-profile') { + element = + } else if (modal.name === 'server-input') { + element = + } else if (modal.name === 'report-post') { + element = + } else if (modal.name === 'report-account') { + element = + } else if (modal.name === 'crop-image') { + element = } else { return null } @@ -81,7 +72,7 @@ export const Modal = observer(function Modal() { ) -}) +} const styles = StyleSheet.create({ mask: { diff --git a/src/view/com/profile/ProfileHeader.tsx b/src/view/com/profile/ProfileHeader.tsx index 0ca6e1e74..087b1f39b 100644 --- a/src/view/com/profile/ProfileHeader.tsx +++ b/src/view/com/profile/ProfileHeader.tsx @@ -15,11 +15,7 @@ import { import {BlurView} from '../util/BlurView' import {ProfileViewModel} from 'state/models/profile-view' import {useStores} from 'state/index' -import { - EditProfileModal, - ReportAccountModal, - ProfileImageLightbox, -} from 'state/models/shell-ui' +import {ProfileImageLightbox} from 'state/models/shell-ui' import {pluralize} from 'lib/strings/helpers' import {toShareUrl} from 'lib/strings/url-helpers' import {s, gradients} from 'lib/styles' @@ -65,7 +61,11 @@ export const ProfileHeader = observer(function ProfileHeader({ } const onPressEditProfile = () => { track('ProfileHeader:EditProfileButtonClicked') - store.shell.openModal(new EditProfileModal(view, onRefreshAll)) + store.shell.openModal({ + name: 'edit-profile', + profileView: view, + onUpdate: onRefreshAll, + }) } const onPressFollowers = () => { track('ProfileHeader:FollowersButtonClicked') @@ -101,7 +101,10 @@ export const ProfileHeader = observer(function ProfileHeader({ } const onPressReportAccount = () => { track('ProfileHeader:ReportAccountButtonClicked') - store.shell.openModal(new ReportAccountModal(view.did)) + store.shell.openModal({ + name: 'report-account', + did: view.did, + }) } // loading diff --git a/src/view/com/util/UserAvatar.tsx b/src/view/com/util/UserAvatar.tsx index 0c5c9d254..5a7a4801d 100644 --- a/src/view/com/util/UserAvatar.tsx +++ b/src/view/com/util/UserAvatar.tsx @@ -18,6 +18,7 @@ import {useStores} from 'state/index' import {colors, gradients} from 'lib/styles' import {DropdownButton} from './forms/DropdownButton' import {usePalette} from 'lib/hooks/usePalette' +import {isWeb} from 'platform/detection' export function UserAvatar({ size, @@ -58,7 +59,7 @@ export function UserAvatar({ ) const dropdownItems = [ - { + !isWeb && { label: 'Camera', icon: 'camera' as IconProp, onPress: async () => { diff --git a/src/view/com/util/UserBanner.tsx b/src/view/com/util/UserBanner.tsx index c17294f3d..06a80d45b 100644 --- a/src/view/com/util/UserBanner.tsx +++ b/src/view/com/util/UserBanner.tsx @@ -18,6 +18,7 @@ import { } from 'lib/permissions' import {DropdownButton} from './forms/DropdownButton' import {usePalette} from 'lib/hooks/usePalette' +import {isWeb} from 'platform/detection' export function UserBanner({ banner, @@ -29,7 +30,7 @@ export function UserBanner({ const store = useStores() const pal = usePalette('default') const dropdownItems = [ - { + !isWeb && { label: 'Camera', icon: 'camera' as IconProp, onPress: async () => { diff --git a/src/view/com/util/forms/DropdownButton.tsx b/src/view/com/util/forms/DropdownButton.tsx index 8fddd5941..2946c5ca0 100644 --- a/src/view/com/util/forms/DropdownButton.tsx +++ b/src/view/com/util/forms/DropdownButton.tsx @@ -16,7 +16,6 @@ import {Button, ButtonType} from './Button' import {colors} from 'lib/styles' import {toShareUrl} from 'lib/strings/url-helpers' import {useStores} from 'state/index' -import {ReportPostModal, ConfirmModal} from 'state/models/shell-ui' import {TABS_ENABLED} from 'lib/build-flags' import {usePalette} from 'lib/hooks/usePalette' import {useTheme} from 'lib/ThemeContext' @@ -28,6 +27,7 @@ export interface DropdownItem { label: string onPress: () => void } +type MaybeDropdownItem = DropdownItem | false | undefined export type DropdownButtonType = ButtonType | 'bare' @@ -44,7 +44,7 @@ export function DropdownButton({ }: { type?: DropdownButtonType style?: StyleProp - items: DropdownItem[] + items: MaybeDropdownItem[] label?: string menuWidth?: number children?: React.ReactNode @@ -71,7 +71,12 @@ export function DropdownButton({ ? pageX + width + rightOffset : pageX + width - menuWidth const newY = pageY + height + bottomOffset - createDropdownMenu(newX, newY, menuWidth, items) + createDropdownMenu( + newX, + newY, + menuWidth, + items.filter(v => !!v) as DropdownItem[], + ) }, ) } @@ -151,7 +156,11 @@ export function PostDropdownBtn({ icon: 'circle-exclamation', label: 'Report post', onPress() { - store.shell.openModal(new ReportPostModal(itemUri, itemCid)) + store.shell.openModal({ + name: 'report-post', + postUri: itemUri, + postCid: itemCid, + }) }, }, isAuthor @@ -159,13 +168,12 @@ export function PostDropdownBtn({ icon: ['far', 'trash-can'], label: 'Delete post', onPress() { - store.shell.openModal( - new ConfirmModal( - 'Delete this post?', - 'Are you sure? This can not be undone.', - onDeletePost, - ), - ) + store.shell.openModal({ + name: 'confirm', + title: 'Delete this post?', + message: 'Are you sure? This can not be undone.', + onPressConfirm: onDeletePost, + }) }, } : undefined, diff --git a/src/view/shell/mobile/index.tsx b/src/view/shell/mobile/index.tsx index 0b3921b7e..da8e73a60 100644 --- a/src/view/shell/mobile/index.tsx +++ b/src/view/shell/mobile/index.tsx @@ -28,7 +28,7 @@ import {Login} from '../../screens/Login' import {Menu} from './Menu' import {Onboard} from '../../screens/Onboard' import {HorzSwipe} from '../../com/util/gestures/HorzSwipe' -import {Modal} from '../../com/modals/Modal' +import {ModalsContainer} from '../../com/modals/Modal' import {Lightbox} from '../../com/lightbox/Lightbox' import {Text} from '../../com/util/text/Text' import {ErrorBoundary} from '../../com/util/ErrorBoundary' @@ -366,7 +366,7 @@ export const MobileShell: React.FC = observer(() => { return ( - + ) } @@ -515,7 +515,7 @@ export const MobileShell: React.FC = observer(() => { notificationCount={store.me.notifications.unreadCount} /> - + { return ( - + ) } @@ -67,7 +67,7 @@ export const WebShell: React.FC = observer(() => { imagesOpen={store.shell.composerOpts?.imagesOpen} onPost={store.shell.composerOpts?.onPost} /> - + ) -- cgit 1.4.1