diff --git a/common/src/main/ets/default/model/browser/AlbumDefine.ts b/common/src/main/ets/default/model/browser/AlbumDefine.ts index e9bca9ef..c68ed6d3 100644 --- a/common/src/main/ets/default/model/browser/AlbumDefine.ts +++ b/common/src/main/ets/default/model/browser/AlbumDefine.ts @@ -12,8 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import userFileManager from '@ohos.filemanagement.userFileManager'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; import type { FetchOptions } from '../../access/UserFileManagerAccess'; - import { AlbumFetchOptionBuilder, FileFetchOptionBuilder, @@ -50,6 +51,22 @@ export class AlbumDefine { return builder.build(); } + static getFileFetchOptWithEmptyColumn(startIndex?: number, count?: number, filterMediaType?: string): FetchOptions { + let fetchOption: userFileManager.FetchOptions = { + predicates: new dataSharePredicates.DataSharePredicates(), + fetchColumns: [] + }; + let builder = new FileFetchOptionBuilder(fetchOption); + builder.order(UserFileManagerAccess.FILE_KEY_DATE_TAKEN.toString(), false); + if (filterMediaType) { + AlbumDefine.setFilterMediaType(builder, filterMediaType); + } + if (startIndex != undefined && count != undefined && startIndex >= 0 && count >= 0) { + builder.select(startIndex, count); + } + return builder.build(); + } + static getFavoriteFetchOpt(filterMediaType?: string) { let builder = new FileFetchOptionBuilder(); if (filterMediaType == undefined) { diff --git a/common/src/main/ets/default/model/browser/BrowserDataImpl.ts b/common/src/main/ets/default/model/browser/BrowserDataImpl.ts index 95e57a35..3459aa53 100644 --- a/common/src/main/ets/default/model/browser/BrowserDataImpl.ts +++ b/common/src/main/ets/default/model/browser/BrowserDataImpl.ts @@ -85,6 +85,16 @@ export abstract class BrowserDataImpl implements BrowserDataInterface { return result; } + async getItemsCountOfAlbum(album: Album, filterMediaType?: string): Promise { + let count = 0; + // 当前相册count始终为0,先通过查全部图片获取count + let fetchOpt = AlbumDefine.getFileFetchOptWithEmptyColumn(Constants.INVALID, Constants.INVALID, filterMediaType); + let fetchResult = await album.getPhotoAssets(fetchOpt); + count = fetchResult.getCount(); + fetchResult.close(); + return count; + } + async getItemsCount(albumUri?: string, filterMediaType?: string): Promise { let count = 0; if (albumUri) { @@ -132,7 +142,6 @@ export abstract class BrowserDataImpl implements BrowserDataInterface { Log.debug(TAG, `getItemIndexByUri count: ${allObject.length}`); index = allObject.findIndex((item: FileAsset) => item.uri == realUri); } - return index; } diff --git a/common/src/main/ets/default/model/browser/album/AlbumDataImpl.ts b/common/src/main/ets/default/model/browser/album/AlbumDataImpl.ts index 79f2d31a..e7252b56 100644 --- a/common/src/main/ets/default/model/browser/album/AlbumDataImpl.ts +++ b/common/src/main/ets/default/model/browser/album/AlbumDataImpl.ts @@ -22,6 +22,7 @@ import { UserFileManagerAccess } from '../../../access/UserFileManagerAccess'; import { Log } from '../../../utils/Log'; import { Constants } from '../../common/Constants'; import { MediaItem } from '../photo/MediaItem'; +import { ImageUtil } from '../../../utils/ImageUtil'; const TAG: string = 'common_AlbumDataImpl'; @@ -139,53 +140,58 @@ export class AlbumDataImpl extends BrowserDataImpl { } private async getUserAlbumsInfo(albumArray: Array, filterMediaType?: string): Promise { - Log.debug(TAG, 'getUserAlbumsInfo'); - + Log.info(TAG, 'getUserAlbumsInfo start'); let albums: Album[] = await UserFileManagerAccess.getInstance().getUserAlbums(); - Log.debug(TAG, `getUserAlbumsInfo albums is : ${albums}`); - if (albums) { + if (!albums) { + Log.error(TAG, 'getUserAlbumsInfo, albums undefined'); + } + Log.info(TAG, `getUserAlbumsInfo fetch albums length : ${albums.length}`); + try { for (let album of albums) { let albumInfo: AlbumInfo = new AlbumInfo(album); let albumName: string = await UserFileManagerAccess.getInstance().getAlbumName(album); albumInfo.setAlbumName(albumName); - albumInfo.setFilterMediaType(filterMediaType); - // 没有相册,设置为第一张 - if (!album.coverUri) { - await UserFileManagerAccess.getInstance().getAlbumFirstObject(album).then((obj) => { - if (obj) { - let mediaItem = new MediaItem(obj); - mediaItem.setThumbnail(this.getThumbnailSafe(obj.uri, String(obj.get(Constants.KEY_FILE_DATA)))); - albumInfo.setMediaItem(mediaItem); - albumInfo.setCoverUri(this.getThumbnailSafe(obj.uri, String(obj.get(Constants.KEY_FILE_DATA)))); - } - }); - } else { - await UserFileManagerAccess.getInstance().getFirstObject(AlbumDefine.getFileFetchOptByUri(album.coverUri)).then((obj) => { - if (obj) { - let mediaItem = new MediaItem(obj.obj); - mediaItem.setThumbnail(this.getThumbnailSafe(obj.obj.uri, String(obj.obj.get(Constants.KEY_FILE_DATA)))); - albumInfo.setMediaItem(mediaItem); - albumInfo.setCoverUri(this.getThumbnailSafe(obj.obj.uri, String(obj.obj.get(Constants.KEY_FILE_DATA)))); - } - }); + albumInfo.setFilterMediaType(filterMediaType as string); + let count = albumInfo.count; + albumInfo.setCount(count); // Waiting: album.count不为0时,在构造函数里直接获取 + let videoCount = 0; + if (count > 0) { + // 没有相册,设置为第一张 + let hasCoverUri: Boolean = false; + if (album.coverUri) { + await UserFileManagerAccess.getInstance().getFirstObject(AlbumDefine.getFileFetchOptByUri(album.coverUri)).then((obj) => { + if (obj && obj.obj) { + let mediaItem = new MediaItem(obj.obj); + mediaItem.setThumbnail(this.getThumbnailSafe(obj.obj.uri, String(obj.obj.get(Constants.KEY_FILE_DATA)))); + albumInfo.setMediaItem(mediaItem); + albumInfo.setCoverUri(ImageUtil.calcThumbnail(obj.obj.uri, mediaItem.height, mediaItem.width)); + hasCoverUri = true; + } + }); + } + if (!hasCoverUri) { + await UserFileManagerAccess.getInstance().getAlbumFirstObject(album).then((obj) => { + if (obj) { + let mediaItem = new MediaItem(obj); + mediaItem.setThumbnail(this.getThumbnailSafe(obj.uri, String(obj.get(Constants.KEY_FILE_DATA)))); + albumInfo.setMediaItem(mediaItem); + albumInfo.setCoverUri(ImageUtil.calcThumbnail(obj.uri, mediaItem.height, mediaItem.width)); + } + }); + } + // 相册的视频数量 + videoCount = await this.getItemsCountOfAlbum(album, AlbumDefine.FILTER_MEDIA_TYPE_VIDEO); } - let count = await this.getItemsCount(album.albumUri); - albumInfo.setCount(count); // TODO album.count不为0时,在构造函数里直接获取 - // 相册的视频数量 - let videoCount = await this.getItemsCount(album.albumUri, AlbumDefine.FILTER_MEDIA_TYPE_VIDEO); albumInfo.setVideoCount(videoCount); - Log.debug(TAG, `getUserAlbumsInfo albumInfo is : ${albumInfo}`); albumArray.push(albumInfo); - Log.debug(TAG, `getUserAlbumsInfo albumArray length is : ${albumArray.length}`); + Log.info(TAG, `getUserAlbumsInfo done, albumInfo : ${JSON.stringify(albumInfo)}, albumArray length: ${albumArray.length}`); } - } else { - Log.error(TAG, 'Failed getUserAlbumsInfo'); + } catch (error) { + Log.error(TAG, `getUserAlbumsInfo error occured: ${error}`); } - - Log.debug(TAG, 'getUserAlbumsInfo done'); + Log.info(TAG, 'getUserAlbumsInfo done'); } - private async getSystemAlbumsInfo(albumArray: Array, filterMediaType?: string): Promise { Log.debug(TAG, 'getSystemAlbumsInfo'); @@ -239,23 +245,23 @@ export class AlbumDataImpl extends BrowserDataImpl { } private async getTrashAlbumInfo(albumArray: Array, filterMediaType?: string): Promise { - Log.debug(TAG, 'getTrashAlbumInfo'); - let album: Album = await UserFileManagerAccess.getInstance().getTrashAlbum(); - Log.debug(TAG, `getTrashAlbumInfo albums is : ${album}`); + Log.info(TAG, 'getTrashAlbumInfo start'); + let album: Album = await UserFileManagerAccess.getInstance().getTrashAlbum() as Album; + if (!album) { + Log.error(TAG, 'getTrashAlbumInfo, get album undefined'); + } let albumInfo: AlbumInfo = new AlbumInfo(album); - let count = await this.getItemsCount(album.albumUri); + let count = albumInfo.count; // 系统相册为空时不展示 if (count === 0) { Log.warn(TAG, 'getTrashAlbumInfo count is 0'); return; } albumInfo.setCount(count); - let albumName: string = await UserFileManagerAccess.getInstance().getAlbumName(album); + let albumName: string = await UserFileManagerAccess.getInstance().getAlbumName(album) as string; albumInfo.setAlbumName(albumName); - albumInfo.setFilterMediaType(filterMediaType); - Log.debug(TAG, `getTrashAlbumInfo albumArray albumInfo is : ${albumInfo}`); + albumInfo.setFilterMediaType(filterMediaType as string); albumArray.push(albumInfo); - Log.debug(TAG, `getTrashAlbumInfo albumArray length is : ${albumArray.length}`); - Log.debug(TAG, 'getSystemAlbumsInfo done'); + Log.info(TAG, `getTrashAlbumInfo done, albumInfo : ${JSON.stringify(albumInfo)}, albumArray length: ${albumArray.length}`); } } \ No newline at end of file diff --git a/common/src/main/ets/default/model/browser/album/AlbumInfo.ts b/common/src/main/ets/default/model/browser/album/AlbumInfo.ts index 6ad1fe9f..2acbd4ad 100644 --- a/common/src/main/ets/default/model/browser/album/AlbumInfo.ts +++ b/common/src/main/ets/default/model/browser/album/AlbumInfo.ts @@ -33,8 +33,10 @@ export class AlbumInfo { dateModified: number; videoCount: number; mediaItem: MediaItem; + deviceName: string; + deviceId: string; - constructor(album: Album) { + constructor(album?: Album) { if (album) { this.uri = album.albumUri; this.coverUri = album.coverUri; diff --git a/common/src/main/ets/default/model/browser/album/AlbumSetDataSource.ts b/common/src/main/ets/default/model/browser/album/AlbumSetDataSource.ts index 6b2e1d72..15762f28 100644 --- a/common/src/main/ets/default/model/browser/album/AlbumSetDataSource.ts +++ b/common/src/main/ets/default/model/browser/album/AlbumSetDataSource.ts @@ -43,7 +43,9 @@ export class AlbumSetDataSource extends AbsDataSource { super(); Log.debug(TAG, `constructor ${JSON.stringify(param)}`); - this.broadCast_ = broadCast; + if (broadCast) { + this.broadCast_ = broadCast; + } this.albumDataImpl = BrowserDataFactory.getFeature(BrowserDataFactory.TYPE_ALBUM, param); if (param && param.deviceId) { @@ -62,7 +64,8 @@ export class AlbumSetDataSource extends AbsDataSource { if (this.albumDataImpl != null) { let callback: AlbumSetCallback = new AlbumSetCallback(this); this.albumDataImpl.getData(callback, - (this.filterMediaType == undefined) ? null : { filterMediaType: this.filterMediaType }); + (this.filterMediaType === undefined || this.filterMediaType === null) ? + null : { filterMediaType: this.filterMediaType }); } } diff --git a/common/src/main/ets/default/model/browser/dataObserver/MediaObserver.ts b/common/src/main/ets/default/model/browser/dataObserver/MediaObserver.ts index 1f5b9bc8..4884b5fe 100644 --- a/common/src/main/ets/default/model/browser/dataObserver/MediaObserver.ts +++ b/common/src/main/ets/default/model/browser/dataObserver/MediaObserver.ts @@ -24,10 +24,10 @@ export class MediaObserver { callbacks: Set = new Set(); static getInstance(): MediaObserver { - if (AppStorage.Get(Constants.APP_KEY_MENU_USER_FILE_MANAGER_OBSERVER) == null) { + if (AppStorage.get(Constants.APP_KEY_MENU_USER_FILE_MANAGER_OBSERVER) == null) { AppStorage.SetOrCreate(Constants.APP_KEY_MENU_USER_FILE_MANAGER_OBSERVER, new MediaObserver()); } - return AppStorage.Get(Constants.APP_KEY_MENU_USER_FILE_MANAGER_OBSERVER); + return AppStorage.get(Constants.APP_KEY_MENU_USER_FILE_MANAGER_OBSERVER); } registerObserver(callback: MediaObserverCallback) { diff --git a/common/src/main/ets/default/model/browser/photo/PhotoDataSource.ts b/common/src/main/ets/default/model/browser/photo/PhotoDataSource.ts index 64d86512..161a869a 100644 --- a/common/src/main/ets/default/model/browser/photo/PhotoDataSource.ts +++ b/common/src/main/ets/default/model/browser/photo/PhotoDataSource.ts @@ -28,7 +28,7 @@ import { ImageUtil } from '../../../utils/ImageUtil'; import { ScreenManager } from '../../common/ScreenManager'; import display from '@ohos.display'; -import { UserFileManagerAccess } from '../../../access/UserFileManagerAccess'; +import { FileAsset, UserFileManagerAccess } from '../../../access/UserFileManagerAccess'; const TAG: string = 'common_PhotoDataSource'; @@ -285,8 +285,9 @@ export class PhotoDataSource implements IDataSource, LoadingListener { } } - async getDataByUri(uri) { - return await this.photoDataImpl.getDataByUri(uri); + async getDataByUri(uri: string): Promise { + let tmp: FileAsset = await this.photoDataImpl.getDataByUri(uri) as FileAsset; + return tmp; } getItemByUri(uri: string): any { diff --git a/common/src/main/ets/default/model/browser/photo/TimelineData.ts b/common/src/main/ets/default/model/browser/photo/TimelineData.ts index 21ef319a..c7ab5b47 100644 --- a/common/src/main/ets/default/model/browser/photo/TimelineData.ts +++ b/common/src/main/ets/default/model/browser/photo/TimelineData.ts @@ -18,7 +18,7 @@ export class TimelineData { startDate: number; endDate: number; - constructor(startDate: number, endDate: number, count: number) { + constructor(startDate?: number, endDate?: number, count?: number) { this.startDate = startDate; this.endDate = endDate; this.count = count; diff --git a/common/src/main/ets/default/model/common/BroadCastManager.ts b/common/src/main/ets/default/model/common/BroadCastManager.ts index 4af28d01..df5ccad8 100644 --- a/common/src/main/ets/default/model/common/BroadCastManager.ts +++ b/common/src/main/ets/default/model/common/BroadCastManager.ts @@ -29,10 +29,10 @@ export class BroadCastManager { } public static getInstance(): BroadCastManager { - if (AppStorage.Get(Constants.APP_KEY_EVENT_BUS) == null) { + if (AppStorage.get(Constants.APP_KEY_EVENT_BUS) == null) { AppStorage.SetOrCreate(Constants.APP_KEY_EVENT_BUS, new BroadCastManager()); } - return AppStorage.Get(Constants.APP_KEY_EVENT_BUS); + return AppStorage.get(Constants.APP_KEY_EVENT_BUS); } public getBroadCast(): BroadCast { diff --git a/common/src/main/ets/default/model/common/Constants.ts b/common/src/main/ets/default/model/common/Constants.ts index c12cdf9f..b8ed13b3 100644 --- a/common/src/main/ets/default/model/common/Constants.ts +++ b/common/src/main/ets/default/model/common/Constants.ts @@ -74,6 +74,9 @@ export class Constants { static readonly IS_SHOW_MOVE_COPY_DIALOG: string = 'is_show_move_copy_dialog'; static readonly INSTANCE_MOVE_OR_COPY_BROADCAST_PROP: string = 'instance_move_or_copy_broadcast_prop'; + // used as album uri for creating album from picker page + static readonly APP_NEW_ALBUM_SOURCE_PICKER: string = 'picker_page'; + // BroadCast static readonly APP_KEY_EVENT_BUS: string = 'app_key_event_bus'; diff --git a/common/src/main/ets/default/model/common/HistogramManager.ets b/common/src/main/ets/default/model/common/HistogramManager.ets index c599aa2f..77cb783e 100644 --- a/common/src/main/ets/default/model/common/HistogramManager.ets +++ b/common/src/main/ets/default/model/common/HistogramManager.ets @@ -198,7 +198,7 @@ export class HistogramManager { */ private initializePixelArray(): void { Log.info(TAG, 'get pixel array by deserialize'); - let serializedBuffer = AppStorage.Get(Constants.HISTOGRAM_ARRAY_BUFFER_KEY); + let serializedBuffer = AppStorage.get(Constants.HISTOGRAM_ARRAY_BUFFER_KEY); if (!serializedBuffer) { Log.error(TAG, 'initializePixelArray: serializedBuffer is undefined'); return; diff --git a/common/src/main/ets/default/model/common/PixelMapManager.ts b/common/src/main/ets/default/model/common/PixelMapManager.ts index dedf4add..a9769f95 100644 --- a/common/src/main/ets/default/model/common/PixelMapManager.ts +++ b/common/src/main/ets/default/model/common/PixelMapManager.ts @@ -30,10 +30,10 @@ export class PixelMapManager { } public static getInstance(): PixelMapManager { - if (AppStorage.Get(Constants.PIXEL_MAP_MANAGER) == null) { + if (AppStorage.get(Constants.PIXEL_MAP_MANAGER) == null) { AppStorage.SetOrCreate(Constants.PIXEL_MAP_MANAGER, new PixelMapManager()); } - return AppStorage.Get(Constants.PIXEL_MAP_MANAGER); + return AppStorage.get(Constants.PIXEL_MAP_MANAGER); } public getFifoCache(): FifoCache { diff --git a/common/src/main/ets/default/model/common/ScreenManager.ts b/common/src/main/ets/default/model/common/ScreenManager.ts index 777c5d39..6c9da8b9 100644 --- a/common/src/main/ets/default/model/common/ScreenManager.ts +++ b/common/src/main/ets/default/model/common/ScreenManager.ts @@ -79,10 +79,10 @@ export class ScreenManager { } static getInstance(): ScreenManager { - if (AppStorage.Get(Constants.APP_KEY_SCREEN_MANAGER) == null) { + if (AppStorage.get(Constants.APP_KEY_SCREEN_MANAGER) == null) { AppStorage.SetOrCreate(Constants.APP_KEY_SCREEN_MANAGER, new ScreenManager()); } - let manager: ScreenManager = AppStorage.Get(Constants.APP_KEY_SCREEN_MANAGER); + let manager: ScreenManager = AppStorage.get(Constants.APP_KEY_SCREEN_MANAGER); return manager; } @@ -157,7 +157,7 @@ export class ScreenManager { // Returns the height of the layout area (LayoutHeight = WindowHeight - WindowDecorHeight). getWinLayoutHeight(): number { - let deviceTp: string = AppStorage.Get('deviceType') as string; + let deviceTp: string = AppStorage.get('deviceType') as string; Log.debug(TAG, `deviceTp=${deviceTp}, isFull=${this.isFullScreen}, winH=${this.winHeight}`); if (deviceTp === Constants.DEFAULT_DEVICE_TYPE) { return this.winHeight; @@ -191,7 +191,9 @@ export class ScreenManager { async checkWindowMode(): Promise { let before = this.windowMode; - let mode = await globalThis.photosWindowStage.getWindowMode(); + let windowStage: window.WindowStage = AppStorage.get('photosWindowStage'); + // @ts-ignore + let mode: WindowMode = await windowStage.getWindowMode() as WindowMode; Log.info(TAG, `photos application before/current window mode: ${before}/${mode}`); if (before == mode) { @@ -241,7 +243,7 @@ export class ScreenManager { try { topWindow.setLayoutFullScreen(true, () => { Log.debug(TAG, 'setFullScreen true Succeeded'); - if (AppStorage.Get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { + if (AppStorage.get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { this.hideStatusBar(); } else { this.setWindowBackgroundColorDefault(true); @@ -308,7 +310,7 @@ export class ScreenManager { } setSystemUi(isShowBar: boolean): void { - let deviceTp: string = AppStorage.Get('deviceType') as string; + let deviceTp: string = AppStorage.get('deviceType') as string; Log.debug(TAG, `setSystemUi start, isShowBar=${isShowBar}, deviceType=${deviceTp}`); let topWindow: window.Window = this.getMainWindow(); Log.debug(TAG, 'getTopWindow start'); @@ -336,17 +338,17 @@ export class ScreenManager { } isHorizontal(): boolean { - if (AppStorage.Get(Constants.SCREEN_ORIENTATION_HORIZONTAL) == null) { + if (AppStorage.get(Constants.SCREEN_ORIENTATION_HORIZONTAL) == null) { AppStorage.SetOrCreate(Constants.SCREEN_ORIENTATION_HORIZONTAL, this.horizontal); } - return AppStorage.Get(Constants.SCREEN_ORIENTATION_HORIZONTAL); + return AppStorage.get(Constants.SCREEN_ORIENTATION_HORIZONTAL); } isSidebar(): boolean { - if (AppStorage.Get(Constants.SCREEN_SIDEBAR) == null) { + if (AppStorage.get(Constants.SCREEN_SIDEBAR) == null) { AppStorage.SetOrCreate(Constants.SCREEN_SIDEBAR, this.sidebar); } - return AppStorage.Get(Constants.SCREEN_SIDEBAR); + return AppStorage.get(Constants.SCREEN_SIDEBAR); } getColumnsWidth(count: number): number { @@ -370,7 +372,7 @@ export class ScreenManager { } private getMainWindow(): window.Window { - return AppStorage.Get('mainWindow'); + return AppStorage.get('mainWindow'); } private emit(event: string, argument: unknown[]): void { diff --git a/common/src/main/ets/default/model/common/StatusBarColorController.ts b/common/src/main/ets/default/model/common/StatusBarColorController.ts index 5795edde..b3f54624 100644 --- a/common/src/main/ets/default/model/common/StatusBarColorController.ts +++ b/common/src/main/ets/default/model/common/StatusBarColorController.ts @@ -42,11 +42,11 @@ export class StatusBarColorController { } public static getInstance(): StatusBarColorController { - if (AppStorage.Get(Constants.APP_KEY_STATUS_BAR_COLOR_CONTROLLER) == null) { + if (AppStorage.get(Constants.APP_KEY_STATUS_BAR_COLOR_CONTROLLER) == null) { AppStorage.SetOrCreate( Constants.APP_KEY_STATUS_BAR_COLOR_CONTROLLER, new StatusBarColorController()); } - return AppStorage.Get(Constants.APP_KEY_STATUS_BAR_COLOR_CONTROLLER); + return AppStorage.get(Constants.APP_KEY_STATUS_BAR_COLOR_CONTROLLER); } public setMode(mode: StatusBarColorMode): void { diff --git a/common/src/main/ets/default/model/common/TabItem.ets b/common/src/main/ets/default/model/common/TabItem.ets index 5842cf87..9fcacefc 100644 --- a/common/src/main/ets/default/model/common/TabItem.ets +++ b/common/src/main/ets/default/model/common/TabItem.ets @@ -20,7 +20,7 @@ export class TabItem { iconResource: Resource; iconSelectedResource: Resource; iconDefault: Resource = $r('sys.color.ohos_id_color_bottom_tab_icon_off'); - iconSelected: Resource; + iconSelected: Resource | null = null; textColorDefault: Resource = $r('sys.color.ohos_id_color_text_primary'); textColorSelected: Resource = $r('sys.color.ohos_id_color_bottom_tab_text_on'); textFamilyDefault: Resource = $r('sys.string.ohos_id_text_font_family_medium'); @@ -38,7 +38,7 @@ export class TabItem { } getConditionIcon(isSelected: boolean): Resource { - return isSelected ? this.iconSelected : this.iconDefault; + return isSelected ? this.iconSelected as Resource : this.iconDefault; } getIcon(isSelected: boolean): Resource { diff --git a/common/src/main/ets/default/model/common/WorkerThreadPool.ets b/common/src/main/ets/default/model/common/WorkerThreadPool.ets index 23e8fdb0..12ceaf1c 100644 --- a/common/src/main/ets/default/model/common/WorkerThreadPool.ets +++ b/common/src/main/ets/default/model/common/WorkerThreadPool.ets @@ -117,7 +117,7 @@ export class WorkerThreadPool { Log.info(TAG, 'thread pool start running, capacity: ' + WorkerThreadPool.CAPACITY); let groupCount = data.byteLength / byteLengthOfOneGroup; let byteLengthOfOneWorker = Math.floor(groupCount / WorkerThreadPool.CAPACITY) * byteLengthOfOneGroup; - let deviceType: string = AppStorage.Get('deviceType'); + let deviceType: string = AppStorage.get('deviceType'); const FIRST_INDEX = 0; for (let i = WorkerThreadPool.CAPACITY - 1; i >= 0; i--) { let workerInstance = WorkerThreadPool.createWorker(path, deviceType); diff --git a/common/src/main/ets/default/utils/DataStoreUtil.ts b/common/src/main/ets/default/utils/DataStoreUtil.ts index b59fef35..4c1ec171 100644 --- a/common/src/main/ets/default/utils/DataStoreUtil.ts +++ b/common/src/main/ets/default/utils/DataStoreUtil.ts @@ -16,6 +16,7 @@ import { Log } from './Log'; import { Constants } from '../model/common/Constants'; import data_preferences from '@ohos.data.preferences'; import contextConstant from '@ohos.app.ability.contextConstant'; +import common from '@ohos.app.ability.common'; const TAG: string = 'common_DataStoreUtil'; @@ -28,10 +29,10 @@ export class DataStoreUtil { } public static getInstance(): DataStoreUtil { - if (AppStorage.Get(Constants.FROM_DATA_STORE_UTIL) == null) { + if (AppStorage.get(Constants.FROM_DATA_STORE_UTIL) == null) { AppStorage.SetOrCreate(Constants.FROM_DATA_STORE_UTIL, new DataStoreUtil()); } - return AppStorage.Get(Constants.FROM_DATA_STORE_UTIL); + return AppStorage.get(Constants.FROM_DATA_STORE_UTIL); } public async init(): Promise { @@ -40,7 +41,7 @@ export class DataStoreUtil { Log.debug(TAG, 'init already!'); return; } - let context = globalThis.photosGlobalContext; + let context: common.AbilityStageContext = AppStorage.get('photosGlobalContext'); let area: contextConstant.AreaMode = context.area; context.area = contextConstant.AreaMode.EL1; try { @@ -130,7 +131,7 @@ export class DataStoreUtil { public async removeCache() { Log.debug(TAG, 'removeCache start!'); - let context = globalThis.photosGlobalContext; + let context: common.AbilityStageContext = AppStorage.get('photosGlobalContext'); let area: contextConstant.AreaMode = context.area; context.area = contextConstant.AreaMode.EL1; try { diff --git a/common/src/main/ets/default/utils/ErrUtil.ts b/common/src/main/ets/default/utils/ErrUtil.ts new file mode 100644 index 00000000..5a9c2d77 --- /dev/null +++ b/common/src/main/ets/default/utils/ErrUtil.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved. + */ +import { Log } from './Log'; + +const TAG: string = 'ErrUtil'; + +export function tryFunc(getValue: Function, ...args): any { + if (typeof getValue !== 'function') { + Log.e(TAG, typeof getValue, 'is not a func ', ...args); + return; + } + let res; + try { + res = getValue(...args); + } catch (error) { + Log.e(TAG, { + function: getValue.name, + args: args, + error, + errMsg: String(error) + }); + } + return res; +} + +export async function tryFuncAsync(getValue: Function, ...args): Promise { + if (typeof getValue !== 'function') { + Log.e(TAG, 'not a func ', ...args); + return; + } + let res; + try { + res = await getValue(...args); + } catch (error) { + Log.e(TAG, { + function: getValue.name, + args: args, + error, + errMsg: String(error) + }); + } + return res; +} \ No newline at end of file diff --git a/common/src/main/ets/default/utils/Log.ts b/common/src/main/ets/default/utils/Log.ts index 0b7fb04c..a8c4a6bc 100644 --- a/common/src/main/ets/default/utils/Log.ts +++ b/common/src/main/ets/default/utils/Log.ts @@ -18,6 +18,7 @@ import HiLog from '@ohos.hilog'; const DOMAIN: number = 0x0220; const TAG: string = 'Photos'; const COLON = ': '; +const SEPARATOR = ' '; export class Log { static debug(className: string, message: string, ...args: string[]): boolean { @@ -59,4 +60,69 @@ export class Log { } return false; } + + /** + * 使用方法 直接逗号分隔开: + ``` + Log.debug(TAG, `params = , ${JSON.stringify(param1)}, ${JSON.stringify(param2)...`) + 简化为 Log.d(TAG, 'params = ', param1, param2...) + Log.error(TAG, `${JSON.stringify(err)obj = key1: ${JSON.stringify(v1)}, key2: ${JSON.stringify(v2)...`) + 简化为 Log.e(TAG, err, 'obj = ', { key1: v1, key2: v2 }) + ``` + */ + static d(className: string, ...args): void { + return HiLog.debug(DOMAIN, TAG, className + COLON + this.join(...args)); + } + + static i(className: string, ...args): void { + return HiLog.info(DOMAIN, TAG, className + COLON + this.join(...args)); + } + + static w(className: string, ...args): void { + return HiLog.warn(DOMAIN, TAG, className + COLON + this.join(...args)); + } + + static e(className: string, ...args): void { + return HiLog.error(DOMAIN, TAG, className + COLON + this.join(...args)); + } + + static f(className: string, ...args): void { + return HiLog.fatal(DOMAIN, TAG, className + COLON + this.join(...args)); + } + + static stringify(a): string { + let res: string; + if (typeof a !== 'string') { + try { + res = JSON.stringify(a); + HiLog.debug(DOMAIN, TAG, a); + } catch (e) { + if (e) { + HiLog.error(DOMAIN, TAG, `${e} type: ${typeof a}, ${a}, catch error: ${JSON.stringify(e)}`); + } + res = e; + } + } + if (res === '{}') { + try { + res = String(a); + } catch (e) { + if (e) { + HiLog.warn(DOMAIN, TAG, `${e} type: ${typeof a}, ${a}, catch error: ${JSON.stringify(e)}`); + } + } + } + return res ?? a; + } + + static join(...args): string { + for (let i = 0; i < args.length; i++) { + try { + args[i] = this.stringify(args[i]); + } catch (e) { + HiLog.warn(DOMAIN, TAG, `${e} type: ${typeof args[i]}, ${args[i]}, catch error: ${JSON.stringify(e)}`); + } + } + return args.join(SEPARATOR); + } } diff --git a/common/src/main/ets/default/utils/Matrix4x4.ets b/common/src/main/ets/default/utils/Matrix4x4.ets new file mode 100644 index 00000000..4f04886b --- /dev/null +++ b/common/src/main/ets/default/utils/Matrix4x4.ets @@ -0,0 +1,5 @@ +import Matrix4 from '@ohos.matrix4'; + +export interface Matrix4x4 extends Matrix4.Matrix4Transit { + matrix4x4?: Array; +} diff --git a/common/src/main/ets/default/utils/ReportToBigDataUtil.ts b/common/src/main/ets/default/utils/ReportToBigDataUtil.ts index 361a5ddc..7c69b9f2 100644 --- a/common/src/main/ets/default/utils/ReportToBigDataUtil.ts +++ b/common/src/main/ets/default/utils/ReportToBigDataUtil.ts @@ -25,7 +25,7 @@ export class ReportToBigDataUtil { private static PREFIX_NUMBER: number = 4; static readonly PHOTOS_DFX_DOMAIN: string = 'PHOTOS'; - public static report(eventId: string, eventMsg: object): void { + public static report(eventId: string, eventMsg?: object): void { hiSysEvent.write({ domain: ReportToBigDataUtil.PHOTOS_DFX_DOMAIN, name: eventId, @@ -38,7 +38,7 @@ export class ReportToBigDataUtil { Log.info(TAG, `report, eventId: ${eventId} msg: ${JSON.stringify(eventMsg)}`); } - public static statisticReport(eventId: string, eventMsg: object): void { + public static statisticReport(eventId: string, eventMsg?: object): void { hiSysEvent.write({ domain: ReportToBigDataUtil.PHOTOS_DFX_DOMAIN, name: eventId, @@ -51,7 +51,7 @@ export class ReportToBigDataUtil { Log.info(TAG, `report, eventId: ${eventId} msg: ${JSON.stringify(eventMsg)}`); } - public static errEventReport(eventId: string, eventMsg: object): void { + public static errEventReport(eventId: string, eventMsg?: object): void { hiSysEvent.write({ domain: ReportToBigDataUtil.PHOTOS_DFX_DOMAIN, name: eventId, diff --git a/common/src/main/ets/default/utils/UiUtil.ts b/common/src/main/ets/default/utils/UiUtil.ts index 1ff57f16..c7948894 100644 --- a/common/src/main/ets/default/utils/UiUtil.ts +++ b/common/src/main/ets/default/utils/UiUtil.ts @@ -21,6 +21,7 @@ import prompt from '@system.prompt'; import type window from '@ohos.window'; import type { Action } from '../view/browserOperation/Action'; import { AlbumInfo } from '../model/browser/album/AlbumInfo'; +import common from '@ohos.app.ability.common'; const TAG: string = 'common_UiUtil'; @@ -130,11 +131,12 @@ export class UiUtil { static async getResourceString(resource: Resource): Promise { try { Log.info(TAG, `getResourceString: ${JSON.stringify(resource)}`); - if (globalThis.photosAbilityContext == null || globalThis.photosAbilityContext === 'undefined') { + if (AppStorage.get('photosAbilityContext') === null || AppStorage.get('photosAbilityContext') === 'undefined') { Log.error(TAG, 'getResourceString error: context is null'); return null; } - let mgr = await globalThis.photosAbilityContext.resourceManager.getString(resource.id); + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext'); + let mgr: string = await context.resourceManager.getString(resource.id); if (mgr) { return mgr; } else { @@ -156,11 +158,12 @@ export class UiUtil { static async getResourceNumber(resource: Resource): Promise { try { Log.info(TAG, `getResourceNumber: ${JSON.stringify(resource)}`); - if (globalThis.photosAbilityContext == null || globalThis.photosAbilityContext === 'undefined') { + if (AppStorage.get('photosAbilityContext') === null || AppStorage.get('photosAbilityContext') === 'undefined') { Log.error(TAG, 'getResourceNumber error: context is null'); return null; } - let mgr = await globalThis.photosAbilityContext.resourceManager.getNumber(resource.id); + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext'); + let mgr: number = context.resourceManager.getNumber(resource.id); if (mgr) { return mgr; } else { diff --git a/common/src/main/ets/default/utils/WindowUtil.ts b/common/src/main/ets/default/utils/WindowUtil.ts index c5c01dd8..556b05d1 100644 --- a/common/src/main/ets/default/utils/WindowUtil.ts +++ b/common/src/main/ets/default/utils/WindowUtil.ts @@ -14,11 +14,13 @@ */ import { Log } from './Log'; import window from '@ohos.window'; +import { Router, UIContext } from '@ohos.arkui.UIContext'; +import common from '@ohos.app.ability.common'; const TAG: string = 'common_WindowUtil'; export class WindowUtil { - static setWindowKeepScreenOn(context, isKeepScreenOn: boolean) { + static setWindowKeepScreenOn(context: common.UIAbilityContext, isKeepScreenOn: boolean): void { try { window.getLastWindow(context).then((windows) => { windows.setWindowKeepScreenOn(isKeepScreenOn).then(() => { @@ -34,7 +36,7 @@ export class WindowUtil { } } - static setPreferredOrientation(context, orientation: number) { + static setPreferredOrientation(context: common.UIAbilityContext, orientation: number): void { try { window.getLastWindow(context, (err, data) => { if (err.code || !data) { @@ -54,4 +56,22 @@ export class WindowUtil { Log.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(exception)); } } + + static prepareWinRouter(): void { + Log.debug(TAG, `prepareWinRouter AppStorage.get('router')=${AppStorage.get('router')}`); + if (AppStorage.get('router')) { + return; + } + try { + AppStorage.setOrCreate('uiContext', (AppStorage.get('mainWindow') as window.Window).getUIContext()); + } catch (error) { + Log.error(TAG, `Failed to get UIContext, error: ${error}`); + return; + } + if (AppStorage.get('uiContext')) { + Log.info(TAG, `prepareWinRouter AppStorage.get('uiContext')=${AppStorage.get('uiContext')}`); + AppStorage.setOrCreate('router', (AppStorage.get('uiContext')).getRouter()); + Log.info(TAG, `prepareWinRouter localRouter=${AppStorage.get('router')}`); + } + } } \ No newline at end of file diff --git a/common/src/main/ets/default/view/BrowserController.ets b/common/src/main/ets/default/view/BrowserController.ets index 1f09e203..d5a1ce0b 100644 --- a/common/src/main/ets/default/view/BrowserController.ets +++ b/common/src/main/ets/default/view/BrowserController.ets @@ -24,11 +24,11 @@ export class BrowserController { public geometryTransitionEnable: boolean = false; public isAnimating: boolean = false; public isBrowserShow: boolean = false; - public browserParam: Object = undefined; - public browserBackFunc: Function; + public browserParam?: Object; + public browserBackFunc: Function = (): void => {}; public isSelectBrowserShow: boolean = false; - public selectBrowserParam: Object = undefined; - public pageFrom: string = undefined; + public selectBrowserParam?: Object; + public pageFrom: string = ''; constructor(isGeometryEnable: boolean) { this.geometryTransitionEnable = isGeometryEnable; @@ -73,10 +73,10 @@ export class BrowserController { } }, () => { this.isBrowserShow = false; - this.browserParam = undefined; + this.browserParam; this.isAnimating = true; AppStorage.SetOrCreate('placeholderIndex', -1); - Log.info(TAG, `placeholderIndex ${AppStorage.get('placeholderIndex')}`); + Log.info(TAG, `placeholderIndex ${AppStorage.get('placeholderIndex')}`); }); } @@ -109,7 +109,7 @@ export class BrowserController { } }, () => { this.isSelectBrowserShow = false; - this.selectBrowserParam = undefined; + this.selectBrowserParam; this.isAnimating = true; AppStorage.SetOrCreate('placeholderIndex', -1); }); diff --git a/common/src/main/ets/default/view/DetailsDialogComponent.ets b/common/src/main/ets/default/view/DetailsDialogComponent.ets index 7086df36..7a52c63e 100644 --- a/common/src/main/ets/default/view/DetailsDialogComponent.ets +++ b/common/src/main/ets/default/view/DetailsDialogComponent.ets @@ -16,8 +16,8 @@ import { Constants } from '../model/common/Constants'; @Component export struct DetailsDialogComponent { - title: Resource; - content: string | Resource; + title?: Resource; + content: string | Resource = ''; colon: string = ': '; isLast: boolean = false; keyForAutoTest: string = ''; diff --git a/common/src/main/ets/default/view/GridScrollBar.ets b/common/src/main/ets/default/view/GridScrollBar.ets index c171b5de..0e786153 100644 --- a/common/src/main/ets/default/view/GridScrollBar.ets +++ b/common/src/main/ets/default/view/GridScrollBar.ets @@ -19,11 +19,11 @@ const TAG: string = 'common_GridScrollBar'; @Component export struct GridScrollBar { - scroller: Scroller; + scroller: Scroller | null = null; @State isClickScrollBar: boolean = false; build() { - ScrollBar({ scroller: this.scroller, direction: ScrollBarDirection.Vertical, + ScrollBar({ scroller: this.scroller as Scroller, direction: ScrollBarDirection.Vertical, state: BarState.Auto }) { Row() { if (this.isClickScrollBar) { @@ -46,12 +46,12 @@ export struct GridScrollBar { x: this.isClickScrollBar ? $r('app.float.scroll_bar_big_width') : $r('app.float.scroll_bar_small_width'), y: 0 }) - .onTouch((event: TouchEvent) => { - if (event.type == TouchType.Move && !this.isClickScrollBar) { + .onTouch((event?: TouchEvent) => { + if (event?.type == TouchType.Move && !this.isClickScrollBar) { Log.debug(TAG, `scrollBar first TouchType.Move`); this.isClickScrollBar = true; - } else if (event.type == TouchType.Up || event.type == TouchType.Cancel) { - Log.debug(TAG, `scrollBar TouchType.Up or Cancel. type=${event.type}`); + } else if (event?.type == TouchType.Up || event?.type == TouchType.Cancel) { + Log.debug(TAG, `scrollBar TouchType.Up or Cancel. type=${event?.type}`); this.isClickScrollBar = false; } }) diff --git a/common/src/main/ets/default/view/ImageGridItemComponent.ets b/common/src/main/ets/default/view/ImageGridItemComponent.ets index d78e3206..49cfab0b 100644 --- a/common/src/main/ets/default/view/ImageGridItemComponent.ets +++ b/common/src/main/ets/default/view/ImageGridItemComponent.ets @@ -37,15 +37,19 @@ const TAG: string = 'common_ImageGridItemComponent'; @Extend(Image) function focusSetting(uri: string, handleEvent: Function) { .key('ImageGridFocus_' + uri) .focusable(true) - .onKeyEvent((event: KeyEvent) => { - handleEvent(event); + .onKeyEvent((event?: KeyEvent) => { + handleEvent((event as KeyEvent)); }) } +interface Msg { + from: string; +} + // General grid picture control @Component export struct ImageGridItemComponent { - item: MediaItem; + item: MediaItem | null = null; @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @Consume @Watch('onModeChange') isSelectedMode: boolean; @State isSelected: boolean = false; @@ -55,44 +59,26 @@ export struct ImageGridItemComponent { @Link selectedCount: number; @State autoResize: boolean = true; loaded = false; - mPosition: number; + mPosition: number = 0; pageName = ''; @State isLoadImageError: boolean = false; @State pressAnimScale: number = 1.0; @State recycleDays: number = 0; @Consume rightClickMenuList: Array; - onMenuClicked: Function; - onMenuClickedForSingleItem: Function; + onMenuClicked: Function = (): void => {}; + onMenuClickedForSingleItem: Function = (): void => {}; @State geometryTransitionString: string = 'default_id'; @State isTap: boolean = false; @StorageLink('placeholderIndex') @Watch('verifyTapStatus') placeholderIndex: number = -1; @StorageLink('geometryTransitionBrowserId') @Watch('verifyTapStatus') geometryTransitionBrowserId: string = ''; - private imageThumbnail: string = undefined; - private transitionId: string; + private imageThumbnail: string = ''; + private transitionId: string = ''; private isEnteringPhoto = false; private isThird = false; private isThirdMultiPick: boolean = false; - private OPTS = { - 'sampleSize': 1, - 'rotateDegrees': 0, - 'editable': false, - 'desiredSize': { - 'width': 0, - 'height': 0 - }, - 'desiredRegion': { - 'size': { - 'width': 0, - 'height': 0 - }, - 'x': 0, - 'y': 0 - }, - 'desiredPixelFormat': 3, - }; private albumUri: string = ''; - private dataSource: MediaDataSource; - private geometryTapIndex: number; + private dataSource: MediaDataSource | null = null; + private geometryTapIndex: number = 0; private isTapStatusChange: boolean = false; verifyTapStatus() { @@ -116,12 +102,14 @@ export struct ImageGridItemComponent { } aboutToAppear(): void { - this.imageThumbnail = this.item?.thumbnail; - this.albumUri = AppStorage.Get(Constants.KEY_OF_ALBUM_URI); - if (this.isSelected) { - this.transitionId = `${this.item.hashCode}_${this.albumUri}_${this.isSelected}`; - } else { - this.transitionId = `${this.item.hashCode}_${this.albumUri}`; + this.imageThumbnail = this.item?.thumbnail ?? ''; + this.albumUri = AppStorage.get(Constants.KEY_OF_ALBUM_URI) as string; + if (this.item != null) { + if (this.isSelected) { + this.transitionId = `${this.item.hashCode}_${this.albumUri}_${this.isSelected}`; + } else { + this.transitionId = `${this.item.hashCode}_${this.albumUri}`; + } } if (this.isRecycle) { this.calculateRecycleDays(); @@ -131,7 +119,6 @@ export struct ImageGridItemComponent { } aboutToDisappear(): void { - Log.debug(TAG, `aboutToDisappear: ${this.item.uri}`); this.resetPressAnim(); } @@ -176,12 +163,13 @@ export struct ImageGridItemComponent { Log.info(TAG, 'change selected.'); let newState = !this.isSelected; AppStorage.SetOrCreate('focusUpdate', true); - if (this.item.uri) { + if (this.item != null && this.item.uri) { this.mPosition = this.getPosition(); - this.broadCast.emit(BroadCastConstants.SELECT, [this.mPosition, this.item.uri, newState, function(isSelected){ - Log.info(TAG, `enter callback, select status ${this.mPosition} ${this.item.uri} ${newState} ${this.isSelected}`); + this.broadCast.emit(BroadCastConstants.SELECT, [this.mPosition, this.item.uri, newState, (isSelected: boolean): void => { + let itemUri: string = this.item == null ? '' : this.item.uri; + Log.info(TAG, `enter callback, select status ${this.mPosition} ${itemUri} ${newState} ${this.isSelected}`); this.isSelected = isSelected == undefined ? newState : isSelected; - }.bind(this)]); + }]); } } @@ -211,7 +199,7 @@ export struct ImageGridItemComponent { } } }) - }, menu => menu.actionID.toString()) + }, (item: Action) => JSON.stringify(item)) } .width(ScreenManager.getInstance().getColumnsWidth(ColumnSize.COLUMN_TWO)) .borderRadius($r('sys.float.ohos_id_corner_radius_card')) @@ -228,6 +216,7 @@ export struct ImageGridItemComponent { }) } + build() { Column() { if (this.isTap) { @@ -252,7 +241,7 @@ export struct ImageGridItemComponent { .rotate({ x: 0, y: 0, z: 1, angle: 0 }) .objectFit(ImageFit.Cover) .autoResize(false) - .focusSetting(this.item.uri, this.handleKeyEvent.bind(this)) + .focusSetting(this.item == null ? '' : this.item.uri, (event: KeyEvent): void => this.handleKeyEvent(event)) .onError(() => { this.isLoadImageError = true; AppStorage.SetOrCreate('focusUpdate', true); @@ -265,11 +254,8 @@ export struct ImageGridItemComponent { this.requestFocus('ImageGridFocus_'); }) .geometryTransition(this.geometryTransitionString) - // @ts-ignore .transition(TransitionEffect.asymmetric( - // @ts-ignore - TransitionEffect.scale({ x: AppStorage.Get('geometryScale'), y: AppStorage.Get('geometryScale') }), - // @ts-ignore + TransitionEffect.scale({ x: AppStorage.get('geometryScale'), y: AppStorage.get('geometryScale') }), TransitionEffect.opacity(0.99))) if (this.geometryTransitionBrowserId === '' || !this.isTapStatusChange) { @@ -279,10 +265,10 @@ export struct ImageGridItemComponent { @Builder buildIcon() { - if (this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO || this.isRecycle) { + if (this.item != null && this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO || this.isRecycle) { Row() { // 缩略图左下角视频时长 - if (this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO) { + if (this.item != null && this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO) { Text(DateUtil.getFormattedDuration(this.item.duration)) .fontSize($r('sys.float.ohos_id_text_size_caption')) .fontFamily($r('app.string.id_text_font_family_regular')) @@ -317,7 +303,7 @@ export struct ImageGridItemComponent { [[$r('app.color.album_cover_gradient_start_color'), 0], [$r('app.color.transparent'), 1.0]] }) } - if (this.item.isFavor) { + if (this.item != null && this.item.isFavor) { Image($r('app.media.ic_favorite_overlay')) .height($r('app.float.overlay_icon_size')) .width($r('app.float.overlay_icon_size')) @@ -377,13 +363,13 @@ export struct ImageGridItemComponent { Stack({ alignContent: Alignment.Start }) { // 缩略图 if (this.isLoadImageError) { - Image((this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO) + Image((this.item != null && this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO) ? $r('app.media.alt_video_placeholder') : $r('app.media.alt_placeholder')) .aspectRatio(1) .rotate({ x: 0, y: 0, z: 1, angle: 0 }) .objectFit(ImageFit.Cover) .autoResize(false) - .focusSetting(this.item.uri, this.handleKeyEvent.bind(this)) + .focusSetting(this.item == null ? '' : this.item.uri, (event: KeyEvent): void => this.handleKeyEvent(event)) .onAppear(() => { Log.debug(TAG, `appear the default image!`); }) @@ -422,7 +408,7 @@ export struct ImageGridItemComponent { } // Press animation - if (event.type == TouchType.Down) { + if (event?.type === TouchType.Down) { animateTo({ duration: Constants.PRESS_ANIM_DURATION, curve: Curve.Ease @@ -431,7 +417,7 @@ export struct ImageGridItemComponent { }) } - if ((event.type == TouchType.Up || event.type == TouchType.Cancel) && this.pressAnimScale != 1) { + if ((event?.type == TouchType.Up || event?.type == TouchType.Cancel) && this.pressAnimScale != 1) { animateTo({ duration: Constants.PRESS_ANIM_DURATION, curve: Curve.Ease @@ -441,19 +427,20 @@ export struct ImageGridItemComponent { } }) .gesture(GestureGroup(GestureMode.Exclusive, - TapGesture().onAction((event: GestureEvent) => { - let ret: Boolean = focusControl.requestFocus('ImageGridFocus_' + this.item.uri); + TapGesture().onAction((event?: GestureEvent) => { + let ret: boolean = focusControl.requestFocus('ImageGridFocus_' + (this.item == null ? '' : this.item.uri)); if (ret !== true) { - Log.error(TAG, `requestFocus${'ImageGridFocus_' + this.item.uri}, ret:${ret}`); + let itemUri: string = this.item == null ? '' : this.item.uri; + Log.error(TAG, `requestFocus${'ImageGridFocus_' + itemUri}, ret:${ret}`); } - let msg = { - 'From': BigDataConstants.BY_CLICK, + let msg: Msg = { + from: BigDataConstants.BY_CLICK, } ReportToBigDataUtil.report(BigDataConstants.ENTER_PHOTO_BROWSER_WAY, msg); this.openPhotoBrowser(); }), - LongPressGesture().onAction((event: GestureEvent) => { - Log.info(TAG, `LongPressGesture ${event}`); + LongPressGesture().onAction((event?: GestureEvent) => { + Log.info(TAG, `LongPressGesture ${event as GestureEvent}`); this.selectStateChange(); this.pressAnimScale = 1; }) @@ -504,24 +491,25 @@ export struct ImageGridItemComponent { // 获取最近删除中,待回收照片倒计天数 private calculateRecycleDays(): void { let currentTimeSeconds: number = new Date().getTime() / 1000; - let trashedDay = DateUtil.convertSecondsToDays(currentTimeSeconds - this.item.dateTrashed); - Log.debug(TAG, `currentSec=${currentTimeSeconds}, trashedSec=${this.item.dateTrashed}, trashedDay=${trashedDay}`); + let itemDateTrashed: number = this.item == null ? 0 : this.item.dateTrashed; + let trashedDay = DateUtil.convertSecondsToDays(currentTimeSeconds - itemDateTrashed); + Log.debug(TAG, `currentSec=${currentTimeSeconds}, trashedSec=${itemDateTrashed}, trashedDay=${trashedDay}`); if (trashedDay > Constants.RECYCLE_DAYS_MAX) { this.recycleDays = 0; } else if (trashedDay <= 0) { this.recycleDays = Constants.RECYCLE_DAYS_MAX - 1; } else { - this.recycleDays = parseInt((Constants.RECYCLE_DAYS_MAX - trashedDay) + ''); + this.recycleDays = Number.parseInt((Constants.RECYCLE_DAYS_MAX - trashedDay) + ''); } } private requestFocus(keyName: string): void { - if (AppStorage.Get('deviceType') == Constants.DEFAULT_DEVICE_TYPE) { + if (AppStorage.get('deviceType') == Constants.DEFAULT_DEVICE_TYPE) { return; } - let positionUri = AppStorage.Get('focusPosition'); - let isUpdate = AppStorage.Get('focusUpdate'); - if (isUpdate && positionUri === this.item.uri) { + let positionUri = AppStorage.get('focusPosition'); + let isUpdate = AppStorage.get('focusUpdate'); + if (this.item !== null && isUpdate && positionUri === this.item.uri) { let ret: Boolean = focusControl.requestFocus(keyName + this.item.uri); if (ret !== true) { Log.error(TAG, `requestFocus${keyName + this.item.uri}, ret:${ret}`); @@ -552,8 +540,8 @@ export struct ImageGridItemComponent { if (KeyType.Up == event.type) { switch (event.keyCode) { case MultimodalInputManager.KEY_CODE_KEYBOARD_ENTER: - let msg = { - 'From': BigDataConstants.BY_KEYBOARD, + let msg: Msg = { + from: BigDataConstants.BY_KEYBOARD, } ReportToBigDataUtil.report(BigDataConstants.ENTER_PHOTO_BROWSER_WAY, msg); this.openPhotoBrowser(); @@ -573,6 +561,7 @@ export struct ImageGridItemComponent { } private getPosition(): number { + if (this.dataSource == null || this.item == null) return 0; return this.dataSource.getDataIndex(this.item) + this.dataSource.getGroupCountBeforeItem(this.item); } } \ No newline at end of file diff --git a/common/src/main/ets/default/view/NoPhotoComponent.ets b/common/src/main/ets/default/view/NoPhotoComponent.ets index 915aebb7..b1b212fc 100644 --- a/common/src/main/ets/default/view/NoPhotoComponent.ets +++ b/common/src/main/ets/default/view/NoPhotoComponent.ets @@ -21,7 +21,7 @@ const TAG: string = 'common_NoPhotoComponent'; @Component export struct NoPhotoComponent { - title: Resource; + title?: Resource; // set an initial value temporarily, later change to 0. @State offSetY: number = Constants.EMPTY_PAGE_DEFAULT_OFFSET; @@ -33,15 +33,13 @@ export struct NoPhotoComponent { aboutToAppear(): void { Log.info(TAG, `aboutToAppear`); - this.updateImageLayout = this.updateImageLayout.bind(this); - ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateImageLayout); + ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, (): void => this.updateImageLayout()); this.updateImageLayout(); } aboutToDisappear(): void { Log.info(TAG, 'aboutToDisappear'); - ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateImageLayout); - this.updateImageLayout = null; + ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, (): void => this.updateImageLayout()); } build() { diff --git a/common/src/main/ets/default/view/NoPhotoIndexComponent.ets b/common/src/main/ets/default/view/NoPhotoIndexComponent.ets index 8547d235..98f146ba 100644 --- a/common/src/main/ets/default/view/NoPhotoIndexComponent.ets +++ b/common/src/main/ets/default/view/NoPhotoIndexComponent.ets @@ -22,12 +22,12 @@ const TAG: string = 'common_NoPhotoIndexComponent'; @Component export struct NoPhotoIndexComponent { - index: number; - hasBarSpace: boolean; + index: number = 0; + hasBarSpace: boolean = false; // set an initial value temporarily, later change to 0. @State imageSize: number = 0; - private reSizeFunc = this.reSizeLayout.bind(this); + private reSizeFunc = (): void => this.reSizeLayout(); aboutToAppear(): void { Log.info(TAG, 'aboutToAppear'); @@ -35,14 +35,13 @@ export struct NoPhotoIndexComponent { this.updateImageSize(); } - reSizeLayout() { + reSizeLayout() { this.updateImageSize(); } aboutToDisappear(): void { Log.info(TAG, 'aboutToDisappear'); ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.reSizeFunc); - this.reSizeFunc = null; } updateImageSize() { diff --git a/common/src/main/ets/default/view/PhotoItem.ets b/common/src/main/ets/default/view/PhotoItem.ets index 47b70994..ce74219e 100644 --- a/common/src/main/ets/default/view/PhotoItem.ets +++ b/common/src/main/ets/default/view/PhotoItem.ets @@ -31,12 +31,13 @@ import { BigDataConstants, ReportToBigDataUtil } from '../utils/ReportToBigDataU import { MultimodalInputManager } from '../model/common/MultimodalInputManager'; import { BroadCastConstants } from '../model/common/BroadCastConstants'; import { PhotoDataSource } from '../model/browser/photo/PhotoDataSource'; +import { Matrix4x4 } from '../utils/Matrix4x4'; const TAG: string = 'common_PhotoItem'; @Component export struct PhotoItem { - @State @Watch('onViewDataChanged') item: MediaItem = new MediaItem(null); + @State @Watch('onViewDataChanged') item: MediaItem = new MediaItem(); @State matrix: Matrix4.Matrix4Transit = Matrix4.identity().copy(); @State mDirection: PanDirection = PanDirection.Vertical; // @Consume broadCast: BroadCast; @@ -49,12 +50,13 @@ export struct PhotoItem { @State lcdPixelMapUpdate: boolean = false; @Consume pageFrom: number; @Consume('transitionIndex') @Watch('onTransitionChange') updateTransition: number; - mPosition: number; - transitionTag: string; + mPosition: number = 0; + transitionTag: string = ''; @State isLoading: boolean = true; @State usePixmap: boolean = false; @Provide listCardWidth: number = 0; - verifyPhotoScaled: (matrix: Matrix4.Matrix4Transit) => void; + verifyPhotoScaled: (matrix: Matrix4.Matrix4Transit) => void = (matrix: Matrix4.Matrix4Transit): void => { + }; @Consume currentIndex: number; @StorageLink('geometryScale') geometryScale: number = 1; @StorageLink('geometryOffsetX') geometryOffsetX: number = 0; @@ -66,21 +68,21 @@ export struct PhotoItem { = ScreenManager.getInstance().isHorizontal(); @State isPhotoScaled: boolean = false; @State justifyWidth: boolean = true; - @State imageWidth: string = Constants.PERCENT_100; - @State imageHeight: string = Constants.PERCENT_100; + @State imageWidth?: string = Constants.PERCENT_100; + @State imageHeight?: string = Constants.PERCENT_100; @State isEdgeTop: boolean = true; @Link isRunningAnimation: boolean; @State geometryTransitionId: string = 'default_id'; @StorageLink('geometryTransitionBrowserId') @Watch('onGeometryIdChange') geometryTransitionBrowserId: string = ''; private lastUpdateTransition: number = -1; - private eventPipeline: EventPipeline; - private animationOption: AnimationParam = null; - private animationEndMatrix: Matrix4.Matrix4Transit = null; + private eventPipeline: EventPipeline | null = null; + private animationOption?: AnimationParam; + private animationEndMatrix?: Matrix4.Matrix4Transit; private isHandlingTap: boolean = false; - private timerCounter: number; + private timerCounter: number = 0; private imgScale: number = 1; private firstLoad: boolean = true; - private preItem = { height: 0, width: 0 }; + private preItem: PreItem = { height: 0, width: 0 }; private albumUri: string = ''; private imagePropertyComponentHeight: number = 578; private propertyHeightHorizontal: number = 300; @@ -92,12 +94,12 @@ export struct PhotoItem { private windowLayoutHeight: number = ScreenManager.getInstance().getWinLayoutHeight(); private windowColumns: number = ScreenManager.getInstance().getScreenColumns(); private isFromFACard: boolean = false; - private dataSource: PhotoDataSource; + private dataSource: PhotoDataSource | null = null; private isDefaultFA: boolean = false; private onWindowSizeChangeCallBack = () => this.onWindowSizeChanged(); - private onDataReloadFunc: Function = this.onDataReload.bind(this); - private resetDefaultScaleFunc: Function = this.resetDefaultScale.bind(this); - private saveScaleFunc: Function = this.saveScale.bind(this); + private onDataReloadFunc: Function = (addCount: KeyEvent): void => this.onDataReload(addCount); + private resetDefaultScaleFunc: Function = (): void => this.resetDefaultScale(); + private saveScaleFunc: Function = (): void => this.saveScale(); onGeometryIdChange() { this.geometryTransitionId = (this.mPosition === this.currentIndex) ? this.geometryTransitionBrowserId : 'default_id'; @@ -107,7 +109,7 @@ export struct PhotoItem { private onDataReload(addCount: KeyEvent): void { Log.info(TAG, `onDataReload ${this.item.uri}`); - let item: MediaItem = this.dataSource.getItemByUri(this.item.uri) as MediaItem; + let item: MediaItem | null = this.dataSource?.getItemByUri(this.item.uri) as MediaItem ?? null; if (item) { this.item = item; Log.debug(TAG, `Item[${this.item.uri}] is changed`); @@ -130,7 +132,6 @@ export struct PhotoItem { this.matrix = Matrix4.identity().copy(); this.isPhotoScaled = false; this.firstLoad = true; - this.eventPipelineSizeChange = this.eventPipelineSizeChange.bind(this) if (this.dataSource) { this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadFunc); } @@ -143,7 +144,7 @@ export struct PhotoItem { this.calculateImagePos(); this.onGeometryIdChange(); - let matrix: Matrix4.Matrix4Transit = AppStorage.Get(PhotoConstants.MATRIX); + let matrix: Matrix4.Matrix4Transit = AppStorage.get(PhotoConstants.MATRIX) as Matrix4.Matrix4Transit; if (this.currentIndex == this.mPosition && matrix) { this.matrix = matrix; this.updatePhotoScaledStatus(); @@ -165,13 +166,13 @@ export struct PhotoItem { duration: Constants.SCREEN_ROTATE_DURATION, curve: PhotoConstants.PHOTO_TRANSITION_CURVE, onFinish: () => { - this.eventPipeline.onAnimationEnd(this.animationEndMatrix); - this.animationOption = null; - this.animationEndMatrix = null; + this.eventPipeline?.onAnimationEnd(this.animationEndMatrix); + this.animationOption = undefined; + this.animationEndMatrix = undefined; } }, () => { this.eventPipelineSizeChange(); - this.matrix = this.animationEndMatrix; + this.matrix = this.animationEndMatrix as Matrix4.Matrix4Transit; this.calculateImagePos(); this.updateListCardWidth(); }); @@ -179,7 +180,7 @@ export struct PhotoItem { } eventPipelineSizeChange(): void { - this.eventPipeline.onComponentSizeChanged(vp2px(this.windowLayoutWidth), vp2px(this.windowLayoutHeight)); + this.eventPipeline?.onComponentSizeChanged(vp2px(this.windowLayoutWidth), vp2px(this.windowLayoutHeight)); } aboutToDisappear(): void { @@ -191,7 +192,6 @@ export struct PhotoItem { this.broadCast.off(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadFunc); } ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; this.broadCast.off(PhotoConstants.RESET_DEFAULT_SCALE + this.item.uri, this.resetDefaultScaleFunc); this.broadCast.off(PhotoConstants.SAVE_SCALE, this.saveScaleFunc); this.lcdPixelMapUpdate = false; @@ -241,20 +241,20 @@ export struct PhotoItem { } resetScaleAnimation(matrix: Matrix4.Matrix4Transit): void { - if (this.eventPipeline.isDefaultScale()) { + if (this.eventPipeline?.isDefaultScale()) { return; } - this.eventPipeline.startAnimation(matrix); + this.eventPipeline?.startAnimation(matrix); animateTo({ - duration: this.animationOption.duration, - curve: this.animationOption.curve, - onFinish: () => { - this.eventPipeline.onAnimationEnd(this.animationEndMatrix); - this.animationOption = null; - this.animationEndMatrix = null; + duration: (this.animationOption as AnimationParam).duration, + curve: (this.animationOption as AnimationParam).curve as Curve, + onFinish: (): void => { + this.eventPipeline?.onAnimationEnd(this.animationEndMatrix as Matrix4.Matrix4Transit); + this.animationOption = undefined; + this.animationEndMatrix = undefined; } }, () => { - this.matrix = this.animationEndMatrix; + this.matrix = this.animationEndMatrix as Matrix4.Matrix4Transit; this.updatePhotoScaledStatus(); }) } @@ -266,13 +266,15 @@ export struct PhotoItem { } updatePhotoScaledStatus() { - let matrix: any = this.matrix; + let matrix: Matrix4.Matrix4Transit = this.matrix; if (!!matrix) { - let mat = matrix.copy().matrix4x4; - let xScale = mat[Constants.NUMBER_0]; - let yScale = mat[Constants.NUMBER_5]; - Log.debug(TAG, `photo in PhotoItem has Scaled x scale: ${xScale}, y scale: ${yScale}, mat: ${mat}`); - this.isPhotoScaled = (xScale != 1 || yScale != 1); + let mat: number[] | undefined = (matrix.copy() as Matrix4x4).matrix4x4; + if (mat) { + let xScale: number = mat[Constants.NUMBER_0]; + let yScale: number = mat[Constants.NUMBER_5]; + Log.debug(TAG, `photo in PhotoItem has Scaled x scale: ${xScale}, y scale: ${yScale}, mat: ${mat}`); + this.isPhotoScaled = (xScale != 1 || yScale != 1); + } } else { this.isPhotoScaled = false; } @@ -302,11 +304,11 @@ export struct PhotoItem { this.broadCast.emit(PhotoConstants.PHOTO_SHOW_STATE, [false]); } }) - .onKeyEvent((event: KeyEvent) => { - this.handleKeyEvent(event); + .onKeyEvent((event?: KeyEvent) => { + this.handleKeyEvent(event as KeyEvent); }) - .width(this.imageWidth) - .height(this.imageHeight) + .width(this.imageWidth as string) + .height(this.imageHeight as string) .scale({ x: this.geometryScale, y: this.geometryScale @@ -316,15 +318,12 @@ export struct PhotoItem { y: this.geometryOffsetY }) .geometryTransition(this.geometryTransitionId) - // @ts-ignore .transition(TransitionEffect.asymmetric(TransitionEffect.opacity(0.99), - // @ts-ignore TransitionEffect.scale({ x: 1 / this.geometryScale, y: 1 / this.geometryScale, centerX: '50%', centerY: '50%' }) - // @ts-ignore .combine(TransitionEffect.opacity(0.99)) )) .onAppear(() => { @@ -377,8 +376,8 @@ export struct PhotoItem { this.broadCast.emit(PhotoConstants.PHOTO_SHOW_STATE, [false]); } }) - .onKeyEvent((event: KeyEvent) => { - this.handleKeyEvent(event); + .onKeyEvent((event?: KeyEvent) => { + this.handleKeyEvent(event as KeyEvent); }) .onAppear(() => { if (this.currentIndex == this.mPosition) { @@ -407,38 +406,38 @@ export struct PhotoItem { fingers: 2, distance: 1 }) - .onActionStart((event: GestureEvent) => { + .onActionStart((event?: GestureEvent) => { Log.info(TAG, 'PinchGesture onActionStart'); Log.info(TAG, `PinchGesture onActionStart scale:\ - ${event.scale}, cx: ${event.pinchCenterX}, cy: ${event.pinchCenterY}`); + ${(event as GestureEvent).scale}, cx: ${(event as GestureEvent).pinchCenterX}, cy: ${(event as GestureEvent).pinchCenterY}`); if (this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_IMAGE || this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO) { - this.eventPipeline.onScaleStart(event.scale, event.pinchCenterX, event.pinchCenterY); + this.eventPipeline?.onScaleStart((event as GestureEvent).scale, (event as GestureEvent).pinchCenterX, (event as GestureEvent).pinchCenterY); } }) - .onActionUpdate((event) => { - Log.info(TAG, `PinchGesture onActionUpdate scale: ${event.scale}`); + .onActionUpdate((event?: GestureEvent) => { + Log.debug(TAG, `PinchGesture onActionUpdate scale: ${(event as GestureEvent).scale}`); if (this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_IMAGE || this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO) { - this.eventPipeline.onScale(event.scale); + this.eventPipeline?.onScale((event as GestureEvent).scale); } }) .onActionEnd(() => { Log.info(TAG, 'PinchGesture onActionEnd'); if (this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_IMAGE || this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO) { - this.eventPipeline.onScaleEnd(); + this.eventPipeline?.onScaleEnd(); if (this.animationOption != null) { animateTo({ duration: this.animationOption.duration, curve: this.animationOption.curve, onFinish: () => { - this.eventPipeline.onAnimationEnd(this.animationEndMatrix); - this.animationOption = null; - this.animationEndMatrix = null; + this.eventPipeline?.onAnimationEnd(this.animationEndMatrix); + this.animationOption = undefined; + this.animationEndMatrix = undefined; } }, () => { - this.matrix = this.animationEndMatrix; + this.matrix = this.animationEndMatrix as Matrix4.Matrix4Transit; }) if (!!this.verifyPhotoScaled) { this.verifyPhotoScaled(this.matrix) @@ -451,50 +450,50 @@ export struct PhotoItem { PanGesture({ direction: this.mDirection }) - .onActionStart((event: GestureEvent) => { + .onActionStart((event?: GestureEvent) => { Log.info(TAG, `PanGesture start offsetX:\ - ${vp2px(event.offsetX)}, offsetY: ${vp2px(event.offsetY)}`); - if (this.isNeedShieldPullUpEvent(event)) { + ${vp2px((event as GestureEvent).offsetX)}, offsetY: ${vp2px((event as GestureEvent).offsetY)}`); + if (this.isNeedShieldPullUpEvent((event as GestureEvent))) { Log.info(TAG, `shield pullup event, is album recycle = ${this.albumUri == UserFileManagerAccess.getInstance() .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)},\ - is photo scaled = ${this.isPhotoScaled}, is pull Up = ${event.offsetY < 0}`); + is photo scaled = ${this.isPhotoScaled}, is pull Up = ${(event as GestureEvent).offsetY < 0}`); return; } - this.eventPipeline.onMoveStart(vp2px(event.offsetX), vp2px(event.offsetY)); + this.eventPipeline?.onMoveStart(vp2px((event as GestureEvent).offsetX), vp2px((event as GestureEvent).offsetY)); }) - .onActionUpdate((event: GestureEvent) => { + .onActionUpdate((event?: GestureEvent) => { Log.info(TAG, `PanGesture update offsetX:\ - ${vp2px(event.offsetX)}, offsetY: ${vp2px(event.offsetY)}`); - if (this.isNeedShieldPullUpEvent(event)) { + ${vp2px((event as GestureEvent).offsetX)}, offsetY: ${vp2px((event as GestureEvent).offsetY)}`); + if (this.isNeedShieldPullUpEvent((event as GestureEvent))) { return; } - this.eventPipeline.onMove(vp2px(event.offsetX), vp2px(event.offsetY)); - this.isPullDownAndDragPhoto = this.eventPipeline.canPullDownAndDragPhoto(); + this.eventPipeline?.onMove(vp2px((event as GestureEvent).offsetX), vp2px((event as GestureEvent).offsetY)); + this.isPullDownAndDragPhoto = this.eventPipeline?.canPullDownAndDragPhoto() ?? false; if (this.isPullDownAndDragPhoto && this.geometryTransitionEnable && !this.isOnSwiperAnimation && !this.isFromFACard) { - this.doDragPhoto(event.offsetX, event.offsetY); + this.doDragPhoto((event as GestureEvent).offsetX, (event as GestureEvent).offsetY); } }) - .onActionEnd((event: GestureEvent) => { + .onActionEnd((event?: GestureEvent) => { Log.info(TAG, `PanGesture end offsetX:\ - ${vp2px(event.offsetX)}, offsetY: ${vp2px(event.offsetY)} \ + ${vp2px((event as GestureEvent).offsetX)}, offsetY: ${vp2px((event as GestureEvent).offsetY)} \ this.isOnSwiperAnimation ${this.isOnSwiperAnimation}`); - if (this.isOnSwiperAnimation || this.isNeedShieldPullUpEvent(event)) { + if (this.isOnSwiperAnimation || this.isNeedShieldPullUpEvent((event as GestureEvent))) { return; } - this.eventPipeline.onMoveEnd(vp2px(event.offsetX), vp2px(event.offsetY)); - this.isPullDownAndDragPhoto = this.eventPipeline.canPullDownAndDragPhoto(); + this.eventPipeline?.onMoveEnd(vp2px((event as GestureEvent).offsetX), vp2px((event as GestureEvent).offsetY)); + this.isPullDownAndDragPhoto = this.eventPipeline?.canPullDownAndDragPhoto() ?? false; if (this.animationOption != null) { animateTo({ duration: this.animationOption.duration, curve: this.animationOption.curve, onFinish: () => { - this.eventPipeline.onAnimationEnd(this.animationEndMatrix); - this.animationOption = null; - this.animationEndMatrix = null; + this.eventPipeline?.onAnimationEnd(this.animationEndMatrix); + this.animationOption = undefined; + this.animationEndMatrix = undefined; } }, () => { - this.matrix = this.animationEndMatrix; + this.matrix = this.animationEndMatrix as Matrix4.Matrix4Transit; }) if (!!this.verifyPhotoScaled) { this.verifyPhotoScaled(this.matrix) @@ -506,11 +505,11 @@ export struct PhotoItem { TapGesture({ count: 1 }) - .onAction((event: GestureEvent) => { + .onAction((event?: GestureEvent) => { if (this.isHandlingTap) { if (this.timerCounter != null) { clearTimeout(this.timerCounter) - this.timerCounter = null; + this.timerCounter = 0; this.isHandlingTap = false; } } else { @@ -522,19 +521,19 @@ export struct PhotoItem { return; } Log.info(TAG, `onDoubleTap event: ${JSON.stringify(event)}`); - this.eventPipeline.onDoubleTap(event.fingerList[0].localX, event.fingerList[0].localY); + this.eventPipeline?.onDoubleTap((event as GestureEvent).fingerList[0].localX, (event as GestureEvent).fingerList[0].localY); if (this.animationOption != null) { Log.info(TAG, 'TapGesture animateTo start'); animateTo({ duration: this.animationOption.duration, curve: this.animationOption.curve, onFinish: () => { - this.eventPipeline.onAnimationEnd(this.animationEndMatrix); - this.animationOption = null; - this.animationEndMatrix = null; + this.eventPipeline?.onAnimationEnd(this.animationEndMatrix); + this.animationOption = undefined; + this.animationEndMatrix = undefined; } }, () => { - this.matrix = this.animationEndMatrix; + this.matrix = this.animationEndMatrix as Matrix4.Matrix4Transit; }) if (!!this.verifyPhotoScaled) { this.verifyPhotoScaled(this.matrix) @@ -545,9 +544,9 @@ export struct PhotoItem { ) ) .clip(true) - .onTouch((event) => { - this.dealTouchEvent(event); - this.eventPipeline.onTouch(event); + .onTouch((event?: TouchEvent) => { + this.dealTouchEvent(event as TouchEvent); + this.eventPipeline?.onTouch(event as TouchEvent); }) // TODO Remind users when pictures of other devices cannot be show if ((this.showError || this.item.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO) && @@ -585,9 +584,13 @@ export struct PhotoItem { previewUri: this.thumbnail } }) - let msg = { - 'PhotoButton': BigDataConstants.PHOTO_BUTTON_VIDEO, - 'From': BigDataConstants.LOCAL_MEDIA, + interface Msg { + photoButton: string; + from: string; + } + let msg: Msg = { + photoButton: BigDataConstants.PHOTO_BUTTON_VIDEO, + from: BigDataConstants.LOCAL_MEDIA, } ReportToBigDataUtil.report(BigDataConstants.CLICK_PHOTO_BUTTON_ID, msg); } @@ -686,6 +689,7 @@ export struct PhotoItem { } private dealTouchEvent(event: TouchEvent): void { + if (this.eventPipeline === null) return; if (!this.eventPipeline.canTouch() || this.isOnSwiperAnimation || event.touches.length > 1 || this.isPhotoScaled || this.isInSelectedMode || this.isDefaultFA) { return; } @@ -707,11 +711,14 @@ export struct PhotoItem { private handleKeyEvent(event: KeyEvent): void { Log.info(TAG, `type=${event.type}, keyCode=${event.keyCode}`); + interface Msg { + from: string; + } if (KeyType.Up == event.type) { switch (event.keyCode) { case MultimodalInputManager.KEY_CODE_KEYBOARD_ESC: - let msg = { - 'From': BigDataConstants.BY_KEYBOARD, + let msg: Msg = { + from: BigDataConstants.BY_KEYBOARD, } ReportToBigDataUtil.report(BigDataConstants.ESC_PHOTO_BROWSER_WAY, msg); this.broadCast.emit(PhotoConstants.PULL_DOWN_END, []); @@ -726,10 +733,6 @@ export struct PhotoItem { previewUri: this.thumbnail } }) - let msg = { - 'PhotoButton': BigDataConstants.PHOTO_BUTTON_VIDEO, - 'From': BigDataConstants.LOCAL_MEDIA, - } } break; default: @@ -744,3 +747,8 @@ export struct PhotoItem { !this.isPhotoScaled; } } + +interface PreItem { + height: number; + width: number; +} diff --git a/common/src/main/ets/default/view/PhotoSwiper.ets b/common/src/main/ets/default/view/PhotoSwiper.ets index 90654dc7..d962c0db 100644 --- a/common/src/main/ets/default/view/PhotoSwiper.ets +++ b/common/src/main/ets/default/view/PhotoSwiper.ets @@ -21,46 +21,59 @@ import { BroadCast } from '../utils/BroadCast'; import Curves from '@ohos.curves'; import { Constants } from '../model/common/Constants'; import { Constants as BrowserConstants } from '../model/browser/photo/Constants'; +import { PhotoDataSource } from '../model/browser/photo/PhotoDataSource'; +import { MediaItem } from '../model/browser/photo/MediaItem'; const TAG: string = 'common_PhotoSwiper'; +export interface Results { + data: MediaItem; + pos: number; + thumbnail: string; +}; + @Component export struct PhotoSwiper { - mTransition: string; + mTransition: string = ''; @Consume currentIndex: number; @Link broadCast: BroadCast; @State mDuration: number = 300; - onPhotoChanged: Function; - swiperController: SwiperController; - isInSelectedMode: boolean; + onPhotoChanged: Function = (): void => {}; + swiperController?: SwiperController; + isInSelectedMode: boolean = false; @Consume canSwipe: boolean; swiperItemSpace: number = Constants.NUMBER_8; - verifyPhotoScaledFunc: (matrix: Matrix4.Matrix4Transit) => void + verifyPhotoScaledFunc: (matrix?: Matrix4.Matrix4Transit) => void = (matrix?: Matrix4.Matrix4Transit): void => {} @Link isRunningAnimation: boolean; isLeftSwiper: boolean = false; @Consume isDeleting: boolean; @State isOnSwiperAnimation: boolean = false; - private dataSource; + private dataSource?: PhotoDataSource; private geometryTransitionEnable: boolean = false; private isFromFACard: boolean = false; private SWIPE_CACHE_COUNT: number = 2; + private onDataReloadFunc: Function = (addCount: number): void => this.onDataReload(addCount); + private onChangeSwiperDurationFunc: Function = (value: number): void => this.onChangeSwiperDuration(value); - aboutToAppear() { - this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, (addCount) => { - let totalCount = this.dataSource.totalCount(); - if (addCount > Constants.NUMBER_0) { + private onDataReload(addCount: number): void { + let totalCount = this.dataSource == null ? 0 : this.dataSource.totalCount(); + let add = addCount; + if (add > Constants.NUMBER_0) { + if (this.dataSource != null) { this.dataSource.onDataReloaded(); - if (this.currentIndex + addCount < totalCount) { - this.currentIndex += addCount; - } - Log.info(TAG, `ON_DATA_RELOADED: ${this.currentIndex}, ${addCount}`); - return; } - Log.debug(TAG, 'animate to data reloaded start'); - animateTo({ - duration: 300, // 删除动画时长 - curve: Curves.cubicBezier(0.0, 0.0, 0.2, 1.0), // 减速曲线参数 - onFinish: () => { + if (this.currentIndex + add < totalCount) { + this.currentIndex += add; + } + Log.info(TAG, `ON_DATA_RELOADED: ${this.currentIndex}, ${add}`); + return; + } + Log.debug(TAG, 'animate to data reloaded start'); + animateTo({ + duration: 300, // 删除动画时长 + curve: Curves.cubicBezier(0.0, 0.0, 0.2, 1.0), // 减速曲线参数 + onFinish: () => { + if (this.dataSource != null) { let totalCount = this.dataSource.totalCount(); this.dataSource.onDataChanged(this.currentIndex); // UPDATE NEXT TWO DATA FOR AVOID NOT LOADING DATA @@ -71,30 +84,37 @@ export struct PhotoSwiper { this.dataSource.onDataChanged(this.currentIndex + 2); } this.dataSource.onDataReloaded(); - } }, () => { - if (this.isDeleting) { - this.dataSource.deleteData(this.currentIndex); } - if (this.currentIndex === this.dataSource.totalCount() || (this.isDeleting && this.isLeftSwiper && this.currentIndex > 0)) { - this.currentIndex--; - } - this.isDeleting = false; - }) - }); + } }, () => { + if (this.dataSource != null && this.isDeleting) { + this.dataSource.deleteData(this.currentIndex); + } + if (this.dataSource != null && this.currentIndex === this.dataSource.totalCount() || (this.isDeleting && this.isLeftSwiper && this.currentIndex > 0)) { + this.currentIndex--; + } + this.isDeleting = false; + }) + } - this.broadCast.on(BroadCastConstants.CHANGE_SWIPER_DURATION, (value) => { - Log.debug(TAG, `change duration start ${value}`); - this.mDuration = value; - }); + private onChangeSwiperDuration(value: number): void { + Log.debug(TAG, `change duration start ${value}`); + this.mDuration = value; + } + + aboutToAppear() { + this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadFunc); + this.broadCast.on(BroadCastConstants.CHANGE_SWIPER_DURATION, this.onChangeSwiperDurationFunc); } aboutToDisappear(): void { this.swiperController = undefined; + this.broadCast.off(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadFunc); + this.broadCast.off(BroadCastConstants.CHANGE_SWIPER_DURATION, this.onChangeSwiperDurationFunc); } build() { Swiper(this.swiperController) { - LazyForEach(this.dataSource, (item, index?: number) => { + LazyForEach(this.dataSource as PhotoDataSource, (item: Results, index?: number) => { if (!!item) { Column() { PhotoItem({ @@ -103,7 +123,7 @@ export struct PhotoSwiper { thumbnail: item.thumbnail, transitionTag: this.mTransition ? this.mTransition : 'default_id', verifyPhotoScaled: this.verifyPhotoScaledFunc, - albumUri: this.dataSource.getAlbumUri(), + albumUri: (this.dataSource == null ? '' : this.dataSource.getAlbumUri()), geometryTransitionEnable: this.geometryTransitionEnable, broadCast: $broadCast, isRunningAnimation: $isRunningAnimation, @@ -114,7 +134,7 @@ export struct PhotoSwiper { }) }.zIndex(item.pos == this.currentIndex ? 2 : 1) } - }, (item, index) => { + }, (item: Results, index?: number) => { if (item == null || item == undefined) { return JSON.stringify(item) + index; } @@ -127,7 +147,7 @@ export struct PhotoSwiper { .parallelGesture(PanGesture({ direction: PanDirection.Horizontal }) - .onActionStart((event: GestureEvent) => { + .onActionStart((event?: GestureEvent) => { if (!this.canSwipe) { this.isOnSwiperAnimation = true; } diff --git a/common/src/main/ets/default/view/TabBar.ets b/common/src/main/ets/default/view/TabBar.ets index c2ae4ab6..f64cf33d 100644 --- a/common/src/main/ets/default/view/TabBar.ets +++ b/common/src/main/ets/default/view/TabBar.ets @@ -28,34 +28,35 @@ export enum DEVICE_TYPE { PC_LIKE } -const TabMap = { - 0: BigDataConstants.PHOTO_TAB, - 1: BigDataConstants.ALBUM_TAB, -} +const TabMap = [ +BigDataConstants.PHOTO_TAB, +BigDataConstants.ALBUM_TAB +] @Component export struct TabBar { @Consume isSelectedMode: boolean; @Consume isAlbumSetSelectedMode: boolean; @Consume isShowSideBar: boolean; - @Link @Watch('updateCurrentIndex') currentIndex: number; + @Link @Watch('updateCurrentIndex') currentIndex: 0 | 1; @Link isSidebar: boolean; @StorageLink('sideBarBoundaryLineOpacity') sideBarBoundaryLineOpacity: number = 1; @StorageLink('sideBarOpacity') sideBarOpacity: number = 1; private tabs: TabItem[] = []; - private controller: TabsController; + private controller: TabsController | null = null; private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); private deviceType: DEVICE_TYPE = DEVICE_TYPE.PC_LIKE; + private funcOnTabSelected?: Function; aboutToAppear(): void { - this.onTabSelected = this.onTabSelected.bind(this); + this.funcOnTabSelected = (index: number): void => this.onTabSelected(index); this.tabs[this.currentIndex].isSelected = true; this.tabs.forEach((tab: TabItem) => { - Log.info(TAG, `${JSON.stringify(tab.name)} , ${tab.iconSelected}`) + Log.info(TAG, `${JSON.stringify(tab.name)} , ${tab.iconSelected}`); }); } - updateCurrentIndex() { + updateCurrentIndex(): void { this.onTabSelected(this.currentIndex); } @@ -72,23 +73,25 @@ export struct TabBar { Tab({ tabItem: tab, index: this.tabs.indexOf(tab), - onTabSelected: this.onTabSelected, + onTabSelected: this.funcOnTabSelected, isSidebar: $isSidebar, deviceType: this.deviceType }) - }, tab => tab.name.id) + }, (tab: TabItem): string => { + return (tab.name.id).toString(); + }) } - .padding({ left: Constants.NUMBER_16, top: Constants.NUMBER_96, right: Constants.NUMBER_16 }) - .flexGrow(Constants.NUMBER_1) + .padding({ left: 16, top: 96, right: 16 }) + .flexGrow(1) .backgroundColor($r('app.color.default_background_color')) // Sidebar boundary line if (this.isShowSideBar) { Row() { } - .width(Constants.NUMBER_0) + .width(0) .height(Constants.PERCENT_100) - .border({ width: Constants.NUMBER_0_5, color: $r('app.color.album_cover_gradient_start_color') }) + .border({ width: 0.5, color: $r('app.color.album_cover_gradient_start_color') }) .opacity(this.sideBarBoundaryLineOpacity) } } @@ -104,13 +107,15 @@ export struct TabBar { Tab({ tabItem: tab, index: this.tabs.indexOf(tab), - onTabSelected: this.onTabSelected, + onTabSelected: this.funcOnTabSelected, isSidebar: $isSidebar, deviceType: this.deviceType }) } - .layoutWeight(Constants.NUMBER_1) - }, tab => tab.name.id) + .layoutWeight(1) + }, (tab: TabItem): string => { + return (tab.name.id).toString(); + }) } .height($r('app.float.horizontal_width')) } @@ -126,14 +131,22 @@ export struct TabBar { }) { ForEach(this.tabs, (tab: TabItem) => { Stack() { - TabPhone({ tabItem: tab, index: this.tabs.indexOf(tab), onTabSelected: this.onTabSelected }) + TabPhone({ tabItem: tab, index: this.tabs.indexOf(tab), onTabSelected: this.funcOnTabSelected }) } .layoutWeight(1) .onClick(() => { - this.onTabSelected && this.onTabSelected(this.tabs.indexOf(tab)); + if (this.funcOnTabSelected) { + if (this.currentIndex == this.tabs.indexOf(tab)) { + Log.debug(TAG, `it is same: ${this.currentIndex}`); + this.appBroadCast.emit(BroadCastConstants.RESET_ZERO, [this.currentIndex]); + } + this.funcOnTabSelected(this.tabs.indexOf(tab)); + } tab.isSelected = true; }) - }, tab => tab.name.id) + }, (tab: TabItem): string => { + return (tab.name.id).toString(); + }) } .visibility((this.isSelectedMode || this.isAlbumSetSelectedMode) ? Visibility.None : Visibility.Visible) .height($r('app.float.tab_bar_vertical_height')) @@ -143,13 +156,9 @@ export struct TabBar { } private onTabSelected(index: number): void { - Log.debug(TAG, `this.currentIndex: ${this.currentIndex} index: ${index}`); - if (this.currentIndex == index) { - Log.error(TAG, `it is same: ${index}`); - this.appBroadCast.emit(BroadCastConstants.RESET_ZERO, [index]); - } - this.currentIndex = index; - this.controller.changeIndex(this.currentIndex); + Log.debug(TAG, `TabBar this.currentIndex: ${this.currentIndex} index: ${index}`); + this.currentIndex = index as 0 | 1; + if (this.controller != null) this.controller.changeIndex(this.currentIndex); this.tabs.forEach((tab: TabItem) => { if (this.tabs.indexOf(tab) == index) { tab.isSelected = true; @@ -157,10 +166,14 @@ export struct TabBar { tab.isSelected = false; } }) - let currentTab = TabMap[this.currentIndex] ? TabMap[this.currentIndex] : BigDataConstants.PHOTO_TAB; - let msg = { - 'SwitchTab': BigDataConstants.CLICK_SWITCH, - 'Current': currentTab, + let currentTab: string = TabMap[this.currentIndex] ? TabMap[this.currentIndex] : BigDataConstants.PHOTO_TAB; + interface Msg { + switchTab: string; + current: string; + } + let msg: Msg = { + switchTab: BigDataConstants.CLICK_SWITCH, + current: currentTab, } ReportToBigDataUtil.report(BigDataConstants.TAB_SWITCH_ID, msg); Log.info(TAG, `select ${this.currentIndex}`); @@ -172,9 +185,9 @@ export struct TabBar { struct Tab { @ObjectLink tabItem: TabItem; @Link isSidebar: boolean; - index: number; - onTabSelected: Function; - private deviceType: number; + index: number = 0; + onTabSelected?: Function; + private deviceType: number = 0; build() { if (this.deviceType == DEVICE_TYPE.PC_LIKE) { @@ -185,6 +198,7 @@ struct Tab { }) { Stack() { Image(this.tabItem.getIcon(this.tabItem.isSelected)) + .draggable(false) .height($r('app.float.icon_size')) .width($r('app.float.icon_size')) .objectFit(ImageFit.Fill) @@ -206,7 +220,7 @@ struct Tab { } .backgroundColor(this.tabItem.isSelected ? '#DAE2F5' : $r('app.color.transparent')) .borderRadius($r('app.float.single_tab_margin')) - .onClick(() => { + .onClick((): void => { this.onTabSelected && this.onTabSelected(this.index); this.tabItem.isSelected = true; }) @@ -218,12 +232,13 @@ struct Tab { }) { Stack() { Image(this.tabItem.getIcon(this.tabItem.isSelected)) + .draggable(false) .height($r('app.float.icon_size')) .width($r('app.float.icon_size')) .objectFit(ImageFit.Fill) } .padding({ - left: this.isSidebar ? Constants.NUMBER_0 : $r('app.float.tab_bar_text_padding_left'), + left: this.isSidebar ? 0 : $r('app.float.tab_bar_text_padding_left'), }) Text(this.tabItem.name) @@ -236,7 +251,7 @@ struct Tab { right: $r('app.float.tab_bar_text_padding_horizontal') }) } - .onClick(() => { + .onClick((): void => { this.onTabSelected && this.onTabSelected(this.index); this.tabItem.isSelected = true; }) @@ -248,8 +263,8 @@ struct Tab { @Component struct TabPhone { @ObjectLink tabItem: TabItem; - index: number; - onTabSelected: Function; + index: number = 0; + onTabSelected?: Function; build() { Flex({ @@ -258,6 +273,7 @@ struct TabPhone { justifyContent: FlexAlign.Center }) { Image(this.tabItem.getIcon(this.tabItem.isSelected)) + .draggable(false) .height($r('app.float.icon_size')) .width($r('app.float.icon_size')) .objectFit(ImageFit.Fill) @@ -285,12 +301,13 @@ struct TabPhone { @Component export struct TabBarForAlbumSet { @Consume isTabBarShow: boolean; - private currentIndex: number; + private currentIndex: number = 0; private tabs: TabItemWithText[] = []; - private controller: TabsController; + private controller: TabsController | null = null; + private funcOnTabSelected?: Function; aboutToAppear(): void { - this.onTabSelected = this.onTabSelected.bind(this); + this.funcOnTabSelected = (index: number): void => this.onTabSelected(index); this.tabs[this.currentIndex].isSelected = true; this.tabs.forEach((tab: TabItemWithText) => { Log.info(TAG, `${JSON.stringify(tab.name)}, ${tab.isSelected}`); @@ -305,8 +322,10 @@ export struct TabBarForAlbumSet { alignItems: ItemAlign.Start }) { ForEach(this.tabs, (tab: TabItemWithText) => { - TabWithText({ tabItemWithText: tab, index: this.tabs.indexOf(tab), onTabSelected: this.onTabSelected }) - }, tab => tab.name.id) + TabWithText({ tabItemWithText: tab, index: this.tabs.indexOf(tab), onTabSelected: this.funcOnTabSelected }) + }, (tab: TabItemWithText): string => { + return (tab.name.id).toString(); + }) } .width('100%') .height($r('app.float.album_set_tab_bar_height')) @@ -315,10 +334,10 @@ export struct TabBarForAlbumSet { } } - private onTabSelected(index: number) { - Log.info(TAG, `this.currentIndex: ${this.currentIndex} index: ${index}`); + private onTabSelected(index: number): void { + Log.info(TAG, `TabBarForAlbumSet this.currentIndex: ${this.currentIndex} index: ${index}`); this.currentIndex = index; - this.controller.changeIndex(this.currentIndex); + if (this.controller != null) this.controller.changeIndex(this.currentIndex); this.tabs.forEach((tab: TabItemWithText) => { tab.isSelected = false; }) @@ -333,8 +352,8 @@ struct TabWithText { @Consume isAlbumSetSelectedMode: boolean; @ObjectLink tabItemWithText: TabItemWithText; @State TabWidth: number = 0; - index: number; - onTabSelected: Function; + index: number = 0; + onTabSelected?: Function; aboutToAppear(): void { // Determine the length of the underline based on the font length @@ -371,7 +390,7 @@ struct TabWithText { .height('100%') .onClick(() => { if (!this.isAlbumSetSelectedMode) { - this.onTabSelected && this.onTabSelected(this.index) + this.onTabSelected && this.onTabSelected(this.index); this.tabItemWithText.isSelected = true } }) diff --git a/common/src/main/ets/default/view/ThirdSelectPhotoBrowserActionBar.ets b/common/src/main/ets/default/view/ThirdSelectPhotoBrowserActionBar.ets index 2136d663..8550abac 100644 --- a/common/src/main/ets/default/view/ThirdSelectPhotoBrowserActionBar.ets +++ b/common/src/main/ets/default/view/ThirdSelectPhotoBrowserActionBar.ets @@ -28,7 +28,7 @@ export struct ThirdSelectPhotoBrowserActionBar { = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; @State isMultiPick: boolean = false; @Consume @Watch('createActionBar') isSelected: boolean; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @StorageLink('isHorizontal') @Watch('createActionBar') isHorizontal: boolean = ScreenManager.getInstance() .isHorizontal(); @State actionBarProp: ActionBarProp = new ActionBarProp(); @@ -38,7 +38,7 @@ export struct ThirdSelectPhotoBrowserActionBar { @Link @Watch('onSelectedCountChanged') totalSelectedCount: number; @Provide moreMenuList: Action[] = new Array(); @Provide hidePopup: boolean = false; - private title: string | Resource; + private title: string | Resource = ''; private isThird: boolean = false; aboutToAppear() { diff --git a/common/src/main/ets/default/view/actionbar/ActionBar.ets b/common/src/main/ets/default/view/actionbar/ActionBar.ets index 964eaa7e..561c4afe 100644 --- a/common/src/main/ets/default/view/actionbar/ActionBar.ets +++ b/common/src/main/ets/default/view/actionbar/ActionBar.ets @@ -32,11 +32,11 @@ const TAG: string = 'common_ActionBar'; @Component export struct ActionBar { @Link actionBarProp: ActionBarProp; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; isVideoPage: boolean = false; isFromPhotoBrowser: boolean = false; @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); - @Prop isNeedPlaceholder: boolean; + @Prop isNeedPlaceholder: boolean = false; createArray(): ActionBarProp[] { let actionBarProps = new Array(); @@ -57,7 +57,7 @@ export struct ActionBar { .height(Constants.NUMBER_32) } if (!this.actionBarProp.getLeftAction().equals(Action.NONE)) { - ForEach(this.createArray(), (item) => { + ForEach(this.createArray(), (item: ActionBarProp) => { ActionBarButton({ res: item.getLeftAction().iconRes, action: item.getLeftAction(), diff --git a/common/src/main/ets/default/view/actionbar/ActionBarButton.ets b/common/src/main/ets/default/view/actionbar/ActionBarButton.ets index 7d3fa468..084f6ac6 100644 --- a/common/src/main/ets/default/view/actionbar/ActionBarButton.ets +++ b/common/src/main/ets/default/view/actionbar/ActionBarButton.ets @@ -21,20 +21,20 @@ import { Constants } from '../../model/common/Constants'; @Component export struct ActionBarButton { @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); - @State res: Resource = undefined; - action: Action; - onMenuClicked: Function; + @State res: Resource | undefined = undefined; + action: Action = Action.NONE; + onMenuClicked: Function = (): void => {}; isLeft = true; isFirst = false; isAutoTint = true; - colorMode: ActionBarColorMode; + colorMode: ActionBarColorMode = ActionBarColorMode.NORMAL; @State showPopup: boolean = false; @Consume moreMenuList: Action[]; @Consume @Watch("isNeedHidePopup") hidePopup: boolean; - private isPadDeviceType: boolean; + private isPadDeviceType: boolean = false; aboutToAppear(): void { - this.isPadDeviceType = AppStorage.Get('deviceType') !== Constants.DEFAULT_DEVICE_TYPE; + this.isPadDeviceType = AppStorage.get('deviceType') !== Constants.DEFAULT_DEVICE_TYPE; } isNeedHidePopup(): void { @@ -62,7 +62,7 @@ export struct ActionBarButton { .color($r('sys.color.ohos_id_color_list_separator')) .key('ActionBarButton_Divider_' + menu.componentKey) } - }, menu => menu.actionID.toString()) + }, (menu: Action) => menu.actionID.toString()) } .width(ScreenManager.getInstance().getColumnsWidth(ColumnSize.COLUMN_TWO)) .borderRadius($r('sys.float.ohos_id_corner_radius_default_l')) diff --git a/common/src/main/ets/default/view/actionbar/DetailMenuPanel.ets b/common/src/main/ets/default/view/actionbar/DetailMenuPanel.ets index 8408333b..76c12907 100644 --- a/common/src/main/ets/default/view/actionbar/DetailMenuPanel.ets +++ b/common/src/main/ets/default/view/actionbar/DetailMenuPanel.ets @@ -25,7 +25,7 @@ const TAG: string = 'common_DetailMenuPanel'; export struct DetailMenuPanel { @Consume menuList: Action[]; actionBarProp: ActionBarProp = new ActionBarProp(); - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; isLeft = false; build() { @@ -41,7 +41,7 @@ export struct DetailMenuPanel { colorMode: this.actionBarProp.getColorMode() }) .margin({ right: $r('app.float.max_padding_end') }) - }, menu => menu.actionID.toString()) + }, (menu: Action) => menu.actionID.toString()) } .key('DetailMenuPanel') } diff --git a/common/src/main/ets/default/view/actionbar/MenuPanel.ets b/common/src/main/ets/default/view/actionbar/MenuPanel.ets index 3e8f35be..20de1877 100644 --- a/common/src/main/ets/default/view/actionbar/MenuPanel.ets +++ b/common/src/main/ets/default/view/actionbar/MenuPanel.ets @@ -25,7 +25,7 @@ const TAG: string = 'common_MenuPanel'; export struct MenuPanel { @Link @Watch('onActionBarPropChanged') actionBarProp: ActionBarProp; @State menuList: Action[] = []; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; aboutToAppear(): void { Log.info(TAG, 'aboutToAppear.'); @@ -44,7 +44,7 @@ export struct MenuPanel { colorMode: this.actionBarProp.getColorMode() }) .margin({ right: $r('app.float.max_padding_end') }) - }, menu => String(menu.actionID)) + }, (menu: Action) => String(menu.actionID)) } .alignItems(VerticalAlign.Center) } diff --git a/common/src/main/ets/default/view/actionbar/ToolBar.ets b/common/src/main/ets/default/view/actionbar/ToolBar.ets index 4a5ddd0b..5de78dd6 100644 --- a/common/src/main/ets/default/view/actionbar/ToolBar.ets +++ b/common/src/main/ets/default/view/actionbar/ToolBar.ets @@ -21,8 +21,8 @@ import { Action } from '../browserOperation/Action'; import { ActionBarMode } from '../browserOperation/ActionBarMode'; export class MenuItem { - value: string; - action: () => void; + value?: string; + action?: () => void; } @Component @@ -35,7 +35,7 @@ export struct ToolBar { @Consume moreMenuList: Action[]; @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @State showPopup: boolean = false; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @State actionBarProp: ActionBarProp = new ActionBarProp(); @Consume @Watch("isNeedHidePopup") hidePopup: boolean; private isFromPhotoBrowser = false; @@ -69,7 +69,7 @@ export struct ToolBar { .strokeWidth(Constants.MENU_DIVIDER_STROKE_WIDTH) .color($r('sys.color.ohos_id_color_list_separator')) } - }, menu => menu.actionID.toString()) + }, (menu: Action) => menu.actionID.toString()) } .width(ScreenManager.getInstance().getColumnsWidth(ColumnSize.COLUMN_TWO)) .borderRadius($r('sys.float.ohos_id_corner_radius_card')) @@ -157,7 +157,7 @@ export struct ToolBar { .width(`${100 / this.toolMenuList.length}%`) .height(Constants.PERCENT_100) } - }, menu => menu.actionID.toString()) + }, (menu: Action) => menu.actionID.toString()) } .width(Constants.PERCENT_100) .height(Constants.ActionBarHeight) diff --git a/common/src/main/ets/default/view/actionbar/ToolBarButton.ets b/common/src/main/ets/default/view/actionbar/ToolBarButton.ets index e8033c4f..42818aab 100644 --- a/common/src/main/ets/default/view/actionbar/ToolBarButton.ets +++ b/common/src/main/ets/default/view/actionbar/ToolBarButton.ets @@ -18,11 +18,11 @@ import { ActionBarColorMode } from '../browserOperation/ActionBarMode'; @Component export struct ToolBarButton { - @State res: Resource = undefined; - action: Action; + @State res: Resource | undefined = undefined; + action: Action = Action.NONE; isLeft = true; isAutoTint = true; - colorMode: ActionBarColorMode; + colorMode: ActionBarColorMode = ActionBarColorMode.NORMAL; build() { Flex({ diff --git a/common/src/main/ets/default/view/browserOperation/AlbumListCard.ets b/common/src/main/ets/default/view/browserOperation/AlbumListCard.ets index 92e0e612..ee66c35c 100644 --- a/common/src/main/ets/default/view/browserOperation/AlbumListCard.ets +++ b/common/src/main/ets/default/view/browserOperation/AlbumListCard.ets @@ -25,8 +25,8 @@ export struct AlbumListCard { @State isEmptyAlbum: boolean = false; @State useAlt: boolean = false; @Consume broadCast: BroadCast; - item: AlbumInfo; - index: number; + item: AlbumInfo | null = null; + index: number = 0; readonly imageCenterLength: number = 28; private dividerMarginRight = 12; @@ -35,21 +35,25 @@ export struct AlbumListCard { } mediaOperation() { - this.broadCast.emit(BroadCastConstants.MEDIA_OPERATION, [this.item.albumName, this.item.uri]); - } + if (this.broadCast != null && this.item != null) { + this.broadCast.emit(BroadCastConstants.MEDIA_OPERATION, [this.item.albumName, this.item.uri]); + } } - showMediaRes(): Resource { - if (this.item.videoCount == 0) { - return $r('app.plural.show_photo_num', this.item.count, this.item.count); - } else if (this.item.videoCount == this.item.count) { - return $r('app.plural.show_video_num', this.item.count, this.item.count); - } else if (this.item.videoCount == 1) { - return $r('app.plural.show_one_video_with_photo_num', this.item.count - this.item.videoCount, - this.item.count - this.item.videoCount, this.item.videoCount); - } else { - return $r('app.plural.show_multi_video_with_photo_num', this.item.count - this.item.videoCount, - this.item.count - this.item.videoCount, this.item.videoCount) + showMediaRes(): Resource | undefined { + if (this.item != null) { + if (this.item.videoCount == 0) { + return $r('app.plural.show_photo_num', this.item.count, this.item.count); + } else if (this.item.videoCount == this.item.count) { + return $r('app.plural.show_video_num', this.item.count, this.item.count); + } else if (this.item.videoCount == 1) { + return $r('app.plural.show_one_video_with_photo_num', this.item.count - this.item.videoCount, + this.item.count - this.item.videoCount, this.item.videoCount); + } else { + return $r('app.plural.show_multi_video_with_photo_num', this.item.count - this.item.videoCount, + this.item.count - this.item.videoCount, this.item.videoCount) + } } + return undefined; } build() { @@ -80,7 +84,7 @@ export struct AlbumListCard { .border({ radius: $r('sys.float.ohos_id_corner_radius_default_m') }) .flexShrink(0) } else { - Image(this.item.coverUri) + Image(this.item == null ? '' : this.item.coverUri) .aspectRatio(1) .autoResize(false) .objectFit(ImageFit.Cover) @@ -101,7 +105,7 @@ export struct AlbumListCard { } Column() { - Text(this.item.albumName) + Text(this.item == null ? '' : this.item.albumName) .fontSize($r('sys.float.ohos_id_text_size_body1')) .fontColor($r('sys.color.ohos_id_color_primary')) .maxLines(1) @@ -109,7 +113,7 @@ export struct AlbumListCard { .padding({ bottom: $r('sys.float.ohos_id_text_margin_vertical') }) - if (this.item.count != 0) { + if (this.item != null && this.item.count != 0) { Text(this.showMediaRes()) .fontSize($r('sys.float.ohos_id_text_size_body2')) .fontColor($r('sys.color.ohos_id_color_text_secondary')) diff --git a/common/src/main/ets/default/view/browserOperation/AlbumSetNewMenuOperation.ets b/common/src/main/ets/default/view/browserOperation/AlbumSetNewMenuOperation.ets index 3b4edb51..5a40a506 100644 --- a/common/src/main/ets/default/view/browserOperation/AlbumSetNewMenuOperation.ets +++ b/common/src/main/ets/default/view/browserOperation/AlbumSetNewMenuOperation.ets @@ -17,7 +17,7 @@ import { Log } from '../../utils/Log'; import { BroadCastConstants } from '../../model/common/BroadCastConstants'; import { MenuOperationCallback } from './MenuOperationCallback'; import { MenuOperation } from './MenuOperation'; -import { MenuContext } from './MenuContext'; +import { MenuContext, SourceSceneType } from './MenuContext'; import { JumpSourceToMain } from '../../model/browser/photo/JumpSourceToMain'; import { AlbumInfo } from '../../model/browser/album/AlbumInfo'; import router from '@ohos.router'; @@ -26,13 +26,14 @@ import { AlbumDefine } from '../../model/browser/AlbumDefine'; import { BrowserDataFactory } from '../../interface/BrowserDataFactory'; import { BigDataConstants, ReportToBigDataUtil } from '../../utils/ReportToBigDataUtil'; import { Album, UserFileManagerAccess } from '../../access/UserFileManagerAccess'; +import common from '@ohos.app.ability.common'; const TAG: string = 'common_AlbumSetNewMenuOperation'; export class AlbumSetNewMenuOperation implements MenuOperation, MenuOperationCallback { private menuContext: MenuContext; - private defaultAlbumName: string; - private onOperationEnd: Function; + private defaultAlbumName: string = ''; + private onOperationEnd: Function = (): void => {}; constructor(menuContext: MenuContext) { this.menuContext = menuContext; @@ -43,8 +44,11 @@ export class AlbumSetNewMenuOperation implements MenuOperation, MenuOperationCal Log.error(TAG, 'menuContext is null, return'); return; } - let msg = { - 'Type': BigDataConstants.ALBUM_CREATE + interface Msg1 { + type: string + } + let msg: Msg1 = { + type: BigDataConstants.ALBUM_CREATE }; ReportToBigDataUtil.report(BigDataConstants.ALBUM_OPERATION_ID, msg); @@ -52,8 +56,10 @@ export class AlbumSetNewMenuOperation implements MenuOperation, MenuOperationCal Log.info(TAG, `The display name from resource ${JSON.stringify(a)}`); this.defaultAlbumName = ''; try { - let context = globalThis.photosAbilityContext; - if (context == null || context === 'undefined') { + let contextName: string = this.menuContext.sourceScene === SourceSceneType.BIG_PHOTO_COMPONENT ? + 'photoLibraryContext' : 'photosAbilityContext'; + let context: common.UIAbilityContext = AppStorage.get(contextName) as common.UIAbilityContext; + if (context == null || context === undefined) { Log.info(TAG, 'context is null!'); } else { this.defaultAlbumName = await context.resourceManager.getString(a.id); @@ -62,16 +68,18 @@ export class AlbumSetNewMenuOperation implements MenuOperation, MenuOperationCal = this.getNewAlbumDefaultName(this.defaultAlbumName); Log.info(TAG, `The display name of new album is ${newAlbumDisplayName}`); - this.confirmCallback = this.confirmCallback.bind(this); - this.cancelCallback = this.cancelCallback.bind(this); - this.menuContext.broadCast.emit(BroadCastConstants.SHOW_NEW_ALBUM_PHOTO_DIALOG, - [newAlbumDisplayName, this.confirmCallback, this.cancelCallback]); + [newAlbumDisplayName, async (displayName: string): Promise => await this.confirmCallbackBindImpl(displayName), + (): void => this.cancelCallbackBindImpl()]); } } catch (error) { - let msg = { - 'Type': BigDataConstants.ALBUM_CREATE_ERROR, - 'errMsg': JSON.stringify(error) + interface Msg2 { + type: string + errMsg: string + } + let msg: Msg2 = { + type: BigDataConstants.ALBUM_CREATE_ERROR, + errMsg: JSON.stringify(error) }; ReportToBigDataUtil.errEventReport(BigDataConstants.ALBUM_OPERATION_ERROR_ID, msg); Log.info(TAG, `The display name error ${error}`); @@ -89,6 +97,10 @@ export class AlbumSetNewMenuOperation implements MenuOperation, MenuOperationCal } private async confirmCallback(displayName: string): Promise { + return await this.confirmCallbackBindImpl(displayName); + } + + private async confirmCallbackBindImpl(displayName: string): Promise { Log.info(TAG, `AlbumSet new album confirm and the new name is: ${displayName}`); if (displayName) { // 过滤用户相册 @@ -109,7 +121,7 @@ export class AlbumSetNewMenuOperation implements MenuOperation, MenuOperationCal if (this.menuContext.jumpSourceToMain == JumpSourceToMain.ALBUM) { Log.info(TAG, 'go back to photo grid'); this.menuContext.broadCast.emit(BroadCastConstants.MEDIA_OPERATION, - [displayName, album.albumUri, this.onCompleted.bind(this)]); + [displayName, album.albumUri, (): void => this.onCompleted()]); } else { router.pushUrl({ url: 'pages/AlbumSelect', @@ -125,15 +137,25 @@ export class AlbumSetNewMenuOperation implements MenuOperation, MenuOperationCal } private cancelCallback(): void { + this.cancelCallbackBindImpl(); + } + + private cancelCallbackBindImpl(): void { Log.info(TAG, 'AlbumSet new album cancel'); } private checkAndAddNumber(albumInfo: AlbumInfo, prefixName: string, numbers: number[]): void { - let res = albumInfo.albumName.match(new RegExp('^' + prefixName + '[1-9][0-9]*$')); + if (!albumInfo || !albumInfo.albumName) { + Log.warn(TAG, 'album is empty'); + return; + } + let res: string[] = albumInfo.albumName.match(new RegExp('^' + prefixName + '[1-9][0-9]*$')) as string[]; Log.info(TAG, `check name res ${res}`) if (res) { - let number = res[0].match(new RegExp(`[1-9][0-9]*`)); - numbers.push(parseInt(number[0])); + let number: string[] = res[0].match(new RegExp('[1-9][0-9]*')) as string[]; + if (number != null && number[0] != null) { + numbers.push(Number.parseInt(number[0])); + } } } @@ -159,7 +181,7 @@ export class AlbumSetNewMenuOperation implements MenuOperation, MenuOperationCal } } - numbers.sort(function (a, b) { + numbers.sort((a: number, b: number) => { return a - b; }); diff --git a/common/src/main/ets/default/view/browserOperation/MediaOperationActionBar.ets b/common/src/main/ets/default/view/browserOperation/MediaOperationActionBar.ets index db5307ba..8d0f7ecb 100644 --- a/common/src/main/ets/default/view/browserOperation/MediaOperationActionBar.ets +++ b/common/src/main/ets/default/view/browserOperation/MediaOperationActionBar.ets @@ -28,7 +28,7 @@ const TAG: string = 'common_MediaOperationActionBar'; export struct MediaOperationActionBar { @Consume pageType: string; @Consume @Watch('createActionBar') loadingFinish: boolean; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @StorageLink('isHorizontal') @Watch('createActionBar') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @State actionBarProp: ActionBarProp = new ActionBarProp(); diff --git a/common/src/main/ets/default/view/browserOperation/MediaOperationBasePage.ets b/common/src/main/ets/default/view/browserOperation/MediaOperationBasePage.ets index 88c5efe0..9ff81b8c 100644 --- a/common/src/main/ets/default/view/browserOperation/MediaOperationBasePage.ets +++ b/common/src/main/ets/default/view/browserOperation/MediaOperationBasePage.ets @@ -38,6 +38,15 @@ import { UiUtil } from '../../utils/UiUtil'; const TAG: string = 'common_MediaOperationBasePage'; +interface Params { + pageType: string; + pageFrom: string; + albumInfo: AlbumInfo; + mediaType: number; + selectedItems: Array; + mediaUri?: string; +}; + @Component export struct MediaOperationBasePage { @StorageLink('leftBlank') leftBlank: number[] @@ -49,15 +58,36 @@ export struct MediaOperationBasePage { @State listCardWidth: number = 0; @State listCardPaddingBottom: number = 24; scroller: Scroller = new Scroller(); - albums: AlbumSetDataSource; + albums: AlbumSetDataSource | null = null; isActive: boolean = false; // Whether the page is in the foreground - sourceAlbumUri: string; - currentAlbum: AlbumInfo; - private pageFrom: string; + sourceAlbumUri: string = ''; + currentAlbum: AlbumInfo | null = null; + private pageFrom: string = ''; private selectedItems: Array = []; - private mediaType: number; + private mediaType: number = 0; private listCardBorderRadius: number = 16; - onWindowSizeChangeCallBack = () => this.updateListCardWidth(); + private onWindowSizeChangeCallBack: Function = () => this.updateListCardWidth(); + private funcOnMenuClicked: Function = (action: Action): void => this.onMenuClicked(action); + private onLoadingFinishedFunc: Function = (): void => this.onLoadingFinished(); + private mediaOperationFunc: Function = (displayName: string, albumUri: string, completedFunc?: Function): void => + this.mediaOperation(displayName, albumUri, completedFunc); + + private onLoadingFinished(): void { + this.loadingFinish = true; + } + + private mediaOperation(displayName: string, albumUri: string, completedFunc?: Function): void { + Log.info(TAG, `broadCast on mediaOperation, albumName: ${displayName}, albumUri: ${albumUri}`); + router.back({ + url: '', + params: { + pageType: this.pageType, + albumName: displayName, + albumUri: albumUri + } + }); + completedFunc && completedFunc(); + } aboutToAppear(): void { Log.info(TAG, `aboutToAppear`); @@ -66,7 +96,7 @@ export struct MediaOperationBasePage { }); this.albums = new AlbumSetDataSource(this.broadCast, { moreInfo: true }); this.albums.setMultiParameter(true); - let param: any = router.getParams(); + let param: Params = router.getParams() as Params; if (param) { Log.info(TAG, `router getParams ${JSON.stringify(param)}`); this.pageType = param.pageType; @@ -75,42 +105,22 @@ export struct MediaOperationBasePage { if (this.currentAlbum != null) { this.sourceAlbumUri = this.currentAlbum.uri; } - switch (this.pageFrom) { - case Constants.MEDIA_OPERATION_FROM_PHOTO_BROWSER: - this.mediaType = param.mediaType; - break; - case Constants.MEDIA_OPERATION_FROM_TIMELINE: - this.selectedItems = param.selectedItems; - break; - case Constants.MEDIA_OPERATION_FROM_PHOTO_GRID: - this.selectedItems = param.selectedItems; - break; - default: - break; + if (this.pageFrom === Constants.MEDIA_OPERATION_FROM_PHOTO_BROWSER) { + this.mediaType = param.mediaType; + } else if (this.pageFrom === Constants.MEDIA_OPERATION_FROM_TIMELINE) { + this.selectedItems = param.selectedItems; + }else if (this.pageFrom === Constants.MEDIA_OPERATION_FROM_PHOTO_GRID) { + this.selectedItems = param.selectedItems; } } - this.albums.setFilterAlbumsFunction(this.filterAlbumInList.bind(this)); + this.albums.setFilterAlbumsFunction((mediaSetList: AlbumInfo[]): Array => this.filterAlbumInList(mediaSetList)); this.onActive(); - this.onMenuClicked = this.onMenuClicked.bind(this); - this.broadCast.on(Constants.ON_LOADING_FINISHED, (totalCount) => { - this.loadingFinish = true; - }); + this.broadCast.on(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.broadCast.on(BroadCastConstants.MEDIA_OPERATION, (displayName: string, albumUri: string, completedFunc?: Function) => { - Log.info(TAG, `broadCast on mediaOperation, albumName: ${displayName}, albumUri: ${albumUri}`); - router.back({ - url: '', - params: { - pageType: this.pageType, - albumName: displayName, - albumUri: albumUri - } - }); - completedFunc && completedFunc(); - }); + this.broadCast.on(BroadCastConstants.MEDIA_OPERATION, this.mediaOperationFunc); this.albums.updateAlbumMediaCount(); this.updateListCardWidth(); Log.info(TAG, `album mediaSet ${this.albums.mediaSetList}`); @@ -118,37 +128,31 @@ export struct MediaOperationBasePage { aboutToDisappear(): void { Log.info(TAG, 'aboutToDisappear'); - this.broadCast.off(null, null); + if(this.broadCast) { + this.broadCast.off(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); + this.broadCast.off(BroadCastConstants.MEDIA_OPERATION, this.mediaOperationFunc); + } ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; } onMenuClicked(action: Action) { Log.info(TAG, `onMenuClicked, actionID: ${action.actionID}`); - - switch (action.actionID) { - case Action.CANCEL.actionID: - router.back({ - url: '', - params: {} - }); - break; - case Action.NEW.actionID: - this.createNewAlbum(); - break; - default: - break; + if (action.actionID === Action.CANCEL.actionID) { + router.back({ + url: '', + params: {} + }); + } else if (action.actionID === Action.NEW.actionID) { + this.createNewAlbum(); } } createNewAlbum() { Log.info(TAG, 'createNewAlbum'); let menuContext = new MenuContext(); - this.onOperationStart = this.onOperationStart.bind(this); - this.onOperationEnd = this.onOperationEnd.bind(this); menuContext - .withOperationStartCallback(this.onOperationStart) - .withOperationEndCallback(this.onOperationEnd) + .withOperationStartCallback((): void => this.onOperationStart()) + .withOperationEndCallback((): void => this.onOperationEnd()) .withAlbumSetDataSource(this.albums) .withAlbumInfo(this.currentAlbum) .withBroadCast(this.broadCast) @@ -212,28 +216,29 @@ export struct MediaOperationBasePage { return res; } - getBorderRadius(index: number): BorderRadiuses { - if (index === 0 && index + 1 === this.albums.totalCount()) { + getBorderRadius(index: number): BorderRadiuses | undefined { + if (this.albums != null && index === 0 && index + 1 === this.albums.totalCount()) { return { topLeft: this.listCardBorderRadius, topRight: this.listCardBorderRadius, bottomLeft: this.listCardBorderRadius, bottomRight: this.listCardBorderRadius }; - } else if (index + 1 === this.albums.totalCount()) { + } else if (this.albums != null && index + 1 === this.albums.totalCount()) { return { bottomLeft: this.listCardBorderRadius, bottomRight: this.listCardBorderRadius }; } else if (index === 0) { return { topLeft: this.listCardBorderRadius, topRight: this.listCardBorderRadius }; } + return undefined; } build() { Column() { - MediaOperationActionBar({ onMenuClicked: this.onMenuClicked }) + MediaOperationActionBar({ onMenuClicked: this.funcOnMenuClicked }) Stack() { List({ scroller: this.scroller }) { - LazyForEach(this.albums, (albumSetDataInfo: AlbumSetDataInfo, index?: number) => { + LazyForEach(this.albums as AlbumSetDataSource, (albumSetDataInfo: AlbumSetDataInfo, index?: number) => { ListItem() { AlbumListCard({ item: albumSetDataInfo.data, @@ -246,8 +251,10 @@ export struct MediaOperationBasePage { .padding({ left: $r('app.float.list_card_margin') }) - .borderRadius(this.getBorderRadius(index)) - }, (item) => item.data.id) + .borderRadius(this.getBorderRadius(index as number) as BorderRadiuses) + }, (item: AlbumSetDataInfo): string => { + return item.data.uri; + }); } .alignListItem(ListItemAlign.Center) .padding({ @@ -255,10 +262,10 @@ export struct MediaOperationBasePage { bottom: this.leftBlank[3] + this.listCardPaddingBottom }) .scrollBar(BarState.Auto) - .height(Constants.PERCENT_100) - .width(Constants.PERCENT_100) + .height(Constants.PERCENT_100 as string) + .width(Constants.PERCENT_100 as string) } - .height(Constants.PERCENT_100) + .height(Constants.PERCENT_100 as string) CustomDialogView({ broadCast: $broadCast }) } diff --git a/common/src/main/ets/default/view/browserOperation/MenuContext.ts b/common/src/main/ets/default/view/browserOperation/MenuContext.ts index 4ef37005..0610ace2 100644 --- a/common/src/main/ets/default/view/browserOperation/MenuContext.ts +++ b/common/src/main/ets/default/view/browserOperation/MenuContext.ts @@ -19,6 +19,14 @@ import { BroadCast } from '../../utils/BroadCast'; import { AlbumSetDataSource } from '../../model/browser/album/AlbumSetDataSource'; import { AlbumInfo } from '../../model/browser/album/AlbumInfo'; +export enum SourceSceneType { + INVALID, + SYSTEM_ALBUM, + USER_ALBUM, + PICKER, + BIG_PHOTO_COMPONENT +} + export class MenuContext { mediaItem: MediaItem; albumUri: string; @@ -34,6 +42,7 @@ export class MenuContext { albumInfo: AlbumInfo; fromSelectMode: boolean; targetAlbumName: string; + sourceScene: SourceSceneType = SourceSceneType.INVALID; withMediaItem(mediaItem: MediaItem): MenuContext { this.mediaItem = mediaItem; @@ -80,7 +89,7 @@ export class MenuContext { return this; } - withAlbumSetDataSource(albumSetDataSource: AlbumSetDataSource): MenuContext { + withAlbumSetDataSource(albumSetDataSource: AlbumSetDataSource | null): MenuContext { this.albumSetDataSource = albumSetDataSource; return this; } @@ -90,7 +99,7 @@ export class MenuContext { return this; } - withAlbumInfo(albumInfo) { + withAlbumInfo(albumInfo: AlbumInfo | null | undefined): MenuContext { this.albumInfo = albumInfo; return this; } diff --git a/common/src/main/ets/default/view/browserOperation/MoveMenuOperation.ts b/common/src/main/ets/default/view/browserOperation/MoveMenuOperation.ts index 7245388b..4780fe71 100644 --- a/common/src/main/ets/default/view/browserOperation/MoveMenuOperation.ts +++ b/common/src/main/ets/default/view/browserOperation/MoveMenuOperation.ts @@ -112,7 +112,7 @@ export class MoveMenuOperation extends ProcessMenuOperation { Log.debug(TAG, 'move file.mediaType:' + JSON.stringify(sourceAsset.fileType)); try { TraceControllerUtils.startTraceWithTaskId('move', this.currentBatch); - let sourceAlbumUri: string = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_SOURCE); + let sourceAlbumUri: string = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_SOURCE); let sourceAlbum: Album = await UserFileManagerAccess.getInstance().getAlbumByUri(sourceAlbumUri); await sourceAlbum.removePhotoAssets([sourceAsset]); // TODO 媒体库支持批量移除,传参后续整改 diff --git a/common/src/main/ets/default/view/browserOperation/MoveOrCopyBroadCastProp.ets b/common/src/main/ets/default/view/browserOperation/MoveOrCopyBroadCastProp.ets index 87941f2b..ea2d60ab 100644 --- a/common/src/main/ets/default/view/browserOperation/MoveOrCopyBroadCastProp.ets +++ b/common/src/main/ets/default/view/browserOperation/MoveOrCopyBroadCastProp.ets @@ -29,8 +29,13 @@ import { AlbumDefine } from '../../model/browser/AlbumDefine'; const TAG: string = 'common_MoveOrCopyBroadCastProp'; +interface ParamAlbumInfo { + item: string; + isFromFACard?: boolean; +} + export class MoveOrCopyBroadCastProp { - private broadCast: BroadCast; + private broadCast: BroadCast | null = null; private constructor() { } @@ -39,10 +44,10 @@ export class MoveOrCopyBroadCastProp { * Get MoveOrCopyBroadCastProp instance */ public static getInstance(): MoveOrCopyBroadCastProp { - if (AppStorage.Get(Constants.INSTANCE_MOVE_OR_COPY_BROADCAST_PROP) == null) { + if (AppStorage.get(Constants.INSTANCE_MOVE_OR_COPY_BROADCAST_PROP) == null) { AppStorage.SetOrCreate(Constants.INSTANCE_MOVE_OR_COPY_BROADCAST_PROP, new MoveOrCopyBroadCastProp()); } - return AppStorage.Get(Constants.INSTANCE_MOVE_OR_COPY_BROADCAST_PROP); + return AppStorage.get(Constants.INSTANCE_MOVE_OR_COPY_BROADCAST_PROP) as MoveOrCopyBroadCastProp; } /** @@ -50,28 +55,32 @@ export class MoveOrCopyBroadCastProp { * * @param broadCast broadCast */ - public sendMoveOrAddBroadCast(broadCast: BroadCast) { + public sendMoveOrAddBroadCast(broadCast: BroadCast): void { if (broadCast === null || broadCast === undefined) { Log.error(TAG, 'sendMoveOrAddBroadCast error: null or undefined broadcast'); return; } this.setBroadCast(broadCast); - // 如果是系统相册,则直接添加到,而不是弹窗选择添加还是移动 - let isSystemAlbumSource: boolean = false; - let sourceAlbumUri: string = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_SOURCE); - let systemAlbumUris: IterableIterator = UserFileManagerAccess.getInstance().getSystemAlbumUriMap().values(); - for (let uri of systemAlbumUris) { - if (sourceAlbumUri === uri) { - isSystemAlbumSource = true; - break; - } + /// 如果是系统相册,或者是新建相册从PickerPage界面添加图片的场景,直接添加到,而不是弹窗选择添加还是移动 + let sourceAlbumUri = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_SOURCE); + let isOnlyAddAlbumSource: boolean = sourceAlbumUri === Constants.APP_NEW_ALBUM_SOURCE_PICKER; + if (!isOnlyAddAlbumSource) { + UserFileManagerAccess.getInstance().getSystemAlbumUriMap().forEach( + (value: string) => { + if (sourceAlbumUri === value) { + isOnlyAddAlbumSource = true; + return; + } + }); } - if (isSystemAlbumSource) { + if (isOnlyAddAlbumSource) { this.addOperation(); } else { - this.broadCast.emit(BroadCastConstants.SHOW_COPY_OR_MOVE_DIALOG, - [this.moveOperation.bind(this), this.addOperation.bind(this)]); + if (this.broadCast != null) { + this.broadCast.emit(BroadCastConstants.SHOW_COPY_OR_MOVE_DIALOG, + [async (): Promise => await this.moveOperation(), async (): Promise => await this.addOperation()]); + } } } @@ -94,21 +103,19 @@ export class MoveOrCopyBroadCastProp { } private async addOperation() { - let selectManager: SelectManager = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_SELECTED); - let targetAlbumName: string = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_TARGET); - let targetAlbumUri: string = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_TARGET_URI); + let selectManager: SelectManager = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_SELECTED) as SelectManager;; + let targetAlbumName: string = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_TARGET) as string;; + let targetAlbumUri: string = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_TARGET_URI)as string; if (this.broadCast === null || this.broadCast === undefined) { Log.error(TAG, 'addOperation error: null or undefined broadcast'); return; } let menuContext = new MenuContext(); - this.onOperationStart = this.onOperationStart.bind(this); - this.onOperationEnd = this.onOperationEnd.bind(this); menuContext .withSelectManager(selectManager) - .withOperationStartCallback(this.onOperationStart) - .withOperationEndCallback(this.onOperationEnd) + .withOperationStartCallback((): void => this.onOperationStartBindImpl()) + .withOperationEndCallback(async (): Promise => await this.onOperationEndBindImpl()) .withBroadCast(this.broadCast) menuContext.withTargetAlbumName(targetAlbumName).withAlbumUri(targetAlbumUri); let menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddMenuOperation, menuContext); @@ -116,21 +123,19 @@ export class MoveOrCopyBroadCastProp { } private async moveOperation() { - let selectManager: SelectManager = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_SELECTED); - let targetAlbumName: string = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_TARGET); - let targetAlbumUri: string = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_TARGET_URI); + let selectManager: SelectManager = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_SELECTED) as SelectManager; + let targetAlbumName: string = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_TARGET) as string; + let targetAlbumUri: string = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_TARGET_URI) as string; if (this.broadCast === null || this.broadCast === undefined) { Log.error(TAG, 'moveOperation error: null or undefined broadcast'); return; } let menuContext = new MenuContext(); - this.onOperationStart = this.onOperationStart.bind(this); - this.onOperationEnd = this.onOperationEnd.bind(this); menuContext .withSelectManager(selectManager) - .withOperationStartCallback(this.onOperationStart) - .withOperationEndCallback(this.onOperationEnd) + .withOperationStartCallback((): void => this.onOperationStartBindImpl()) + .withOperationEndCallback(async (): Promise => await this.onOperationEndBindImpl()) .withBroadCast(this.broadCast) menuContext.withTargetAlbumName(targetAlbumName).withAlbumUri(targetAlbumUri); let menuOperation = MenuOperationFactory.getInstance().createMenuOperation(MoveMenuOperation, menuContext); @@ -138,14 +143,14 @@ export class MoveOrCopyBroadCastProp { } private onOperationStart(): void { - AppStorage.SetOrCreate(Constants.IS_DATA_FREEZE, true); + this.onOperationStartBindImpl(); } - private async onOperationEnd(): Promise { + private async onOperationEndBindImpl(): Promise { AppStorage.SetOrCreate(Constants.IS_DATA_FREEZE, false); - let isNewAlbum: boolean = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM); - let selectManager: SelectManager = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_SELECTED); - let targetAlbumName: string = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_TARGET); + let isNewAlbum: boolean = AppStorage.get(Constants.APP_KEY_NEW_ALBUM) as boolean; + let selectManager: SelectManager = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_SELECTED) as SelectManager; + let targetAlbumName: string = AppStorage.get(Constants.APP_KEY_NEW_ALBUM_TARGET) as string; let album = await UserFileManagerAccess.getInstance().getAlbumByName(targetAlbumName); let albumInfo: AlbumInfo = new AlbumInfo(album); @@ -169,11 +174,21 @@ export class MoveOrCopyBroadCastProp { } }); } else { - AppStorage.SetOrCreate(Constants.KEY_OF_PHOTO_GRID_VIEW_ALBUM_ITEM, { item: JSON.stringify(albumInfo) }); + AppStorage.setOrCreate(Constants.KEY_OF_PHOTO_GRID_VIEW_ALBUM_ITEM, { + item: JSON.stringify(albumInfo) + }); AppStorage.SetOrCreate(Constants.KEY_OF_ALBUM_URI, albumInfo.uri); router.back({ url: 'pages/index', }); } } + + private onOperationStartBindImpl(): void { + AppStorage.SetOrCreate(Constants.IS_DATA_FREEZE, true); + } + + private async onOperationEnd(): Promise { + await this.onOperationEndBindImpl(); + } } \ No newline at end of file diff --git a/common/src/main/ets/default/view/browserOperation/ShareMenuOperation.ts b/common/src/main/ets/default/view/browserOperation/ShareMenuOperation.ts index 3d9aa8e0..1362bf0f 100644 --- a/common/src/main/ets/default/view/browserOperation/ShareMenuOperation.ts +++ b/common/src/main/ets/default/view/browserOperation/ShareMenuOperation.ts @@ -23,6 +23,7 @@ import { MediaItem } from '../../model/browser/photo/MediaItem'; import { UserFileManagerAccess } from '../../access/UserFileManagerAccess'; import { UiUtil } from '../../utils/UiUtil'; import { BigDataConstants, ReportToBigDataUtil } from '../../utils/ReportToBigDataUtil'; +import common from '@ohos.app.ability.common'; const TAG: string = 'common_ShareMenuOperation'; @@ -114,13 +115,14 @@ export class ShareMenuOperation implements MenuOperation, AsyncCallback('photosAbilityContext'); + context.startAbility(want); } private reportToBigData(shareType: string, imageCount: number, videoCount: number): void { let count: number = 1; - if (AppStorage.Get('click_share_count') != null) { - let oldCount: number = AppStorage.Get('click_share_count'); + if (AppStorage.get('click_share_count') != null) { + let oldCount: number = AppStorage.get('click_share_count'); count = oldCount + 1; } AppStorage.SetOrCreate('click_share_count', count); diff --git a/common/src/main/ets/default/view/dialog/AddNotesDialog.ets b/common/src/main/ets/default/view/dialog/AddNotesDialog.ets index b9dd46e2..a7995428 100644 --- a/common/src/main/ets/default/view/dialog/AddNotesDialog.ets +++ b/common/src/main/ets/default/view/dialog/AddNotesDialog.ets @@ -28,7 +28,7 @@ export struct AddNotesDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; + controller?: CustomDialogController; @Consume dialogCallback: DialogCallback; @State isNull: boolean = false; private inputNote: string = ''; @@ -49,7 +49,7 @@ export struct AddNotesDialog { .width($r('app.float.icon_size')) .onClick(() => { this.dialogCallback && this.dialogCallback.cancelCallback(); - this.controller.close() + this.controller?.close(); }) }.margin({ right: $r('app.float.dialog_icon_margin_horizontal') }) @@ -80,11 +80,11 @@ export struct AddNotesDialog { let passCheck = StringUtil.checkNameInvalid(this.inputNote); if (passCheck) { UiUtil.showToast($r('app.string.specific_characters_not_supported')); - this.controller.close() + this.controller?.close(); return } this.dialogCallback && this.dialogCallback.confirmCallback(this.inputNote); - this.controller.close() + this.controller?.close(); }) } }.margin({ top: $r('sys.float.ohos_id_text_paragraph_margin_s'), diff --git a/common/src/main/ets/default/view/dialog/CancelOperationDialog.ets b/common/src/main/ets/default/view/dialog/CancelOperationDialog.ets index d5ada580..fcda5157 100644 --- a/common/src/main/ets/default/view/dialog/CancelOperationDialog.ets +++ b/common/src/main/ets/default/view/dialog/CancelOperationDialog.ets @@ -22,8 +22,8 @@ const TAG: string = 'common_CancelOperationDialog'; @Observed export class CancelParam { - continueFunc: Function - cancelFunc: Function + continueFunc: Function = (): void => {}; + cancelFunc: Function = (): void => {}; } @CustomDialog @@ -32,12 +32,12 @@ export struct CancelOperationDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; + controller?: CustomDialogController; @Consume cancelMessage: Resource; @Consume broadCast: BroadCast; @Consume deleteProgress: number; @Consume cancelParam: CancelParam; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; build() { Column() { @@ -66,7 +66,7 @@ export struct CancelOperationDialog { .onClick(() => { Log.info(TAG, 'click continue') this.cancelParam.continueFunc(); - this.controller.close() + this.controller?.close(); }) .margin({ right: $r('app.float.dialog_double_buttons_margin_right') @@ -88,7 +88,7 @@ export struct CancelOperationDialog { .onClick(() => { Log.info(TAG, 'click cancel') this.cancelParam.cancelFunc(); - this.controller.close() + this.controller?.close(); }) .margin({ left: $r('app.float.dialog_double_buttons_margin_left') diff --git a/common/src/main/ets/default/view/dialog/CopyOrMoveDialog.ets b/common/src/main/ets/default/view/dialog/CopyOrMoveDialog.ets index 5ff5cfc4..e7f9d13f 100644 --- a/common/src/main/ets/default/view/dialog/CopyOrMoveDialog.ets +++ b/common/src/main/ets/default/view/dialog/CopyOrMoveDialog.ets @@ -21,8 +21,8 @@ const TAG: string = 'common_CopyOrMoveDialog'; @Observed export class OperateParam { - moveFunc: Function - copyFunc: Function + moveFunc: Function = (): void => {}; + copyFunc: Function = (): void => {}; } @CustomDialog @@ -33,10 +33,10 @@ export struct CopyOrMoveDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; - dataTime: string; + controller?: CustomDialogController; + dataTime: string = ''; @Consume operateParam: OperateParam; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; aboutToAppear() { @@ -65,7 +65,7 @@ export struct CopyOrMoveDialog { .width('100%') .key('Copy') .onClick(() => { - this.controller.close() + this.controller?.close(); this.operateParam.copyFunc(); }) @@ -87,7 +87,7 @@ export struct CopyOrMoveDialog { .height($r('app.float.dialog_list_card_height')) .width('100%') .onClick(() => { - this.controller.close() + this.controller?.close(); this.operateParam.moveFunc(); }) @@ -105,7 +105,7 @@ export struct CopyOrMoveDialog { .height($r('app.float.details_dialog_button_height')) .key('Cancel') .onClick(() => { - this.controller.close() + this.controller?.close(); }) .margin({ left: $r('app.float.dialog_single_button_indent_margin'), diff --git a/common/src/main/ets/default/view/dialog/CustomDialogView.ets b/common/src/main/ets/default/view/dialog/CustomDialogView.ets index 24d9c95f..59f0af46 100644 --- a/common/src/main/ets/default/view/dialog/CustomDialogView.ets +++ b/common/src/main/ets/default/view/dialog/CustomDialogView.ets @@ -37,6 +37,7 @@ import { NewAlbumDialog } from './NewAlbumDialog'; import { CopyOrMoveDialog, OperateParam } from './CopyOrMoveDialog'; import { ScreenManager } from '../../model/common/ScreenManager'; import { SaveImageDialog } from './SaveImageDialog'; +import { tryFunc } from '../../utils/ErrUtil'; const TAG: string = 'common_CustomDialogView'; @@ -47,15 +48,15 @@ export struct CustomDialogView { @Provide progressMessage: Resource = $r('app.string.common_place_holder', String('')); @Provide deleteProgress: number = 0; @Provide removeProgress: number = 0; - @Provide dialogCallback: DialogCallback = { confirmCallback: null, cancelCallback: null }; - @Provide saveDialogCallback: SaveDialogCallback = { saveAsNewCallback: null, replaceOriginalCallback: null }; - @Provide editExitDialogCallback: EditExitDialogCallback = { discardCallback: null }; + @Provide dialogCallback: DialogCallback = { confirmCallback: (): void => {}, cancelCallback: () => {} }; + @Provide saveDialogCallback: SaveDialogCallback = { saveAsNewCallback: (): void => {}, replaceOriginalCallback: () => {} }; + @Provide editExitDialogCallback: EditExitDialogCallback = { discardCallback: (): void => {} }; @Link broadCast: BroadCast; - @Provide progressParam: ProgressParam = { cancelFunc: null, operationType: '' }; - @Provide deleteProgressParam: DeleteProgressParam = { currentCount: 0, totalCount: 0, message: null }; - @Provide removeProgressParam: RemoveProgressParam = { currentCount: 0, totalCount: 0, message: null }; - @Provide cancelParam: CancelParam = { continueFunc: null, cancelFunc: null }; - @Provide operateParam: OperateParam = { moveFunc: null, copyFunc: null }; + @Provide progressParam: ProgressParam = { cancelFunc: (): void => {}, operationType: '' }; + @Provide deleteProgressParam: DeleteProgressParam = { currentCount: 0, totalCount: 0, message: undefined }; + @Provide removeProgressParam: RemoveProgressParam = { currentCount: 0, totalCount: 0, message: undefined }; + @Provide cancelParam: CancelParam = { continueFunc: (): void => {}, cancelFunc: () => {} }; + @Provide operateParam: OperateParam = { moveFunc: (): void => {}, copyFunc: () => {} }; @Provide cancelMessage: Resource = $r('app.string.common_place_holder', String('')); @Provide renameFileName: string = ''; @Provide isDistributedAlbum: boolean = false; @@ -87,28 +88,90 @@ export struct CustomDialogView { count: 500, size: 256, }; - @StorageLink('isHorizontal') @Watch('buildDialogs') isHorizontal: boolean = ScreenManager.getInstance() + @StorageLink('isHorizontal') @Watch('refreshDialogs') isHorizontal: boolean = ScreenManager.getInstance() .isHorizontal(); - @StorageLink('isSidebar') @Watch('buildDialogs') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); - dialogController: CustomDialogController; - multiSelectDialog: CustomDialogController; - deleteDialogController: CustomDialogController; - thirdDeleteDialogController: CustomDialogController; - removeDialogController: CustomDialogController; - deleteProgressDialogController: CustomDialogController; - removeProgressDialogController: CustomDialogController; - progressDialogController: CustomDialogController; - cancelDialogController: CustomDialogController; - renameFileDialogController: CustomDialogController; - saveDialogController: CustomDialogController; - editExitDialogController: CustomDialogController; - addNotesDialogController: CustomDialogController; - newAlbumDialogController: CustomDialogController; - copyOrMoveDialogController: CustomDialogController; - downloadCancelOperationDialog: CustomDialogController; - saveImageDialogController: CustomDialogController; + @StorageLink('isSidebar') @Watch('refreshDialogs') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); + dialogController?: CustomDialogController | null; + multiSelectDialog?: CustomDialogController | null; + deleteDialogController?: CustomDialogController | null; + thirdDeleteDialogController?: CustomDialogController | null; + removeDialogController?: CustomDialogController | null; + deleteProgressDialogController?: CustomDialogController | null; + removeProgressDialogController?: CustomDialogController | null; + progressDialogController?: CustomDialogController | null; + cancelDialogController?: CustomDialogController | null; + renameFileDialogController?: CustomDialogController | null; + saveDialogController?: CustomDialogController | null; + editExitDialogController?: CustomDialogController | null; + addNotesDialogController?: CustomDialogController | null; + newAlbumDialogController?: CustomDialogController | null; + copyOrMoveDialogController?: CustomDialogController | null; + downloadCancelOperationDialog?: CustomDialogController | null; + saveImageDialogController?: CustomDialogController | null; - buildDialogs(): void { + private showDetailDialogFunc: Function = + (item: MediaItem, isDistributed: boolean): void => this.showDetailDialog(item,isDistributed); + + private showMultiSelectDialogFunc: Function = + (count: number, size: number): void => this.showMultiSelectDialog(count, size); + + private showDeleteDialogFunc: Function = + (deleteMessage: Resource, confirmCallback: Function, cancelCallback: Function, isAlbumDelete: boolean): void => + this.showDeleteDialog(deleteMessage, confirmCallback, cancelCallback); + + private showThirdDeleteDialogFunc: Function = + (deleteMessage: Resource, confirmCallback: Function, cancelCallback?: Function): void => + this.showThirdDeleteDialog(deleteMessage, confirmCallback, cancelCallback); + + private showRemoveDialogFunc: Function = + (removeMessage: Resource, confirmCallback: Function, cancelCallback?: Function): void => + this.showRemoveDialog(removeMessage, confirmCallback, cancelCallback); + + private showRenamePhotoDialogFunc:Function = (fileName: string, confirmCallback: Function, cancelCallback?: Function): void => + this.showRenamePhotoDialog(fileName, confirmCallback, cancelCallback); + + private showAddNotePhotoDialogFunc: Function = (confirmCallback: Function, cancelCallback?: Function): void => + this.showAddNotePhotoDialog(confirmCallback, cancelCallback); + + private showProgressDialogFunc: Function = (message: Resource, operationType: string, cancelFunc?: Function): void => + this.showProgressDialog(message, operationType,cancelFunc); + + private updateProgressFunc: Function = (progress: number, currentCount: number): void => + this.updateProgress(progress, currentCount); + + private cancelOperateFunc: Function = (cancelMessage: Resource, continueFunc: Function, cancelFunc: Function): void => + this.cancelOperate(cancelMessage, continueFunc, cancelFunc); + + private downloadCancelOperateFunc: Function = + (cancelMessage: Resource, continueFunc: Function, cancelFunc: Function): void => + this.downloadCancelOperate(cancelMessage, continueFunc, cancelFunc); + + private showSavePhotoDialogFunc: Function = + (saveAsNewCallback: Function, replaceOriginalCallback: Function): void => + this.showSavePhotoDialog(saveAsNewCallback, replaceOriginalCallback); + + private showEditExitPhotoDialogFunc: Function = (discardCallback: Function): void => + this.showEditExitPhotoDialog(discardCallback); + + private showEditSaveProgressDialogFunc: Function = (): void => this.showEditSaveProgressDialog(); + + private showNewAlbumDialogFunc: Function = + (fileName: string, confirmCallback: Function, cancelCallback?: Function): void => this.showNewAlbumDialog(fileName, confirmCallback, cancelCallback); + + private showCopyOrMoveDialogFunc: Function = (moveFunc: Function, copyFunc: Function): void => + this.showCopyOrMoveDialog(moveFunc, copyFunc); + + private deleteProgressDialogFunc: Function = (message: Resource, totalCount: number): void => + this.deleteProgressDialog(message, totalCount) + + private removeProgressDialogFunc: Function = (message: Resource, totalCount: number): void => + this.removeProgressDialog(message, totalCount); + + refreshDialogs(): void { + this.buildDialogs(true); + } + + buildDialogs(refreshFlag: boolean): void { this.dialogController = new CustomDialogController({ builder: DetailsDialog(), autoCancel: false, @@ -283,224 +346,226 @@ export struct CustomDialogView { aboutToDisappear(): void { Log.info(TAG, 'aboutToDisappear'); - this.broadCast.off(null, null); - delete this.dialogController; - this.dialogController = undefined; - delete this.multiSelectDialog; - this.multiSelectDialog = undefined; - delete this.deleteDialogController; - this.deleteDialogController = undefined; - delete this.thirdDeleteDialogController; - this.thirdDeleteDialogController = undefined; - delete this.removeDialogController; - this.removeDialogController = undefined; - delete this.deleteProgressDialogController; - this.deleteProgressDialogController = undefined; - delete this.removeProgressDialogController; - this.removeProgressDialogController = undefined; - delete this.progressDialogController; - this.progressDialogController = undefined; - delete this.cancelDialogController; - this.cancelDialogController = undefined; - delete this.renameFileDialogController; - this.renameFileDialogController = undefined; - delete this.saveDialogController; - this.saveDialogController = undefined; - delete this.editExitDialogController; - this.editExitDialogController = undefined; - delete this.addNotesDialogController; - this.addNotesDialogController = undefined; - delete this.newAlbumDialogController; - this.newAlbumDialogController = undefined; - delete this.copyOrMoveDialogController; - this.copyOrMoveDialogController = undefined; - delete this.downloadCancelOperationDialog; - this.downloadCancelOperationDialog = undefined; - delete this.saveImageDialogController; - this.saveImageDialogController = undefined; + this.buildDialogs(false); + this.dialogController = null; + this.multiSelectDialog = null; + this.deleteDialogController = null; + this.thirdDeleteDialogController = null; + this.removeDialogController = null; + this.deleteProgressDialogController = null; + this.removeProgressDialogController = null; + this.progressDialogController = null; + this.cancelDialogController = null; + this.renameFileDialogController = null; + this.saveDialogController = null; + this.editExitDialogController = null; + this.addNotesDialogController = null; + this.newAlbumDialogController = null; + this.copyOrMoveDialogController = null; + this.downloadCancelOperationDialog = null; + this.saveImageDialogController = null; + + this.broadCast.off(BroadCastConstants.SHOW_DETAIL_DIALOG, this.showDetailDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_MULTI_SELECT_DIALOG, this.showMultiSelectDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_DELETE_DIALOG, this.showDeleteDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_THIRD_DELETE_DIALOG, this.showThirdDeleteDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_REMOVE_DIALOG, this.showRemoveDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_RENAME_PHOTO_DIALOG, this.showRenamePhotoDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_ADD_NOTES_PHOTO_DIALOG, this.showAddNotePhotoDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_PROGRESS_DIALOG, this.showProgressDialogFunc); + this.broadCast.off(BroadCastConstants.UPDATE_PROGRESS, this.updateProgressFunc); + this.broadCast.off(BroadCastConstants.CANCEL_OPERATE, this.cancelOperateFunc); + this.broadCast.off(BroadCastConstants.DOWNLOAD_CANCEL_OPERATE, this.downloadCancelOperateFunc); + this.broadCast.off(BroadCastConstants.SHOW_SAVE_PHOTO_DIALOG, this.showSavePhotoDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_NEW_ALBUM_PHOTO_DIALOG, this.showNewAlbumDialogFunc); + this.broadCast.off(BroadCastConstants.SHOW_COPY_OR_MOVE_DIALOG, this.showCopyOrMoveDialogFunc); + this.broadCast.off(BroadCastConstants.DELETE_PROGRESS_DIALOG, this.deleteProgressDialogFunc); + this.broadCast.off(BroadCastConstants.REMOVE_PROGRESS_DIALOG, this.removeProgressDialogFunc); + } + + private showDetailDialog(item: MediaItem, isDistributed: boolean): void { + Log.info(TAG, item.uri, ' SHOW_DETAIL_DIALOG '); + let title: string = item.getTitle ? tryFunc(((): string => item.getTitle())) : undefined; + let dateTaken: number = item.getDataTaken ? tryFunc(((): number => item.getDataTaken())) : undefined; + let dateModified: number = item.getDateModified ? tryFunc(((): number => item.getDateModified())) : undefined; + this.mediaDetails = { + mediaType: item.mediaType, + height: item.height, + width: item.width, + size: item.size, + duration: item.duration, + title, + dateTaken, + uri: item.uri, + displayName: item.displayName, + dateModified + }; + this.isDistributedAlbum = isDistributed; + (this.dialogController as CustomDialogController).open(); + } + + private showMultiSelectDialog(count: number, size: number): void { + Log.info(TAG, 'SHOW_MULTI_SELECT_DIALOG '); + this.multiSelectDetails = { + size: size, + count: count + }; + (this.multiSelectDialog as CustomDialogController).open(); + } + + private showDeleteDialog(deleteMessage: Resource, confirmCallback: Function, cancelCallback: Function): void { + Log.info(TAG, 'SHOW_DELETE_DIALOG '); + this.dialogMessage = deleteMessage; + this.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback as Function }; + (this.deleteDialogController as CustomDialogController).open(); + } + + private showThirdDeleteDialog(deleteMessage: Resource, confirmCallback: Function, cancelCallback?: Function): void { + Log.info(TAG, 'SHOW_THIRD_DELETE_DIALOG '); + this.dialogMessage = deleteMessage; + this.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback as Function }; + (this.thirdDeleteDialogController as CustomDialogController).open(); + } + + private showRemoveDialog(removeMessage: Resource, confirmCallback: Function, cancelCallback?: Function): void { + Log.info(TAG, 'SHOW_REMOVE_DIALOG '); + this.dialogMessage = removeMessage; + this.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback as Function }; + (this.removeDialogController as CustomDialogController).open(); + } + + private showRenamePhotoDialog(fileName: string, confirmCallback: Function, cancelCallback?: Function): void { + Log.info(TAG, 'SHOW_RENAME_PHOTO_DIALOG '); + this.renameFileName = fileName; + this.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback as Function }; + (this.renameFileDialogController as CustomDialogController).open(); + } + + private showAddNotePhotoDialog(confirmCallback: Function, cancelCallback?: Function): void { + Log.info(TAG, 'SHOW_ADD_NOTES_PHOTO_DIALOG '); + this.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback as Function }; + (this.addNotesDialogController as CustomDialogController).open(); + } + + private showProgressDialog(message: Resource, operationType: string, cancelFunc?: Function): void { + Log.info(TAG, 'SHOW_PROGRESS_DIALOG'); + if (message != null) { + this.progressMessage = message; + } + if (operationType) { + this.progressParam.operationType = operationType; + } + + if (cancelFunc) { + this.progressParam.cancelFunc = cancelFunc; + } + this.deleteProgress = 0; + this.removeProgress = 0; + (this.progressDialogController as CustomDialogController).open(); + } + + private updateProgress(progress: number, currentCount: number): void { + Log.info(TAG, `UPDATE_PROGRESS ${progress}`); + this.deleteProgress = progress; + this.removeProgress = progress; + this.deleteProgressParam.currentCount = currentCount; + this.removeProgressParam.currentCount = currentCount; + if (progress == 100) { + Log.info(TAG, 'Update progress 100%'); + (this.progressDialogController as CustomDialogController).close(); + (this.deleteProgressDialogController as CustomDialogController).close(); + this.deleteProgressParam.currentCount = 0; + (this.removeProgressDialogController as CustomDialogController).close(); + this.removeProgressParam.currentCount = 0; + } + } + + private cancelOperate(cancelMessage: Resource, continueFunc: Function, cancelFunc: Function): void { + this.cancelMessage = cancelMessage; + this.cancelParam.continueFunc = continueFunc; + this.cancelParam.cancelFunc = cancelFunc; + Log.info(TAG, 'CANCEL_OPERATE'); + (this.cancelDialogController as CustomDialogController).open(); + } + + private downloadCancelOperate(cancelMessage: Resource, continueFunc: Function, cancelFunc: Function): void { + this.cancelMessage = cancelMessage; + this.cancelParam.continueFunc = continueFunc; + this.cancelParam.cancelFunc = cancelFunc; + Log.info(TAG, 'DOWNLOAD_CANCEL_OPERATE'); + (this.downloadCancelOperationDialog as CustomDialogController).open(); + } + + private showSavePhotoDialog(saveAsNewCallback: Function, replaceOriginalCallback: Function): void { + Log.info(TAG, 'SHOW_SAVE_PHOTO_DIALOG'); + this.saveDialogCallback = { + saveAsNewCallback: saveAsNewCallback, + replaceOriginalCallback: replaceOriginalCallback }; + (this.saveDialogController as CustomDialogController).open(); + } + + private showEditExitPhotoDialog(discardCallback: Function): void { + Log.info(TAG, 'SHOW_EDIT_EXIT_PHOTO_DIALOG'); + this.editExitDialogCallback = { discardCallback: discardCallback }; + (this.editExitDialogController as CustomDialogController).open(); + } + + private showEditSaveProgressDialog(): void { + Log.info(TAG, 'SHOW_EDIT_SAVE_PROGRESS_DIALOG'); + (this.saveImageDialogController as CustomDialogController).open(); + } + + private showNewAlbumDialog(fileName: string, confirmCallback: Function, cancelCallback?: Function): void { + Log.info(TAG, 'SHOW_NEW_ALBUM_PHOTO_DIALOG'); + this.renameFileName = fileName; + this.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback as Function }; + (this.newAlbumDialogController as CustomDialogController).open(); + } + + private showCopyOrMoveDialog(moveFunc: Function, copyFunc: Function): void { + Log.info(TAG, 'SHOW_COPY_OR_MOVE_DIALOG'); + this.operateParam.moveFunc = moveFunc; + this.operateParam.copyFunc = copyFunc; + (this.copyOrMoveDialogController as CustomDialogController).open(); + } + + private deleteProgressDialog(message: Resource, totalCount: number): void { + Log.info(TAG, 'DELETE_PROGRESS_DIALOG'); + this.deleteProgressParam.currentCount = 0; + this.deleteProgressParam.totalCount = totalCount; + this.deleteProgressParam.message = message; + (this.deleteProgressDialogController as CustomDialogController).open(); + } + + private removeProgressDialog(message: Resource, totalCount: number): void { + Log.info(TAG, 'REMOVE_PROGRESS_DIALOG'); + this.removeProgressParam.currentCount = 0; + this.removeProgressParam.totalCount = totalCount; + this.removeProgressParam.message = message; + (this.removeProgressDialogController as CustomDialogController).open(); } aboutToAppear(): void { Log.info(TAG, 'aboutToAppear'); - let self = this; - this.buildDialogs(); - this.broadCast.on(BroadCastConstants.SHOW_DETAIL_DIALOG, - function (item: MediaItem, isDistributed: boolean) { - Log.info(TAG, 'SHOW_DETAIL_DIALOG '); - self.mediaDetails = { - mediaType: item.mediaType, - height: item.height, - width: item.width, - size: item.size, - duration: item.duration, - title: item.getTitle(), - dateTaken: item.getDataTaken(), - uri: item.uri, - displayName: item.displayName, - dateModified: item.getDateModified() - }; - self.isDistributedAlbum = isDistributed; - self.dialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_MULTI_SELECT_DIALOG, - function (count: number, size: number) { - Log.info(TAG, 'SHOW_MULTI_SELECT_DIALOG '); - self.multiSelectDetails = { - size: size, - count: count - }; - - self.multiSelectDialog.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_DELETE_DIALOG, - function (deleteMessage: Resource, confirmCallback: Function, cancelCallback?: Function) { - Log.info(TAG, 'SHOW_DELETE_DIALOG '); - self.dialogMessage = deleteMessage; - self.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback }; - self.deleteDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_THIRD_DELETE_DIALOG, - function (deleteMessage: Resource, confirmCallback: Function, cancelCallback?: Function) { - Log.info(TAG, 'SHOW_THIRD_DELETE_DIALOG '); - self.dialogMessage = deleteMessage; - self.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback }; - self.thirdDeleteDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_REMOVE_DIALOG, - function (removeMessage: Resource, confirmCallback: Function, cancelCallback?: Function) { - Log.info(TAG, 'SHOW_REMOVE_DIALOG '); - self.dialogMessage = removeMessage; - self.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback }; - self.removeDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_RENAME_PHOTO_DIALOG, - function (fileName: string, confirmCallback: Function, cancelCallback?: Function) { - Log.info(TAG, 'SHOW_RENAME_PHOTO_DIALOG '); - self.renameFileName = fileName; - self.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback }; - self.renameFileDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_ADD_NOTES_PHOTO_DIALOG, - function (confirmCallback: Function, cancelCallback?: Function) { - Log.info(TAG, 'SHOW_ADD_NOTES_PHOTO_DIALOG '); - self.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback }; - self.addNotesDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_PROGRESS_DIALOG, - function (message: Resource, operationType: string, cancelFunc?: Function) { - Log.info(TAG, 'SHOW_PROGRESS_DIALOG'); - if (message != null) { - self.progressMessage = message; - } - - if (operationType) { - self.progressParam.operationType = operationType; - } - - if (cancelFunc) { - self.progressParam.cancelFunc = cancelFunc; - } - self.deleteProgress = 0; - self.removeProgress = 0; - self.progressDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.UPDATE_PROGRESS, - function (progress: number, currentCount: number) { - Log.info(TAG, `UPDATE_PROGRESS ${progress}`); - self.deleteProgress = progress; - self.removeProgress = progress; - self.deleteProgressParam.currentCount = currentCount; - self.removeProgressParam.currentCount = currentCount; - if (progress == 100) { - Log.info(TAG, 'Update progress 100%'); - self.progressDialogController.close(); - self.deleteProgressDialogController.close(); - self.deleteProgressParam.currentCount = 0; - self.removeProgressDialogController.close(); - self.removeProgressParam.currentCount = 0; - } - }); - - this.broadCast.on(BroadCastConstants.CANCEL_OPERATE, - function (cancelMessage: Resource, continueFunc: Function, cancelFunc: Function) { - self.cancelMessage = cancelMessage; - self.cancelParam.continueFunc = continueFunc; - self.cancelParam.cancelFunc = cancelFunc; - Log.info(TAG, 'CANCEL_OPERATE'); - self.cancelDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.DOWNLOAD_CANCEL_OPERATE, - function (cancelMessage: Resource, continueFunc: Function, cancelFunc: Function) { - self.cancelMessage = cancelMessage; - self.cancelParam.continueFunc = continueFunc; - self.cancelParam.cancelFunc = cancelFunc; - Log.info(TAG, 'DOWNLOAD_CANCEL_OPERATE'); - self.downloadCancelOperationDialog.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_SAVE_PHOTO_DIALOG, - function (saveAsNewCallback: Function, replaceOriginalCallback: Function) { - Log.info(TAG, 'SHOW_SAVE_PHOTO_DIALOG'); - self.saveDialogCallback - = { saveAsNewCallback: saveAsNewCallback, replaceOriginalCallback: replaceOriginalCallback }; - self.saveDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_EDIT_EXIT_PHOTO_DIALOG, - function (discardCallback: Function) { - Log.info(TAG, 'SHOW_EDIT_EXIT_PHOTO_DIALOG'); - self.editExitDialogCallback = { discardCallback: discardCallback }; - self.editExitDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_EDIT_SAVE_PROGRESS_DIALOG, - function () { - Log.info(TAG, 'SHOW_EDIT_SAVE_PROGRESS_DIALOG'); - self.saveImageDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_NEW_ALBUM_PHOTO_DIALOG, - function (fileName: string, confirmCallback: Function, cancelCallback?: Function) { - Log.info(TAG, 'SHOW_NEW_ALBUM_PHOTO_DIALOG'); - self.renameFileName = fileName; - self.dialogCallback = { confirmCallback: confirmCallback, cancelCallback: cancelCallback }; - self.newAlbumDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.SHOW_COPY_OR_MOVE_DIALOG, - function (moveFunc: Function, copyFunc: Function) { - Log.info(TAG, 'SHOW_COPY_OR_MOVE_DIALOG'); - self.operateParam.moveFunc = moveFunc; - self.operateParam.copyFunc = copyFunc; - self.copyOrMoveDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.DELETE_PROGRESS_DIALOG, - function (message: Resource, totalCount: number) { - Log.info(TAG, 'DELETE_PROGRESS_DIALOG'); - self.deleteProgressParam.currentCount = 0; - self.deleteProgressParam.totalCount = totalCount; - self.deleteProgressParam.message = message; - self.deleteProgressDialogController.open(); - }); - - this.broadCast.on(BroadCastConstants.REMOVE_PROGRESS_DIALOG, - function (message: Resource, totalCount: number) { - Log.info(TAG, 'DELETE_PROGRESS_DIALOG'); - self.removeProgressParam.currentCount = 0; - self.removeProgressParam.totalCount = totalCount; - self.removeProgressParam.message = message; - self.removeProgressDialogController.open(); - }); + this.buildDialogs(false); + this.broadCast.on(BroadCastConstants.SHOW_DETAIL_DIALOG, this.showDetailDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_MULTI_SELECT_DIALOG,this.showMultiSelectDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_DELETE_DIALOG, this.showDeleteDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_THIRD_DELETE_DIALOG, this.showThirdDeleteDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_REMOVE_DIALOG, this.showRemoveDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_RENAME_PHOTO_DIALOG, this.showRenamePhotoDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_ADD_NOTES_PHOTO_DIALOG, this.showAddNotePhotoDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_PROGRESS_DIALOG, this.showProgressDialogFunc); + this.broadCast.on(BroadCastConstants.UPDATE_PROGRESS, this.updateProgressFunc); + this.broadCast.on(BroadCastConstants.CANCEL_OPERATE, this.cancelOperateFunc); + this.broadCast.on(BroadCastConstants.DOWNLOAD_CANCEL_OPERATE, this.downloadCancelOperateFunc); + this.broadCast.on(BroadCastConstants.SHOW_SAVE_PHOTO_DIALOG, this.showSavePhotoDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_EDIT_EXIT_PHOTO_DIALOG, this.showEditExitPhotoDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_EDIT_SAVE_PROGRESS_DIALOG, this.showEditSaveProgressDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_NEW_ALBUM_PHOTO_DIALOG, this.showNewAlbumDialogFunc); + this.broadCast.on(BroadCastConstants.SHOW_COPY_OR_MOVE_DIALOG, this.showCopyOrMoveDialogFunc); + this.broadCast.on(BroadCastConstants.DELETE_PROGRESS_DIALOG, this.deleteProgressDialogFunc); + this.broadCast.on(BroadCastConstants.REMOVE_PROGRESS_DIALOG, this.removeProgressDialogFunc); } build() { diff --git a/common/src/main/ets/default/view/dialog/DeleteDialog.ets b/common/src/main/ets/default/view/dialog/DeleteDialog.ets index ec47f832..be8730dd 100644 --- a/common/src/main/ets/default/view/dialog/DeleteDialog.ets +++ b/common/src/main/ets/default/view/dialog/DeleteDialog.ets @@ -17,6 +17,7 @@ import { Log } from '../../utils/Log'; import { ColumnSize, ScreenManager } from '../../model/common/ScreenManager'; import { Constants } from '../../model/common/Constants'; import data_preferences from '@ohos.data.preferences'; +import { BusinessError } from '@ohos.base'; const TAG: string = 'common_DeleteDialog'; @@ -28,19 +29,19 @@ export struct DeleteDialog { = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; @Consume dialogCallback: DialogCallback; @Consume dialogMessage: Resource; - controller: CustomDialogController; + controller?: CustomDialogController; @StorageLink('isFirstTimeDelete') isFirstTimeDelete: boolean = false; @StorageLink('confirmText') confirmText: Resource = $r('app.string.dialog_delete'); - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; aboutToDisappear() { if (this.isFirstTimeDelete) { AppStorage.SetOrCreate(Constants.IS_FIRST_TIME_DELETE, false); - let pref: data_preferences.Preferences = AppStorage.Get(Constants.PHOTOS_STORE_KEY); + let pref: data_preferences.Preferences = AppStorage.get(Constants.PHOTOS_STORE_KEY) as data_preferences.Preferences; pref.put(Constants.IS_FIRST_TIME_DELETE, false).then(() => { Log.debug(TAG, `Succeeded in putting the value of '${Constants.IS_FIRST_TIME_DELETE}'.`); pref.flush(); - }).catch((err) => { + }).catch((err: BusinessError) => { Log.error(TAG, `Failed to put the value of '${Constants.IS_FIRST_TIME_DELETE}'. Cause: ${err}`); }); } @@ -102,7 +103,7 @@ export struct DeleteDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { Log.debug(TAG, `cancelCallback`); - this.controller.close(); + this.controller?.close(); this.dialogCallback && this.dialogCallback.cancelCallback(); }) }.width('50%') @@ -132,7 +133,7 @@ export struct DeleteDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { Log.debug(TAG, `confirmCallback`); - this.controller.close(); + this.controller?.close(); this.dialogCallback && this.dialogCallback.confirmCallback(); }) }.width('50%') diff --git a/common/src/main/ets/default/view/dialog/DeleteProgressDialog.ets b/common/src/main/ets/default/view/dialog/DeleteProgressDialog.ets index 5aa3b0a6..3edb898f 100644 --- a/common/src/main/ets/default/view/dialog/DeleteProgressDialog.ets +++ b/common/src/main/ets/default/view/dialog/DeleteProgressDialog.ets @@ -21,9 +21,9 @@ const TAG: string = 'common_DeleteProgressDialog'; @Observed export class DeleteProgressParam { - currentCount: number - totalCount: number - message: Resource + currentCount: number = 0; + totalCount: number = 0; + message?: Resource } @CustomDialog @@ -32,10 +32,10 @@ export struct DeleteProgressDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController + controller?: CustomDialogController @Consume deleteProgress: number; @Consume deleteProgressParam: DeleteProgressParam; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; build() { Column() { diff --git a/common/src/main/ets/default/view/dialog/DetailsDialog.ets b/common/src/main/ets/default/view/dialog/DetailsDialog.ets index 62fa3870..daceec90 100644 --- a/common/src/main/ets/default/view/dialog/DetailsDialog.ets +++ b/common/src/main/ets/default/view/dialog/DetailsDialog.ets @@ -24,16 +24,16 @@ const TAG: string = 'common_DetailsDialog'; @Observed export class MediaDetails { - mediaType: number - height: number - width: number - size: number - duration: number - title: string - dateTaken: number - uri: string - displayName: string - dateModified: number + mediaType: number = 0; + height: number = 0; + width: number = 0; + size: number = 0; + duration: number = 0; + title: string = ''; + dateTaken: number = 0; + uri: string = ''; + displayName: string = ''; + dateModified: number = 0; } @CustomDialog @@ -45,13 +45,13 @@ export struct DetailsDialog { @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; sizeConvert = 1024; - controller: CustomDialogController; - dataTime: string; + controller?: CustomDialogController; + dataTime: string = ''; @Consume mediaDetails: MediaDetails; @Consume isDistributedAlbum: boolean; @State refresh: boolean = false; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; - onWindowSizeChangeCallBack = () => this.updateDialogSize(); + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; + onWindowSizeChangeCallBack = (): void => this.updateDialogSize(); aboutToAppear() { let localizedDate = DateUtil.getLocalizedDate(this.mediaDetails.dateTaken); @@ -65,7 +65,6 @@ export struct DetailsDialog { aboutToDisappear(): void { Log.info(TAG, 'aboutToDisappear'); ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; } getResolution(height: number, width: number): string { @@ -151,7 +150,7 @@ export struct DetailsDialog { .backgroundColor(this.isPcDevice ? $r('sys.color.ohos_id_color_button_normal') : $r('app.color.transparent')) .height($r('app.float.details_dialog_button_height')) .onClick(() => { - this.controller.close() + this.controller?.close(); }) .margin({ left: $r('app.float.dialog_single_button_indent_margin'), diff --git a/common/src/main/ets/default/view/dialog/DownloadCancelOperationDialog.ets b/common/src/main/ets/default/view/dialog/DownloadCancelOperationDialog.ets index 0807c61e..39661990 100644 --- a/common/src/main/ets/default/view/dialog/DownloadCancelOperationDialog.ets +++ b/common/src/main/ets/default/view/dialog/DownloadCancelOperationDialog.ets @@ -22,8 +22,8 @@ const TAG: string = 'common_DownloadCancelOperationDialog'; @Observed export class CancelParam { - continueFunc: Function - cancelFunc: Function + continueFunc: Function = (): void => {}; + cancelFunc: Function = (): void => {}; } @CustomDialog @@ -32,11 +32,11 @@ export struct DownloadCancelOperationDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; + controller?: CustomDialogController; @Consume broadCast: BroadCast; @Consume deleteProgress: number; @Consume cancelParam: CancelParam; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; build() { Column() { @@ -71,7 +71,7 @@ export struct DownloadCancelOperationDialog { .onClick(() => { Log.info(TAG, 'click continue') this.cancelParam.continueFunc(); - this.controller.close() + this.controller?.close(); }) }.width('50%') @@ -93,7 +93,7 @@ export struct DownloadCancelOperationDialog { .onClick(() => { Log.info(TAG, 'click cancel') this.cancelParam.cancelFunc(); - this.controller.close() + this.controller?.close(); }) }.width('50%') } diff --git a/common/src/main/ets/default/view/dialog/EditExitDialog.ets b/common/src/main/ets/default/view/dialog/EditExitDialog.ets index e6044d22..af6989f6 100644 --- a/common/src/main/ets/default/view/dialog/EditExitDialog.ets +++ b/common/src/main/ets/default/view/dialog/EditExitDialog.ets @@ -19,7 +19,7 @@ import { Constants } from '../../model/common/Constants'; @Observed export class EditExitDialogCallback { - discardCallback: Function + discardCallback: Function = (): void => {}; } @CustomDialog @@ -29,8 +29,8 @@ export struct EditExitDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + controller?: CustomDialogController; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; build() { Column() { @@ -65,7 +65,7 @@ export struct EditExitDialog { .borderRadius($r('sys.float.ohos_id_corner_radius_button')) .height($r('app.float.details_dialog_button_height')) .onClick(() => { - this.controller.close() + this.controller?.close(); }) }.width('50%') @@ -93,7 +93,7 @@ export struct EditExitDialog { .borderRadius($r('sys.float.ohos_id_corner_radius_button')) .height($r('app.float.details_dialog_button_height')) .onClick(() => { - this.controller.close() + this.controller?.close(); this.editExitDialogCallback && this.editExitDialogCallback.discardCallback() router.back() }) diff --git a/common/src/main/ets/default/view/dialog/MultiSelectDialog.ets b/common/src/main/ets/default/view/dialog/MultiSelectDialog.ets index beb3a1fe..81916fa5 100644 --- a/common/src/main/ets/default/view/dialog/MultiSelectDialog.ets +++ b/common/src/main/ets/default/view/dialog/MultiSelectDialog.ets @@ -22,8 +22,8 @@ const TAG: string = 'common_MultiSelectDialog'; @Observed export class MultiSelectDetails { - count: number; - size: number + count: number = 0; + size: number = 0; } @CustomDialog @@ -34,9 +34,9 @@ export struct MultiSelectDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; + controller?: CustomDialogController; @Consume multiSelectDetails: MultiSelectDetails; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; aboutToAppear() { } @@ -95,7 +95,7 @@ export struct MultiSelectDialog { .backgroundColor($r('sys.color.ohos_id_color_button_normal')) .height($r('app.float.details_dialog_button_height')) .onClick(() => { - this.controller.close() + this.controller?.close(); }) .margin({ left: $r('app.float.dialog_single_button_indent_margin'), diff --git a/common/src/main/ets/default/view/dialog/NewAlbumDialog.ets b/common/src/main/ets/default/view/dialog/NewAlbumDialog.ets index 7cf848e8..f502f0b0 100644 --- a/common/src/main/ets/default/view/dialog/NewAlbumDialog.ets +++ b/common/src/main/ets/default/view/dialog/NewAlbumDialog.ets @@ -28,7 +28,7 @@ export struct NewAlbumDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; + controller?: CustomDialogController; @Consume renameFileName: string; @Consume dialogCallback: DialogCallback; @State isNull: boolean = false; @@ -36,7 +36,7 @@ export struct NewAlbumDialog { @State dividerWidth: string = '1vp'; @State isFocusable: boolean = true; private inputName: string = ''; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; aboutToAppear(): void { Log.info(TAG, 'aboutToAppear'); @@ -71,8 +71,8 @@ export struct NewAlbumDialog { .maxLength(Constants.RENAME_MAX_LENGTH) .enterKeyType(EnterKeyType.Done) .backgroundColor($r('app.color.transparent')) - .onTouch((event: TouchEvent) => { - if (event.type == TouchType.Down && !this.isFocusable) { + .onTouch((event?: TouchEvent) => { + if ((event as TouchEvent).type == TouchType.Down && !this.isFocusable) { this.isFocusable = true; } }) @@ -115,7 +115,7 @@ export struct NewAlbumDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { this.dialogCallback && this.dialogCallback.cancelCallback(); - this.controller.close(); + this.controller?.close(); }) }.width('50%') @@ -178,12 +178,13 @@ export struct NewAlbumDialog { private handleConfirmCallback() { if (this.dialogCallback === null || this.dialogCallback === undefined) { - this.controller.close(); + this.controller?.close(); return; } - this.dialogCallback.confirmCallback(this.inputName).then((res) => { + let confirmCb: Promise = (this.dialogCallback as DialogCallback).confirmCallback(this.inputName) as Promise; + confirmCb.then((res: Function): void => { if (res) { - this.controller.close(); + this.controller?.close(); return; } Log.warn(TAG, 'new album name is not available!'); diff --git a/common/src/main/ets/default/view/dialog/ProgressDialog.ets b/common/src/main/ets/default/view/dialog/ProgressDialog.ets index d18c6562..9a09c905 100644 --- a/common/src/main/ets/default/view/dialog/ProgressDialog.ets +++ b/common/src/main/ets/default/view/dialog/ProgressDialog.ets @@ -22,8 +22,8 @@ const TAG: string = 'common_ProgressDialog'; @Observed export class ProgressParam { - cancelFunc: Function - operationType: string + cancelFunc: Function = (): void => {}; + operationType: string = ''; } @CustomDialog @@ -32,7 +32,7 @@ export struct ProgressDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController + controller?: CustomDialogController @Consume progressMessage: Resource; @Consume deleteProgress: number; @Consume progressParam: ProgressParam; diff --git a/common/src/main/ets/default/view/dialog/RemoveDialog.ets b/common/src/main/ets/default/view/dialog/RemoveDialog.ets index 148bef47..71853312 100644 --- a/common/src/main/ets/default/view/dialog/RemoveDialog.ets +++ b/common/src/main/ets/default/view/dialog/RemoveDialog.ets @@ -28,9 +28,9 @@ export struct RemoveDialog { = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; @Consume dialogCallback: DialogCallback; @Consume dialogMessage: Resource; - controller: CustomDialogController; + controller?: CustomDialogController; @StorageLink('confirmText') confirmText: Resource = $r('app.string.dialog_remove'); - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; build() { Column() { @@ -69,7 +69,7 @@ export struct RemoveDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { Log.debug(TAG, `cancelCallback`); - this.controller.close(); + this.controller?.close(); this.dialogCallback && this.dialogCallback.cancelCallback(); }) }.width('50%') @@ -99,7 +99,7 @@ export struct RemoveDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { Log.debug(TAG, `confirmCallback`); - this.controller.close(); + this.controller?.close(); this.dialogCallback && this.dialogCallback.confirmCallback(); }) }.width('50%') diff --git a/common/src/main/ets/default/view/dialog/RemoveProgressDialog.ets b/common/src/main/ets/default/view/dialog/RemoveProgressDialog.ets index aeea3a9b..2400d6f5 100644 --- a/common/src/main/ets/default/view/dialog/RemoveProgressDialog.ets +++ b/common/src/main/ets/default/view/dialog/RemoveProgressDialog.ets @@ -21,9 +21,9 @@ const TAG: string = 'common_RemoveProgressDialog'; @Observed export class RemoveProgressParam { - currentCount: number - totalCount: number - message: Resource + currentCount: number = 0; + totalCount: number = 0; + message?: Resource } @CustomDialog @@ -32,10 +32,10 @@ export struct RemoveProgressDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController + controller?: CustomDialogController @Consume removeProgress: number; @Consume removeProgressParam: RemoveProgressParam; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; build() { Column() { diff --git a/common/src/main/ets/default/view/dialog/RenameDialog.ets b/common/src/main/ets/default/view/dialog/RenameDialog.ets index f5579a36..d3016305 100644 --- a/common/src/main/ets/default/view/dialog/RenameDialog.ets +++ b/common/src/main/ets/default/view/dialog/RenameDialog.ets @@ -28,14 +28,14 @@ export struct RenameDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; + controller?: CustomDialogController; @Consume renameFileName: string; @Consume dialogCallback: DialogCallback; @State isNull: boolean = false; @State dividerColor: Resource = $r('app.color.dialog_divider_h_color_182431'); @State dividerWidth: string = '1vp'; private inputName: string = ''; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; aboutToAppear(): void { Log.info(TAG, 'aboutToAppear'); @@ -108,7 +108,7 @@ export struct RenameDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { this.dialogCallback && this.dialogCallback.cancelCallback(); - this.controller.close() + this.controller?.close(); }) }.width('50%') @@ -142,11 +142,11 @@ export struct RenameDialog { return; } if (this.inputName == this.renameFileName) { - this.controller.close(); + this.controller?.close(); return; } this.dialogCallback && this.dialogCallback.confirmCallback(this.inputName); - this.controller.close(); + this.controller?.close(); }) }.width('50%') } diff --git a/common/src/main/ets/default/view/dialog/SaveDialog.ets b/common/src/main/ets/default/view/dialog/SaveDialog.ets index 8a1add5a..a302d657 100644 --- a/common/src/main/ets/default/view/dialog/SaveDialog.ets +++ b/common/src/main/ets/default/view/dialog/SaveDialog.ets @@ -20,8 +20,8 @@ import { Constants } from '../../model/common/Constants'; @Observed export class SaveDialogCallback { - saveAsNewCallback: Function - replaceOriginalCallback: Function + saveAsNewCallback: Function = (): void => {}; + replaceOriginalCallback: Function = (): void => {}; } @Extend(Text) function buttonTextExtend() { @@ -31,7 +31,7 @@ export class SaveDialogCallback { .fontWeight(FontWeight.Medium) } -@Extend(Button) function verticalButtonExtend(isPcDevice) { +@Extend(Button) function verticalButtonExtend(isPcDevice: boolean) { .width('100%') .height($r('app.float.details_dialog_button_height')) .borderRadius($r('sys.float.ohos_id_corner_radius_button')) @@ -46,9 +46,9 @@ export struct SaveDialog { = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; @Consume broadCast: BroadCast; @Consume saveDialogCallback: SaveDialogCallback; - controller: CustomDialogController; + controller?: CustomDialogController; readonly buttonWidth: number = 100 / 3; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; @Builder horizontalThreeButtons() { Stack({ alignContent: Alignment.Top }) { @@ -64,7 +64,7 @@ export struct SaveDialog { .backgroundColor($r('app.color.transparent')) .height($r('app.float.details_dialog_button_height')) .onClick(() => { - this.controller.close() + this.controller?.close(); }) }.width(`${this.buttonWidth}%`) @@ -83,7 +83,7 @@ export struct SaveDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { this.broadCast.emit(BroadCastConstants.SHOW_EDIT_SAVE_PROGRESS_DIALOG, []); - this.controller.close() + this.controller?.close(); this.saveDialogCallback && this.saveDialogCallback.replaceOriginalCallback() }) }.width(`${this.buttonWidth}%`) @@ -101,7 +101,7 @@ export struct SaveDialog { .backgroundColor($r('app.color.transparent')) .height($r('app.float.details_dialog_button_height')) .onClick(() => { - this.controller.close() + this.controller?.close(); this.broadCast.emit(BroadCastConstants.SHOW_EDIT_SAVE_PROGRESS_DIALOG, []); this.saveDialogCallback && this.saveDialogCallback.saveAsNewCallback() }) @@ -126,7 +126,7 @@ export struct SaveDialog { .verticalButtonExtend(this.isPcDevice) .margin({ bottom: $r('app.float.vertical_three_buttons_margin_bottom') }) .onClick(() => { - this.controller.close() + this.controller?.close(); this.broadCast.emit(BroadCastConstants.SHOW_EDIT_SAVE_PROGRESS_DIALOG, []); this.saveDialogCallback && this.saveDialogCallback.saveAsNewCallback() }) @@ -142,7 +142,7 @@ export struct SaveDialog { .margin({ bottom: $r('app.float.vertical_three_buttons_margin_bottom') }) .onClick(() => { this.broadCast.emit(BroadCastConstants.SHOW_EDIT_SAVE_PROGRESS_DIALOG, []); - this.controller.close() + this.controller?.close(); this.saveDialogCallback && this.saveDialogCallback.replaceOriginalCallback() }) } @@ -155,7 +155,7 @@ export struct SaveDialog { .key('Cancel') .verticalButtonExtend(this.isPcDevice) .onClick(() => { - this.controller.close() + this.controller?.close(); }) }.width('100%') } diff --git a/common/src/main/ets/default/view/dialog/SaveImageDialog.ets b/common/src/main/ets/default/view/dialog/SaveImageDialog.ets index fe1ec4da..11987c2a 100644 --- a/common/src/main/ets/default/view/dialog/SaveImageDialog.ets +++ b/common/src/main/ets/default/view/dialog/SaveImageDialog.ets @@ -25,19 +25,19 @@ export struct SaveImageDialog { @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - controller: CustomDialogController; - private isPcDevice: boolean = AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE; + controller?: CustomDialogController; + private isPcDevice: boolean = AppStorage.get('deviceType') === Constants.PC_DEVICE_TYPE; controllerClose() { - this.controller.close() + this.controller?.close(); } aboutToAppear() { - this.broadCast.on(BroadCastConstants.EXIT_SAVE_PROGRESS_CLOSE, this.controllerClose.bind(this)); + this.broadCast.on(BroadCastConstants.EXIT_SAVE_PROGRESS_CLOSE, (): void => this.controllerClose()); } aboutToDisappear(): void { - this.broadCast.off(null, null); + this.broadCast.off(BroadCastConstants.EXIT_SAVE_PROGRESS_CLOSE, (): void => {}); } build() { diff --git a/common/src/main/ets/default/view/dialog/ThirdDeleteDialog.ets b/common/src/main/ets/default/view/dialog/ThirdDeleteDialog.ets index e9288a77..1beeac07 100644 --- a/common/src/main/ets/default/view/dialog/ThirdDeleteDialog.ets +++ b/common/src/main/ets/default/view/dialog/ThirdDeleteDialog.ets @@ -26,14 +26,15 @@ export struct ThirdDeleteDialog { @Consume dialogCallback: DialogCallback; @Consume dialogMessage: Resource; @StorageLink('confirmText') confirmText: Resource = $r('app.string.dialog_delete'); - controller: CustomDialogController; + controller?: CustomDialogController; - private uris: any; - private thirdAppName: string; + private uris: string[] = []; + private thirdAppName: string | undefined = ''; aboutToAppear() { - this.uris = AppStorage.Get("uris"); - this.thirdAppName = AppStorage.Get("appName"); + let stored = AppStorage.get('uris'); + this.uris = stored === undefined ? [] : stored; + this.thirdAppName = AppStorage.get('appName'); } build() { @@ -94,7 +95,7 @@ export struct ThirdDeleteDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { Log.debug(this.TAG, `cancelCallback`); - this.controller.close(); + this.controller?.close(); this.dialogCallback && this.dialogCallback.cancelCallback(); }) }.width('50%') @@ -121,7 +122,7 @@ export struct ThirdDeleteDialog { .height($r('app.float.details_dialog_button_height')) .onClick(() => { Log.debug(this.TAG, `confirmCallback`); - this.controller.close(); + this.controller?.close(); this.dialogCallback && this.dialogCallback.confirmCallback(); }) }.width('50%') diff --git a/feature/browser/src/main/ets/default/view/album/AlbumGridItemNewStyle.ets b/feature/browser/src/main/ets/default/view/album/AlbumGridItemNewStyle.ets index d55a89da..6403f35c 100644 --- a/feature/browser/src/main/ets/default/view/album/AlbumGridItemNewStyle.ets +++ b/feature/browser/src/main/ets/default/view/album/AlbumGridItemNewStyle.ets @@ -38,6 +38,11 @@ const TAG: string = 'browser_AlbumGridItemNewStyle'; .focusable(true) } +interface ParamAlbumInfo { + item: string; + isFromFACard?: boolean; +} + // The item of album grid, and it's new style. @Component export struct AlbumGridItemNewStyle { @@ -54,20 +59,21 @@ export struct AlbumGridItemNewStyle { @Consume('selectedCount') selectedCount: number; @Consume @Watch('onModeChange') isAlbumSetSelectedMode: boolean; @Consume rightClickMenuList: Array; - currentRightClickMenuList: Array; - onMenuClicked: Function; - onMenuClickedForSingleItem: Function; + currentRightClickMenuList: Array = []; + onMenuClicked: Function = (): void => {}; + onMenuClickedForSingleItem: Function = (): void => {}; gridAspectRatio = Constants.CARD_ASPECT_RATIO; albumCountMarginRight = Constants.ALBUM_SET_NEW_ICON_SIZE + Constants.ALBUM_SET_NEW_ICON_MARGIN * 2; iconMarkAnchorX = Constants.ALBUM_SET_NEW_ICON_SIZE + Constants.ALBUM_SET_NEW_ICON_MARGIN; iconMarkAnchorY = Constants.ALBUM_SET_NEW_ICON_SIZE + Constants.ALBUM_SET_NEW_ICON_MARGIN; - @StorageLink('deviceType') deviceType: string = AppStorage.Get('deviceType'); + @StorageLink('deviceType') deviceType: string | undefined = AppStorage.get('deviceType') ; @State transitionId: string = ''; @StorageLink('isShowPhotoGridView') isShowPhotoGridView: boolean = false; private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); private keyIndex?: number; private fp2vpUnit: number = px2vp(fp2px(Constants.NUMBER_1)); private recycleAlbumOfPhoneHeight: number = Constants.RECYCLE_ALBUM_OF_PHONE_HEIGHT; + private updateCardSizeFunc: Function = (): void => this.updateCardSize(); doAnimation(): void { let albumToPhotoGridDuration: number; @@ -93,14 +99,14 @@ export struct AlbumGridItemNewStyle { curve: Curve.Friction, }, () => { AppStorage.SetOrCreate(Constants.KEY_OF_IS_SHOW_PHOTO_GRID_VIEW,!this.isShowPhotoGridView); - AppStorage.SetOrCreate(Constants.KEY_OF_SELECTED_ALBUM_INDEX, this.keyIndex); + AppStorage.SetOrCreate(Constants.KEY_OF_SELECTED_ALBUM_INDEX, this.keyIndex ? this.keyIndex : -1); AppStorage.SetOrCreate(Constants.KEY_OF_SELECTED_ALBUM_URI, this.item.uri); }) animateTo({ duration: albumActionBarDuration, curve: Curve.Sharp }, () => { - if (AppStorage.Get('deviceType') !== Constants.PC_DEVICE_TYPE) { + if (AppStorage.get('deviceType') !== Constants.PC_DEVICE_TYPE) { AppStorage.SetOrCreate(Constants.KEY_OF_ALBUM_OPACITY, 0); } AppStorage.SetOrCreate(Constants.KEY_OF_ALBUM_ACTIONBAR_OPACITY, 0); @@ -110,7 +116,7 @@ export struct AlbumGridItemNewStyle { curve: Curve.Sharp, delay: BrowserConstants.LINK_IN_PHOTO_GRID_DELAY, }, () => { - if (AppStorage.Get('deviceType') !== Constants.PC_DEVICE_TYPE) { + if (AppStorage.get('deviceType') !== Constants.PC_DEVICE_TYPE) { AppStorage.SetOrCreate(Constants.KEY_OF_PHOTO_GRID_VIEW_OPACITY, 1); } }) @@ -128,7 +134,7 @@ export struct AlbumGridItemNewStyle { AppStorage.SetOrCreate(Constants.KEY_OF_PHOTO_GRID_ACTIONBAR_OPACITY, 1); }) - if (AppStorage.Get('deviceType') === Constants.PC_DEVICE_TYPE) { + if (AppStorage.get('deviceType') !== Constants.PC_DEVICE_TYPE) { animateTo({ duration: BrowserConstants.PC_LINK_IN_PHOTO_GRID_DURATION, delay: BrowserConstants.LINK_IN_PHOTO_GRID_DELAY, @@ -157,15 +163,14 @@ export struct AlbumGridItemNewStyle { aboutToAppear(): void { Log.debug(TAG, `aboutToAppear`); this.selectable = !this.item.isTrashAlbum; - this.updateCardSize = this.updateCardSize.bind(this) // 后续phone缩略图支持横竖屏后再放开 - if (AppStorage.Get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { - ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateCardSize); + if (AppStorage.get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { + ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateCardSizeFunc); } - let isFirstPhotoItem = AppStorage.Get(Constants.KEY_OF_IS_FIRST_PHOTO_ITEM); - let lastTransitionId = AppStorage.Get(Constants.KEY_OF_GEOMETRY_TRANSITION_ID_HEIGHT); - if (!isFirstPhotoItem && this.item.uri === AppStorage.Get(Constants.KEY_OF_ALBUM_URI)) { + let isFirstPhotoItem = AppStorage.get(Constants.KEY_OF_IS_FIRST_PHOTO_ITEM); + let lastTransitionId = AppStorage.get(Constants.KEY_OF_GEOMETRY_TRANSITION_ID_HEIGHT) as string; + if (!isFirstPhotoItem && this.item.uri === AppStorage.get(Constants.KEY_OF_ALBUM_URI)) { this.transitionId = lastTransitionId; } else { if (!this.isRecycleAlbumOfPhoneLikeDevice() && this.item.mediaItem) { @@ -183,9 +188,8 @@ export struct AlbumGridItemNewStyle { aboutToDisappear(): void { // 后续phone缩略图支持横竖屏后再放开 - if (AppStorage.Get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { - ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateCardSize); - this.updateCardSize = null; + if (AppStorage.get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { + ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateCardSizeFunc); } } @@ -197,7 +201,7 @@ export struct AlbumGridItemNewStyle { updateCardSize(): void { let sideBarWidth: number = 0; let count: number = 0; - let currentBreakpoint = AppStorage.Get('currentBreakpoint'); + let currentBreakpoint = AppStorage.get('currentBreakpoint'); if (currentBreakpoint === Constants.BREAKPOINT_LG && this.deviceType == Constants.PAD_DEVICE_TYPE) { sideBarWidth = Constants.PAD_TAB_BAR_WIDTH; count = UiUtil.getAlbumGridCount(true); @@ -244,10 +248,10 @@ export struct AlbumGridItemNewStyle { if (this.selectable) { let newState: boolean = !this.isSelected; this.broadCast.emit(BroadCastConstants.SELECT, - [this.item.uri, newState, this.item.isSystemAlbum, this.item.isSystemAlbum, function(){ + [this.item.uri, newState, this.item.isSystemAlbum, this.item.isSystemAlbum, (): void => { Log.info(TAG, 'enter callback'); this.isSelected = newState; - }.bind(this)]); + }]); } } @@ -288,7 +292,7 @@ export struct AlbumGridItemNewStyle { } } }) - }, menu => menu.actionID.toString()) + }, (menu: Action) => menu.actionID.toString()) } .width(ScreenManager.getInstance().getColumnsWidth(ColumnSize.COLUMN_ONE_POINT_FIVE)) .borderRadius($r('sys.float.ohos_id_corner_radius_card')) @@ -449,8 +453,8 @@ export struct AlbumGridItemNewStyle { this.albumOnClick(); }) .bindContextMenu(this.RightClickMenuBuilder, this.showRightClickPopup() ? ResponseType.RightClick : -1) - .onKeyEvent((event: KeyEvent) => { - if (KeyType.Up == event.type) { + .onKeyEvent((event?: KeyEvent) => { + if (event != null && KeyType.Up == event.type) { switch (event.keyCode) { case MultimodalInputManager.KEY_CODE_KEYBOARD_ENTER: this.albumOnClick(); @@ -489,7 +493,7 @@ export struct AlbumGridItemNewStyle { this.selectStateChange(); } else { Log.info(TAG, `After onClick, MediaSet is: ${JSON.stringify(this.item)}`); - if (this.item.isTrashAlbum && AppStorage.Get('deviceType') !== Constants.PC_DEVICE_TYPE) { + if (this.item.isTrashAlbum && (AppStorage.get('deviceType') !== Constants.PC_DEVICE_TYPE)) { router.pushUrl({ url: 'pages/PhotoGridPage', params: { @@ -497,7 +501,8 @@ export struct AlbumGridItemNewStyle { } }); } else if (!this.isShowPhotoGridView) { - AppStorage.SetOrCreate(Constants.KEY_OF_PHOTO_GRID_VIEW_ALBUM_ITEM, { item: JSON.stringify(this.item) }); + let albumInfo: ParamAlbumInfo = { item: JSON.stringify(this.item) } + AppStorage.setOrCreate(Constants.KEY_OF_PHOTO_GRID_VIEW_ALBUM_ITEM, albumInfo); AppStorage.SetOrCreate(Constants.KEY_OF_GEOMETRY_TRANSITION_ID_HEIGHT, this.transitionId); AppStorage.SetOrCreate(Constants.KEY_OF_ALBUM_URI, this.item.uri); this.doAnimation(); diff --git a/feature/browser/src/main/ets/default/view/album/AlbumSelectActionBar.ets b/feature/browser/src/main/ets/default/view/album/AlbumSelectActionBar.ets index f146eb39..90d37ccc 100644 --- a/feature/browser/src/main/ets/default/view/album/AlbumSelectActionBar.ets +++ b/feature/browser/src/main/ets/default/view/album/AlbumSelectActionBar.ets @@ -34,7 +34,7 @@ export struct AlbumSelectActionBar { @State actionBarProp: ActionBarProp = new ActionBarProp(); @Link @Watch('createActionBar') totalSelectedCount: number; @Provide selectedCount: number = 0; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @Link @Watch('updateMenu') menuList: Action[]; @Provide moreMenuList: Action[] = new Array(); @Provide hidePopup: boolean = false; diff --git a/feature/browser/src/main/ets/default/view/album/AlbumSelectGridItemNewStyle.ets b/feature/browser/src/main/ets/default/view/album/AlbumSelectGridItemNewStyle.ets index 09a0b729..13d6e41c 100644 --- a/feature/browser/src/main/ets/default/view/album/AlbumSelectGridItemNewStyle.ets +++ b/feature/browser/src/main/ets/default/view/album/AlbumSelectGridItemNewStyle.ets @@ -22,12 +22,12 @@ const TAG: string = 'browser_AlbumSelectGridItemNewStyle'; // The item of album grid, and it's new style. @Component export struct AlbumSelectGridItemNewStyle { - @State @Watch('updateCard') item: AlbumInfo = undefined; + @State @Watch('updateCard') item: AlbumInfo = new AlbumInfo(); @State isEmptyAlbum: boolean = false; @Provide gridHeight: number = 0; @Provide gridWidth: number = 0; @Consume broadCast: BroadCast; - mSelectManager: SelectManager; + mSelectManager: SelectManager | null = null; gridAspectRatio = Constants.CARD_ASPECT_RATIO; albumCountMarginRight = Constants.ALBUM_SET_NEW_ICON_SIZE + Constants.ALBUM_SET_NEW_ICON_MARGIN * 2; iconMarkAnchorX = Constants.ALBUM_SET_NEW_ICON_SIZE + Constants.ALBUM_SET_NEW_ICON_MARGIN; @@ -38,22 +38,21 @@ export struct AlbumSelectGridItemNewStyle { [AlbumDefine.ALBUM_ID_VIDEO, $r('app.media.ic_video')], [AlbumDefine.ALBUM_ID_FAVOR, $r('app.media.ic_favorite_overlay')] ]); + private updateCardSizeFunc: Function = (): void => this.updateCardSize() aboutToAppear(): void { Log.info(TAG, `aboutToAppear + ${this.item.coverUri}`); - this.updateCardSize = this.updateCardSize.bind(this); this.updateCardSize(); // 后续phone缩略图支持横竖屏后再放开 - if (AppStorage.Get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { - ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateCardSize); + if (AppStorage.get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { + ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateCardSizeFunc); } } aboutToDisappear(): void { // 后续phone缩略图支持横竖屏后再放开 - if (AppStorage.Get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { - ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateCardSize); - this.updateCardSize = null; + if (AppStorage.get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { + ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.updateCardSizeFunc); } } diff --git a/feature/browser/src/main/ets/default/view/album/AlbumSetPage.ets b/feature/browser/src/main/ets/default/view/album/AlbumSetPage.ets index 0caed3b8..23dca634 100644 --- a/feature/browser/src/main/ets/default/view/album/AlbumSetPage.ets +++ b/feature/browser/src/main/ets/default/view/album/AlbumSetPage.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { MenuOperation } from '@ohos/common'; +import { MenuOperation, WindowUtil } from '@ohos/common'; import { Action, AlbumInfo, @@ -73,7 +73,7 @@ export struct AlbumSetPage { @Provide rightClickMenuList: Array = new Array(); @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @StorageLink('statusBarHeight') statusBarHeight: number = 0; - @StorageLink('deviceType') deviceType: string = AppStorage.Get('deviceType'); + @StorageLink('deviceType') deviceType: string | undefined = AppStorage.get('deviceType') ; @State pageStatus: boolean = false; @State bottomHeight: number = 0; @StorageLink('selectedAlbumUri') selectedAlbumUri: string = ''; @@ -90,61 +90,59 @@ export struct AlbumSetPage { private needNotify = false; private ignoreLocalNotify = false; private minGridColumnsCount: number = 2; + private onWinSizeChangedFunc: Function = (): void => this.initGridRowCount(); + private onTabChangedFunc: Function = (index: number): void => this.onTabChanged(index); + private onStateResetFunc: Function = (index: number): void => this.onStateReset(index); + private onSendMoveCopyBroadCastFunc: Function = (index: number): void => this.onSendMoveCopyBroadCast(index); + private onLoadingFinishedFunc: Function = (size: number): void => this.onLoadingFinished(size); + private onResetZeroFunc: Function = (pageNumber: number): void => this.onResetZero(pageNumber); + private onUpdateRemoteDeviceFunc: Function = (res: string, deviceId: string, size: number): void => + this.onUpdateRemoteDevice(res, deviceId, size); + private onMenuClickedFunc = (action: Action, arg: Object[]): void => this.onMenuClicked(action, arg); + private selectFunc = ( + key: string, value: boolean, isDisableRename: boolean, isDisableDelete: boolean, callback: Function): void => + this.select(key, value, isDisableRename, isDisableDelete, callback); - onMenuClicked(action: Action, arg: unknown[]) { + onMenuClicked(action: Action, arg: Object[]) { Log.info(TAG, `onMenuClicked, action: ${action.actionID}`); let menuContext: MenuContext; let menuOperation: MenuOperation; - switch (action.actionID) { - case Action.NEW.actionID: - menuContext = new MenuContext(); - this.onOperationStart = this.onOperationStart.bind(this); - this.onOperationEnd = this.onOperationEnd.bind(this); - menuContext - .withOperationStartCallback(this.onOperationStart) - .withOperationEndCallback(this.onOperationEnd) - .withAlbumSetDataSource(this.albums) - .withBroadCast(this.broadCast); - menuOperation + if (action.actionID === Action.NEW.actionID) { + menuContext = new MenuContext(); + menuContext + .withOperationStartCallback((): void => this.onOperationStart()) + .withOperationEndCallback((): void => this.onOperationEnd()) + .withAlbumSetDataSource(this.albums) + .withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AlbumSetNewMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.CANCEL.actionID: - this.isAlbumSetSelectedMode = false; - break; - case Action.MULTISELECT.actionID: - this.isAlbumSetSelectedMode = true; - break; - case Action.RENAME.actionID: - menuContext = new MenuContext(); - this.onOperationStart = this.onOperationStart.bind(this); - this.onOperationEnd = this.onOperationEnd.bind(this); - menuContext - .withFromSelectMode(true) - .withSelectManager(this.mSelectManager) - .withOperationStartCallback(this.onOperationStart) - .withOperationEndCallback(this.onOperationEnd) - .withBroadCast(this.broadCast); - menuOperation + menuOperation.doAction(); + } else if (action.actionID === Action.CANCEL.actionID) { + this.isAlbumSetSelectedMode = false; + } else if (action.actionID === Action.MULTISELECT.actionID) { + this.isAlbumSetSelectedMode = true; + } else if (action.actionID === Action.RENAME.actionID) { + menuContext = new MenuContext(); + menuContext + .withFromSelectMode(true) + .withSelectManager(this.mSelectManager) + .withOperationStartCallback((): void => this.onOperationStart()) + .withOperationEndCallback((): void => this.onOperationEnd()) + .withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AlbumSetRenameMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.DELETE.actionID: - menuContext = new MenuContext(); - this.onOperationStart = this.onOperationStart.bind(this); - this.onOperationEnd = this.onOperationEnd.bind(this); - menuContext - .withFromSelectMode(true) - .withSelectManager(this.mSelectManager) - .withOperationStartCallback(this.onOperationStart) - .withOperationEndCallback(this.onOperationEnd) - .withBroadCast(this.broadCast); - menuOperation + menuOperation.doAction(); + } else if (action.actionID === Action.DELETE.actionID) { + menuContext = new MenuContext(); + menuContext + .withFromSelectMode(true) + .withSelectManager(this.mSelectManager) + .withOperationStartCallback((): void => this.onOperationStart()) + .withOperationEndCallback((): void => this.onOperationEnd()) + .withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AlbumSetDeleteMenuOperation, menuContext); - menuOperation.doAction(); - break; - default: - break; + menuOperation.doAction(); } } @@ -166,55 +164,48 @@ export struct AlbumSetPage { aboutToAppear(): void { TraceControllerUtils.startTrace('AlbumSetPageAboutToAppear'); Log.info(TAG, `AlbumSetPageAboutToAppear`); - this.appBroadCast.on(BroadCastConstants.ON_TAB_CHANGED, this.onTabChanged.bind(this)); - this.appBroadCast.on(BroadCastConstants.RESET_STATE_EVENT, this.onStateReset.bind(this)); - this.appBroadCast.on(BroadCastConstants.SEND_COPY_OR_MOVE_BROADCAST, this.onSendMoveCopyBroadCast.bind(this)); + this.appBroadCast.on(BroadCastConstants.ON_TAB_CHANGED, this.onTabChangedFunc); + this.appBroadCast.on(BroadCastConstants.RESET_STATE_EVENT, this.onStateResetFunc); + this.appBroadCast.on(BroadCastConstants.SEND_COPY_OR_MOVE_BROADCAST, this.onSendMoveCopyBroadCastFunc); AppStorage.SetOrCreate('setSelectManagerToAnother', this.mSelectManager); - this.broadCast.on(Constants.ON_LOADING_FINISHED, (size: number) => { - this.isEmpty = (size == 0); - }); - - this.appBroadCast.on(BroadCastConstants.RESET_ZERO, this.onResetZero.bind(this)); - this.appBroadCast.on(BroadCastConstants.ON_REMOTE_CHANGED, this.onUpdateRemoteDevice.bind(this)); + this.broadCast.on(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); + this.appBroadCast.on(BroadCastConstants.RESET_ZERO, this.onResetZeroFunc); + this.appBroadCast.on(BroadCastConstants.ON_REMOTE_CHANGED, this.onUpdateRemoteDeviceFunc); MediaObserver.getInstance().registerObserver(this.dataObserver); this.onActive(); this.updateRightClickMenuList(); - this.initGridRowCount = this.initGridRowCount.bind(this); this.initGridRowCount(); // 后续phone缩略图支持横竖屏后再放开 - if (AppStorage.Get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { - ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.initGridRowCount); + if (AppStorage.get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { + ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWinSizeChangedFunc); } let self = this; - this.onMenuClicked = this.onMenuClicked.bind(this); - this.onMenuClickedForSingleItem = this.onMenuClickedForSingleItem.bind(this); - this.broadCast.on(BroadCastConstants.SELECT, function ( - key: string, value: boolean, isDisableRename: boolean, isDisableDelete: boolean, callback: Function) { - self.mSelectManager.toolBarStateToggle(key, value, isDisableRename, isDisableDelete); - if (self.mSelectManager.toggle(key, value)) { - Log.info(TAG, 'enter event process'); - callback(); + this.broadCast.on(BroadCastConstants.SELECT, this.selectFunc); + this.mSelectManager.registerCallback('updateCount', (newState: number) => { + Log.info(TAG, `updateSelectedCount ${newState}`); + if (this.isDataFreeze) { + return; + } + if (this.selectedAlbumsCount === 0 && newState === 0) { + this.selectedAlbumsCount--; + } else { + this.selectedAlbumsCount = newState; } }); - this.mSelectManager.registerCallback('updateCount', this.freezeAdapter(function (newState: number) { - Log.info(TAG, `updateSelectedCount ${newState}`); - if (self.selectedAlbumsCount === 0 && newState === 0) { - self.selectedAlbumsCount--; - } else { - self.selectedAlbumsCount = newState; - } - })); - this.mSelectManager.registerCallback('updateToolBarState', this.freezeAdapter( - function (isDisableRename: boolean, isDisableDelete: boolean) { + this.mSelectManager.registerCallback('updateToolBarState', + (isDisableRename: boolean, isDisableDelete: boolean) => { + if (this.isDataFreeze) { + return; + } Log.info(TAG, `updateToolBarState:\ isDisableRename: ${isDisableRename}, isDisableDelete: ${isDisableDelete}`); - self.isDisableRename = isDisableRename - self.isDisableDelete = isDisableDelete - }) + this.isDisableRename = isDisableRename + this.isDisableDelete = isDisableDelete + } ); if (Constants.LOCAL_TAB_INDEX == this.currentIndex) { @@ -229,18 +220,18 @@ export struct AlbumSetPage { aboutToDisappear(): void { this.onInActive(); - this.broadCast.off(null, null); - this.appBroadCast.off(BroadCastConstants.ON_TAB_CHANGED, null); - this.appBroadCast.off(BroadCastConstants.RESET_STATE_EVENT, null); - this.appBroadCast.off(BroadCastConstants.RESET_ZERO, null); - this.appBroadCast.off(BroadCastConstants.ON_REMOTE_CHANGED, null); - this.appBroadCast.off(BroadCastConstants.SEND_COPY_OR_MOVE_BROADCAST, null); + this.broadCast.off(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); + this.broadCast.off(BroadCastConstants.SELECT, this.selectFunc); + this.appBroadCast.off(BroadCastConstants.ON_TAB_CHANGED, this.onTabChangedFunc); + this.appBroadCast.off(BroadCastConstants.RESET_STATE_EVENT, this.onStateResetFunc); + this.appBroadCast.off(BroadCastConstants.SEND_COPY_OR_MOVE_BROADCAST, this.onSendMoveCopyBroadCastFunc); + this.appBroadCast.off(BroadCastConstants.RESET_ZERO, this.onResetZeroFunc); + this.appBroadCast.off(BroadCastConstants.ON_REMOTE_CHANGED, this.onUpdateRemoteDeviceFunc); MediaObserver.getInstance().unregisterObserver(this.dataObserver); this.dataObserver.clearSource(); // 后续phone缩略图支持横竖屏后再放开 - if (AppStorage.Get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { - ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.initGridRowCount); - this.initGridRowCount = null; + if (AppStorage.get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { + ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWinSizeChangedFunc); } } @@ -276,18 +267,6 @@ export struct AlbumSetPage { } } - freezeAdapter(fn): Function { - let self = this; - return function () { - if (self.isDataFreeze) { - return; - } - let context = this; - let args = arguments; - fn.apply(context, args); - } - } - onStateReset(index: number): void { if (index == Constants.ALBUM_PAGE_INDEX) { this.isAlbumSetSelectedMode = false; @@ -305,6 +284,18 @@ export struct AlbumSetPage { } } + onLoadingFinished(size: number): void { + this.isEmpty = (size == 0); + } + + select(key: string, value: boolean, isDisableRename: boolean, isDisableDelete: boolean, callback: Function): void { + this.mSelectManager.toolBarStateToggle(key, value, isDisableRename, isDisableDelete); + if (this.mSelectManager.toggle(key, value)) { + Log.info(TAG, 'enter event process'); + callback(); + } + } + onSendMoveCopyBroadCast(index: number): void { if (index == Constants.ALBUM_PAGE_INDEX) { MoveOrCopyBroadCastProp.getInstance().sendMoveOrAddBroadCast(this.broadCast); @@ -360,7 +351,7 @@ export struct AlbumSetPage { initGridRowCount(): void { Log.info(TAG, `get screen width is : ${ScreenManager.getInstance().getWinWidth()}`); Log.info(TAG, `get screen height is : ${ScreenManager.getInstance().getWinHeight()}`); - let currentBreakpoint = AppStorage.Get('currentBreakpoint'); + let currentBreakpoint = AppStorage.get('currentBreakpoint'); if (currentBreakpoint === Constants.BREAKPOINT_LG && this.deviceType == Constants.PAD_DEVICE_TYPE) { this.gridColumnsCount = UiUtil.getAlbumGridCount(true); } else { @@ -369,7 +360,7 @@ export struct AlbumSetPage { Log.info(TAG, `the grid count in a line is: ${this.gridColumnsCount}`); } - onMediaLibDataChange(changeType) { + onMediaLibDataChange(changeType: string): void { Log.info(TAG, `onMediaLibDataChange type: ${changeType}`); if (!this.ignoreLocalNotify) { this.albums.onChange(changeType); @@ -390,15 +381,16 @@ export struct AlbumSetPage { Column() { } .width('100%') - .height(AppStorage.Get(Constants.KEY_OF_ALBUM_WIDTH)) + .height(AppStorage.get(Constants.KEY_OF_ALBUM_WIDTH) as string) .key('' + index) } else { AlbumGridItemNewStyle({ item: item.data, isSelected: this.isAlbumSetSelectedMode ? this.mSelectManager.isItemSelected(item.data.uri) : false, - onMenuClicked: this.onMenuClicked, - onMenuClickedForSingleItem: this.onMenuClickedForSingleItem, + onMenuClicked: this.onMenuClickedFunc, + onMenuClickedForSingleItem: (action: Action, currentAlbum: AlbumInfo): void => + this.onMenuClickedForSingleItem(action, currentAlbum), keyIndex: index, bottomHeight: $bottomHeight }) @@ -442,7 +434,7 @@ export struct AlbumSetPage { }) { if (!this.isEmpty || this.isTabBarShow) { Column() { - AlbumSetPageActionBar({ onMenuClicked: this.onMenuClicked }) + AlbumSetPageActionBar({ onMenuClicked: this.onMenuClickedFunc }) .opacity(this.albumActionBarOpacity) } .backgroundColor($r('app.color.default_background_color')) @@ -457,7 +449,7 @@ export struct AlbumSetPage { } if (this.isAlbumSetSelectedMode) { - AlbumSetPageToolBar({ onMenuClicked: this.onMenuClicked }) + AlbumSetPageToolBar({ onMenuClicked: this.onMenuClickedFunc }) } if (this.isEmpty && !this.isTabBarShow) { @@ -476,37 +468,28 @@ export struct AlbumSetPage { } let menuContext: MenuContext; let menuOperation: MenuOperation; - switch (action.actionID) { - case Action.RENAME.actionID: - menuContext = new MenuContext(); - this.onOperationStart = this.onOperationStart.bind(this); - this.onOperationEnd = this.onOperationEnd.bind(this); - menuContext - .withFromSelectMode(false) - .withAlbumInfo(currentAlbum) - .withOperationStartCallback(this.onOperationStart) - .withOperationEndCallback(this.onOperationEnd) - .withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(AlbumSetRenameMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.DELETE.actionID: - menuContext = new MenuContext(); - this.onOperationStart = this.onOperationStart.bind(this); - this.onOperationEnd = this.onOperationEnd.bind(this); - menuContext - .withFromSelectMode(false) - .withAlbumInfo(currentAlbum) - .withOperationStartCallback(this.onOperationStart) - .withOperationEndCallback(this.onOperationEnd) - .withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(AlbumSetDeleteMenuOperation, menuContext); - menuOperation.doAction(); - break; - default: - break; + if (action.actionID === Action.RENAME.actionID) { + menuContext = new MenuContext(); + menuContext + .withFromSelectMode(false) + .withAlbumInfo(currentAlbum) + .withOperationStartCallback((): void => this.onOperationStart()) + .withOperationEndCallback((): void => this.onOperationEnd()) + .withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(AlbumSetRenameMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.DELETE.actionID) { + menuContext = new MenuContext(); + menuContext + .withFromSelectMode(false) + .withAlbumInfo(currentAlbum) + .withOperationStartCallback((): void => this.onOperationStart()) + .withOperationEndCallback((): void => this.onOperationEnd()) + .withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(AlbumSetDeleteMenuOperation, menuContext); + menuOperation.doAction(); } } @@ -526,7 +509,7 @@ export struct AlbumSetPage { } } - private onUpdateRemoteDevice(res, deviceId, size): void { + private onUpdateRemoteDevice(res: string, deviceId: string, size: number): void { Log.info(TAG, `onUpdateRemoteDevice size: ${size} deviceId: ${deviceId} type: ${res}`); if (res == 'offline') { diff --git a/feature/browser/src/main/ets/default/view/album/AlbumSetPageActionBar.ets b/feature/browser/src/main/ets/default/view/album/AlbumSetPageActionBar.ets index ac93658b..4da26fd8 100644 --- a/feature/browser/src/main/ets/default/view/album/AlbumSetPageActionBar.ets +++ b/feature/browser/src/main/ets/default/view/album/AlbumSetPageActionBar.ets @@ -38,11 +38,11 @@ export struct AlbumSetPageActionBar { = ScreenManager.getInstance().isHorizontal(); @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @StorageLink('statusBarHeight') statusBarHeight: number = 0; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @State isNeedPlaceholder: boolean = true; @Provide moreMenuList: Action[] = new Array(); @Provide hidePopup: boolean = false; - private deviceType: string; + private deviceType: string = ''; private actionBarPaddingTop: number | Resource = 0; updatePlaceholderStatus(): void { @@ -62,7 +62,7 @@ export struct AlbumSetPageActionBar { } aboutToAppear(): void { - this.deviceType = AppStorage.Get('deviceType'); + this.deviceType = AppStorage.get('deviceType') as string; if (this.deviceType === Constants.PC_DEVICE_TYPE) { this.actionBarPaddingTop = $r('app.float.album_set_page_action_bar_padding_top'); } else if (this.deviceType === Constants.PAD_DEVICE_TYPE) { @@ -110,7 +110,7 @@ export struct AlbumSetPageActionBar { .setSelectionMode(ActionBarSelectionMode.MULTI); } else { menuList.push(Action.NEW) - const deviceType: string = AppStorage.Get('deviceType'); + const deviceType: string = AppStorage.get('deviceType') as string; if (deviceType === Constants.PC_DEVICE_TYPE) { menuList.push(Action.MULTISELECT) } diff --git a/feature/browser/src/main/ets/default/view/album/AlbumSetPageToolBar.ets b/feature/browser/src/main/ets/default/view/album/AlbumSetPageToolBar.ets index 6d0c52e8..276f96ba 100644 --- a/feature/browser/src/main/ets/default/view/album/AlbumSetPageToolBar.ets +++ b/feature/browser/src/main/ets/default/view/album/AlbumSetPageToolBar.ets @@ -27,7 +27,7 @@ export struct AlbumSetPageToolBar { @Consume('selectedCount') @Watch('updateToolbar') selectedAlbumsCount: number; @Consume isDisableRename: boolean; @Consume isDisableDelete: boolean; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @Provide hidePopup: boolean = false; aboutToAppear(): void { diff --git a/feature/browser/src/main/ets/default/view/album/NewAlbumPageActionBar.ets b/feature/browser/src/main/ets/default/view/album/NewAlbumPageActionBar.ets index 26965748..ce664fb5 100644 --- a/feature/browser/src/main/ets/default/view/album/NewAlbumPageActionBar.ets +++ b/feature/browser/src/main/ets/default/view/album/NewAlbumPageActionBar.ets @@ -28,7 +28,7 @@ const TAG: string = 'browser_NewAlbumPageActionBar'; @Component export struct NewAlbumPageActionBar { - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @StorageLink('isHorizontal') @Watch('createActionBar') isHorizontal: boolean = ScreenManager.getInstance() .isHorizontal(); @State actionBarProp: ActionBarProp = new ActionBarProp(); diff --git a/feature/browser/src/main/ets/default/view/album/RecycleAlbum.ets b/feature/browser/src/main/ets/default/view/album/RecycleAlbum.ets index 9a741b5b..4e777068 100644 --- a/feature/browser/src/main/ets/default/view/album/RecycleAlbum.ets +++ b/feature/browser/src/main/ets/default/view/album/RecycleAlbum.ets @@ -17,6 +17,18 @@ import { Constants, Log } from '@ohos/common'; const TAG: string = 'browser_RecycleAlbum'; +interface MsgOnError { + componentWidth: number; + componentHeight: number; +} + +interface MsgOnComplete { + width: number; + height: number; + componentWidth: number; + componentHeight: number; +} + @Component export struct RecycleAlbum { @State icHeight: number = 0; @@ -41,23 +53,19 @@ export struct RecycleAlbum { .width($r('app.float.recycle_album_cover_icon_size')) .height($r('app.float.recycle_album_cover_icon_size')) .fillColor($r('app.color.empty_or_recycle_album_icon')) - .onError((msg: { - componentWidth: number, - componentHeight: number - }) => { - Log.debug(TAG, `image load failed and its componentWidth is: ${msg.componentWidth}`); - Log.debug(TAG, `image load failed and its componentHeight is: ${msg.componentHeight}`); + .onError((msg?: MsgOnError) => { + if(msg){ + Log.debug(TAG, `image load failed and its componentWidth is: ${msg.componentWidth}`); + Log.debug(TAG, `image load failed and its componentHeight is: ${msg.componentHeight}`); + } }) - .onComplete((msg: { - width: number, - height: number, - componentWidth: number, - componentHeight: number - }) => { - Log.debug(TAG, `image load successfully and its width is: ${msg.width}`); - Log.debug(TAG, `image load successfully and its height is: ${msg.height}`); - Log.debug(TAG, `image load successfully and its componentWidth is: ${msg.componentWidth}`); - Log.debug(TAG, `image load successfully and its componentHeight is: ${msg.componentHeight}`); + .onComplete((msg?: MsgOnComplete) => { + if(msg){ + Log.debug(TAG, `image load successfully and its width is: ${msg.width}`); + Log.debug(TAG, `image load successfully and its height is: ${msg.height}`); + Log.debug(TAG, `image load successfully and its componentWidth is: ${msg.componentWidth}`); + Log.debug(TAG, `image load successfully and its componentHeight is: ${msg.componentHeight}`); + } }) } .height(this.icHeight) diff --git a/feature/browser/src/main/ets/default/view/photo/MouseTurnPageButton.ets b/feature/browser/src/main/ets/default/view/photo/MouseTurnPageButton.ets index b76fff43..4ce56ff9 100644 --- a/feature/browser/src/main/ets/default/view/photo/MouseTurnPageButton.ets +++ b/feature/browser/src/main/ets/default/view/photo/MouseTurnPageButton.ets @@ -19,8 +19,8 @@ export struct MouseTurnPageButton { @State buttonBackgroundColor: Resource = $r('app.color.ohos_id_color_whiteIcon_blackPlane') @State isButtonHover: boolean = false @Consume @Watch('handleIconColor') isDefaultBackgroundColor: boolean - private isStart: boolean - private imageResource: Resource + private isStart: boolean = false; + private imageResource: Resource | null = null; aboutToAppear() { this.imageResource = this.isStart ? $r('app.media.ic_public_arrow_left_swiper') @@ -58,8 +58,10 @@ export struct MouseTurnPageButton { width: $r('app.float.mouse_turn_page_button_response_size'), height: $r('app.float.mouse_turn_page_button_response_size') }) - .onHover((isHover: boolean) => { - this.isButtonHover = isHover + .onHover((isHover?: boolean) => { + if (isHover != null) { + this.isButtonHover = isHover + } this.handleIconColor() }) } diff --git a/feature/browser/src/main/ets/default/view/photo/MouseTurnPageOperation.ets b/feature/browser/src/main/ets/default/view/photo/MouseTurnPageOperation.ets index acc205a6..0a487866 100644 --- a/feature/browser/src/main/ets/default/view/photo/MouseTurnPageOperation.ets +++ b/feature/browser/src/main/ets/default/view/photo/MouseTurnPageOperation.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { Constants, Log, ScreenManager } from '@ohos/common'; +import { Constants, Log, PhotoDataSource, ScreenManager } from '@ohos/common'; import { MouseTurnPageButton } from './MouseTurnPageButton'; const TAG: string = 'browser_MouseTurnPageOperation'; @@ -23,11 +23,11 @@ export struct MouseTurnPageOperation { @State isOnLeftHover: boolean = false @State isOnRightHover: boolean = false @State isOnFirstHover: boolean = false - isShowBar: boolean + isShowBar: boolean = false @Consume('transitionIndex') currentIndex: number - @Prop isPhotoScaled: boolean - private controller - private dataSource + @Prop isPhotoScaled: boolean = false + private controller: SwiperController | null = null; + private dataSource: PhotoDataSource | null = null; aboutToAppear(): void { this.isOnFirstHover = true @@ -46,7 +46,7 @@ export struct MouseTurnPageOperation { bottom: $r('app.float.mouse_turn_page_button_margin') }) .hitTestBehavior(HitTestMode.Transparent) - .onMouse((event: MouseEvent) => { + .onMouse((event?: MouseEvent) => { if (this.isOnFirstHover) { this.isOnFirstHover = false this.isOnLeftHover = true @@ -68,8 +68,10 @@ export struct MouseTurnPageOperation { Column() .width('100%') .height('100%') - .onHover((isHover: boolean) => { - this.isOnLeftHover = isHover + .onHover((isHover?: boolean) => { + if (isHover != null) { + this.isOnLeftHover = isHover + } }) } .hitTestBehavior(HitTestMode.Transparent) @@ -84,12 +86,16 @@ export struct MouseTurnPageOperation { MouseTurnPageButton({ isStart: true }) .key('LeftMouseTurnPageButton') .onClick(() => { - this.controller.showPrevious(); + if (this.controller != null) { + this.controller.showPrevious(); + } }) } } - .onHover((isHover: boolean) => { - this.isOnLeftHover = isHover + .onHover((isHover?: boolean) => { + if (isHover != null) { + this.isOnLeftHover = isHover + } }) .width($r('app.float.mouse_turn_page_button_response_size')) .height($r('app.float.mouse_turn_page_button_response_size')) @@ -106,8 +112,10 @@ export struct MouseTurnPageOperation { Column() .width('100%') .height('100%') - .onHover((isHover: boolean) => { - this.isOnRightHover = isHover + .onHover((isHover?: boolean) => { + if (isHover != null) { + this.isOnRightHover = isHover + } }) } .hitTestBehavior(HitTestMode.Transparent) @@ -117,17 +125,21 @@ export struct MouseTurnPageOperation { }) Column() { - if (this.isOnRightHover && + if (this.isOnRightHover && this.dataSource != null && this.currentIndex < this.dataSource.totalCount() - Constants.NUMBER_1) { MouseTurnPageButton({ isStart: false }) .key('RightMouseTurnPageButton') .onClick(() => { - this.controller.showNext(); + if (this.controller != null) { + this.controller.showNext(); + } }) } } - .onHover((isHover: boolean) => { - this.isOnRightHover = isHover + .onHover((isHover?: boolean) => { + if (isHover != null) { + this.isOnRightHover = isHover + } }) .width($r('app.float.mouse_turn_page_button_response_size')) .height($r('app.float.mouse_turn_page_button_response_size')) diff --git a/feature/browser/src/main/ets/default/view/photo/PhotoBrowserActionBar.ets b/feature/browser/src/main/ets/default/view/photo/PhotoBrowserActionBar.ets index b3e6dd0c..d27f1250 100644 --- a/feature/browser/src/main/ets/default/view/photo/PhotoBrowserActionBar.ets +++ b/feature/browser/src/main/ets/default/view/photo/PhotoBrowserActionBar.ets @@ -37,7 +37,7 @@ export struct PhotoBrowserActionBar { @StorageLink('isSplitMode') isSplitMode: boolean = ScreenManager.getInstance().isSplitMode(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; isVideoPage: boolean = false; @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); diff --git a/feature/browser/src/main/ets/default/view/photo/PhotoBrowserToolBar.ets b/feature/browser/src/main/ets/default/view/photo/PhotoBrowserToolBar.ets index 015a012e..748b1dbd 100644 --- a/feature/browser/src/main/ets/default/view/photo/PhotoBrowserToolBar.ets +++ b/feature/browser/src/main/ets/default/view/photo/PhotoBrowserToolBar.ets @@ -27,7 +27,7 @@ export struct PhotoBrowserToolBar { @State opacityValue: number = 1; @State isVisibility: boolean = true; @State currentBackgroundColor: Resource = $r('app.color.default_background_color'); - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @StorageLink('isSplitMode') isSplitMode: boolean = ScreenManager.getInstance().isSplitMode(); @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @StorageLink('leftBlank') leftBlank: number[] diff --git a/feature/browser/src/main/ets/default/view/photo/TipPopup.ets b/feature/browser/src/main/ets/default/view/photo/TipPopup.ets index 46051691..f4a36940 100644 --- a/feature/browser/src/main/ets/default/view/photo/TipPopup.ets +++ b/feature/browser/src/main/ets/default/view/photo/TipPopup.ets @@ -18,18 +18,27 @@ import { BroadCast, BrowserConstants as PhotoConstants } from '@ohos/common'; export struct TipPopup { @State isShowPop: boolean = false; @Consume broadCast: BroadCast; + private popAppearFunc: Function = (): void => this.popAppear(); + private popDisappearFunc: Function = (): void => this.popDisappear(); + + private popAppear(): void { + this.isShowPop = true; + } + + private popDisappear(): void { + this.isShowPop = false; + } aboutToAppear() { - this.broadCast.on(PhotoConstants.POP_APPEAR, () => { - this.isShowPop = true; - }); - this.broadCast.on(PhotoConstants.POP_DISAPPEAR, () => { - this.isShowPop = false; - }); + this.broadCast.on(PhotoConstants.POP_APPEAR, this.popAppearFunc); + this.broadCast.on(PhotoConstants.POP_DISAPPEAR, this.popDisappearFunc); } aboutToDisappear(): void { - this.broadCast.off(null, null); + if (this.broadCast) { + this.broadCast.off(PhotoConstants.POP_APPEAR, this.popAppearFunc); + this.broadCast.off(PhotoConstants.POP_DISAPPEAR, this.popDisappearFunc); + } } build() { diff --git a/feature/browser/src/main/ets/default/view/photoGrid/BatchRecoverMenuOperation.ets b/feature/browser/src/main/ets/default/view/photoGrid/BatchRecoverMenuOperation.ets index 93d319a6..ca972199 100644 --- a/feature/browser/src/main/ets/default/view/photoGrid/BatchRecoverMenuOperation.ets +++ b/feature/browser/src/main/ets/default/view/photoGrid/BatchRecoverMenuOperation.ets @@ -23,14 +23,17 @@ import { SelectManager, UserFileManagerAccess } from '@ohos/common'; +import { BusinessError } from '@ohos.base'; const TAG: string = 'browser_BatchRecoverMenuOperation'; export class BatchRecoverMenuOperation extends ProcessMenuOperation { + private callbackFunc?: Function; + constructor(menuContext: MenuContext) { super(menuContext); //初始化绑定this指向 - this.callback = this.callback.bind(this) + this.callbackFunc = (uris: string[]): void => this.callback(uris); } doAction(): void { @@ -87,7 +90,7 @@ export class BatchRecoverMenuOperation extends ProcessMenuOperation { fileAssets.push(fileItem); operationImpl.recoverFromTrash(fileAssets).then(() => { this.onCompleted() - }).catch((error) => { + }).catch((error: BusinessError) => { Log.error(TAG, `recover error: ${error}`); this.onError(); }) diff --git a/feature/browser/src/main/ets/default/view/photoGrid/ClearRecycleMenuOperation.ets b/feature/browser/src/main/ets/default/view/photoGrid/ClearRecycleMenuOperation.ets index 865cfeee..f8d986c0 100644 --- a/feature/browser/src/main/ets/default/view/photoGrid/ClearRecycleMenuOperation.ets +++ b/feature/browser/src/main/ets/default/view/photoGrid/ClearRecycleMenuOperation.ets @@ -46,12 +46,9 @@ export class ClearRecycleMenuOperation extends BatchDeleteMenuOperation { return; } - this.confirmCallback = this.confirmCallback.bind(this); - this.cancelCallback = this.cancelCallback.bind(this); - AppStorage.SetOrCreate(Constants.CONFIRM_TEXT_KEY, $r('app.string.dialog_clear')); this.menuContext.broadCast.emit(BroadCastConstants.SHOW_DELETE_DIALOG, - [$r('app.string.recycleAlbum_clear_message'), this.confirmCallback, this.cancelCallback]); + [$r('app.string.recycleAlbum_clear_message'), (): void => this.confirmCallback(), (): void => this.cancelCallback()]); } cancelCallback(): void { diff --git a/feature/browser/src/main/ets/default/view/photoGrid/PhotoGridPageActionBar.ets b/feature/browser/src/main/ets/default/view/photoGrid/PhotoGridPageActionBar.ets index d55e6dde..6b2981ae 100644 --- a/feature/browser/src/main/ets/default/view/photoGrid/PhotoGridPageActionBar.ets +++ b/feature/browser/src/main/ets/default/view/photoGrid/PhotoGridPageActionBar.ets @@ -37,12 +37,12 @@ export struct PhotoGridPageActionBar { @Provide selectedCount: number = 0; @Link @Watch('updateActionBarProp') totalSelectedCount: number; @Consume isEmpty: boolean; - title: string; - albumInfo: AlbumInfo; - isSystemAlbum: boolean; - isRecycle: boolean; - onMenuClicked: Function; - isDistributedAlbum: boolean; + title: string = ''; + albumInfo: AlbumInfo | null = null; + isSystemAlbum: boolean = true; + isRecycle: boolean = false; + onMenuClicked: Function = (): void => {}; + isDistributedAlbum: boolean = false; @State actionBarProp: ActionBarProp = new ActionBarProp(); @StorageLink('statusBarHeight') statusBarHeight: number = 0; @@ -141,10 +141,12 @@ export struct PhotoGridPageActionBar { return actionBarProp; } - private getTitle(albumInfo: AlbumInfo): Resource | string { - let res = UiUtil.getDisplayNameResourceByAlbumInfo(albumInfo); - if (res != null) { - return res; + private getTitle(albumInfo: AlbumInfo | null): Resource | string { + if (albumInfo) { + let res = UiUtil.getDisplayNameResourceByAlbumInfo(albumInfo); + if (res != null) { + return res; + } } return this.title; } diff --git a/feature/browser/src/main/ets/default/view/photoGrid/PhotoGridPageToolBar.ets b/feature/browser/src/main/ets/default/view/photoGrid/PhotoGridPageToolBar.ets index c6c48b29..cf1158f6 100644 --- a/feature/browser/src/main/ets/default/view/photoGrid/PhotoGridPageToolBar.ets +++ b/feature/browser/src/main/ets/default/view/photoGrid/PhotoGridPageToolBar.ets @@ -25,9 +25,9 @@ export struct PhotoGridPageToolBar { @Link @Watch('updateToolbar') totalSelectedCount: number; @Provide selectedCount: number = 0; @Consume isEmpty: boolean; - isRecycleAlbum: boolean; - onMenuClicked: Function; - isDistributedAlbum: boolean; + isRecycleAlbum: boolean = false; + onMenuClicked: Function = (): void => {}; + isDistributedAlbum: boolean = false; @Provide toolMenuList: Array = new Array(); @Consume hidePopup: boolean; diff --git a/feature/editor/src/main/ets/default/PhotoEditorManager.ts b/feature/editor/src/main/ets/default/PhotoEditorManager.ts index 5c11b300..dfe839de 100644 --- a/feature/editor/src/main/ets/default/PhotoEditorManager.ts +++ b/feature/editor/src/main/ets/default/PhotoEditorManager.ts @@ -40,10 +40,10 @@ export class PhotoEditorManager { } static getInstance(): PhotoEditorManager { - if (AppStorage.Get(Constants.PHOTO_EDITOR_MANAGER) == null) { + if (AppStorage.get(Constants.PHOTO_EDITOR_MANAGER) == null) { AppStorage.SetOrCreate(Constants.PHOTO_EDITOR_MANAGER, new PhotoEditorManager()); } - return AppStorage.Get(Constants.PHOTO_EDITOR_MANAGER); + return AppStorage.get(Constants.PHOTO_EDITOR_MANAGER); } initialize(item: MediaItem, albumUri: string, mode: PhotoEditMode, errCallback?: Function): void { diff --git a/feature/editor/src/main/ets/default/view/ActionButton.ets b/feature/editor/src/main/ets/default/view/ActionButton.ets index bf845868..57b6c782 100644 --- a/feature/editor/src/main/ets/default/view/ActionButton.ets +++ b/feature/editor/src/main/ets/default/view/ActionButton.ets @@ -18,7 +18,7 @@ import { BroadCast, Constants } from '@ohos/common'; @Component export struct ActionButton { src: Resource = $r('app.media.alt_placeholder'); - text: Resource = undefined; + text: Resource | null = null; textSize: number | Resource = $r('app.float.buttonActionTextSize_default'); isActive: boolean = false; actionID: number = Constants.NEGATIVE_1; @@ -27,7 +27,7 @@ export struct ActionButton { widthOfActionButton: number | Resource = $r('app.float.actionButton_default'); isCropStyleButton: boolean = false; @Consume broadCast: BroadCast; - componentKey: string; + componentKey: string = ''; aboutToAppear() { if (this.text == undefined) { diff --git a/feature/editor/src/main/ets/default/view/CropImageShow.ets b/feature/editor/src/main/ets/default/view/CropImageShow.ets index 1977a7f7..7f26ab56 100644 --- a/feature/editor/src/main/ets/default/view/CropImageShow.ets +++ b/feature/editor/src/main/ets/default/view/CropImageShow.ets @@ -34,6 +34,7 @@ export struct CropImageShow { private stateMenuSize: number = ScreenManager.getInstance().getStatusBarHeight(); private preTouch: number = Constants.NUMBER_0; private prePinch: number = Constants.NUMBER_0; + private onCropResetClickedFunc: Function = (): void => this.onCropResetClicked() onCropResetClicked(): void { Log.debug(TAG, 'crop reset is clicked'); @@ -93,8 +94,8 @@ export struct CropImageShow { aboutToAppear(): void { Log.debug(TAG, 'Photo CropImageShow called'); - this.onCropResetClicked = this.onCropResetClicked.bind(this); - this.broadCast.on(Constants.CROP_RESET_CLICKED, this.onCropResetClicked); + + this.broadCast.on(Constants.CROP_RESET_CLICKED, this.onCropResetClickedFunc); this.adjustLayout(); } @@ -106,7 +107,7 @@ export struct CropImageShow { aboutToDisappear(): void { this.cropEdit.setCanvasReady(false); - this.broadCast.off(Constants.CROP_RESET_CLICKED, this.onCropResetClicked); + this.broadCast.off(Constants.CROP_RESET_CLICKED, this.onCropResetClickedFunc); } build() { @@ -121,18 +122,18 @@ export struct CropImageShow { this.cropEdit.setCanvasReady(true); }) } - .onTouch((event) => { - this.onTouchStart(event); + .onTouch((event?: TouchEvent) => { + this.onTouchStart(event as TouchEvent); }) .gesture( PinchGesture() - .onActionStart((event: GestureEvent) => { - this.onPinchGestureStart(event); + .onActionStart((event?: GestureEvent) => { + this.onPinchGestureStart(event as GestureEvent); }) - .onActionUpdate((event: GestureEvent) => { - this.onPinchGestureUpdate(event); + .onActionUpdate((event?: GestureEvent) => { + this.onPinchGestureUpdate(event as GestureEvent); }) - .onActionEnd(() => { + .onActionEnd((): void => { this.onPinchGestureEnd(); }) ) diff --git a/feature/editor/src/main/ets/default/view/CropModeBar.ets b/feature/editor/src/main/ets/default/view/CropModeBar.ets index 6bab63d1..3320f248 100644 --- a/feature/editor/src/main/ets/default/view/CropModeBar.ets +++ b/feature/editor/src/main/ets/default/view/CropModeBar.ets @@ -26,6 +26,10 @@ const TAG: string = 'editor_CropModeBar'; const COMPONENT_KEY_ROTATE: string = 'Rotate'; const COMPONENT_KEY_MIRROR: string = 'Mirror'; +interface RulerProperties { + rulerWidth: number; + rulerHeight: number; +} @Component export struct CropModeBar { @@ -39,18 +43,15 @@ export struct CropModeBar { @Consume screenHeight: number; @State rulerSwitchOn: boolean = true; @State frameStyleSwitchOn: boolean = true; - @StorageLink('rulerProperties') rulerProperties: { - rulerWidth: number, - rulerHeight: number - } = { rulerWidth: 0, rulerHeight: 0 } - private rulerChanged: Function = undefined; - private resetClicked: Function = undefined; + @StorageLink('rulerProperties') rulerProperties: RulerProperties = { rulerWidth: 0, rulerHeight: 0 }; + private rulerChanged: Function = (): void => {}; + private resetClicked: Function = (): void => {}; private cropRulerBarHeight: number = Constants.VERTICAL_RULER_COMPONENT_HEIGHT; aboutToAppear(): void { - this.rulerChanged = this.onRulerChanged.bind(this); - this.broadCast.on(Constants.RULER_CHANGED, this.rulerChanged); - this.resetClicked = this.onResetClicked.bind(this); + this.rulerChanged = (number: number): void => this.onRulerChanged(number); + this.broadCast.on(Constants.RULER_CHANGED, (): void => this.rulerChanged()); + this.resetClicked = (): void => this.onResetClicked(); this.broadCast.on(Constants.CROP_RESET_CLICKED, this.resetClicked); } diff --git a/feature/editor/src/main/ets/default/view/CropRulerBar.ets b/feature/editor/src/main/ets/default/view/CropRulerBar.ets index 5431a9ae..12e5506a 100644 --- a/feature/editor/src/main/ets/default/view/CropRulerBar.ets +++ b/feature/editor/src/main/ets/default/view/CropRulerBar.ets @@ -17,6 +17,11 @@ import { BroadCast, Constants, Log, ScreenManager } from '@ohos/common'; const TAG: string = 'editor_CropRulerBar'; +interface RulerProperties { + rulerWidth: number; + rulerHeight: number; +} + @Component export struct CropRulerBar { @Consume broadCast: BroadCast; @@ -32,17 +37,14 @@ export struct CropRulerBar { private startPos: number = Constants.NUMBER_0; private setting: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.setting); - private resetClicked: Function = undefined; + private resetClicked: Function = (): void => {}; private previous: number = Constants.NUMBER_0; - setRulerProperties(rulerWidth: number, rulerHeight: number) { - AppStorage.SetOrCreate<{ - rulerWidth: number, - rulerHeight: number - }>('rulerProperties', { + setRulerProperties(rulerWidth: number, rulerHeight: number): void { + AppStorage.SetOrCreate('rulerProperties', { rulerWidth: rulerWidth, rulerHeight: rulerHeight - }) + } as RulerProperties) } iniSize(): void { @@ -89,9 +91,9 @@ export struct CropRulerBar { drawIntegerLine(cur_x: number, cur_num: number): void { if (!this.isVerticalScreen) { - this.context.moveTo((this.rulerWidth * Constants.NUMBER_8_5) / Constants.NUMBER_15, cur_x); + this.context.moveTo((this.rulerWidth * 8.5) / 15, cur_x); } else { - this.context.moveTo(cur_x, (this.rulerWidth * Constants.NUMBER_8_5) / Constants.NUMBER_15); + this.context.moveTo(cur_x, (this.rulerWidth * 8.5) / 15); } if (Math.abs(cur_num) > Constants.EDGE_ANGLE) { @@ -104,26 +106,26 @@ export struct CropRulerBar { this.context.shadowBlur = Constants.RULER_LINE_WIDTH if (Math.round(cur_num) == Math.round(this.current_def)) { if (!this.isVerticalScreen) { - this.context.fillText(this.integerAngleToString(Math.round(cur_num)), - (this.rulerWidth * Constants.NUMBER_6) / Constants.NUMBER_15, cur_x); + this.context.fillText(this.integerAngleToString(Math.round(cur_num)) as string, + (this.rulerWidth * 6) / 15, cur_x); } else { - this.context.fillText(this.integerAngleToString(Math.round(cur_num)), cur_x, - (this.rulerWidth * Constants.NUMBER_6) / Constants.NUMBER_15); + this.context.fillText(this.integerAngleToString(Math.round(cur_num)) as string, cur_x, + (this.rulerWidth * 6) / 15); } } else { if (!this.isVerticalScreen) { this.context.fillText((-cur_num).toString(), - (this.rulerWidth * Constants.NUMBER_6) / Constants.NUMBER_15, cur_x); + (this.rulerWidth * 6) / 15, cur_x); } else { this.context.fillText(cur_num.toString(), cur_x, - (this.rulerWidth * Constants.NUMBER_6) / Constants.NUMBER_15); + (this.rulerWidth * 6) / 15); } } if (!this.isVerticalScreen) { - this.context.lineTo(this.rulerWidth * Constants.NUMBER_10_5 / Constants.NUMBER_15, cur_x); + this.context.lineTo(this.rulerWidth * 10.5 / 15, cur_x); } else { - this.context.lineTo(cur_x, this.rulerWidth * Constants.NUMBER_10_5 / Constants.NUMBER_15); + this.context.lineTo(cur_x, this.rulerWidth * 10.5 / 15); } } @@ -175,36 +177,30 @@ export struct CropRulerBar { } onTouchEvent(event: TouchEvent): void { - if (event.type == TouchType.Down) { - if (this.isVerticalScreen) { - this.startPos = (event.touches[0].x); - } else { - this.startPos = (event.touches[0].y); - } + let axis = this.isVerticalScreen ? 'x' : 'y'; + if (event.type === TouchType.Down) { + this.startPos = event.touches[0][axis]; this.previous = new Date().getTime(); } - - if (event.type == TouchType.Move) { - let now = new Date().getTime(); - if (now - this.previous >= Constants.TIMEOUT) { - this.previous = now; - } else { - return; - } - - let dir = this.isVerticalScreen ? this.startPos - (event.touches[0].x) : - this.startPos - (event.touches[0].y); - if (Math.abs(dir / Constants.NUMBER_5) >= Constants.NUMBER_1) { - this.current_def += parseInt((dir / Constants.NUMBER_5).toFixed(0)); - this.startPos = this.isVerticalScreen ? (event.touches[0].x) : (event.touches[0].y); - if (Math.abs(this.current_def) > Constants.EDGE_ANGLE) { - this.current_def = this.current_def > Constants.EDGE_ANGLE ? - Constants.EDGE_ANGLE : -Constants.EDGE_ANGLE; - } - this.drawRuler(); - this.broadCast.emit(Constants.RULER_CHANGED, [this.current_def]); - } + if (event.type !== TouchType.Move) { + return; } + let now = new Date().getTime(); + if (now - this.previous < Constants.TIMEOUT) { + return; + } + this.previous = now; + let dir = this.startPos - event.touches[0][axis]; + if (Math.abs(dir / 5) < 1) { + return; + } + this.current_def += Number.parseInt((dir / 5).toFixed(0)); + this.startPos = event.touches[0][axis]; + if (Math.abs(this.current_def) > Constants.EDGE_ANGLE) { + this.current_def = this.current_def > Constants.EDGE_ANGLE ? Constants.EDGE_ANGLE : -Constants.EDGE_ANGLE; + } + this.drawRuler(); + this.broadCast.emit(Constants.RULER_CHANGED, [this.current_def]); } onResetClicked(): void { @@ -212,33 +208,16 @@ export struct CropRulerBar { this.drawRuler(); } - integerAngleToString(currentAngle: number): string { - switch (currentAngle) { - case -Constants.NUMBER_40: - return Constants.NEGATIVE_FORTY; - case -Constants.NUMBER_30: - return Constants.NEGATIVE_THIRTY; - case -Constants.NUMBER_20: - return Constants.NEGATIVE_TWENTY; - case -Constants.NUMBER_10: - return Constants.NEGATIVE_TEN; - case Constants.NUMBER_0: - return Constants.ZERO_STR; - case Constants.NUMBER_10: - return Constants.POSITIVE_TEN; - case Constants.NUMBER_20: - return Constants.POSITIVE_TWENTY; - case Constants.NUMBER_30: - return Constants.POSITIVE_THIRTY; - case Constants.NUMBER_40: - return Constants.POSITIVE_FORTY; - default: - break; + integerAngleToString(currentAngle: number): string | undefined{ + if (currentAngle % 10 === 0 && Math.abs(currentAngle) <= 40) { + return currentAngle.toString(); } + + return undefined; } aboutToAppear(): void { - this.resetClicked = this.onResetClicked.bind(this); + this.resetClicked = (): void => this.onResetClicked(); this.broadCast.on(Constants.CROP_RESET_CLICKED, this.resetClicked); this.iniSize(); } @@ -265,8 +244,8 @@ export struct CropRulerBar { this.drawRuler(); }) } - .onTouch((event) => { - this.onTouchEvent(event); + .onTouch((event?: TouchEvent) => { + this.onTouchEvent(event as TouchEvent); }) .width(this.isVerticalScreen ? this.rulerLength : Constants.CROP_RULER_WIDTH) .height(this.isVerticalScreen ? this.rulerWidth : this.rulerLength) diff --git a/feature/editor/src/main/ets/default/view/CropStyleBar.ets b/feature/editor/src/main/ets/default/view/CropStyleBar.ets index 070234b8..ec54df4c 100644 --- a/feature/editor/src/main/ets/default/view/CropStyleBar.ets +++ b/feature/editor/src/main/ets/default/view/CropStyleBar.ets @@ -34,6 +34,10 @@ const COMPONENT_KEY_EDIT_CROP_16_9: string = 'EditCrop_16_9'; const COMPONENT_KEY_EDIT_CROP_PORT_FULL: string = 'PortFull'; const COMPONENT_KEY_EDIT_CROP_LAND_FULL: string = 'LandFull'; +interface Msg { + type: string +} + @Component export struct CropStyleBar { @Consume broadCast: BroadCast; @@ -95,8 +99,8 @@ export struct CropStyleBar { }), ]; @State @Watch('clickEvent') menuChanged: RefreshActionMenu = new RefreshActionMenu(-1, this.mainMenuList); - private menuClick: Function = undefined; - private resetClick: Function = undefined; + private menuClick: Function = (): void => {}; + private resetClick: Function = (): void => {}; clickEvent(): void { ActionChangedEvent.isActiveNotChanged(this.menuChanged); @@ -127,7 +131,7 @@ export struct CropStyleBar { let id = -1; for (let i = 0; i < this.menuChanged.menuArray.length; i++) { if (this.menuChanged.menuArray[i].isActive) { - id = this.menuChanged.menuArray[i].actionID; + id = this.menuChanged.menuArray[i].actionID as number; } } @@ -158,8 +162,8 @@ export struct CropStyleBar { this.cropEdit.onRotationAngleChange(); this.isCropReset = this.cropEdit.couldReset(); - let msg = { - 'Type': BigDataConstants.PHOTO_EDIT_ROTATE + let msg: Msg = { + type: BigDataConstants.PHOTO_EDIT_ROTATE }; ReportToBigDataUtil.report(BigDataConstants.PHOTO_EDIT_TYPE_ID, msg); } @@ -167,8 +171,8 @@ export struct CropStyleBar { onMirrorClicked(): void { this.cropEdit.onMirrorChange(); this.isCropReset = this.cropEdit.couldReset(); - let msg = { - 'Type': BigDataConstants.PHOTO_EDIT_MIRROR + let msg: Msg = { + type: BigDataConstants.PHOTO_EDIT_MIRROR }; ReportToBigDataUtil.report(BigDataConstants.PHOTO_EDIT_TYPE_ID, msg); } @@ -176,15 +180,15 @@ export struct CropStyleBar { onResetClicked(): void { this.menuChanged.isChanged = 0; this.isCropReset = this.cropEdit.couldReset(); - let msg = { - 'Type': BigDataConstants.PHOTO_EDIT_RESET + let msg: Msg = { + type: BigDataConstants.PHOTO_EDIT_RESET }; ReportToBigDataUtil.report(BigDataConstants.PHOTO_EDIT_TYPE_ID, msg); } aboutToAppear(): void { - this.menuClick = this.onMenuClicked.bind(this); - this.resetClick = this.onResetClicked.bind(this); + this.menuClick = (actionID: number | CropRatioType): void => this.onMenuClicked(actionID); + this.resetClick = (): void => this.onResetClicked(); this.broadCast.on(Constants.UPDATE_MENU, this.menuClick); this.broadCast.on(Constants.CROP_RESET_CLICKED, this.resetClick); } diff --git a/feature/editor/src/main/ets/default/view/MainMenuInfo.ets b/feature/editor/src/main/ets/default/view/MainMenuInfo.ets index adab0b93..48f59857 100644 --- a/feature/editor/src/main/ets/default/view/MainMenuInfo.ets +++ b/feature/editor/src/main/ets/default/view/MainMenuInfo.ets @@ -22,10 +22,10 @@ export enum ID { DEFAULT } -interface ActionInfo { +export interface ActionInfo { src ?: Resource; isActive ?: boolean; - actionID: number | PhotoEditMode; + actionID?: number | PhotoEditMode; text ?: Resource; mode ?: number; height ?: Resource; @@ -36,23 +36,23 @@ interface ActionInfo { } export class ActionButtonInfo { - src: Resource; + src?: Resource; isActive: boolean; isDoubleClicked: boolean; - actionID: number; - text: Resource; - mode: number; - height: Resource; - width: Resource - color: Resource - uri: string; + actionID?: number; + text: Resource | null = null; + mode: number = 0; + height: Resource | null = null; + width: Resource | null = null; + color: Resource | null = null; + uri: string = ''; componentKey: string; constructor(action: ActionInfo) { this.src = action.src == undefined ? undefined : action.src; - this.actionID = action.actionID; + this.actionID = action.actionID as number; this.isDoubleClicked = false; - this.componentKey = action.componentKey; + this.componentKey = action.componentKey as string; if (action.isActive != undefined) { this.isActive = action.isActive; } else { diff --git a/feature/editor/src/main/ets/default/view/PcCropModeBar.ets b/feature/editor/src/main/ets/default/view/PcCropModeBar.ets index 697639c0..51df210d 100644 --- a/feature/editor/src/main/ets/default/view/PcCropModeBar.ets +++ b/feature/editor/src/main/ets/default/view/PcCropModeBar.ets @@ -39,13 +39,13 @@ export struct PcCropModeBar { @State rulerSwitchOn: boolean = true; @State frameStyleSwitchOn: boolean = true; private rulerComponentSize: number = 0; - private rulerChanged: Function = undefined; - private resetClicked: Function = undefined; + private rulerChanged: Function = (): void => {}; + private resetClicked: Function = (): void => {}; aboutToAppear() { - this.rulerChanged = this.onRulerChanged.bind(this); + this.rulerChanged = (number: number): void => this.onRulerChanged(number); this.broadCast.on(Constants.RULER_CHANGED, this.rulerChanged); - this.resetClicked = this.onResetClicked.bind(this); + this.resetClicked = (): void => this.onResetClicked(); this.broadCast.on(Constants.CROP_RESET_CLICKED, this.resetClicked); this.rulerComponentSize = this.screenWidth; Log.debug(TAG, `this.rulerComponentSize = ${this.rulerComponentSize}`); @@ -171,8 +171,8 @@ export struct PcCropModeBar { } .width('100%') .margin({ bottom: $r('app.float.crop_vertical_padding_right') }) - .onClick(() => { - this.switchFrameStyle() + .onClick((): void => { + this.switchFrameStyle(); }) // 剪切风格bar diff --git a/feature/editor/src/main/ets/default/view/PcCropRulerBar.ets b/feature/editor/src/main/ets/default/view/PcCropRulerBar.ets index c3f02806..959f97c3 100644 --- a/feature/editor/src/main/ets/default/view/PcCropRulerBar.ets +++ b/feature/editor/src/main/ets/default/view/PcCropRulerBar.ets @@ -29,7 +29,7 @@ export struct PcCropRulerBar { private startPos: number = 0; private setting: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.setting); - private resetClicked: Function = undefined; + private resetClicked: Function = (): void => {}; private previous: number = 0; private rulerLength: number = 0 private rulerWidth: number = 0 @@ -154,38 +154,31 @@ export struct PcCropRulerBar { } } - onTouchEvent(event: TouchEvent) { - if (event.type == TouchType.Down) { - if (this.isVerticalScreen) { - this.startPos = (event.touches[0].x); - } else { - this.startPos = (event.touches[0].y); - } + onTouchEvent(event: TouchEvent): void { + let axis = this.isVerticalScreen ? 'x' : 'y'; + if (event.type === TouchType.Down) { + this.startPos = event.touches[0][axis]; this.previous = new Date().getTime(); } - - if (event.type == TouchType.Move) { - let now = new Date().getTime(); - if (now - this.previous >= Constants.TIMEOUT) { - this.previous = now; - } else { - return; - } - - let dir = this.isVerticalScreen ? this.startPos - (event.touches[0].x) : - this.startPos - (event.touches[0].y); - if (Math.abs(dir / Constants.NUMBER_5) >= Constants.NUMBER_1) { - this.current_def += parseInt((dir / Constants.NUMBER_5).toFixed(0)); - this.startPos = this.isVerticalScreen ? (event.touches[0].x) : (event.touches[0].y) - if (Math.abs(this.current_def) > Constants.EDGE_ANGLE) { - this.current_def = this.current_def > Constants.EDGE_ANGLE ? - Constants.EDGE_ANGLE : -Constants.EDGE_ANGLE; - } - - this.drawRuler(); - this.broadCast.emit(Constants.RULER_CHANGED, [this.current_def]); - } + if (event.type !== TouchType.Move) { + return; } + let now = new Date().getTime(); + if (now - this.previous < Constants.TIMEOUT) { + return; + } + this.previous = now; + let dir = this.startPos - event.touches[0][axis]; + if (Math.abs(dir / 5) < 1) { + return; + } + this.current_def += Number.parseInt((dir / 5).toFixed(0)); + this.startPos = event.touches[0][axis]; + if (Math.abs(this.current_def) > Constants.EDGE_ANGLE) { + this.current_def = this.current_def > Constants.EDGE_ANGLE ? Constants.EDGE_ANGLE : -Constants.EDGE_ANGLE; + } + this.drawRuler(); + this.broadCast.emit(Constants.RULER_CHANGED, [this.current_def]); } onResetClicked() { @@ -193,33 +186,16 @@ export struct PcCropRulerBar { this.drawRuler(); } - integerAngleToString(currentAngle: number): string { - switch (currentAngle) { - case -Constants.NUMBER_40: - return Constants.NEGATIVE_FORTY; - case -Constants.NUMBER_30: - return Constants.NEGATIVE_THIRTY; - case -Constants.NUMBER_20: - return Constants.NEGATIVE_TWENTY; - case -Constants.NUMBER_10: - return Constants.NEGATIVE_TEN; - case Constants.NUMBER_0: - return Constants.ZERO_STR; - case Constants.NUMBER_10: - return Constants.POSITIVE_TEN; - case Constants.NUMBER_20: - return Constants.POSITIVE_TWENTY; - case Constants.NUMBER_30: - return Constants.POSITIVE_THIRTY; - case Constants.NUMBER_40: - return Constants.POSITIVE_FORTY; - default: - break; + integerAngleToString(currentAngle: number): string | undefined { + if (currentAngle % 10 === 0 && Math.abs(currentAngle) <= 40) { + return currentAngle.toString(); } + + return undefined; } aboutToAppear() { - this.resetClicked = this.onResetClicked.bind(this); + this.resetClicked = (): void => this.onResetClicked(); this.broadCast.on(Constants.CROP_RESET_CLICKED, this.resetClicked); this.iniSize() } @@ -247,8 +223,8 @@ export struct PcCropRulerBar { this.drawRuler() }) } - .onTouch((event) => { - this.onTouchEvent(event); + .onTouch((event?: TouchEvent) => { + this.onTouchEvent(event as TouchEvent); }) .backgroundColor('#33000000') .borderRadius($r('app.float.edit_menu_item_radius')) diff --git a/feature/editor/src/main/ets/default/view/PcCropStyleBar.ets b/feature/editor/src/main/ets/default/view/PcCropStyleBar.ets index e92e9880..947a60d2 100644 --- a/feature/editor/src/main/ets/default/view/PcCropStyleBar.ets +++ b/feature/editor/src/main/ets/default/view/PcCropStyleBar.ets @@ -98,8 +98,8 @@ export struct PcCropStyleBar { }), ]; @State @Watch('clickEvent') menuChanged: RefreshActionMenu = new RefreshActionMenu(-1, this.mainMenuList); - private menuClick: Function = undefined; - private resetClick: Function = undefined; + private menuClick: Function = (): void => {}; + private resetClick: Function = (): void => {}; clickEvent() { ActionChangedEvent.isActiveNotChanged(this.menuChanged); @@ -126,11 +126,11 @@ export struct PcCropStyleBar { } } - onRotateClicked() { + onRotateClicked(): void { let id = -1; for (let i = 0; i < this.menuChanged.menuArray.length; i++) { if (this.menuChanged.menuArray[i].isActive) { - id = this.menuChanged.menuArray[i].actionID; + id = this.menuChanged.menuArray[i].actionID as number; } } @@ -173,8 +173,8 @@ export struct PcCropStyleBar { } aboutToAppear() { - this.menuClick = this.onMenuClicked.bind(this); - this.resetClick = this.onResetClicked.bind(this); + this.menuClick = (actionID: number | CropRatioType): void => this.onMenuClicked(actionID); + this.resetClick = (): void => this.onResetClicked(); this.broadCast.on(Constants.UPDATE_MENU, this.menuClick); this.broadCast.on(Constants.CROP_RESET_CLICKED, this.resetClick); } diff --git a/feature/editor/src/main/ets/default/view/TitleBar.ets b/feature/editor/src/main/ets/default/view/TitleBar.ets index cff5b0ba..85317385 100644 --- a/feature/editor/src/main/ets/default/view/TitleBar.ets +++ b/feature/editor/src/main/ets/default/view/TitleBar.ets @@ -22,11 +22,13 @@ import { Constants, Log, ReportToBigDataUtil, - UiUtil + UiUtil, + WindowUtil } from '@ohos/common'; import { PhotoEditorManager } from '../PhotoEditorManager'; import { PhotoEditCrop } from '../crop/PhotoEditCrop'; import router from '@ohos.router'; +import { Router } from '@ohos.arkui.UIContext'; const TAG: string = 'editor_TitleBar'; @@ -34,7 +36,7 @@ const TAG: string = 'editor_TitleBar'; export struct TitleBar { @Consume isRedo: boolean; @Consume isUndo: boolean; - @State name: Resource = undefined; + @State name: Resource | undefined = undefined; @State isPcStyle: boolean = true; @Consume('selected') selectedMode: number; @Consume broadCast: BroadCast; @@ -44,25 +46,31 @@ export struct TitleBar { @Consume cropEdit: PhotoEditCrop; private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); private newImageId: number = -1; - private immersiveClick: Function = undefined; - private onBackAfterSaveComplete: Function = undefined; + private immersiveClick: Function = (): void => {}; + private onBackAfterSaveComplete: Function = (): void => {}; saveAsNewCallback() { Log.debug(TAG, 'saveAsNewCallback called'); - let msg = { - 'SAVE_TYPE': BigDataConstants.SAVE_AS_NEW + interface Msg { + saveType: string; + } + let msg: Msg = { + saveType: BigDataConstants.SAVE_AS_NEW } ReportToBigDataUtil.report(BigDataConstants.PHOTO_EDIT_SAVE_ID, msg); - PhotoEditorManager.getInstance().save(false, this.saveImageCallback.bind(this)); + PhotoEditorManager.getInstance().save(false, (uri: string): void => this.saveImageCallback(uri)); } - replaceOriginalCallback() { + replaceOriginalCallback(): void { Log.debug(TAG, 'replaceOriginalCallback called'); - let msg = { - 'SAVE_TYPE': BigDataConstants.SAVE_REPLACE + interface Msg { + saveType: string; + } + let msg: Msg = { + saveType: BigDataConstants.SAVE_REPLACE } ReportToBigDataUtil.report(BigDataConstants.PHOTO_EDIT_SAVE_ID, msg); - PhotoEditorManager.getInstance().save(true, this.saveImageCallback.bind(this)); + PhotoEditorManager.getInstance().save(true, (uri: string): void => this.saveImageCallback(uri)); } discardCallback() { @@ -90,9 +98,9 @@ export struct TitleBar { } aboutToAppear() { - this.immersiveClick = this.immersive.bind(this); + this.immersiveClick = (isImmersive: boolean): void => this.immersive(isImmersive); this.broadCast.on(Constants.IS_IMMERSIVE, this.immersiveClick); - this.onBackAfterSaveComplete = this.backAfterSaveComplete.bind(this); + this.onBackAfterSaveComplete = (): void => this.backAfterSaveComplete(); this.appBroadCast.on(BroadCastConstants.PHOTO_EDIT_SAVE_COMPLETE, this.onBackAfterSaveComplete); } @@ -105,27 +113,33 @@ export struct TitleBar { this.isImmersive = isImmersive; } - onBackClicked() { + onBackClicked(): void { Log.debug(TAG, 'back clicked'); if (this.isRedo || this.isUndo) { - this.broadCast.emit(BroadCastConstants.SHOW_EDIT_EXIT_PHOTO_DIALOG, [this.discardCallback.bind(this)]); + this.broadCast.emit(BroadCastConstants.SHOW_EDIT_EXIT_PHOTO_DIALOG, [(): void => this.discardCallback()]); } else if (this.selectedMode == PhotoEditMode.EDIT_MODE_CROP && this.cropEdit.couldReset()) { - this.broadCast.emit(BroadCastConstants.SHOW_EDIT_EXIT_PHOTO_DIALOG, [this.discardCallback.bind(this)]); + this.broadCast.emit(BroadCastConstants.SHOW_EDIT_EXIT_PHOTO_DIALOG, [(): void => this.discardCallback()]); } else { - router.back(); + router.back({ + url: '', + params: {} + }); } } - onSaveClicked() { + onSaveClicked(): void { Log.info(TAG, 'save clicked'); if (this.isRedo || this.isRedo) { this.broadCast.emit(BroadCastConstants.SHOW_SAVE_PHOTO_DIALOG, - [this.saveAsNewCallback.bind(this), this.replaceOriginalCallback.bind(this)]); + [(): void => this.saveAsNewCallback(), (): void => this.replaceOriginalCallback()]); } else if (this.selectedMode == PhotoEditMode.EDIT_MODE_CROP && this.cropEdit.couldReset()) { this.broadCast.emit(BroadCastConstants.SHOW_SAVE_PHOTO_DIALOG, - [this.saveAsNewCallback.bind(this), this.replaceOriginalCallback.bind(this)]); + [(): void => this.saveAsNewCallback(), (): void => this.replaceOriginalCallback()]); } else { - router.back(); + router.back({ + url: '', + params: {} + }); } } diff --git a/feature/editor/src/main/ets/default/view/ToolBar.ets b/feature/editor/src/main/ets/default/view/ToolBar.ets index 8fcbdc1d..2bf72261 100644 --- a/feature/editor/src/main/ets/default/view/ToolBar.ets +++ b/feature/editor/src/main/ets/default/view/ToolBar.ets @@ -15,7 +15,7 @@ import { ActionButton } from './ActionButton'; import { BroadCast, Constants, Log } from '@ohos/common'; -import { ActionButtonInfo } from './MainMenuInfo'; +import { ActionButtonInfo, ActionInfo } from './MainMenuInfo'; import { ActionChangedEvent, RefreshActionMenu } from './RefreshMenu'; import { PhotoEditMode } from '../base/PhotoEditType'; import { PhotoEditorManager } from '../PhotoEditorManager'; @@ -40,22 +40,22 @@ export struct ToolBar { @Consume titleSize: number; @Consume isRedo: boolean; @Consume isUndo: boolean; + private actionInfo: ActionInfo = { + src: $r('app.media.ic_edit_photo_toolbar_crop'), + // 加入其它按钮时改为PhotoEditMode.EDIT_MODE_CROP + actionID: PhotoEditMode.EDIT_MODE_CROP, + text: $r('app.string.crop_text'), + isActive: true, + componentKey: COMPONENT_KEY_Edit_CROP + }; mainMenuList: Array = [ - new ActionButtonInfo({ - src: $r('app.media.ic_edit_photo_toolbar_crop'), - - // 加入其它按钮时改为PhotoEditMode.EDIT_MODE_CROP - actionID: undefined, - text: $r('app.string.crop_text'), - isActive: true, - componentKey: COMPONENT_KEY_Edit_CROP - }) + new ActionButtonInfo(this.actionInfo) ]; // 2022年8月11日 @Watch('clickEvent')打包报错 @State @Watch('clickEvent') menuChanged: RefreshActionMenu = new RefreshActionMenu(-1, this.mainMenuList); @State menuChanged: RefreshActionMenu = new RefreshActionMenu(-1, this.mainMenuList); private textSize: number | Resource = $r('app.float.buttonActionTextSize_default'); - private menuClick: Function = undefined; - private immersiveClick: Function = undefined; + private menuClick: Function = (): void => {}; + private immersiveClick: Function = (): void => {}; clickEvent() { ActionChangedEvent.isActiveNotChanged(this.menuChanged); @@ -96,8 +96,8 @@ export struct ToolBar { } aboutToAppear() { - this.menuClick = this.onMenuClick.bind(this); - this.immersiveClick = this.immersive.bind(this); + this.menuClick = (actionID: number): void => this.onMenuClick(actionID); + this.immersiveClick = (isImmersive: boolean): void => this.immersive(isImmersive); this.broadCast.on(Constants.UPDATE_MENU, this.menuClick); this.broadCast.on(Constants.IS_IMMERSIVE, this.immersiveClick); diff --git a/feature/formAbility/src/main/ets/default/controller/FormController.ts b/feature/formAbility/src/main/ets/default/controller/FormController.ts index 114ad1a0..9ce316a2 100644 --- a/feature/formAbility/src/main/ets/default/controller/FormController.ts +++ b/feature/formAbility/src/main/ets/default/controller/FormController.ts @@ -19,6 +19,7 @@ import formBindingData from '@ohos.application.formBindingData'; import { Constants } from '../common/Constants'; import formProvider from '@ohos.application.formProvider'; import type Want from '@ohos.app.ability.Want'; +import common from '@ohos.app.ability.common'; const TAG: string = 'formA_The_FormController'; @@ -59,18 +60,18 @@ export class FormController implements FormListener { Log.info(TAG, `bindFormData start formId: ${formId} fd:${fd}`); let image: string = this.imageHashCode(fd, formId); let dataObj: object = { - 'fd': fd === -1 ? false : true, - 'image0': 'memory://' + image, - 'image1': 'memory://' + image, - 'indexValue': this.indexValue, - 'albumName': this.mediaDataManager.getCurrentAlbumName(), - 'currentIndex': this.mediaDataManager.getCurrentIndex(), - 'isShow': this.mediaDataManager.getIsShowAlbumName(), - 'formImages': JSON.parse(`{ "${image}": ${fd} }`), - 'uri': (this.mediaDataManager.getMediaData().currentUri !== '') ? - commonConstants.ACTION_URI_FORM_ABILITY : commonConstants.ACTION_URI_FORM_ABILITY_NONE, - 'albumUri': `${this.mediaDataManager.getMediaData().albumUri}`, - 'currentUri': this.mediaDataManager.getMediaData().currentUri + fd: fd !== -1, + image0: 'memory://' + image, + image1: 'memory://' + image, + indexValue: this.indexValue, + albumName: this.mediaDataManager.getCurrentAlbumName(), + currentIndex: this.mediaDataManager.getCurrentIndex(), + isShow: this.mediaDataManager.getIsShowAlbumName(), + formImages: JSON.parse(`{ "${image}": ${fd} }`), + uri: this.mediaDataManager.getMediaData().currentUri !== + '' ? commonConstants.ACTION_URI_FORM_ABILITY : commonConstants.ACTION_URI_FORM_ABILITY_NONE, + albumUri: `${this.mediaDataManager.getMediaData().albumUri}`, + currentUri: this.mediaDataManager.getMediaData().currentUri }; Log.debug(TAG, `bindFormData, createFormBindingData dataObj2.data: ${JSON.stringify(dataObj)}`); let obj: formBindingData.FormBindingData = formBindingData.createFormBindingData(JSON.stringify(dataObj)); @@ -135,7 +136,8 @@ export class FormController implements FormListener { }; Log.debug(TAG, `routerPhotoBrowser parm ${JSON.stringify(param)}`); - globalThis.formContext.startAbility(param).then(() => { + let context: common.UIAbilityContext = AppStorage.get('formContext'); + context.startAbility(param).then((): void => { AppStorage.Delete(Constants.FROM_CONTROLLER_MANAGER); }) diff --git a/feature/formAbility/src/main/ets/default/data/MediaDataManager.ts b/feature/formAbility/src/main/ets/default/data/MediaDataManager.ts index 3e8fccf2..faa58adb 100644 --- a/feature/formAbility/src/main/ets/default/data/MediaDataManager.ts +++ b/feature/formAbility/src/main/ets/default/data/MediaDataManager.ts @@ -19,6 +19,7 @@ import { AlbumDefine, DataStoreUtil, Log, MediaConstants, UserFileManagerAccess, import resourceManager from '@ohos.resourceManager'; import type { FormListener } from '../controller/FormController'; import userFileManager from '@ohos.filemanagement.userFileManager'; +import common from '@ohos.app.ability.common'; const TAG: string = 'formA_MediaDataManager'; @@ -45,7 +46,8 @@ export class MediaDataManager { await this.initShowName(); if (this.mediaData == null || this.mediaData == undefined) { Log.info(TAG, `initData new MediaData! form ${formId}`); - let mgr: resourceManager.ResourceManager = globalThis.formContext.resourceManager; + let context = AppStorage.get('formContext'); + let mgr: resourceManager.ResourceManager = context.resourceManager as resourceManager.ResourceManager; let displayName = await mgr.getStringValue($r('app.string.album_photos').id); let albumUri = this.mediaModel.getSystemAlbumUri(UserFileManagerAccess.IMAGE_ALBUM_SUB_TYPE); this.mediaData = new MediaData(formId, displayName, displayName, albumUri, '', 0, diff --git a/feature/thirdselect/src/main/ets/default/utils/ThirdSelectConstants.ts b/feature/thirdselect/src/main/ets/default/utils/ThirdSelectConstants.ts index 73b179e5..ecf0509e 100644 --- a/feature/thirdselect/src/main/ets/default/utils/ThirdSelectConstants.ts +++ b/feature/thirdselect/src/main/ets/default/utils/ThirdSelectConstants.ts @@ -38,8 +38,19 @@ export class SelectParams { isMultiPick: boolean; /* caller bundle name */ bundleName: string; + /* whether picker from Camera */ + cameraAble: boolean; + /* whether picker can edit */ + editAble: boolean; + uri: string; + itemDisplayName: unknown; + itemId: string; + isFirstEnter: boolean; + itemCount: number; + itemCoverUri: string; + remainingOfWallpapers: number; - static defaultParam() { + static defaultParam(): SelectParams { return { maxSelectCount: Constants.DEFAULT_MAX_THIRD_SELECT_COUNT, filterMediaType: AlbumDefine.FILTER_MEDIA_TYPE_ALL, @@ -47,11 +58,19 @@ export class SelectParams { isFromFa: false, isFromFaPhoto: false, isMultiPick: false, - bundleName: '' - } + bundleName: '', + cameraAble: true, + editAble: true, + uri: '', + itemDisplayName: undefined, + itemId: '', + isFirstEnter: false, + itemCount: 0, + itemCoverUri: '', + remainingOfWallpapers: 0 + }; } } - /* storage key begin */ export const THIRD_SELECT_IS_ORIGIN = 'third_select_is_origin'; diff --git a/feature/thirdselect/src/main/ets/default/view/CameraGridItemComponent.ets b/feature/thirdselect/src/main/ets/default/view/CameraGridItemComponent.ets index 9e47f5a8..34bf8bb5 100644 --- a/feature/thirdselect/src/main/ets/default/view/CameraGridItemComponent.ets +++ b/feature/thirdselect/src/main/ets/default/view/CameraGridItemComponent.ets @@ -16,6 +16,9 @@ import { AlbumDefine, BigDataConstants, Constants, Log, ReportToBigDataUtil } from '@ohos/common'; import wantConstant from '@ohos.ability.wantConstant'; import { SelectParams } from '../utils/ThirdSelectConstants'; +import ability from '@ohos.ability.ability'; +import common from '@ohos.app.ability.common'; +import Want from '@ohos.app.ability.Want'; const TAG: string = 'thiSel_CameraGridItemComponent'; @@ -24,7 +27,7 @@ export struct CameraGridItemComponent { selectParams: SelectParams = SelectParams.defaultParam(); resultUri: string = ''; @Consume @Watch('onShow') isShow: boolean; - updateDataFunc: Function; + updateDataFunc: Function = (): void => {}; aboutToAppear(): void { Log.info(TAG, `aboutToAppear`); @@ -64,11 +67,19 @@ export struct CameraGridItemComponent { .key('PickerCamera') .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center) - .onClick((event: ClickEvent) => { + .onClick((event?: ClickEvent) => { this.jumpCameraTakePhoto().then((result) => { Log.info(TAG, `resourceUri = ${JSON.stringify(result)}`); - this.resultUri = result?.want?.parameters?.resourceUri; - }).catch((err) => { + let want: Want | null = result.want as Want; + if(want == null || want.parameters == null) return; + this.resultUri = want.parameters['resourceUri'] as string; + + if (this.resultUri?.length > 0) { + + this.isShow = true; + this.onShow(); + } + }).catch((err: Error) => { Log.error(TAG, `jumpCameraTakephoto err: ${err}`); }); }) @@ -88,20 +99,26 @@ export struct CameraGridItemComponent { } } - private async jumpCameraTakePhoto(): Promise { + private async jumpCameraTakePhoto(): Promise { let action = this.selectParams.filterMediaType == AlbumDefine.FILTER_MEDIA_TYPE_VIDEO ? wantConstant.Action.ACTION_VIDEO_CAPTURE : wantConstant.Action.ACTION_IMAGE_CAPTURE; let uri = this.selectParams.filterMediaType == AlbumDefine.FILTER_MEDIA_TYPE_VIDEO ? Constants.CAMERA_TYPE_VIDEO : Constants.CAMERA_TYPE_CAPTURE; - ReportToBigDataUtil.report(BigDataConstants.SELECT_PICKER_CLICK_CAMERA_ID, { 'action': action }); + interface Msg { + action: wantConstant.Action + } + let msg: Msg = { + action: action + } + ReportToBigDataUtil.report(BigDataConstants.SELECT_PICKER_CLICK_CAMERA_ID, msg); let supportMultiMode: boolean = (this.selectParams.filterMediaType == AlbumDefine.FILTER_MEDIA_TYPE_ALL); - let want = { - 'action': action, - 'bundleName': Constants.CAMERA_BUNDLE_NAME, - 'parameters': { + let want: Want = { + action: action, + bundleName: Constants.CAMERA_BUNDLE_NAME, + parameters: { uri: uri, supportMultiMode: supportMultiMode, callBundleName: this.selectParams.bundleName @@ -109,7 +126,8 @@ export struct CameraGridItemComponent { }; Log.debug(TAG, `jump camera want: ${JSON.stringify(want)}`); - let result = await globalThis.photosAbilityContext.startAbilityForResult(want); + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + let result = await context.startAbilityForResult(want); return result; } @@ -118,16 +136,17 @@ export struct CameraGridItemComponent { Log.error(TAG, `no valid uri!`); return; } - let abilityResult = { - 'resultCode': 0, - 'want': { - 'parameters': { + let abilityResult: ability.AbilityResult = { + resultCode: (uri == null || uri.length <= 0) ? -1 : 0, + want: { + parameters: { 'select-item-list': [uri], } } }; - globalThis.photosAbilityContext.terminateSelfWithResult(abilityResult).then((result) => { - Log.info(TAG, `terminateSelf result: ${result}`); + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelfWithResult(abilityResult as ability.AbilityResult).then((result: void) => { + Log.info(TAG, `terminateSelfWithResult abilityResult: ${abilityResult} result: ${result}`); }); } } diff --git a/feature/thirdselect/src/main/ets/default/view/ThirdAlbumGridItem.ets b/feature/thirdselect/src/main/ets/default/view/ThirdAlbumGridItem.ets index b03909b7..048cfb10 100644 --- a/feature/thirdselect/src/main/ets/default/view/ThirdAlbumGridItem.ets +++ b/feature/thirdselect/src/main/ets/default/view/ThirdAlbumGridItem.ets @@ -24,10 +24,10 @@ import { ScreenManager, UiUtil } from '@ohos/common'; -import router from '@ohos.router'; import { SelectParams } from '../utils/ThirdSelectConstants'; import { EmptyAlbumComponent } from '@ohos/browser/BrowserComponents'; -import Router from '@system.router'; +import { Router } from '@ohos.arkui.UIContext'; +import router from '@ohos.router'; const TAG: string = 'thiSel_ThirdAlbumGridItem'; @@ -44,7 +44,7 @@ export struct ThirdAlbumGridItem { MASK_LAYER_HEIGHT = '50%'; @State transformV: number = 0; @State isEmptyAlbum: boolean = false; - isFirstEnter: boolean; + isFirstEnter: boolean = false; @Consume selectParams: SelectParams; private staticIconList = new Map([ [AlbumDefine.ALBUM_ID_VIDEO, $r('app.media.ic_video')], @@ -52,7 +52,7 @@ export struct ThirdAlbumGridItem { ]); private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); private fp2vpUnit: number = px2vp(fp2px(Constants.NUMBER_1)); - onWindowSizeChangeCallBack = () => this.updateCardSize(); + private onWindowSizeChangeCallBack: Function = (): void => this.updateCardSize(); aboutToAppear(): void { Log.info(TAG, `aboutToAppear + ${this.item.coverUri}, select param ${JSON.stringify(this.selectParams)}`) @@ -66,7 +66,6 @@ export struct ThirdAlbumGridItem { aboutToDisappear(): void { Log.info(TAG, 'aboutToDisappear'); ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; } updateCardSize() { @@ -169,15 +168,16 @@ export struct ThirdAlbumGridItem { .border({ radius: $r('sys.float.ohos_id_corner_radius_default_m') }) - .onClick(this.handleClick.bind(this)) + .onClick((): void => this.handleClick()) + } - private handleClick() { + private handleClick(): void { if (this.selectParams.isFromFa && (!this.selectParams.isFromFaPhoto)) { this.appBroadCast.emit(BroadCastConstants.SAVE_FORM_EDITOR_DATA, [this.item.albumName, this.item.uri, this.item.albumName, '', true]); } else { - let params: any = this.selectParams; + let params: SelectParams = this.selectParams; params.isFirstEnter = false; params.itemDisplayName = this.item.albumName; params.itemCount = this.item.count; @@ -186,7 +186,7 @@ export struct ThirdAlbumGridItem { router.pushUrl({ url: 'pages/ThirdSelectPhotoGridPage', params: params - }, router.RouterMode.Single); + }); } } } \ No newline at end of file diff --git a/feature/thirdselect/src/main/ets/default/view/ThirdSelectAlbumPageBase.ets b/feature/thirdselect/src/main/ets/default/view/ThirdSelectAlbumPageBase.ets index 185b7c21..e94c162e 100644 --- a/feature/thirdselect/src/main/ets/default/view/ThirdSelectAlbumPageBase.ets +++ b/feature/thirdselect/src/main/ets/default/view/ThirdSelectAlbumPageBase.ets @@ -39,16 +39,29 @@ import { IS_SIDE_BAR, IS_SPLIT_MODE, LEFT_BLANK, SelectParams } from '../utils/T const TAG: string = 'thiSel_ThirdSelectAlbumPageBase'; +interface Params { + bundleName: string; + isMultiPick: boolean; + isFromFa: boolean; + isFromFaPhoto: boolean; + filterMediaType?: string; + isFirstEnter: boolean; + isFromWallpaper: boolean; + remainingOfWallpapers: number; + maxSelectCount: number; +}; + // Third Select AlbumSet Page @Component export struct ThirdSelectAlbumPageBase { @State isEmpty: boolean = false; - albums: AlbumSetDataSource; + @State totalSelectedCount: number = 0; @Provide broadCast: BroadCast = new BroadCast(); + private albums: AlbumSetDataSource = new AlbumSetDataSource(this.broadCast); @Provide isSelectedMode: boolean = true; @Provide moreMenuList: Array = new Array(); - selectManager: ThirdSelectManager; + selectManager?: ThirdSelectManager; @Provide gridColumnsCount: number = 3; isActive = false; @StorageLink(IS_SPLIT_MODE) isSplitMode: boolean = ScreenManager.getInstance().isSplitMode(); @@ -57,15 +70,26 @@ export struct ThirdSelectAlbumPageBase { @StorageLink(IS_SIDE_BAR) isSidebar: boolean = ScreenManager.getInstance().isSidebar(); dataObserver: CommonObserverCallback = new CommonObserverCallback(this); @State title: string = ''; - isFirstEnter: boolean; - @Prop @Watch('onPageChanged') pageStatus: boolean; + isFirstEnter: boolean = false; + @Prop @Watch('onPageChanged') pageStatus: boolean = false; @Provide selectParams: SelectParams = SelectParams.defaultParam(); scroller: Scroller = new Scroller(); private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); + private initGridRowCountFunc: Function = (): void => this.initGridRowCount(); + private onLoadingFinishedFunc: Function = (size: number): void => this.onLoadingFinished(size); + + private onLoadingFinished(size: number): void { + Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); + if (size === 1 && this.albums?.mediaSetList[0].albumName === AlbumDefine.ALBUM_ID_RECYCLE) { + this.isEmpty = true; + } else { + this.isEmpty = size == 0; + } + } aboutToAppear(): void { this.albums = new AlbumSetDataSource(this.broadCast); - let param: any = router.getParams(); + let param: Params = router.getParams() as Params; this.initSelectParams(param); if (this.selectParams.isFromFa) { this.selectParams.filterMediaType = AlbumDefine.FILTER_MEDIA_TYPE_IMAGE; @@ -77,17 +101,9 @@ export struct ThirdSelectAlbumPageBase { userFile.getSystemAlbumUri(UserFileManagerAccess.FAVORITE_ALBUM_SUB_TYPE)]); } this.albums.setFilterMediaType(this.selectParams.filterMediaType); - this.selectManager = AppStorage.Get(Constants.THIRD_SELECT_MANAGER); - this.onMenuClicked = this.onMenuClicked.bind(this); + this.selectManager = AppStorage.get(Constants.THIRD_SELECT_MANAGER) as ThirdSelectManager; Log.debug(TAG, `select params ${JSON.stringify(this.selectParams)}`); - this.broadCast.on(Constants.ON_LOADING_FINISHED, (size: number) => { - Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); - if (size === 1 && this.albums.mediaSetList[0].albumName === AlbumDefine.ALBUM_ID_RECYCLE) { - this.isEmpty = true; - } else { - this.isEmpty = size == 0; - } - }); + this.broadCast.on(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); if (this.selectParams.isMultiPick) { this.selectManager.registerCallback('thirdSelectUpdateCount', (newState: number) => { Log.info(TAG, `thirdSelectUpdateCount ${newState}`); @@ -95,11 +111,10 @@ export struct ThirdSelectAlbumPageBase { }); } MediaObserver.getInstance().registerObserver(this.dataObserver); - this.initGridRowCount = this.initGridRowCount.bind(this); this.initGridRowCount(); // 后续phone缩略图支持横竖屏后再放开 - if (AppStorage.Get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { - ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.initGridRowCount); + if (AppStorage.get('deviceType') as string !== Constants.DEFAULT_DEVICE_TYPE) { + ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.initGridRowCountFunc); } let titleRes = ActionBarProp.SINGLE_TAB_ALBUM_TITLE; UiUtil.getResourceString(titleRes).then((stringResource) => { @@ -123,16 +138,17 @@ export struct ThirdSelectAlbumPageBase { } aboutToDisappear() { - this.broadCast.off(null, null); - ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.initGridRowCount); - this.initGridRowCount = null; + if(this.broadCast) { + this.broadCast.off(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); + } + ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.initGridRowCountFunc); MediaObserver.getInstance().unregisterObserver(this.dataObserver); this.dataObserver.clearSource(); } - onMediaLibDataChange(changeType) { + onMediaLibDataChange(changeType: string): void { Log.info(TAG, `onMediaLibDataChange type: ${changeType}`); - this.albums.onChange(changeType); + this.albums?.onChange(changeType); } onPageHide() { @@ -158,16 +174,12 @@ export struct ThirdSelectAlbumPageBase { onMenuClicked(action: Action) { Log.info(TAG, `onMenuClicked, action: ${action.actionID}`); - switch (action.actionID) { - case Action.BACK.actionID: - router.back(); - break; - default: - break; + if (action.actionID === Action.BACK.actionID) { + router.back(); } } - @Builder buildItem(item) { + @Builder buildItem(item: AlbumSetDataInfo) { ThirdAlbumGridItem({ item: item.data, isFirstEnter: this.isFirstEnter @@ -184,7 +196,7 @@ export struct ThirdSelectAlbumPageBase { leftAction: Action.BACK, isSelectPhotoGrid: false, title: $title, - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), totalSelectedCount: $totalSelectedCount }) Stack() { @@ -198,9 +210,7 @@ export struct ThirdSelectAlbumPageBase { this.buildItem(item) } } - }, (item: AlbumSetDataInfo, index: number) => { - return item.data.getHashCode() + index; - }) + }, (item: AlbumSetDataInfo) => 'uri:' + item.data.uri) } .edgeEffect(EdgeEffect.Spring) .scrollBar(BarState.Auto) @@ -222,7 +232,7 @@ export struct ThirdSelectAlbumPageBase { }) } - private initSelectParams(param) { + private initSelectParams(param: Params | null): void { if (param != null) { this.selectParams.bundleName = param.bundleName; this.selectParams.isMultiPick = param.isMultiPick; diff --git a/feature/thirdselect/src/main/ets/default/view/ThirdSelectPhotoBrowserBase.ets b/feature/thirdselect/src/main/ets/default/view/ThirdSelectPhotoBrowserBase.ets index add7df61..261557da 100644 --- a/feature/thirdselect/src/main/ets/default/view/ThirdSelectPhotoBrowserBase.ets +++ b/feature/thirdselect/src/main/ets/default/view/ThirdSelectPhotoBrowserBase.ets @@ -14,6 +14,7 @@ */ import router from '@ohos.router'; +import Matrix4 from '@ohos.matrix4'; import { Action, BigDataConstants, @@ -23,6 +24,7 @@ import { BrowserConstants, Constants, Log, + MediaDataSource, MediaItem, mMultimodalInputManager, PhotoDataSource, @@ -41,9 +43,23 @@ import { import { FormConstants, IS_HORIZONTAL } from '../utils/ThirdSelectConstants'; import { ThirdSelectedPanel } from './ThirdSelectedPanel'; import { MouseTurnPageOperation } from '@ohos/browser/BrowserComponents'; +import { Matrix4x4 } from '@ohos/common/src/main/ets/default/utils/Matrix4x4' +import ability from '@ohos.ability.ability'; +import common from '@ohos.app.ability.common'; +import { Results } from '@ohos/common/src/main/ets/default/view/PhotoSwiper'; const TAG: string = 'thiSel_ThirdSelectPhotoBrowserBase'; +interface Params { + isFromFa: boolean; + selectMode: boolean; + position: number; + transition: string; + bundleName: string; + title: string; + maxSelectCount: number; +}; + // third selection photoBrowser @Component export struct ThirdSelectPhotoBrowserBase { @@ -55,21 +71,21 @@ export struct ThirdSelectPhotoBrowserBase { @Provide isDefaultBackgroundColor: boolean = true; @State isPhotoScaled: boolean = false; @Provide pageFrom: number = Constants.ENTRY_FROM.NORMAL; - selectManager: ThirdSelectManager; + selectManager: ThirdSelectManager | null = null; bundleName: string = ''; isMultiPick = true; - mTransition: string; + mTransition: string = ''; controller: SwiperController = new SwiperController(); @Provide('transitionIndex') currentIndex: number = 0; @State currentUri: string = ''; isFromFa: boolean = false; @Provide canSwipe: boolean = true; // position - mPosition: number; + mPosition: number = 0; @State title: string = ''; - @Prop @Watch('onPageChanged') pageStatus: boolean; + @Prop @Watch('onPageChanged') pageStatus: boolean = false; @StorageLink(IS_HORIZONTAL) isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); - maxSelectCount: number; + maxSelectCount: number = 0; @StorageLink('geometryOpacity') geometryOpacity: number = 1; @State @Watch('onGeometryChanged') geometryTransitionId: string = 'default_id'; @Link isRunningAnimation: boolean; @@ -79,7 +95,14 @@ export struct ThirdSelectPhotoBrowserBase { private dataSource: ThirdBrowserDataSource = new ThirdBrowserDataSource(); private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); private geometryTransitionEnable: boolean = false; - private isSelectMode: boolean; + private isSelectMode: boolean = false; + private pullDownFunc: Function = (): Boolean => this.onBackPress(); + private dataSizeChangedFunc: Function = (size: number): void => this.onDataSizeChanged(size); + private selectFunc: Function = (position: number, key: string, value: boolean): void => this.selectCallback(position, key, value); + private dataContentChangedFunc: Function = (index: number): void => this.onPhotoChanged(index); + private jumpThirdPhotoBrowserFunc: Function = (name: string, item: MediaItem, isSelectMode = false): void => + this.jumpBrowserCallback(name, item, isSelectMode); + private setDisableSwipeFunc: Function = (value: boolean): void => this.setDisableSwipe(value); onGeometryChanged() { AppStorage.SetOrCreate('geometryTransitionBrowserId', this.geometryTransitionId); @@ -89,8 +112,8 @@ export struct ThirdSelectPhotoBrowserBase { Log.info(TAG, 'photoBrowser aboutToAppear'); this.backgroundColorResource = $r('app.color.black'); this.isDefaultBackgroundColor = false; - this.geometryTransitionId = AppStorage.Get('geometryTransitionBrowserId'); - this.browserController.browserBackFunc = this.onBackPress.bind(this); + this.geometryTransitionId = AppStorage.get('geometryTransitionBrowserId') as string; + this.browserController.browserBackFunc = (): boolean => this.onBackPress(); mMultimodalInputManager.registerListener((control: number) => { Log.info(TAG, `key control : ${control} index ${this.currentIndex}`); if (control == 0) { @@ -105,16 +128,16 @@ export struct ThirdSelectPhotoBrowserBase { this.onBackPress(); } }); - this.selectManager = AppStorage.Get(Constants.THIRD_SELECT_MANAGER); - this.dataSource.setAlbumDataSource(AppStorage.Get(Constants.APP_KEY_PHOTO_BROWSER)); + this.selectManager = AppStorage.get(Constants.THIRD_SELECT_MANAGER) as ThirdSelectManager; + this.dataSource.setAlbumDataSource(AppStorage.get(Constants.APP_KEY_PHOTO_BROWSER) as MediaDataSource); this.isMultiPick = this.selectManager.getIsMultiPick(); - if (this.isMultiPick == true) { - this.totalSelectedCount = this.selectManager.getSelectedCount(); + if (this.isMultiPick) { + this.totalSelectedCount = this.selectManager?.getSelectedCount() ?? 0; } else { - this.totalSelectedCount = Constants.NUMBER_1; + this.totalSelectedCount = 1; } - let param: any = this.browserController.browserParam; + let param: Params = this.browserController.browserParam as Params; this.isFromFa = param.isFromFa; this.isSelectMode = param.selectMode; if (param.selectMode) { @@ -125,19 +148,16 @@ export struct ThirdSelectPhotoBrowserBase { this.bundleName = param.bundleName; this.title = param.title; this.maxSelectCount = param.maxSelectCount; - this.onMenuClicked = this.onMenuClicked.bind(this); this.dataSource.setBroadCast(this.broadCast); - this.broadCast.on(BrowserConstants.PULL_DOWN_END, this.onBackPress.bind(this)); - this.broadCast.on(BrowserConstants.DATA_SIZE_CHANGED, this.onDataSizeChanged.bind(this)); - this.broadCast.on(BroadCastConstants.SELECT, this.selectCallback.bind(this)); - this.broadCast.on(BrowserConstants.DATA_CONTENT_CHANGED, this.onPhotoChanged.bind(this, this.currentIndex)); - this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpBrowserCallback.bind(this)); - this.broadCast.on(BrowserConstants.SET_DISABLE_SWIPE, (value: boolean) => { - Log.info(TAG, `set swiper swipe ${value}`); - this.canSwipe = value; - }); + this.broadCast.on(BrowserConstants.PULL_DOWN_END, this.pullDownFunc); + this.broadCast.on(BrowserConstants.DATA_SIZE_CHANGED, this.dataSizeChangedFunc); + this.broadCast.on(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.on(BrowserConstants.DATA_CONTENT_CHANGED, this.dataContentChangedFunc); + this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.on(BrowserConstants.SET_DISABLE_SWIPE, this.setDisableSwipeFunc); + if (this.pageStatus) { this.onPageShow(); } @@ -145,9 +165,16 @@ export struct ThirdSelectPhotoBrowserBase { aboutToDisappear(): void { this.broadCast.release(); + if(this.broadCast) { + this.broadCast.off(BrowserConstants.PULL_DOWN_END, this.pullDownFunc); + this.broadCast.off(BrowserConstants.DATA_SIZE_CHANGED, this.dataSizeChangedFunc); + this.broadCast.off(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.off(BrowserConstants.DATA_CONTENT_CHANGED, this.dataContentChangedFunc); + this.broadCast.off(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.off(BrowserConstants.SET_DISABLE_SWIPE, this.setDisableSwipeFunc); + } this.dataSource.release(); mMultimodalInputManager.unregisterListener(); - this.controller = undefined; } onDataSizeChanged(size: number): void { @@ -157,16 +184,21 @@ export struct ThirdSelectPhotoBrowserBase { } } + setDisableSwipe(value: boolean): void { + Log.info(TAG, `set swiper swipe ${value}`); + this.canSwipe = value; + } + onPhotoChanged(index: number): void { this.currentIndex = index; let currentPhoto = this.getCurrentPhoto(); if (currentPhoto == undefined) { Log.error(TAG, 'onPhotoChanged, item is undefined'); } else { - this.isSelected = this.selectManager.isItemSelected(currentPhoto.uri); + this.isSelected = this.selectManager?.isItemSelected(currentPhoto.uri) ?? false; this.currentUri = currentPhoto.uri; - let dataSourceIndex = this.isSelectMode ? this.selectManager.getSelectItemDataSourceIndex(currentPhoto) : index; + let dataSourceIndex = this.isSelectMode ? (this.selectManager?.getSelectItemDataSourceIndex(currentPhoto) ?? Constants.INVALID) : index; let timelineIndex = this.dataSource.getPositionByIndex(dataSourceIndex); AppStorage.SetOrCreate('placeholderIndex', timelineIndex); this.geometryTransitionId = this.browserController.pageFrom + currentPhoto.getHashCode() + this.isSelected; @@ -183,11 +215,11 @@ export struct ThirdSelectPhotoBrowserBase { } this.isSelected = !this.isSelected; if (this.isSelected) { - this.selectManager.toggle(currentPhoto.uri, true); + this.selectManager?.toggle(currentPhoto.uri, true); } else { - this.selectManager.toggle(currentPhoto.uri, false); + this.selectManager?.toggle(currentPhoto.uri, false); } - this.totalSelectedCount = this.selectManager.getSelectedCount(); + this.totalSelectedCount = this.selectManager?.getSelectedCount() ?? 0; this.geometryTransitionId = this.browserController.pageFrom + currentPhoto.getHashCode() + this.isSelected; Log.info(TAG, `totalSelectedCount: ${this.totalSelectedCount} after state change geometryTransitionId ${this.geometryTransitionId}`); } @@ -199,7 +231,7 @@ export struct ThirdSelectPhotoBrowserBase { if (this.selectManager) { this.selectManager.toggle(key, value); } - this.totalSelectedCount = this.selectManager.getSelectedCount(); + this.totalSelectedCount = this.selectManager?.getSelectedCount() ?? 0; Log.info(TAG, `totalSelectedCount: ${this.totalSelectedCount} after select callback`); } @@ -224,28 +256,24 @@ export struct ThirdSelectPhotoBrowserBase { onMenuClicked(action: Action) { Log.info(TAG, `onMenuClicked, action: ${action.actionID}`); - switch (action.actionID) { - case Action.BACK.actionID: - let msg = { - 'From': BigDataConstants.BY_CLICK, - } - ReportToBigDataUtil.report(BigDataConstants.ESC_PHOTO_BROWSER_WAY, msg); - this.onBackPress(); - return; - case Action.MATERIAL_SELECT.actionID: - Log.info(TAG, 'click UN_SELECTED'); - this.selectStateChange(); - return; - case Action.SELECTED.actionID: - Log.info(TAG, 'click SELECTED'); - this.selectStateChange(); - return; - case Action.OK.actionID: - Log.info(TAG, 'click OK'); - this.setPickResult(); - break; - default: - break; + if (action.actionID === Action.BACK.actionID) { + interface Msg { + from: string; + } + let msg: Msg = { + from: BigDataConstants.BY_CLICK, + } + ReportToBigDataUtil.report(BigDataConstants.ESC_PHOTO_BROWSER_WAY, msg); + this.onBackPress(); + } else if (action.actionID === Action.MATERIAL_SELECT.actionID) { + Log.info(TAG, 'click UN_SELECTED'); + this.selectStateChange(); + } else if (action.actionID === Action.SELECTED.actionID) { + Log.info(TAG, 'click SELECTED'); + this.selectStateChange(); + } else if (action.actionID === Action.OK.actionID) { + Log.info(TAG, 'click OK'); + this.setPickResult(); } } @@ -256,7 +284,7 @@ export struct ThirdSelectPhotoBrowserBase { onBackPress() { if (this.geometryTransitionEnable) { - this.controller.finishAnimation(this.onBackPressInner.bind(this)); + this.controller.finishAnimation((): void => this.onBackPressInner()); } else { router.back({ url: '', @@ -294,7 +322,7 @@ export struct ThirdSelectPhotoBrowserBase { @Builder buildPanel() { ThirdSelectedPanel({ maxSelectCount: this.maxSelectCount, - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), isBrowserMode: true, isMultiPick: this.isMultiPick, mTransition: TAG, @@ -320,9 +348,9 @@ export struct ThirdSelectPhotoBrowserBase { PhotoSwiper({ dataSource: this.dataSource, mTransition: this.mTransition, - onPhotoChanged: this.onPhotoChanged.bind(this), + onPhotoChanged: (index: number): void => this.onPhotoChanged(index), swiperController: this.controller, - verifyPhotoScaledFunc: this.verifyPhotoScaled.bind(this), + verifyPhotoScaledFunc: (matrix?: Matrix4.Matrix4Transit): void => this.verifyPhotoScaled(matrix), geometryTransitionEnable: true, broadCast: $broadCast, isRunningAnimation: $isRunningAnimation @@ -343,7 +371,7 @@ export struct ThirdSelectPhotoBrowserBase { } ThirdSelectPhotoBrowserActionBar({ isMultiPick: this.isMultiPick, - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), title: this.title, isThird: true, isShowBar: $isShowBar, @@ -368,21 +396,23 @@ export struct ThirdSelectPhotoBrowserBase { .opacity(0) } - verifyPhotoScaled(matrix: any) { - if (!!matrix) { - let mat = matrix.copy().matrix4x4 - let xScale = mat[Constants.NUMBER_0] - let yScale = mat[Constants.NUMBER_5] - Log.info(TAG, `photo in PhotoItem has Scaled x scale: ${xScale}, y scale: ${yScale}, mat: ${mat}`) - this.isPhotoScaled = xScale != 1 || yScale != 1 + verifyPhotoScaled(matrix?: Matrix4.Matrix4Transit): void { + if (matrix) { + let mat: number[] | undefined = (matrix.copy() as Matrix4x4).matrix4x4; + if (mat) { + let xScale: number = mat[0]; + let yScale: number = mat[5]; + Log.info(TAG, `photo in PhotoItem has Scaled x scale: ${xScale}, y scale: ${yScale}, mat: ${mat}`); + this.isPhotoScaled = xScale != 1 || yScale != 1 + } } else { this.isPhotoScaled = false - Log.info(TAG, `photo in PhotoItem has not Scaled isPhotoScaled: ${this.isPhotoScaled}`) + Log.info(TAG, `photo in PhotoItem has not Scaled isPhotoScaled: ${this.isPhotoScaled}`); } } private onBackPressInner(): void { - this.browserController.hideBrowser(); + let timelineIndex = this.dataSource.getPositionByIndex(this.currentIndex) as number; } private jumpBrowserCallback(name: string, item: MediaItem, isSelectMode = false) { @@ -399,16 +429,20 @@ export struct ThirdSelectPhotoBrowserBase { if (currentPhoto) { Log.debug(TAG, `setPickResult. updateFormData obj: ${currentPhoto.uri} currentIndex: ${this.currentIndex}`); this.appBroadCast.emit(BroadCastConstants.SAVE_FORM_EDITOR_DATA, - ["", AppStorage.Get(FormConstants.FORM_ITEM_ALBUM_URI), AppStorage.Get(FormConstants.FORM_ITEM_DISPLAY_NAME), + ['', AppStorage.get(FormConstants.FORM_ITEM_ALBUM_URI), AppStorage.get(FormConstants.FORM_ITEM_DISPLAY_NAME), currentPhoto.uri, false]); } else { Log.error(TAG, 'Fa setPickResult is null'); } return; } - let uriArray; + let uriArray: Array; if (this.isMultiPick) { - uriArray = SelectUtil.getUriArray(this.selectManager.clickedSet); + if (this.selectManager === null) { + Log.error(TAG, 'Select Manager empty'); + return; + } + uriArray = SelectUtil.getUriArray(this.selectManager?.clickedSet ?? new Set()); Log.info(TAG, `uri size: ${uriArray}`); } else { let currentPhoto = this.getCurrentPhoto(); @@ -418,21 +452,17 @@ export struct ThirdSelectPhotoBrowserBase { uriArray = [currentPhoto.uri]; } let promise: Promise = SelectUtil.grantPermissionForUris(uriArray, this.bundleName); - let abilityResult = { - 'resultCode': 0, - 'want': { - 'parameters': { + let abilityResult: ability.AbilityResult = { + resultCode: 0, + want: { + parameters: { 'select-item-list': uriArray, } } }; - promise.then(function () { - Log.info(TAG, `grant permission success.`); - globalThis.photosAbilityContext.terminateSelfWithResult(abilityResult).then((result) => { - Log.info(TAG, `terminateSelf result: ${result}`); - }); - }).catch(function (err) { - Log.error(TAG, `grant permission error: ${JSON.stringify(err)}`); + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelfWithResult(abilityResult).then((result: void) => { + Log.info(TAG, `terminateSelf result: ${result}, self result ${JSON.stringify(abilityResult)}`); }); } } @@ -452,11 +482,11 @@ class ThirdBrowserDataSource extends PhotoDataSource { return super.totalCount(); } - getData(index: number): any { + getData(index: number): Results { if (this.isSelectMode) { - return this.packData(index, this.selectedItems[index]); + return this.packData(index, this.selectedItems[index]) as Results; } - return super.getData(index); + return super.getData(index) as Results; } setSelectMode(manager: ThirdSelectManager) { diff --git a/feature/thirdselect/src/main/ets/default/view/ThirdSelectPhotoGridBase.ets b/feature/thirdselect/src/main/ets/default/view/ThirdSelectPhotoGridBase.ets index 7bbf3d56..38800ae5 100644 --- a/feature/thirdselect/src/main/ets/default/view/ThirdSelectPhotoGridBase.ets +++ b/feature/thirdselect/src/main/ets/default/view/ThirdSelectPhotoGridBase.ets @@ -53,9 +53,27 @@ import { SelectParams, THIRD_SELECT_IS_ORIGIN } from '../utils/ThirdSelectConstants'; +import ability from '@ohos.ability.ability'; +import { Router } from '@ohos.arkui.UIContext'; +import common from '@ohos.app.ability.common'; const TAG: string = 'thiSel_ThirdSelectPhotoGridBase'; +interface Params { + uri: string; + itemDisplayName: string; + itemId: string; + bundleName: string; + isMultiPick: boolean; + isFromFa: boolean; + isFromFaPhoto: boolean; + filterMediaType?: string; + isFirstEnter: boolean; + isFromWallpaper: boolean; + remainingOfWallpapers: number; + maxSelectCount: number; +}; + // Third Select Album Page @Component export struct ThirdSelectPhotoGridBase { @@ -63,11 +81,11 @@ export struct ThirdSelectPhotoGridBase { @Provide isSelectedMode: boolean = true; @Provide moreMenuList: Array = new Array(); @Provide rightClickMenuList: Array = new Array(); - PhotoDataImpl: PhotoDataImpl; + PhotoDataImpl: PhotoDataImpl | null = null; dataSource: MediaDataSource = new MediaDataSource(Constants.DEFAULT_SLIDING_WIN_SIZE); @Provide broadCast: BroadCast = new BroadCast(); @Provide isShow: boolean = true; - selectManager: ThirdSelectManager; + selectManager: ThirdSelectManager | null = null; isActive = false; @State title: string = ''; @State isEmpty: boolean = false; @@ -82,18 +100,24 @@ export struct ThirdSelectPhotoGridBase { @Provide isShowBar: boolean = true; scroller: Scroller = new Scroller(); isFirstEnter: boolean = false; - @Prop @Watch('onPageChanged') pageStatus: boolean; - backFuncBinder: Function; + @Prop @Watch('onPageChanged') pageStatus: boolean = false; + backFuncBinder: Function | null = null; @State selectParams: SelectParams = SelectParams.defaultParam(); @State screenHeight: number = ScreenManager.getInstance().getWinHeight(); @StorageLink('placeholderIndex') @Watch('onPlaceholderChanged') placeholderIndex: number = -1; @ObjectLink @Watch('onBrowserControllerChanged') browserController: BrowserController; private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); private dataObserver: CommonObserverCallback = new CommonObserverCallback(this); - private selectFromCameraFunc: () => void; - private itemId: string = undefined; + private selectFromCameraFunc: Function = (): void => {}; + private itemId: string = ''; private isItemIdChange: boolean = false; - onWindowSizeChangeCallBack = () => this.initGridRowCount(); + private onWindowSizeChangeCallBack: Function = () => this.initGridRowCount(); + private selectFunc: Function = (position: number, key: string, value: boolean, callback: Function): void => + this.onSelectCallback(position, key, value, callback); + private jumpThirdPhotoBrowserFunc: Function = (name: string, item: MediaItem, geometryTapIndex: number, + geometryTransitionString: string, isSelectMode = false): void => + this.jumpBrowserCallback(name, item, geometryTapIndex, geometryTransitionString, isSelectMode); + private onDataReloadedFunc: Function = (): void => this.onReloadFinishedCallback(); onPlaceholderChanged() { Log.debug(TAG, 'onPlaceholderChanged placeholderIndex is ' + this.placeholderIndex); @@ -110,33 +134,29 @@ export struct ThirdSelectPhotoGridBase { onMenuClicked(action: Action) { Log.info(TAG, `onMenuClicked, action: ${action.actionID}`); - switch (action.actionID) { - case Action.BACK.actionID: - this.goBackFormEditor(); - break; - case Action.CANCEL.actionID: - this.setPickResult(null); - break; - case Action.OK.actionID: - this.setPickResult(SelectUtil.getUriArray(this.selectManager.clickedSet)); - break; - case Action.NAVIGATION_ALBUMS.actionID: - let params: any = this.selectParams; - params.isFirstEnter = false; - let options = { - url: 'pages/ThirdSelectAlbumSetPage', - params: params - } - router.pushUrl(options); - ReportToBigDataUtil.report(BigDataConstants.SELECT_PICKER_SWITCH_ALBUM, null); - break; - default: - break; + if (action.actionID === Action.BACK.actionID) { + this.goBackFormEditor(); + } else if (action.actionID === Action.CANCEL.actionID) { + this.setPickResult(); + } else if (action.actionID === Action.OK.actionID) { + let uriArray: Array = new Array(); + if (this.selectManager !== null) { + uriArray = SelectUtil.getUriArray(this.selectManager.clickedSet); + } + this.setPickResult(uriArray); + } else if (action.actionID === Action.NAVIGATION_ALBUMS.actionID) { + let params = this.selectParams; + params.isFirstEnter = false; + router.pushUrl({ + url: 'pages/ThirdSelectAlbumSetPage', + params: this.selectParams + }) + ReportToBigDataUtil.report(BigDataConstants.SELECT_PICKER_SWITCH_ALBUM, undefined); } } aboutToAppear(): void { - let param: any = router.getParams(); + let param: Params = router.getParams() as Params; this.initSelectParams(param); if (this.selectParams.isFromFa) { this.selectParams.filterMediaType = AlbumDefine.FILTER_MEDIA_TYPE_IMAGE; @@ -145,7 +165,7 @@ export struct ThirdSelectPhotoGridBase { } this.dataSource.setFilterMediaType(this.selectParams.filterMediaType); this.initSelectManager(); - this.selectManager.setIsMultiPick(this.selectParams.isMultiPick); + this.selectManager?.setIsMultiPick(this.selectParams.isMultiPick); let self = this; // 后续phone缩略图支持横竖屏后再放开 @@ -153,26 +173,25 @@ export struct ThirdSelectPhotoGridBase { ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); } this.initGridRowCount(); - this.onMenuClicked = this.onMenuClicked.bind(this); this.dataSource.setBroadCast(this.broadCast); - this.broadCast.on(BroadCastConstants.SELECT, this.onSelectCallback.bind(this)); - this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpBrowserCallback.bind(this)); + this.broadCast.on(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); this.broadCast.on(Constants.ON_LOADING_FINISHED, (size: number) => { - this.onLoadFinishedCallback(size, this.updateTitle.bind(this, param)); + this.onLoadFinishedCallback(size, (param: Params): void => this.updateTitle(param)); }); - this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, this.onReloadFinishedCallback.bind(this)); - this.selectManager.registerCallback('updateCount', + this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadedFunc); + this.selectManager?.registerCallback('updateCount', (newState: number) => { Log.info(TAG, `updateSelectedCount ${newState}`); self.selectedCount = newState; - self.selectManager.emitCallback('thirdSelectUpdateCount', [newState]); + self.selectManager?.emitCallback('thirdSelectUpdateCount', [newState]); }); this.dataSource.registerCallback('updateCount', (newState: number) => { Log.info(TAG, `updateTotalCount ${newState}`); self.isShowScrollBar = (newState > Constants.PHOTOS_CNT_FOR_HIDE_SCROLL_BAR); - self.selectManager.setTotalCount(newState); + self.selectManager?.setTotalCount(newState); }); MediaObserver.getInstance().registerObserver(this.dataObserver); this.isActive = true; @@ -186,8 +205,8 @@ export struct ThirdSelectPhotoGridBase { onPageShow() { Log.debug(TAG, 'onPageShow'); - let param: any = router.getParams(); - this.isItemIdChange = this.itemId && param && this.itemId !== param.itemId; + let param: Params = router.getParams() as Params; + this.isItemIdChange = (this.itemId && param && this.itemId !== param.itemId) as boolean; if (this.isItemIdChange) { this.initSelectParams(param); } @@ -217,21 +236,29 @@ export struct ThirdSelectPhotoGridBase { aboutToDisappear(): void { ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; MediaObserver.getInstance().unregisterObserver(this.dataObserver); this.dataObserver.clearSource(); - this.broadCast.off(null, null); + if(this.broadCast) { + this.broadCast.off(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.off(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.off(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadedFunc); + } this.dataSource.releaseBroadCast(); Log.info(TAG, `call aboutToDisappear`) } - onMediaLibDataChange(changeType) { + onMediaLibDataChange(changeType: string): void { Log.info(TAG, `onMediaLibDataChange type: ${changeType}`); this.dataSource.onChange(changeType); } getGeometryTransitionId(item: ViewData, index: number): string { - return TAG + item.mediaItem.getHashCode() + this.selectManager.isItemSelected(item?.mediaItem?.uri); + let mediaItem = item.mediaItem as MediaItem; + if (mediaItem) { + return TAG + mediaItem.getHashCode() + (this.selectManager?.isItemSelected(mediaItem.uri as string) ?? false); + } else { + return TAG + item.viewIndex; + } } @Builder buildGrid() { @@ -244,36 +271,36 @@ export struct ThirdSelectPhotoGridBase { Log.debug(TAG, `get camera callback, uri ${uri}`) this.dataSource.initData(); this.selectFromCameraFunc = () => { - this.onSelectCallback(0, uri, true, null); + this.onSelectCallback(0, uri, true, () => {}); } } }) } .aspectRatio(1) } - LazyForEach(this.dataSource, (item, index?: number) => { - if (!!item) { + LazyForEach(this.dataSource, (item: ViewData, index?: number) => { + if (item?.mediaItem) { GridItem() { ImageGridItemComponent({ dataSource: this.dataSource, item: item?.mediaItem, - isSelected: this.selectManager.isItemSelected(item?.mediaItem?.uri), + isSelected: this.selectManager?.isItemSelected((item.mediaItem as MediaItem).uri as string) ?? false, pageName: Constants.PHOTO_TRANSITION_ALBUM, isThird: true, mPosition: item?.viewIndex, isThirdMultiPick: this.selectParams.isMultiPick, - geometryTransitionString: this.getGeometryTransitionId(item, index), + geometryTransitionString: this.getGeometryTransitionId(item, index as number), selectedCount: $selectedCount }) } .aspectRatio(1) .zIndex(index === this.placeholderIndex ? 1 : 0) } - }, (item, index) => { + }, (item: ViewData, index?: number) => { if (item == null || item == undefined) { return JSON.stringify(item) + index; } - return this.getGeometryTransitionId(item, index); + return this.getGeometryTransitionId(item, index as number); }) } .edgeEffect(EdgeEffect.Spring) @@ -288,7 +315,7 @@ export struct ThirdSelectPhotoGridBase { isSelectPhotoGrid: true, title: $title, selectParams: this.selectParams, - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), isFirstEnter: this.isFirstEnter, totalSelectedCount: $selectedCount }) @@ -307,7 +334,7 @@ export struct ThirdSelectPhotoGridBase { if (this.selectParams.isMultiPick) { ThirdSelectedPanel({ maxSelectCount: this.selectParams.maxSelectCount, - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), mTransition: TAG, currentUri: this.currentUri, isShowBar: $isShowBar, @@ -324,41 +351,63 @@ export struct ThirdSelectPhotoGridBase { } jumpToBrowserNormal(targetIndex: number, name: string, item: MediaItem, isSelectMode = false): void { - router.pushUrl({ - url: 'pages/ThirdSelectPhotoBrowser', - params: { - position: targetIndex, - bundleName: this.selectParams.bundleName, - transition: name, - title: this.title, - selectMode: isSelectMode, - maxSelectCount: this.selectParams.maxSelectCount, - isFromFa: this.selectParams.isFromFa - } - }); - } - - jumpToBrowserGeometryTransition(targetIndex: number, name: string, item: MediaItem, isSelectMode = false, - geometryTapIndex: number = undefined, - geometryTransitionString: string = undefined): void { - this.browserController.showBrowser(geometryTapIndex, geometryTransitionString, TAG, { + interface AniParams { + position: number; + bundleName: string; + transition: string; + title: string; + selectMode: boolean; + maxSelectCount: number; + isFromFa: boolean; + } + let params: AniParams = { position: targetIndex, bundleName: this.selectParams.bundleName, transition: name, title: this.title, selectMode: isSelectMode, maxSelectCount: this.selectParams.maxSelectCount, - isFromFa: this.selectParams.isFromFa + isFromFa: this.selectParams.isFromFa, + }; + + router.pushUrl({ + url: 'pages/ThirdSelectPhotoBrowser', + params: params }); } + jumpToBrowserGeometryTransition(targetIndex: number, name: string, item: MediaItem, isSelectMode = false, + geometryTapIndex: number, + geometryTransitionString: string): void { + interface AniParams { + position: number; + bundleName: string; + transition: string; + title: string; + selectMode: boolean; + maxSelectCount: number; + isFromFa: boolean; + } + + let params: AniParams = { + position: targetIndex, + bundleName: this.selectParams.bundleName, + transition: name, + title: this.title, + selectMode: isSelectMode, + maxSelectCount: this.selectParams.maxSelectCount, + isFromFa: this.selectParams.isFromFa, + }; + this.browserController.showBrowser(geometryTapIndex, geometryTransitionString, TAG, params); + } + private initGridRowCount(): void { let contentWidth = ScreenManager.getInstance().getWinWidth(); let margin = 0; let maxThumbWidth = px2vp(Constants.GRID_IMAGE_SIZE) * Constants.GRID_MAX_SIZE_RATIO; let calCount = Math.round( ((contentWidth - Constants.NUMBER_2 * margin) + Constants.GRID_GUTTER) - / (maxThumbWidth + Constants.GRID_GUTTER)); + / (maxThumbWidth + Constants.GRID_GUTTER)); let newCount = Math.max(Constants.GRID_MIN_COUNT, calCount); if (newCount != this.gridRowCount) { this.gridRowCount = newCount; @@ -366,13 +415,13 @@ export struct ThirdSelectPhotoGridBase { Log.info(TAG, `initGridRowCount contentWidth: ${contentWidth}, row count ${this.gridRowCount}`); } - private initSelectParams(param) { - if (param != null) { - this.isItemIdChange = this.itemId && this.itemId !== param.itemId; + private initSelectParams(param?: Params): void { + if (param) { + this.isItemIdChange = (this.itemId !== undefined && this.itemId !== null && this.itemId !== param.itemId) as boolean; this.itemId = param.itemId == undefined ? AlbumDefine.ALBUM_ID_ALL : param.itemId; - this.dataSource.setAlbumUri(this.itemId); + this.dataSource.setAlbumUri(this.itemId as string); - let albumUri = param.uri == undefined ? + let albumUri = param.uri === undefined ? UserFileManagerAccess.getInstance().getSystemAlbumUri(UserFileManagerAccess.IMAGE_ALBUM_SUB_TYPE) : param.uri; this.dataSource.setAlbumUri(albumUri); @@ -400,7 +449,7 @@ export struct ThirdSelectPhotoGridBase { : param.maxSelectCount; } if (this.backFuncBinder) { - this.backFuncBinder(this.onBackPress.bind(this)); + this.backFuncBinder((): void => this.onBackPress()); } Log.debug(TAG, `select param ${JSON.stringify(this.selectParams)}`); } @@ -408,19 +457,19 @@ export struct ThirdSelectPhotoGridBase { Log.debug(TAG, `select param ${JSON.stringify(this.selectParams)}, select mode ${this.isSelectedMode}`); } - private updateTitle(param) { - let displayName = param.itemDisplayName == undefined ? $r('app.string.album_all') : param.itemDisplayName; + private updateTitle(param?: Params): void { + let displayName = param?.itemDisplayName == undefined ? $r('app.string.album_all') : param.itemDisplayName; if (typeof displayName === 'object') { - UiUtil.getResourceString(displayName).then((stringResource) => { + UiUtil.getResourceString(displayName as Resource).then((stringResource: string) => { this.title = stringResource; }) } else { - this.title = displayName; + this.title = displayName as string; } Log.debug(TAG, `update title ${this.title}`); } - private onSelectCallback(position: number, key: string, value: boolean, callback: Function) { + private onSelectCallback(position: number, key: string, value: boolean, callback: Function): void{ Log.debug(TAG, `isHorizontal ${this.isHorizontal}, position ${position}, uri ${key}, select ${value}`) let isMultiPick = this.selectParams.isMultiPick; if (value && isMultiPick && this.selectedCount >= this.selectParams.maxSelectCount) { @@ -431,35 +480,36 @@ export struct ThirdSelectPhotoGridBase { } if (!isMultiPick) { // update correct status from select manager - value = !this.selectManager.isItemSelected(key); - this.selectManager.deSelectAll(); + value = !this.selectManager?.isItemSelected(key); + this.selectManager?.deSelectAll(); } - if (this.selectManager.toggle(key, value, position)) { + if (this.selectManager?.toggle(key, value, position)) { Log.info(TAG, 'enter event process'); this.dataSource.onDataChanged(this.dataSource.getDataIndexByUri(key)); callback && callback(value); } } - private jumpBrowserCallback(name: string, item: MediaItem, geometryTapIndex: number = undefined, - geometryTransitionString: string = undefined, isSelectMode = false) { - let targetIndex = isSelectMode ? this.selectManager.getSelectItemIndex(item) : this.dataSource.getDataIndex(item); + private jumpBrowserCallback(name: string, item: MediaItem, geometryTapIndex: number , + geometryTransitionString: string, isSelectMode = false) { + let selectItemIndex: number = this.selectManager?.getSelectItemIndex(item) ?? Constants.INVALID; + let targetIndex = isSelectMode ? selectItemIndex : this.dataSource.getDataIndex(item); Log.info(TAG, `jump to photo browser at index: ${targetIndex}, transition: ${name}`); AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, this.dataSource); - if (geometryTapIndex != undefined && geometryTransitionString != undefined) { + if (geometryTapIndex && geometryTransitionString) { this.jumpToBrowserGeometryTransition( targetIndex, name, item, isSelectMode, geometryTapIndex, geometryTransitionString); } else { this.jumpToBrowserNormal(targetIndex, name, item, isSelectMode); } - ReportToBigDataUtil.report(BigDataConstants.SELECT_PICKER_CLICK_PREVIEW, null); + ReportToBigDataUtil.report(BigDataConstants.SELECT_PICKER_CLICK_PREVIEW, undefined); } - private onReloadFinishedCallback() { + private onReloadFinishedCallback(): void { Log.info(TAG, 'ON_DATA_RELOADED'); this.dataSource.onDataReloaded(); this.selectFromCameraFunc && this.selectFromCameraFunc(); - this.selectFromCameraFunc = undefined; + this.selectFromCameraFunc = () => {}; } private onLoadFinishedCallback(size: number, updateTitle: Function) { @@ -473,7 +523,7 @@ export struct ThirdSelectPhotoGridBase { } private initSelectManager() { - let manager: ThirdSelectManager = AppStorage.Get(Constants.THIRD_SELECT_MANAGER); + let manager: ThirdSelectManager = AppStorage.get(Constants.THIRD_SELECT_MANAGER) as ThirdSelectManager; if (manager && manager.getClassName() === 'ThirdSelectManager') { Log.debug(TAG, `use cached select manager, current select count ${manager.getSelectedCount()}`); this.selectManager = manager; @@ -487,7 +537,9 @@ export struct ThirdSelectPhotoGridBase { this.selectManager.deSelectAll(); AppStorage.SetOrCreate(THIRD_SELECT_IS_ORIGIN, false); } - this.selectManager.setGetMediaItemFunc(this.dataSource.getMediaItemByUri.bind(this.dataSource)); + this.selectManager.setGetMediaItemFunc((uri: string): MediaItem => { + return this.dataSource.getMediaItemByUri(uri); + }); } private onActive() { @@ -514,43 +566,52 @@ export struct ThirdSelectPhotoGridBase { } } - private setPickResult(uriArray: Array): void { - let isOrigin: boolean = AppStorage.Get(THIRD_SELECT_IS_ORIGIN); + private setPickResult(uriArray?: Array): void { + let isOrigin: boolean = AppStorage.get(THIRD_SELECT_IS_ORIGIN) as boolean; if (isOrigin == undefined) { isOrigin = false; } - let abilityResult = { - 'resultCode': 0, - 'want': { - 'parameters': { - 'select-item-list': uriArray, - 'isOriginal': isOrigin + let abilityResult: ability.AbilityResult = { + resultCode: (uriArray === null || uriArray === undefined) ? -1 : 0, + want: { + parameters: { + 'select-item-list': uriArray as Object, + isOriginal: isOrigin } } }; let self = this; let uriLength = 0; if (uriArray == null && uriArray == undefined) { - globalThis.photosAbilityContext.terminateSelfWithResult(abilityResult).then((result) => { + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelfWithResult(abilityResult as ability.AbilityResult).then((result: void) => { Log.debug(TAG, `terminateSelfWithResult result: ${result}, self result ${JSON.stringify(abilityResult)}`); }); } else { uriLength = uriArray.length; - SelectUtil.grantPermissionForUris(uriArray, self.selectParams.bundleName).then(function () { + SelectUtil.grantPermissionForUris(uriArray, self.selectParams.bundleName).then(() => { Log.info(TAG, `grant permission success.`); - globalThis.photosAbilityContext.terminateSelfWithResult(abilityResult).then((result) => { + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelfWithResult(abilityResult as ability.AbilityResult).then((result: void) => { Log.debug(TAG, `terminateSelfWithResult result: ${result}, self result ${JSON.stringify(abilityResult)}`); }); - }).catch(function (err) { + }).catch((err: Error) => { Log.error(TAG, `grant permission error: ${JSON.stringify(err)}, self result ${JSON.stringify(abilityResult)}`); }); } - ReportToBigDataUtil.report(BigDataConstants.SELECT_PICKER_RESULT, - { "isOriginalChecked": isOrigin, "selectItemSize": uriLength }); + interface Msg { + isOriginalChecked: boolean; + selectItemSize: number; + } + let msg: Msg = { + isOriginalChecked: isOrigin, + selectItemSize: uriLength, + } + ReportToBigDataUtil.report(BigDataConstants.SELECT_PICKER_RESULT, msg); } - private goBackFormEditor() { - let formEditorOption = { + private goBackFormEditor(): void { + let formEditorOption: router.RouterOptions = { url: 'pages/FormEditorPage' }; router.replaceUrl(formEditorOption); diff --git a/feature/thirdselect/src/main/ets/default/view/ThirdSelectedPageActionBar.ets b/feature/thirdselect/src/main/ets/default/view/ThirdSelectedPageActionBar.ets index 5ce197c6..daa58aa4 100644 --- a/feature/thirdselect/src/main/ets/default/view/ThirdSelectedPageActionBar.ets +++ b/feature/thirdselect/src/main/ets/default/view/ThirdSelectedPageActionBar.ets @@ -25,8 +25,8 @@ export struct ThirdSelectedPageActionBar { selectParams: SelectParams = SelectParams.defaultParam(); @Provide selectedCount: number = 0; @Link @Watch('onSelectedCountChanged') totalSelectedCount: number; - isSelectPhotoGrid: boolean; - onMenuClicked: Function; + isSelectPhotoGrid: boolean = false; + onMenuClicked: Function = (): void => {}; leftAction: Action = Action.BACK; @Link @Watch('onSelectedCountChanged') title: string; @State actionBarProp: ActionBarProp = new ActionBarProp(); diff --git a/feature/thirdselect/src/main/ets/default/view/ThirdSelectedPanel.ets b/feature/thirdselect/src/main/ets/default/view/ThirdSelectedPanel.ets index 9b59e486..d4c3f79e 100644 --- a/feature/thirdselect/src/main/ets/default/view/ThirdSelectedPanel.ets +++ b/feature/thirdselect/src/main/ets/default/view/ThirdSelectedPanel.ets @@ -30,39 +30,51 @@ import { IS_HORIZONTAL, THIRD_SELECT_IS_ORIGIN, THUMBNAIL_WIDTH } from '../utils const TAG: string = 'thiSel_ThirdSelectedPanel'; +interface WidthAndHeight { + height: number; + width: number; +}; + @Component export struct ThirdSelectedPanel { - onMenuClicked: Function; - maxSelectCount: number; + onMenuClicked: Function = (): void => {}; + maxSelectCount: number = 0; @Provide selectedCount: number = 0; @Link @Watch('onSelectedCountChanged') totalSelectedCount: number; - selectManager: ThirdSelectManager; + selectManager: ThirdSelectManager | null = null; @State itemArray: Array = []; @StorageLink(THIRD_SELECT_IS_ORIGIN) isOriginalChecked: boolean = false; @StorageLink(IS_HORIZONTAL) isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @Consume broadCast: BroadCast; @Link isShowBar: boolean; - @Prop currentUri: string; + @Prop currentUri: string = ''; isBrowserMode: boolean = false; isMultiPick = true; mTransition: string = ''; isFromFa: boolean = false; - dataSource: MediaDataSource; + dataSource: MediaDataSource | null = null; private selectedScroller: Scroller = new Scroller(); aboutToAppear(): void { - this.selectManager = AppStorage.Get(Constants.THIRD_SELECT_MANAGER); + this.selectManager = AppStorage.get(Constants.THIRD_SELECT_MANAGER) as ThirdSelectManager; this.onSelectedCountChanged(); } - onSelectedCountChanged() { + onSelectedCountChanged(): void { this.selectedCount = this.totalSelectedCount; - this.itemArray = this.selectManager.getSelectItems(); + this.itemArray = this.selectManager == null ? [] : this.selectManager.getSelectItems(); + Log.debug(TAG, `call scroll to edge, current count ${this.itemArray.length} this.selectedCount is: ${this.selectedCount}`); + this.selectedScroller.scrollEdge(Edge.End); + } + + refreshSelectData(refresh: boolean): void { + this.selectedCount = this.totalSelectedCount; + this.itemArray = this.selectManager == null ? [] : this.selectManager.getSelectItems(); Log.debug(TAG, `call scroll to edge, current count ${this.itemArray.length}`) this.selectedScroller.scrollEdge(Edge.End); } - getThumbnailSafe(sourceUri: string, path: string, size?) { + getThumbnailSafe(sourceUri: string, path: string, size?: WidthAndHeight): string { try { if (size) { if (size.width != 0 && size.height != 0) { @@ -76,7 +88,7 @@ export struct ThirdSelectedPanel { } } catch (err) { Log.warn(TAG, `get Thumbnail Failed! msg:${err}`); - return null; + return ''; } } @@ -86,13 +98,13 @@ export struct ThirdSelectedPanel { .key('Original') .width($r('app.float.icon_size')) .aspectRatio(1) - .onClick(this.clickOriginButton.bind(this)) + .onClick((): void => this.clickOriginButton()) } else { Radio({ value: '', group: this.mTransition }) .key('Original') .checked(this.isOriginalChecked) .margin(0) - .onClick(this.clickOriginButton.bind(this)) + .onClick((): void => this.clickOriginButton()) } } @@ -212,9 +224,9 @@ export struct ThirdSelectedPanel { @Builder buildThumbnailList() { List({ scroller: this.selectedScroller, space: 8 }) { - ForEach(this.itemArray, (item: MediaItem, index: number) => { + ForEach(this.itemArray, (item: MediaItem, index?: number) => { ListItem() { - this.buildThumbnailItem(item, index) + this.buildThumbnailItem(item, index as number); } .width($r('app.float.third_selected_panel_image_height')) .aspectRatio(1) @@ -222,7 +234,7 @@ export struct ThirdSelectedPanel { left: index == 0 ? $r('sys.float.ohos_id_max_padding_start') : 0, right: index == this.itemArray.length - 1 ? $r('sys.float.ohos_id_max_padding_end') : 0 }) - }, item => item.getHashCode()) + }, (item: MediaItem) => item?.getHashCode()) } .width('100%') .height('100%') @@ -285,6 +297,8 @@ export struct ThirdSelectedPanel { private getPosition(item: MediaItem): number { if (this.dataSource) { return this.dataSource.getDataIndex(item) + this.dataSource.getGroupCountBeforeItem(item); + } else { + return Constants.NOT_FOUND; } } @@ -303,7 +317,7 @@ export struct ThirdSelectedPanel { return!this.isMultiPick || this.selectedCount > 0; } - private clickOriginButton() { + private clickOriginButton(): void { this.isOriginalChecked = !this.isOriginalChecked; Log.info(TAG, `origin clicked: ${this.isOriginalChecked}`); } diff --git a/feature/timeline/src/main/ets/view/TimelinePage.ets b/feature/timeline/src/main/ets/view/TimelinePage.ets index 9cc59672..708a9525 100644 --- a/feature/timeline/src/main/ets/view/TimelinePage.ets +++ b/feature/timeline/src/main/ets/view/TimelinePage.ets @@ -14,7 +14,7 @@ */ import Curves from '@ohos.curves'; -import { MenuOperation } from '@ohos/common'; +import { MenuOperation, WindowUtil } from '@ohos/common'; import { Action, AddMenuOperation, @@ -56,6 +56,13 @@ import { TimelineScrollBar } from './TimelineScrollBar'; const TAG: string = 'TimelinePage'; AppStorage.SetOrCreate('TimelinePageIndex', Constants.INVALID); +interface Params { + albumName: string; + albumUri: string; + pageType: string; + pageFrom: number; +}; + // PHOTO Page @Component export struct TimelinePage { @@ -73,7 +80,7 @@ export struct TimelinePage { @StorageLink('isSplitMode') isSplitMode: boolean = ScreenManager.getInstance().isSplitMode(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - dataSource: TimelineDataSource; + dataSource: TimelineDataSource | null = null; mSelectManager: TimelineSelectManager = new TimelineSelectManager(); scroller: Scroller = new Scroller(); appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); @@ -93,8 +100,22 @@ export struct TimelinePage { @Provide hidePopup: boolean = false; // 选择模式下,鼠标对着未勾选项按右键弹框时,移动和复制菜单点击事件的标识位 private isMvOrCpSeparatesItem: boolean = false; - private mvOrCpSeparatesItem: MediaItem = null; - private onWindowSizeChangeCallBack = () => this.initGridRowCount(); + private mvOrCpSeparatesItem?: MediaItem; + private onWindowSizeChangeCallBack: Function = (): void => this.initGridRowCount(); + private backPressEventFunc: Function = (callback: Function): void => this.onIndexBackPress(callback); + private onTableChangedFunc: Function = (index: number): void => this.onTabChanged(index); + private resetStateEventFunc: Function = (index: number): void => this.onStateReset(index); + private updateDataSourceFunc: Function = (item: MediaItem): void => this.onUpdateFavorState(item); + private resetZeroFunc: Function = (pageNumber: number): void => this.resetZero(pageNumber); + private onLoadingFinishedFunc: Function = (size: number): void => this.onLoadingFinished(size); + private selectFunc: Function = (index: number, id: string, isSelected: boolean, callback?: Function): void => this.select(index, id, isSelected, callback); + private groupSelectFunc: Function = (position: number): void => this.groupSelect(position); + private jumpPhotoBrowserFunc: Function = (name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void => + this.jumpPhotoBrowser(name, item, geometryTapIndex, geometryTransitionString); + private jumpThirdPhotoBrowserFunc: Function = (name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void => + this.jumpThirdPhotoBrowser(name, item, geometryTapIndex, geometryTransitionString); + private onDataReloadedFunc: Function = (): void => this.onDataReloaded(); + private initDateTextFunc: Function = (): void => this.initDateText(); @State layoutOptions: GridLayoutOptions = { regularSize: [1, 1], irregularIndexes: [], @@ -112,7 +133,7 @@ export struct TimelinePage { Log.info(TAG, 'aboutToAppear begin'); let self = this; this.dataSource = TimelineDataSourceManager.getInstance().getDataSource(); - let params: any = router.getParams(); + let params: Params = router.getParams() as Params; if (params != null && params.pageFrom && params.pageFrom == Constants.ENTRY_FROM.CAMERA) { this.dataSource.initData(); } @@ -137,109 +158,49 @@ export struct TimelinePage { ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); } - this.appBroadCast.on(BroadCastConstants.BACK_PRESS_EVENT, this.onIndexBackPress.bind(this)); - this.appBroadCast.on(BroadCastConstants.ON_TAB_CHANGED, this.onTabChanged.bind(this)); - this.appBroadCast.on(BroadCastConstants.RESET_STATE_EVENT, this.onStateReset.bind(this)); - this.appBroadCast.on(BroadCastConstants.UPDATE_DATA_SOURCE, this.onUpdateFavorState.bind(this)); - this.appBroadCast.on(BroadCastConstants.RESET_ZERO, (pageNumber: number) => { - if (pageNumber == Constants.TIMELINE_PAGE_INDEX) { - this.scroller.scrollEdge(Edge.Top); - } - }); - this.broadCast.on(Constants.ON_LOADING_FINISHED, (size: number) => { - Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); - }); + this.appBroadCast.on(BroadCastConstants.BACK_PRESS_EVENT, this.backPressEventFunc); + this.appBroadCast.on(BroadCastConstants.ON_TAB_CHANGED, this.onTableChangedFunc); + this.appBroadCast.on(BroadCastConstants.RESET_STATE_EVENT, this.resetStateEventFunc); + this.appBroadCast.on(BroadCastConstants.UPDATE_DATA_SOURCE, this.updateDataSourceFunc); + this.appBroadCast.on(BroadCastConstants.RESET_ZERO, this.resetZeroFunc); + this.broadCast.on(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); - this.onMenuClicked = this.onMenuClicked.bind(this); - this.onMenuClickedForSingleItem = this.onMenuClickedForSingleItem.bind(this); Log.info(TAG, 'aboutToAppear doing'); this.mSelectManager.setPhotoDataImpl(); - this.broadCast.on(BroadCastConstants.SELECT, - (index: number, id: string, isSelected: boolean, callback?: Function) => { - if (self.mSelectManager.toggle(id, isSelected, index)) { - if (!self.isSelectedMode) { - self.isSelectedMode = true; - } - } - callback(); - }); - this.broadCast.on(BroadCastConstants.GROUP_SELECT, (position: number) => { - Log.info(TAG, `GROUP_SELECT ${position}`); - if (self.mSelectManager.toggleGroup(self.mSelectManager.getTitleCoordinate(position))) { - self.totalSelectedCount = self.mSelectManager.getSelectedCount(); - } - }); - this.broadCast.on(BroadCastConstants.JUMP_PHOTO_BROWSER, (name: string, item: MediaItem, geometryTapIndex: number, - geometryTransitionString: string) => { - let targetIndex = self.dataSource.getDataIndex(item); - if (targetIndex == Constants.NOT_FOUND) { - Log.error(TAG, 'targetIndex is not found'); - return; - } - AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, self.dataSource); - if (geometryTapIndex !== undefined && geometryTransitionString !== undefined) { - this.jumpToPhotoBrowserGeometryTransition(targetIndex, name, item, geometryTapIndex, geometryTransitionString); - } else { - this.jumpToPhotoBrowserNormal(targetIndex, name, item); - } - }); - this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, (name: string, item: MediaItem, - geometryTapIndex: number, - geometryTransitionString: string) => { - let targetIndex = self.dataSource.getDataIndex(item); - if (targetIndex == Constants.NOT_FOUND) { - Log.error(TAG, 'targetIndex is not found'); - return; - } - Log.info(TAG, `JUMP_THIRD_PHOTO_BROWSER.index: ${targetIndex} transition: ${name}`); - AppStorage.SetOrCreate(Constants.PHOTO_GRID_SELECT_MANAGER, self.mSelectManager); - AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, self.dataSource); - if (geometryTapIndex !== undefined && geometryTransitionString !== undefined) { - this.jumpToSelectPhotoBrowserGeometryTransition( - targetIndex, name, item, geometryTapIndex, geometryTransitionString); - } else { - this.jumpToSelectPhotoBrowserNormal(targetIndex, name, item); - } - }); + this.broadCast.on(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.on(BroadCastConstants.GROUP_SELECT, this.groupSelectFunc); + this.broadCast.on(BroadCastConstants.JUMP_PHOTO_BROWSER, this.jumpPhotoBrowserFunc); + this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadedFunc); + this.broadCast.on(BroadCastConstants.INIT_DATE_TEXT, this.initDateTextFunc); - this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, () => { - Log.info(TAG, 'ON_DATA_RELOADED'); - if (this.deleteMode) { - animateTo({ - duration: 300, // 删除动画时长 - curve: Curves.cubicBezier(0.0, 0.0, 0.2, 1.0) // 减速曲线参数 - }, () => { - this.dataSource.onDataReloaded(); - }) - this.deleteMode = false; - } else { - this.dataSource.onDataReloaded(); - } - }); - - this.broadCast.on(BroadCastConstants.INIT_DATE_TEXT, () => { - let scrollMediaItem = this.dataSource.getMediaItemByPosition(0); - this.dateText = DateUtil.getLocalizedYearAndMonth(scrollMediaItem.getDataTaken()); - }) - - this.mSelectManager.registerCallback('allSelect', this.freezeAdapter((newState: boolean) => { + this.mSelectManager.registerCallback('allSelect', (newState: boolean) => { Log.info(TAG, `allSelect ${newState}`); - self.isAllSelected = newState; - self.dataSource.forceUpdate(); - })); + if (this.isDataFreeze) { + return; + } + this.isAllSelected = newState; + if (this.dataSource != null) this.dataSource.forceUpdate(); + }); - this.mSelectManager.registerCallback('updateGroupCount', this.freezeAdapter(() => { + this.mSelectManager.registerCallback('updateGroupCount', () => { Log.info(TAG, 'updateGroupCount'); - self.updateGroupSelectMode(); - })); + if (this.isDataFreeze) { + return; + } + this.updateGroupSelectMode(); + }); - this.mSelectManager.registerCallback('updateCount', this.freezeAdapter((newState: number) => { + this.mSelectManager.registerCallback('updateCount', (newState: number) => { Log.info(TAG, `mSelectManager updateCount ${newState}`); - self.totalSelectedCount = newState; - self.moreMenuList = Boolean(newState) ? [Action.ADD, Action.INFO] - : [Action.ADD_INVALID, Action.INFO_INVALID]; - })); + if (this.isDataFreeze) { + return; + } + this.totalSelectedCount = newState; + this.moreMenuList = Boolean(newState) ? [Action.ADD, Action.INFO] + : [Action.ADD_INVALID, Action.INFO_INVALID]; + }); this.initGridRowCount(); this.updateGroupSelectMode(); this.updateYearMap(); @@ -249,22 +210,93 @@ export struct TimelinePage { } updateLayoutOptions(groups: TimelineData[]): void { - this.layoutOptions.irregularIndexes.pop(); + this.layoutOptions.irregularIndexes && this.layoutOptions.irregularIndexes.pop(); let currentTitleIndex = 0; let count: number[] = []; count.push(currentTitleIndex); - for (let index = 0; index < groups.length - 1; index++) { currentTitleIndex = currentTitleIndex + groups[index].count + 1; count.push(currentTitleIndex); } - this.layoutOptions = { regularSize: [1, 1], irregularIndexes: count, }; } + private onLoadingFinished(size: number): void { + Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); + } + + private select(index: number, id: string, isSelected: boolean, callback?: Function): void { + if (this.mSelectManager.toggle(id, isSelected, index)) { + if (!this.isSelectedMode) { + this.isSelectedMode = true; + } + } + if (callback) { + callback(); + } + } + + private groupSelect(position: number): void { + Log.info(TAG, `GROUP_SELECT ${position}`); + if (this.mSelectManager.toggleGroup(this.mSelectManager.getTitleCoordinate(position))) { + this.totalSelectedCount = this.mSelectManager.getSelectedCount(); + } + } + + private jumpPhotoBrowser(name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void { + let targetIndex = this.dataSource == null ? Constants.NOT_FOUND : this.dataSource.getDataIndex(item); + if (targetIndex == Constants.NOT_FOUND) { + Log.error(TAG, 'targetIndex is not found'); + return; + } + AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, this.dataSource); + if (geometryTapIndex !== undefined && geometryTransitionString !== undefined) { + this.jumpToPhotoBrowserGeometryTransition(targetIndex, name, item, geometryTapIndex, geometryTransitionString); + } else { + this.jumpToPhotoBrowserNormal(targetIndex, name, item); + } + } + + private jumpThirdPhotoBrowser(name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void { + let targetIndex = this.dataSource == null ? Constants.NOT_FOUND : this.dataSource.getDataIndex(item); + if (targetIndex == Constants.NOT_FOUND) { + Log.error(TAG, 'targetIndex is not found'); + return; + } + Log.info(TAG, `JUMP_THIRD_PHOTO_BROWSER.index: ${targetIndex} transition: ${name}`); + AppStorage.SetOrCreate(Constants.PHOTO_GRID_SELECT_MANAGER, this.mSelectManager); + AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, this.dataSource); + if (geometryTapIndex !== undefined && geometryTransitionString !== undefined) { + this.jumpToSelectPhotoBrowserGeometryTransition( + targetIndex, name, item, geometryTapIndex, geometryTransitionString); + } else { + this.jumpToSelectPhotoBrowserNormal(targetIndex, name, item); + } + } + + private onDataReloaded(): void { + Log.info(TAG, 'ON_DATA_RELOADED'); + if (this.deleteMode) { + animateTo({ + duration: 300, // 删除动画时长 + curve: Curves.cubicBezier(0.0, 0.0, 0.2, 1.0) // 减速曲线参数 + }, (): void => { + this.dataSource?.onDataReloaded(); + }) + this.deleteMode = false; + } else { + if (this.dataSource != null) this.dataSource.onDataReloaded(); + } + } + + private initDateText(): void { + let scrollMediaItem: MediaItem = this.dataSource == null ? new MediaItem() : this.dataSource.getMediaItemByPosition(0) as MediaItem; + this.dateText = DateUtil.getLocalizedYearAndMonth(scrollMediaItem.getDataTaken()); + } + jumpToPhotoBrowserNormal(targetIndex: number, name: string, item: MediaItem) { router.pushUrl({ url: 'pages/PhotoBrowser', @@ -278,11 +310,18 @@ export struct TimelinePage { jumpToPhotoBrowserGeometryTransition(targetIndex: number, name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string) { - this.browserController.showBrowser(geometryTapIndex, geometryTransitionString, TAG, { + interface Msg { + position: number; + transition: string; + leftBlank: number[]; + } + + const params: Msg = { position: targetIndex, transition: name, leftBlank: this.leftBlank, - }); + }; + this.browserController.showBrowser(geometryTapIndex, geometryTransitionString, TAG, params); } jumpToSelectPhotoBrowserNormal(targetIndex: number, name: string, item: MediaItem) { @@ -297,11 +336,18 @@ export struct TimelinePage { jumpToSelectPhotoBrowserGeometryTransition(targetIndex: number, name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string) { - this.browserController.showSelectBrowser(geometryTapIndex, geometryTransitionString, TAG, { + interface Params { + position: number; + transition: string; + leftBlank: number[]; + } + + const params: Params = { position: targetIndex, transition: name, leftBlank: this.leftBlank, - }); + }; + this.browserController.showSelectBrowser(geometryTapIndex, geometryTransitionString, TAG, params); } onPageShow() { @@ -309,31 +355,37 @@ export struct TimelinePage { aboutToDisappear(): void { Log.debug(TAG, 'aboutToDisappear'); - this.broadCast.off(null, null); ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; - if (this.dataSource != null) { - this.dataSource.unregisterCallback('updateGroupData'); - this.dataSource.unregisterCallback('updateCount'); - } + this.dataSource?.unregisterCallback('updateGroupData'); + this.dataSource?.unregisterCallback('updateCount'); if (this.appBroadCast != null) { - this.appBroadCast.off(BroadCastConstants.BACK_PRESS_EVENT, null); - this.appBroadCast.off(BroadCastConstants.ON_TAB_CHANGED, null); - this.appBroadCast.off(BroadCastConstants.RESET_STATE_EVENT, null); - this.appBroadCast.off(BroadCastConstants.UPDATE_DATA_SOURCE, null); - this.appBroadCast.off(BroadCastConstants.RESET_ZERO, null); + this.appBroadCast.off(BroadCastConstants.BACK_PRESS_EVENT, this.backPressEventFunc); + this.appBroadCast.off(BroadCastConstants.ON_TAB_CHANGED, this.onTableChangedFunc); + this.appBroadCast.off(BroadCastConstants.RESET_STATE_EVENT, this.resetStateEventFunc); + this.appBroadCast.off(BroadCastConstants.UPDATE_DATA_SOURCE, this.updateDataSourceFunc); + this.appBroadCast.off(BroadCastConstants.RESET_ZERO, this.resetZeroFunc); + } + if (this.broadCast != null) { + this.broadCast.off(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); + this.broadCast.off(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.off(BroadCastConstants.GROUP_SELECT, this.groupSelectFunc); + this.broadCast.off(BroadCastConstants.JUMP_PHOTO_BROWSER, this.jumpPhotoBrowserFunc); + this.broadCast.off(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.off(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadedFunc); + this.broadCast.off(BroadCastConstants.INIT_DATE_TEXT, this.initDateTextFunc); } } - updateGroupSelectMode() { + updateGroupSelectMode(): void { + let groups: TimelineData[] = this.dataSource == null ? [] : this.dataSource.groups; if (this.groupSelectMode.length == 0) { - Log.info(TAG, 'first updateGroupSelectMode') - for (let i = 0; i < this.dataSource.groups.length; i++) { + Log.info(TAG, 'first updateGroupSelectMode'); + for (let i = 0; i < groups.length; i++) { this.groupSelectMode.push(this.mSelectManager.isGroupSelected(i)); } } else { - Log.info(TAG, 'no first updateGroupSelectMode') - for (let i = 0; i < this.dataSource.groups.length; i++) { + Log.info(TAG, 'no first updateGroupSelectMode'); + for (let i = 0; i < groups.length; i++) { Log.info(TAG, 'update one'); this.groupSelectMode[i] = this.mSelectManager.isGroupSelected(i); } @@ -346,25 +398,29 @@ export struct TimelinePage { : [Action.MULTISELECT, Action.DELETE, Action.ADD, Action.INFO]; } - updateYearMap() { + updateYearMap(): void { Log.info(TAG, 'updateYearMap'); - if (this.dataSource.groups.length == 0) { + let groups: TimelineData[] = this.dataSource == null ? [] : this.dataSource.groups; + if (groups.length == 0) { Log.error(TAG, 'year length is 0'); return; } this.yearData = []; - let count = this.dataSource.groups[0].count; - let startTime = this.dataSource.groups[0].startDate; - let endTime = this.dataSource.groups[0].startDate; - for (let i = 1; i < this.dataSource.groups.length; i++) { - let dateTaken = this.dataSource.groups[i].startDate; + + let startGroup: TimelineData = groups[0]; + let count: number = startGroup.count as number; + let startTime: number = startGroup.startDate as number; + let endTime: number = startGroup.startDate as number; + + for (let i = 1; i < groups.length; i++) { + let dateTaken: number = groups[i].startDate as number; if (DateUtil.isTheSameYear(startTime, dateTaken)) { - count = count + this.dataSource.groups[i].count; + count = count + groups[i].count as number; endTime = dateTaken; } else { let groupData = new TimelineData(startTime, endTime, count); this.yearData.push(groupData); - count = this.dataSource.groups[i].count; + count = groups[i].count as number; startTime = dateTaken; endTime = dateTaken; } @@ -374,9 +430,9 @@ export struct TimelinePage { Log.info(TAG, 'updateYearMap end'); } - onIndexChange() { + onIndexChange(): void { Log.info(TAG, `onIndexChange ${this.TimelinePageIndex}`); - if (this.TimelinePageIndex != Constants.INVALID) { + if (this.TimelinePageIndex != Constants.INVALID && this.dataSource != null) { this.scroller.scrollToIndex(this.dataSource.getPositionByIndex(this.TimelinePageIndex)); } } @@ -404,56 +460,49 @@ export struct TimelinePage { } } - onMenuClicked(action: Action) { + resetZero(pageNumber: number): void { + if (pageNumber == Constants.TIMELINE_PAGE_INDEX) { + this.scroller.scrollEdge(Edge.Top); + } + } + + onMenuClicked(action: Action): void { Log.info(TAG, `onMenuClicked, actionID: ${action.actionID}`); let menuContext: MenuContext; let menuOperation: MenuOperation; - switch (action) { - case Action.CANCEL: - this.onModeChange(); - break; - case Action.MULTISELECT: - this.isSelectedMode = true; - break; - case Action.SELECT_ALL: - this.mSelectManager.selectAll(true); - break; - case Action.DESELECT_ALL: - this.mSelectManager.deSelectAll(); - break; - case Action.DELETE: - menuContext = new MenuContext(); - this.onDeleteStart = this.onDeleteStart.bind(this); - this.onDeleteEnd = this.onDeleteEnd.bind(this); - menuContext - .withSelectManager(this.mSelectManager) - .withFromSelectMode(this.isSelectedMode) - .withOperationStartCallback(this.onDeleteStart) - .withOperationEndCallback(this.onDeleteEnd) - .withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(BatchDeleteMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.SHARE: - menuContext = new MenuContext(); - menuContext.withFromSelectMode(true).withSelectManager(this.mSelectManager); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(ShareMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.INFO: - this.hidePopup = true; - this.openDetailsDialog(); - break; - case Action.ADD: - this.mSelectManager.getSelectedItems((selectedItems: Array) => { - Log.info(TAG, `Get selected items success, size: ${selectedItems.length}`); - this.routeToSelectAlbumPage(MediaOperationType.Add, selectedItems); - }) - break; - default: - break; + if (action === Action.CANCEL) { + this.onModeChange(); + } else if (action === Action.MULTISELECT) { + this.isSelectedMode = true; + } else if (action === Action.SELECT_ALL) { + this.mSelectManager.selectAll(true); + } else if (action === Action.DESELECT_ALL) { + this.mSelectManager.deSelectAll(); + } else if (action === Action.DELETE) { + menuContext = new MenuContext(); + menuContext + .withSelectManager(this.mSelectManager) + .withFromSelectMode(this.isSelectedMode) + .withOperationStartCallback((): void => this.onDeleteStart()) + .withOperationEndCallback((): void => this.onDeleteEnd()) + .withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(BatchDeleteMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action === Action.SHARE) { + menuContext = new MenuContext(); + menuContext.withFromSelectMode(true).withSelectManager(this.mSelectManager); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(ShareMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action === Action.INFO) { + this.hidePopup = true; + this.openDetailsDialog(); + } else if (action === Action.ADD) { + this.mSelectManager.getSelectedItems((selectedItems: Array) => { + Log.info(TAG, `Get selected items success, size: ${selectedItems.length}`); + this.routeToSelectAlbumPage(MediaOperationType.Add, selectedItems); + }) } } @@ -508,34 +557,42 @@ export struct TimelinePage { Log.info(TAG, `onDeleteStart`); this.deleteMode = true; this.isDataFreeze = true; - this.dataSource.unregisterTimelineObserver(); - this.dataSource.freeze(); + if (this.dataSource != null) { + this.dataSource.unregisterTimelineObserver(); + this.dataSource.freeze(); + } } onDeleteEnd(): void { Log.info(TAG, `onDeleteEnd`); this.isDataFreeze = false; this.onModeChange(); - this.dataSource.registerTimelineObserver(); - this.dataSource.onChange('image'); - this.dataSource.unfreeze(); + if (this.dataSource != null) { + this.dataSource.registerTimelineObserver(); + this.dataSource.onChange('image'); + this.dataSource.unfreeze(); + } } onCopyStart(): void { Log.info(TAG, `onCopyStart`); this.isDataFreeze = true; - this.dataSource.unregisterTimelineObserver(); - this.dataSource.freeze(); + if (this.dataSource != null) { + this.dataSource.unregisterTimelineObserver(); + this.dataSource.freeze(); + } } - onCopyEnd(err, count, total): void { + onCopyEnd(err: Object, count: number, total: number): void { Log.info(TAG, `onCopyEnd count: ${count}, total: ${total}`); this.isDataFreeze = false; this.onModeChange(); - this.dataSource.registerTimelineObserver(); - this.dataSource.onChange('image'); - this.dataSource.unfreeze(); + if (this.dataSource != null) { + this.dataSource.registerTimelineObserver(); + this.dataSource.onChange('image'); + this.dataSource.unfreeze(); + } if (err) { UiUtil.showToast($r('app.string.copy_failed_single')); } @@ -544,33 +601,24 @@ export struct TimelinePage { onMoveStart(): void { Log.info(TAG, `onMoveStart`); this.isDataFreeze = true; - this.dataSource.unregisterTimelineObserver(); - this.dataSource.freeze(); - } - - onMoveEnd(err, count, total): void { - Log.info(TAG, `onMoveEnd count: ${count}, total: ${total}`); - this.isDataFreeze = false; - this.onModeChange(); - this.dataSource.registerTimelineObserver(); - this.dataSource.unfreeze(); - this.dataSource.switchRefreshOn(); - this.dataSource.onChange('image'); - if (err) { - UiUtil.showToast($r('app.string.move_failed_single')); + if (this.dataSource != null) { + this.dataSource.unregisterTimelineObserver(); + this.dataSource.freeze(); } } - // If the interface is frozen, the adapter function will be executed only when the page is not frozen - freezeAdapter(fn): Function { - let self = this; - return function () { - if (self.isDataFreeze) { - return; - } - let context = this; - let args = arguments; - fn.apply(context, args); + onMoveEnd(err: Object, count: number, total: number): void { + Log.info(TAG, `onMoveEnd count: ${count}, total: ${total}`); + this.isDataFreeze = false; + this.onModeChange(); + if (this.dataSource != null) { + this.dataSource.registerTimelineObserver(); + this.dataSource.unfreeze(); + this.dataSource.switchRefreshOn(); + this.dataSource.onChange('image'); + } + if (err) { + UiUtil.showToast($r('app.string.move_failed_single')); } } @@ -590,15 +638,11 @@ export struct TimelinePage { onIndexPageShow() { Log.info(TAG, `[onIndexPageShow] isShow=${this.isShow}, isInCurrentTab=${this.isInCurrentTab}`); if (this.isShow && this.isInCurrentTab) { - let params: any = router.getParams(); + let params: Params = router.getParams() as Params; if (this.routerStart && params != null && params.pageType != null) { Log.info(TAG, `MediaOperation back ${JSON.stringify(params)}`) - switch (params.pageType) { - case MediaOperationType.Add: - this.addOperation(params.albumName, params.albumUri); - break; - default: - break; + if (params.pageType = MediaOperationType.Add) { + this.addOperation(params.albumName, params.albumUri); } } this.routerStart = false; @@ -615,10 +659,10 @@ export struct TimelinePage { Log.info(TAG, 'onActive'); this.isActive = true; - this.dataSource.onActive(); + this.dataSource?.onActive(); if (this.isSelectedMode) { this.totalSelectedCount = this.mSelectManager.getSelectedCount(); - this.dataSource.forceUpdate(); + this.dataSource?.forceUpdate(); } } } @@ -628,12 +672,17 @@ export struct TimelinePage { if (this.isActive) { Log.info(TAG, 'onInActive'); this.isActive = false; - this.dataSource.onInActive(); + this.dataSource?.onInActive(); } } getGeometryTransitionId(item: ViewData, index: number): string { - return TAG + item.mediaItem.getHashCode() + this.mSelectManager.isItemSelected(item.mediaItem.uri, item.viewIndex); + let mediaItem = item.mediaItem as MediaItem; + if (mediaItem) { + return TAG + mediaItem.getHashCode() + this.mSelectManager.isItemSelected(mediaItem.uri, item.viewIndex); + } else { + return TAG + item.viewIndex; + } } build() { @@ -643,13 +692,13 @@ export struct TimelinePage { NoPhotoIndexComponent({ index: Constants.TIMELINE_PAGE_INDEX, hasBarSpace: true }) } else { TimelinePageActionBar({ - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), totalSelectedCount: $totalSelectedCount }); Stack() { Grid(this.scroller, this.layoutOptions) { - LazyForEach(this.dataSource, (item: ViewData, index?: number) => { + LazyForEach(this.dataSource as TimelineDataSource, (item: ViewData, index?: number) => { if (!!item) { if (item.viewType == ViewType.GROUP_TITLE) { GridItem() { @@ -666,11 +715,11 @@ export struct TimelinePage { dataSource: this.dataSource, item: item.mediaItem, mPosition: item.viewIndex, - isSelected: this.isSelectedMode ? this.mSelectManager.isItemSelected(item.mediaItem.uri, item.viewIndex) : false, + isSelected: this.isSelectedMode ? this.mSelectManager.isItemSelected((item.mediaItem as MediaItem).uri as string, item.viewIndex) : false, pageName: Constants.PHOTO_TRANSITION_TIMELINE, - onMenuClicked: this.onMenuClicked, - onMenuClickedForSingleItem: this.onMenuClickedForSingleItem, - geometryTransitionString: this.getGeometryTransitionId(item, index), + onMenuClicked: (action: Action): void => this.onMenuClicked(action), + onMenuClickedForSingleItem: (action: Action, currentPhoto: MediaItem): void => this.onMenuClickedForSingleItem(action, currentPhoto), + geometryTransitionString: this.getGeometryTransitionId(item, index as number), selectedCount: $totalSelectedCount }) } @@ -681,12 +730,12 @@ export struct TimelinePage { } }, (item: ViewData, index?: number) => { if (item == null || item == undefined) { - return JSON.stringify(item) + index; + return (JSON.stringify(item) + index) as string; } if (item.viewType == ViewType.GROUP_TITLE) { - return JSON.stringify(item.viewData) + this.groupSelectMode[item.viewIndex]; + return (JSON.stringify(item.viewData) + this.groupSelectMode[item.viewIndex]) as string; } else { - return this.getGeometryTransitionId(item, index); + return this.getGeometryTransitionId(item, index as number) as string; } }) } @@ -697,7 +746,7 @@ export struct TimelinePage { .rowsGap(Constants.GRID_GUTTER) .cachedCount(Constants.GRID_CACHE_ROW_COUNT) .onScrollIndex((first) => { - let scrollMediaItem = this.dataSource.getMediaItemByPosition(first); + let scrollMediaItem: MediaItem | null = this.dataSource == null ? null : this.dataSource.getMediaItemByPosition(first) as MediaItem; if (scrollMediaItem?.getDataTaken()) { this.dateText = DateUtil.getLocalizedYearAndMonth(scrollMediaItem.getDataTaken()); Log.debug(TAG, `scrollIndex=${first}, dateTaken=${scrollMediaItem.getDataTaken()}`); @@ -721,7 +770,7 @@ export struct TimelinePage { if (this.isSelectedMode) { TimelinePageToolBar({ - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), totalSelectedCount: $totalSelectedCount }) } @@ -736,24 +785,18 @@ export struct TimelinePage { } let menuOperation: MenuOperation; let menuContext: MenuContext; - switch (action) { - case Action.DELETE: - menuContext = new MenuContext(); - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(DeleteMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.ADD: - this.isMvOrCpSeparatesItem = true; - this.mvOrCpSeparatesItem = currentPhoto; - this.routeToSelectAlbumPage(MediaOperationType.Add, [currentPhoto]); - break; - case Action.INFO: - this.broadCast.emit(BroadCastConstants.SHOW_DETAIL_DIALOG, [currentPhoto, false]); - break; - default: - break; + if (action === Action.DELETE) { + menuContext = new MenuContext(); + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(DeleteMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action === Action.ADD) { + this.isMvOrCpSeparatesItem = true; + this.mvOrCpSeparatesItem = currentPhoto; + this.routeToSelectAlbumPage(MediaOperationType.Add, [currentPhoto]); + } else if (action === Action.INFO) { + this.broadCast.emit(BroadCastConstants.SHOW_DETAIL_DIALOG, [currentPhoto, false]); } } @@ -775,17 +818,17 @@ export struct TimelinePage { private async addOperation(albumName: string, albumUri: string) { let menuContext = new MenuContext(); - this.onCopyStart = this.onCopyStart.bind(this); - this.onCopyEnd = this.onCopyEnd.bind(this); + let onCopyStartFunc = (): void => this.onCopyStart(); if (this.isMvOrCpSeparatesItem) { - menuContext.withMediaItem(this.mvOrCpSeparatesItem); + menuContext.withMediaItem(this.mvOrCpSeparatesItem as MediaItem); this.onCopyStart && this.onCopyStart(); this.isMvOrCpSeparatesItem = false; - this.mvOrCpSeparatesItem = null; + this.mvOrCpSeparatesItem = undefined; } else { - menuContext.withSelectManager(this.mSelectManager).withOperationStartCallback(this.onCopyStart); + menuContext.withSelectManager(this.mSelectManager).withOperationStartCallback(onCopyStartFunc); } - menuContext.withOperationEndCallback(this.onCopyEnd).withBroadCast(this.broadCast) + menuContext.withOperationEndCallback((err: Object, count: number, total: number): void => this.onCopyEnd(err as Object, count, total)) + .withBroadCast(this.broadCast) .withTargetAlbumName(albumName).withAlbumUri(albumUri); let menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddMenuOperation, menuContext); menuOperation.doAction(); @@ -793,8 +836,9 @@ export struct TimelinePage { private onUpdateFavorState(item: MediaItem): void { Log.debug(TAG, 'onUpdateFavorState favor'); - let index = this.dataSource.getIndexByMediaItem(item); - if (index != -1) { + if (this.dataSource != null) { + let index = this.dataSource.getIndexByMediaItem(item); + if (index == Constants.NOT_FOUND) return; let flushIndex = this.dataSource.getPositionByIndex(index); Log.debug(TAG, `onUpdateFavorState favor flushIndex ${flushIndex}`); this.dataSource.onDataChanged(flushIndex); diff --git a/feature/timeline/src/main/ets/view/TimelinePageActionBar.ets b/feature/timeline/src/main/ets/view/TimelinePageActionBar.ets index 25483a5b..84cd86de 100644 --- a/feature/timeline/src/main/ets/view/TimelinePageActionBar.ets +++ b/feature/timeline/src/main/ets/view/TimelinePageActionBar.ets @@ -34,7 +34,7 @@ export struct TimelinePageActionBar { @Link @Watch('updateActionBarProp') totalSelectedCount: number; @Provide selectedCount: number = 0; @Consume @Watch('updatePlaceholderStatus') isShowSideBar: boolean; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @StorageLink('isHorizontal') @Watch('updateActionBarProp') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); @@ -42,11 +42,10 @@ export struct TimelinePageActionBar { @StorageLink('statusBarHeight') statusBarHeight: number = 0; @State isNeedPlaceholder: boolean = true; @Consume moreMenuList: Action[]; - private deviceType: string; + @StorageLink('deviceType') deviceType: string | undefined = AppStorage.get('deviceType') ; private actionBarPaddingTop: number | Resource = 0; aboutToAppear(): void { - this.deviceType = AppStorage.Get('deviceType'); if (this.deviceType === Constants.PC_DEVICE_TYPE) { this.actionBarPaddingTop = $r('app.float.album_set_page_action_bar_padding_top'); } else if (this.deviceType === Constants.PAD_DEVICE_TYPE) { @@ -91,8 +90,7 @@ export struct TimelinePageActionBar { private createHorizontalActionBar(): ActionBarProp { let menuList: Array = new Array(); let actionBarProp: ActionBarProp = new ActionBarProp(); - const deviceType: string = AppStorage.Get('deviceType'); - if (!this.isEmpty && deviceType === Constants.PC_DEVICE_TYPE) { + if (!this.isEmpty && this.deviceType === Constants.PC_DEVICE_TYPE) { menuList.push(Action.MULTISELECT); } actionBarProp diff --git a/feature/timeline/src/main/ets/view/TimelinePageToolBar.ets b/feature/timeline/src/main/ets/view/TimelinePageToolBar.ets index 35134f85..a186eb8c 100644 --- a/feature/timeline/src/main/ets/view/TimelinePageToolBar.ets +++ b/feature/timeline/src/main/ets/view/TimelinePageToolBar.ets @@ -24,7 +24,7 @@ export struct TimelinePageToolBar { @Consume @Watch('updateToolbar') isAllSelected: boolean; @Link @Watch('updateToolbar') totalSelectedCount: number; @Provide selectedCount: number = 0; - onMenuClicked: Function; + onMenuClicked: Function = (): void => {}; @Provide toolMenuList: Array = new Array(); @Consume moreMenuList: Action[]; @Consume hidePopup: boolean; diff --git a/feature/timeline/src/main/ets/view/TimelineScrollBar.ets b/feature/timeline/src/main/ets/view/TimelineScrollBar.ets index 26bdd1cc..52812c69 100644 --- a/feature/timeline/src/main/ets/view/TimelineScrollBar.ets +++ b/feature/timeline/src/main/ets/view/TimelineScrollBar.ets @@ -18,7 +18,7 @@ const TAG: string = 'timeline_TimelineScrollBar'; @Component export struct TimelineScrollBar { - scroller: Scroller; + scroller: Scroller | null = null; @Consume @Watch('updateTotalNum') yearData: TimelineData[]; @State isClickScrollBar: boolean = false; @Consume dateText: string; @@ -83,7 +83,7 @@ export struct TimelineScrollBar { bottom: this.nodeGap(year.count) }) } - }, year => JSON.stringify(year)) + }, (year: TimelineData) => JSON.stringify(year)) } .height('100%') .margin({ @@ -93,7 +93,7 @@ export struct TimelineScrollBar { }) } - ScrollBar({ scroller: this.scroller, direction: ScrollBarDirection.Vertical, + ScrollBar({ scroller: this.scroller as Scroller, direction: ScrollBarDirection.Vertical, state: BarState.Auto }) { Row() { if (this.isClickScrollBar) { @@ -142,16 +142,16 @@ export struct TimelineScrollBar { } .height('100%') .width(this.isClickScrollBar ? $r('app.float.scroll_press_all_width') : $r('app.float.scroll_bar_small_width')) - .onTouch((event: TouchEvent) => { + .onTouch((event?: TouchEvent) => { if (this.dateText == '') { Log.debug(TAG, `dateText is null`) this.broadCast.emit(BroadCastConstants.INIT_DATE_TEXT, []) } - if (event.type == TouchType.Move && !this.isClickScrollBar) { + if ((event as TouchEvent).type == TouchType.Move && !this.isClickScrollBar) { Log.debug(TAG, `scrollBar first TouchType.Move`); this.isClickScrollBar = true; - } else if (event.type == TouchType.Up || event.type == TouchType.Cancel) { - Log.debug(TAG, `scrollBar TouchType.Up or Cancel. type=${event.type}`); + } else if ((event as TouchEvent).type == TouchType.Up || (event as TouchEvent).type == TouchType.Cancel) { + Log.debug(TAG, `scrollBar TouchType.Up or Cancel. type=${(event as TouchEvent).type}`); this.isClickScrollBar = false; } }) diff --git a/feature/timeline/src/main/ets/view/TimelineTitleComponent.ets b/feature/timeline/src/main/ets/view/TimelineTitleComponent.ets index 0bf8a21a..187d4636 100644 --- a/feature/timeline/src/main/ets/view/TimelineTitleComponent.ets +++ b/feature/timeline/src/main/ets/view/TimelineTitleComponent.ets @@ -20,7 +20,7 @@ const TAG: string = 'timeline_TimelineTitleComponent'; // Group Title @Component export struct TimelineTitleComponent { - @State groupData: TimelineData = new TimelineData(null, null, null); + @State groupData: TimelineData = new TimelineData(); @Consume isSelectedMode: boolean; @State isSelected: boolean = false; @Consume broadCast: BroadCast; diff --git a/product/phone/src/main/ets/Application/AbilityStage.ts b/product/phone/src/main/ets/Application/AbilityStage.ts index 1585a0ca..01b0647e 100644 --- a/product/phone/src/main/ets/Application/AbilityStage.ts +++ b/product/phone/src/main/ets/Application/AbilityStage.ts @@ -17,6 +17,6 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; export default class PhotosAbilityStage extends AbilityStage { onCreate() { - globalThis.photosGlobalContext = this.context; + AppStorage.setOrCreate('photosGlobalContext', this.context); } } \ No newline at end of file diff --git a/product/phone/src/main/ets/FormAbility/FormAbility.ts b/product/phone/src/main/ets/FormAbility/FormAbility.ts index 0cc9b838..1b99f2b4 100644 --- a/product/phone/src/main/ets/FormAbility/FormAbility.ts +++ b/product/phone/src/main/ets/FormAbility/FormAbility.ts @@ -101,7 +101,7 @@ export default class FormAbility extends FormExtension { // Init system album information UserFileManagerAccess.getInstance().prepareSystemAlbums(); - globalThis.formContext = this.context; + AppStorage.setOrCreate('formContext', this.context); } private async clearCache(newStatus: FormVisibilityArray): Promise { diff --git a/product/phone/src/main/ets/MainAbility/MainAbility.ts b/product/phone/src/main/ets/MainAbility/MainAbility.ts index ee5e5eee..aae04e81 100644 --- a/product/phone/src/main/ets/MainAbility/MainAbility.ts +++ b/product/phone/src/main/ets/MainAbility/MainAbility.ts @@ -36,6 +36,7 @@ import deviceInfo from '@ohos.deviceInfo'; import type Want from '@ohos.app.ability.Want'; import type window from '@ohos.window'; import type AbilityConstant from '@ohos.app.ability.AbilityConstant'; +import common from '@ohos.app.ability.common'; const TAG: string = 'MainAbility'; let isFromCard = false; @@ -52,14 +53,14 @@ export default class MainAbility extends Ability { private isOnDestroy: boolean = false; onCreate(want: Want, param: AbilityConstant.LaunchParam): void { - globalThis.photosAbilityContext = this.context; - globalThis.formContext = this.context + AppStorage.setOrCreate('photosAbilityContext', this.context); + AppStorage.setOrCreate('formContext', this.context); this.isOnDestroy = false; this.initPhotosPref(); this.parseWantParameter(false, want); - UserFileManagerAccess.getInstance().onCreate(globalThis.photosAbilityContext); + UserFileManagerAccess.getInstance().onCreate(AppStorage.get('photosAbilityContext')); MediaObserver.getInstance().registerForAllPhotos(); MediaObserver.getInstance().registerForAllAlbums(); if (!isFromCard && !isFromCamera) { @@ -92,9 +93,9 @@ export default class MainAbility extends Ability { let wantParamUri: string = wantParam?.uri as string; if (wantParamUri === Constants.WANT_PARAM_URI_DETAIL) { isFromCamera = true; - if (isOnNewWant && globalThis.photosWindowStage) { + if (isOnNewWant) { AppStorage.SetOrCreate('entryFromHapCamera', Constants.ENTRY_FROM_CAMERA); - globalThis.photosWindowStage.loadContent('pages/PhotoBrowser', (err, data) => { + AppStorage.get('photosWindowStage').loadContent('pages/PhotoBrowser', (err, data) => { if (err.code) { Log.error(TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; @@ -167,7 +168,7 @@ export default class MainAbility extends Ability { onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created, set main page for this ability Log.info(TAG, 'Application onWindowStageCreate'); - globalThis.photosWindowStage = windowStage; + AppStorage.setOrCreate('photosWindowStage', windowStage); AppStorage.SetOrCreate('deviceType', deviceInfo.deviceType == ('phone' || 'default') ? Constants.DEFAULT_DEVICE_TYPE : Constants.PAD_DEVICE_TYPE); ScreenManager.getInstance().on(ScreenManager.ON_LEFT_BLANK_CHANGED, data => { @@ -322,7 +323,7 @@ export default class MainAbility extends Ability { private initPhotosPref(): void { Log.info(TAG, 'Application initPhotosPref start'); - data_preferences.getPreferences(globalThis.photosAbilityContext, Constants.PHOTOS_STORE_KEY) + data_preferences.getPreferences(AppStorage.get('photosAbilityContext'), Constants.PHOTOS_STORE_KEY) .then((pref: data_preferences.Preferences) => { pref.get(Constants.IS_FIRST_TIME_DELETE, true).then((data: boolean) => { AppStorage.SetOrCreate(Constants.IS_FIRST_TIME_DELETE, data); diff --git a/product/phone/src/main/ets/ServiceExt/ServiceExtAbility.ts b/product/phone/src/main/ets/ServiceExt/ServiceExtAbility.ts index 0a88c0af..bbcd5b0d 100644 --- a/product/phone/src/main/ets/ServiceExt/ServiceExtAbility.ts +++ b/product/phone/src/main/ets/ServiceExt/ServiceExtAbility.ts @@ -1,6 +1,5 @@ - /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,134 +13,135 @@ * limitations under the License. */ -import { - Constants, - ScreenManager, - UserFileManagerAccess, - MediaObserver, - Log -} from '@ohos/common'; +import { Constants, ScreenManager, UserFileManagerAccess, MediaObserver, Log } from '@ohos/common'; import display from '@ohos.display'; import Extension from '@ohos.app.ability.ServiceExtensionAbility'; import Window from '@ohos.window'; import dialogRequest from '@ohos.app.ability.dialogRequest'; -import common from '@ohos.app.ability.common'; +import type common from '@ohos.app.ability.common'; +import type Want from '@ohos.app.ability.Want'; const TAG: string = 'ServiceExtAbility'; export default class ServiceExtAbility extends Extension { + private windowClass; - onCreate(want) { - Log.info(TAG, `ServiceExtAbility want param : ${JSON.stringify(want)}`); + onCreate(want: Want): void { + Log.info(TAG, 'ServiceExtAbility want param:' + JSON.stringify(want)); AppStorage.setOrCreate('windowClass', null); AppStorage.setOrCreate('photosAbilityContext', this.context); AppStorage.SetOrCreate(Constants.SCREEN_SIDEBAR, false); - AppStorage.SetOrCreate("deviceType", Constants.DEFAULT_DEVICE_TYPE); + AppStorage.SetOrCreate('deviceType', Constants.PC_DEVICE_TYPE); } - onRequest(want, startId) { - if (want.action != Constants.ACTION_DELETE_DATA) { + onReconnect(want: Want): void { + Log.info(TAG, 'onReconnect windowClass : ' + this.windowClass); + if (this.windowClass === null || this.windowClass === undefined) { + return; + } + try { + Log.info(TAG, 'test start1'); + this.windowClass.destroyWindow((err): void => { + if (err.code) { + Log.info(TAG, 'Failed to destroy the window. Cause:' + JSON.stringify(err)); + return; + } + Log.info(TAG, 'Succeeded in destroying the window.'); + this.windowClass = null; + }); + Log.info(TAG, 'test done1'); + } catch (e) { + Log.error(TAG, 'fail1 ' + JSON.stringify(e)); + } + } + + + onRequest(want: Want, startId: number): void { + if (want.action !== Constants.ACTION_DELETE_DATA) { return; } UserFileManagerAccess.getInstance().onCreate(AppStorage.get('photosAbilityContext')); MediaObserver.getInstance().registerForAllPhotos(); MediaObserver.getInstance().registerForAllAlbums(); - - let wantParam: {[key:string]: object} = want.parameters; + let wantParam: { [key: string]: Object } = want.parameters; let uris: any = wantParam?.uris; - let appName: string = wantParam?.appName as unknown as string; - Log.info(TAG, `get delete data : ${JSON.stringify(wantParam)}}`); - if (uris == undefined || uris.length ===0) { + let appName: string = wantParam?.appName as string; + Log.info(TAG, 'get delete data : ' + JSON.stringify(wantParam)); + if (!uris?.length) { return; } - AppStorage.SetOrCreate("uris", uris); - AppStorage.SetOrCreate("appName", appName); - - let windowClass = globalThis.windowClassg; + AppStorage.SetOrCreate('uris', uris); + AppStorage.SetOrCreate('appName', appName); + this.windowClass = AppStorage.get('windowClassg'); + let config: Window.Configuration = { + name: 'DeleteDialog ' + appName + Math.random(), windowType: Window.WindowType.TYPE_DIALOG, ctx: this.context + }; try { - let config = { - name: "DeleteDialog " + appName + Math.random(), windowType: Window.WindowType.TYPE_DIALOG, ctx: this.context - } - try { - Window.createWindow(config, (err, data) => { - if (err.code) { - Log.info(TAG, `Failed to create the window. Cause : ${JSON.stringify(err)}`); - return; - } - windowClass = data; - Log.info(TAG, `Success ded in creating the window. Data : ${JSON.stringify(data)}`); - try { - let requestInfo = dialogRequest.getRequestInfo(want); - Log.info(TAG, `requestInfo param : ${JSON.stringify(requestInfo)}`); - - var requestCallback = dialogRequest.getRequestCallback(want); - AppStorage.SetOrCreate("requestCallback", requestCallback); - Log.info(TAG, `Succeeded in get requestCallback`); - - windowClass.bindDialogTarget(requestInfo, () => { - Log.info(TAG, 'Dialog Window Need Destroy.'); - }, (err) => { - Log.error(TAG, 'Dialog bindDialogTarget err'); - if (err.code) { - Log.error(TAG, `Failed to bind dialog target. Cause : ${JSON.stringify(err)}`); - return; - } - Log.error(TAG, 'Succeeded in binding dialog target.'); - try { - windowClass.setUIContent('pages/ResourceDeletePage', (err) => { - if (err.code) { - Log.error(TAG, `Failed to load the content. Cause : ${JSON.stringify(err)}`); - return; - } - Log.error(TAG, `Succeeded in loading the content`); - let promise = display.getDefaultDisplay(); - promise.then((data) => { - Log.error(TAG, `Succeeded in loading the content, width : ${data.width}, height : ${data.height}`); - ScreenManager.getInstance().setWinWidth(px2vp(data.width)); - windowClass.resetSize(data.width, data.height); - windowClass.setBackgroundColor('#00000000'); - windowClass.show(); - }) - }) - } catch (err) { - Log.error(TAG, `getDefaultDisplay fail : ${JSON.stringify(err)}`); - } - }) - Log.info(TAG, 'bindDialogTarget done'); - } catch (exception) { - Log.error(TAG, `Failed to load the content. Cause : ${JSON.stringify(exception)}`); - } - }) - } catch (exception) { - Log.error(TAG, `Failed to bind the window. Cause : ${JSON.stringify(exception)}`); - } - } catch { - Log.error(TAG, `Failed`); + Window.createWindow(config, (err, data): void => { //创建模态窗口 + if (err.code) { + Log.info(TAG, 'Failed to create the window. Cause: ' + JSON.stringify(err)); + return; + } + this.windowClass = data; + Log.info(TAG, 'Success ded in creating the window. Data: '); + this.bindDialogTarget(want); + }); + } catch (exception) { + Log.info(TAG, 'Failed to create the window. Cause: ' + JSON.stringify(exception)); } - - globalThis.onStart1 = (() => { - try { - Log.info(TAG, 'test start1'); - windowClass.destroyWindow((err) => { - if (err.code) { - Log.info(TAG, `Failed to destroy the window. Cause : ${JSON.stringify(err)}`); - return; - } - Log.info(TAG, `Succeeded in destroying the window.`); - windowClass = null; - }); - } catch (e) { - Log.info(TAG, `Failed 1 : ${JSON.stringify(e)}`); - } - }); } - onDisconnect(want) { + private bindDialogTarget(want: Want): void { + try { + let requestInfo: dialogRequest.RequestInfo = dialogRequest.getRequestInfo(want); //从Want中获取请求方的RequestInfo + Log.info(TAG, 'requestInfo param:' + JSON.stringify(requestInfo)); + + let requestCallback: dialogRequest.RequestCallback = dialogRequest.getRequestCallback(want); + AppStorage.SetOrCreate('requestCallback', requestCallback); + + this.windowClass.bindDialogTarget(requestInfo, (): void => { //绑定模态窗口与目标窗口 + Log.info(TAG, 'Dialog Window Need Destroy.'); + }, (err): void => { + if (err.code) { + Log.info(TAG, 'Failed to bind dialog target. Cause:' + JSON.stringify(err)); + return; + } + Log.info(TAG, 'Succeeded in binding dialog target.'); + this.setContentUI(); + }); + } catch (exception) { + Log.error(TAG, 'Failed to bind dialog target. Cause:' + JSON.stringify(exception)); + } + } + + private setContentUI(): void { + try { + this.windowClass.setUIContent('pages/ResourceDeletePage', (err): void => { + if (err.code) { + Log.info(TAG, 'Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + Log.info(TAG, 'Succeeded in loading the content.'); + display.getDefaultDisplay().then((data): void => { + Log.info(TAG, 'Succeeded in loading the content.' + data.width + ', ' + data.height); + ScreenManager.getInstance().setWinWidth(px2vp(data.width)); + this.windowClass.resetSize(data.width, data.height); //设置窗口全屏 + this.windowClass.setBackgroundColor('#00000000'); //设置窗口背景透明 + this.windowClass.show(); + }).catch((err): void => { + Log.error(TAG, 'getDefaultDisplay fail: ' + JSON.stringify(err)); + }); + }); + } catch (exception) { + Log.error(TAG, 'Failed to load the content. Cause:' + JSON.stringify(exception)); + } + } + + onDisconnect(want: Want): void { Log.info(TAG, `onDisconnect, want: ${want.abilityName}`); } - onDestroy() { + onDestroy(): void { Log.info(TAG, 'onDestroy'); } - } \ No newline at end of file diff --git a/product/phone/src/main/ets/pages/AlbumSelect.ets b/product/phone/src/main/ets/pages/AlbumSelect.ets index 8e505bb0..2be2b409 100644 --- a/product/phone/src/main/ets/pages/AlbumSelect.ets +++ b/product/phone/src/main/ets/pages/AlbumSelect.ets @@ -17,6 +17,7 @@ import router from '@ohos.router'; import { AlbumSelectGridItemNewStyle, NewAlbumPageActionBar } from '@ohos/browser/BrowserComponents'; import { Action, + AlbumSetDataInfo, AlbumSetDataSource, BroadCast, BroadCastConstants, @@ -34,6 +35,12 @@ import { NoPhotoComponent } from '@ohos/common/CommonComponents'; const TAG: string = 'AlbumSelect'; +interface Params { + albumName: string; + albumUri: string; + isNewAlbum: boolean; +}; + @Entry @Component export struct AlbumSelect { @@ -45,29 +52,37 @@ export struct AlbumSelect { = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; private isActive = false; private scroller: Scroller = new Scroller(); - private albums: AlbumSetDataSource; + private albums: AlbumSetDataSource = new AlbumSetDataSource(this.broadCast); private dataSource: MediaDataSource = new MediaDataSource(Constants.DEFAULT_SLIDING_WIN_SIZE); private mSelectManager = new SelectManager(); - private currentAlbumUri: string; - private newAlbumName: string; - onWindowSizeChangeCallBack = () => { + private currentAlbumUri: string = ''; + private newAlbumName: string = ''; + private onWindowSizeChangeFunc: Function = (): void => this.onWindowSizeChange(); + private onLoadingFinshedFunc: Function = (size: number): void => this.onLoadingFinshed(size); + + private onLoadingFinshed(size: number): void { + Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); + this.isEmpty = size == 0; + } + + private onWindowSizeChange(): void { // 后续phone缩略图支持横竖屏后再放开 - // this.gridColumnsCount = UiUtil.getAlbumGridCount(false); + if (AppStorage.get('deviceType') !== Constants.DEFAULT_DEVICE_TYPE) { + // Waiting: 后续phone的宫格页,支持横竖屏后,再放开 + this.gridColumnsCount = UiUtil.getAlbumGridCount(false); + } } aboutToAppear(): void { TraceControllerUtils.startTrace('AlbumSetPageAboutToAppear'); - this.broadCast.on(Constants.ON_LOADING_FINISHED, (size: number) => { - Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); - this.isEmpty = size == 0; - }); + this.broadCast.on(Constants.ON_LOADING_FINISHED, this.onLoadingFinshedFunc); this.albums = new AlbumSetDataSource(this.broadCast); this.onActive(); this.gridColumnsCount = UiUtil.getAlbumGridCount(false); Log.info(TAG, `the grid count in a line is: ${this.gridColumnsCount}`); - ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); + ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeFunc); - let param: any = router.getParams(); + let param: Params = router.getParams() as Params; if (param) { this.newAlbumName = param.albumName; this.currentAlbumUri = param.albumUri; @@ -80,7 +95,6 @@ export struct AlbumSelect { this.albums.setBlackList([this.currentAlbumUri, UserFileManagerAccess.getInstance() .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)]); Log.info(TAG, `the album uri is: ${this.currentAlbumUri}`); - this.onMenuClicked = this.onMenuClicked.bind(this); AppStorage.SetOrCreate(Constants.APP_KEY_NEW_ALBUM_TARGET, this.newAlbumName); AppStorage.SetOrCreate(Constants.APP_KEY_NEW_ALBUM_TARGET_URI, this.currentAlbumUri); AppStorage.SetOrCreate(Constants.APP_KEY_NEW_ALBUM_SELECTED, this.mSelectManager); @@ -88,9 +102,8 @@ export struct AlbumSelect { } aboutToDisappear(): void { - this.broadCast.off(null, null); - ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; + ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeFunc); + this.broadCast.off(Constants.ON_LOADING_FINISHED, this.onLoadingFinshedFunc); this.albums.setBlackList([]); this.dataSource.releaseBroadCast(); } @@ -130,21 +143,21 @@ export struct AlbumSelect { justifyContent: FlexAlign.Start, alignItems: ItemAlign.Start }) { - NewAlbumPageActionBar({ onMenuClicked: this.onMenuClicked }) + NewAlbumPageActionBar({ onMenuClicked: (action: Action): void => this.onMenuClicked(action) }) Stack() { if (this.isEmpty) { NoPhotoComponent({ title: $r('app.string.title_no_albums') }) } Grid(this.scroller) { - LazyForEach(this.albums, (item, index?: number) => { + LazyForEach(this.albums, (item: AlbumSetDataInfo, index?: number) => { GridItem() { AlbumSelectGridItemNewStyle({ item: item.data, mSelectManager: this.mSelectManager }) }.key('SelectAlbum' + index) - }, item => 'uri:' + item.data.uri) + }, (item: AlbumSetDataInfo) => 'uri:' + item.data.uri) } .edgeEffect(EdgeEffect.Spring) .scrollBar(BarState.Auto) @@ -168,15 +181,11 @@ export struct AlbumSelect { private onMenuClicked(action: Action): void { Log.debug(TAG, `onMenuClicked, action: ${action.actionID}`); - switch (action.actionID) { - case Action.CANCEL.actionID: - Log.info(TAG, 'clear SelectManager data'); - this.mSelectManager.onModeChange(false); - AppStorage.Delete(Constants.APP_KEY_NEW_ALBUM_SELECTED); - router.back(); - break; - default: - break; + if (action.actionID === Action.CANCEL.actionID) { + Log.info(TAG, 'clear SelectManager data'); + this.mSelectManager.onModeChange(false); + AppStorage.Delete(Constants.APP_KEY_NEW_ALBUM_SELECTED); + router.back(); } return; } diff --git a/product/phone/src/main/ets/pages/DefaultPhotoPage.ets b/product/phone/src/main/ets/pages/DefaultPhotoPage.ets index 148d31c7..df3faacb 100644 --- a/product/phone/src/main/ets/pages/DefaultPhotoPage.ets +++ b/product/phone/src/main/ets/pages/DefaultPhotoPage.ets @@ -48,7 +48,7 @@ export struct DefaultPhotoPage { @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - defaultMediaItem: MediaItem; + defaultMediaItem: MediaItem | undefined = undefined; @StorageLink('statusBarHeight') statusBarHeight: number = 0; @State backgroundColorResource: Resource = $r('app.color.default_background_color'); @State isShowBar: boolean = true; @@ -58,17 +58,15 @@ export struct DefaultPhotoPage { @State isRunningAnimation: boolean = false; @State isOnSwiperAnimation: boolean = false; @Provide hidePopup: boolean = false; + private onToggleBarsFunc: Function = (): void => this.onToggleBars(); + private hideBarsFunc: Function = (): void => this.hideBars(); onMenuClicked(action: Action) { Log.info(TAG, `onMenuClicked, action: ${action.actionID}`); - switch (action.actionID) { - case Action.BACK.actionID: - router.replaceUrl({ - url: 'pages/index', - }); - break; - default: - break; + if (action.actionID === Action.BACK.actionID) { + router.replaceUrl({ + url: 'pages/index', + }); } } @@ -76,18 +74,12 @@ export struct DefaultPhotoPage { if (!this.isShowBar) { ScreenManager.getInstance().setSystemUi(true); } - this.onMenuClicked = this.onMenuClicked.bind(this); this.defaultMediaItem = this.getDefaultMediaItem(); this.actionBarProp .setLeftAction(Action.BACK) .setMode(ActionBarMode.STANDARD_MODE); - this.broadCast.on(PhotoConstants.TOGGLE_BAR, () => { - this.onToggleBars(); - }); - - this.broadCast.on(PhotoConstants.HIDE_BARS, () => { - this.hideBars(); - }); + this.broadCast.on(PhotoConstants.TOGGLE_BAR, this.onToggleBarsFunc); + this.broadCast.on(PhotoConstants.HIDE_BARS, this.hideBarsFunc); } onPageShow() { @@ -121,11 +113,14 @@ export struct DefaultPhotoPage { } aboutToDisappear(): void { - this.broadCast.off(null, null); + if (this.broadCast) { + this.broadCast.off(PhotoConstants.TOGGLE_BAR, this.onToggleBarsFunc); + this.broadCast.off(PhotoConstants.HIDE_BARS, this.hideBarsFunc); + } } getDefaultMediaItem(): MediaItem { - return new MediaItem(null) + return new MediaItem() } build() { @@ -141,7 +136,7 @@ export struct DefaultPhotoPage { isDefaultFA: true }) Column() { - ActionBar({ actionBarProp: $actionBarProp, onMenuClicked: this.onMenuClicked, isNeedPlaceholder: false }) + ActionBar({ actionBarProp: $actionBarProp, onMenuClicked: (action: Action): void => this.onMenuClicked(action), isNeedPlaceholder: false }) } .visibility(this.isShowBar ? Visibility.Visible : Visibility.Hidden) .padding({ diff --git a/product/phone/src/main/ets/pages/EditMain.ets b/product/phone/src/main/ets/pages/EditMain.ets index e29354a1..7852dc2f 100644 --- a/product/phone/src/main/ets/pages/EditMain.ets +++ b/product/phone/src/main/ets/pages/EditMain.ets @@ -38,7 +38,6 @@ export struct EditMain { @Provide editorManager: PhotoEditorManager = PhotoEditorManager.getInstance(); @Provide('compare') isCompare: boolean = false; @Provide('angle') rotateAngle: number = Constants.NUMBER_0; - @Provide confirmToolBarText: Resource = undefined; @Provide isCropReset: boolean = false; @Provide isBigTextShow: boolean = false; @Provide bigText: string = ''; @@ -49,7 +48,7 @@ export struct EditMain { @Provide('verticalScreen') isVerticalScreen: boolean = !ScreenManager.getInstance().isHorizontal(); @Provide screenWidth: number = Constants.NUMBER_0; @Provide screenHeight: number = Constants.NUMBER_0; - @Provide cropEdit: PhotoEditCrop = undefined; + @Provide cropEdit: PhotoEditCrop | undefined = undefined; @Provide isRedo: boolean = false; @Provide isUndo: boolean = false; @Provide isMagnifier: boolean = false; @@ -66,11 +65,11 @@ export struct EditMain { @State imageScaleWidth: number = Constants.NUMBER_0; appEventBus: BroadCast = BroadCastManager.getInstance().getBroadCast(); @StorageLink('currentBreakpoint') @Watch('updateIsVerticalScreen') currentBreakpoint: string = Constants.BREAKPOINT_MD; - private mediaItem: MediaItem = globalThis.EditorMediaItem; + private mediaItem: MediaItem = AppStorage.get('EditorMediaItem') as MediaItem; private screenManager = ScreenManager.getInstance(); private isLoadFailed: boolean = false; - private albumUri: string = globalThis.EditorAlbumUri; - onWindowSizeChangeCallBack = () => this.updateIsVerticalScreen(); + private albumUri: string = AppStorage.get('EditorAlbumUri') as string; + private onWindowSizeChangeCallBack: Function = (): void => this.updateIsVerticalScreen(); updateIsVerticalScreen(): void { if (this.currentBreakpoint == Constants.BREAKPOINT_LG) { @@ -95,7 +94,7 @@ export struct EditMain { onBackPress(): boolean { if (this.isCropReset) { - this.broadCast.emit(BroadCastConstants.SHOW_EDIT_EXIT_PHOTO_DIALOG, [this.discardCallback.bind(this)]); + this.broadCast.emit(BroadCastConstants.SHOW_EDIT_EXIT_PHOTO_DIALOG, [(): void => this.discardCallback()]); } else { router.back(); } @@ -116,19 +115,19 @@ export struct EditMain { if (this.mediaItem) { this.isLoadFailed = false; this.editorManager.initialize( - this.mediaItem, this.albumUri, PhotoEditMode.EDIT_MODE_CROP, this.loadFailedCallback.bind(this)); + this.mediaItem, this.albumUri, PhotoEditMode.EDIT_MODE_CROP, (): void => this.loadFailedCallback()); } this.cropEdit = this.editorManager.getPhotoEditBaseInstance(PhotoEditMode.EDIT_MODE_CROP) as PhotoEditCrop; ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); this.updateIsVerticalScreen(); - ReportToBigDataUtil.report(BigDataConstants.ENTER_PHOTO_EDIT_ID, null); + ReportToBigDataUtil.report(BigDataConstants.ENTER_PHOTO_EDIT_ID, undefined); } aboutToDisappear(): void { ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; Log.debug(TAG, 'aboutToDisappear'); - globalThis.EditorMediaItem = undefined; + + AppStorage.setOrCreate('EditorMediaItem', undefined); PhotoEditorManager.getInstance().clear(); ScreenManager.getInstance().setSystemUi(true); } diff --git a/product/phone/src/main/ets/pages/FormEditorPage.ets b/product/phone/src/main/ets/pages/FormEditorPage.ets index 616e6970..5024d212 100644 --- a/product/phone/src/main/ets/pages/FormEditorPage.ets +++ b/product/phone/src/main/ets/pages/FormEditorPage.ets @@ -20,6 +20,7 @@ import { BroadCast, BroadCastConstants, BroadCastManager, + ColumnSize, Constants as Cons, DataStoreUtil, Log, @@ -27,14 +28,20 @@ import { ScreenManager, UiUtil, UserFileManagerAccess, + WindowUtil } from '@ohos/common'; import { Constants, FormControllerManager } from '@ohos/formAbility'; import formBindingData from '@ohos.application.formBindingData'; import formProvider from '@ohos.application.formProvider'; import userFileManager from '@ohos.filemanagement.userFileManager'; +import common from '@ohos.app.ability.common'; +import { BusinessError } from '@ohos.base'; +import { Router } from '@ohos.arkui.UIContext'; const TAG: string = 'FormEditorPage'; +declare type UnionType = number | boolean | string; +declare type DisplayNameUnionType = Resource | string; @Entry @Component @@ -42,29 +49,31 @@ struct FormEditorPage { @StorageLink('FASetting_FormId') formId: string = '0'; @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal(); @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar(); - @StorageLink('leftBlank') leftBlank: number[] - = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; + @StorageLink('leftBlank') leftBlank: number[] = + [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; currentIndex: number = 0; @State isShowName: boolean = true; isShowAlbums: boolean = true; fd: number = Constants.FA_FD_NULL; - fileAsset: userFileManager.FileAsset = null; + fileAsset: userFileManager.FileAsset | null = null; displayName: string = ''; albumUri: string = ''; uri: string = ''; @State time: number = 30; private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); - private saveDataFunc = this.saveData.bind(this); + private saveDataFunc = async ( + albumName: string, albumUri: string, displayName: DisplayNameUnionType, uri: string, isShowAlbums: boolean + ): Promise => await this.saveData(albumName, albumUri, displayName, uri, isShowAlbums); private indexValue: number = 0; @State private selectAlbumsStr: string = ''; async getItems(albumUri?: string, startIndex?: number, count?: number, filterMediaType?: string): Promise> { - let result: Array = null; + let result: Array = []; // Get from target album if albumUri is not undefined, otherwise getAllObject if (albumUri) { - let album: userFileManager.Album = await UserFileManagerAccess.getInstance().getAlbumByUri(albumUri); + let album: userFileManager.Album = await UserFileManagerAccess.getInstance().getAlbumByUri(albumUri) as userFileManager.Album; let fetchOpt = AlbumDefine.getFileFetchOpt(startIndex, count, filterMediaType); let fetchResult = await album.getPhotoAssets(fetchOpt); result = await fetchResult.getAllObject(); @@ -77,8 +86,8 @@ struct FormEditorPage { return result; } - async GetMediaData(albumUri: string, uri: string) { - Log.debug(TAG, `GetMediaData start uri: ${uri} albumUri: ${albumUri}`) + async GetMediaData(albumUri: string, uri: string): Promise { + Log.debug(TAG, `GetMediaData start uri: ${uri} albumUri: ${albumUri}`); let dataList = await this.getItems(albumUri); if (uri != '') { for (let i = 0; i < dataList.length; i++) { @@ -95,26 +104,37 @@ struct FormEditorPage { Log.debug(TAG, 'GetMediaData fileAsset: ' + JSON.stringify(this.fileAsset)); } - async openCurrentfd() { - this.fd = (this.fileAsset != null) ? await UserFileManagerAccess.getInstance().openAsset('R', this.fileAsset) - : Constants.FA_FD_NULL; + async openCurrentFd(): Promise { + this.fd = (this.fileAsset != null) ? await UserFileManagerAccess.getInstance().openAsset('R', this.fileAsset) as number + : Constants.FA_FD_NULL; } bindFormData(): formBindingData.FormBindingData { - Log.debug(TAG, `bindFormData start formId: ${this.formId}`) - let image: string = 'image_' + this.fd + '_formId_' + this.formId; - let dataObj1: object = { - "fd": this.fd == Constants.FA_FD_NULL ? false : true, - "image0": "memory://" + image, - "image1": "memory://" + image, - "indexValue": this.indexValue, - "albumName": this.displayName, - "currentIndex": this.currentIndex, - "isShow": Boolean(this.isShowName) && Boolean(this.isShowAlbums), - "formImages": JSON.parse(`{ "${image}": ${this.fd} }`), - "uri": (this.uri != '') ? Cons.ACTION_URI_FORM_ABILITY : Cons.ACTION_URI_FORM_ABILITY_NONE, - "albumUri": `${this.albumUri}`, - "currentUri": this.uri + Log.debug(TAG, `bindFormData start formId: ${this.formId}`); + let image: string = 'image_' + this.fd + '_formId_' + this.formId + '_uri_' + this.uri; + interface DataObjectType { + fd: boolean; + image0: string; + image1: string; + albumName: string; + currentIndex: number; + isShow: boolean; + formImages: object; + uri: string; + albumUri: string; + currentUri: string; + } + let dataObj1: DataObjectType = { + fd: this.fd != Constants.FA_FD_NULL, + image0: 'memory://' + image, + image1: 'memory://' + image, + albumName: this.displayName, + currentIndex: this.currentIndex, + isShow: Boolean(this.isShowName) && Boolean(this.isShowAlbums), + formImages: JSON.parse(`{ "${image}": ${this.fd} }`) as object, + uri: (this.uri != '') ? Cons.ACTION_URI_FORM_ABILITY : Cons.ACTION_URI_FORM_ABILITY_NONE, + albumUri: `${this.albumUri}`, + currentUri: this.uri }; Log.debug(TAG, `bindFormData, createFormBindingData dataObj2.data: ${JSON.stringify(dataObj1)}`); let obj = formBindingData.createFormBindingData(JSON.stringify(dataObj1)); @@ -122,48 +142,49 @@ struct FormEditorPage { return obj; } - terminate() { - globalThis.photosAbilityContext.terminateSelf((result) => { + terminate(): void { + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelf((result: BusinessError) => { Log.info(TAG, `terminateSelf result: ${JSON.stringify(result)}`); }) } - async updateFormData() { + async updateFormData(): Promise { Log.debug(TAG, `updateFormData formId: ${JSON.stringify(this.formId)}`); let dataStore = DataStoreUtil.getInstance(); await dataStore.init(); - let temp = await dataStore.getData(Constants.FA_INDEX_VALUE, 0); - this.indexValue = (temp + Constants.NUMBER_1) % Constants.NUMBER_2; + let temp: number = await dataStore.getData(Constants.FA_INDEX_VALUE, 0) as number; + this.indexValue = (temp + 1) % 2; await dataStore.putData(Constants.FA_INDEX_VALUE, this.indexValue); await dataStore.flush(); - await this.GetMediaData(this.albumUri, this.uri); - await this.openCurrentfd(); let obj3 = this.bindFormData(); Log.debug(TAG, `updateFormData obj: ${JSON.stringify(obj3)}`); - Log.debug(TAG, `indexValueindexValueindexValue: ${this.indexValue}`); formProvider.updateForm(this.formId, obj3) - .then(() => { - Log.debug(TAG, `updateFormData, success`); + .then((): void => { + Log.debug(TAG, 'updateFormData, success'); this.terminate(); - }).catch((error) => { + }).catch((error: BusinessError) => { Log.error(TAG, `updateForm failed. Cause: ${JSON.stringify(error)}`); - let msg = { - 'err': JSON.stringify(error) + interface Msg { + err: string; + } + let msg: Msg = { + err: JSON.stringify(error) } ReportToBigDataUtil.errEventReport(BigDataConstants.CHANGE_FA_CARD_IMAGE_ERROR, msg); this.terminate(); }); } - async saveData(albumName: string, albumUri: string, displayName, uri: string, isShowAlbums: boolean) { - Log.debug(TAG, `saveData start! ${albumUri} ${displayName} ${uri}`) - ReportToBigDataUtil.report(BigDataConstants.CHANGE_FA_CARD_IMAGE_ID, null); - let msgDisplayName: string = ''; + async saveData(albumName: string, albumUri: string, displayName: DisplayNameUnionType, uri: string, isShowAlbums: boolean): Promise { + Log.debug(TAG, `saveData start! ${albumUri} ${displayName} ${uri}`); + ReportToBigDataUtil.report(BigDataConstants.CHANGE_FA_CARD_IMAGE_ID, undefined); + let msgDisplayName = ''; if (displayName instanceof Object) { Log.debug(TAG, `saveData object ${displayName}`); - msgDisplayName = await UiUtil.getResourceString(displayName); + msgDisplayName = await UiUtil.getResourceString(displayName as Resource) as string; } else { - msgDisplayName = displayName; + msgDisplayName = displayName as string; } this.isShowAlbums = isShowAlbums; this.displayName = msgDisplayName; @@ -171,6 +192,8 @@ struct FormEditorPage { this.uri = uri; Log.debug(TAG, `saveData msgDisplayName ${msgDisplayName}`); await DataStoreUtil.getInstance().init(); + await this.GetMediaData(albumUri, uri); + await this.openCurrentFd(); let formIdKey = 'formId_' + this.formId; let hasFormId = await DataStoreUtil.getInstance().hasData(formIdKey); Log.debug(TAG, `The value of hasFormId is ${hasFormId}`); @@ -183,66 +206,50 @@ struct FormEditorPage { await DataStoreUtil.getInstance().putData(albumUriKey, albumUri); let currentUriKey = 'currentUri_' + this.formId; await DataStoreUtil.getInstance().putData(currentUriKey, uri); - let intervalTimeKey = 'intervalTime_' + this.formId; - await DataStoreUtil.getInstance().putData(intervalTimeKey, this.time); let currentIndexKey = 'currentIndex_' + this.formId; await DataStoreUtil.getInstance().putData(currentIndexKey, this.currentIndex); - let isShowKey = 'isShowAlbums_' + this.formId; - await DataStoreUtil.getInstance().putData(isShowKey, this.isShowAlbums ? 1 : 0); await DataStoreUtil.getInstance().flush(); this.updateFormData(); } else { - globalThis.photosAbilityContext.terminateSelf((result) => { + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelf((result: BusinessError) => { Log.info(TAG, `terminateSelf result: ${JSON.stringify(result)}`); }) } - Log.debug(TAG, 'meow saveData end!'); + Log.debug(TAG, 'saveData end!'); } - routerPhotos(isSelectPhoto: boolean) { - let options = { - url: 'pages/ThirdSelectPhotoGridPage', - params: { - itemCoverUri: '', - uri: "", - itemCount: 1, - bundleName: '', - isMultiPick: false, - filterMediaType: AlbumDefine.FILTER_MEDIA_TYPE_IMAGE, - maxSelectCount: Cons.NUMBER_1, - itemDisplayName: $r('app.string.album_all'), - isFromFa: isSelectPhoto, - isFromFaPhoto: isSelectPhoto, - isFirstEnter: true - } - } - router.pushUrl(options); + routerPhotos(isSelectPhoto: boolean): void { + let albumUriKey = 'albumUri_' + this.formId; + DataStoreUtil.getInstance().getData(albumUriKey, '').then((theAlbumUri: UnionType) => { + let options: router.RouterOptions = { + url: 'pages/ThirdSelectPhotoGridPage', + params: { + itemCoverUri: '', + uri: theAlbumUri, + itemCount: 1, + bundleName: '', + isMultiPick: false, + filterMediaType: AlbumDefine.FILTER_MEDIA_TYPE_IMAGE, + maxSelectCount: 1, + itemDisplayName: $r('app.string.album_photos'), + isFromFa: isSelectPhoto, + isFromFaPhoto: isSelectPhoto, + isFirstEnter: true + } + }; + router.pushUrl(options); + }) } - selectPhoto() { + selectPhoto(): void { this.routerPhotos(true); } aboutToAppear(): void { - Log.debug(TAG, 'aboutToAppear start!') + Log.debug(TAG, 'aboutToAppear start!'); ScreenManager.getInstance().setSystemUi(false); this.appBroadCast.on(BroadCastConstants.SAVE_FORM_EDITOR_DATA, this.saveDataFunc); - DataStoreUtil.getInstance().init().then(() => { - let intervalTimeKey = 'intervalTime_' + this.formId; - DataStoreUtil.getInstance().getData(intervalTimeKey, this.time).then((intervalTime) => { - this.time = intervalTime; - AppStorage.SetOrCreate(Constants.FROM_PLAYBACK_INTERVAL, this.time); - }) - let isShowKey = Constants.FROM_PLAYBACK_ISSHOWNAME; - DataStoreUtil.getInstance().getData(isShowKey, this.isShowName).then((isShowName) => { - Log.debug(TAG, `aboutToAppear isShowKey:` + JSON.stringify(isShowKey) + JSON.stringify(Boolean(isShowName))) - this.isShowName = isShowName; - }) - }) - UiUtil.getResourceString($r('app.string.fa_select_album_text')).then((stringResource) => { - Log.debug(TAG, `getResourceString ${stringResource}}`) - this.selectAlbumsStr = stringResource; - }) } aboutToDisappear() { @@ -313,7 +320,7 @@ struct FormEditorPage { }) .backgroundColor($r('app.color.white')) .borderRadius($r('app.float.FA_ListCard_radius')) - .onClick(() => { + .onClick((): void => { this.selectPhoto(); }) } diff --git a/product/phone/src/main/ets/pages/NewAlbumPage.ets b/product/phone/src/main/ets/pages/NewAlbumPage.ets index ed33b6eb..cd3e9536 100644 --- a/product/phone/src/main/ets/pages/NewAlbumPage.ets +++ b/product/phone/src/main/ets/pages/NewAlbumPage.ets @@ -16,6 +16,7 @@ import router from '@ohos.router'; import { Action, + AlbumInfo, BroadCast, BroadCastConstants, BroadCastManager, @@ -45,6 +46,10 @@ import { SelectPhotoBrowserView } from '../view/SelectPhotoBrowserView'; const TAG: string = 'NewAlbumPage'; AppStorage.SetOrCreate('PhotoGridPageIndex', Constants.INVALID); +interface Params { + item: string; +} + @Entry @Component export struct NewAlbumPage { @@ -65,7 +70,7 @@ export struct NewAlbumPage { @StorageLink('isSplitMode') isSplitMode: boolean = ScreenManager.getInstance().isSplitMode(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - title: string; + title: string = ''; @StorageLink('placeholderIndex') @Watch('onPlaceholderChanged') placeholderIndex: number = -1; @State pageStatus: boolean = false; @State isRunningAnimation: boolean = false; @@ -73,14 +78,83 @@ export struct NewAlbumPage { private dataSource: MediaDataSource = new MediaDataSource(Constants.DEFAULT_SLIDING_WIN_SIZE); private scroller: Scroller = new Scroller(); private isDataFreeze = false; - private mSelectManager: SelectManager; + private mSelectManager: SelectManager | null = null; private isActive = false; private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); - private isNewAlbum: boolean = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM); - onWindowSizeChangeCallBack = () => { + private isNewAlbum: boolean = AppStorage.get(Constants.APP_KEY_NEW_ALBUM) as boolean; + private onWindowSizeChangeCallBack: Function = () => { // 后续phone缩略图支持横竖屏后再放开 // this.initGridRowCount; } + private onUpdateFavorStateFunc: Function = (item: MediaItem): void => this.onUpdateFavorState(item); + private selectFunc: Function = (position: number, key: string, value: boolean, callback: Function): void => this.select(position, key, value, callback); + private jumpPhotoBrowserFunc: Function = (name: string, item: MediaItem): void => this.jumpPhotoBrowser(name, item); + private jumpThirdPhotoBrowserFunc: Function = (name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void => + this.jumpThirdPhotoBrowser(name, item, geometryTapIndex, geometryTransitionString); + private onDataReloadedFunc: Function = (size: number): void => this.onDataReloaded(size); + private onLoadingFinishedFunc: Function = (): void => this.onLoadingFinished(); + + private select(position: number, key: string, value: boolean, callback: Function): void { + if (this.mSelectManager?.toggle(key, value, position)) { + Log.info(TAG, 'enter event process'); + callback(); + } + } + + private jumpPhotoBrowser(name: string, item: MediaItem): void { + let targetIndex = this.dataSource.getDataIndex(item); + if (targetIndex == Constants.NOT_FOUND) { + Log.error(TAG, 'targetIndex is not found'); + return; + } + Log.info(TAG, `jump to photo browser at index: ${targetIndex}`); + AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, this.dataSource); + interface Params { + position: number; + transition: string; + leftBlank: number[]; + } + let params: Params = { + position: targetIndex, + transition: name, + leftBlank: this.leftBlank, + } + this.browserController.showBrowserWithNoAnimation(params); + } + + private jumpThirdPhotoBrowser(name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void { + let targetIndex = this.dataSource.getDataIndex(item); + Log.info(TAG, `jump to photo browser, index: ${targetIndex}, transition: ${name}`); + AppStorage.SetOrCreate(Constants.PHOTO_GRID_SELECT_MANAGER, this.mSelectManager); + AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, this.dataSource); + interface Params { + position: number; + transition: string; + leftBlank: number[]; + } + + const params: Params = { + position: targetIndex, + transition: name, + leftBlank: this.leftBlank, + }; + if (geometryTapIndex && geometryTransitionString) { + this.browserController.showSelectBrowser(geometryTapIndex, geometryTransitionString, TAG, params); + } else { + this.browserController.showSelectBrowserWithNoAnimation(params); + } + } + + private onDataReloaded(size: number): void { + Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); + this.isEmpty = size == 0; + Log.info(TAG, `isEmpty: ${this.isEmpty}`); + } + + private onLoadingFinished(): void { + Log.info(TAG, 'ON_DATA_RELOADED'); + this.dataSource.onDataReloaded(); + } onIndexChange() { Log.info(TAG, `onIndexChange ${this.PhotoGridPageIndex}`) @@ -98,44 +172,25 @@ export struct NewAlbumPage { onMenuClicked(action: Action) { Log.info(TAG, `onMenuClicked, action: ${action.actionID}`); - switch (action.actionID) { - case Action.CANCEL.actionID: - router.back(); - break; - case Action.OK.actionID: - if (this.mSelectManager.getSelectedCount() == 0) { - Log.info(TAG, `onMenuClicked, action: ${action.actionID}, count = 0`); - break; - } - Log.info(TAG, `onMenuClicked, action: ${action.actionID} newAlbum: ${this.isNewAlbum}`); - if (this.isNewAlbum) { - AppStorage.SetOrCreate(Constants.IS_SHOW_MOVE_COPY_DIALOG, true); - let url = 'pages/index'; - router.back({ - url: url, - params: { - jumpSource: JumpSourceToMain.ALBUM, - } - }) - } else { - MoveOrCopyBroadCastProp.getInstance().doAddOperation(this.broadCast); - } - break; - default: - break; - } - } - - freezeAdapter(fn): Function { - let self = this; - return function () { - self.isDataFreeze = AppStorage.Get(Constants.IS_DATA_FREEZE); - if (self.isDataFreeze) { - return; + if (action.actionID === Action.CANCEL.actionID) { + router.back(); + } else if (action.actionID === Action.OK.actionID) { + if (this.mSelectManager?.getSelectedCount() == 0) { + Log.info(TAG, `onMenuClicked, action: ${action.actionID}, count = 0`); + } + Log.info(TAG, `onMenuClicked, action: ${action.actionID} newAlbum: ${this.isNewAlbum}`); + if (this.isNewAlbum) { + AppStorage.SetOrCreate(Constants.IS_SHOW_MOVE_COPY_DIALOG, true); + let url = 'pages/index'; + router.back({ + url: url, + params: { + jumpSource: JumpSourceToMain.ALBUM, + } + }) + } else { + MoveOrCopyBroadCastProp.getInstance().doAddOperation(this.broadCast); } - let context = this; - let args = arguments; - fn.apply(context, args); } } @@ -162,7 +217,7 @@ export struct NewAlbumPage { this.isActive = true; this.dataSource && this.dataSource.onActive(); - if (this.isSelectedMode) { + if (this.isSelectedMode && this.mSelectManager) { this.totalSelectedCount = this.mSelectManager.getSelectedCount(); this.dataSource.forceUpdate(); } @@ -207,15 +262,15 @@ export struct NewAlbumPage { aboutToAppear(): void { TraceControllerUtils.startTrace('PhotoGridPageAboutToAppear'); - this.mSelectManager = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_SELECTED); + this.mSelectManager = AppStorage.Get(Constants.APP_KEY_NEW_ALBUM_SELECTED) as SelectManager; if (this.mSelectManager == null) { this.mSelectManager = new SelectManager(); AppStorage.SetOrCreate(Constants.APP_KEY_NEW_ALBUM_SELECTED, this.mSelectManager); } - let param: any = router.getParams(); + let param: Params = router.getParams() as Params; if (param != null) { Log.debug(TAG, `After router.getParams, param is: ${JSON.stringify(param)}`); - let item = JSON.parse(param.item); + let item: AlbumInfo = JSON.parse(param.item) as AlbumInfo; this.title = item.albumName; this.dataSource.setAlbumUri(item.uri); AppStorage.SetOrCreate(Constants.APP_KEY_NEW_ALBUM_SOURCE, item.uri); @@ -225,89 +280,49 @@ export struct NewAlbumPage { } let self = this; - this.onMenuClicked = this.onMenuClicked.bind(this); this.dataSource.setBroadCast(this.broadCast) this.mSelectManager.setPhotoDataImpl(); - this.initGridRowCount = this.initGridRowCount.bind(this); this.initGridRowCount(); ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.broadCast.on(BroadCastConstants.SELECT, - (position: number, key: string, value: boolean, callback: Function) => { - if (self.mSelectManager.toggle(key, value, position)) { - Log.info(TAG, 'enter event process'); - callback(); - } - }); + this.broadCast.on(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.on(BroadCastConstants.JUMP_PHOTO_BROWSER, this.jumpPhotoBrowserFunc); + this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.on(Constants.ON_LOADING_FINISHED, this.onDataReloadedFunc); + this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, this.onLoadingFinishedFunc); - this.broadCast.on(BroadCastConstants.JUMP_PHOTO_BROWSER, - (name: string, item: MediaItem) => { - let targetIndex = self.dataSource.getDataIndex(item); - if (targetIndex == Constants.NOT_FOUND) { - Log.error(TAG, 'targetIndex is not found'); - return; - } - Log.info(TAG, `jump to photo browser at index: ${targetIndex}`); - AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, self.dataSource); - this.browserController.showBrowserWithNoAnimation({ - position: targetIndex, - transition: name, - leftBlank: self.leftBlank, - }); - }) - - this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, - (name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string) => { - let targetIndex = self.dataSource.getDataIndex(item); - Log.info(TAG, `jump to photo browser, index: ${targetIndex}, transition: ${name}`); - AppStorage.SetOrCreate(Constants.PHOTO_GRID_SELECT_MANAGER, self.mSelectManager); - AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, self.dataSource); - if (geometryTapIndex && geometryTransitionString) { - this.browserController.showSelectBrowser(geometryTapIndex, geometryTransitionString, TAG, { - position: targetIndex, - transition: name - }); - } else { - this.browserController.showSelectBrowserWithNoAnimation({ - position: targetIndex, - transition: name, - }); - } - }) - - this.broadCast.on(Constants.ON_LOADING_FINISHED, - (size: number) => { - Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); - this.isEmpty = size == 0; - Log.info(TAG, `isEmpty: ${this.isEmpty}`); - }); - - this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, - () => { - Log.info(TAG, 'ON_DATA_RELOADED'); - this.dataSource.onDataReloaded(); - }); - - this.appBroadCast.on(BroadCastConstants.UPDATE_DATA_SOURCE, this.onUpdateFavorState.bind(this)); + this.appBroadCast.on(BroadCastConstants.UPDATE_DATA_SOURCE, this.onUpdateFavorStateFunc); AppStorage.SetOrCreate(Constants.PHOTO_GRID_SELECT_MANAGER, this.mSelectManager); - this.mSelectManager.registerCallback('allSelect', this.freezeAdapter((newState: boolean) => { + this.mSelectManager.registerCallback('allSelect', (newState: boolean) => { Log.info(TAG, `allSelect ${newState}`); - self.isAllSelected = newState; - self.dataSource.forceUpdate(); - })); - this.mSelectManager.registerCallback('select', this.freezeAdapter((newState: number) => { + this.isDataFreeze = AppStorage.get(Constants.IS_DATA_FREEZE) as boolean; + if (this.isDataFreeze) { + return; + } + this.isAllSelected = newState; + this.dataSource.forceUpdate(); + }); + this.mSelectManager.registerCallback('select', (newState: number) => { Log.info(TAG, `select ${newState}`); - self.dataSource.onDataChanged(newState); - })); - this.mSelectManager.registerCallback('updateCount', this.freezeAdapter((newState: number) => { + this.isDataFreeze = AppStorage.get(Constants.IS_DATA_FREEZE) as boolean; + if (this.isDataFreeze) { + return; + } + this.dataSource.onDataChanged(newState); + }); + this.mSelectManager.registerCallback('updateCount', (newState: number) => { Log.info(TAG, `updateSelectedCount ${newState}`); - self.moreMenuList = []; - self.moreMenuList.push(Boolean(newState) ? Action.INFO : Action.INFO_INVALID); - self.totalSelectedCount = newState; - })); + this.isDataFreeze = AppStorage.get(Constants.IS_DATA_FREEZE) as boolean; + if (this.isDataFreeze) { + return; + } + this.moreMenuList = []; + this.moreMenuList.push(Boolean(newState) ? Action.INFO : Action.INFO_INVALID); + this.totalSelectedCount = newState; + }); this.dataSource.registerCallback('updateCount', (newState: number) => { Log.info(TAG, `updateTotalCount ${newState}`); self.isShowScrollBar = (newState > Constants.PHOTOS_CNT_FOR_HIDE_SCROLL_BAR); - self.mSelectManager.setTotalCount(newState); + self.mSelectManager?.setTotalCount(newState); }) this.moreMenuList = []; @@ -316,11 +331,16 @@ export struct NewAlbumPage { } aboutToDisappear(): void { - this.broadCast.off(null, null); - this.appBroadCast.off(BroadCastConstants.UPDATE_DATA_SOURCE, null); + if(this.broadCast) { + this.broadCast.off(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.off(BroadCastConstants.JUMP_PHOTO_BROWSER, this.jumpPhotoBrowserFunc); + this.broadCast.off(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.off(Constants.ON_LOADING_FINISHED, this.onDataReloadedFunc); + this.broadCast.off(BroadCastConstants.ON_DATA_RELOADED, this.onLoadingFinishedFunc); + } + this.appBroadCast.off(BroadCastConstants.UPDATE_DATA_SOURCE, this.onUpdateFavorStateFunc); this.dataSource.releaseBroadCast(); ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; AppStorage.Delete(Constants.PHOTO_GRID_SELECT_MANAGER); } @@ -328,7 +348,7 @@ export struct NewAlbumPage { Stack() { Column() { AlbumSelectActionBar({ - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), totalSelectedCount: $totalSelectedCount, menuList: $moreMenuList }) @@ -339,16 +359,16 @@ export struct NewAlbumPage { } else { Stack() { Grid(this.scroller) { - LazyForEach(this.dataSource, (item, index?: number) => { + LazyForEach(this.dataSource, (item: ViewData, index?: number) => { if (!!item) { GridItem() { ImageGridItemComponent({ dataSource: this.dataSource, item: item.mediaItem, - isSelected: this.mSelectManager.isItemSelected(item.mediaItem.uri), + isSelected: this.isSelectedMode ? this.mSelectManager?.isItemSelected((item.mediaItem as MediaItem).uri as string, item.viewIndex) : false, pageName: Constants.PHOTO_TRANSITION_ALBUM, mPosition: index, - geometryTransitionString: this.getGeometryTransitionId(item, index), + geometryTransitionString: this.getGeometryTransitionId(item, index as number), selectedCount: $totalSelectedCount }) } @@ -358,11 +378,11 @@ export struct NewAlbumPage { .key('NewAlbumPageImage' + index) .zIndex(index === this.placeholderIndex ? 1 : 0) } - }, (item, index) => { + }, (item: ViewData, index?: number) => { if (item == null || item == undefined) { return JSON.stringify(item) + index; } - return this.getGeometryTransitionId(item, index); + return this.getGeometryTransitionId(item, index as number); }) } .edgeEffect(EdgeEffect.Spring) @@ -433,7 +453,12 @@ export struct NewAlbumPage { } private getGeometryTransitionId(item: ViewData, index: number): string { - return TAG + item.mediaItem.getHashCode() + this.mSelectManager.isItemSelected(item.mediaItem.uri, item.viewIndex); + let mediaItem = item.mediaItem as MediaItem; + if (mediaItem) { + return TAG + mediaItem.getHashCode() + (this.mSelectManager?.isItemSelected(mediaItem.uri as string) ?? false); + } else { + return TAG + item.viewIndex; + } } private initGridRowCount(): void { @@ -441,7 +466,7 @@ export struct NewAlbumPage { let margin = 0; let maxThumbWidth = px2vp(Constants.GRID_IMAGE_SIZE) * Constants.GRID_MAX_SIZE_RATIO; this.gridRowCount = Math.max(Math.round(((contentWidth - Constants.NUMBER_2 * margin) - + Constants.GRID_GUTTER) / (maxThumbWidth + Constants.GRID_GUTTER)), Constants.DEFAULT_ALBUM_GRID_COLUMN_MIN_COUNT); + + Constants.GRID_GUTTER) / (maxThumbWidth + Constants.GRID_GUTTER)), Constants.DEFAULT_ALBUM_GRID_COLUMN_MIN_COUNT); Log.info(TAG, `initGridRowCount contentWidth: ${contentWidth}`); } } \ No newline at end of file diff --git a/product/phone/src/main/ets/pages/ResourceDeletePage.ets b/product/phone/src/main/ets/pages/ResourceDeletePage.ets index cadbb095..e24a23d7 100644 --- a/product/phone/src/main/ets/pages/ResourceDeletePage.ets +++ b/product/phone/src/main/ets/pages/ResourceDeletePage.ets @@ -26,6 +26,7 @@ import { CustomDialogView } from '@ohos/common/CommonComponents'; import { MenuOperation } from '@ohos/common'; import dialogRequest from '@ohos.app.ability.dialogRequest'; import uri from '@ohos.uri'; +import common from '@ohos.app.ability.common'; const TAG: string = 'ResourceDeletePage'; @@ -35,7 +36,7 @@ struct ResourceDeletePage { @Provide broadCast: BroadCast = new BroadCast(); isShow: boolean = false; - selectManager: SelectManager; + selectManager: SelectManager = new SelectManager(); onPageShow() { if (this.isShow) { @@ -44,30 +45,30 @@ struct ResourceDeletePage { this.isShow = true; Log.info(TAG, 'onPageShow'); let menuOperation: MenuOperation; - let menuContext: MenuContext = new MenuContext(); - this.onOperationEnd = this.onOperationEnd.bind(this); - this.onOperationCancel = this.onOperationCancel.bind(this); + let menuContext: MenuContext; + menuContext = new MenuContext(); menuContext .withSelectManager(this.selectManager) - .withOperationEndCallback(this.onOperationEnd) - .withOperationCancelCallback(this.onOperationCancel) + .withOperationEndCallback((): void => this.onOperationEnd()) + .withOperationCancelCallback((): void => this.onOperationCancel()) .withBroadCast(this.broadCast); menuOperation = MenuOperationFactory.getInstance() .createMenuOperation(ThirdDeleteOperation, menuContext); - menuOperation.doAction() + menuOperation.doAction(); } aboutToAppear() { this.selectManager = new SelectManager(); - let uris: [] = AppStorage.Get("uris"); - Log.info(TAG, `aboutToAppear uris : ${JSON.stringify(uris)}`); - if (uris != undefined && uris.length > 0) { - uris.forEach(uri => { - if (!this.selectManager.clickedSet.has(uri)) { - this.selectManager.clickedSet.add(uri); - } - }) + let uris: string[] | undefined = AppStorage.get('uris'); + Log.info(TAG, 'aboutToAppear uris : ' + JSON.stringify(uris)); + if (!uris?.length) { + return; } + uris.forEach((uri: string): void => { + if (this.selectManager !== null && !this.selectManager.clickedSet.has(uri)) { + this.selectManager.clickedSet.add(uri); + } + }) } aboutToDisappear() { @@ -95,18 +96,13 @@ struct ResourceDeletePage { this.setDeleteResult(dialogRequest.ResultCode.RESULT_CANCEL); } - private setDeleteResult(result: dialogRequest.ResultCode) { - Log.info(TAG, `start to setDeleteResult : ${result}}`); + private setDeleteResult(result: dialogRequest.ResultCode): void { + Log.info(TAG, 'start to setDeleteResult : ' + result); try { - var requestCallback = AppStorage.Get("requestCallback"); - let myResult = { - result: result, - } - // @ts-ignore - requestCallback.setRequestResult(myResult); - globalThis.photoAbilityContext.terminateSelf(); - } catch(err) { - Log.info(TAG, `getRequestInfo err : ${JSON.stringify(err)}`); + (AppStorage.get('requestCallback') as dialogRequest.RequestCallback).setRequestResult({ result }); + (AppStorage.get('photosAbilityContext') as common.UIAbilityContext).terminateSelf(); + } catch (err) { + Log.info(TAG, `getRequestInfo err= ${JSON.stringify(err)}`); } } } \ No newline at end of file diff --git a/product/phone/src/main/ets/pages/ThirdSelectPhotoGridPage.ets b/product/phone/src/main/ets/pages/ThirdSelectPhotoGridPage.ets index fb955161..8206b5bd 100644 --- a/product/phone/src/main/ets/pages/ThirdSelectPhotoGridPage.ets +++ b/product/phone/src/main/ets/pages/ThirdSelectPhotoGridPage.ets @@ -25,7 +25,7 @@ export struct ThirdSelectPhotoGridPage { @Provide albumId: string = ''; @State @Watch('updateAnimationStatus') browserController: BrowserController = new BrowserController(true); @State isRunningAnimation: boolean = false; - private onBackFunc: Function; + private onBackFunc: Function = (): void => {}; onPageShow() { this.pageStatus = true; @@ -44,9 +44,10 @@ export struct ThirdSelectPhotoGridPage { this.onBackFunc(); return true; } + return false; } - bindBackFunc(backFunc: Function) { + bindBackFunc(backFunc: Function): void { this.onBackFunc = backFunc; } @@ -55,7 +56,7 @@ export struct ThirdSelectPhotoGridPage { Column() { ThirdSelectPhotoGridBase({ pageStatus: this.pageStatus, - backFuncBinder: this.bindBackFunc.bind(this), + backFuncBinder: (backFunc: Function): void => this.bindBackFunc(backFunc), browserController: this.browserController }) .transition({ type: TransitionType.All, opacity: 0 }) diff --git a/product/phone/src/main/ets/pages/VideoBrowser.ets b/product/phone/src/main/ets/pages/VideoBrowser.ets index 9d18fc9f..367fa9fd 100644 --- a/product/phone/src/main/ets/pages/VideoBrowser.ets +++ b/product/phone/src/main/ets/pages/VideoBrowser.ets @@ -28,9 +28,16 @@ import { WindowUtil } from '@ohos/common'; import { PhotoBrowserActionBar } from '@ohos/browser/BrowserComponents'; +import common from '@ohos.app.ability.common'; const TAG: string = 'VideoBrowser'; +interface Params { + uri: string; + dateTaken: number; + previewUri: string; +} + @Entry @Component struct VideoBrowser { @@ -46,7 +53,7 @@ struct VideoBrowser { private isNeedRecoveryStatus: boolean = false; private uri = ''; private dateTaken = 0; - private previewUri = null; + private previewUri = ''; onBackPress() { Log.info(TAG, 'onBackPress'); @@ -56,7 +63,7 @@ struct VideoBrowser { aboutToAppear() { TraceControllerUtils.startTrace('VideoBrowserAboutToAppear'); - let param: any = router.getParams(); + let param: Params = router.getParams() as Params; this.uri = param.uri; this.dateTaken = param.dateTaken; this.previewUri = param.previewUri; @@ -71,7 +78,6 @@ struct VideoBrowser { } this.photoDate = DateUtil.getLocalizedDate(this.dateTaken); this.timeAndLocation = DateUtil.getLocalizedTime(this.dateTaken); - this.onMenuClicked = this.onMenuClicked.bind(this); TraceControllerUtils.finishTrace('VideoBrowserAboutToAppear'); } @@ -108,26 +114,27 @@ struct VideoBrowser { }) .onStart(() => { this.mVideoStatus = Constants.VIDEO_STATUS_PLAYING; - WindowUtil.setWindowKeepScreenOn(globalThis.photosAbilityContext, true); + WindowUtil.setWindowKeepScreenOn(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, true); }) .onPause(() => { this.mVideoStatus = Constants.VIDEO_STATUS_PAUSE; - WindowUtil.setWindowKeepScreenOn(globalThis.photosAbilityContext, false); + WindowUtil.setWindowKeepScreenOn(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, false); }) .onFinish(() => { this.mVideoStatus = Constants.VIDEO_STATUS_FINISH; this.isShowBar = true; - WindowUtil.setWindowKeepScreenOn(globalThis.photosAbilityContext, false); + WindowUtil.setWindowKeepScreenOn(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, false); }) .onError(() => { this.mVideoStatus = Constants.VIDEO_STATUS_ERROR; this.isShowBar = true; - WindowUtil.setWindowKeepScreenOn(globalThis.photosAbilityContext, false); + WindowUtil.setWindowKeepScreenOn(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, false); }) .autoPlay(true) PhotoBrowserActionBar({ - onMenuClicked: this.onMenuClicked, isVideoPage: true + onMenuClicked: (action: Action): void => this.onMenuClicked(action), + isVideoPage: true }) } .width('100%') @@ -145,15 +152,8 @@ struct VideoBrowser { private onMenuClicked(action: Action) { Log.info(TAG, `onMenuClicked, action: ${action.actionID}`); let menuOperation: MenuOperation; - switch (action.actionID) { - case Action.BACK.actionID: - this.onBackPress(); - return; - default: - break; - } - if (menuOperation != null) { - menuOperation.doAction(); + if (action.actionID === Action.BACK.actionID) { + this.onBackPress(); } } } diff --git a/product/phone/src/main/ets/pages/index.ets b/product/phone/src/main/ets/pages/index.ets index 75bc3366..16a48572 100644 --- a/product/phone/src/main/ets/pages/index.ets +++ b/product/phone/src/main/ets/pages/index.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import app from '@system.app'; import { BigDataConstants, @@ -28,7 +28,8 @@ import { Log, ReportToBigDataUtil, ScreenManager, - TraceControllerUtils + TraceControllerUtils, + WindowUtil } from '@ohos/common'; import { BrowserController, @@ -42,6 +43,9 @@ import { TabContentComponent } from '../view/TabContentComponent'; import { TimelineTabContentComponent } from '../view/TimelineContentComponent'; import data_preferences from '@ohos.data.preferences'; +import common from '@ohos.app.ability.common'; +import { BusinessError } from '@ohos.base'; +import { Router } from '@ohos.arkui.UIContext'; export type Preferences = data_preferences.Preferences; @@ -51,6 +55,10 @@ const COMPONENT_KEY_ALBUMS: string = 'Albums'; const IMAGE_CACHE_COUNT: number = 100; const IMAGE_CACHE_SIZE: number = 1024 * 1024 * IMAGE_CACHE_COUNT; +interface Params { + jumpSource: number; +}; + // Application entry @Entry @Component @@ -74,7 +82,7 @@ struct IndexPage { @State currentIndex: number = this.preIndex; @StorageLink('entryFromHap') entryFromHap: number = Constants.ENTRY_FROM_NONE; @State controlButtonMarginLeft: number = 16; - @StorageLink('deviceType') deviceType: string = AppStorage.Get('deviceType'); + @StorageLink('deviceType') deviceType: string = AppStorage.get('deviceType') as string; @StorageLink('currentBreakpoint') @Watch('updateParameters') currentBreakpoint: string = Constants.BREAKPOINT_MD; @StorageLink('isShowPhotoGridView') @Watch('doAnimation') isShowPhotoGridView: boolean = false; @State isShowTabBar: boolean = true; @@ -88,9 +96,9 @@ struct IndexPage { ]; private tabsController: TabsController = new TabsController(); private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); - private jumpSource: number; + private jumpSource: number = 0; private breakpointSystem: BreakpointSystem = new BreakpointSystem(); - private photosPreferences: Preferences; + private photosPreferences: Preferences | null = null; doAnimation(): void { if (this.isSidebar && this.currentBreakpoint !== Constants.BREAKPOINT_LG) { @@ -119,12 +127,12 @@ struct IndexPage { } initPhotosStore() { - this.photosPreferences = AppStorage.Get(Constants.PHOTOS_STORE_KEY); + this.photosPreferences = AppStorage.get(Constants.PHOTOS_STORE_KEY) as Preferences; if (this.photosPreferences) { - this.photosPreferences.get('lastPage', 0).then((data: number) => { - this.preIndex = data; + this.photosPreferences.get('lastPage', 0).then((data: data_preferences.ValueType) => { + this.preIndex = data as number; this.currentIndex = this.preIndex; - }).catch((err) => { + }).catch((err: Error) => { this.updatePhotosStore('lastPage', 0); }); } else { @@ -132,12 +140,12 @@ struct IndexPage { } } - updatePhotosStore(key, value) { + updatePhotosStore(key: string, value: number): void { if (this.photosPreferences) { - this.photosPreferences.put(key, value).then(() => { + this.photosPreferences.put(key, value).then((): void => { Log.debug(TAG, `Succeeded in putting the value of '${key}'.`); - this.photosPreferences.flush(); - }).catch((err) => { + this.photosPreferences?.flush(); + }).catch((err: Error) => { Log.error(TAG, `Failed to put the value of '${key}'. Cause: ${err}`); }); } @@ -148,7 +156,7 @@ struct IndexPage { ScreenManager.getInstance().setSystemUi(true); this.breakpointSystem.register(); this.updateParameters(); - let param: any = router.getParams(); + let param: Params = router.getParams() as Params; Log.info(TAG, `[aboutToAppear] param: ${JSON.stringify(param)}`); this.requestPermissions(); if (param != null) { @@ -157,8 +165,11 @@ struct IndexPage { this.entryFromHap = Constants.ENTRY_FROM_NONE; this.currentIndex = Constants.TIMELINE_PAGE_INDEX; Log.info(TAG, `Camera in, switch to Tab ${this.currentIndex}.`); - let msg = { - 'Type': BigDataConstants.ENTER_BY_CAMERA + interface Msg { + type: string; + } + let msg: Msg = { + type: BigDataConstants.ENTER_BY_CAMERA }; ReportToBigDataUtil.report(BigDataConstants.ENTER_PHOTOS_ID, msg); } @@ -169,20 +180,20 @@ struct IndexPage { onPageShow(): void { Log.info(TAG, `[onPageShow] entryFromHap: ${this.entryFromHap}`); - if (typeof globalThis.IsSetImageRawDataCacheSize === 'undefined') { + if (typeof AppStorage.get('IsSetImageRawDataCacheSize') === 'undefined') { Log.info(TAG, '[onPageShow] setImageRawDataCacheSize'); // ImageCacheCount:缓存解码后的图片,默认为0 app.setImageCacheCount(IMAGE_CACHE_COUNT); // ImageRawDataCache:缓存解码前的图片数据和缩略图的数据(datashare thumbnail格式) app.setImageRawDataCacheSize(IMAGE_CACHE_SIZE); - globalThis.IsSetImageRawDataCacheSize = true; + AppStorage.setOrCreate('IsSetImageRawDataCacheSize', true); } this.appBroadCast.emit(BroadCastConstants.THIRD_ROUTE_PAGE, []); setTimeout(() => { this.isShow = true }, 50); - let param: any = router.getParams(); + let param: Params =router.getParams() as Params; if (param != null) { this.jumpSource = param.jumpSource; } @@ -193,7 +204,7 @@ struct IndexPage { router.clear(); // To help AlbumSetPage show copy or move dialog - if (AppStorage.Get(Constants.IS_SHOW_MOVE_COPY_DIALOG)) { + if (AppStorage.get(Constants.IS_SHOW_MOVE_COPY_DIALOG)) { this.appBroadCast.emit(BroadCastConstants.SEND_COPY_OR_MOVE_BROADCAST, [this.currentIndex]); AppStorage.SetOrCreate(Constants.IS_SHOW_MOVE_COPY_DIALOG, false); } @@ -237,9 +248,8 @@ struct IndexPage { } } let isProcessed = false; - this.appBroadCast.emit(BroadCastConstants.BACK_PRESS_EVENT, [function(isModeChanged: boolean){ - isProcessed = isModeChanged; - }.bind(this)]); + this.appBroadCast.emit(BroadCastConstants.BACK_PRESS_EVENT, + [(isModeChanged: boolean): void => { isProcessed = isModeChanged; }]); return isProcessed; } @@ -351,7 +361,7 @@ struct IndexPage { } private async requestPermissions(): Promise { - this.photosPreferences = AppStorage.Get(Constants.PHOTOS_STORE_KEY); + this.photosPreferences = AppStorage.get(Constants.PHOTOS_STORE_KEY) as Preferences; let isRequested: boolean = false; if (this.photosPreferences) { isRequested = await this.photosPreferences.get(Constants.PHOTOS_PERMISSION_FLAG, false) as boolean; @@ -367,8 +377,8 @@ struct IndexPage { ]; let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { - // @ts-ignore - atManager.requestPermissionsFromUser(globalThis.photosAbilityContext, permissionList).then((data) => { + atManager.requestPermissionsFromUser(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, permissionList as Permissions[]) + .then((data) => { Log.debug(TAG, `permissions: ${JSON.stringify(data.permissions)}` + `, authResult: ${JSON.stringify(data.authResults)}`); let sum: number = 0; @@ -379,12 +389,12 @@ struct IndexPage { if (this.photosPreferences) { this.photosPreferences.put(Constants.PHOTOS_PERMISSION_FLAG, true).then(() => { Log.debug(TAG, `Succeeded in putting the value of '${Constants.PHOTOS_PERMISSION_FLAG}'.`); - this.photosPreferences.flush(); - }).catch((err) => { + this.photosPreferences?.flush(); + }).catch((err: Error) => { Log.error(TAG, `Failed to put the value of '${Constants.PHOTOS_PERMISSION_FLAG}'. Cause: ${err}`); }); } - }, (err) => { + }, (err: BusinessError) => { Log.error(TAG, `Failed to start ability err code: ${err.code}`); }); } catch (error) { diff --git a/product/phone/src/main/ets/view/PhotoBrowserComponent.ets b/product/phone/src/main/ets/view/PhotoBrowserComponent.ets index 0d4b9119..82c1497b 100644 --- a/product/phone/src/main/ets/view/PhotoBrowserComponent.ets +++ b/product/phone/src/main/ets/view/PhotoBrowserComponent.ets @@ -17,7 +17,7 @@ import router from '@ohos.router'; import bundle from '@ohos.bundle'; import CommonEvent from '@ohos.commonEvent'; import window from '@ohos.window'; -import { MenuOperation } from '@ohos/common'; +import { MenuOperation, ViewData } from '@ohos/common'; import { Action, AddMenuOperation, @@ -72,9 +72,38 @@ import { PhotoBrowserActionBar, PhotoBrowserToolBar } from '@ohos/browser/BrowserComponents'; +import ability from '@ohos.ability.ability'; +import common from '@ohos.app.ability.common'; const TAG: string = 'PhotoBrowserComponent'; +interface ParamBrowser { + pageFrom: number; + albumInfo: AlbumInfo; + clickThumbnailTime: number; + albumUri: string; + uri: string; + viewData: ViewData; + viewDataIndex: string; + viewDataAlbum: string; + transition: string; + position: number; + isShowMenuFromThirdView: boolean; + deviceName: string; + deviceId: string; +}; + +interface Params { + pageType: string; + albumName: string; + albumUri: string; +}; + +interface TitleName { + title: string; + displayName: string; +} + // page of large photo @Component export struct PhotoBrowserComponent { @@ -99,12 +128,12 @@ export struct PhotoBrowserComponent { @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; @StorageLink('entryFromHap') entryFromHap: number = Constants.ENTRY_FROM_NONE; - mTransition: string; + mTransition: string = ''; albumUri = ''; // swiper currentIndex, there may not be onChanged callback during data refresh, so mediaItem cannot be saved @Provide('transitionIndex') currentIndex: number = Constants.NUMBER_0; controller: SwiperController = new SwiperController(); - @Prop @Watch('onPageChanged') pageStatus: boolean; + @Prop @Watch('onPageChanged') pageStatus: boolean = false; @StorageLink('geometryOpacity') geometryOpacity: number = 1; @State geometryTransitionId: string = ''; @Link isRunningAnimation: boolean; @@ -128,22 +157,41 @@ export struct PhotoBrowserComponent { // time when clicks the thumbnail from the camera private clickThumbnailTime = Constants.NUMBER_0; // time to view the current picture - private checkedTransition: string; + private checkedTransition: string = ''; private viewTime = Constants.NUMBER_0; // When clicking quickly, only run aboutToAppear for the first time - private hasAppeared: boolean; - private albumInfo: AlbumInfo; + private hasAppeared: boolean = false; + private albumInfo?: AlbumInfo; private deviceName = ''; private backFromCopy = false; - private uriFromThirdPartyApp: string; + private uriFromThirdPartyApp: string = ''; private editNewUri: string = ""; private favorCacheItemsMap = new Map() private breakpointSystem: BreakpointSystem = new BreakpointSystem(); - private theDeleteItem: MediaItem; + private theDeleteItem: MediaItem | null = null; private geometryTransitionEnable: boolean = false; private isShowMenuFromThirdView: boolean = true; private isToEdit = false; - private photoBrowserBackFunc: Function = this.photoBrowserBack.bind(this); + private photoBrowserBackFunc: Function = (): void => this.photoBrowserBack(); + private onToggleBarsFunc: Function = (backgroundColorResource?: Resource): void => this.onToggleBars(backgroundColorResource); + private showBarsFunc: Function = (backgroundColorResource?: Resource): void => this.showBars(backgroundColorResource); + private hideBarsFunc: Function = (backgroundColorResource?: Resource): void => this.hideBars(backgroundColorResource); + private pullDownStartFunc: Function = (): void => this.pullDownStart(); + private pullDownEndFunc: Function = (): void => this.pullDownEnd(); + private onDataSizeChangedFunc: Function = (size: number): void => this.onDataSizeChanged(size); + private onDataContentChangedFunc: Function = (): void => this.onDataContentChanged(); + private setFavorFunc: Function = (isFavor: boolean): void => this.setFavor(isFavor); + private doRenameFunc: Function = (result: TitleName): void => this.doRename(result); + private doRotateFunc: Function = (result: number): void => this.doRotate(result); + private pullDownStartWithEventFunc: Function = (event: KeyEvent): void => this.pullDownStartWithEvent(event); + private pullDownCancelFunc: Function = (): void => this.pullDownCancel(); + private onPhotoBrowserDeleteConfirmFunc: Function = (): void => this.onPhotoBrowserDeleteConfirm(); + private onPhotoBrowserRemoveConfirmFunc: Function = (): void => this.onPhotoBrowserRemoveConfirm(); + private doDeleteFunc: Function = (): void => this.doDelete(); + private onPhotoShowStateChangedFunc: Function = (state: boolean): void => this.onPhotoShowStateChanged(state); + private setSwiperDisableFunc: Function = (value: boolean): void => this.setSwiperDisable(value); + private onDataReloadWithEditFunc: Function = (): void => this.onDataReloadWithEdit(); + onPageChanged() { Log.info(TAG, `call page status changed ${this.pageStatus}`) @@ -177,208 +225,156 @@ export struct PhotoBrowserComponent { onMenuClicked(action: Action): void { let actionID: number = action.actionID; Log.info(TAG, `onMenuClicked, actionID: ${actionID}`); - let menuOperation: MenuOperation = null; + let menuOperation: MenuOperation | null = null; let menuContext: MenuContext = new MenuContext(); let currentPhoto = this.getCurrentPhoto(); - switch (actionID) { - case Action.BACK.actionID: - this.onBackPress(); + if (actionID === Action.BACK.actionID) { + this.onBackPress(); + } else if (actionID === Action.INFO.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined'); return; - case Action.INFO.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined'); - return; - } - this.broadCast.emit(BroadCastConstants.SHOW_DETAIL_DIALOG, [currentPhoto, this.pageFrom == Constants.ENTRY_FROM.DISTRIBUTED]); + } + this.broadCast.emit(BroadCastConstants.SHOW_DETAIL_DIALOG, [currentPhoto, this.pageFrom == Constants.ENTRY_FROM.DISTRIBUTED]); + } else if (actionID === Action.SHARE.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined'); return; - case Action.SHARE.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined'); - return; - } - menuContext.withFromSelectMode(false).withMediaItem(currentPhoto); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(ShareMenuOperation, menuContext); - break; - case Action.NOT_FAVORITE.actionID: - case Action.FAVORITE.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined.'); - return; - } - currentPhoto.isFavor = !currentPhoto.isFavor; + } + menuContext.withFromSelectMode(false).withMediaItem(currentPhoto); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(ShareMenuOperation, menuContext); + } else if (actionID === Action.NOT_FAVORITE.actionID || actionID === Action.FAVORITE.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined.'); + return; + } + currentPhoto.isFavor = !currentPhoto.isFavor; - if (this.albumUri !== UserFileManagerAccess.getInstance() - .getSystemAlbumUri(UserFileManagerAccess.FAVORITE_ALBUM_SUB_TYPE)) { - let currentPhoto = this.getCurrentPhoto(); - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance().createMenuOperation(FavoriteMenuOperation, menuContext); - this.appBroadCast.emit(BroadCastConstants.UPDATE_DATA_SOURCE, [currentPhoto]); - } else { - if (currentPhoto.isFavor === true) { - if (this.favorCacheItemsMap.has(currentPhoto.uri)) { - this.favorCacheItemsMap.delete(currentPhoto.uri); - } else { - Log.error(TAG, `not fount item uri ${currentPhoto.uri}`); - } + if (this.albumUri !== UserFileManagerAccess.getInstance() + .getSystemAlbumUri(UserFileManagerAccess.FAVORITE_ALBUM_SUB_TYPE)) { + let currentPhoto = this.getCurrentPhoto(); + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(FavoriteMenuOperation, menuContext); + this.appBroadCast.emit(BroadCastConstants.UPDATE_DATA_SOURCE, [currentPhoto]); + } else { + if (currentPhoto.isFavor === true) { + if (this.favorCacheItemsMap.has(currentPhoto.uri)) { + this.favorCacheItemsMap.delete(currentPhoto.uri); } else { - this.favorCacheItemsMap.set(currentPhoto.uri, currentPhoto); + Log.error(TAG, `not fount item uri ${currentPhoto.uri}`); } + } else { + this.favorCacheItemsMap.set(currentPhoto.uri, currentPhoto); } - this.updateMenu(); - this.geometryTransitionId = this.browserController.pageFrom + currentPhoto.getHashCode() + 'false'; - AppStorage.SetOrCreate('geometryTransitionBrowserId', this.geometryTransitionId); - break; - case Action.DELETE.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined.'); - return; - } - menuContext.withAlbumInfo(this.albumInfo); - this.theDeleteItem = currentPhoto; - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(DeleteMenuOperation, menuContext); - break; - case Action.RECOVER.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined.'); - return; - } - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(RecoverMenuOperation, menuContext); - break; - case Action.GOTO_PHOTOS.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined.'); - return; - } - menuContext.withJumpSourceToMain(this.jumpSourceToMain); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(GotoPhotosMenuOperation, menuContext); - break; - case Action.EDIT.actionID: - if (currentPhoto == undefined || currentPhoto.size == 0) { - Log.warn(TAG, 'currentPhoto is undefined or size is 0.'); - return; - } - globalThis.EditorMediaItem = currentPhoto; - globalThis.EditorAlbumUri = this.albumUri; - router.pushUrl({ - url: 'pages/EditMain' - }) - this.isToEdit = true; + } + this.updateMenu(); + this.geometryTransitionId = this.browserController.pageFrom + currentPhoto.getHashCode() + 'false'; + AppStorage.SetOrCreate('geometryTransitionBrowserId', this.geometryTransitionId); + } else if (actionID === Action.DELETE.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined.'); return; - case Action.EDIT_INVALID.actionID: - if (currentPhoto == undefined || currentPhoto.size == 0) { - Log.warn(TAG, 'currentPhoto is undefined or size is 0.'); - return; - } + } + menuContext.withAlbumInfo(this.albumInfo); + this.theDeleteItem = currentPhoto; + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(DeleteMenuOperation, menuContext); + } else if (actionID === Action.RECOVER.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined.'); return; - case Action.RENAME.actionID: - this.hidePopup = true; - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined.'); - return; - } - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast).withAlbumUri(this.albumUri); - menuOperation = MenuOperationFactory.getInstance().createMenuOperation(RenameMenuOperation, menuContext); - break; - case Action.ROTATE.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined when onMenuClicked Action.RENAME.'); - return; - } - let rotateValue = currentPhoto.orientation - Constants.DEFAULT_ROTATE_VALUE + Constants.ROTATE_AROUND; - if (rotateValue >= Constants.ROTATE_AROUND) { - rotateValue = rotateValue - Constants.ROTATE_AROUND; - } - currentPhoto.orientation = rotateValue; - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance().createMenuOperation(RotateMenuOperation, menuContext); - break; - case Action.ADD_NOTES.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined when onMenuClicked Action.RENAME.'); - return; - } - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddNotesMenuOperation, menuContext); - break; - case Action.MOVE.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined when onMenuClicked Action.MOVE.'); - return; - } - this.backFromCopy = true; - currentPhoto && currentPhoto.mediaType && - this.routeToSelectAlbumPage(MediaOperationType.Move, currentPhoto.mediaType); + } + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(RecoverMenuOperation, menuContext); + } else if (actionID === Action.GOTO_PHOTOS.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined.'); return; - case Action.ADD.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined when onMenuClicked Action.ADD.'); - return; - } - this.backFromCopy = true; - currentPhoto && currentPhoto.mediaType && - this.routeToSelectAlbumPage(MediaOperationType.Add, currentPhoto.mediaType); + } + menuContext.withJumpSourceToMain(this.jumpSourceToMain); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(GotoPhotosMenuOperation, menuContext); + } else if (actionID === Action.EDIT.actionID) { + if (currentPhoto == undefined || currentPhoto.size == 0) { + Log.warn(TAG, 'currentPhoto is undefined or size is 0.'); return; - case Action.REMOVE_FROM.actionID: - if (currentPhoto == undefined) { - Log.warn(TAG, 'currentPhoto is undefined.'); - return; - } + } + AppStorage.setOrCreate('EditorMediaItem', currentPhoto); + AppStorage.setOrCreate('EditorAlbumUri', this.albumUri); + router.pushUrl({ + url: 'pages/EditMain' + }) + this.isToEdit = true; + } else if (actionID === Action.EDIT_INVALID.actionID) { + if (currentPhoto == undefined || currentPhoto.size == 0) { + Log.warn(TAG, 'currentPhoto is undefined or size is 0.'); + return; + } + } else if (actionID === Action.RENAME.actionID) { + this.hidePopup = true; + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined.'); + return; + } + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast).withAlbumUri(this.albumUri); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(RenameMenuOperation, menuContext); + } else if (actionID === Action.ROTATE.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined when onMenuClicked Action.RENAME.'); + return; + } + let rotateValue = currentPhoto.orientation - Constants.DEFAULT_ROTATE_VALUE + Constants.ROTATE_AROUND; + if (rotateValue >= Constants.ROTATE_AROUND) { + rotateValue = rotateValue - Constants.ROTATE_AROUND; + } + currentPhoto.orientation = rotateValue; + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(RotateMenuOperation, menuContext); + } else if (actionID === Action.ADD_NOTES.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined when onMenuClicked Action.RENAME.'); + return; + } + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddNotesMenuOperation, menuContext); + } else if (actionID === Action.MOVE.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined when onMenuClicked Action.MOVE.'); + return; + } + this.backFromCopy = true; + currentPhoto && currentPhoto.mediaType && + this.routeToSelectAlbumPage(MediaOperationType.Move, currentPhoto.mediaType); + return; + } else if (actionID === Action.ADD.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined when onMenuClicked Action.ADD.'); + return; + } + this.backFromCopy = true; + currentPhoto && currentPhoto.mediaType && + this.routeToSelectAlbumPage(MediaOperationType.Add, currentPhoto.mediaType); + } else if (actionID === Action.REMOVE_FROM.actionID) { + if (currentPhoto == undefined) { + Log.warn(TAG, 'currentPhoto is undefined.'); + return; + } - menuContext.withAlbumUri(this.albumUri); - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(RemoveMenuOperation, menuContext); - break; - case Action.DOWNLOAD.actionID: - this.downLoad(); - return; - default: - return; + menuContext.withAlbumUri(this.albumUri); + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(RemoveMenuOperation, menuContext); + } else if (actionID === Action.DOWNLOAD.actionID) { + this.downLoad(); } if (!!menuOperation) { menuOperation.doAction(); } } - onToggleBars(backgroundColorResource?: Resource): void { - if (this.isShowBar) { - this.hideBars(backgroundColorResource); - } else { - this.showBars(backgroundColorResource); - } - Log.info(TAG, `Toggle bars, isShowBar: ${this.isShowBar}`); - } - - showBars(backgroundColorResource?: Resource): void { - this.backgroundColorResource = backgroundColorResource ? - backgroundColorResource : $r('app.color.default_background_color'); - if (!this.isShowBar) { - this.isShowBar = !this.isShowBar; - if (!this.isHorizontal) { - ScreenManager.getInstance().setSystemUi(true); - } - } else { - this.onlyChangeBgColor = !this.onlyChangeBgColor; - } - } - - hideBars(backgroundColorResource?: Resource): void { - this.backgroundColorResource = backgroundColorResource ? - backgroundColorResource : $r('app.color.black'); - if (this.isShowBar) { - this.isShowBar = !this.isShowBar; - ScreenManager.getInstance().setSystemUi(false); - } else { - this.onlyChangeBgColor = !this.onlyChangeBgColor; - } - } - routeToSelectAlbumPage(pageType: string, mediaType: number): void { router.pushUrl({ url: 'pages/MediaOperationPage', @@ -395,7 +391,7 @@ export struct PhotoBrowserComponent { Log.info(TAG, `onPhotoChanged start, index=${index}`); this.reportToBigDataForPhotoSlide(index); this.currentIndex = index; - this.updateActionBar(); + this.updateActionBar && this.updateActionBar(); let currentPhoto = this.getCurrentPhoto(); if (currentPhoto == undefined) { Log.error(TAG, 'onPhotoChanged, item is undefined'); @@ -405,7 +401,7 @@ export struct PhotoBrowserComponent { this.geometryTransitionId = this.browserController.pageFrom + currentPhoto.getHashCode() + 'false'; AppStorage.SetOrCreate('geometryTransitionBrowserId', this.geometryTransitionId); Log.debug(TAG, `onPhotoChanged, index: ${index}, currentPhoto: ${currentPhoto.uri}, \ - placeholderIndex ${AppStorage.Get('placeholderIndex')},\ + placeholderIndex ${AppStorage.get('placeholderIndex') as number},\ geometryTransitionBrowserId ${this.geometryTransitionId}, this.mTransition ${this.mTransition}, \ pageFrom = ${this.pageFrom}`); } @@ -450,7 +446,7 @@ export struct PhotoBrowserComponent { updateMenu(): void { let currentPhoto = this.getCurrentPhoto(); - if (currentPhoto == undefined) { + if (!currentPhoto) { return; } @@ -458,7 +454,7 @@ export struct PhotoBrowserComponent { .getSystemAlbumUri(UserFileManagerAccess.FAVORITE_ALBUM_SUB_TYPE)) { let key = currentPhoto.uri; if (this.favorCacheItemsMap.has(key)) { - let tempPhotoItem = this.favorCacheItemsMap.get(key); + let tempPhotoItem: MediaItem = this.favorCacheItemsMap.get(key) as MediaItem; currentPhoto.isFavor = tempPhotoItem.isFavor; this.favorCacheItemsMap.set(key, currentPhoto); } @@ -474,10 +470,10 @@ export struct PhotoBrowserComponent { let menuTemp: Array = new Array(); if (this.pageFrom == Constants.ENTRY_FROM.CAMERA || - this.pageFrom == Constants.ENTRY_FROM.CARD || - (this.isFromViewDataWithMediaUri == true && - this.albumUri != UserFileManagerAccess.getInstance() - .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE))) { + this.pageFrom == Constants.ENTRY_FROM.CARD || + (this.isFromViewDataWithMediaUri == true && + this.albumUri != UserFileManagerAccess.getInstance() + .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE))) { menuTemp = [Action.GOTO_PHOTOS, Action.INFO]; } else if (pageFrom == Constants.ENTRY_FROM.RECYCLE || this.isFromViewDataWithThirdUri == true) { menuTemp = []; @@ -489,24 +485,18 @@ export struct PhotoBrowserComponent { } let list: Array = new Array(); - switch (pageFrom) { - case Constants.ENTRY_FROM.NORMAL: - case Constants.ENTRY_FROM.CAMERA: - list.push(currentPhoto.isFavor ? Action.FAVORITE : Action.NOT_FAVORITE, - ((currentPhoto.mediaType == UserFileManagerAccess.MEDIA_TYPE_IMAGE)) - ? Action.EDIT : Action.EDIT_INVALID, Action.DELETE, Action.MORE); // TODO: delete edit - break; - case Constants.ENTRY_FROM.RECYCLE: - list.push(Action.RECOVER, Action.DELETE); - break; - case Constants.ENTRY_FROM.DISTRIBUTED: - list.push(Action.DOWNLOAD); - break; - default: - list.push(currentPhoto.isFavor ? Action.FAVORITE : Action.NOT_FAVORITE, - ((currentPhoto.mediaType == UserFileManagerAccess.MEDIA_TYPE_IMAGE)) - ? Action.EDIT : Action.EDIT_INVALID, Action.DELETE, Action.MORE); // TODO: delete edit - break; + if (pageFrom === Constants.ENTRY_FROM.NORMAL || pageFrom === Constants.ENTRY_FROM.CAMERA) { + list.push(currentPhoto.isFavor ? Action.FAVORITE : Action.NOT_FAVORITE, + ((currentPhoto.mediaType == UserFileManagerAccess.MEDIA_TYPE_IMAGE)) + ? Action.EDIT : Action.EDIT_INVALID, Action.DELETE, Action.MORE); // TODO: delete edit + } else if (pageFrom === Constants.ENTRY_FROM.RECYCLE) { + list.push(Action.RECOVER, Action.DELETE); + } else if (pageFrom === Constants.ENTRY_FROM.DISTRIBUTED) { + list.push(Action.DOWNLOAD); + } else { + list.push(currentPhoto.isFavor ? Action.FAVORITE : Action.NOT_FAVORITE, + ((currentPhoto.mediaType == UserFileManagerAccess.MEDIA_TYPE_IMAGE)) + ? Action.EDIT : Action.EDIT_INVALID, Action.DELETE, Action.MORE); // TODO: delete edit } if (this.isHorizontal) { @@ -538,21 +528,24 @@ export struct PhotoBrowserComponent { } isShowMenuBigData(isShowMenuFromThirdView: boolean): void { - let isShowMenuMsg = {}; + interface ShowMenuMsg { + isShowMenuFromThirdView: string + } + let isShowMenuMsg: ShowMenuMsg; if (isShowMenuFromThirdView) { this.isShowMenuFromThirdView = true; isShowMenuMsg = { - 'isShowMenuFromThirdView': BigDataConstants.SHOW_MENU + isShowMenuFromThirdView: BigDataConstants.SHOW_MENU } } else if (isShowMenuFromThirdView == false) { this.isShowMenuFromThirdView = false; isShowMenuMsg = { - 'isShowMenuFromThirdView': BigDataConstants.HIDE_MENU + isShowMenuFromThirdView: BigDataConstants.HIDE_MENU } } else { this.isShowMenuFromThirdView = true; isShowMenuMsg = { - 'isShowMenuFromThirdView': BigDataConstants.UNDEFINED_IS_SHOW_MENU + isShowMenuFromThirdView: BigDataConstants.UNDEFINED_IS_SHOW_MENU } } this.updateMenu(); @@ -560,7 +553,7 @@ export struct PhotoBrowserComponent { } updateMoreMenu(): void { - this.moreMenuList = this.albumInfo.isSystemAlbum ? + this.moreMenuList = this.albumInfo?.isSystemAlbum ? [Action.ADD, Action.RENAME] : [Action.MOVE, Action.ADD, Action.REMOVE_FROM, Action.RENAME]; } @@ -572,7 +565,7 @@ export struct PhotoBrowserComponent { return this.dataSource.getRawData(index).data; } - async onMoveEnd(err, count, total): Promise { + async onMoveEnd(err: Object, count: number, total: number): Promise { Log.debug(TAG, `onMoveEnd count: ${count}, total: ${total}`); if (err) { UiUtil.showToast($r('app.string.move_failed_single')); @@ -583,14 +576,14 @@ export struct PhotoBrowserComponent { this.appBroadCast.emit(BroadCastConstants.UPDATE_DATA_SOURCE, [currentPhoto]); } - onCopyEnd(err, count, total): void { + onCopyEnd(err: Object, count: number, total: number): void { Log.debug(TAG, `onCopyEnd count: ${count}, total: ${total}`); if (err) { UiUtil.showToast($r('app.string.copy_failed_single')); } } - async onDownloadEnd(err, count, total): Promise { + async onDownloadEnd(err: Object, count: number, total: number): Promise { Log.debug(TAG, `onDownloadEnd count: ${count}, total: ${total}`); this.appBroadCast.emit(BroadCastConstants.PHOTO_BROWSER_ACTIVE, [true, this.checkedTransition]); if (err) { @@ -602,64 +595,59 @@ export struct PhotoBrowserComponent { onBackPress(): boolean { Log.info(TAG, 'onBackPress'); - this.controller.finishAnimation(this.onBackPressInner.bind(this)); + this.controller.finishAnimation((): void => this.onBackPressInner()); return true; } onBackPressInner(): void { Log.info(TAG, `onBackPressInner ${this.checkedTransition}`); this.dataSource.release(); - switch (this.checkedTransition) { - case Constants.PHOTO_TRANSITION_TIMELINE: - Log.info(TAG, 'onBackPress TimelinePage'); - this.TimelinePageIndex = this.currentIndex; // call scrollTo - this.TimelinePageIndex = Constants.INVALID; - break; - case Constants.PHOTO_TRANSITION_ALBUM: - Log.info(TAG, 'onBackPress PhotoGridPage'); - this.PhotoGridPageIndex = this.currentIndex; // call scrollTo - this.PhotoGridPageIndex = Constants.INVALID; + if (this.checkedTransition === Constants.PHOTO_TRANSITION_TIMELINE) { + Log.info(TAG, 'onBackPress TimelinePage'); + this.TimelinePageIndex = this.currentIndex; // call scrollTo + this.TimelinePageIndex = Constants.INVALID; + } else if (this.checkedTransition === Constants.PHOTO_TRANSITION_ALBUM) { + Log.info(TAG, 'onBackPress PhotoGridPage'); + this.PhotoGridPageIndex = this.currentIndex; // call scrollTo + this.PhotoGridPageIndex = Constants.INVALID; - if (this.isFromFACard) { - if (this.isPullDown) { - this.isPullDown = false; - globalThis.photosAbilityContext.terminateSelf(); - } else { - let displayName: string = AppStorage.Get('form_displayName'); - let uri: string = AppStorage.Get('form_albumUri'); - let item: AlbumInfo = new AlbumInfo(undefined); - item.uri = uri; - item.albumName = displayName; - //item.innerId = uri; - router.replaceUrl({ - url: 'pages/PhotoGridPage', - params: { - item: JSON.stringify(item), - isFromFACard: this.isFromFACard - } - }); - } - - if (this.geometryTransitionEnable) { - UiUtil.resetGeometryTransitionParams(); - } - this.breakpointSystem.unregisterOrientationChange(); - WindowUtil.setPreferredOrientation(globalThis.photosAbilityContext, window.Orientation.UNSPECIFIED); - return; + if (this.isFromFACard) { + if (this.isPullDown) { + this.isPullDown = false; + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelf(); + } else { + let displayName: string = AppStorage.get('form_displayName') as string; + let uri: string = AppStorage.get('form_albumUri') as string; + let item: AlbumInfo = new AlbumInfo(undefined); + item.uri = uri; + item.albumName = displayName; + //item.innerId = uri; + router.replaceUrl({ + url: 'pages/PhotoGridPage', + params: { + item: JSON.stringify(item), + isFromFACard: this.isFromFACard + } + }); } - break; - case Constants.PHOTO_TRANSITION_CAMERA: - Log.info(TAG, 'onBackPress Camera'); - // Entering from the camera does not need to return to close directly - globalThis.photosAbilityContext.terminateSelf(); + if (this.geometryTransitionEnable) { + UiUtil.resetGeometryTransitionParams(); + } + this.breakpointSystem.unregisterOrientationChange(); + WindowUtil.setPreferredOrientation(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, + window.Orientation.UNSPECIFIED); return; - case Constants.PHOTO_TRANSITION_THIRD_APP: - Log.info(TAG, 'onBackPress third app'); - this.setViewDataResult(true); - return; - default: - break + } + } else if (this.checkedTransition === Constants.PHOTO_TRANSITION_CAMERA) { + Log.info(TAG, 'onBackPress Camera'); + // Entering from the camera does not need to return to close directly + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelf(); + } else if (this.checkedTransition === Constants.PHOTO_TRANSITION_THIRD_APP) { + Log.info(TAG, 'onBackPress third app'); + this.setViewDataResult(true); } if (this.geometryTransitionEnable) { this.browserController.hideBrowser(); @@ -673,7 +661,7 @@ export struct PhotoBrowserComponent { } } - updatePhotoName(result: {title: string, displayName: string}): void { + updatePhotoName(result: TitleName): void { let currentPhoto = this.getCurrentPhoto(); currentPhoto.setTitle(result.title); currentPhoto.displayName = result.displayName; @@ -682,7 +670,6 @@ export struct PhotoBrowserComponent { aboutToDisappear(): void { Log.info(TAG, 'photoBrowser aboutToDisappear'); - this.controller = undefined; this.favorCacheItemsMap.forEach((item) => { let menuFavorContext = new MenuContext().withMediaItem(item).withBroadCast(this.broadCast); let menuFavorOperation = MenuOperationFactory.getInstance() @@ -702,10 +689,28 @@ export struct PhotoBrowserComponent { if (!this.isFromFACard) { this.breakpointSystem.unregisterOrientationChange(); - WindowUtil.setPreferredOrientation(globalThis.photosAbilityContext, + WindowUtil.setPreferredOrientation(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, window.Orientation.UNSPECIFIED); } - this.broadCast.off(null, null); + + this.broadCast.off(PhotoConstants.TOGGLE_BAR, this.onToggleBarsFunc); + this.broadCast.off(PhotoConstants.HIDE_BARS, this.hideBarsFunc); + this.broadCast.off(PhotoConstants.SHOW_BARS, this.showBarsFunc); + this.broadCast.off(PhotoConstants.PULL_DOWN_START, this.pullDownStartFunc); + this.broadCast.off(PhotoConstants.PULL_DOWN_END, this.pullDownEndFunc); + this.broadCast.off(PhotoConstants.DATA_SIZE_CHANGED, this.onDataSizeChangedFunc); + this.broadCast.off(PhotoConstants.DATA_CONTENT_CHANGED, this.onDataContentChangedFunc); + this.broadCast.off(PhotoConstants.SET_FAVOR, this.setFavorFunc); + this.broadCast.off(PhotoConstants.RENAME, this.doRenameFunc); + this.broadCast.off(PhotoConstants.ROTATE, this.doRotateFunc); + this.broadCast.off(PhotoConstants.PULL_DOWN_START, this.pullDownStartWithEventFunc); + this.broadCast.off(PhotoConstants.PULL_DOWN_CANCEL, this.pullDownCancelFunc); + this.broadCast.off(PhotoConstants.PHOTO_BROWSER_DELETE_CONFIRM, this.onPhotoBrowserDeleteConfirmFunc); + this.broadCast.off(PhotoConstants.PHOTO_BROWSER_REMOVE_CONFIRM, this.onPhotoBrowserRemoveConfirmFunc); + this.broadCast.off(PhotoConstants.DELETE, this.doDeleteFunc); + this.broadCast.off(PhotoConstants.PHOTO_SHOW_STATE, this.onPhotoShowStateChangedFunc); + this.broadCast.off(PhotoConstants.SET_DISABLE_SWIPE, this.setSwiperDisableFunc); + this.broadCast.off(BroadCastConstants.ON_DATA_RELOADED_WITH_EDIT, this.onDataReloadWithEditFunc); this.appBroadCast.off(BroadCastConstants.PHOTO_BROWSER_BACK_PRESS_EVENT, this.photoBrowserBackFunc); } @@ -720,20 +725,20 @@ export struct PhotoBrowserComponent { aboutToAppear(): void { TraceControllerUtils.startTrace('PhotoBrowserAboutToAppear'); Log.info(TAG, 'photoBrowser aboutToAppear'); - this.geometryTransitionId = AppStorage.Get('geometryTransitionBrowserId'); + this.geometryTransitionId = AppStorage.get('geometryTransitionBrowserId') as string; this.hasAppeared = true; this.updateIsHorizontal(); - WindowUtil.setPreferredOrientation(globalThis.photosAbilityContext, + WindowUtil.setPreferredOrientation(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, window.Orientation.AUTO_ROTATION_RESTRICTED); - let param: any = this.browserController.browserParam; - let entryFromCamera = (AppStorage.Get('entryFromHapCamera')) == Constants.ENTRY_FROM_CAMERA; + let param: ParamBrowser = this.browserController.browserParam as ParamBrowser; + let entryFromCamera = (AppStorage.get('entryFromHapCamera')) as number == Constants.ENTRY_FROM_CAMERA; Log.info(TAG, `photoBrowser start with entryFrom ` + JSON.stringify(entryFromCamera)); if (entryFromCamera) { param = { pageFrom: Constants.ENTRY_FROM.CAMERA - } + } as ParamBrowser; AppStorage.SetOrCreate('entryFromHapCamera', Constants.ENTRY_FROM_NONE); } @@ -768,15 +773,15 @@ export struct PhotoBrowserComponent { MediaObserver.getInstance().registerObserver(this.dataObserver); this.uriFromThirdPartyApp = param.uri; this.currentIndex = 0; - this.dataSource.getItemIndexByUri(this.uriFromThirdPartyApp, this.onGetItemIndexByUri.bind(this)); + this.dataSource.getItemIndexByUri(this.uriFromThirdPartyApp, (index: number): void => this.onGetItemIndexByUri(index)); this.isFromFACard = true; this.geometryTransitionEnable = true; } else if (this.pageFrom == Constants.ENTRY_FROM.RECYCLE) { this.dataSource.setAlbumUri(this.albumUri); - this.dataSource.setAlbumDataSource(AppStorage.Get(Constants.APP_KEY_PHOTO_BROWSER)); + this.dataSource.setAlbumDataSource(AppStorage.get(Constants.APP_KEY_PHOTO_BROWSER) as MediaDataSource); } else if (this.pageFrom == Constants.ENTRY_FROM.DISTRIBUTED) { this.dataSource.setDeviceId(param.albumInfo.deviceId); - this.dataSource.setAlbumDataSource(AppStorage.Get(Constants.APP_KEY_PHOTO_BROWSER)); + this.dataSource.setAlbumDataSource(AppStorage.get(Constants.APP_KEY_PHOTO_BROWSER) as MediaDataSource); } else if (this.pageFrom == Constants.ENTRY_FROM.VIEW_DATA) { if (String(param.viewData).length === 0) { Log.error(TAG, 'Invalid uri'); @@ -787,7 +792,7 @@ export struct PhotoBrowserComponent { if (String(param.viewDataIndex).length > 0) { Log.debug(TAG, `Found viewIndex`); this.dataSource = new UriDataSource(String(param.viewData).split('?')); - let viewIndex = parseInt(param.viewDataIndex); + let viewIndex = Number.parseInt(param.viewDataIndex); if (Number.isNaN(viewIndex) || viewIndex <= 0 || viewIndex > String(param.viewData).split('?').length) { viewIndex = 0; } else { @@ -821,7 +826,7 @@ export struct PhotoBrowserComponent { MediaObserver.getInstance().registerObserver(this.dataObserver); this.uriFromThirdPartyApp = String(param.viewData); this.currentIndex = 0; - this.dataSource.getItemIndexByUri(this.uriFromThirdPartyApp, this.onGetItemIndexByUri.bind(this)); + this.dataSource.getItemIndexByUri(this.uriFromThirdPartyApp, (index: number): void => this.onGetItemIndexByUri(index)); // 是否显示菜单栏并且处理大数据打点 this.isShowMenuBigData(param.isShowMenuFromThirdView); } else { @@ -832,7 +837,7 @@ export struct PhotoBrowserComponent { } } else { MediaObserver.getInstance().registerObserver(this.dataObserver); - this.dataSource.setAlbumDataSource(AppStorage.Get(Constants.APP_KEY_PHOTO_BROWSER)); + this.dataSource.setAlbumDataSource(AppStorage.get(Constants.APP_KEY_PHOTO_BROWSER) as MediaDataSource); } this.onPhotoChanged(param.position || 0); @@ -849,14 +854,14 @@ export struct PhotoBrowserComponent { Log.info(TAG, `photoBrowser start without param`); if (this.entryFromHap == Constants.ENTRY_FROM_FORM_ABILITY) { this.pageFrom = Constants.ENTRY_FROM.CARD; - this.albumUri = AppStorage.Get('form_albumUri'); + this.albumUri = AppStorage.get('form_albumUri') as string; } else { this.pageFrom = Constants.ENTRY_FROM.CAMERA; this.albumUri = UserFileManagerAccess.getInstance() .getSystemAlbumUri(UserFileManagerAccess.IMAGE_ALBUM_SUB_TYPE); } AppStorage.SetOrCreate('entryFromHap', Constants.ENTRY_FROM_NONE); - let albumDataSource: MediaDataSource = AppStorage.Get(Constants.APP_KEY_PHOTO_BROWSER); + let albumDataSource: MediaDataSource = AppStorage.get(Constants.APP_KEY_PHOTO_BROWSER) as MediaDataSource; if (albumDataSource) { this.dataSource.setAlbumDataSource(albumDataSource); } else { @@ -876,155 +881,197 @@ export struct PhotoBrowserComponent { this.checkedTransition = this.mTransition.substr(0, this.mTransition.length - 5) } - this.onMenuClicked = this.onMenuClicked.bind(this); - this.dataSource.setBroadCast(this.broadCast); this.dataSource.setBroadCastToAlbum(this.broadCast); + // register event handling - this.broadCast.on(PhotoConstants.TOGGLE_BAR, (backgroundColorResource?: Resource) => { - this.onToggleBars(backgroundColorResource); - }); - - this.broadCast.on(PhotoConstants.HIDE_BARS, (backgroundColorResource?: Resource) => { - this.hideBars(backgroundColorResource); - }); - - this.broadCast.on(PhotoConstants.SHOW_BARS, (backgroundColorResource?: Resource) => { - this.showBars(backgroundColorResource); - }); - - this.broadCast.on(PhotoConstants.PULL_DOWN_START, () => { - Log.info(TAG, 'pulling down start'); - }); - - this.broadCast.on(PhotoConstants.PULL_DOWN_END, () => { - Log.info(TAG, 'pulling down end'); - if (this.isFromFACard) { - this.isPullDown = true; - } - this.onBackPress(); - }); - - this.broadCast.on(PhotoConstants.DATA_SIZE_CHANGED, (size: number) => { - this.onDataSizeChanged(size); - }); - - this.broadCast.on(PhotoConstants.DATA_CONTENT_CHANGED, () => { - this.reportToBigDataForCameraIn(); - Log.debug(TAG, `PhotoConstants.DATA_CONTENT_CHANGED`); - this.onPhotoChanged(this.currentIndex); - }); - - this.broadCast.on(PhotoConstants.SET_FAVOR, (isFavor: boolean) => { - Log.debug(TAG, 'set favor !') - let currentPhoto = this.getCurrentPhoto(); - if (!isFavor) { - currentPhoto.isFavor = isFavor; - this.updateMenu(); - } else { - Log.debug(TAG, 'update favor !'); - } - }); - - this.broadCast.on(PhotoConstants.RENAME, (result: {title: string, displayName: string}) => { - Log.info(TAG, `rename refresh: ${result.title}, ${result.displayName}`); - this.updatePhotoName(result); - }); - - this.broadCast.on(PhotoConstants.ROTATE, (result: number) => { - Log.debug(TAG, `rotate finish: ${result}`); - let currentPhoto = this.getCurrentPhoto(); - currentPhoto.orientation = result; - let temp = currentPhoto.height; - currentPhoto.height = currentPhoto.width; - currentPhoto.width = temp; - this.dataSource.onDataChanged(this.currentIndex); - this.appBroadCast.emit(BroadCastConstants.UPDATE_DATA_SOURCE, [currentPhoto]); - }); - - this.broadCast.on(PhotoConstants.PULL_DOWN_START, (event) => { - Log.debug(TAG, `pulling down start : ${JSON.stringify(event)}`); - }) - - this.broadCast.on(PhotoConstants.PULL_DOWN_CANCEL, () => { - Log.info(TAG, 'pulling down cancel'); - }) - - this.broadCast.on(PhotoConstants.PHOTO_BROWSER_DELETE_CONFIRM, () => { - this.isDeleting = true; - // clear temp not favorite items - if (this.albumUri == UserFileManagerAccess.getInstance() - .getSystemAlbumUri(UserFileManagerAccess.FAVORITE_ALBUM_SUB_TYPE)) { - let key = this.theDeleteItem.uri; - if (this.favorCacheItemsMap.has(key)) { - let item = this.favorCacheItemsMap.get(key) - let menuFavorContext = new MenuContext().withMediaItem(item).withBroadCast(this.broadCast); - let menuFavorOperation = MenuOperationFactory.getInstance() - .createMenuOperation(FavoriteMenuOperation, menuFavorContext); - menuFavorOperation.doAction(); - this.favorCacheItemsMap.delete(key); - } - } - }) - - this.broadCast.on(PhotoConstants.PHOTO_BROWSER_REMOVE_CONFIRM, () => { - this.isDeleting = true; - }) - - this.broadCast.on(PhotoConstants.DELETE, () => { - Log.info(TAG, 'delete finish now update data'); - }); - - this.broadCast.on(PhotoConstants.PHOTO_SHOW_STATE, (state: boolean) => { - Log.debug(TAG, 'current photo show state change'); - this.currentShow = state; - }); - - this.broadCast.on(PhotoConstants.SET_DISABLE_SWIPE, (value: boolean) => { - Log.info(TAG, `set swiper swipe ${value}`); - this.canSwipe = value; - }); - - this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED_WITH_EDIT, () => { - Log.debug(TAG, 'animate to data reloaded start with edit'); - this.isToEdit = false; - try { - let uri: string = AppStorage.Get(BroadCastConstants.PHOTO_EDIT_SAVE_URI); - Log.debug(TAG, `data reloaded start with edit by uri ${uri}`); - if (uri) { - let newIndex = this.dataSource.getDataIndexByUri(uri); - let oldIndex = this.currentIndex; - if (newIndex != Constants.NOT_FOUND) { - // Search for the position of new image/video after edit in current 500 items succeed - Log.debug(TAG, `data reloaded from ${oldIndex} move to ${newIndex}`); - this.onPhotoChanged(newIndex); - } else { - // Search for the position of new image/video after edit in current 500 items failed - Log.debug(TAG, `data reloaded from ${oldIndex} move to unknown`); - this.editNewUri = uri; - this.dataSource.enableGetData(false); - this.currentIndex = 0; - this.dataSource.getItemIndexByUri(uri, this.onGetItemIndexByNewEditUri.bind(this)); - } - } - } catch (e) { - Log.error(TAG, `ON_DATA_RELOADED_WITH_EDIT error ${e}`); - } finally { - this.appBroadCast.emit(BroadCastConstants.PHOTO_EDIT_SAVE_COMPLETE, []); - } - }); + this.broadCast.on(PhotoConstants.TOGGLE_BAR, this.onToggleBarsFunc); + this.broadCast.on(PhotoConstants.HIDE_BARS, this.hideBarsFunc); + this.broadCast.on(PhotoConstants.SHOW_BARS, this.showBarsFunc); + this.broadCast.on(PhotoConstants.PULL_DOWN_START, this.pullDownStartFunc); + this.broadCast.on(PhotoConstants.PULL_DOWN_END, this.pullDownEndFunc); + this.broadCast.on(PhotoConstants.DATA_SIZE_CHANGED, this.onDataSizeChangedFunc); + this.broadCast.on(PhotoConstants.DATA_CONTENT_CHANGED, this.onDataContentChangedFunc); + this.broadCast.on(PhotoConstants.SET_FAVOR, this.setFavorFunc); + this.broadCast.on(PhotoConstants.RENAME, this.doRenameFunc); + this.broadCast.on(PhotoConstants.ROTATE, this.doRotateFunc); + this.broadCast.on(PhotoConstants.PULL_DOWN_START, this.pullDownStartWithEventFunc); + this.broadCast.on(PhotoConstants.PULL_DOWN_CANCEL, this.pullDownCancelFunc); + this.broadCast.on(PhotoConstants.PHOTO_BROWSER_DELETE_CONFIRM, this.onPhotoBrowserDeleteConfirmFunc); + this.broadCast.on(PhotoConstants.PHOTO_BROWSER_REMOVE_CONFIRM, this.onPhotoBrowserRemoveConfirmFunc); + this.broadCast.on(PhotoConstants.DELETE, this.doDeleteFunc); + this.broadCast.on(PhotoConstants.PHOTO_SHOW_STATE, this.onPhotoShowStateChangedFunc); + this.broadCast.on(PhotoConstants.SET_DISABLE_SWIPE, this.setSwiperDisableFunc); + this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED_WITH_EDIT, this.onDataReloadWithEditFunc); this.appBroadCast.on(BroadCastConstants.PHOTO_BROWSER_BACK_PRESS_EVENT, this.photoBrowserBackFunc); - let msg = { - 'From': BigDataConstants.LOCAL_MEDIA, - 'FovMode': 0 + interface MsgNavigation { + from: string; + fovMode: number; + } + + let msg: MsgNavigation = { + from: BigDataConstants.LOCAL_MEDIA, + fovMode: 0 } ReportToBigDataUtil.report(BigDataConstants.ENTER_PHOTO_BROWSER_ID, msg); this.breakpointSystem.registerOrientationChange(); TraceControllerUtils.finishTrace('PhotoBrowserAboutToAppear'); } + onToggleBars(backgroundColorResource?: Resource): void { + if (this.isShowBar) { + this.hideBars(backgroundColorResource); + } else { + this.showBars(backgroundColorResource); + } + Log.info(TAG, `Toggle bars, isShowBar: ${this.isShowBar}`); + } + + showBars(backgroundColorResource?: Resource): void { + this.backgroundColorResource = backgroundColorResource ? + backgroundColorResource : $r('app.color.default_background_color'); + if (!this.isShowBar) { + this.isShowBar = !this.isShowBar; + if (!this.isHorizontal) { + ScreenManager.getInstance().setSystemUi(true); + } + } else { + this.onlyChangeBgColor = !this.onlyChangeBgColor; + } + } + + hideBars(backgroundColorResource?: Resource): void { + this.backgroundColorResource = backgroundColorResource ? + backgroundColorResource : $r('app.color.black'); + if (this.isShowBar) { + this.isShowBar = !this.isShowBar; + ScreenManager.getInstance().setSystemUi(false); + } else { + this.onlyChangeBgColor = !this.onlyChangeBgColor; + } + } + + private pullDownStart(): void { + Log.info(TAG, 'pulling down start'); + } + + private pullDownEnd(): void { + Log.info(TAG, 'pulling down end'); + if (this.isFromFACard) { + this.isPullDown = true; + } + this.onBackPress(); + } + + private onDataContentChanged(): void { + this.reportToBigDataForCameraIn(); + Log.debug(TAG, `PhotoConstants.DATA_CONTENT_CHANGED`); + this.onPhotoChanged(this.currentIndex); + } + + private setFavor(isFavor: boolean): void { + Log.debug(TAG, 'set favor !') + let currentPhoto = this.getCurrentPhoto(); + if (!isFavor) { + currentPhoto.isFavor = isFavor; + this.updateMenu(); + } else { + Log.debug(TAG, 'update favor !'); + } + } + + private doRename(result: TitleName): void { + Log.info(TAG, `rename refresh: ${result.title}, ${result.displayName}`); + this.updatePhotoName(result); + } + + private doRotate(result: number): void { + Log.debug(TAG, `rotate finish: ${result}`); + let currentPhoto = this.getCurrentPhoto(); + currentPhoto.orientation = result; + let temp = currentPhoto.height; + currentPhoto.height = currentPhoto.width; + currentPhoto.width = temp; + this.dataSource.onDataChanged(this.currentIndex); + this.appBroadCast.emit(BroadCastConstants.UPDATE_DATA_SOURCE, [currentPhoto]); + } + + private pullDownStartWithEvent(event: KeyEvent): void { + Log.debug(TAG, `pulling down start : ${JSON.stringify(event)}`); + if (this.isFromViewDataWithThirdUri) { + return; + } + } + + private pullDownCancel(): void { + Log.info(TAG, 'pulling down cancel'); + } + + private onPhotoBrowserDeleteConfirm(): void { + this.isDeleting = true; + // clear temp not favorite items + if (this.albumUri == UserFileManagerAccess.getInstance() + .getSystemAlbumUri(UserFileManagerAccess.FAVORITE_ALBUM_SUB_TYPE)) { + let key = this.theDeleteItem?.uri ?? ''; + if (this.favorCacheItemsMap.has(key)) { + let item = this.favorCacheItemsMap.get(key) + let menuFavorContext = new MenuContext().withMediaItem(item as MediaItem).withBroadCast(this.broadCast); + let menuFavorOperation = MenuOperationFactory.getInstance() + .createMenuOperation(FavoriteMenuOperation, menuFavorContext); + menuFavorOperation.doAction(); + this.favorCacheItemsMap.delete(key); + } + } + } + + private onPhotoBrowserRemoveConfirm(): void { + this.isDeleting = true; + } + + private doDelete(): void { + Log.info(TAG, 'delete finish now update data'); + } + + private onPhotoShowStateChanged(state: boolean): void { + Log.debug(TAG, 'current photo show state change'); + this.currentShow = state; + } + + private setSwiperDisable(value: boolean): void { + Log.info(TAG, `set swiper swipe ${value}`); + this.canSwipe = value; + } + + private onDataReloadWithEdit(): void { + Log.debug(TAG, 'animate to data reloaded start with edit'); + try { + let uri: string = AppStorage.get(BroadCastConstants.PHOTO_EDIT_SAVE_URI) as string; + Log.debug(TAG, `data reloaded start with edit by uri ${uri}`); + if (uri) { + let newIndex = this.dataSource.getDataIndexByUri(uri); + let oldIndex = this.currentIndex; + if (newIndex != Constants.NOT_FOUND) { + // Search for the position of new image/video after edit in current 500 items succeed + Log.debug(TAG, `data reloaded from ${oldIndex} move to ${newIndex}`); + this.onPhotoChanged(newIndex); + } else { + // Search for the position of new image/video after edit in current 500 items failed + Log.debug(TAG, `data reloaded from ${oldIndex} move to unknown`); + this.editNewUri = uri; + this.dataSource.enableGetData(false); + this.currentIndex = 0; + this.dataSource.getItemIndexByUri(uri, (index: number): void => this.onGetItemIndexByNewEditUri(index)); + } + } + } catch (e) { + Log.error(TAG, `ON_DATA_RELOADED_WITH_EDIT error ${e}`); + } finally { + this.appBroadCast.emit(BroadCastConstants.PHOTO_EDIT_SAVE_COMPLETE, []); + } + } + private photoBrowserBack(): void { Log.debug(TAG, 'hook back press from page.'); this.onBackPress(); @@ -1035,7 +1082,7 @@ export struct PhotoBrowserComponent { if (this.uriFromThirdPartyApp) { if (index != Constants.NOT_FOUND) { this.currentIndex = index; - this.uriFromThirdPartyApp = null; + this.uriFromThirdPartyApp = ''; this.dataSource.enableGetData(true); this.dataSource.getData(this.currentIndex); this.dataSource.onDataReloaded(); @@ -1050,16 +1097,16 @@ export struct PhotoBrowserComponent { } else { Log.error(TAG, `Uri from others is invalid`); } - this.uriFromThirdPartyApp = null; + this.uriFromThirdPartyApp = ''; this.dataSource.enableGetData(true); this.setViewDataResult(false); } else if (this.albumUri === "") { this.resetAlbum(UserFileManagerAccess.getInstance() .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)); - this.dataSource.getItemIndexByUri(this.uriFromThirdPartyApp, this.onGetItemIndexByUri.bind(this)); + this.dataSource.getItemIndexByUri(this.uriFromThirdPartyApp, (index: number): void => this.onGetItemIndexByUri(index)); } else { this.resetAlbum(""); - this.dataSource.getItemIndexByUri(this.uriFromThirdPartyApp, this.onGetItemIndexByUri.bind(this)); + this.dataSource.getItemIndexByUri(this.uriFromThirdPartyApp, (index: number): void => this.onGetItemIndexByUri(index)); } } this.onPhotoChanged(this.currentIndex); @@ -1096,7 +1143,7 @@ export struct PhotoBrowserComponent { onPageShow(): void { TraceControllerUtils.startTrace('PhotoBrowseronPageShow'); Log.info(TAG, 'photoBrowser page show'); - WindowUtil.setPreferredOrientation(globalThis.photosAbilityContext, + WindowUtil.setPreferredOrientation(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, window.Orientation.AUTO_ROTATION_RESTRICTED); let currentPhoto = this.getCurrentPhoto(); if (currentPhoto) { @@ -1115,47 +1162,48 @@ export struct PhotoBrowserComponent { this.appBroadCast.emit(BroadCastConstants.PHOTO_BROWSER_ACTIVE, [true, this.checkedTransition]); this.broadCast.emit(BroadCastConstants.CHANGE_SWIPER_DURATION, [400]); this.viewTime = Date.now(); - let params: any = router.getParams(); + let params: Params = router.getParams() as Params; if (params != null && params.pageType != null && this.backFromCopy) { Log.debug(TAG, `MediaOperation back ${JSON.stringify(params)}`) let menuContext = new MenuContext(); - let menuOperation: MenuOperation; + let menuOperation: MenuOperation | null = null; if (currentPhoto == undefined) { Log.error(TAG, 'MediaOperation currentPhoto is undefined'); return; } - switch (params.pageType) { - case MediaOperationType.Move: - this.onMoveEnd = this.onMoveEnd.bind(this); - menuContext.withMediaItem(currentPhoto) - .withBroadCast(this.broadCast) - .withTargetAlbumName(params.albumName) - .withAlbumUri(params.albumUri) - .withOperationEndCallback(this.onMoveEnd); - menuOperation = MenuOperationFactory.getInstance().createMenuOperation(MoveMenuOperation, menuContext); - AppStorage.SetOrCreate(Constants.APP_KEY_NEW_ALBUM_SOURCE, this.albumInfo.uri); - break; - case MediaOperationType.Remove: - this.onMoveEnd = this.onMoveEnd.bind(this); - menuContext.withMediaItem(currentPhoto) - .withBroadCast(this.broadCast) - .withTargetAlbumName(params.albumName) - .withAlbumUri(params.albumUri) - .withOperationEndCallback(this.onMoveEnd); - menuOperation = MenuOperationFactory.getInstance().createMenuOperation(RemoveMenuOperation, menuContext); - AppStorage.SetOrCreate(Constants.APP_KEY_NEW_ALBUM_SOURCE, this.albumInfo.uri); - break; - case MediaOperationType.Add: // "添加到"不需要设置源相册 - this.onCopyEnd = this.onCopyEnd.bind(this); - menuContext.withMediaItem(currentPhoto) - .withBroadCast(this.broadCast) - .withTargetAlbumName(params.albumName) - .withAlbumUri(params.albumUri) - .withOperationEndCallback(this.onCopyEnd); - menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddMenuOperation, menuContext); - this.appBroadCast.emit(BroadCastConstants.PHOTO_BROWSER_ACTIVE, [false, this.checkedTransition]); - break; + if (params.pageType === MediaOperationType.Move) { + let onMoveEndFunc = async (err: Error, count: number, total: number): Promise => { + await this.onMoveEnd(err as Object, count, total)}; + menuContext.withMediaItem(currentPhoto) + .withBroadCast(this.broadCast) + .withTargetAlbumName(params.albumName) + .withAlbumUri(params.albumUri) + .withOperationEndCallback(onMoveEndFunc); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(MoveMenuOperation, menuContext); + AppStorage.setOrCreate(Constants.APP_KEY_NEW_ALBUM_SOURCE, this.albumInfo?.uri); + } else if (params.pageType === MediaOperationType.Remove) { + let onMoveEndFunc = async (err: Error, count: number, total: number): Promise => { + await this.onMoveEnd(err as Object, count, total)}; + menuContext.withMediaItem(currentPhoto) + .withBroadCast(this.broadCast) + .withTargetAlbumName(params.albumName) + .withAlbumUri(params.albumUri) + .withOperationEndCallback(onMoveEndFunc); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(RemoveMenuOperation, menuContext); + AppStorage.setOrCreate(Constants.APP_KEY_NEW_ALBUM_SOURCE, this.albumInfo?.uri); + } else if (params.pageType === MediaOperationType.Add) { + // "添加到"不需要设置源相册 + let onCopyEndFunc = (err: Error, count: number, total: number): void => { + this.onCopyEnd(err as Object, count, total)}; + menuContext.withMediaItem(currentPhoto) + .withBroadCast(this.broadCast) + .withTargetAlbumName(params.albumName) + .withAlbumUri(params.albumUri) + .withOperationEndCallback(onCopyEndFunc); + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddMenuOperation, menuContext); + this.appBroadCast.emit(BroadCastConstants.PHOTO_BROWSER_ACTIVE, [false, this.checkedTransition]); } + if (menuOperation != null) { menuOperation.doAction(); } @@ -1167,11 +1215,11 @@ export struct PhotoBrowserComponent { onPageHide(): void { Log.info(TAG, `call onPageHide`); this.appBroadCast.emit(BroadCastConstants.PHOTO_BROWSER_ACTIVE, [false, this.checkedTransition]); - WindowUtil.setPreferredOrientation(globalThis.photosAbilityContext, + WindowUtil.setPreferredOrientation(AppStorage.get('photosAbilityContext') as common.UIAbilityContext, window.Orientation.UNSPECIFIED); } - onMediaLibDataChange(changeType): void { + onMediaLibDataChange(changeType: string): void { Log.info(TAG, `onMediaLibDataChange type: ${changeType}`); this.dataSource.onChange(changeType); } @@ -1187,7 +1235,7 @@ export struct PhotoBrowserComponent { dataSource: this.dataSource, mTransition: this.mTransition, swiperController: this.controller, - onPhotoChanged: this.onPhotoChanged.bind(this), + onPhotoChanged: (index: number): void => this.onPhotoChanged(index), geometryTransitionEnable: this.geometryTransitionEnable, broadCast: $broadCast, isRunningAnimation: $isRunningAnimation, @@ -1196,7 +1244,7 @@ export struct PhotoBrowserComponent { if (!this.isFromViewDataWithThirdUri) { PhotoBrowserActionBar({ - onMenuClicked: this.onMenuClicked.bind(this), + onMenuClicked: (action: Action): void => this.onMenuClicked(action), }) .opacity(this.geometryOpacity) // @ts-ignore @@ -1204,7 +1252,7 @@ export struct PhotoBrowserComponent { if (!this.isHorizontal) { PhotoBrowserToolBar({ - onMenuClicked: this.onMenuClicked.bind(this), + onMenuClicked: (action: Action): void => this.onMenuClicked(action), isFromPhotoBrowser: true }) .opacity(this.geometryOpacity) @@ -1221,7 +1269,7 @@ export struct PhotoBrowserComponent { } else { PhotoBrowserActionBar({ - onMenuClicked: this.onMenuClicked.bind(this), + onMenuClicked: (action: Action): void => this.onMenuClicked(action), }) .opacity(this.geometryOpacity) .transition(TransitionEffect.opacity(0)) @@ -1239,12 +1287,13 @@ export struct PhotoBrowserComponent { resultCode = -1; } - let abilityResult = { - 'resultCode': resultCode, - 'want': {} + let abilityResult: ability.AbilityResult = { + resultCode: resultCode, + want: {} }; - globalThis.photosAbilityContext.terminateSelfWithResult(abilityResult).then((result) => { + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelfWithResult(abilityResult).then((result: void) => { Log.info(TAG, `terminateSelfWithResult result: ${result}`); }); } @@ -1254,7 +1303,8 @@ export struct PhotoBrowserComponent { let menuContext = new MenuContext(); let menuOperation: MenuOperation; let currentPhoto = this.getCurrentPhoto(); - this.onDownloadEnd = this.onDownloadEnd.bind(this); + let onDownloadEndFunc = async (err: Error, count: number, total: number): Promise => { + await this.onDownloadEnd(err as Object, count, total)}; if (currentPhoto == undefined) { Log.error(TAG, 'MediaOperation currentPhoto is undefined'); return; @@ -1263,7 +1313,7 @@ export struct PhotoBrowserComponent { .withMediaItem(currentPhoto) .withBroadCast(this.broadCast) .withRemoteDevice('0') // TODO input deviceId - .withOperationEndCallback(this.onDownloadEnd) + .withOperationEndCallback(onDownloadEndFunc) menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddMenuOperation, menuContext); this.appBroadCast.emit(BroadCastConstants.PHOTO_BROWSER_ACTIVE, [false, this.checkedTransition]); menuOperation.doAction(); @@ -1273,10 +1323,14 @@ export struct PhotoBrowserComponent { let currentPhoto = this.getCurrentPhoto(); if (currentPhoto && index != this.currentIndex && this.viewTime != 0) { let currentTime = Date.now(); - let msg = { - 'type': currentPhoto.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO ? + interface Msg { + type: string; + duration: number; + } + let msg: Msg = { + type: currentPhoto.mediaType == UserFileManagerAccess.MEDIA_TYPE_VIDEO ? BigDataConstants.VIDEO : BigDataConstants.NORMAL_PHOTO, - 'duration': (currentTime - this.viewTime) + duration: (currentTime - this.viewTime) } ReportToBigDataUtil.report(BigDataConstants.PHOTO_BROWSER_SLIDE_ID, msg); this.viewTime = Date.now(); @@ -1287,25 +1341,33 @@ export struct PhotoBrowserComponent { if (this.clickThumbnailTime == 0 || !this.isFromCamera) { return; } - let msg = { - 'clickThumbnailTime': this.clickThumbnailTime, + interface Msg { + clickThumbnailTime: number; + ShowSinglePhoto: number; + FileName?: string; + } + let msg: Msg = { + clickThumbnailTime: this.clickThumbnailTime, + ShowSinglePhoto: Date.now() } let fileName = ReportToBigDataUtil.getFileNameOfPhotoTakenByCamera(this.getPhotoByIndex(0)); ReportToBigDataUtil.setFileNameProperty(msg, fileName); - Object.defineProperty(msg, 'ShowSinglePhoto', { value: Date.now(), enumerable: true }); ReportToBigDataUtil.report(BigDataConstants.BROWSE_PHOTO_FROM_CAMERA_ID, msg); this.clickThumbnailTime = 0; } - private async syncPhotoName(currentPhoto: MediaItem): Promise<{title: string, displayName: string}> { + private async syncPhotoName(currentPhoto: MediaItem): Promise { Log.debug(TAG, 'syncPhotoName start'); - let renameResult: {title: string, displayName: string} = {title: '', displayName: ''}; + let renameResult: TitleName = {title: '', displayName: ''}; let fileAsset = await this.dataSource.getDataByUri(currentPhoto.uri); if (fileAsset) { - renameResult = {title: fileAsset.get(UserFileManagerAccess.FILE_KEY_TITLE.toString()), displayName: fileAsset.displayName} + renameResult = { + title: fileAsset.get(UserFileManagerAccess.FILE_KEY_TITLE.toString()) as string, + displayName: fileAsset.displayName + }; } else { let key: string = 'renameResult' + currentPhoto.uri; - renameResult = AppStorage.Get<{title: string, displayName: string}>(key); + renameResult = AppStorage.get(key) as TitleName; AppStorage.Delete(key); } Log.debug(TAG, `syncPhotoName end, renameResult : ${JSON.stringify(renameResult)}`); diff --git a/product/phone/src/main/ets/view/PhotoGridView.ets b/product/phone/src/main/ets/view/PhotoGridView.ets index ce903386..4b8115ac 100644 --- a/product/phone/src/main/ets/view/PhotoGridView.ets +++ b/product/phone/src/main/ets/view/PhotoGridView.ets @@ -88,13 +88,13 @@ export struct PhotoGridView { @StorageLink('isSplitMode') isSplitMode: boolean = ScreenManager.getInstance().isSplitMode(); @StorageLink('leftBlank') leftBlank: number[] = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()]; - @Prop @Watch('onPageChanged') pageStatus: boolean; + @Prop @Watch('onPageChanged') pageStatus: boolean = false; @State gridItemWidth: number = 0; @StorageLink('photoGridActionBarOpacity') photoGridActionBarOpacity: number = 0; @StorageLink('photoGridViewOpacity') photoGridViewOpacity: number = 0; - albumInfo: AlbumInfo; - title: string; - deviceName: string; + albumInfo: AlbumInfo = new AlbumInfo(); + title: string = ''; + deviceName: string = ''; dataSource: MediaDataSource = new MediaDataSource(Constants.DEFAULT_SLIDING_WIN_SIZE); scroller: Scroller = new Scroller(); isDataFreeze = false; @@ -111,14 +111,23 @@ export struct PhotoGridView { private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); // 选择模式下,鼠标对着未勾选项按右键弹框时,移动和复制菜单点击事件的标识位 private isMvOrCpSeparatesItem: boolean = false; - private mvOrCpSeparatesItem: MediaItem = null; - private photoTotalCount: number; - private params: any; + private mvOrCpSeparatesItem: MediaItem = new MediaItem(); + private photoTotalCount: number = 0; + private params: Params | null = null; private scrollIndex: number = 0; - onWindowSizeChangeCallBack = () => { + private onWindowSizeChangeCallBack: Function = () => { // 后续phone缩略图支持横竖屏后再放开 // this.initGridRowCount; } + private selectFunc: Function = (position: number, key: string, value: boolean, callback: Function): void => this.select(position, key, value, callback); + private jumpPhotoBrowserFunc: Function = (name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void => + this.jumpPhotoBrowser(name, item, geometryTapIndex, geometryTransitionString); + private jumpThirdPhotoBrowserFunc: Function = (name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void => + this.jumpThirdPhotoBrowser(name, item, geometryTapIndex, geometryTransitionString); + private onLoadingFinishedFunc: Function = (size: number): void => this.onLoadingFinished(size); + private doAnimationFunc: Function = (): void => this.doAnimationFn(); + private onDataReloadedFunc: Function = (): void => this.onDataReloaded(); + private onUpdateFavorStateFunc: Function = (item: MediaItem): void => this.onUpdateFavorState(item); onPlaceholderChanged() { Log.debug(TAG, 'onPlaceholderChanged placeholderIndex is ' + this.placeholderIndex); @@ -175,138 +184,110 @@ export struct PhotoGridView { Log.info(TAG, `onMenuClicked, action: ${action.actionID}`); let menuContext: MenuContext; let menuOperation: MenuOperation; - switch (action.actionID) { - case Action.BACK.actionID: - if (this.isFromFACard) { - router.replaceUrl({ - url: 'pages/index', - params: { - jumpSource: JumpSourceToMain.ALBUM, - } - }); - } else { - if (router.getState().name === Constants.USER_FILE_MANAGER_PHOTO_TRANSITION_ALBUM) { - router.back(); - } else { - this.doAnimation(); + if (action.actionID === Action.BACK.actionID) { + if (this.isFromFACard) { + router.replaceUrl({ + url: 'pages/index', + params: { + jumpSource: JumpSourceToMain.ALBUM, } + }); + } else { + if (router.getState().name === Constants.USER_FILE_MANAGER_PHOTO_TRANSITION_ALBUM) { + router.back(); + } else { + this.doAnimation(); } - break; - case Action.CANCEL.actionID: - this.onModeChange(); - break; - case Action.MULTISELECT.actionID: - this.isSelectedMode = true; - break; - case Action.SELECT_ALL.actionID: - this.mSelectManager.selectAll(true); - break; - case Action.DESELECT_ALL.actionID: - this.mSelectManager.deSelectAll(); - break; - case Action.DELETE.actionID: - menuContext = new MenuContext(); - this.onDeleteStart = this.onDeleteStart.bind(this); - this.onDeleteEnd = this.onDeleteEnd.bind(this); - menuContext - .withSelectManager(this.mSelectManager) - .withOperationStartCallback(this.onDeleteStart) - .withOperationEndCallback(this.onDeleteEnd) - .withBroadCast(this.broadCast) - .withAlbumUri(this.albumInfo.uri) - .withFromSelectMode(this.isSelectedMode) - .withAlbumInfo(this.albumInfo) - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(BatchDeleteMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.SHARE.actionID: - menuContext = new MenuContext(); - menuContext.withFromSelectMode(true).withSelectManager(this.mSelectManager); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(ShareMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.INFO.actionID: - this.hidePopup = true; - this.openDetailsDialog(); - break; - case Action.CLEAR_RECYCLE.actionID: - menuContext = new MenuContext(); - this.onDeleteStart = this.onDeleteStart.bind(this); - this.onDeleteEnd = this.onDeleteEnd.bind(this); - menuContext - .withSelectManager(this.mSelectManager) - .withOperationStartCallback(this.onDeleteStart) - .withOperationEndCallback(this.onDeleteEnd) - .withBroadCast(this.broadCast) - .withAlbumUri(UserFileManagerAccess.getInstance() - .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)) - .withAlbumInfo(this.albumInfo) - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(ClearRecycleMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.RECOVER.actionID: - menuContext = new MenuContext(); - this.onDeleteStart = this.onDeleteStart.bind(this); - this.onDeleteEnd = this.onDeleteEnd.bind(this); - menuContext - .withAlbumUri(UserFileManagerAccess.getInstance() - .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)) - .withSelectManager(this.mSelectManager) - .withOperationStartCallback(this.onDeleteStart) - .withOperationEndCallback(this.onDeleteEnd) - .withBroadCast(this.broadCast) - .withAlbumInfo(this.albumInfo) - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(BatchRecoverMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.MOVE.actionID: - this.mSelectManager.getSelectedItems((selectedItems: Array) => { - Log.info(TAG, `Get selected items success, size: ${selectedItems.length}, start route to select album page`); - this.routeToSelectAlbumPage(MediaOperationType.Move, selectedItems); - }) - break; - case Action.ADD.actionID: - this.mSelectManager.getSelectedItems((selectedItems: Array) => { - Log.info(TAG, `Get selected items success, size: ${selectedItems.length}, start route to select album page`); - this.routeToSelectAlbumPage(MediaOperationType.Add, selectedItems); - }) - break; - case Action.REMOVE_FROM.actionID: - menuContext = new MenuContext(); - this.onRemoveStart = this.onRemoveStart.bind(this); - this.onRemoveEnd = this.onRemoveEnd.bind(this); - menuContext - .withSelectManager(this.mSelectManager) - .withOperationStartCallback(this.onRemoveStart) - .withOperationEndCallback(this.onRemoveEnd) - .withBroadCast(this.broadCast) - .withAlbumUri(this.albumInfo.uri) - .withFromSelectMode(this.isSelectedMode) - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(BatchRemoveMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.NEW.actionID: - this.routeToAddMediaPage(); - break; - case Action.DOWNLOAD.actionID: - this.onDownloadStart = this.onDownloadStart.bind(this); - this.onDownloadEnd = this.onDownloadEnd.bind(this); - menuContext = new MenuContext(); - menuContext - .withSelectManager(this.mSelectManager) - .withOperationStartCallback(this.onDownloadStart) - .withOperationEndCallback(this.onDownloadEnd) - .withBroadCast(this.broadCast) - menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddMenuOperation, menuContext); - menuOperation.doAction(); - break; - default: - break; + } + } else if (action.actionID === Action.CANCEL.actionID) { + this.onModeChange(); + } else if (action.actionID === Action.MULTISELECT.actionID) { + this.isSelectedMode = true; + } else if (action.actionID === Action.SELECT_ALL.actionID) { + this.mSelectManager.selectAll(true); + } else if (action.actionID === Action.DESELECT_ALL.actionID) { + this.mSelectManager.deSelectAll(); + } else if (action.actionID === Action.DELETE.actionID) { + menuContext = new MenuContext(); + menuContext + .withSelectManager(this.mSelectManager) + .withOperationStartCallback((): void => this.onDeleteStart()) + .withOperationEndCallback((): void => this.onDeleteEnd()) + .withBroadCast(this.broadCast) + .withAlbumUri(this.albumInfo.uri) + .withFromSelectMode(this.isSelectedMode) + .withAlbumInfo(this.albumInfo) + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(BatchDeleteMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.SHARE.actionID) { + menuContext = new MenuContext(); + menuContext.withFromSelectMode(true).withSelectManager(this.mSelectManager); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(ShareMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.INFO.actionID) { + this.hidePopup = true; + this.openDetailsDialog(); + } else if (action.actionID === Action.CLEAR_RECYCLE.actionID) { + menuContext = new MenuContext(); + menuContext + .withSelectManager(this.mSelectManager) + .withOperationStartCallback((): void => this.onDeleteStart()) + .withOperationEndCallback((): void => this.onDeleteEnd()) + .withBroadCast(this.broadCast) + .withAlbumUri(UserFileManagerAccess.getInstance() + .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)) + .withAlbumInfo(this.albumInfo) + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(ClearRecycleMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.RECOVER.actionID) { + menuContext = new MenuContext(); + menuContext + .withAlbumUri(UserFileManagerAccess.getInstance() + .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)) + .withSelectManager(this.mSelectManager) + .withOperationStartCallback((): void => this.onDeleteStart()) + .withOperationEndCallback((): void => this.onDeleteEnd()) + .withBroadCast(this.broadCast) + .withAlbumInfo(this.albumInfo) + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(BatchRecoverMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.MOVE.actionID) { + this.mSelectManager.getSelectedItems((selectedItems: Array) => { + Log.info(TAG, `Get selected items success, size: ${selectedItems.length}, start route to select album page`); + this.routeToSelectAlbumPage(MediaOperationType.Move, selectedItems); + }) + } else if (action.actionID === Action.ADD.actionID) { + this.mSelectManager.getSelectedItems((selectedItems: Array) => { + Log.info(TAG, `Get selected items success, size: ${selectedItems.length}, start route to select album page`); + this.routeToSelectAlbumPage(MediaOperationType.Add, selectedItems); + }) + } else if (action.actionID === Action.REMOVE_FROM.actionID) { + menuContext = new MenuContext(); + menuContext + .withSelectManager(this.mSelectManager) + .withOperationStartCallback((): void => this.onRemoveStart()) + .withOperationEndCallback((): void => this.onRemoveEnd()) + .withBroadCast(this.broadCast) + .withAlbumUri(this.albumInfo.uri) + .withFromSelectMode(this.isSelectedMode) + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(BatchRemoveMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.NEW.actionID) { + this.routeToAddMediaPage(); + } else if (action.actionID === Action.DOWNLOAD.actionID) { + menuContext = new MenuContext(); + menuContext + .withSelectManager(this.mSelectManager) + .withOperationStartCallback((): void => this.onDownloadStart()) + .withOperationEndCallback(async (err: Error, count: number, total: number): Promise => this.onDownloadEnd(err as Object, count, total)) + .withBroadCast(this.broadCast) + menuOperation = MenuOperationFactory.getInstance().createMenuOperation(AddMenuOperation, menuContext); + menuOperation.doAction(); } } @@ -371,7 +352,7 @@ export struct PhotoGridView { this.dataSource.freeze(); } - onCopyEnd(err, count, total): void { + onCopyEnd(err: Object, count: number, total: number): void { Log.info(TAG, `onCopyEnd count: ${count}, total: ${total}`); this.isDataFreeze = false; this.onModeChange(); @@ -390,7 +371,7 @@ export struct PhotoGridView { this.dataSource.freeze(); } - async onDownloadEnd(err, count, total): Promise { + async onDownloadEnd(err: Object, count: number, total: number): Promise { Log.info(TAG, `onDownloadEnd count: ${count}, total: ${total}`); this.isDataFreeze = false; this.onModeChange(); @@ -422,7 +403,7 @@ export struct PhotoGridView { this.dataSource.freeze(); } - onMoveEnd(err, count, total): void { + onMoveEnd(err: Object, count: number, total: number): void { Log.info(TAG, `onMoveEnd count: ${count}, total: ${total}`); this.isDataFreeze = false; this.onModeChange(); @@ -469,18 +450,6 @@ export struct PhotoGridView { this.dataSource.unfreeze(); } - freezeAdapter(fn): Function { - let _self = this; - return function () { - if (_self.isDataFreeze) { - return; - } - let context = this; - let args = arguments; - fn.apply(context, args); - } - } - onModeChange(): void { Log.info(TAG, 'onModeChange'); this.isSelectedMode = false; @@ -489,7 +458,7 @@ export struct PhotoGridView { } onPageChanged(): void { - this.params = router.getParams(); + this.params = router.getParams() as Params; if (this.pageStatus) { this.onPageShow(); } else { @@ -502,20 +471,15 @@ export struct PhotoGridView { this.isShow = true; if (this.routerStart && this.params != null && this.params.pageType != null) { Log.info(TAG, 'MediaOperation back'); - switch (this.params.pageType) { - case MediaOperationType.Move: - this.moveOperation(this.params.albumName, this.params.albumUri); - break; - case MediaOperationType.Add: - this.addOperation(this.params.albumName, this.params.albumUri); - break; - default: - break; + if (this.params.pageType === MediaOperationType.Move) { + this.moveOperation(this.params.albumName, this.params.albumUri); + } else if (this.params.pageType === MediaOperationType.Add) { + this.addOperation(this.params.albumName, this.params.albumUri); } } MediaObserver.getInstance().registerObserver(this.dataObserver); this.isMvOrCpSeparatesItem = false; - this.mvOrCpSeparatesItem = null; + this.mvOrCpSeparatesItem = new MediaItem(); this.routerStart = false; this.onActive(); } @@ -576,13 +540,13 @@ export struct PhotoGridView { this.photoGridActionBarOpacity = 1; this.photoGridViewOpacity = 1; } - let param: any; - param = router.getParams(); + let param: ParamAlbumInfo; + param = router.getParams() as ParamAlbumInfo; if (!param || (param && !param.item)) { - param = AppStorage.Get(Constants.KEY_OF_PHOTO_GRID_VIEW_ALBUM_ITEM); + param = AppStorage.get(Constants.KEY_OF_PHOTO_GRID_VIEW_ALBUM_ITEM) as ParamAlbumInfo; } if (param != null) { - if (!!param.isFromFACard) { + if (param.isFromFACard) { this.isFromFACard = param.isFromFACard; } this.albumInfo = JSON.parse(param.item); @@ -598,98 +562,43 @@ export struct PhotoGridView { } let self = this; - this.onMenuClicked = this.onMenuClicked.bind(this); - this.onMenuClickedForSingleItem = this.onMenuClickedForSingleItem.bind(this); this.dataSource.setBroadCast(this.broadCast) this.mSelectManager.setPhotoDataImpl(); this.mSelectManager.setAlbumUri(this.albumInfo.uri); MediaObserver.getInstance().registerObserver(this.dataObserver); - this.broadCast.on(BroadCastConstants.SELECT, - (position: number, key: string, value: boolean, callback: Function) => { - if (self.mSelectManager.toggle(key, value, position)) { - Log.info(TAG, 'enter event process') - if (!self.isSelectedMode) { - self.isSelectedMode = true; - } - callback(); - } - }); - this.broadCast.on(BroadCastConstants.JUMP_PHOTO_BROWSER, (name: string, item: MediaItem, geometryTapIndex: number, - geometryTransitionString: string) => { - let targetIndex = self.dataSource.getDataIndex(item); - if (targetIndex == Constants.NOT_FOUND) { - Log.error(TAG, 'targetIndex is not found'); - return; - } - Log.info(TAG, `jump to photo browser at index: ${targetIndex}`); - let pageEntryFrom = Constants.ENTRY_FROM.NORMAL; - if (self.albumInfo.isTrashAlbum) { - pageEntryFrom = Constants.ENTRY_FROM.RECYCLE; - } else if (self.isDistributedAlbum) { - pageEntryFrom = Constants.ENTRY_FROM.DISTRIBUTED; - } - - AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, self.dataSource); - if (geometryTapIndex !== undefined && geometryTransitionString !== undefined) { - this.jumpToPhotoBrowserGeometryTransition( - targetIndex, name, pageEntryFrom, geometryTapIndex, geometryTransitionString); - } else { - this.jumpToPhotoBrowserNormal(targetIndex, name, pageEntryFrom); - } - }); - this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, (name: string, item: MediaItem, - geometryTapIndex: number, - geometryTransitionString: string) => { - Log.info(TAG, 'JUMP_THIRD_PHOTO_BROWSER'); - let targetIndex = self.dataSource.getDataIndex(item); - if (targetIndex == Constants.NOT_FOUND) { - Log.error(TAG, 'targetIndex is not found'); - return; - } - Log.info(TAG, `jump to photo browser at index: ${targetIndex} ${name}`); - let pageEntryFrom = Constants.ENTRY_FROM.NORMAL; - if (self.albumInfo.isTrashAlbum) { - pageEntryFrom = Constants.ENTRY_FROM.RECYCLE; - } else if (self.isDistributedAlbum) { - pageEntryFrom = Constants.ENTRY_FROM.DISTRIBUTED; - } - AppStorage.SetOrCreate(Constants.PHOTO_GRID_SELECT_MANAGER, self.mSelectManager); - AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, self.dataSource); - if (geometryTapIndex !== undefined && geometryTransitionString !== undefined) { - this.jumpToSelectPhotoBrowserGeometryTransition( - targetIndex, name, pageEntryFrom, geometryTapIndex, geometryTransitionString); - } else { - this.jumpToSelectPhotoBrowserNormal(targetIndex, name, pageEntryFrom); - } - }); - this.broadCast.on(Constants.ON_LOADING_FINISHED, (size: number) => { - Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); - }); - - this.appBroadCast.on(BroadCastConstants.DO_ANIMATION, () => { - this.doAnimation(); - this.appBroadCast.off(BroadCastConstants.DO_ANIMATION, null) - }); - - this.appBroadCast.on(BroadCastConstants.UPDATE_DATA_SOURCE, this.onUpdateFavorState.bind(this)); + this.broadCast.on(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.on(BroadCastConstants.JUMP_PHOTO_BROWSER, this.jumpPhotoBrowserFunc); + this.broadCast.on(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.on(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); + this.broadCast.on(BroadCastConstants.DO_ANIMATION, this.doAnimationFunc); + this.appBroadCast.on(BroadCastConstants.UPDATE_DATA_SOURCE, this.onUpdateFavorStateFunc); AppStorage.SetOrCreate(Constants.PHOTO_GRID_SELECT_MANAGER, this.mSelectManager); - this.mSelectManager.registerCallback('allSelect', this.freezeAdapter((newState: boolean) => { + this.mSelectManager.registerCallback('allSelect', (newState: boolean) => { Log.info(TAG, `allSelect ${newState}`); - self.isAllSelected = newState; - self.dataSource.forceUpdate(); - })); - this.mSelectManager.registerCallback('updateCount', this.freezeAdapter((newState: number) => { + if (this.isDataFreeze) { + return; + } + this.isAllSelected = newState; + this.dataSource.forceUpdate(); + }); + this.mSelectManager.registerCallback('updateCount', (newState: number) => { Log.info(TAG, `updateSelectedCount ${newState}`); - self.moreMenuList = Boolean(newState) ? (this.albumInfo.isSystemAlbum ? [Action.ADD, Action.INFO] : [Action.MOVE, Action.ADD, Action.REMOVE_FROM, Action.INFO]) - : (this.albumInfo.isSystemAlbum ? [Action.ADD_INVALID, Action.INFO_INVALID] : [Action.MOVE_INVALID, Action.ADD_INVALID, Action.REMOVE_FROM_INVALID, Action.INFO_INVALID]); - self.totalSelectedCount = newState; - })); - this.mSelectManager.registerCallback('select', this.freezeAdapter((newState: number) => { + if (this.isDataFreeze) { + return; + } + this.moreMenuList = Boolean(newState) ? (this.albumInfo.isSystemAlbum ? [Action.ADD, Action.INFO] : [Action.MOVE, Action.ADD, Action.REMOVE_FROM, Action.INFO]) + : (this.albumInfo.isSystemAlbum ? [Action.ADD_INVALID, Action.INFO_INVALID] : [Action.MOVE_INVALID, Action.ADD_INVALID, Action.REMOVE_FROM_INVALID, Action.INFO_INVALID]); + this.totalSelectedCount = newState; + }); + this.mSelectManager.registerCallback('select', (newState: number) => { Log.info(TAG, `select ${newState}`); - self.dataSource.onDataChanged(newState); - })); + if (this.isDataFreeze) { + return; + } + this.dataSource.onDataChanged(newState); + }); this.dataSource.registerCallback('updateCount', (newState: number) => { Log.info(TAG, `updateTotalCount ${newState}`); self.isShowScrollBar = (newState > Constants.PHOTOS_CNT_FOR_HIDE_SCROLL_BAR); @@ -697,17 +606,7 @@ export struct PhotoGridView { self.mSelectManager.setTotalCount(newState); }); - this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, () => { - Log.info(TAG, 'ON_DATA_RELOADED'); - if (this.deleteMode) { - animateTo({ duration: 300 }, () => { - this.dataSource.onDataReloaded(); - }) - this.deleteMode = false; - } else { - this.dataSource.onDataReloaded(); - } - }); + this.broadCast.on(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadedFunc); ScreenManager.getInstance().on(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); @@ -717,6 +616,85 @@ export struct PhotoGridView { TraceControllerUtils.finishTrace('PhotoGridPageAboutToAppear'); } + private select(position: number, key: string, value: boolean, callback: Function): void { + if (this.mSelectManager.toggle(key, value, position)) { + Log.info(TAG, 'enter event process') + if (!this.isSelectedMode) { + this.isSelectedMode = true; + } + callback(); + } + } + + private jumpPhotoBrowser(name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void { + let targetIndex = this.dataSource.getDataIndex(item); + if (targetIndex == Constants.NOT_FOUND) { + Log.error(TAG, 'targetIndex is not found'); + return; + } + Log.info(TAG, `jump to photo browser at index: ${targetIndex}`); + let pageEntryFrom = Constants.ENTRY_FROM.NORMAL; + if (this.albumInfo.isTrashAlbum) { + pageEntryFrom = Constants.ENTRY_FROM.RECYCLE; + } else if (this.isDistributedAlbum) { + pageEntryFrom = Constants.ENTRY_FROM.DISTRIBUTED; + } + + AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, this.dataSource); + if (geometryTapIndex !== undefined && geometryTransitionString !== undefined) { + this.jumpToPhotoBrowserGeometryTransition( + targetIndex, name, pageEntryFrom, geometryTapIndex, geometryTransitionString); + } else { + this.jumpToPhotoBrowserNormal(targetIndex, name, pageEntryFrom); + } + } + + private jumpThirdPhotoBrowser(name: string, item: MediaItem, geometryTapIndex: number, geometryTransitionString: string): void { + Log.info(TAG, 'JUMP_THIRD_PHOTO_BROWSER'); + let targetIndex = this.dataSource.getDataIndex(item); + if (targetIndex == Constants.NOT_FOUND) { + Log.error(TAG, 'targetIndex is not found'); + return; + } + Log.info(TAG, `jump to photo browser at index: ${targetIndex} ${name}`); + let pageEntryFrom = Constants.ENTRY_FROM.NORMAL; + if (this.albumInfo.isTrashAlbum) { + pageEntryFrom = Constants.ENTRY_FROM.RECYCLE; + } else if (this.isDistributedAlbum) { + pageEntryFrom = Constants.ENTRY_FROM.DISTRIBUTED; + } + AppStorage.SetOrCreate(Constants.PHOTO_GRID_SELECT_MANAGER, this.mSelectManager); + AppStorage.SetOrCreate(Constants.APP_KEY_PHOTO_BROWSER, this.dataSource); + if (geometryTapIndex !== undefined && geometryTransitionString !== undefined) { + this.jumpToSelectPhotoBrowserGeometryTransition( + targetIndex, name, pageEntryFrom, geometryTapIndex, geometryTransitionString); + } else { + this.jumpToSelectPhotoBrowserNormal(targetIndex, name, pageEntryFrom); + } + } + + private onLoadingFinished(size: number): void { + Log.info(TAG, `ON_LOADING_FINISHED size: ${size}`); + } + + private doAnimationFn(): void { + this.doAnimation(); + this.appBroadCast.off(BroadCastConstants.DO_ANIMATION, this.doAnimationFunc); + } + + private onDataReloaded(): void { + Log.info(TAG, 'ON_DATA_RELOADED'); + if (this.deleteMode) { + animateTo({ duration: 300 }, () => { + this.dataSource.onDataReloaded(); + }) + this.deleteMode = false; + } else { + this.dataSource.onDataReloaded(); + } + } + + updateFirstPhotoItemInfo(item: MediaItem, isFirstPhotoItem: boolean): void { if (item) { AppStorage.SetOrCreate(Constants.KEY_OF_IS_FIRST_PHOTO_ITEM, isFirstPhotoItem); @@ -745,14 +723,25 @@ export struct PhotoGridView { jumpToPhotoBrowserGeometryTransition(targetIndex: number, name: string, pageEntryFrom: number, geometryTapIndex: number, geometryTransitionString: string) { Log.debug(TAG, 'start jump to photo browser in geometry transition'); - this.browserController.showBrowser(geometryTapIndex, geometryTransitionString, TAG, { + + interface Params { + position: number; + transition: string; + leftBlank: number[]; + pageFrom: number; + deviceName: string; + albumInfo: AlbumInfo; + } + + let params: Params = { position: targetIndex, transition: name, leftBlank: this.leftBlank, pageFrom: pageEntryFrom, deviceName: this.deviceName, albumInfo: this.albumInfo - }); + } + this.browserController.showBrowser(geometryTapIndex, geometryTransitionString, TAG, params); } jumpToSelectPhotoBrowserNormal(targetIndex: number, name: string, pageEntryFrom: number) { @@ -770,14 +759,21 @@ export struct PhotoGridView { jumpToSelectPhotoBrowserGeometryTransition(targetIndex: number, name: string, pageEntryFrom: number, geometryTapIndex: number, geometryTransitionString: string) { Log.debug(TAG, 'start jump to select photo browser in geometry transition'); - this.browserController.showSelectBrowser(geometryTapIndex, geometryTransitionString, TAG, { + interface Params { + position: number; + transition: string; + pageFrom: number; + } + + const params: Params = { position: targetIndex, transition: name, pageFrom: pageEntryFrom, - }); + }; + this.browserController.showSelectBrowser(geometryTapIndex, geometryTransitionString, TAG, params); } - onMediaLibDataChange(changeType): void { + onMediaLibDataChange(changeType: string): void { Log.info(TAG, `onMediaLibDataChange type: ${changeType}`); this.dataSource.switchRefreshOn(); this.dataSource.onChange(changeType); @@ -786,23 +782,25 @@ export struct PhotoGridView { aboutToDisappear(): void { Log.info(TAG, `aboutToDisappear`); ScreenManager.getInstance().off(ScreenManager.ON_WIN_SIZE_CHANGED, this.onWindowSizeChangeCallBack); - this.onWindowSizeChangeCallBack = null; - this.broadCast.off(null, null); - this.appBroadCast.off(BroadCastConstants.UPDATE_DATA_SOURCE, null); - this.appBroadCast.off(BroadCastConstants.ON_REMOTE_CHANGED, null); - this.appBroadCast.off(BroadCastConstants.DO_ANIMATION, null); + this.broadCast.off(BroadCastConstants.SELECT, this.selectFunc); + this.broadCast.off(BroadCastConstants.JUMP_PHOTO_BROWSER, this.jumpPhotoBrowserFunc); + this.broadCast.off(BroadCastConstants.JUMP_THIRD_PHOTO_BROWSER, this.jumpThirdPhotoBrowserFunc); + this.broadCast.off(Constants.ON_LOADING_FINISHED, this.onLoadingFinishedFunc); + this.broadCast.off(BroadCastConstants.DO_ANIMATION, this.doAnimationFunc); + this.broadCast.off(BroadCastConstants.ON_DATA_RELOADED, this.onDataReloadedFunc); + this.appBroadCast.off(BroadCastConstants.UPDATE_DATA_SOURCE, this.onUpdateFavorStateFunc); this.dataSource.releaseBroadCast(); MediaObserver.getInstance().unregisterObserver(this.dataObserver); this.dataObserver.clearSource(); } - isSameTransitionId(item): boolean { - return AppStorage.Get(Constants.KEY_OF_GEOMETRY_TRANSITION_ID_HEIGHT) === - `${item.hashCode}_${this.dataSource.albumUri}`; + isSameTransitionId(item: MediaItem): boolean { + return AppStorage.get(Constants.KEY_OF_GEOMETRY_TRANSITION_ID_HEIGHT) as string === + `${item.hashCode}_${this.dataSource.albumUri}`; } getGeometryTransitionId(item: ViewData): string { - return TAG + item.mediaItem.hashCode + this.mSelectManager.isItemSelected(item.mediaItem.uri); + return TAG + (item.mediaItem as MediaItem).hashCode + this.mSelectManager.isItemSelected((item.mediaItem as MediaItem).uri); } build() { @@ -811,7 +809,7 @@ export struct PhotoGridView { title: this.title, albumInfo: this.albumInfo, isSystemAlbum: this.albumInfo.isSystemAlbum, - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), isRecycle: this.albumInfo.isTrashAlbum, isDistributedAlbum: this.isDistributedAlbum, totalSelectedCount: $totalSelectedCount @@ -828,51 +826,53 @@ export struct PhotoGridView { .fontWeight(FontWeight.Regular) .width(Constants.PERCENT_100) .padding(this.isHorizontal ? { - left: $r('sys.float.ohos_id_max_padding_start'), - top: $r('app.float.recycle_prompt_message_margin_tb'), - bottom: $r('app.float.recycle_prompt_message_margin_tb') - } : { - left: $r('sys.float.ohos_id_max_padding_start'), - right: $r('sys.float.ohos_id_max_padding_end'), - top: $r('app.float.recycle_prompt_message_margin_tb'), - bottom: $r('app.float.recycle_prompt_message_margin_tb') - } + left: $r('sys.float.ohos_id_max_padding_start'), + top: $r('app.float.recycle_prompt_message_margin_tb'), + bottom: $r('app.float.recycle_prompt_message_margin_tb') + } : { + left: $r('sys.float.ohos_id_max_padding_start'), + right: $r('sys.float.ohos_id_max_padding_end'), + top: $r('app.float.recycle_prompt_message_margin_tb'), + bottom: $r('app.float.recycle_prompt_message_margin_tb') + } ) } Stack() { Grid(this.scroller) { - LazyForEach(this.dataSource, (item, index?: number) => { + LazyForEach(this.dataSource, (item: ViewData, index?: number) => { if (!!item) { GridItem() { ImageGridItemComponent({ dataSource: this.dataSource, item: item.mediaItem, isSelected: this.isSelectedMode ? - this.mSelectManager.isItemSelected(item.mediaItem.uri) : false, + this.mSelectManager.isItemSelected((item.mediaItem as MediaItem).uri) : false, isRecycle: this.albumInfo.isTrashAlbum, pageName: Constants.PHOTO_TRANSITION_ALBUM, - onMenuClicked: this.onMenuClicked, - onMenuClickedForSingleItem: this.onMenuClickedForSingleItem, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), + onMenuClickedForSingleItem: (action: Action, currentPhoto: MediaItem): void => { + this.onMenuClickedForSingleItem(action, currentPhoto); + }, geometryTransitionString: this.getGeometryTransitionId(item), mPosition: index, selectedCount: $totalSelectedCount }) } - .zIndex(this.isSameTransitionId(item.mediaItem) || index === this.placeholderIndex ? 1 : 0) + .zIndex(this.isSameTransitionId(item.mediaItem as MediaItem) || index === this.placeholderIndex ? 1 : 0) .width(this.gridItemWidth) .aspectRatio(1) .key('AlbumGridImage' + index) } - }, (item, index) => { + }, (item: ViewData, index?: number) => { if (item == null || item == undefined) { return JSON.stringify(item); } // Update animation object if (index === 0) { if (this.scrollIndex === 0) { - this.updateFirstPhotoItemInfo(item.mediaItem, true); + this.updateFirstPhotoItemInfo(item.mediaItem as MediaItem, true); } else { - this.updateFirstPhotoItemInfo(this.dataSource.getData(this.scrollIndex)?.mediaItem, false); + this.updateFirstPhotoItemInfo((this.dataSource.getData(this.scrollIndex) as ViewData)?.mediaItem as MediaItem, false); } } return this.getGeometryTransitionId(item) @@ -882,7 +882,7 @@ export struct PhotoGridView { .clip(false) .onScrollIndex((index: number) => { this.scrollIndex = index; - this.updateFirstPhotoItemInfo(this.dataSource.getData(index)?.mediaItem, false); + this.updateFirstPhotoItemInfo((this.dataSource.getData(index) as ViewData)?.mediaItem as MediaItem, false); }) .edgeEffect(EdgeEffect.Spring) .scrollBar(BarState.Off) @@ -918,7 +918,7 @@ export struct PhotoGridView { .borderRadius($r('sys.float.ohos_id_corner_radius_button')) .backgroundColor($r('sys.color.ohos_id_color_button_normal')) .onClick(() => { - this.onMenuClicked && this.onMenuClicked(Action.CLEAR_RECYCLE) + this.onMenuClicked && this.onMenuClicked(Action.CLEAR_RECYCLE); }) } .borderRadius($r('sys.float.ohos_id_corner_radius_button')) @@ -944,7 +944,7 @@ export struct PhotoGridView { if (this.isSelectedMode) { PhotoGridPageToolBar({ - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), isRecycleAlbum: (this.albumInfo.isTrashAlbum), isDistributedAlbum: this.isDistributedAlbum, totalSelectedCount: $totalSelectedCount @@ -969,15 +969,13 @@ export struct PhotoGridView { private moveOperation(albumName: string, albumUri: string): void { let menuContext = new MenuContext(); - this.onMoveStart = this.onMoveStart.bind(this); - this.onMoveEnd = this.onMoveEnd.bind(this); if (this.isMvOrCpSeparatesItem) { menuContext.withMediaItem(this.mvOrCpSeparatesItem); this.onMoveStart && this.onMoveStart(); } else { - menuContext.withSelectManager(this.mSelectManager).withOperationStartCallback(this.onMoveStart); + menuContext.withSelectManager(this.mSelectManager).withOperationStartCallback((): void => this.onMoveStart()); } - menuContext.withOperationEndCallback(this.onMoveEnd) + menuContext.withOperationEndCallback((err: Error, count: number, total: number): void => this.onMoveEnd(err as Object, count, total)) .withBroadCast(this.broadCast) .withTargetAlbumName(albumName) .withAlbumUri(albumUri); @@ -988,15 +986,13 @@ export struct PhotoGridView { private addOperation(albumName: string, albumUri: string): void { let menuContext = new MenuContext(); - this.onCopyStart = this.onCopyStart.bind(this); - this.onCopyEnd = this.onCopyEnd.bind(this); if (this.isMvOrCpSeparatesItem) { menuContext.withMediaItem(this.mvOrCpSeparatesItem); this.onCopyStart && this.onCopyStart(); } else { - menuContext.withSelectManager(this.mSelectManager).withOperationStartCallback(this.onCopyStart); + menuContext.withSelectManager(this.mSelectManager).withOperationStartCallback((): void => this.onCopyStart()); } - menuContext.withOperationEndCallback(this.onCopyEnd) + menuContext.withOperationEndCallback((err: Error, count: number, total: number): void => this.onCopyEnd(err as Object, count, total)) .withBroadCast(this.broadCast) .withTargetAlbumName(albumName) .withAlbumUri(albumUri); @@ -1011,48 +1007,39 @@ export struct PhotoGridView { } let menuOperation: MenuOperation; let menuContext: MenuContext; - switch (action.actionID) { - case Action.RECOVER.actionID: - menuContext = new MenuContext(); - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(RecoverMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.DELETE.actionID: - menuContext = new MenuContext(); - if (this.dataSource.albumUri == UserFileManagerAccess.getInstance() - .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)) { - menuContext.withAlbumUri(UserFileManagerAccess.getInstance() - .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)); - } - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(DeleteMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.MOVE.actionID: - this.isMvOrCpSeparatesItem = true; - this.mvOrCpSeparatesItem = currentPhoto; - this.routeToSelectAlbumPage(MediaOperationType.Move, [currentPhoto]); - break; - case Action.ADD.actionID: - this.isMvOrCpSeparatesItem = true; - this.mvOrCpSeparatesItem = currentPhoto; - this.routeToSelectAlbumPage(MediaOperationType.Add, [currentPhoto]); - break; - case Action.REMOVE_FROM.actionID: - menuContext = new MenuContext(); - menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); - menuOperation = MenuOperationFactory.getInstance() - .createMenuOperation(RemoveMenuOperation, menuContext); - menuOperation.doAction(); - break; - case Action.INFO.actionID: - this.broadCast.emit(BroadCastConstants.SHOW_DETAIL_DIALOG, [currentPhoto, false]); - break; - default: - break; + if (action.actionID === Action.RECOVER.actionID) { + menuContext = new MenuContext(); + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(RecoverMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.DELETE.actionID) { + menuContext = new MenuContext(); + if (this.dataSource.albumUri == UserFileManagerAccess.getInstance() + .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)) { + menuContext.withAlbumUri(UserFileManagerAccess.getInstance() + .getSystemAlbumUri(UserFileManagerAccess.TRASH_ALBUM_SUB_TYPE)); + } + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(DeleteMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.MOVE.actionID) { + this.isMvOrCpSeparatesItem = true; + this.mvOrCpSeparatesItem = currentPhoto; + this.routeToSelectAlbumPage(MediaOperationType.Move, [currentPhoto]); + } else if (action.actionID === Action.ADD.actionID) { + this.isMvOrCpSeparatesItem = true; + this.mvOrCpSeparatesItem = currentPhoto; + this.routeToSelectAlbumPage(MediaOperationType.Add, [currentPhoto]); + } else if (action.actionID === Action.REMOVE_FROM.actionID) { + menuContext = new MenuContext(); + menuContext.withMediaItem(currentPhoto).withBroadCast(this.broadCast); + menuOperation = MenuOperationFactory.getInstance() + .createMenuOperation(RemoveMenuOperation, menuContext); + menuOperation.doAction(); + } else if (action.actionID === Action.INFO.actionID) { + this.broadCast.emit(BroadCastConstants.SHOW_DETAIL_DIALOG, [currentPhoto, false]); } } @@ -1061,16 +1048,16 @@ export struct PhotoGridView { let margin = 0; let maxThumbWidth = px2vp(Constants.GRID_IMAGE_SIZE) * Constants.GRID_MAX_SIZE_RATIO; // 原型机竖屏为4不变,横屏需计算: currentBreakpoint == 'lg' 表示横屏 - const currentBreakpoint: string = AppStorage.Get('currentBreakpoint'); + const currentBreakpoint: string = AppStorage.get('currentBreakpoint') as string; this.gridRowCount = currentBreakpoint == Constants.BREAKPOINT_LG ? Math.max(Constants.GRID_MIN_COUNT, Math.ceil(((contentWidth - Constants.NUMBER_2 * margin) - + Constants.GRID_GUTTER) / (maxThumbWidth + Constants.GRID_GUTTER))) : Constants.GRID_MIN_COUNT; + + Constants.GRID_GUTTER) / (maxThumbWidth + Constants.GRID_GUTTER))) : Constants.GRID_MIN_COUNT; this.gridItemWidth = (contentWidth - (this.gridRowCount - 1) * Constants.GRID_GUTTER - - Constants.NUMBER_2 * margin) / this.gridRowCount; + Constants.NUMBER_2 * margin) / this.gridRowCount; Log.info(TAG, `initGridRowCount contentWidth: ${contentWidth}`); } - private onUpdateRemoteDevice(res, deviceId): void { + private onUpdateRemoteDevice(res: string, deviceId: string): void { Log.info(TAG, `onUpdateRemoteDevice`); if (res == 'offline') { Log.debug(TAG, `device offline route to album main`); @@ -1085,4 +1072,15 @@ export struct PhotoGridView { return; } } -} \ No newline at end of file +} + +interface Params { + albumName: string; + albumUri: string; + pageType: string; +}; + +interface ParamAlbumInfo { + item: string; + isFromFACard: boolean; +}; \ No newline at end of file diff --git a/product/phone/src/main/ets/view/SelectPhotoBrowserView.ets b/product/phone/src/main/ets/view/SelectPhotoBrowserView.ets index d29a462c..f1bf3678 100644 --- a/product/phone/src/main/ets/view/SelectPhotoBrowserView.ets +++ b/product/phone/src/main/ets/view/SelectPhotoBrowserView.ets @@ -28,7 +28,8 @@ import { ScreenManager, SelectManager, SelectUtil, - UiUtil + UiUtil, + MediaDataSource } from '@ohos/common'; import { BrowserController, @@ -36,9 +37,18 @@ import { PhotoSwiper, ThirdSelectPhotoBrowserActionBar } from '@ohos/common/CommonComponents'; +import ability from '@ohos.ability.ability'; +import common from '@ohos.app.ability.common'; const TAG: string = 'SelectPhotoBrowserView'; +interface Params { + pageFrom: number; + deviceId: string; + position: number; + transition: string; +}; + // select mode @Component export struct SelectPhotoBrowserView { @@ -49,9 +59,9 @@ export struct SelectPhotoBrowserView { @State isShowBar: boolean = true; @Provide pageFrom: number = Constants.ENTRY_FROM.NORMAL; @Provide canSwipe: boolean = true; - selectManager: SelectManager; + selectManager: SelectManager | null = null; isMultiPick = true; - mTransition: string; + mTransition: string = ''; controller: SwiperController = new SwiperController(); @Provide isDeleting: boolean = false; @@ -59,9 +69,9 @@ export struct SelectPhotoBrowserView { @Provide('transitionIndex') currentIndex: number = 0; // position - mPosition: number; + mPosition: number = 0; timelineIndex: number = -1; - @Prop @Watch('onPageChanged') pageStatus: boolean; + @Prop @Watch('onPageChanged') pageStatus: boolean = false; @StorageLink('geometryOpacity') geometryOpacity: number = 1; @State @Watch('onGeometryChanged') geometryTransitionId: string = 'default_id'; @Link isRunningAnimation: boolean; @@ -71,6 +81,25 @@ export struct SelectPhotoBrowserView { // The global BroadCast of the application process. Event registration and destruction should be paired private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast(); private geometryTransitionEnable: boolean = false; + private pullDownEndFunc: Function = (): void => this.pullDownEnd(); + private dataSizeChangedFunc: Function = (size: number): void => this.onDataSizeChanged(size);; + private dataContentChangedFunc: Function = (size: number): void => this.dataContentChanged(size); + private setDisableSwipeFunc: Function = (value: boolean): void => this.setDisableSwipe(value); + + private pullDownEnd(): void { + this.onBackPress(); + } + + private dataContentChanged(size: number): void { + // onContentChanged only the current item is updated + Log.info(TAG, `DATA_CONTENT_CHANGED : ${size}`); + this.onPhotoChanged(this.currentIndex); + } + + private setDisableSwipe(value: boolean): void { + Log.info(TAG, `set swiper swipe ${value}`); + this.canSwipe = value; + } onPageChanged() { if (this.pageStatus) { @@ -86,7 +115,7 @@ export struct SelectPhotoBrowserView { aboutToAppear(): void { Log.info(TAG, 'photoBrowser aboutToAppear'); - this.geometryTransitionId = AppStorage.Get('geometryTransitionBrowserId') + this.geometryTransitionId = AppStorage.get('geometryTransitionBrowserId') as string; Log.info(TAG, `photoBrowser aboutToAppear ${this.geometryTransitionId}`); this.backgroundColorResource = $r('app.color.black'); mMultimodalInputManager.registerListener((control: number) => { @@ -103,8 +132,8 @@ export struct SelectPhotoBrowserView { this.onBackPress(); } }); - this.selectManager = AppStorage.Get(Constants.PHOTO_GRID_SELECT_MANAGER); - let param: any = this.browserController.selectBrowserParam; + this.selectManager = AppStorage.get(Constants.PHOTO_GRID_SELECT_MANAGER) as SelectManager; + let param: Params = this.browserController.selectBrowserParam as Params; if (param.pageFrom) { this.pageFrom = param.pageFrom; } @@ -114,50 +143,35 @@ export struct SelectPhotoBrowserView { this.dataSource.setDeviceId(param.deviceId); } - this.dataSource.setAlbumDataSource(AppStorage.Get(Constants.APP_KEY_PHOTO_BROWSER)); + this.dataSource.setAlbumDataSource(AppStorage.get(Constants.APP_KEY_PHOTO_BROWSER) as MediaDataSource); if (this.isMultiPick == true && this.selectManager) { this.selectedCount = this.selectManager.getSelectedCount(); } this.onPhotoChanged(param.position); this.mTransition = param.transition; - this.onMenuClicked = this.onMenuClicked.bind(this); this.dataSource.setBroadCast(this.broadCast); - this.broadCast.on(PhotoConstants.PULL_DOWN_END, (event) => { - Log.info(TAG, `PULL_DOWN_END : ${JSON.stringify(event)}`); - this.onBackPress(); - }); + this.broadCast.on(PhotoConstants.PULL_DOWN_END, this.pullDownEndFunc); + this.broadCast.on(PhotoConstants.DATA_SIZE_CHANGED, this.dataSizeChangedFunc); + this.broadCast.on(PhotoConstants.DATA_CONTENT_CHANGED, this.dataContentChangedFunc); + this.broadCast.on(PhotoConstants.SET_DISABLE_SWIPE, this.setDisableSwipeFunc); - this.broadCast.on(PhotoConstants.DATA_SIZE_CHANGED, (size: number) => { - this.onDataSizeChanged(size); - }); - - this.broadCast.on(PhotoConstants.DATA_CONTENT_CHANGED, (size: number) => { - // onContentChanged only the current item is updated - Log.info(TAG, `DATA_CONTENT_CHANGED : ${size}`); - this.onPhotoChanged(this.currentIndex); - }); - - this.broadCast.on(PhotoConstants.SET_DISABLE_SWIPE, (value: boolean) => { - Log.info(TAG, `set swiper swipe ${value}`); - this.canSwipe = value; - }); - - this.appBroadCast.on(BroadCastConstants.SELECT_PHOTO_BROWSER_BACK_PRESS_EVENT, () => { - Log.debug(TAG, 'hook back press from page.'); - this.onBackPress(); - }); + this.appBroadCast.on(BroadCastConstants.SELECT_PHOTO_BROWSER_BACK_PRESS_EVENT, this.pullDownEndFunc); } aboutToDisappear(): void { this.broadCast.release(); this.dataSource.release(); mMultimodalInputManager.unregisterListener(); - this.controller = undefined; - this.broadCast.off(null, null); - this.appBroadCast.off(BroadCastConstants.SELECT_PHOTO_BROWSER_BACK_PRESS_EVENT, null); + if(this.broadCast) { + this.broadCast.off(PhotoConstants.PULL_DOWN_END, this.pullDownEndFunc); + this.broadCast.off(PhotoConstants.DATA_SIZE_CHANGED, this.dataSizeChangedFunc); + this.broadCast.off(PhotoConstants.DATA_CONTENT_CHANGED, this.dataContentChangedFunc); + this.broadCast.off(PhotoConstants.SET_DISABLE_SWIPE, this.setDisableSwipeFunc); + } + this.appBroadCast.off(BroadCastConstants.SELECT_PHOTO_BROWSER_BACK_PRESS_EVENT, this.pullDownEndFunc); } onDataSizeChanged(size: number): void { @@ -174,7 +188,7 @@ export struct SelectPhotoBrowserView { if (currentPhoto == undefined) { Log.error(TAG, 'onPhotoChanged, item is undefined'); } else { - this.isSelected = this.selectManager.isItemSelected(currentPhoto.uri, this.timelineIndex); + this.isSelected = this.selectManager?.isItemSelected(currentPhoto.uri, this.timelineIndex) ?? false; AppStorage.SetOrCreate('placeholderIndex', this.timelineIndex); this.geometryTransitionId = this.browserController.pageFrom + currentPhoto.getHashCode() + this.isSelected; Log.info(TAG, `onPhotoChanged, index: ${index}, currentPhoto: ${currentPhoto.uri},\ @@ -189,8 +203,8 @@ export struct SelectPhotoBrowserView { return; } this.isSelected = !this.isSelected; - if (this.selectManager.toggle(currentPhoto.uri, this.isSelected, this.timelineIndex)) { - this.selectedCount = this.selectManager.getSelectedCount(); + if (this.selectManager?.toggle(currentPhoto.uri, this.isSelected, this.timelineIndex)) { + this.selectedCount = this.selectManager?.getSelectedCount() ?? 0; } this.geometryTransitionId = this.browserController.pageFrom + currentPhoto.getHashCode() + this.isSelected; Log.info(TAG, `selectedCount: ${this.selectedCount} after state change`) @@ -209,24 +223,17 @@ export struct SelectPhotoBrowserView { onMenuClicked(action: Action) { Log.debug(TAG, `onMenuClicked, action: ${action.actionID}`); - switch (action.actionID) { - case Action.BACK.actionID: - this.onBackPress(); - return; - case Action.MATERIAL_SELECT.actionID: - Log.info(TAG, 'click UN_SELECTED'); - this.selectStateChange(); - return; - case Action.SELECTED.actionID: - Log.info(TAG, 'click SELECTED'); - this.selectStateChange(); - return; - case Action.OK.actionID: - Log.info(TAG, 'click OK'); - this.setPickResult(); - break; - default: - break; + if (action.actionID === Action.BACK.actionID) { + this.onBackPress(); + } else if (action.actionID === Action.MATERIAL_SELECT.actionID) { + Log.info(TAG, 'click UN_SELECTED'); + this.selectStateChange(); + } else if (action.actionID === Action.SELECTED.actionID) { + Log.info(TAG, 'click SELECTED'); + this.selectStateChange(); + } else if (action.actionID === Action.OK.actionID) { + Log.info(TAG, 'click OK'); + this.setPickResult(); } } @@ -256,7 +263,7 @@ export struct SelectPhotoBrowserView { PhotoSwiper({ dataSource: this.dataSource, mTransition: this.mTransition, - onPhotoChanged: this.onPhotoChanged.bind(this), + onPhotoChanged: (index: number): void => this.onPhotoChanged(index), swiperController: this.controller, geometryTransitionEnable: this.geometryTransitionEnable, broadCast: $broadCast, @@ -266,7 +273,7 @@ export struct SelectPhotoBrowserView { ThirdSelectPhotoBrowserActionBar({ isMultiPick: this.isMultiPick, - onMenuClicked: this.onMenuClicked, + onMenuClicked: (action: Action): void => this.onMenuClicked(action), isShowBar: $isShowBar, totalSelectedCount: $selectedCount }) @@ -284,26 +291,27 @@ export struct SelectPhotoBrowserView { } private setPickResult(): void { - let uriArray; + let uriArray: string[]; if (this.isMultiPick) { - uriArray = SelectUtil.getUriArray(this.selectManager.clickedSet); + uriArray = SelectUtil.getUriArray(this.selectManager?.clickedSet ?? new Set()); Log.debug(TAG, `uri size: ${uriArray}`); } else { let currentPhoto = this.getCurrentPhoto(); if (currentPhoto == undefined) { return; } - uriArray = currentPhoto.uri; + uriArray = [currentPhoto.uri]; } - let abilityResult = { - 'resultCode': 0, - 'want': { - 'parameters': { + let abilityResult: ability.AbilityResult = { + resultCode: 0, + want: { + parameters: { 'select-item-list': uriArray } } }; - globalThis.photosAbilityContext.terminateSelfWithResult(abilityResult).then((result) => { + let context: common.UIAbilityContext = AppStorage.get('photosAbilityContext') as common.UIAbilityContext; + context.terminateSelfWithResult(abilityResult).then((result: void) => { Log.info(TAG, `terminateSelfWithResult result: ${result}`); }); } diff --git a/product/phone/src/main/ets/view/TabContentComponent.ets b/product/phone/src/main/ets/view/TabContentComponent.ets index 2f3f4f5c..120cdf60 100644 --- a/product/phone/src/main/ets/view/TabContentComponent.ets +++ b/product/phone/src/main/ets/view/TabContentComponent.ets @@ -24,9 +24,9 @@ const TAG = 'TabContentComponent'; @Component export struct TabContentComponent { - @Prop pageStatus: boolean; + @Prop pageStatus: boolean = false; @StorageLink('isShowPhotoGridView') isShowPhotoGridView: boolean = false; - @Prop currentIndex: number; + @Prop currentIndex: number = 0; @StorageLink('currentBreakpoint') currentBreakpoint: string = Constants.BREAKPOINT_MD; @Consume @Watch('onShowStatusChanged') isShow: boolean; @State @Watch('updateIndexStatus') browserController: BrowserController = new BrowserController(true); diff --git a/product/phone/src/main/ets/view/TimelineContentComponent.ets b/product/phone/src/main/ets/view/TimelineContentComponent.ets index 79d72912..21dae03e 100644 --- a/product/phone/src/main/ets/view/TimelineContentComponent.ets +++ b/product/phone/src/main/ets/view/TimelineContentComponent.ets @@ -24,7 +24,7 @@ const TAG = 'TimelineTabContentComponent'; @Component export struct TimelineTabContentComponent { @State pageStatus: boolean = false; - @Prop currentIndex: number; + @Prop currentIndex: number = 0; @Link isShowTabBar: boolean; @State @Watch('updateIndexStatus') browserController: BrowserController = new BrowserController(true); @State isRunningAnimation: boolean = false; diff --git a/product/phone/src/ohosTest/ets/TestAbility/TestAbility.ts b/product/phone/src/ohosTest/ets/TestAbility/TestAbility.ts index 9e50aafd..ab23f6c0 100644 --- a/product/phone/src/ohosTest/ets/TestAbility/TestAbility.ts +++ b/product/phone/src/ohosTest/ets/TestAbility/TestAbility.ts @@ -40,7 +40,7 @@ export default class TestAbility extends Ability { Log.info(TAG, 'TestAbility onWindowStageCreate') windowStage.setUIContent(this.context, 'TestAbility/pages/index', null) - globalThis.abilityContext = this.context; + AppStorage.setOrCreate('abilityContext', this.context); } onWindowStageDestroy(): void {