Skip to content

Commit

Permalink
improvement(useimage): add method of useImage
Browse files Browse the repository at this point in the history
  • Loading branch information
innocces committed Jul 27, 2021
1 parent 53b5dfd commit 4d6979a
Show file tree
Hide file tree
Showing 4 changed files with 182 additions and 9 deletions.
13 changes: 13 additions & 0 deletions packages/app/src/pages/useImage/index.less
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.taro-hooks {
&-swiper {
width: 100%;
height: 300px;
margin-bottom: 20px;
background-color: #6190e8;
}

&-image {
display: block;
margin: 0 auto;
}
}
78 changes: 74 additions & 4 deletions packages/app/src/pages/useImage/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,58 @@
import React, { useCallback } from 'react';
import { AtButton } from 'taro-ui';
import React, { useCallback, useState } from 'react';
import { AtButton, AtFloatLayout, AtList, AtListItem } from 'taro-ui';
import DocPage from '@components/DocPage';
import { Swiper, SwiperItem, Image } from '@tarojs/components';

import { useImage } from 'taro-hooks';
import { useImage, useEnv } from 'taro-hooks';
import { ENV_TYPE } from '@tarojs/taro';

import './index.less';

export default () => {
const [fileInfo, { choose, preview, save }] = useImage({});
const [open, changeOpen] = useState<boolean>(false);
const [imageInfo, setImageInfo] = useState({});
const env = useEnv();
const [
fileInfo,
{ choose, chooseMessageFile, preview, save, getInfo, compress },
] = useImage({
count: 15,
});

const getImageInfo = useCallback(
async (src: string) => {
const info = await getInfo(src);
setImageInfo(info);
changeOpen(true);
},
[getInfo],
);

const getMessageFileInfo = useCallback(async () => {
const info = await chooseMessageFile(1);
setImageInfo(info.tempFiles[0]);
changeOpen(true);
}, [chooseMessageFile]);

const compressInfo = useCallback(
async (src: string) => {
const info = await compress(src);
setImageInfo(info);
changeOpen(true);
},
[compress],
);

return (
<>
<DocPage title="useImage 图片" panelTitle="useImage">
<Swiper className="taro-hooks-swiper" autoplay>
{(fileInfo.tempFilePaths || []).map((v: string) => (
<SwiperItem key={v}>
<Image className="taro-hooks-image" mode="aspectFit" src={v} />
</SwiperItem>
))}
</Swiper>
<AtButton onClick={() => choose()}>选择图片</AtButton>
<AtButton
disabled={!fileInfo.tempFilePaths}
Expand All @@ -24,6 +67,33 @@ export default () => {
>
保存图片
</AtButton>
<AtButton
className="gap"
disabled={!fileInfo.tempFilePaths}
onClick={() => getImageInfo(fileInfo.tempFilePaths[0])}
>
获取图片信息
</AtButton>
<AtButton
disabled={env !== ENV_TYPE.WEAPP}
onClick={getMessageFileInfo}
>
获取会话文件(仅小程序)
</AtButton>
<AtButton
className="gap"
disabled={!fileInfo.tempFilePaths}
onClick={() => compressInfo(fileInfo.tempFilePaths[0])}
>
压缩图片
</AtButton>
<AtFloatLayout isOpened={open} onClose={() => changeOpen(false)}>
<AtList>
{Object.entries(imageInfo).map(([key, value]) => (
<AtListItem key={key} title={key} note={String(value)} />
))}
</AtList>
</AtFloatLayout>
</DocPage>
</>
);
Expand Down
99 changes: 95 additions & 4 deletions packages/hooks/src/useImage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
General,
ENV_TYPE,
} from '@tarojs/taro';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useState } from 'react';
import { useEnv } from '..';
import { saveImageForH5 } from './utils';

Expand All @@ -26,10 +26,25 @@ export type PreviewImageAction = (
option: PreviewImageOption,
) => Promise<General.CallbackResult>;

export type saveImageToPhotosAlbumAction = (
export type SaveImageToPhotosAlbumAction = (
filePath: string,
) => Promise<General.CallbackResult>;

export type GetImageInfoAction = (
src: string,
) => Promise<getImageInfo.SuccessCallbackResult>;

export type ChooseMessageFileAction = (
count: number,
type?: Pick<chooseMessageFile.Option, 'type'>,
extend?: Pick<chooseMessageFile.Option, 'extension'>,
) => Promise<chooseMessageFile.SuccessCallbackResult>;

export type CompressImageAction = (
src: string,
quality?: number,
) => Promise<compressImage.SuccessCallbackResult>;

export type IFileInfo = Partial<
Pick<chooseImage.SuccessCallbackResult, 'tempFilePaths' | 'tempFiles'>
>;
Expand All @@ -38,8 +53,11 @@ export type IOptions = ChooseImageOption;

export interface IAction {
choose: ChooseImageAction;
chooseMessageFile: ChooseMessageFileAction;
preview: PreviewImageAction;
save: saveImageToPhotosAlbumAction;
save: SaveImageToPhotosAlbumAction;
getInfo: GetImageInfoAction;
compress: CompressImageAction;
}

function useImage(options: IOptions): [IFileInfo, IAction] {
Expand Down Expand Up @@ -91,7 +109,7 @@ function useImage(options: IOptions): [IFileInfo, IAction] {
});
}, []);

const saveImageToPhotosAlbumAsync = useCallback<saveImageToPhotosAlbumAction>(
const saveImageToPhotosAlbumAsync = useCallback<SaveImageToPhotosAlbumAction>(
(filePath) => {
return new Promise(async (resolve, reject) => {
if (!filePath) {
Expand Down Expand Up @@ -123,12 +141,85 @@ function useImage(options: IOptions): [IFileInfo, IAction] {
[env],
);

const getImageInfoAsync = useCallback<GetImageInfoAction>((src) => {
return new Promise((resolve, reject) => {
if (!src) {
reject('please enter a valid path');
} else {
try {
getImageInfo({
src,
success: resolve,
fail: reject,
}).catch(reject);
} catch (e) {
reject(e);
}
}
});
}, []);

const chooseMessageFileAsync = useCallback<ChooseMessageFileAction>(
(count, type, extension) => {
return new Promise((resolve, reject) => {
if (!count || env !== ENV_TYPE.WEAPP) {
reject('you must provide count');
} else {
try {
const payload = Object.fromEntries(
[
['type', type],
['extension', extension],
].filter((v) => v[1]) || [],
);
chooseMessageFile({
count,
...payload,
success: resolve,
fail: reject,
});
} catch (e) {
reject(e);
}
}
});
},
[env],
);

const compressImageAsync = useCallback<CompressImageAction>(
(src, quality) => {
return new Promise((resolve, reject) => {
if (!src) {
reject('you must provide src');
}
try {
if (env === ENV_TYPE.WEB) {
} else {
compressImage({
src,
...(quality ? { quality } : {}),
success: resolve,
fail: reject,
}).catch(reject);
}
} catch (e) {
reject(e);
}
});
},
[env],
);

return [
fileInfo,
{
choose: chooseImageAsync,
chooseMessageFile: chooseMessageFileAsync,
preview: previewImageAsync,
save: saveImageToPhotosAlbumAsync,
getInfo: getImageInfoAsync,
compress: compressImageAsync,
},
];
}
Expand Down
1 change: 0 additions & 1 deletion packages/hooks/src/useImage/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ export const saveImageForH5 = async (filePath: string) => {
let result = true;
try {
const responese = await fetch(filePath);
console.log(responese);
const blob = await responese.blob();
const blobInstance = new Blob([blob], {
type: 'application/octet-stream',
Expand Down

0 comments on commit 4d6979a

Please sign in to comment.