!184 代码整改

Merge pull request !184 from 范飞/master
This commit is contained in:
openharmony_ci
2025-09-08 09:05:13 +00:00
committed by Gitee
125 changed files with 4173 additions and 2823 deletions
+37 -16
View File
@@ -12,24 +12,45 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class EventClass {
public NEW_WANT: number;
export default {
Event: {
NEW_WANT: 1,
},
Storage: {
mainTabsIndex: "mainTabsIndex",
teleNumber: 'teleNumber',
targetPage: "targetPage"
},
CONFIG: {
constructor() {
this.NEW_WANT = 1;
}
}
class StorageClass {
public mainTabsIndex: string;
public teleNumber: string;
public targetPage: string;
constructor() {
this.mainTabsIndex = 'mainTabsIndex';
this.teleNumber = 'teleNumber';
this.targetPage = 'targetPage';
}
}
class ConfigClass {
public useDataWorker: boolean = false;
public needCache: boolean = false;
}
class ExportClass {
public appUseDataWorker: string = 'appUseDataWorker';
public event: EventClass = new EventClass();
public storage: StorageClass = new StorageClass();
public config: ConfigClass = {
useDataWorker: false,
needCache: false
},
};
initConfig(context: Context) {
this.CONFIG.useDataWorker = context.resourceManager.getBoolean($r('app.boolean.use_data_worker'));
this.CONFIG.needCache = context.resourceManager.getBoolean($r('app.boolean.cache_page_one'));
return this.CONFIG
initConfig(context: Context): ConfigClass {
this.config.useDataWorker = context.resourceManager.getBoolean($r('app.boolean.use_data_worker'));
this.config.needCache=context.resourceManager.getBoolean($r('app.boolean.cache_page_one'));
return this.config;
}
}
}
export default new ExportClass();
@@ -13,8 +13,8 @@
* limitations under the License.
*/
import { HiLog } from '../util/HiLog';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base';
const TAG = 'PermissionManager';
export class PermissionManager {
@@ -35,7 +35,7 @@ export class PermissionManager {
}
async initPermissions() {
let requestPermissions: Array<any> = [
let requestPermissions: Permissions[] = [
"ohos.permission.READ_CONTACTS",
"ohos.permission.WRITE_CONTACTS",
"ohos.permission.MANAGE_VOICEMAIL",
@@ -55,7 +55,7 @@ export class PermissionManager {
HiLog.i(TAG, "authFlag: " + JSON.stringify(authFlag));
this._isAllPermissionsGranted = authFlag;
})
.catch(err => {
.catch((err: BusinessError) => {
HiLog.e(TAG, "requestPermissionsFromUser err:" + JSON.stringify(err));
});
HiLog.i(TAG, 'Application requestPermissionsFromUser end');
+2 -2
View File
@@ -14,7 +14,7 @@
*/
export class ArrayUtil {
static isEmpty(list: any[]) {
return list == undefined || list == null || (Array.prototype.isPrototypeOf(list) && list.length === 0);
static isEmpty(list: Array): boolean {
return list === undefined || list === null || (Array.isArray(list) && list.length === 0);
}
}
+9 -9
View File
@@ -37,23 +37,23 @@ export class HiLog {
}
private static prefix(tag: string) {
return tag + this.COLON;
return tag + HiLog.COLON;
}
static d(tag: string, msg: string, ...args: any[]) {
Log.debug(DOMAIN, TAG, this.prefix(tag) + msg, args);
static d(tag: string, msg: string, ...args: string[]) {
Log.debug(DOMAIN, TAG, HiLog.prefix(tag) + msg, args);
}
static i(tag: string, msg: string, ...args: any[]) {
Log.info(DOMAIN, TAG, this.prefix(tag) + msg, args);
static i(tag: string, msg: string, ...args: string[]) {
Log.info(DOMAIN, TAG, HiLog.prefix(tag) + msg, args);
}
static w(tag: string, msg: string, ...args: any[]) {
Log.warn(DOMAIN, TAG, this.prefix(tag) + msg, args);
static w(tag: string, msg: string, ...args: string[]) {
Log.warn(DOMAIN, TAG, HiLog.prefix(tag) + msg, args);
}
static e(tag: string, msg: string, ...args: any[]) {
Log.error(DOMAIN, TAG, this.prefix(tag) + msg, args);
static e(tag: string, msg: string, ...args: string[]) {
Log.error(DOMAIN, TAG, HiLog.prefix(tag) + msg, args);
}
}
@@ -17,11 +17,11 @@ import data_preferences from '@ohos.data.preferences';
import contextConstant from '@ohos.app.ability.contextConstant'
const NAME: string = "CONTACT_PREFERENCE";
type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean>;
type ValueType = number | string | boolean | Array | Array | Array | undefined;
class SharedPreferencesUtils {
private mPreferences: data_preferences.Preferences;
private context: Context;
private mPreferences?: data_preferences.Preferences;
private context?: Context;
constructor() {
this.getPreferences().then((data) => {
@@ -42,7 +42,7 @@ class SharedPreferencesUtils {
*
* @return the value get from Preferences
*/
public async getFromPreferences(key: string, defValue) {
public async getFromPreferences(key: string, defValue: data_preferences.ValueType) {
let preferences: data_preferences.Preferences = await this.getPreferences();
return await preferences.get(key, defValue);
}
+21 -6
View File
@@ -18,20 +18,35 @@ export class StringUtil {
}
static removeSpace(str: string): string {
if (this.isEmpty(str)) {
if (StringUtil.isEmpty(str)) {
return '';
}
return str.replace(/[\s]/g, '');
}
/* Obtains the result string that matches the specified substring in the original character string.
Only the result of the first successful match is returned.(The matching rule ignores spaces.)
/**
根据指定字符padCh,补全字符串str 到指定长度len
@param str
@param padCh
@param len
@returns
*/
static getMatchedString(textValue, regString): string {
if (this.isEmpty(textValue) || this.isEmpty(regString)) {
static paddingLeft(str: string, padCh: string, len: number): string {
while (str.length < len) {
str = padCh + str;
}
return str;
}
/* Obtains the result string that matches the specified substring in the original character string.
Only the result of the first successful match is returned.(The matching rule ignores spaces.)
*/
static getMatchedString(textValue:string, regString:string): string {
if (StringUtil.isEmpty(textValue) || StringUtil.isEmpty(regString)) {
return '';
}
regString = this.removeSpace(regString);
regString = StringUtil.removeSpace(regString);
let matchedTemp = '';
// spaces count
@@ -12,9 +12,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { HiLog } from '../../../../../common/src/main/ets/util/HiLog';
import Constants from '../../../../../common/src/main/ets/Constants';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import Constants from 'common/src/main/ets/Constants';
import AbilityStage from '@ohos.app.ability.AbilityStage'
import notification from '@ohos.notificationManager';
import notificationManager from '@ohos.notificationManager';
@@ -22,7 +21,7 @@ import notificationManager from '@ohos.notificationManager';
const TAG = 'MyAbilityStage ';
export default class MyAbilityStage extends AbilityStage {
onCreate() {
onCreate(): void {
HiLog.i(TAG, 'AbilityStage onCreate');
notificationManager.setNotificationEnable({
bundle: 'com.ohos.contacts'
+21 -11
View File
@@ -16,17 +16,19 @@
import Ability from '@ohos.app.ability.UIAbility'
import Window from '@ohos.window'
import WorkFactory, { WorkerType } from '../workers/WorkFactory';
import { HiLog } from '../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import Want from '@ohos.app.ability.Want';
import SimManager from '../feature/sim/SimManager';
import { missedCallManager } from '../feature/missedCall/MissedCallManager';
import PresenterManager from '../presenter/PresenterManager';
import { AbilityConstant } from '@kit.AbilityKit';
import { MissedCallNotifyData } from '../../../../../feature/call/src/main/ets/missedcall/MissedCallNotifier';
const TAG = 'MainAbility ';
export default class MainAbility extends Ability {
storage: LocalStorage;
simManager: SimManager;
storage: LocalStorage | null = null;
simManager: SimManager | null = null;
mDataWorker = WorkFactory.getWorker(WorkerType.DataWorker);
updateBreakpoint(windowWidth: number) {
@@ -39,22 +41,24 @@ export default class MainAbility extends Ability {
} else {
breakpoint = 'lg';
}
this.storage.setOrCreate('breakpoint', breakpoint);
if (this.storage != null) {
this.storage.setOrCreate('breakpoint', breakpoint);
}
}
onRequest(want: Want, isOnCreate: boolean) {
if (!want || !want.parameters) {
return;
}
const data: any = want.parameters['missedCallData'];
const data: MissedCallNotifyData = want.parameters['missedCallData'] as MissedCallNotifyData;
const action = want.parameters['action'];
HiLog.i(TAG, `onRequest action: ${action}`);
if (action != undefined && data != undefined) {
missedCallManager.requestMissedCallAction(action, data);
missedCallManager.requestMissedCallAction(action as string, data);
}
}
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
HiLog.i(TAG, 'Application onCreate start');
globalThis.isFromOnCreate = true;
globalThis.context = this.context;
@@ -67,7 +71,7 @@ export default class MainAbility extends Ability {
globalThis.presenterManager.onCreate(want);
}
onNewWant(want, launchParam) {
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
HiLog.i(TAG, 'Application onNewWant');
globalThis.isFromOnCreate = false;
globalThis.abilityWant = want;
@@ -78,7 +82,9 @@ export default class MainAbility extends Ability {
onDestroy() {
HiLog.i(TAG, 'Ability onDestroy');
globalThis.presenterManager.onDestroy();
this.mDataWorker.close();
if (this.mDataWorker) {
this.mDataWorker.close();
}
}
onWindowStageCreate(windowStage: Window.WindowStage) {
@@ -111,12 +117,16 @@ export default class MainAbility extends Ability {
onForeground() {
// Ability has brought to foreground
HiLog.i(TAG, 'Ability onForeground');
this.simManager.init();
if (this.simManager) {
this.simManager.init();
}
}
onBackground() {
// Ability has back to background
HiLog.i(TAG, 'Ability onBackground');
this.simManager.recycle();
if (this.simManager) {
this.simManager.recycle();
}
}
}
@@ -17,9 +17,12 @@ import { MissedCallService } from '../../../../../feature/call';
import { PhoneNumber } from '../../../../../feature/phonenumber';
import call from '@ohos.telephony.call';
import telephonySim from '@ohos.telephony.sim';
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility';
import { BusinessError } from '@ohos.base';
import sim from '@ohos.telephony.sim';
import LooseObject from '../model/LooseObject ';
const TAG = 'StaticSubscriber'
var StaticSubscriberExtensionAbility = globalThis.requireNapi('application.StaticSubscriberExtensionAbility');
export default class StaticSubscriber extends StaticSubscriberExtensionAbility {
private async callAction(phoneNumber: string) {
HiLog.i(TAG, 'callAction')
@@ -43,26 +46,25 @@ export default class StaticSubscriber extends StaticSubscriberExtensionAbility {
accountId: readySim,
})
} else {
call.makeCall(phoneNumber).catch(err => {
call.makeCall(phoneNumber).catch((err: BusinessError) => {
HiLog.e(TAG, `callAction, error: ${JSON.stringify(err)}`);
})
}
}
private isSimReady(state) {
private isSimReady(state: sim.SimState) {
return state == telephonySim.SimState.SIM_STATE_READY || state == telephonySim.SimState.SIM_STATE_LOADED;
}
onReceiveEvent(event) {
onReceiveEvent(event: LooseObject) {
HiLog.i(TAG, 'onReceiveEvent, event:' + JSON.stringify(event));
const missCallData = JSON.parse(JSON.stringify(event));
const parameters = JSON.parse(JSON.stringify(missCallData.parameters));
const parameters: LooseObject = JSON.parse(JSON.stringify(event.parameters));
let updateMissedCallNotificationsMap: Map<string, string> = new Map();
MissedCallService.getInstance().init(this.context);
if ('usual.event.INCOMING_CALL_MISSED' == event.event) {
MissedCallService.getInstance().updateMissedCallNotifications();
if (parameters.countList != null) {
updateMissedCallNotificationsMap.set('missedPhoneJson', missCallData.parameters);
updateMissedCallNotificationsMap.set('missedPhoneJson', parameters.phoneNumber);
MissedCallService.getInstance().unreadCallNotification(updateMissedCallNotificationsMap);
}
} else if ('contact.event.CANCEL_MISSED' == event.event) {
@@ -18,7 +18,7 @@ import { ContactVo } from '../../model/bean/ContactVo';
import DeleteDialogEx from '../../pages/dialog/DeleteDialogEx';
import ShareDialogEx from '../../pages/dialog/ShareDialogEx';
import { StringUtil } from '../../../../../../common/src/main/ets/util/StringUtil';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import ContactListPresenter from '../../presenter/contact/ContactListPresenter';
import EnvironmentProp from '../../feature/EnvironmentProp';
@@ -68,8 +68,6 @@ export default struct ContactListItemView {
});
aboutToDisappear() {
this.shareDialogControler = null;
this.deleteDialogControler = null;
}
onDeleteClick() {
@@ -18,8 +18,8 @@ import AccountantsPresenter from '../../../presenter/contact/accountants/Account
@Component
export struct AddItem {
@Link mPresent: AccountantsPresenter;
private labelName: Resource;
private typeName: string;
private labelName: Resource|undefined = undefined;
private typeName: string = '';
@LocalStorageProp('breakpoint') curBp: string = 'sm';
build() {
@@ -17,7 +17,7 @@ import EnvironmentProp from '../../../feature/EnvironmentProp';
@Component
export struct ImageItemLeft {
private mImage: Resource;
private mImage: Resource|undefined = undefined;
private moreFlag?: Boolean = false;
@LocalStorageProp('breakpoint') curBp: string = 'sm';
@@ -17,6 +17,7 @@ import { StringUtil, HiLog } from '../../../../../../../common';
import AccountantsPresenter from '../../../presenter/contact/accountants/AccountantsPresenter';
import StringFormatUtil from '../../../util/StringFormatUtil';
import { Birthday } from '../../../../../../../feature/contact/src/main/ets/contract/Birthday';
import EditType from '../../../../../../../feature/account/src/main/ets/type/EditType';
const TAG = 'ItemEvent'
@@ -25,9 +26,9 @@ export struct ItemEvent {
@Link mPresent: AccountantsPresenter;
@Link itemIndex: number;
@Link eventType: number;
private controller: { [key: string]: any };
private index: number;
private typeName: string;
private controller: CustomDialogController| null = null;
private index: number = -1;
private typeName: string = '';
@LocalStorageProp('breakpoint') curBp: string = 'sm';
build() {
@@ -86,7 +87,7 @@ export struct ItemEvent {
this.eventType = Number(data.item.eventType)
}
this.itemIndex = this.index - 1;
this.controller.open()
this.controller?.open()
})
Column() {
@@ -123,7 +124,7 @@ export struct ItemEvent {
@Builder MenuBuilder() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
ForEach(this.mPresent.getMenuList(this.typeName),
(item) => {
(item:EditType) => {
Text(item.labelRes)
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.width('156vp')
@@ -140,7 +141,7 @@ export struct ItemEvent {
.width($r('app.float.account_Divider_width'))
.color($r('sys.color.ohos_id_color_list_separator'))
},
(item) => item.rawValue.toString())
(item:EditType) => item.rawValue.toString())
}
.width($r('app.float.account_MenuBuilder_width'))
.borderRadius($r('sys.float.ohos_id_corner_radius_default_l'))
@@ -13,15 +13,15 @@
* limitations under the License.
*/
import AccountantsPresenter from '../../../presenter/contact/accountants/AccountantsPresenter';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import EditType from '../../../../../../../feature/account/src/main/ets/type/EditType';
@Component
export struct ItemList {
@Link @Watch('refresh') mPresent: AccountantsPresenter;
@State mTextInputValue: string = '';
private index: number = 0;
private typeName: string;
private placeholder: Resource;
private typeName: string = '';
private placeholder: Resource| undefined = undefined;
@LocalStorageProp('breakpoint') curBp: string = 'sm';
refresh() {
@@ -135,7 +135,7 @@ export struct ItemList {
@Builder MenuBuilder() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
ForEach(this.mPresent.getMenuList(this.typeName),
(item) => {
(item:EditType) => {
Text(item.labelRes)
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.width($r('app.float.account_MenuBuilder_width'))
@@ -153,7 +153,7 @@ export struct ItemList {
.width($r('app.float.account_Divider_width'))
.color($r('sys.color.ohos_id_color_list_separator'))
},
(item) => item.rawValue.toString())
(item:EditType) => item.rawValue.toString())
}
.width($r('app.float.account_MenuBuilder_width'))
.borderRadius($r('sys.float.ohos_id_corner_radius_default_l'))
@@ -28,8 +28,8 @@ export struct ShowDayTime {
@State showTime: Resource = $r('app.string.yearMonthDay', this.date.getFullYear(),
(this.date.getMonth() + 1), this.date.getDate());
controller: CustomDialogController
cancel: () => void
confirm: () => void
@Prop cancel: () => void
@Prop confirm: () => void
build() {
Column() {
@@ -49,8 +49,10 @@ export struct ShowDayTime {
.margin({ bottom: 8 })
.lunar(this.itemType == Birthday.TYPE_LUNARBIRTHDAY)
.onChange((value: DatePickerResult) => {
this.date = new Date(value.year, value.month, value.day);
this.showTime = $r('app.string.yearMonthDay', value.year, (value.month + 1), value.day);
if(value !== undefined && value.year !== undefined && value.month !== undefined){
this.date = new Date(value.year, value.month, value.day);
this.showTime = $r('app.string.yearMonthDay', value.year, (value.month + 1), value.day);
}
})
Row() {
@@ -96,8 +98,8 @@ export struct ShowDayTime {
this.mPresent.contactInfoAfter.events[this.itemIndex] = new EventBean('', '', '1', '');
}
this.mPresent.contactInfoAfter.events[this.itemIndex].data =
StringFormatUtil.numberFormatDateString(this.date.getFullYear(),
this.date.getMonth() + 1, this.date.getDate());
StringFormatUtil.numberFormatDateString(this.date.getFullYear(),
this.date.getMonth() + 1, this.date.getDate());
this.mPresent.refresh();
this.controller.close();
this.confirm();
@@ -13,17 +13,17 @@
* limitations under the License.
*/
import { StringUtil } from '../../../../../../../common/src/main/ets/util/StringUtil';
import { ContactVo, PhoneNumberObj } from '../../../model/bean/ContactVo';
/**
* Select the contact item component, which is responsible for displaying a single contact.
*/
@Component
export default struct BatchSelectContactItemView {
@State private single: boolean = false;
@State private item: { [key: string]: any } = {};
private onContactItemClicked: Function;
private onSingleContactItemClick: Function;
private index: number;
@State private item: ContactVo = new ContactVo('','','','','','',false,'','');
private onContactItemClicked: Function = () =>{};
private onSingleContactItemClick: Function = () =>{};
private index: number = 0;
@State private showIndex: boolean = false;
@State private showDivifer: boolean = false;
@@ -104,7 +104,7 @@ export default struct BatchSelectContactItemView {
})
List({ space: 0, initialIndex: 0 }) {
ForEach(this.item.phoneNumbers, (item, index) => {
ForEach(this.item.phoneNumbers, (item :phoneNumberObj, index) => {
ListItem() {
if (index != 0) {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
@@ -136,12 +136,12 @@ export default struct BatchSelectContactItemView {
if (!this.single) {
this.onContactItemClicked(this.index, index);
} else {
this.onSingleContactItemClick(this.item.phoneNumbers[index].phoneNumber, this.item.showName);
this.onSingleContactItemClick(this.item.phoneNumbers[0].phoneNumber, this.item.showName);
}
})
}
}
}, (item, index) => JSON.stringify(item))
}, (item:phoneNumberObj, index) => JSON.stringify(item))
}
.listDirection(Axis.Vertical)
.edgeEffect(EdgeEffect.Spring)
@@ -165,4 +165,4 @@ export default struct BatchSelectContactItemView {
[this.showDivifer ? 0 : 24, this.showDivifer ? 0 : 24]]
}))
}
}
}
@@ -14,16 +14,29 @@
*/
import { StringUtil } from '../../../../../../../common/src/main/ets/util/StringUtil';
import { CallLogDetailInterface } from '../../../model';
/**
* Select the contact item component, which is responsible for displaying a single contact.
*/
@Component
export default struct BatchSelectRecentItemView {
private onRecentItemClicked: Function;
@State private item: { [key: string]: any } = {};
private index: number;
private onRecentItemClicked: Function = ()=>{};
@State private item: CallLogDetailInterface = {
id: '',
phoneNumber: '',
displayName: '',
callDirection: '',
isRead: '',
ringDuration: '',
endTime: '',
suffix: '',
portraitColor: '',
formattedNumber: '',
numberLocation: '',
checked: false
};
private index: number = -1;
build() {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
Row() {
@@ -21,14 +21,14 @@ const TAG = 'BatchTabGuide ';
export default struct BatchTabGuide {
@State presenter: BatchSelectContactsPresenter = BatchSelectContactsPresenter.getInstance();
@Link currentIndex: number;
private controller: TabsController;
private controller: TabsController|null = null;
build() {
Flex({ direction: FlexDirection.Row,
justifyContent: FlexAlign.Center,
alignItems: ItemAlign.Center }) {
ForEach(this.presenter.tabTextSrc, (item, index) => {
ForEach(this.presenter.tabTextSrc, (item:string, index) => {
Flex({ direction: FlexDirection.Column,
justifyContent: FlexAlign.End,
alignItems: ItemAlign.Center }) {
@@ -52,11 +52,11 @@ export default struct BatchTabGuide {
.margin({ left: $r('app.float.id_card_margin_xl'), right: $r('app.float.id_card_margin_xl') })
.onClick(() => {
if (this.currentIndex != index) {
this.controller.changeIndex(index);
this.controller?.changeIndex(index);
}
})
}, (item, index) => JSON.stringify(item))
}, (item:string, index) => JSON.stringify(item))
}
.width('100%')
@@ -15,9 +15,24 @@
import { PhoneNumber } from '../../../../../../feature/phonenumber';
import { CallType } from '../../../../../../feature/call/src/main/ets/entity/CallLog';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import EnvironmentProp from '../../feature/EnvironmentProp';
import promptAction from '@ohos.promptAction'
import { CallBean } from '../../model/bean/CallBean';
import DetailPresenter from '../../presenter/contact/detail/DetailPresenter';
import { CallLogBean } from '../../model/bean/CallLogBean';
class CallLogObj{
public dateDetail:string = '';
public callType:CallType = CallType.MISSED;
public timeDetail:string = '';
public formatNumber:string = '';
public simId:number = -1;
public talkTime:string = '';
constructor(dateDetail: string) {
this.dateDetail = dateDetail;
}
}
const TAG = 'ContactDetail-calllog';
@@ -26,12 +41,12 @@ const TAG = 'ContactDetail-calllog';
*/
@Component
export default struct CallLogListItem {
@State message: { [key: string]: any } = {};
@State message: CallLogBean = new CallLogBean('','','','');
@State isEmergencyNum: boolean = false;
private imgRes: Resource;
private imgRes: Resource|undefined = undefined;
@StorageLink('haveMultiSimCard') haveMultiSimCard: boolean = false;
@StorageLink('haveSimCard') haveSimCard: boolean = false;
@Link private mPresenter: { [key: string]: any };
@Link private mPresenter: DetailPresenter;
private simImgRes: Resource = $r('app.media.stat_sys_sim1');
aboutToAppear() {
@@ -17,30 +17,36 @@ import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil'
import { DataItemType } from '../../../../../../feature/contact/src/main/ets/contract/DataType';
import StringFormatUtil from '../../util/StringFormatUtil'
import { Birthday } from '../../../../../../feature/contact/src/main/ets/contract/Birthday';
import { HiLog, StringUtil } from 'common';
import { BaseContackSubInfoModel } from '../../model';
@Component
export default struct DetailInfoList {
private dataType: DataItemType;
private List: string;
private hasArrow: boolean;
private dataType: DataItemType = DataItemType.EMAIL;
private List: string = '';
private hasArrow: boolean = false;
aboutToAppear(): void {
HiLog.i('DetailInfoList','DetailInfoList:' + this.List)
}
build() {
Column() {
if (!ArrayUtil.isEmpty(JSON.parse(this.List))) {
if (this.List !== '[]' ) {
Divider()
.color($r("sys.color.ohos_id_color_list_separator"))
.color(r("sys.color.ohos_id_color_list_separator"))
List() {
ForEach(JSON.parse(this.List), (item, index) => {
ForEach(JSON.parse(this.List), (item: BaseContackSubInfoModel, index) => {
ListItem() {
DetailInfoListItem({
title: this.dataType == DataItemType.EVENT ?
StringFormatUtil.stringFormatDateResource(item.data,
item?.type == Birthday.TYPE_LUNARBIRTHDAY) : item.data,
item.type == Birthday.TYPE_LUNARBIRTHDAY) : item.data,
content: item.labelName,
hasArrow: this.hasArrow,
});
}
}, item => JSON.stringify(item))
}, (item: BaseContackSubInfoModel) => JSON.stringify(item))
}
.divider({ strokeWidth: $r("app.float.id_divide_width"), color: $r("sys.color.ohos_id_color_list_separator") })
.scrollBar(BarState.Off)
@@ -53,9 +59,9 @@ export default struct DetailInfoList {
@Component
struct DetailInfoListItem {
private title: string;
private content: string;
private hasArrow: boolean;
private title: string | Resource = '';
private content: string | Resource = '';
private hasArrow: boolean = false;
build() {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
@@ -24,6 +24,8 @@ import { DataItemType } from '../../../../../../feature/contact/src/main/ets/con
import IndexPresenter from '../../presenter/IndexPresenter';
import { SelectDialogBuilder } from '../mutisim/SelectSimIdDialog';
import promptAction from '@ohos.promptAction'
import SelectMemberSendMessagePresenter from '../../presenter/SelectMemberSendMessagePresenter';
import DetailPresenter from '../../presenter/contact/detail/DetailPresenter';
const TAG = 'ContactDetail-detailInfoList';
@@ -33,7 +35,7 @@ enum MenuType {
@Component
export default struct DetailInfoListView {
@Link mPresenter: { [key: string]: any };
@Link mPresenter: DetailPresenter;
@Link selectSimBuilder: SelectDialogBuilder;
build() {
@@ -111,21 +113,24 @@ export default struct DetailInfoListView {
@Component
struct TelList {
@State List: string = '';
@Link private mPresenter: { [key: string]: any };
@Link mPresenter: DetailPresenter;
@Link selectSimBuilder: SelectDialogBuilder;
aboutToAppear(): void {
HiLog.i(TAG,'TelList:' + this.List)
}
build() {
if (!ArrayUtil.isEmpty(JSON.parse(this.List))) {
if (this.List !== '') {
List() {
ForEach(JSON.parse(this.List), item => {
ForEach(JSON.parse(this.List), (item: string) => {
ListItem() {
TelListItem({
message: JSON.stringify(item),
mPresenter: $mPresenter,
selectSimBuilder: $selectSimBuilder
mPresenter: mPresenter,selectSimBuilder:
selectSimBuilder
});
}
}, item => JSON.stringify(item))
}, (item: string) => JSON.stringify(item))
}
.divider({ strokeWidth: $r('app.float.id_divide_width'), color: $r('sys.color.ohos_id_color_list_separator') })
.backgroundColor(Color.White)
@@ -145,8 +150,11 @@ struct TelListItem {
@State isEmergencyNum: boolean = false;
@StorageLink('haveSimCard') haveSimCard: boolean = false;
@StorageLink('haveMultiSimCard') haveMultiSimCard: boolean = false;
@Link private mPresenter: { [key: string]: any };
@Link private mPresenter: DetailPresenter;
@Link selectSimBuilder: SelectDialogBuilder;
aboutToAppear(): void {
HiLog.i(TAG,'TelListItem message:' + this.message)
}
@Builder MenuBuilder() {
Flex({ direction: FlexDirection.Column,
@@ -173,7 +181,8 @@ struct TelListItem {
.backgroundColor($r('sys.color.ohos_id_color_primary_contrary'))
}
@Builder MenuView(menuName, itemType) {
@Builder
MenuView(menuName: string, itemType: MenuType) {
Row() {
Text(menuName)
.fontSize($r('sys.float.ohos_id_text_size_body1'))
@@ -184,26 +193,28 @@ struct TelListItem {
.padding({ left: $r('app.float.id_card_margin_large'), right: $r('app.float.id_card_margin_large') })
.height($r('app.float.id_item_height_mid'))
.backgroundColor($r('sys.color.ohos_id_color_primary_contrary'))
.onClick(() => {
switch (itemType) {
case MenuType.Copy:
this.mIndexPresenter.getCopy(JSON.parse(this.message).data);
break;
case MenuType.EditBeforeCall:
AppStorage.SetOrCreate('isRouterBack', true);
DialerPresenter.getInstance().editPhoneNumber(JSON.parse(this.message).data);
AppStorage.SetOrCreate<boolean>('showDialBtn', true);
break;
}
})
.onClick(() => {
switch (itemType) {
case MenuType.Copy:
this.mIndexPresenter.getCopy(JSON.parse(this.message).data);
break;
case MenuType.EditBeforeCall:
AppStorage.SetOrCreate('isRouterBack', true);
DialerPresenter.getInstance().editPhoneNumber(JSON.parse(this.message).data);
AppStorage.SetOrCreate('showDialBtn', true);
break;
}
})
}
@Builder MenuDivider() {
@Builder
MenuDivider() {
Divider()
.color($r('sys.color.ohos_id_color_list_separator'))
.color(r('sys.color.ohos_id_color_list_separator'))
.lineCap(LineCapStyle.Square)
.width('100%')
.padding({ left: $r('app.float.id_card_margin_large'), right: $r('app.float.id_card_margin_large') })
.padding({ left:
r('app.float.id_card_margin_large'), right: $r('app.float.id_card_margin_large') })
}
build() {
@@ -275,7 +286,7 @@ struct TelListItem {
.backgroundColor(Color.White)
.onClick(() => {
this.mPresenter.sendMessage(JSON.parse(this.message).num,
JSON.parse(this.message).data, this.mPresenter.contactForm.display_name);
JSON.parse(this.message).data, this.mPresenter.contactForm.displayName.toString());
})
}
.flexShrink(0)
@@ -308,8 +319,8 @@ struct TelListItem {
});
}
this.selectSimBuilder.lastSimId = this.mPresenter.lastUsedSlotId;
let spnList = AppStorage.Get<Array<string | Resource>>('spnList');
for (var index = 0; index < spnList.length; index++) {
let spnList = AppStorage.Get<Array<string | Resource>>('spnList') as Array<string | Resource>;
for (let index = 0; index < spnList.length; index++) {
this.selectSimBuilder.multiSimCardItems[index].name = spnList[index];
}
this.selectSimBuilder.controller?.open();
@@ -17,7 +17,7 @@ import EnvironmentProp from '../../feature/EnvironmentProp';
@Component
export struct CallLogTabs {
private controller: TabsController
private controller: TabsController|null = null;
@Link bottomTabIndex: number
@LocalStorageProp('breakpoint') curBp: string = 'sm'
@@ -44,7 +44,7 @@ export struct CallLogTabs {
.margin(this.curBp === 'lg' ? { right: 50 } : { right: 31 })
.onClick(() => {
if (this.bottomTabIndex != 0) {
this.controller.changeIndex(0)
this.controller?.changeIndex(0)
}
})
@@ -68,7 +68,7 @@ export struct CallLogTabs {
.height($r("app.float.id_item_height_large"))
.onClick(() => {
if (this.bottomTabIndex != 1) {
this.controller.changeIndex(1)
this.controller?.changeIndex(1)
}
})
}
@@ -17,13 +17,13 @@ import EnvironmentProp from '../../feature/EnvironmentProp';
import DialerPresenter from '../../presenter/dialer/DialerPresenter';
import { MutiDialerButtonView } from '../mutisim/MutiDialerButtonView'
import { PhoneNumber } from '../../../../../../feature/phonenumber';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import promptAction from '@ohos.promptAction'
const TAG = 'DialerButtonView';
@Component
export struct DialerButtonView {
emergencyNum: string;
emergencyNum: string = '';
@Link mPresenter: DialerPresenter;
@StorageLink('tele_number') tele_number: string = '';
@StorageLink('haveSimCard') haveSimCard: boolean = false;
@@ -41,7 +41,7 @@ export struct MutiDialerButtonView {
build() {
Row() {
ForEach(this.simNames, (item, index) => {
ForEach(this.simNames, (item:string, index:number) => {
//DailButton for voLte
Row() {
Image(this.voLteRegStates[index] ? this.dailHDImg[index] : this.dailImg[index])
@@ -99,18 +99,20 @@ export struct SelectSimIdDialog {
}
class MultiSimCardItems {
name: string | Resource;
img: Resource;
name: string | Resource = '';
img: Resource|undefined = undefined;
}
interface Controller {
close();
open();
export class Controller {
public close: () => void = () => {
};
public open: () => void = () => {
};
}
export class SelectDialogBuilder {
title: string | Resource;
multiSimCardItems: Array<MultiSimCardItems>;
title: string | Resource = '';
multiSimCardItems: Array = [];
lastSimId?: number = -1;
callback?: (simId: number) => void;
controller?: Controller;
@@ -32,7 +32,7 @@ export default class EnvironmentProp {
* smartVision:智慧视觉设备
*/
static getDeviceType(): string {
return this.DEVICE_TYPE;
return EnvironmentProp.DEVICE_TYPE;
}
static isTablet(): boolean {
@@ -16,11 +16,12 @@
import { HiLog } from '../../../../../../common';
import commonEvent from '@ohos.commonEventManager';
import { PhoneNumber } from '../../../../../../feature/phonenumber';
import { MissedCallNotifyData } from '../../../../../../feature/call/src/main/ets/missedcall/MissedCallNotifier';
const TAG = 'MissedCallManager'
class MissedCallManager {
requestMissedCallAction(action, data: any) {
requestMissedCallAction(action: string, data: MissedCallNotifyData) {
if ('notification.event.message' == action) {
if (data && data.phoneNumber) {
PhoneNumber.fromString(data.phoneNumber).sendMessage();
@@ -30,8 +31,7 @@ class MissedCallManager {
this.cancelNotification(data);
}
cancelNotification(data?: any) {
cancelNotification(data?: Object) {
commonEvent.publish('contact.event.CANCEL_MISSED', {
bundleName: 'com.ohos.contacts',
parameters: {
+23 -22
View File
@@ -25,7 +25,8 @@ export const simId_TWO: number = 1;
const TAG = 'SimCardState';
class SimCardState {
mListener: () => void;
public mListener: () => void = () => {
};
mSimStateArray: Array<telephonySim.SimState> =
[telephonySim.SimState.SIM_STATE_UNKNOWN, telephonySim.SimState.SIM_STATE_UNKNOWN];
haveSimCard: boolean = false;
@@ -92,7 +93,7 @@ class SimCardState {
}
}
private parseSimCardStateForSlot(slotId: number, value) {
private parseSimCardStateForSlot(slotId: number, value: telephonySim.SimState) {
let changed: boolean = (value != this.mSimStateArray[slotId]);
if (!changed) {
return;
@@ -100,8 +101,8 @@ class SimCardState {
this.mSimStateArray[slotId] = value;
this.haveSimCard = this.isSimReady(simId_ONE) || this.isSimReady(simId_TWO);
this.haveMultiSimCard = this.isSimReady(simId_ONE) && this.isSimReady(simId_TWO);
AppStorage.SetOrCreate<boolean>('haveMultiSimCard', this.haveMultiSimCard);
AppStorage.SetOrCreate<boolean>('haveSimCard', this.haveSimCard);
AppStorage.SetOrCreate('haveMultiSimCard', this.haveMultiSimCard);
AppStorage.SetOrCreate('haveSimCard', this.haveSimCard);
HiLog.i(TAG, `parseSimCardStateForSlot sim ${slotId}} state ${value}}, haveSimCard: ` + this.haveSimCard +
', haveMultiSimCard: ' + this.haveMultiSimCard);
this.setDefaultSlot();
@@ -110,29 +111,29 @@ class SimCardState {
}
}
private setDefaultSlot() {
if (this.haveSimCard) {
if (!this.haveMultiSimCard) {
if (this.isSimReady(simId_ONE)) {
AppStorage.SetOrCreate<number>('defaultSlot', simId_ONE);
} else {
AppStorage.SetOrCreate<number>('defaultSlot', simId_TWO);
}
private setDefaultSlot() {
if (this.haveSimCard) {
if (!this.haveMultiSimCard) {
if (this.isSimReady(simId_ONE)) {
AppStorage.SetOrCreate('defaultSlot', simId_ONE);
} else {
telephonySim.getDefaultVoiceSlotId((err, slot: number) => {
if (err) {
HiLog.e(TAG, `getDefaultVoiceSlotId, ${slot} error: ${JSON.stringify(err)}`);
} else {
AppStorage.SetOrCreate<number>('defaultSlot', slot);
}
})
AppStorage.SetOrCreate('defaultSlot', simId_TWO);
}
} else {
if (AppStorage.Has('defaultSlot')) {
AppStorage.Delete('defaultSlot')
}
telephonySim.getDefaultVoiceSlotId((err, slot: number) => {
if (err) {
HiLog.e(TAG, `getDefaultVoiceSlotId, ${slot} error: ${JSON.stringify(err)}`);
} else {
AppStorage.SetOrCreate('defaultSlot', slot);
}
})
}
} else {
if (AppStorage.Has('defaultSlot')) {
AppStorage.Delete('defaultSlot')
}
}
}
}
export default new SimCardState();
@@ -21,7 +21,8 @@ const TAG = 'VoLteState';
class VoLteState {
haveVoLteReg: boolean = false;
voLteRegStates: boolean[] = [false, false]
mListener: () => void;
public mListener: () => void = () => {
};
public init() {
try {
@@ -68,7 +69,7 @@ class VoLteState {
radio.off('imsRegStateChange', slot, radio.ImsServiceType.TYPE_VOICE);
}
private parseVoLteState(slotId: number, data) {
private parseVoLteState(slotId: number, data: radio.ImsRegState) {
const voLte = (data == radio.ImsRegState.IMS_REGISTERED);
const changed = (voLte != this.voLteRegStates[slotId]);
if (!changed) {
@@ -77,7 +78,7 @@ class VoLteState {
}
this.voLteRegStates[slotId] = voLte;
this.haveVoLteReg = this.voLteRegStates[0] || this.voLteRegStates[1];
AppStorage.SetOrCreate<boolean>('haveVoLteReg', this.haveVoLteReg);
AppStorage.SetOrCreate('haveVoLteReg', this.haveVoLteReg);
AppStorage.SetOrCreate<boolean[]>('voLteRegStates', this.voLteRegStates);
HiLog.i(TAG, `parseVoLteState: state changed slotId${slotId} volte->${voLte}, haveVoLteReg:${this.haveVoLteReg}`);
if (this.mListener) {
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
/**
Copyright (c) 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
export default interface LooseObject {
[key: string]: any
}
@@ -22,6 +22,7 @@ export class AIMBean {
aimType: string;
//AIM Content
aimName: string;
public labelName?: Resource | string;
constructor(id: string, aimId: string, aimType: string, aimName: string) {
this.id = id;
this.aimId = aimId;
@@ -18,6 +18,7 @@ export class AssociatedPersonBean {
associatedPersonId: string
name: string
associatedType: string
public labelName?: Resource | string;
constructor(id: string, associatedPersonId: string, name: string, associatedType: string) {
this.id = id;
this.associatedPersonId = associatedPersonId;
@@ -12,8 +12,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import LooseObject from '../LooseObject ';
const TAG = 'BasicDataSource';
@@ -24,7 +24,7 @@ export class BasicDataSource implements IDataSource {
return 0
}
public getData(index: number): any {
public getData(index: number): LooseObject | undefined | null {
return undefined
}
@@ -14,9 +14,9 @@
*/
import BasicDataSource from './BasicDataSource';
import { ContactVo } from './ContactVo';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil';
import LooseObject from '../type/LooseObject';
const TAG = 'BatchSelectContactSource';
export default class BatchSelectContactSource extends BasicDataSource {
@@ -26,7 +26,7 @@ export default class BatchSelectContactSource extends BasicDataSource {
return this.contactList.length;
}
public getData(index: number): any {
public getData(index: number): LooseObject | undefined | null {
if (ArrayUtil.isEmpty(this.contactList) || index >= this.contactList.length) {
HiLog.i(TAG, 'getData contactlist is empty');
return null;
@@ -36,7 +36,7 @@ export default class BatchSelectContactSource extends BasicDataSource {
let showIndex: boolean = (index == 0 || !(contact.namePrefix === preContact.namePrefix));
let showDivifer: boolean = false;
if (index < this.contactList.length - 1) {
let nextContact: any = this.contactList[index + 1];
let nextContact: ContactVo = this.contactList[index + 1];
showDivifer = (contact.namePrefix === nextContact.namePrefix);
} else {
showDivifer = false;
@@ -13,19 +13,26 @@
* limitations under the License.
*/
import BasicDataSource from './BasicDataSource';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil';
import MergedCallLog from '../../../../../../feature/call/src/main/ets/entity/MergedCallLog';
import { ContactVo } from './ContactVo';
class LooseObject{
public showDivifer:boolean = false;
public index:number = 0;
public calllog: ContactVo|undefined = undefined;
}
const TAG = 'BatchSelectRecentSource';
export default class BatchSelectRecentSource extends BasicDataSource {
private callLogs: { [key: string]: any }[] = [];
private callLogs: ContactVo[] = [];
public totalCount(): number {
return this.callLogs.length;
}
public getData(index: number): any {
public getData(index: number): LooseObject | undefined | null {
HiLog.i(TAG, 'getData index is ' + JSON.stringify(index));
if (ArrayUtil.isEmpty(this.callLogs) || index >= this.callLogs.length) {
HiLog.i(TAG, 'getData calllog is empty');
@@ -41,7 +48,7 @@ export default class BatchSelectRecentSource extends BasicDataSource {
}
}
public refresh(callLogTemp: any[]) {
public refresh(callLogTemp: ContactVo[]) {
HiLog.i(TAG, ' refresh!');
this.callLogs = callLogTemp;
this.notifyDataReload();
+11 -11
View File
@@ -16,26 +16,26 @@
export class CallBean {
readonly id: string;
phone: string;
name: string;
callTime: string;
name: string = '';
callTime: string = '';
// Call type: 1: incoming call; 2: outgoing call; 3: missed call; 5: rejected call
callType: string;
callType: string = '';
// Home area of the number
callTag: string;
callTag: string = '';
// Call SIM card. 0: SIM card 1, 1: SIM card 2.
simType: string;
simType: string = '';
// Indicates whether an HD call is supported. true: HD call; false: non-HD call
isHd: string;
isHd: string = '';
// Format Phone Number
formatNumber: string;
formatNumber: string = '';
// Contact ID.
contactKey: string;
contactKey: string = '';
// Call Times
num: string;
num: string = '';
// Indicates whether to be selected. The default value is false.
isChecked: boolean = false;
portraitColor: string;
suffix: string;
portraitColor: string = '';
suffix: string = '';
constructor(id: string, phone: string) {
this.id = id;
this.phone = phone;
@@ -24,6 +24,12 @@ export class CallLogBean {
action: string;
calledNumber: string;
status: string;
callType: CallType = CallType.MISSED;
dateDetail: string = '';
timeDetail: string = '';
formatNumber: string = '';
talkTime: string = '';
simId:number = -1;
constructor(time: string, action: string, calledNumber: string, status: string) {
this.id = `${NextId++}`;
this.time = time;
@@ -31,4 +37,12 @@ export class CallLogBean {
this.calledNumber = calledNumber;
this.status = status;
}
}
export enum CallType{
IN = 1,
OUT = 2,
VOICEMAIL = 4,
MISSED = 3,
REJECTED = 5
}
@@ -13,21 +13,22 @@
* limitations under the License.
*/
import BasicDataSource from '../bean/BasicDataSource';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil';
import MergedCallLog from '../../../../../../feature/call/src/main/ets/entity/MergedCallLog';
import LooseObject from '../LooseObject ';
const TAG = 'CallRecordListDataSource';
export default class CallRecordListDataSource extends BasicDataSource {
private callLogData: any[] = [];
private isShow: boolean;
private isDataReload: boolean;
private callLogData: LooseObject[] = [];
private isShow: boolean = false;
private isDataReload: boolean = false;
public totalCount(): number {
return this.callLogData.length;
}
public getData(index: number): any {
public getData(index: number): LooseObject | null {
if (ArrayUtil.isEmpty(this.callLogData) || index >= this.callLogData.length) {
HiLog.w(TAG, 'getData callLogData is empty');
return null;
@@ -36,7 +37,7 @@ export default class CallRecordListDataSource extends BasicDataSource {
}
}
public refreshAll(callLogData) {
public refreshAll(callLogData: LooseObject[]) {
HiLog.i(TAG, ' refreshAll!');
this.callLogData = callLogData;
this.setDataReload(true);
@@ -51,13 +52,13 @@ export default class CallRecordListDataSource extends BasicDataSource {
this.setDataReload(this.isDataReload);
}
public refresh(start: number, count: number, callLogData: []) {
public refresh(start: number, count: number, callLogData: MergedCallLog[]) {
HiLog.i(TAG, ' refresh!');
this.callLogData.splice(start, count, ...callLogData);
this.setDataReload(true);
}
public remove(index: number, count?) {
public remove(index: number, count?: number) {
if (index < 0 || index >= this.totalCount()) {
return;
}
+20 -15
View File
@@ -12,14 +12,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {PhoneNumBean} from '../bean/PhoneNumBean'
import {EmailBean} from '../bean/EmailBean'
import {AIMBean} from '../bean/AIMBean'
import {HouseBean} from '../bean/HouseBean'
import {GroupBean} from '../bean/GroupBean'
import {EventBean} from '../bean/EventBean'
import {AssociatedPersonBean} from '../bean/AssociatedPersonBean'
import { PhoneNumBean } from '../bean/PhoneNumBean'
import { EmailBean } from '../bean/EmailBean'
import { AIMBean } from '../bean/AIMBean'
import { HouseBean } from '../bean/HouseBean'
import { GroupBean } from '../bean/GroupBean'
import { EventBean } from '../bean/EventBean'
import { AssociatedPersonBean } from '../bean/AssociatedPersonBean'
export class ContactInfo {
id: string;
@@ -37,12 +36,15 @@ export class ContactInfo {
relationships: AssociatedPersonBean[];
events: EventBean[];
groups: GroupBean[];
favorite: number;
constructor(id: string, display_name: string,
nickname: string, phones: PhoneNumBean[],
emails: EmailBean[], position: string, company: string, remarks: string,
aims: AIMBean[], houses: HouseBean[], websites: string[],
relationships: AssociatedPersonBean[], events: EventBean[], groups: GroupBean[], favorite: number) {
favorite: string | undefined;
phoneticName: string = '';
otherLanLastName: string = '';
otherLanFirstName: string = '';
constructor(id: string, display_name: string, nickname: string, phones: PhoneNumBean[], emails: EmailBean[],
position: string, company: string, remarks: string, aims: AIMBean[], houses: HouseBean[], websites: string[],
relationships: AssociatedPersonBean[], events: EventBean[], groups: GroupBean[],
favorite: number, phoneticName: string, otherLanLastName: string, otherLanFirstName: string) {
this.id = id;
this.display_name = display_name;
this.nickname = nickname;
@@ -57,7 +59,10 @@ export class ContactInfo {
this.relationships = relationships;
this.events = events;
this.groups = groups;
this.favorite = favorite;
this.favorite = favorite.toString();
this.phoneticName = phoneticName;
this.otherLanLastName = otherLanLastName;
this.otherLanFirstName = otherLanFirstName;
}
setID(id: string) {
@@ -14,22 +14,22 @@
*/
import BasicDataSource from './BasicDataSource';
import { ContactVo } from '../bean/ContactVo';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil';
import { StringUtil } from '../../../../../../common/src/main/ets/util/StringUtil';
import ContactListShowInfo from './ContactListShowInfo';
const TAG = 'ContactListDataSource';
export default class ContactListDataSource extends BasicDataSource {
private contactList: ContactVo[] = [];
private isShow: boolean;
private isDataReload: boolean;
private isShow: boolean = false;
private isDataReload: boolean = false;
public totalCount(): number {
return this.contactList.length;
}
public getData(index: number): any {
public getData(index: number): ContactListShowInfo | null {
if (ArrayUtil.isEmpty(this.contactList) || index >= this.contactList.length) {
HiLog.i(TAG, 'getData contactlist is empty');
return null;
@@ -46,14 +46,11 @@ export default class ContactListDataSource extends BasicDataSource {
}
contact.title = (StringUtil.isEmpty(contact.showName) ? contact.phoneNum : contact.showName);
let subtitleConcat: string = (!StringUtil.isEmpty(contact.company) &&
!StringUtil.isEmpty(contact.position)) ? ' | ' : '';
!StringUtil.isEmpty(contact.position)) ? ' | ' : '';
contact.subTitle = (StringUtil.isEmpty(contact.company) ? '' :
contact.company).concat(subtitleConcat).concat(StringUtil.isEmpty(contact.position) ? '' : contact.position);
return {
showIndex: showIndex,
showDivifer: showDivifer,
contact: contact
};
return new ContactListShowInfo(showIndex, showDivifer, contact.contactId, '',
'', contact.portraitPath, contact.namePrefix, contact.title, contact.subTitle,contact);
}
}
@@ -78,7 +75,7 @@ export default class ContactListDataSource extends BasicDataSource {
this.setDataReload(true);
}
public remove(index: number, count?) {
public remove(index: number, count?:number) {
if (index < 0 || index >= this.totalCount()) {
return;
}
+68 -21
View File
@@ -12,13 +12,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { StringUtil } from '../../../../../../common/src/main/ets/util/StringUtil';
import { PhoneNumberInterface } from '../type';
/**
* Contact List Data Structure Entity
Contact List Data Structure Entity
*/
export class ContactVo {
id: string = '';
suffix: string = '';
displayName: string = '';
phoneNumber: string = '';
quickSearchKey: string = '';
checked: boolean = false;
contactId: string;
namePrefix: string;
emptyNameData: string;
@@ -27,22 +34,22 @@ export class ContactVo {
portraitColor: string;
show: boolean;
portraitPath: string;
nameSuffix: string;
nameSuffix: string = '';
phoneNum: string;
showName: string;
phoneNumbers: object[];
name: NameVo;
title: string;
subTitle: string;
showName: string = '';
phoneNumbers: PhoneNumberInterface[] = [];
name: NameVo = new NameVo('', '', '');
title: string = '';
subTitle: string = '';
constructor(contactId: string,
namePrefix: string,
emptyNameData: string,
company: string,
position: string,
portraitColor: string,
show: boolean,
portraitPath: string,
phoneNum: string
namePrefix: string,
emptyNameData: string,
company: string,
position: string,
portraitColor: string,
show: boolean,
portraitPath: string,
phoneNum: string
) {
this.contactId = contactId;
this.namePrefix = namePrefix;
@@ -56,14 +63,15 @@ export class ContactVo {
}
public setShowName() {
this.showName = !StringUtil.isEmpty(this.emptyNameData) ? this.emptyNameData : (!StringUtil.isEmpty(this.company) ? this.company : (!StringUtil.isEmpty(this.position) ? this.position : ''))
this.showName = !StringUtil.isEmpty(this.emptyNameData) ? this.emptyNameData :
(!StringUtil.isEmpty(this.company) ? this.company : (!StringUtil.isEmpty(this.position) ? this.position : ''))
}
public setName(emptyNameData: string, namePrefix: string, nameSuffix: string) {
this.name = new NameVo(emptyNameData, namePrefix, nameSuffix);
}
public setphoneNumbers(phoneNumbers: object[]) {
public setphoneNumbers(phoneNumbers: PhoneNumberInterface[]) {
this.phoneNumbers = phoneNumbers;
}
@@ -76,13 +84,52 @@ export class ContactVo {
}
}
export class PhoneNumberObj {
public phoneNumber: string = '';
public startPhone: string = '';
public middlePhone: string = '';
public endPhone: string = '';
public checked: boolean = false;
public labelName: Resource | undefined = undefined;
public numType: string = '';
}
export class CharIndex {
public char: string;
public start: number;
public end: number;
constructor(char: string = '', start: number = -1, end: number = -1) {
this.char = char;
this.start = start;
this.end = end;
}
}
export class AlphabetIndexObj {
/**
二级索引对应的排序首字母信息
enPrefix
start end 对应此二级索引的数据start和end,如A字母下有数据'a啊''a给''啊啊''啊给',四个值, 下标就是这几个值的起始,终止下标[0, 3]
char为索引下第一个联系人的photo_first_name
/
public enPrefix: CharIndex = new CharIndex();
/*
二级索引对应的汉字;
每个汉字对应start,end:如果汉字索引只有一个对应名字,下标为该名称位置,start==end;
如果二级索引有多个名字,如 '啊啊''啊给''啊个',三个啊,二级索引显示一个,下标为该三个值的起始位置
*/
public zhPrefix: Array = [];
}
export class NameVo {
fullName: string;
namePrefix: string;
nameSuffix: string;
searchTextStart: string;
searchTextMiddle: string;
searchTextEnd: string;
searchTextStart: string = '';
searchTextMiddle: string = '';
searchTextEnd: string = '';
constructor(emptyNameData: string, namePrefix: string, nameSuffix: string) {
this.fullName = emptyNameData;
this.namePrefix = namePrefix;
@@ -14,8 +14,9 @@
*/
import BasicDataSource from './BasicDataSource';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil';
import LooseObject from '../type/LooseObject';
const TAG = "DetailCallLogDataSource";
@@ -26,7 +27,7 @@ export default class DetailCallLogDataSource extends BasicDataSource {
return this.detailCallLogList.length;
}
public getData(index: number): any {
public getData(index: number): null | LooseObject {
HiLog.i(TAG, "getData index is %s" + index);
if (ArrayUtil.isEmpty(this.detailCallLogList) || index >= this.detailCallLogList.length) {
HiLog.i(TAG, "getData detailCallLogList is empty");
@@ -37,7 +38,7 @@ export default class DetailCallLogDataSource extends BasicDataSource {
if (index == 0) {
showTitle = true;
}
let item = {
let item: LooseObject = {
callLog: callLog,
showTitle: showTitle
}
@@ -45,7 +46,7 @@ export default class DetailCallLogDataSource extends BasicDataSource {
}
}
public refresh(callLog) {
public refresh(callLog: object[]) {
HiLog.i(TAG, ' refresh!');
this.detailCallLogList = callLog;
this.notifyDataReload();
@@ -20,6 +20,7 @@ export class EmailBean {
id: string
address: string
emailType: string
public labelName?: Resource | string;
constructor(id: string, address: string, emailType: string) {
this.id = id;
this.address = address;
@@ -18,6 +18,7 @@ export class EventBean {
data: string;
eventType: string;
eventName: string;
public labelName?: Resource | string;
constructor(id: string, data: string, eventType: string, eventName: string) {
this.id = id;
this.data = data;
+59 -57
View File
@@ -14,67 +14,69 @@
*/
import { StringUtil } from '../../../../../../common/src/main/ets/util/StringUtil';
import { PhoneNumberObj } from './ContactVo';
/**
* Favorite List Data Structure Entity
*/
export class FavoriteBean {
contactId: string;
/**
* 0 Favorite 1 Usually
*/
isCommonUseType: number;
/**
* Contact Name
*/
displayName: string;
phoneNum: string;
nameSuffix: string;
namePrefix: string;
portraitColor: string;
/**
* Display Usually
*/
isUsuallyShow: boolean;
portraitPath: string;
isEditSelect: boolean
favorite: number;
company: string;
position: string;
show: boolean;
showName: string;
phoneNumbers: object[];
title: string;
subTitle: string;
favoriteOrder: string;
constructor(
contactId: string,
isCommonUseType: number,
displayName: string,
phoneNum: string,
nameSuffix: string,
namePrefix: string,
portraitColor: string,
isUsuallyShow: boolean,
portraitPath: string,
isEditSelect: boolean,
favorite: number,
favoriteOrder: string,
) {
this.contactId = contactId;
this.isCommonUseType = isCommonUseType;
this.displayName = displayName;
this.phoneNum = phoneNum;
this.nameSuffix = nameSuffix;
this.namePrefix = namePrefix;
this.portraitColor = portraitColor;
this.isUsuallyShow = isUsuallyShow;
this.portraitPath = portraitPath;
this.isEditSelect = isEditSelect;
this.favorite = favorite;
this.favoriteOrder = favoriteOrder;
}
export class FavoriteBean {
contactId: string;
/*
0 Favorite 1 Usually
*/
isCommonUseType: number;
/*
Contact Name
*/
displayName: string;
phoneNumber: string = '';
phoneNum: string;
nameSuffix: string;
namePrefix: string;
portraitColor: string;
/*
Display Usually
*/
isUsuallyShow: boolean;
portraitPath: string;
isEditSelect: boolean
favorite: number;
company: string = '';
position: string = '';
show: boolean = false;
showName: string = '';
phoneNumbers: phoneNumberObj[] = [];
title: string = '';
subTitle: string = '';
favoriteOrder: string;
editContact: string = '';
constructor(
contactId: string,
isCommonUseType: number,
displayName: string,
phoneNum: string,
nameSuffix: string,
namePrefix: string,
portraitColor: string,
isUsuallyShow: boolean,
portraitPath: string,
isEditSelect: boolean,
favorite: number,
favoriteOrder: string,
) {
this.contactId = contactId;
this.isCommonUseType = isCommonUseType;
this.displayName = displayName;
this.phoneNum = phoneNum;
this.nameSuffix = nameSuffix;
this.namePrefix = namePrefix;
this.portraitColor = portraitColor;
this.isUsuallyShow = isUsuallyShow;
this.portraitPath = portraitPath;
this.isEditSelect = isEditSelect;
this.favorite = favorite;
this.favoriteOrder = favoriteOrder;
}
public setShowName() {
this.showName = !StringUtil.isEmpty(this.displayName) ? this.displayName : (!StringUtil.isEmpty(this.company) ? this.company : (!StringUtil.isEmpty(this.position) ? this.position : ""))
@@ -22,8 +22,8 @@ export class FavoriteListBean {
showIndex: boolean;
showDivider: boolean;
favorite: FavoriteBean;
contact: SearchContactsBean;
constructor(index: number, showIndex: boolean, showDivider: boolean, favorite: FavoriteBean, contact: SearchContactsBean) {
contact: SearchContactsBean | null;
constructor(index: number, showIndex: boolean, showDivider: boolean, favorite: FavoriteBean, contact: SearchContactsBean | null) {
this.index = index;
this.showIndex = showIndex;
this.showDivider = showDivider;
@@ -20,6 +20,7 @@ export class HouseBean {
houseType: string;
//Residential address
houseName: string;
public labelName?: Resource | string;
constructor(id: string, houseId: string, houseType: string, houseName: string) {
this.id = id;
this.houseId = houseId;
+10 -5
View File
@@ -17,13 +17,18 @@
* Phone Number Object
*/
export class PhoneNumBean {
id:string
id: string
num: string
numType: string
homeArea: string
carriers: string
constructor(id: string, num: string, numType: string, homeArea: string, carriers: string) {
homeArea: string = ''
carriers: string = ''
public labelName?: Resource | string;
public phoneAddress?: Resource | string;
formatNum?: string;
primary: boolean = false;
dataId: number = -1;
constructor(id: string, num: string, numType: string, homeArea: string,
carriers: string) {
this.id = id;
this.num = num;
this.numType = numType;
@@ -0,0 +1,14 @@
import MeeTimeAbilityInfoModel from '../../../../../../feature/contact/src/main/ets/entity/MeeTimeAbilityInfoModel';
import { ContactInfo } from './ContactInfo';
export class RichContactInfo extends ContactInfo {
public photoFirstName: string = ''
// 对应contactdata名称类型数据,数据库EXTEND7,如果为1,表示联系人名称没有值,当前显示的名称是根据规则从其他详情信息获取的
public nameUpdate?: number | string | Uint8Array
public meeTimeAbilityInfoModel: MeeTimeAbilityInfoModel = new MeeTimeAbilityInfoModel()
public accountId: number = -1
constructor(id: string) {
super(id, '', '', [], [], '', '', '', [], [], [], [], [], [], -1, '', '', '')
}
}
@@ -0,0 +1,88 @@
/**
Copyright (c) 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
SearchContactResult List Data Structure Entity
*/
export class SearchContactResult {
/*
联系人id
/
public entityId: string;
public entityName: string;
/*
联系人名称艾风 艾慕青
*/
public name: string;
public namePinyin: string;
public organization: string;
public position: string;
public phoneNumbers: object[] = [];
public emails: object[] = [];
public note: string;
public familyAddress: string;
public imInfo: object[] = [];
public groupName:Object[] = [];
public nickname: string;
public meeTimeUri: string;
public relationShip:Object[] = [];
public hicall:Object[] = [];
public isDeleted:number;
public iconUrl:String;
public iconData:String;
public sortFirstLetter: string;
public checked: boolean = false;
constructor(
entityId: string,
entityName: string,
name: string,
namePinyin: string,
organization: string,
position: string,
phoneNumbers: object[] = [],
emails: object[] = [],
note: string,
familyAddress: string,
imInfo: object[] = [],
groupName:Object[] = [],
nickname: string,
meeTimeUri: string,
relationShip:Object[] = [],
hicall:Object[] = [],
isDeleted:number,
iconUrl:String,
iconData:String,
sortFirstLetter: string,
) {
this.entityId = entityId;
this.entityName = entityName;
this.name = name;
this.namePinyin = namePinyin;
this.organization = organization;
this.position = position;
this.phoneNumbers = phoneNumbers;
this.emails = emails;
this.note = note;
this.familyAddress = familyAddress;
this.imInfo = imInfo;
this.groupName = groupName;
this.nickname = nickname;
this.meeTimeUri = meeTimeUri;
this.relationShip = relationShip;
this.hicall = hicall;
this.isDeleted = isDeleted;
this.iconUrl = iconUrl;
this.iconData = iconData;
this.sortFirstLetter = sortFirstLetter;
}
}
@@ -32,10 +32,9 @@ export class SearchContactsBean {
photoFirstName: string;
sortFirstLetter: string;
portraitColor: string;
portraitPath: string;
portraitPath: string = '';
detailInfo: string;
hasPhoneNumber: string;
hasPhoneNumber: string = '';
constructor(
id: string,
accountId: string,
@@ -15,21 +15,22 @@
import { SearchContactsBean } from '../bean/SearchContactsBean';
import { FavoriteListBean } from '../bean/FavoriteListBean';
import BasicDataSource from './BasicDataSource';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil';
import { SearchContactResult } from '../bean/SearchContactResult';
import { FavoriteBean } from './FavoriteBean';
const TAG = 'SearchContactsSource ';
export default class SearchContactsSource extends BasicDataSource {
private contactList: SearchContactsBean[] = [];
public contactObj: { [key: string]: SearchContactsBean[] } = {};
public contactIndexObj: { [key: string]: number } = {};
public contactObj: Record<string, SearchContactResult[]> = {};
public contactIndexObj: Record<string, number> = {};
public totalCount(): number {
return this.contactList.length;
}
public getData(index: number): FavoriteListBean {
public getData(index: number): FavoriteListBean|null {
if (ArrayUtil.isEmpty(this.contactList) || index >= this.contactList.length) {
HiLog.i(TAG, 'getData contactlist is empty');
return null;
@@ -44,7 +45,7 @@ export default class SearchContactsSource extends BasicDataSource {
} else {
showDivider = false;
}
return new FavoriteListBean(index, showIndex, showDivider, null, contact);
return new FavoriteListBean(index, showIndex, showDivider, new FavoriteBean('', -1, '', '', '', '', '', true, '', false, 0, ''), contact);
}
}
@@ -14,14 +14,22 @@
*/
import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { CallLogService, CallLogRepository } from '../../../../../../feature/call';
import { ContactRepository } from '../../../../../../feature/contact/src/main/ets/repo/ContactRepository';
import { StringUtil } from '../../../../../../common/src/main/ets/util/StringUtil';
import { CallInfoGetParamsInCallback } from '../type/ContactParams';
import { ContactInfo } from '../bean/ContactInfo';
import {
AllCallsGetActionData,
CallHistorySearchGetActionData
} from '../../../../../../entry/src/main/ets/model/type';
import { MergeRule } from '../../../../../../feature/call/src/main/ets/CallLogService.ets';
import { CallLog } from '../../../../../../feature/call/src/main/ets/entity/CallLog';
const TAG = 'CallLogModel';
export default {
class CallLogModel {
/**
* Obtains and caches all 2000 call records.
*
@@ -29,14 +37,18 @@ export default {
* @param {string} mergeRule Call Record Type
* @param {Object} callBack Call log data
*/
getAllCalls: async function (param, actionData, mergeRule, callBack, context?) {
async getAllCalls(param: ContactInfo, actionData: AllCallsGetActionData, mergeRule: MergeRule, callBack: Function,
context?: Context) {
if (context) {
CallLogRepository.getInstance().init(context);
}
HiLog.i(TAG, 'getAllCalls in:' + JSON.stringify(actionData));
CallLogRepository.getInstance().findAll(param.favorite, actionData, result => {
let resultData = {
callLogList: [], missedList: [], callLogTotal: 0
CallLogRepository.getInstance().findAll(actionData, (result: CallLog[]) => {
let resultData: CallInfoGetParamsInCallback = {
callLogList: [],
missedList: [],
callLogSearchList: [],
timeStamp: ''
};
if (ArrayUtil.isEmpty(result)) {
HiLog.i(TAG, 'getAllCalls logMessage callLog resultSet is empty!');
@@ -47,16 +59,15 @@ export default {
CallLogService.getInstance().setMergeRule(mergeRule)
resultData.callLogList = CallLogService.getInstance().mergeCallLogs(result);
resultData.missedList = CallLogService.getInstance().mergeMissedCalls(result);
resultData.callLogTotal = result.length;
let numberList = this.getNumberList(resultData);
this.queryContactsName(numberList, resultData, resultData => {
this.queryContactsName(numberList, resultData, (resultData: CallInfoGetParamsInCallback) => {
callBack(resultData);
}, context)
});
},
}
getNumberList(resultData) {
let numberList = new Set();
getNumberList(resultData: CallInfoGetParamsInCallback) {
let numberList: Set = new Set();
for (let callLog of resultData.callLogList) {
numberList.add(callLog.phoneNumber);
}
@@ -64,61 +75,66 @@ export default {
numberList.add(missed.phoneNumber);
}
return Array.from(numberList);
},
}
queryContactsName(numberList, resultData, callback, context?) {
queryContactsName(numberList: string[], resultData: CallInfoGetParamsInCallback, callback: Function,
context?: Context) {
if (numberList.length == 0) {
HiLog.w(TAG, "queryContactsName, has no number");
callback(resultData);
return;
}
ContactRepository.getInstance().init(context);
ContactRepository.getInstance().queryContactDataByNumber(numberList, contacts => {
ContactRepository.getInstance().queryContactDataByNumber(numberList, (contacts: Record<string, string>[]) => {
// Convert the result to Map, key: mobile number, value: name
let numberMap = this.getNumberMap(contacts);
this.buildName(resultData, numberMap);
callback(resultData);
});
},
}
getNumberMap(contacts) {
let numberMap = new Map();
getNumberMap(contacts: Record<string, string>[]) {
let numberMap: Map<string, string> = new Map();
for (let item of contacts) {
if (!StringUtil.isEmpty(item.displayName)) {
numberMap.set(item.detailInfo, item.displayName);
}
}
return numberMap;
},
}
buildName(resultData, numberMap) {
buildName(resultData: CallInfoGetParamsInCallback, numberMap: Map<string, string>) {
// Match the result based on the mobile number.
for (let callLog of resultData.callLogList) {
if (numberMap.has(callLog.phoneNumber)) {
callLog.displayName = numberMap.get(callLog.phoneNumber);
callLog.displayName = numberMap.get(callLog.phoneNumber) as string;
} else {
callLog.displayName = "";
}
}
for (let missed of resultData.missedList) {
if (numberMap.has(missed.phoneNumber)) {
missed.displayName = numberMap.get(missed.phoneNumber);
missed.displayName = numberMap.get(missed.phoneNumber) as string;
} else {
missed.displayName = "";
}
}
},
}
getCallHistorySearch: async function (actionData, mergeRule, callBack, context?) {
async getCallHistorySearch(actionData: CallHistorySearchGetActionData, mergeRule: MergeRule, callBack: Function,
context?: Context) {
if (context) {
CallLogRepository.getInstance().init(context);
}
CallLogRepository.getInstance().findSearch(actionData, result => {
HiLog.i(TAG, 'getCallHistorySearch resultSet.rowCount :' + JSON.stringify(result.rowCount));
let resultData = {
callLogList: [], missedList: []
CallLogRepository.getInstance().findSearch(actionData, (result?: CallLog[]) => {
HiLog.i(TAG, 'getCallHistorySearch resultSet.rowCount :' + JSON.stringify(result?.length));
let resultData: CallInfoGetParamsInCallback = {
callLogList: [],
missedList: [],
callLogSearchList: [],
timeStamp: ''
};
if (ArrayUtil.isEmpty(result)) {
if (result == undefined || ArrayUtil.isEmpty(result)) {
HiLog.i(TAG, 'getCallHistorySearch logMessage callLog resultSet is empty!');
callBack(resultData);
return;
@@ -128,9 +144,11 @@ export default {
resultData.callLogList = CallLogService.getInstance().mergeCallLogs(result);
resultData.missedList = CallLogService.getInstance().mergeMissedCalls(result);
let numberList = this.getNumberList(resultData);
this.queryContactsName(numberList, resultData, resultData => {
this.queryContactsName(numberList, resultData, () => {
callBack(resultData);
}, context)
});
})
}
}
}
export default new CallLogModel();
+133
View File
@@ -0,0 +1,133 @@
import { ContactVo } from './bean/ContactVo';
import common from '@ohos.app.ability.common';
import { RichContactInfo } from './bean/RichContactInfo';
export interface BatchSelectContact {
showIndex: boolean,
showDivifer: boolean,
contact: ContactVo,
index: number,
single?: boolean,
calllog: CallLogDetailInterface
}
export interface CallLogDetailInterface {
id: string,
phoneNumber: string,
displayName: string,
callDirection: string,
isRead: string,
ringDuration: string,
endTime: string,
suffix:string,
portraitColor:ResourceColor,
formattedNumber:string,
numberLocation:string,
checked:boolean,
}
export interface GetLunarDateRe {
year: number
month: number
day: number,
isLeapMonth: boolean
}
export interface PageLimit {
page?: number,
limit?: number
}
export interface AllCallsGetActionData extends PageLimit {
favoriteForm?: string
isNeedQueryContact?: boolean
// 是否使用静默访问方式查询
isProxyQuery?: boolean
}
export interface FindByNumberActionData extends PageLimit {
context?: common.UIAbilityContext,
numbers: string[],
contactId?: number,
}
export interface CallHistorySearchGetActionData {
teleNumber: string
nameArray: Array
}
export class SendMessageParams {
public contactName: string;
public telephone: string;
public telephoneFormat: string;
public contactId?: number;
constructor(number: string, formatNum: string, name?: string, id?: number) {
this.telephone = number;
this.telephoneFormat = formatNum;
this.contactName = name as string;
this.contactId = id;
}
}
export interface AccountantParams extends SingleSelectContact {
isEditMyCard?: boolean
isCreateMyCard?: boolean
avtarDeletedCallBack?: () => void
phoneNumbers?: Record<string, string>[],
}
export interface SingleSelectContact {
editContact: number,
contactId: string,
phones: ContackPhoneSubInfoModel[],
callId: string,
phoneNumberShow: string,
sourceHasParam?: boolean,
//是否展开更多
updataShow?: boolean,
disPlayName: string,
phoneNumbers?: Record<string, string>[],
nameRawContactId?: number,
displayNameHighlight?: boolean,
}
export interface ContactInterface {
i: number,
item: T
}
export class ContactReturnObj {
public data?: RichContactInfo
}
export interface BaseContackSubInfoModel {
id: string;
data: string;
type: number;
labelName: Resource | string;
dataType: number;
calendarEventId: string;
contactDataId: number;
}
export interface ContackPhoneSubInfoModel extends BaseContackSubInfoModel {
num?: string;
phoneAddress?: string | Resource;
primary?: boolean;
dataId?: number;
formatNum?: string;
}
export interface TargetPageInter {
url?: string,
pageIndex?: number,
params?: Record<string, string>
}
export class DetailInfo {
public id:number = -1;
public data: string = '';
public labelName: Resource|string = '';
public type: number | undefined = -1;
}
@@ -0,0 +1,73 @@
/*
Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
*/
import systemSoundManager from '@ohos.multimedia.systemSoundManager';
export interface ToneAttrs {
title: string,
fileName: string,
uri: string,
customizedType: systemSoundManager.ToneCustomizedType,
}
export interface RingtoneInfo {
ringtoneName: string,
ringtoneFilePath: string,
ringtonePath: string,
ringtoneType?: string,
}
/**
本地铃声参数
*/
export class RingtoneParam {
// 要发送给callui的联系人id
public contactId?: string;
// 页面类型 localMusic(本地歌曲)
public pageType?: string;
// 铃声类型 phone, message, notification, alarm
public toneType?: string;
// SIM卡类型:0, 1
public card?: string;
// 音乐app存在时设置选中的铃声路径
public ringtonePath?: string = '';
// 设置选中的铃声路径
public selectedRingtonePath?: string = '';
// 设置选中的铃声名字
public selectedRingtoneName?: string = '';
// 设置选中的铃音库名字
public selectedLibraryRingtonePath?: string = '';
// 是否显示标题栏
public showTitle: boolean = false;
// 设置选中的铃声id
public selectRingtoneContentId: string = '';
}
/**
铃声类型枚举
*/
export enum ToneType {
RINGTONE = 'phone',
MESSAGE_TONE = 'message',
NOTIFICATION_TONE = 'notification',
INVALID_TONE = 'invalid',
ALARM = 'alarm',
CONTACT = 'contact'
}
/**
页面类型枚举
*/
export enum PageType {
LOCAL_PAGE_TYPE = 'localMusic',
ONLINE_PAGE_TYPE = 'onlineRingtone',
}
/**
页面类型枚举
*/
export enum RingtoneType {
SYSTEM_TYPE = '0',
LOCAL_TYPE = '1',
LOCAL_VIDEO_TYPE = '2',
}
@@ -0,0 +1,265 @@
/**
Copyright (c) 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { paramsInterface } from '.';
import MergedCallLog from '../../../../../../feature/call/src/main/ets/entity/MergedCallLog';
import SearchContactListItem from '../../../../../../feature/contact/src/main/ets/repo/SearchContactListItem';
import { AlphabetIndexObj, ContactVo } from '../../../ets/model/bean/ContactVo';
import MorandiColor from '../bean/MorandiColor';
import { SearchContactsBean } from '../bean/SearchContactsBean';
export class AllContactGetParam {
/*
query contact list
page is offset page
*/
public page: number;
public limit: number;
public rawContactIds?: string[];
constructor(page: number, limit: number) {
this.page = page;
this.limit = limit;
}
}
export class AllContactWithPhoneNumbersGetParam {
/*
query all contact info with phone number
this is kind of filter
*/
public favorite: number;
public editContact: number;
public accountId: number = -1;
public pageTag: string = '';
public groupId: number = -1;
constructor(favorite: number, editContact: number, accountId?: number, pageTag?: string, groupId?: number) {
this.favorite = favorite;
this.editContact = editContact;
if (accountId) {
this.accountId = accountId;
}
if (pageTag) {
this.pageTag = pageTag;
}
if (groupId) {
this.groupId = groupId;
}
}
}
export class ContactResultSetQueryParams {
public resultList: ContactVo[];
public alphabetIndex: Record<string, AlphabetIndexObj>;
constructor(resultList: ContactVo[], alphabetIndex: Record<string, AlphabetIndexObj>) {
this.resultList = resultList;
this.alphabetIndex = alphabetIndex;
}
}
export class NameFixInfo {
/*
example: name is wangdabao
namePrefix is wang
nameSuffix is bao
*/
// SORT_FIRST_LETTER
public namePrefix: string;
// PHOTO_FIRST_NAME
public nameSuffix: string;
public displayName: string;
constructor(prefix: string, suffix: string, displayName: string = '') {
this.namePrefix = prefix;
this.nameSuffix = suffix;
this.displayName = displayName;
}
}
export class CountAlphabetIndex {
public count: number;
public alphabetIndex: Record<string, AlphabetIndexObj>;
constructor(count: number, alphabetIndex: Record<string, AlphabetIndexObj>) {
this.count = count;
this.alphabetIndex = alphabetIndex;
}
}
export class CountRawContact {
public count: number;
constructor(count: number) {
this.count = count;
}
}
export class ContactSearchResultData {
public total: number = 0;
public data: Array<SearchContactListItem | SearchContactsBean> = [];
public keyWord: string = '';
constructor(total: number, data: SearchContactListItem[], keyWord: string) {
this.total = total;
this.data = data;
this.keyWord = keyWord;
}
}
export interface IContactSearchParams {
value: string;
loopRequest: boolean;
startIndex: number;
limitNumber: number;
}
export interface ContactInfoGetParamsInCallback {
contactList: Array;
alphabetIndex: Record<string, AlphabetIndexObj>;
}
export interface CallInfoGetParamsInCallback {
callLogList: Array;
missedList: Array;
callLogSearchList: Array;
timeStamp: string;
isEnd?: boolean;
}
export type IT9PhoneNumbersFavoriteGroup = 'teleNumber';
export type IT9PhoneNumbersFavoriteType = Record<IT9PhoneNumbersFavoriteGroup, string>;
export interface IT9PhoneNumbersQueryParams {
favorite: IT9PhoneNumbersFavoriteType;
}
export interface IContactListAndAlphabetIndex {
contactList: ContactVo[];
alphabetIndex: Record<string, AlphabetIndexObj>;
}
export interface PickerContactList {
contactList: ContactPickerListItem[];
defaultSelectContactMap: Map<number, Set>;
isEnd: boolean;
}
export interface PickerShowSubData {
dataId: number,
keyValue: string,
showValue: ResourceStr
}
export interface contact {
photoFirstName: string,
portraitPath: string,
displayName: string,
detailInfo: string,
contactId: ContactVo,
hasPhoneNumber: string,
portraitColor: Resource,
}
export interface ContactPickerListItem {
contactId: number,
displayName: string,
pickerShowSubData: PickerShowSubData,
isFavorite: boolean,
headChar: string,
nameSuffix: string,
namePrefix: string,
showIndex?: boolean,
showDivifer?: boolean,
favoriteOrder: number,
isFirst: boolean,
highLight?: number[],
contact: ContactVo,
index: number
}
export interface ContactPickerParam {
isSaveExistContact: boolean,
isDisplayByName: boolean,
phoneNumberShow: string,
}
export class ContactFormModel {
public contactId?: number = -1;
public displayName: string | Resource = ''; // 没名字,默认为电话号码
public photoFirstName: string = '';
public company: string = '';
public position: string = '';
public portraitColor: string = MorandiColor.Color[0];
public detailsBgColor: string = MorandiColor.detailColor[0];
public favorite: number = 0;
public phones: ContackPhoneSubInfoModel[] = [];
public emails: BaseContackSubInfoModel[] = [];
public houses: BaseContackSubInfoModel[] = [];
public nickname: BaseContackSubInfoModel[] = [];
public events: BaseContackSubInfoModel[] = [];
public relationships: BaseContackSubInfoModel[] = [];
public remarks: BaseContackSubInfoModel[] = [];
public websites: BaseContackSubInfoModel[] = [];
public aims: BaseContackSubInfoModel[] = [];
public numRecords: BaseContackSubInfoModel[] = [];
public phoneticName: BaseContackSubInfoModel[] = [];
public personalRingtone: string = '';
public personalRingtonePath: string = '';
public personalNotificationRingtone: string = '';
}
export class BaseContackSubInfoModel {
public id?: string = '';
public data: string = '';
public type?: string = '';
public labelName?: Resource | string = '';
public dataType?: number = -1;
public calendarEventId?: string = '';
public contactDataId?: number = -1;
}
export class ContackPhoneSubInfoModel extends BaseContackSubInfoModel {
public num?: string;
public phoneAddress?: string | Resource;
public primary?: boolean;
public dataId?: number;
public formatNum?: string;
}
export class FavoriteFormType {
public favorite: number = -1;
}
export class TargetPageClass {
public url: string;
public pageIndex: number;
public params: paramsInterface;
constructor(urlName: string, pageIndex: number, params: paramsInterface) {
this.url = urlName;
this.pageIndex = pageIndex;
this.params = params;
}
}
export class SendMessageParams {
public contactName: string;
public telephone: string;
public telephoneFormat: string;
public contactId?: number;
constructor(number: string, formatNum: string, name?: string, id?: number) {
this.telephone = number;
this.telephoneFormat = formatNum;
this.contactName = name as string;
this.contactId = id;
}
}
@@ -0,0 +1,27 @@
/**
Copyright (c) 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
export enum EnterSingleSelectedMode {
Normal,
ContactSpeedDial,
SpeedDial,
VoiceMail
}
export enum VibrationEffect {
Light = 'haptic.slide.light',
Heavy = 'haptic.long_press.heavy',
Threshold = 'haptic.threshold',
DeleteLongPress = 'haptic.delete_long_press',
DeleteLongPressDouble = 'haptic.common.delete_long_press',
LongPressLight = 'haptic.long_press_light',
}
@@ -0,0 +1,15 @@
/**
Copyright (c) 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
export default interface LooseObject {
[key: string]: any
}
+413
View File
@@ -0,0 +1,413 @@
import MergedCallLog from '../../../../../../feature/call/src/main/ets/entity/MergedCallLog';
import { DataItemType } from '../../../../../../feature/contact';
import { ContactVo } from '../bean/ContactVo';
import common from '@ohos.app.ability.common';
import { FavoriteBean } from '../bean/FavoriteBean';
import { RichContactInfo } from '../bean/RichContactInfo';
import { MergeRule } from '../../../../../../feature/call/src/main/ets/CallLogSetting';
import { ContackPhoneSubInfoModel } from './ContactParams';
import { EnterSingleSelectedMode } from './EnumUtil';
import { AssociatedPersonBean } from '../bean/AssociatedPersonBean';
import contact from '@ohos.contact';
import { CallLogTemp } from '../../../../../../feature/call/src/main/ets/entity/CallLogTemp';
import { RingtoneInfo } from '../ringTone/toneTypes';
export interface CallLogInterface {
showDivifer: boolean,
index: number,
calllog: MergedCallLog
}
export interface SetPrimaryParam {
contactId: string,
dataType: DataItemType,
dataId?: number,
primary: boolean
}
export interface PhoneNumberInterface {
// 对应contactdata表id
dataId: number;
// 对应detail_info
phoneNumber: string,
labelId: string,
numType: string,
labelName: Resource | string |undefined
checked: boolean,
startPhone: string,
middlePhone: string,
endPhone: string,
primary?: boolean,
}
export interface ContactInterface {
i: number,
item: T
}
export interface BatchSelectContact {
showIndex: boolean,
showDivifer: boolean,
contact: ContactVo,
index: number,
single?: boolean,
}
export interface ContactStrInterface {
index: number,
data: string,
}
export interface SingleSelectContact {
editContact: number,
contactId: number,
callId: string,
phones: ContackPhoneSubInfoModel[],
phoneNumberShow: string,
sourceHasParam?: boolean,
//是否展开更多
updataShow?: boolean,
disPlayName?: string,
phoneNumbers?: Record<string, string>[],
fromSpeedDial?: EnterSingleSelectedMode,
nameRawContactId?: number,
displayNameHighlight?: boolean,
//关联人
relationships: AssociatedPersonBean[],
newContactData?: contact.Contact,
// 铃声
ringtoneInfo?: RingtoneInfo,
}
export interface AccountantParams extends SingleSelectContact {
isEditMyCard?: boolean
isCreateMyCard?: boolean
avtarDeletedCallBack?: () => void
}
export interface TableDataInterface {
callLog: CallLogDetailInterface
}
export interface CallLogDetailInterface {
id: string,
phoneNumber: string,
displayName: string,
callDirection: string,
isRead: string,
ringDuration: string,
endTime: string,
}
export interface RequestParam {
actionData: T,
context: common.UIAbilityContext
}
export interface DisplayNameParam {
displayName: string[],
usuallyPhone: string[],
context: common.UIAbilityContext
}
export interface ContactDetailParam {
sourceHasId: boolean,
contactId: string
}
export interface SelectContactParam {
addFavorite: number,
selectType: number,
}
export interface EditFavoriteParam {
favoriteList: FavoriteBean[],
defaultSelectId?: string,
}
export interface FavoriteListParam {
context: common.UIAbilityContext,
favoriteList: string,
favorite: number,
favoriteOrder?: number,
}
export interface DeleteFavoriteParam {
context: common.UIAbilityContext,
favoriteList: string[],
}
export interface UsuallyListParam {
context: common.UIAbilityContext,
usuallyList: string
}
export class EmptyParam {
}
export interface ContactIdParam {
context: common.UIAbilityContext,
contactId: string,
}
export interface SearchContactParam {
value: string,
loopRequest: boolean,
startIndex: number,
limitNumber: number,
}
export class ContactReturnObj {
public data?: RichContactInfo
}
export class ContactReturnArray {
public data?: RichContactInfo[]
}
export interface SpeedDialItem {
number?: number,
contactName?: string,
contactTelephone: string,
portraitColor?: ResourceStr,
nameSuffix?: string,
namePrefix?: string,
portraitPath?: string,
contactId?: string
}
export interface VoiceMailItem {
voiceMailItemName: ResourceStr;
voiceMailItemValue: string;
placeholder: ResourceStr
}
export interface PageLimit {
page?: number,
limit?: number
}
export interface GetAllCallActionData extends PageLimit {
favoriteForm: string
mergeRule: MergeRule
isNeedQueryContact: boolean
}
export interface ReqData {
actionData: T,
}
export interface AllCallsGetActionData extends PageLimit {
mergeRule?: MergeRule
favoriteForm?: string
isNeedQueryContact?: boolean
// 是否使用静默访问方式查询
isProxyQuery?: boolean
}
export interface FindByNumberActionData extends PageLimit {
context?: common.UIAbilityContext,
numbers: string[],
contactId?: number,
}
export interface FindPhotoByIdActionData extends PageLimit {
context?: common.UIAbilityContext,
}
export interface CallHistorySearchGetActionData {
teleNumber: string
nameArray: Array
}
export interface paramsInterface {
mainTabsIndex?: number,
contactId?: Object,
sourceHasId?: boolean,
phoneNumberShow?: Object,
fromSmsList?: boolean,
sourceHasPhone?: boolean,
teleNumber?: Object,
disPlayName?: Object,
phoneNumbers?: Array<Record<string, string>>,
number?: Object,
type?: string,
selectType?: number,
contactCount?: Object,
isLimit?: Object,
sourceHasParam?: boolean,
isNotShowTab?: boolean,
pageFlag?: string,
addFavorite?: number,
isCardEntry?: boolean,
editContact?: number,
newContactData?: contact.Contact,
isFormCard?: boolean,
isCardSharing?: boolean,
isSaveExistContact?: boolean,
isDisplayByName?: boolean,
isNoMissFormCard?: boolean
}
export interface GetLunarDateRe {
year: number
month: number
day: number,
isLeapMonth: boolean
}
export interface TargetPageInter {
url?: string,
pageIndex?: number,
params?: Record<string, string>
}
export interface GroupParams {
id?: number,
groupName: string,
}
export interface SelectContactParams {
addFavorite?: number
contactCount?: number
isLimit?: boolean
pageTag?: string
groupId?: number
isNotShowTab?: boolean
isCardEntry?: boolean
}
export interface ScrollerOffset {
xOffset: number;
yOffset: number;
}
export interface ContactBlobSource {
contactId: string,
blobSource: number,
rawContactId: string,
detailInfo: string,
blobData?: Uint8Array | undefined,
}
export interface RecorderLog {
id: number,
dateAdded: string,
filePath: string,
displayName: string,
phoneNumber?: string,
}
export interface dialogDataStruct {
objectUse: string
confirm: (value?: string) => void
}
export class RepeatContact {
public contactId: string = ''
public name: string = ''
public phoneTags: string[] = []
constructor() {
this.resetRepeatContact();
}
getUniqueKey() {
let uniqueKey = this.name + '-' + this.phoneTags.sort().join('-');
return uniqueKey;
}
initFromRepeatContact(repeatContact: RepeatContact) {
this.contactId = repeatContact.contactId;
this.name = repeatContact.name;
this.phoneTags = repeatContact.phoneTags;
}
resetRepeatContact() {
this.contactId = '';
this.name = '';
this.phoneTags = [];
}
}
export interface CustomizedParams {
PNAMEID?: string,
PVERSIONID?: string,
ENC?: number,
ISNAME?: number,
ISUNIT?: number,
ISPHONE?: number,
ISEMAIL?: number,
ISMESSAGE?: number,
ISADDRESS?: number,
ISREMARKS?: number,
ISNICKNAME?: number,
ISWEBSITE?: number,
ISBIRTHDAYDATE?: number,
ISASSOCIATED?: number,
FLAG?: number,
ACTION?: number,
ISPOP?: number,
ISSAVE?: number,
ISDELETE?: number,
LEVELONE?: number,
LEVELTWO?: number,
ISCANCEL?: number,
ITEM?: number,
ISSELECT?: number,
ISCREATE?: number,
ISADD?: number,
ISDRAG?: number,
ISREMOVE?: number,
ISFAVORITE?: number,
ISCLICK?: number,
ISDEFAULT?: number,
ISOPEN?: number,
ISKNOW?: number,
ISMERGE?: number,
NUM?: number,
ISRESULT?: number,
RESULT?: number,
SLOT?: number,
TYPE?: string,
ISMULTISIMCARD?: number,
ISSHOW?: number,
ISSET?: number,
ISIUPUT?: number,
ISOK?: number,
SETNUM?: number,
HAS_DEFAULT_SIM_CARD?: number,
EDIT_ACTIONS?: number,
ISEXPORT?: number,
REGISTERED_VOLTE_CARD?: number,
BLOCKED_STATUS?: number,
OPTION?: number,
CONFIRM?: number,
RECOVER?: number,
FAULT_INFO?: string,
CLEAR?: number,
OPERATE?: number,
IMPORT?: number,
MARKTYPE?: number,
INDEX?: number,
DIRECTION?: number,
MARKSOURCE?: string
}
export interface DialerSearchResultType {
resultList: CallLogTemp[],
contactsOffset: number,
teleOffset: number,
contactsResultOffset: number,
contactNameKeySet: string[],
searchPhoneNumberSet: string[]
}
export enum CachedContactsPixelMapType {
CONTACT_LIST = 0,
CONTACT_SEARCH_LIST = 1,
}
@@ -18,12 +18,13 @@ import ContactListPresenter from '../../presenter/contact/ContactListPresenter';
import { HiLog, ArrayUtil } from '../../../../../../common';
import emitter from '@ohos.events.emitter';
import { StringUtil } from '../../../../../../common/src/main/ets/util/StringUtil';
import Constants from '../../../../../../common/src/main/ets/Constants';
import Constants from 'common/src/main/ets/Constants';
import { ContactSearch } from './search/ContactSearch';
import { AlphabetIndexerPage } from './alphabetindex/AlphabetIndexerPage';
import AlphabetIndexerPresenter from '../../presenter/contact/alphabetindex/AlphabetIndexerPresenter';
import ContactListShowInfo from '../../model/bean/ContactListShowInfo';
const TAG = 'ContactList ';
const TAG = 'ContactList ';
const EMITTER_SEARCH_ID: number = 105;
let storage = LocalStorage.GetShared();
@@ -53,12 +54,14 @@ export default struct ContactListPage {
this.refresh()
})
this.refresh();
let innerEventSearch = {
let innerEventSearch:emitter.InnerEvent = {
eventId: EMITTER_SEARCH_ID,
priority: emitter.EventPriority.HIGH
};
emitter.on(innerEventSearch, (data) => {
this.mContactPresenter.isSearchPage = data.data['isSearchPage'];
if(data.data !== undefined){
this.mContactPresenter.isSearchPage = data.data['isSearchPage'];
}
})
}
@@ -219,7 +222,7 @@ struct ContactContent {
GridRow({ columns: { sm: 4, md: 8, lg: 12 }, gutter: { x: 12, y: 0 } }) {
GridCol({ span: { sm: 4, md: 6, lg: 8 }, offset: { sm: 0, md: 1, lg: 2 } }) {
List({ space: 0, initialIndex: 0, scroller: this.scroller }) {
LazyForEach(this.presenter.contactListDataSource, (item, index: number) => {
LazyForEach(this.presenter.contactListDataSource, (item:ContactListShowInfo, index: number) => {
ListItem() {
Stack({ alignContent: Alignment.BottomEnd }) {
Column() {
@@ -254,7 +257,7 @@ struct ContactContent {
}
}
}
}, (item) => JSON.stringify(item))
}, (item:ContactListShowInfo) => JSON.stringify(item))
}
.width('100%')
.height('100%')
@@ -276,9 +279,9 @@ struct ContactContent {
AlphabetIndexerPage({scroller: this.scroller, presenter: $alphabetIndexPresenter, selected: this.alphabetSelected,
isClicked: $isAlphabetClicked, drag: $dragList})
.margin({top: '30%', bottom: '10%'})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
@@ -16,10 +16,10 @@
import router from '@ohos.router';
import IndexPresenter from '../../../presenter/IndexPresenter';
import { ArrayUtil } from '../../../../../../../common/src/main/ets/util/ArrayUtil';
import { ObjectUtil } from '../../../../../../../common/src/main/ets/util/ObjectUtil';
import { ObjectUtil } from 'common/src/main/ets/util/ObjectUtil';
import { StringUtil } from '../../../../../../../common/src/main/ets/util/StringUtil';
import EnvironmentProp from '../../../feature/EnvironmentProp';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { PhoneNumBean } from '../../../model/bean/PhoneNumBean';
import AccountantsPresenter from '../../../presenter/contact/accountants/AccountantsPresenter';
import DeleteDialogEx from '../../dialog/DeleteDialogEx';
@@ -28,8 +28,10 @@ import { ItemList } from '../../../component/contact/accountants/ItemList'
import { ItemEvent } from '../../../component/contact/accountants/ItemEvent'
import { AddItem } from '../../../component/contact/accountants/AddItem'
import { ImageItemLeft } from '../../../component/contact/accountants/ImageItemLeft'
import { AccountantParams, ContactInterface } from '../../../model';
import DetailPresenter from '../../../presenter/contact/detail/DetailPresenter';
const TAG = 'AddContact ';
const TAG = 'AddContact ';
let storage = LocalStorage.GetShared();
/**
@@ -90,19 +92,19 @@ struct Accountants {
HiLog.i(TAG, 'Click the callback in the blank area');
}
parseParams(obj) {
parseParams(obj:AccountantParams) {
if (!ObjectUtil.isEmpty(obj)) {
if (obj.hasOwnProperty('updataShow')) {
// 判断新建或者编辑
if (obj.updataShow !== undefined) {
this.updataShow = obj.updataShow;
}
if (obj.hasOwnProperty('phoneNumbers') && (!ArrayUtil.isEmpty(obj.phoneNumbers))
&& this.updataShow === false) {
if (this.updataShow === false && obj.phoneNumbers != undefined) {
let phoTemp = [new PhoneNumBean('1', obj.phoneNumbers[0].phoneNumber, '1', '', '')];
this.mPresenter.contactInfoAfter.setPhones(phoTemp);
this.mPresenter.addState = true;
}
if (obj.hasOwnProperty('disPlayName') && (!StringUtil.isEmpty(obj.disPlayName))
&& this.updataShow === false) {
if ((!StringUtil.isEmpty(obj.disPlayName))
&& this.updataShow === false) {
this.mPresenter.contactInfoAfter.setDisplayName(obj.disPlayName);
this.mPresenter.addState = true;
}
@@ -113,8 +115,8 @@ struct Accountants {
HiLog.i(TAG, 'the Page aboutToAppear Begin !!')
AppStorage.SetOrCreate('isAccountantsPag', true);
this.mPresenter.init(this.refreshPresenter);
let obj: any = router.getParams();
let params = AppStorage.Get('params');
let obj: AccountantParams = router.getParams() as AccountantParams;
let params = AppStorage.Get('params') as AccountantParams;
if (!ObjectUtil.isEmpty(obj)) {
this.parseParams(obj)
} else if (!ObjectUtil.isEmpty(params)) {
@@ -136,7 +138,6 @@ struct Accountants {
aboutToDisappear() {
HiLog.i(TAG, 'the Page aboutToDisappear Begin !!');
this.dialogController = null;
this.mPresenter.showMore = false;
}
@@ -385,15 +386,15 @@ struct Accountants {
Column() {
ForEach(this.updataShow ? this.mPresenter.getPhones
: this.mPresenter.getArray(this.mPresenter.contactInfoBefore.phones)
, (item) => {
: this.mPresenter.getArray(this.mPresenter.contactInfoBefore.phones)
, (item:ContactInterface<PhoneNumBean>) => {
ItemList({
mPresent: $mPresenter,
index: item?.i,
typeName: 'phone',
placeholder: $r('app.string.phone_number')
})
}, item => item?.i.toString())
}, (item:Record<string, string>) => item?.i.toString())
AddItem({ mPresent: $mPresenter,
labelName: $r('app.string.add_more'),
@@ -410,15 +411,15 @@ struct Accountants {
Column() {
ForEach(this.updataShow ? this.mPresenter.getEmails
: this.mPresenter.getArray(this.mPresenter.contactInfoBefore.emails)
, (item) => {
: this.mPresenter.getArray(this.mPresenter.contactInfoBefore.emails)
, (item:ContactInterface<PhoneNumBean>) => {
ItemList({
mPresent: $mPresenter,
index: item?.i,
typeName: 'email',
placeholder: $r('app.string.email')
})
}, item => item?.i.toString())
}, (item:ContactInterface<PhoneNumBean>) => item?.i.toString())
AddItem({ mPresent: $mPresenter,
labelName: $r('app.string.add_more'),
@@ -500,14 +501,14 @@ struct Accountants {
Column() {
ForEach(this.mPresenter.getArray(this.mPresenter.contactInfoBefore.aims)
, (item) => {
, (item:ContactInterface<PhoneNumBean>) => {
ItemList({
mPresent: $mPresenter,
index: item?.i,
typeName: 'AIM',
placeholder: $r('app.string.instant_messaging')
})
}, item => item?.i.toString())
}, (item:ContactInterface<PhoneNumBean>) => item?.i.toString())
AddItem({ mPresent: $mPresenter,
labelName: $r('app.string.add_more'),
@@ -524,14 +525,14 @@ struct Accountants {
Column() {
ForEach(this.mPresenter.getArray(this.mPresenter.contactInfoBefore.houses)
, (item) => {
, (item:ContactInterface<PhoneNumBean>) => {
ItemList({
mPresent: $mPresenter,
index: item?.i,
typeName: 'house',
placeholder: $r('app.string.address_add')
})
}, item => item?.i.toString())
}, (item:ContactInterface<PhoneNumBean>) => item?.i.toString())
AddItem({ mPresent: $mPresenter,
labelName: $r('app.string.add_more'),
@@ -631,7 +632,7 @@ struct Accountants {
Column() {
ForEach(this.mPresenter.getArray(this.mPresenter.contactInfoBefore.events)
, (item) => {
, (item:ContactInterface<PhoneNumBean>) => {
ItemEvent({
mPresent: $mPresenter,
controller: this.dialogController,
@@ -640,7 +641,7 @@ struct Accountants {
eventType: $eventType,
typeName: 'events'
});
}, item => item?.i.toString())
}, (item:ContactInterface<PhoneNumBean>) => item?.i.toString())
AddItem({ mPresent: $mPresenter,
labelName: $r('app.string.add_more'),
@@ -657,14 +658,14 @@ struct Accountants {
Column() {
ForEach(this.mPresenter.getArray(this.mPresenter.contactInfoBefore.relationships)
, (item) => {
, (item:ContactInterface<PhoneNumBean>) => {
ItemList({
mPresent: $mPresenter,
index: item?.i,
typeName: 'relationships',
placeholder: $r('app.string.relation')
})
}, item => item?.i.toString())
}, (item:ContactInterface<PhoneNumBean>) => item?.i.toString())
AddItem({ mPresent: $mPresenter,
labelName: $r('app.string.add_more'),
@@ -711,9 +712,9 @@ struct Accountants {
.height('100%')
.flexShrink(1)
}
.onTouch(() => {
this.mPresenter.hideKeyboard();
})
.onTouch(() => {
this.mPresenter.hideKeyboard();
})
.padding({ left: 12, right: 12 })
.width('100%')
.height('100%')
@@ -17,7 +17,7 @@ import AlphabetIndexerPresenter from '../../../presenter/contact/alphabetindex/A
@Component
export struct AlphabetIndexerPage {
scroller: Scroller;
scroller: Scroller = new Scroller();
@Link presenter: AlphabetIndexerPresenter;
private selectedAlphabetIndex: number = 0;
private popDataSource: string[] = [];
@@ -14,7 +14,7 @@
*/
import BatchSelectContactsPresenter from '../../../presenter/contact/batchselectcontacts/BatchSelectContactsPresenter';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ArrayUtil } from '../../../../../../../common/src/main/ets/util/ArrayUtil';
import BatchSelectRecentItemView from '../../../component/contact/batchselectcontacts/BatchSelectRecentItemView';
import BatchSelectContactItemView from '../../../component/contact/batchselectcontacts/BatchSelectContactItemView';
@@ -22,6 +22,9 @@ import BatchTabGuide from '../../../component/contact/batchselectcontacts/BatchT
import router from '@ohos.router';
import AlphabetIndexerPresenter from '../../../presenter/contact/alphabetindex/AlphabetIndexerPresenter';
import { AlphabetIndexerPage } from '../alphabetindex/AlphabetIndexerPage';
import { ContactVo } from '../../../model/bean/ContactVo';
import { BatchSelectContact } from '../../../model';
import DetailPresenter from '../../../presenter/contact/detail/DetailPresenter';
const TAG = 'BatchSelectContactsPage ';
@@ -38,7 +41,7 @@ export default struct BatchSelectContactsPage {
aboutToAppear() {
HiLog.i(TAG, 'aboutToAppear')
let obj: any = router.getParams();
let obj: DetailPresenter = router.getParams() as DetailPresenter;
this.mPresenter.addFavorite = obj?.addFavorite;
this.mPresenter.aboutToAppear()
}
@@ -205,13 +208,13 @@ struct RecentList {
build() {
Column() {
List({ space: 0, initialIndex: 0 }) {
LazyForEach(this.presenter.recentSource, (item, index: number) => {
LazyForEach(this.presenter.recentSource, (item :BatchSelectContact, index: number) => {
ListItem() {
Stack({ alignContent: Alignment.BottomEnd }) {
BatchSelectRecentItemView({
item: item.calllog,
index: item.index,
onRecentItemClicked: (index) => this.presenter.onRecentItemClicked(index)
onRecentItemClicked: (index: number): void => this.presenter.onRecentItemClicked(index)
})
if (item.showDivifer) {
@@ -221,7 +224,7 @@ struct RecentList {
}
}
}
}, (item) => JSON.stringify(item))
}, (item:BatchSelectContact) => JSON.stringify(item))
}
.width('100%')
.listDirection(Axis.Vertical)
@@ -248,7 +251,7 @@ struct ContactsList {
Column() {
Stack({ alignContent: Alignment.TopEnd }) {
List({ initialIndex: this.presenter.initialIndex, scroller: this.scroller }) {
LazyForEach(this.presenter.contactsSource, (item, index) => {
LazyForEach(this.presenter.contactsSource, (item:BatchSelectContact) => {
ListItem() {
Stack({ alignContent: Alignment.BottomEnd }) {
@@ -271,7 +274,8 @@ struct ContactsList {
BatchSelectContactItemView({
item: item.contact,
index: item.index,
onContactItemClicked: (index, indexChild) => this.presenter.onContactItemClicked(index, indexChild),
onContactItemClicked: (index:number, indexChild:number): void => this.presenter.onContactItemClicked(index,
indexChild),
showIndex: item.showIndex,
showDivifer: item.showDivifer
})
@@ -284,7 +288,7 @@ struct ContactsList {
}
}
}
}, (item) => JSON.stringify(item))
}, (item:BatchSelectContact) => JSON.stringify(item))
}
.width('100%')
.listDirection(Axis.Vertical)
@@ -1,28 +1,35 @@
/**
* Copyright (c) 2022 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Copyright (c) 2022 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import router from '@ohos.router';
import BatchSelectContactsPresenter from '../../../presenter/contact/batchselectcontacts/BatchSelectContactsPresenter';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ArrayUtil } from '../../../../../../../common/src/main/ets/util/ArrayUtil';
import BatchSelectContactItemView from '../../../component/contact/batchselectcontacts/BatchSelectContactItemView';
import { AlphabetIndexerPage } from '../alphabetindex/AlphabetIndexerPage';
import AlphabetIndexerPresenter from '../../../presenter/contact/alphabetindex/AlphabetIndexerPresenter';
import { ContactPickerListItem } from '../../../model/type/ContactParams';
const TAG = 'BatchSelectContactsPage ';
interface RouteParams {
editContact: number
contactId: number
callId: string
phones: string
phoneNumberShow: string
}
/**
* Selecting a contact list by SMS
*/
@@ -32,10 +39,9 @@ export default struct SingleSelectContactPage {
@State mPresenter: BatchSelectContactsPresenter = BatchSelectContactsPresenter.getInstance();
@State currentIndex: number = 0;
@State curBp: string = 'sm';
aboutToAppear() {
HiLog.i(TAG, 'aboutToAppear')
let obj: any = router.getParams();
let obj: RouteParams = router.getParams() as RouteParams;
this.mPresenter.editContact = obj?.editContact;
this.mPresenter.contactId = obj?.contactId;
this.mPresenter.callId = obj?.callId;
@@ -67,13 +73,13 @@ export default struct SingleSelectContactPage {
build() {
Column() {
if (ArrayUtil.isEmpty(this.mPresenter.contactsList)) {
NoContactsEmptyView()
} else {
ContactsList({
presenter: $mPresenter
})
}
if (ArrayUtil.isEmpty(this.mPresenter.contactsList)) {
NoContactsEmptyView()
} else {
ContactsList({
presenter: $mPresenter
})
}
}
.padding({ left: 12, right: 12 })
.width('100%')
@@ -123,27 +129,26 @@ struct ContactsList {
build() {
Column() {
GridRow({ columns: { sm: 4, md: 8, lg: 12 }, gutter: { x: { sm: 12, md: 12, lg: 24 }, y: 0 } }) {
GridCol({ span: { sm: 4, md: 6, lg: 8 }, offset: { sm: 0, md: 1, lg: 2 } }) {
TitleGuide()
}
GridRow({ columns: { sm: 4, md: 8, lg: 12 }, gutter: { x: { sm: 12, md: 12, lg: 24 }, y: 0 } }) {
GridCol({ span: { sm: 4, md: 6, lg: 8 }, offset: { sm: 0, md: 1, lg: 2 } }) {
TitleGuide()
}
.height('100%')
.onBreakpointChange((breakpoint: string) => {
this.curBp = breakpoint
})
}
.onBreakpointChange((breakpoint: string) => {
this.curBp = breakpoint
})
Stack({ alignContent: Alignment.TopEnd }) {
GridRow({columns: {sm: 4, md: 8, lg: 12}, gutter: {x: 12, y: 0}}) {
GridRow({ columns: { sm: 4, md: 8, lg: 12 }, gutter: { x: 12, y: 0 } }) {
GridCol({ span: { sm: 4, md: 6, lg: 8 }, offset: { sm: 0, md: 1, lg: 2 } }) {
List({ initialIndex: this.presenter.initialIndex, scroller: this.scroller }) {
LazyForEach(this.presenter.contactsSource, (item, index) => {
LazyForEach(this.presenter.contactsSource, (item: ContactPickerListItem, index: number) => {
ListItem() {
Stack({ alignContent: Alignment.BottomEnd }) {
Column() {
if (item.showIndex) {
Column() {
Text(item.contact.namePrefix)
Text(item.namePrefix)
.fontColor($r('sys.color.ohos_fa_text_secondary'))
.fontSize($r('sys.float.ohos_id_text_size_sub_title3'))
.fontWeight(FontWeight.Medium)
@@ -157,15 +162,16 @@ struct ContactsList {
}
BatchSelectContactItemView({
single: item.single = true,
single: true,
item: item.contact,
index: item.index,
onSingleContactItemClick: (num, name) => this.presenter.onSingleContactItemClick(num, name, item.contact),
onSingleContactItemClick: (num: number,
name: string): void => this.presenter.onSingleContactItemClick(num, name, item.contact),
showIndex: item.showIndex,
})
}
}
}, (item) => JSON.stringify(item))
}, (item: ContactPickerListItem) => JSON.stringify(item))
}
.scrollBar(BarState.Off)
.width('100%')
@@ -186,8 +192,14 @@ struct ContactsList {
}
}
.height('93%')
AlphabetIndexerPage({scroller: this.scroller, presenter: $alphabetIndexPresenter, selected: this.alphabetSelected,
isClicked: $isAlphabetClicked, drag: $dragList})
AlphabetIndexerPage({
scroller: this.scroller,
presenter: $alphabetIndexPresenter,
selected: this.alphabetSelected,
isClicked: $isAlphabetClicked,
drag: $dragList
})
.margin({ top: '10%', bottom: '10%' })
}
.height('100%')
@@ -14,7 +14,7 @@
*/
import router from '@ohos.router';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { StringUtil } from '../../../../../../../common/src/main/ets/util/StringUtil';
import IndexPresenter from '../../../presenter/IndexPresenter';
import DetailPresenter from '../../../presenter/contact/detail/DetailPresenter';
@@ -23,6 +23,20 @@ import CallLogListItem from '../../../component/contactdetail/DetailCalllog';
import DetailInfoListView from '../../../component/contactdetail/DetailInfoListView';
import EnvironmentProp from '../../../feature/EnvironmentProp';
import { SelectSimIdDialog, SelectDialogBuilder } from '../../../component/mutisim/SelectSimIdDialog';
import { CallLogBean } from '../../../model/bean/CallLogBean';
class ParamsObj {
public sourceHasId: boolean = false;
public sourceHasPhone: number = -1;
}
class LooseObject {
public showTitle: string = '';
public callLog: CallLogBean = new CallLogBean('', '', '', '');
}
class CallLog {
}
const TAG = 'ContactDetail';
let storage = LocalStorage.GetShared()
@@ -35,15 +49,7 @@ let storage = LocalStorage.GetShared()
struct ContactDetail {
@State mPresenter: DetailPresenter = DetailPresenter.getInstance();
@LocalStorageProp('breakpoint') curBp: string = 'sm';
@StorageLink('params') params: { [key: string]: any } = {};
@State private mMoreMenu: Array<{
value: string,
action: () => void
}> = [{
value: '',
action: () => {
}
}];
@StorageLink('params') params: DetailPresenter = DetailPresenter.getInstance();
@State hasFavorited: boolean = false;
@State isShow: number = 0;
@State builder: SelectDialogBuilder = {
@@ -69,7 +75,7 @@ struct ContactDetail {
setTimeout(() => {
this.isShow++;
}, 100);
let obj: any = router.getParams();
let obj: DetailPresenter = router.getParams() as DetailPresenter;
if (obj != undefined) {
this.mPresenter.sourceHasId = obj.sourceHasId;
this.mPresenter.contactId = obj.contactId;
@@ -82,21 +88,10 @@ struct ContactDetail {
this.mPresenter.phoneNumberShow = this.params.phoneNumberShow;
}
this.mPresenter.aboutToAppear();
this.mMoreMenu = this.mPresenter.getSettingsMenus();
let that = this;
this.builder.controller = {
open() {
that.mSelectSlotIdDialog.open();
},
close() {
that.mSelectSlotIdDialog.close();
}
}
}
aboutToDisappear() {
this.mPresenter.aboutToDisappear();
this.mSelectSlotIdDialog = null;
}
onPageShow() {
@@ -108,7 +103,8 @@ struct ContactDetail {
}
}
@Builder MenuBuilder() {
@Builder
MenuBuilder() {
Column() {
this.MenuView($r('app.string.delete_contact'), MenuType.deleteContact)
}
@@ -117,7 +113,8 @@ struct ContactDetail {
.height($r('app.float.id_item_height_mid'))
}
@Builder MenuView(menuName, itemType) {
@Builder
MenuView(menuName: Resource, itemType: MenuType) {
Row() {
Text(menuName)
.fontSize($r('app.float.id_corner_radius_card_mid'))
@@ -141,7 +138,7 @@ struct ContactDetail {
build() {
Stack({ alignContent: Alignment.Bottom }) {
TopBar({ mPresenter: $mPresenter, moreMenu: $mMoreMenu });
TopBar({ mPresenter: $mPresenter });
GridRow({ columns: { sm: 4, md: 8, lg: 12 }, gutter: { x: { sm: 12, md: 12, lg: 24 }, y: 0 } }) {
GridCol({ span: { sm: 4, md: 8, lg: 8 }, offset: { sm: 0, md: 0, lg: 2 } }) {
@@ -172,7 +169,7 @@ struct ContactDetail {
} else {
this.mPresenter.isFavorited = '0';
}
this.mPresenter.updateFavorite(parseInt(this.mPresenter.isFavorited));
this.mPresenter.updateFavorite(this.mPresenter.isFavorited);
})
.visibility(this.mPresenter.contactId != undefined ? Visibility.Visible : Visibility.None)
.width('33%')
@@ -249,11 +246,11 @@ enum MenuType {
@Component
struct Content {
@Link private mPresenter: { [key: string]: any };
@Link private mPresenter: DetailPresenter;
@Link selectSimBuilder: SelectDialogBuilder;
@LocalStorageProp('breakpoint') curBp: string = 'sm';
@State colunmHeight: string = '60%';
@StorageLink('isRouterBack') @Watch('onBackIndex') isRouterBack: boolean = false;
@StorageLink('isRouterBack') @Watch('onBackIndex') isRouterBack: boolean = false;
onBackIndex() {
if (this.isRouterBack) {
@@ -263,7 +260,8 @@ struct Content {
this.isRouterBack = false;
}
@Builder callLogTitle() {
@Builder
callLogTitle() {
Row() {
Text($r('app.string.dialer_calllog'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
@@ -304,14 +302,13 @@ struct Content {
.height($r('app.float.id_item_height_sm'))
}
toPoint(percent) {
var str = percent.replace('%', '');
str = str / 100;
return str;
toPoint(percent: string) {
let str: string = percent.replace('%', '');
return Number.parseInt(str) / 100;
}
toPercent(point) {
var percent = Number(point * 100).toFixed(4);
toPercent(point: number) {
let percent = Number(point * 100).toFixed(4);
percent += '%';
return percent;
}
@@ -351,7 +348,7 @@ struct Content {
.height(this.curBp === 'lg' ? '267vp' : '260.5vp')
Column() {
Text(this.mPresenter.contactForm.display_name)
Text(this.mPresenter.contactForm.displayName)
.fontSize('24fp')
.fontWeight(FontWeight.Medium)
.margin({ top: '18vp', bottom: '4vp' })
@@ -384,11 +381,12 @@ struct Content {
}
}
.onAreaChange((oldArea: Area, newArea: Area) => {
this.mPresenter.changeTopBarBackgroundColor(newArea.globalPosition.y <= -260)
this.mPresenter.changeTopBarBackgroundColor(newArea.globalPosition.y !== undefined ?
newArea.globalPosition.y <= -260 : false)
})
ListItemGroup() {
LazyForEach(this.mPresenter.detailCallLogDataSource, (item, index) => {
LazyForEach(this.mPresenter.detailCallLogDataSource, (item: LooseObject, index) => {
ListItem() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Start }) {
if (item.showTitle) {
@@ -402,12 +400,13 @@ struct Content {
}
}
.width('100%')
}, item => JSON.stringify(item))
}, (item: LooseObject) => JSON.stringify(item))
}
.backgroundColor(Color.White)
.onAreaChange((oldArea: Area, newArea: Area) => {
var itemHeight = AppStorage.Get('windowHeight') == undefined ? 0 : (Number(newArea.height) - Number(oldArea.height)) / Number(AppStorage.Get('windowHeight'))
var itemPoint = this.toPoint(this.colunmHeight) - itemHeight;
let itemHeight = AppStorage.Get('windowHeight') == undefined ? 0 :
(Number(newArea.height) - Number(oldArea.height)) / Number(AppStorage.Get('windowHeight'))
let itemPoint: number = this.toPoint(this.colunmHeight) - itemHeight;
this.colunmHeight = itemPoint < 0 ? '0%' : this.toPercent(itemPoint)
})
.width('100%')
@@ -430,11 +429,10 @@ struct Content {
@Component
struct TopBar {
@State hasFavorited: boolean = false;
@Link private mPresenter: { [key: string]: any };
@Link private moreMenu: { [key: string]: any };
@Link private mPresenter: DetailPresenter;
@LocalStorageProp('breakpoint') curBp: string = 'sm'
@Builder MenuBuilder() {
@Builder
MenuBuilder() {
Column() {
Text($r('app.string.delete_contact'))
.fontSize($r('app.float.id_corner_radius_card_mid'))
@@ -17,7 +17,8 @@ import { StringUtil } from '../../../../../../../common/';
import emitter from '@ohos.events.emitter';
import BatchSelectContactsPresenter from '../../../presenter/contact/batchselectcontacts/BatchSelectContactsPresenter';
import router from '@ohos.router';
import { ContactPickerListItem } from '../../../model/type/ContactParams';
import LooseObject from '../../../model/type/LooseObject';
const TAG = 'ContactSearch ';
@Component
@@ -31,12 +32,14 @@ export struct ContactSearch {
@State cancelIsTouch: boolean = false;
aboutToAppear() {
let innerEvent = {
let innerEvent: emitter.InnerEvent = {
eventId: this.emitterId,
priority: emitter.EventPriority.HIGH
};
emitter.on(innerEvent, (data) => {
this.contactSearchNumber = data.data['contactSearchList'];
if (data.data !== undefined) {
this.contactSearchNumber = data.data['contactSearchList'];
}
})
}
@@ -134,7 +137,7 @@ export struct ContactSearch {
GridRow({ columns: { sm: 4, md: 8, lg: 12 }, gutter: { x: 12, y: 0 } }) {
GridCol({ span: { sm: 4, md: 6, lg: 8 }, offset: { sm: 0, md: 1, lg: 2 } }) {
List({ space: 0, initialIndex: 0 }) {
LazyForEach(this.presenter.searchContactsSource, (item, index: number) => {
LazyForEach(this.presenter.searchContactsSource, (item: LooseObject, index: number) => {
ListItem() {
Stack({ alignContent: Alignment.BottomEnd }) {
Row() {
@@ -164,7 +167,7 @@ export struct ContactSearch {
Column() {
Row() {
ForEach(item?.contact?.displayName.split(this.presenter.inputKeyword), (itemData1, idx: number) => {
ForEach(item?.contact?.displayName.split(this.presenter.inputKeyword), (itemData1: string, idx: number) => {
Row() {
Text(itemData1.toString())
.fontSize($r('sys.float.ohos_id_text_size_body2'))
@@ -199,7 +202,7 @@ export struct ContactSearch {
Row() {
if (!StringUtil.isEmpty(item?.contact?.detailInfo) && '0' !== item?.contact?.hasPhoneNumber) {
ForEach(item?.contact?.detailInfo?.split(this.presenter.inputKeyword), (itemData, idx: number) => {
ForEach(item?.contact?.detailInfo?.split(this.presenter.inputKeyword), (itemData: string, idx: number) => {
Row() {
Text(itemData.toString())
.fontSize($r('sys.float.ohos_id_text_size_body2'))
@@ -269,7 +272,7 @@ export struct ContactSearch {
} else if (this.type === 2) {
}
})
}, item => JSON.stringify(item))
}, (item: ContactPickerListItem) => JSON.stringify(item))
}
.height('90%')
.width('100%')
@@ -289,7 +292,8 @@ export struct ContactSearch {
.padding({ bottom: $r('app.float.dialer_calllog_item_height') })
.height('100%')
.width('100%')
.backgroundColor(this.type === 1 || this.type === 2 ? $r('sys.color.ohos_id_color_sub_background') : this.type === 0 && this.contactSearchNumber > 0 ? Color.White : '#450a0a0a')
.backgroundColor(this.type === 1 || this.type === 2 ? $r('sys.color.ohos_id_color_sub_background') :
this.type === 0 && this.contactSearchNumber > 0 ? Color.White : '#450a0a0a')
}
}
@@ -14,11 +14,18 @@
*/
import CallRecord from './callRecord/CallRecord'
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { DialerInitialPage } from '../../component/dialer/DialerInitialPage';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import DialerPresenter from '../../presenter/dialer/DialerPresenter';
import EnvironmentProp from '../../feature/EnvironmentProp';
import PreferencesUtil from '../../util/PreferencesUtil';
class CallmenuFn {
public value: string = '';
public action: () => void = ()=>{}
constructor(value:string,action:() => void) {
this.value = value;
this.action = action;
}
}
const TAG = 'DialerTablet'
@@ -90,7 +97,7 @@ struct DialButton {
@Component
struct DialPad {
@Link mPresenter: DialerPresenter;
@Link mPresenter: DialerPresenter;
build() {
Column() {
@@ -204,64 +211,62 @@ export default struct CallTablet {
this.mPresenter.onDestroy();
}
getMenu() {
let tmpPhoneMenu = [];
this.menuRes.forEach(element => {
tmpPhoneMenu.push({});
});
this.callmenu = tmpPhoneMenu;
this.menuRes.forEach((element, i) => {
globalThis.context.resourceManager.getString(element.id, (err, typeName) => {
HiLog.i(TAG, typeName);
this.callmenu[i] = {
value: typeName,
action: () => {
}
};
});
});
}
getMenu() {
let tmpPhoneMenu: CallmenuFn[] = [];
this.menuRes.forEach(element => {
tmpPhoneMenu.push(new CallmenuFn(element.bundleName,() => {
}));
});
this.callmenu = tmpPhoneMenu;
this.menuRes.forEach((element, i) => {
globalThis.context.resourceManager.getString(element.id, (err: Error, typeName: string) => {
HiLog.i(TAG, typeName);
this.callmenu[i] = new CallmenuFn(typeName,() => {
});
});
});
}
build() {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
Column() {
if (this.tele_number.length > 0) {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text(`${this.tele_number}`)
.fontSize(this.mPresenter.tele_num_size)
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.maxLines(1)
}
.width('100%')
.height('112vp')
Column() {
if (this.tele_number.length > 0) {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text(`${this.tele_number}`)
.fontSize(this.mPresenter.tele_num_size)
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.maxLines(1)
}
.width('100%')
.height('112vp')
if (this.tele_number.length >= 3) {
Row() {
Image($r('app.media.ic_public_add'))
.width($r('app.float.id_card_margin_max'))
.height($r('app.float.id_card_margin_max'))
.margin({
left: $r('app.float.id_card_margin_max'),
right: $r('app.float.id_card_margin_xxl')
})
Text($r('app.string.new_contact'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontColor($r('sys.color.ohos_id_color_text_primary'))
}
.width('100%')
.height($r('app.float.id_item_height_large'))
.onClick(() => {
this.mPresenter.jumpToAccountants()
if (this.tele_number.length >= 3) {
Row() {
Image($r('app.media.ic_public_add'))
.width($r('app.float.id_card_margin_max'))
.height($r('app.float.id_card_margin_max'))
.margin({
left: $r('app.float.id_card_margin_max'),
right: $r('app.float.id_card_margin_xxl')
})
Divider()
.color($r('sys.color.ohos_id_color_list_separator'))
.lineCap(LineCapStyle.Square)
.width('100%')
.padding({ left: $r('app.float.id_item_height_max') })
Text($r('app.string.new_contact'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontColor($r('sys.color.ohos_id_color_text_primary'))
}
.width('100%')
.height($r('app.float.id_item_height_large'))
.onClick(() => {
this.mPresenter.jumpToAccountants()
})
Divider()
.color($r('sys.color.ohos_id_color_list_separator'))
.lineCap(LineCapStyle.Square)
.width('100%')
.padding({ left: $r('app.float.id_item_height_max') })
//This component is temporarily shielded because there is no requirement currently.
// Row() {
@@ -26,7 +26,7 @@ import IndexPresenter from '../../../presenter/IndexPresenter';
import { HiLog } from '../../../../../../../common'
import emitter from '@ohos.events.emitter'
import promptAction from '@ohos.promptAction'
import MergedCallLog from '../../../../../../../feature/call/src/main/ets/entity/MergedCallLog';
const TAG = 'AllRecord ';
const EMITTER_SAVE_ID = 103;
@@ -52,20 +52,22 @@ export default struct AllRecord {
aboutToAppear() {
HiLog.i(TAG, 'aboutToAppear,recordType:' + this.recordType)
this.onChanged();
let innerEventContact = {
let innerEventContact:emitter.InnerEvent = {
eventId: EMITTER_SAVE_ID,
priority: emitter.EventPriority.HIGH
};
emitter.on(innerEventContact, (data) => {
let phoneNumber: string = data.data['phoneNumber'];
let callId: string = data.data['callId'];
this.mPresenter.saveCallRecordExistingContact(phoneNumber, callId);
if(data.data !== undefined){
let phoneNumber: string = data.data['phoneNumber'];
let callId: string = data.data['callId'];
this.mPresenter.saveCallRecordExistingContact(phoneNumber, callId);
}
})
}
aboutToDisappear() {
HiLog.i(TAG, 'aboutToDisappear,recordType:' + this.recordType)
emitter.off(EMITTER_SAVE_ID);
emitter.off(EMITTER_SAVE_ID);
}
build() {
@@ -81,19 +83,19 @@ export default struct AllRecord {
@Component
struct RecordView {
@Link private mPresenter: { [key: string]: any }
@Link private mPresenter: CallRecordPresenter;
@LocalStorageProp('breakpoint') curBp: string = 'sm';
recordType: number = 0;
build() {
List({ space: 0, initialIndex: 0 }) {
LazyForEach(this.recordType === 0 ? this.mPresenter.mAllCallRecordListDataSource :
this.mPresenter.mMissCallRecordListDataSource, (item, index: number) => {
this.mPresenter.mMissCallRecordListDataSource, (item:MergedCallLog, index: number) => {
ListItem() {
ContactItem({ mPresenter: $mPresenter, item: item, index: index });
ContactItem({ mPresenter: mPresenter, item: item, index: index });
}
.height($r('app.float.id_item_height_max'))
}, item => JSON.stringify(item))
}, (item:MergedCallLog) => JSON.stringify(item))
}
.divider({
strokeWidth: 0.5,
@@ -145,8 +147,8 @@ enum MenuType {
struct ContactItem {
@State mIndexPresenter: IndexPresenter = IndexPresenter.getInstance();
@Link mPresenter: CallRecordPresenter
@State item: { [key: string]: any } = {};
index: number;
@Prop item: MergedCallLog;
index: number = -1;
@State isEmergencyNum: boolean = false;
@LocalStorageProp('breakpoint') curBp: string = 'sm';
@StorageLink('haveMultiSimCard') haveMultiSimCard: boolean = false;
@@ -171,7 +173,6 @@ struct ContactItem {
});
aboutToDisappear() {
this.deleteDialogController = null;
}
build() {
@@ -336,7 +337,7 @@ struct ContactItem {
.backgroundColor($r('sys.color.ohos_id_color_primary_contrary'))
}
@Builder MenuView(menuName, itemType, displayName) {
@Builder MenuView(menuName:Resource, itemType:MenuType, displayName:string) {
Row() {
Text(menuName)
.fontSize($r('sys.float.ohos_id_text_size_body1'))
@@ -348,7 +349,7 @@ struct ContactItem {
.height($r('app.float.id_item_height_mid'))
.backgroundColor($r('sys.color.ohos_id_color_primary_contrary'))
.visibility(itemType !== MenuType.SaveExistingContacts || itemType === MenuType.SaveExistingContacts &&
'' === displayName ? Visibility.Visible : Visibility.None)
'' === displayName ? Visibility.Visible : Visibility.None)
.onClick(() => {
switch (itemType) {
case MenuType.DeleteCallLogs:
@@ -356,7 +357,7 @@ struct ContactItem {
break;
case MenuType.EditBeforeCall:
DialerPresenter.getInstance().editPhoneNumber(this.item.phoneNumber);
AppStorage.SetOrCreate<boolean>('showDialBtn', true);
AppStorage.SetOrCreate('showDialBtn', true);
break;
case MenuType.sendMessage:
let formatnum = PhoneNumber.fromString(this.item.phoneNumber).format();
@@ -368,13 +369,13 @@ struct ContactItem {
this.mIndexPresenter.getCopy(this.item.phoneNumber);
break;
case MenuType.SaveExistingContacts:
let innerEvent = {
let innerEvent:emitter.InnerEvent = {
eventId: EMITTER_SAVE_ID,
priority: emitter.EventPriority.HIGH
};
emitter.emit(innerEvent, {
data: {
'callId': this.item.id,
'callId': this.item.id,
'phoneNumber': this.item.phoneNumber
}
});
@@ -383,7 +384,7 @@ struct ContactItem {
})
}
@Builder MenuDivider(itemType, displayName) {
@Builder MenuDivider(itemType:MenuType, displayName:string) {
Divider()
.color($r('sys.color.ohos_id_color_list_separator'))
.lineCap(LineCapStyle.Square)
@@ -17,7 +17,7 @@
* call log
*/
import AllRecord from './AllRecord';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import CallRecordPresenter from './../../../presenter/dialer/callRecord/CallRecordPresenter'
import {CallLogTabs} from '../../../component/dialer/CallLogTabs';
@@ -42,37 +42,36 @@ export default struct CallRecord {
this.mPresenter.aboutToDisappear();
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
CallLogTabs({ controller: this.controller, bottomTabIndex: $bottomTabIndex})
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
CallLogTabs({ controller: this.controller, bottomTabIndex: $bottomTabIndex})
Tabs({ barPosition: BarPosition.Start, index: this.bottomTabIndex, controller: this.controller }) {
TabContent() {
AllRecord({ mPresenter: $mPresenter, recordType: 0 })
}.align(Alignment.TopStart)
Tabs({ barPosition: BarPosition.Start, index: this.bottomTabIndex, controller: this.controller }) {
TabContent() {
AllRecord({ mPresenter: $mPresenter, recordType: 0 })
}.align(Alignment.TopStart)
TabContent() {
AllRecord({ mPresenter: $mPresenter, recordType: 1 })
}.align(Alignment.TopStart)
TabContent() {
AllRecord({ mPresenter: $mPresenter, recordType: 1 })
}.align(Alignment.TopStart)
}
.onChange((index: number) => {
this.bottomTabIndex = index
this.mPresenter.setTabIndex(index);
})
.vertical(false)
.barHeight(0)
.barWidth(0)
.barMode(BarMode.Fixed)
.scrollable(false)
.backgroundColor($r('sys.color.ohos_id_color_primary_contrary'))
.animationDuration(0)
.zIndex(1)
}
.width('100%')
.height('100%')
.layoutWeight(1)
.onChange((index: number) => {
this.bottomTabIndex = index
this.mPresenter.setTabIndex(index);
})
.vertical(false)
.barHeight(0)
.barWidth(0)
.barMode(BarMode.Fixed)
.scrollable(false)
.backgroundColor($r('sys.color.ohos_id_color_primary_contrary'))
.animationDuration(0)
.zIndex(1)
}
.width('100%')
.height('100%')
.layoutWeight(1)
.backgroundColor($r('sys.color.ohos_id_color_primary_contrary'))
}
}
@@ -19,12 +19,13 @@
@CustomDialog
export default struct DeleteDialogEx {
controller: CustomDialogController;
cancel: () => void;
confirm: () => void;
title: string | Resource;
cancalText: string | Resource;
confrimText: string | Resource;
cancel: () => void = () => {
};
confirm: () => void = () => {
};
title: string | Resource = '';
cancalText: string | Resource = '';
confrimText: string | Resource = '';
build() {
Flex({
direction: FlexDirection.Column,
@@ -39,7 +39,7 @@ export struct SelectMultiNumDialog {
.height('48vp')
.padding({ left: '16vp', })
List() {
ForEach(this.builder.multiNumCardItems, (item, index) => {
ForEach(this.builder.multiNumCardItems, (item:MultiNumCardItems, index) => {
ListItem() {
Row() {
Image(item.img)
@@ -107,7 +107,7 @@ export struct SelectMultiNumDialog {
}.backgroundColor(Color.White)
}
confirm(item, contactId) {
confirm(item:MultiNumCardItems, contactId:string) {
this.controller.close()
if (this.selectDefault) {
sharedPreferencesUtils.saveToPreferences(contactId + '', item.number);
@@ -123,21 +123,18 @@ export struct SelectMultiNumDialog {
}
class MultiNumCardItems {
number: String;
numType: Resource;
img: Resource;
number: string = '';
numType: Resource|undefined = undefined;
img: Resource|undefined = undefined;
}
interface Controller {
close();
open();
}
export class SelectNumDialogBuilder {
title: string | Resource;
contactId: String
multiNumCardItems: Array<MultiNumCardItems>;
title: string | Resource = '';
contactId: string = '';
multiNumCardItems: Array<MultiNumCardItems> = [];
callback?: (item: MultiNumCardItems) => void;
controller?: Controller;
}
@@ -19,12 +19,13 @@
@CustomDialog
export default struct ShareDialogEx {
controller: CustomDialogController;
cancel: () => void;
title: string | Resource;
itemList: string[] | Resource[];
cancelText: string | Resource;
onItemClick: (item, index) => {};
cancel: () => void = () => {
};
title: string | Resource = '';
itemList: string[] | Resource[] = [];
cancelText: string | Resource = '';
onItemClick: (item:string, index:number) => void = (item:string, index:number) => {
};
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Start }) {
Text(this.title)
@@ -33,7 +34,7 @@ export default struct ShareDialogEx {
.fontSize(24)
List() {
ForEach(this.itemList, (item, index) => {
ForEach(this.itemList, (item:string, index) => {
ListItem() {
Column() {
Text(item).fontSize(20).margin({ top: 5, bottom: 5 })
@@ -45,7 +46,7 @@ export default struct ShareDialogEx {
this.controller.close();
})
}
}, item => item);
}, (item:string) => item);
}
.scrollBar(BarState.Off)
.edgeEffect(EdgeEffect.None)
@@ -14,10 +14,30 @@
*/
import EditFavoriteListPresenter from '../../presenter/favorite/EditFavoriteListPresenter';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { StringUtil } from '../../../../../../common/src/main/ets/util/StringUtil';
import router from '@ohos.router';
import { FavoriteBean } from '../../model/bean/FavoriteBean';
import { FavoriteListBean } from '../../model/bean/FavoriteListBean';
import { SearchContactsBean } from '../../model/bean/SearchContactsBean';
class Extra {
public selectedIndex: number = 0;
}
class Favorite{
public favoriteList: FavoriteBean[] = [];
public isEditSelectList: string[] = [];
public selectNumber: number = 0;
public favoriteNumber: number = 0;
public usuallyNumber: number = 0;
public selectFavoriteBean: FavoriteBean|undefined = undefined;
}
class ExtraParamsObj{
public insertIndex:number = 0;
}
const TAG = 'EditFavoriteList';
@@ -33,7 +53,7 @@ export default struct EditFavoriteList {
aboutToAppear() {
HiLog.i(TAG, 'EditFavoriteList aboutToAppear!');
let obj: any = router.getParams();
let obj: Favorite = router.getParams() as Favorite;
this.mFavoriteListPresenter.favoriteList = obj.favoriteList;
this.mFavoriteListPresenter.isEditSelect = obj.isEditSelectList;
this.selectNumbers = obj.selectNumber;
@@ -86,11 +106,12 @@ struct FavoriteContent {
@State selectNumber: number = this.selectNumbers;
@State selectFavoriteIdList: string[] = [];
@State isEditSelectList: string[] = null != this.presenter.isEditSelect &&
this.presenter.isEditSelect.length > 0 ? this.presenter.isEditSelect : [];
this.presenter.isEditSelect.length > 0 ? this.presenter.isEditSelect : [];
@State favoriteListPresenter: EditFavoriteListPresenter = this.presenter;
@State isSelectAll: boolean = false;
@State isSelectAllStatus: boolean = false;
item: any = {};
item: FavoriteListBean = new FavoriteListBean(0,false,false,new FavoriteBean('',0,'','','','','',false,'',false,0,''),
new SearchContactsBean('','','','','','','','','',0,'','','','','',''));
@State text: string = '';
@State isEditDrag: boolean = false;
@State select: number = 0;
@@ -147,7 +168,7 @@ struct FavoriteContent {
GridRow({ columns: { sm: 4, md: 8, lg: 12 }, gutter: { x: 12, y: 0 } }) {
GridCol({ span: { sm: 4, md: 6, lg: 8 }, offset: { sm: 0, md: 1, lg: 2 } }) {
List({ space: 0, initialIndex: 0 }) {
LazyForEach(this.presenter.favoriteDataSource, (item, index: number) => {
LazyForEach(this.presenter.favoriteDataSource, (item: FavoriteListBean, index: number) => {
ListItem() {
FavoriteListItem({
item: item,
@@ -162,7 +183,7 @@ struct FavoriteContent {
}
.onDragStart((event: DragEvent, extraParams: string) => {
console.log('ListItem onDragStarts, ' + extraParams)
var jsonString = JSON.parse(extraParams)
let jsonString: Extra = JSON.parse(extraParams)
if (jsonString.selectedIndex >= this.favoriteNumber) {
console.log('List onDragStarts , return ')
return;
@@ -172,7 +193,7 @@ struct FavoriteContent {
this.item = item;
return this.pixelMapBuilder();
})
}, (item) => JSON.stringify(item))
}, (item:FavoriteListBean) => JSON.stringify(item))
}
.editMode(true)
.width('100%')
@@ -181,7 +202,7 @@ struct FavoriteContent {
.listDirection(Axis.Vertical)
.edgeEffect(EdgeEffect.Spring)
.onDrop((event: DragEvent, extraParams: string) => {
let jsonString = JSON.parse(extraParams);
let jsonString = JSON.parse(extraParams) as ExtraParamsObj;
if (jsonString.insertIndex >= this.favoriteNumber) {
return;
}
@@ -296,7 +317,7 @@ struct FavoriteContent {
@Component
export struct FavoriteListItem {
@Link presenter: EditFavoriteListPresenter;
@State item: { [key: string]: any } = {};
@Prop item: FavoriteListBean;
@Link isEditSelectList: string[];
@Link selectNumber: number;
@Link isSelectAll: boolean;
@@ -24,7 +24,8 @@ import emitter from '@ohos.events.emitter';
import { Phone } from '../../../../../../feature/contact/src/main/ets/contract/Phone';
import prompt from '@ohos.prompt';
import promptAction from '@ohos.promptAction'
import { FavoriteListBean } from '../../model/bean/FavoriteListBean';
import LooseObject from '../../model/LooseObject ';
const TAG = 'FavoriteList';
@Entry
@@ -38,12 +39,14 @@ export default struct FavoriteList {
aboutToAppear() {
HiLog.i(TAG, 'Favorite aboutToAppear!');
this.mFavoriteListPresenter.aboutToAppear();
let innerEvent = {
let innerEvent: emitter.InnerEvent = {
eventId: this.emitterId,
priority: emitter.EventPriority.HIGH
};
emitter.on(innerEvent, (data) => {
this.favoriteListListLen = data.data['favoriteListListLen'];
if (data.data !== undefined) {
this.favoriteListListLen = data.data['favoriteListListLen'];
}
})
}
@@ -101,11 +104,11 @@ struct FavoriteContent {
GridRow({ columns: { sm: 4, md: 8, lg: 12 }, gutter: { x: 12, y: 0 } }) {
GridCol({ span: { sm: 4, md: 6, lg: 8 }, offset: { sm: 0, md: 1, lg: 2 } }) {
List({ space: 0, initialIndex: 0 }) {
LazyForEach(this.presenter.favoriteDataSource, (item, index: number) => {
LazyForEach(this.presenter.favoriteDataSource, (item: FavoriteListBean, index: number) => {
ListItem() {
FavoriteListItem({ presenter: $mPresenter, item: item, mPresenter: $presenter });
}
}, (item) => JSON.stringify(item))
}, (item: FavoriteListBean) => JSON.stringify(item))
}
.scrollBar(BarState.Off)
.editMode(true)
@@ -122,19 +125,18 @@ struct FavoriteContent {
.height('100%')
.width('100%')
.backgroundColor(Color.White)
}
}
@Component
export struct FavoriteListItem {
@Link presenter: FavoriteListPresenter;
@Link private mPresenter: { [key: string]: any };
@Link private mPresenter: FavoriteListPresenter;
@State selectSimBuilder: SelectDialogBuilder = {
title: 'test title',
multiSimCardItems: [],
};
@State item: { [key: string]: any } = {};;
@Prop item: FavoriteListBean;
@State builder: SelectNumDialogBuilder = {
title: $r('app.string.contacts_call'),
multiNumCardItems: [],
@@ -142,7 +144,7 @@ export struct FavoriteListItem {
};
mSelectSlotIdDialog: CustomDialogController = new CustomDialogController({
builder: SelectMultiNumDialog({
builder: $builder
builder: this.builder
}),
customStyle: false,
autoCancel: true,
@@ -153,7 +155,6 @@ export struct FavoriteListItem {
@StorageLink('haveMultiSimCard') haveMultiSimCard: boolean = false;
aboutToDisappear() {
this.mSelectSlotIdDialog = null;
}
build() {
@@ -259,58 +260,61 @@ export struct FavoriteListItem {
}
}
.onClick(() => {
ContactAbilityModel.getContactById(this.item.favorite.contactId, result => {
ContactAbilityModel.getContactById(Number.parseInt(this.item.favorite.contactId), (result: LooseObject) => {
if (result.data.hasOwnProperty('phones')) {
if (result.data.phones.length > 1) {
new Promise<number>(async () => {
let defaultNumber: String = <String> await sharedPreferencesUtils.getFromPreferences(
this.item.favorite.contactId + '', '-1');
let defaultNumber: String =
await sharedPreferencesUtils.getFromPreferences(this.item.favorite.contactId + '', '-1') as String;
this.builder.multiNumCardItems = []
this.builder.contactId = result.data.id
var hasDefault = false
result.data.phones.forEach((element) => {
let hasDefault = false
result.data.phones.forEach((element: LooseObject) => {
let formatNum = PhoneNumber.fromString(element.num).getNumber().replace(/\s+/g, '')
if (defaultNumber != '-1' && defaultNumber == formatNum) {
this.dealCallNumber(formatNum)
hasDefault = true;
return;
}
this.builder.multiNumCardItems.push({ number: element.num, img: $r('app.media.ic_public_phone_dialog'),
numType: Phone.getTypeLabelResource(parseInt(element.numType, 10)) })
this.builder.multiNumCardItems.push({
number: element.num, img: $r('app.media.ic_public_phone_dialog'),
numType: Phone.getTypeLabelResource(parseInt(element.numType, 10))
})
});
this.builder.callback = (item) => {
this.builder.callback = (item: LooseObject) => {
this.dealCallNumber(item.number)
}
if (!hasDefault)
if (!hasDefault) {
this.mSelectSlotIdDialog.open()
}
});
} else if (result.data.phones.length > 0) {
this.dealCallNumber(result.data.phones[0].num)
}
} else {
prompt.showToast({ message: '联系人无可用号码!'})
prompt.showToast({ message: '联系人无可用号码!' })
HiLog.e(TAG, ' popupSelectNumber phones null');
}
}, globalThis.getContext())
})
.gesture(
LongPressGesture({ repeat: false })
.onAction((event: GestureEvent) => {
for (let i = 0; i < this.presenter.favoriteList.length; i++) {
if (this.item.favorite.contactId === this.presenter.favoriteList[i].contactId) {
this.presenter.favoriteList[i].isEditSelect = true;
} else {
this.presenter.favoriteList[i].isEditSelect = false;
LongPressGesture({ repeat: false })
.onAction((event: GestureEvent) => {
for (let i = 0; i < this.presenter.favoriteList.length; i++) {
if (this.item.favorite.contactId === this.presenter.favoriteList[i].contactId) {
this.presenter.favoriteList[i].isEditSelect = true;
} else {
this.presenter.favoriteList[i].isEditSelect = false;
}
}
}
this.presenter.isEditSelectList.pop();
this.presenter.isEditSelectList.push(this.item.favorite.contactId + '');
this.presenter.longItemEditFavorite(this.presenter.favoriteList, this.presenter.isEditSelectList, this.item.favorite);
})
this.presenter.isEditSelectList.pop();
this.presenter.isEditSelectList.push(this.item.favorite.contactId + '');
this.presenter.longItemEditFavorite(this.presenter.favoriteList, this.presenter.isEditSelectList, this.item.favorite);
})
)
}
dealCallNumber(phoneNum) {
dealCallNumber(phoneNum: string) {
if (!this.haveSimCard) {
HiLog.i(TAG, 'No SIM card!');
PhoneNumber.fromString(phoneNum).isDialEmergencyNum().then((res) => {
@@ -321,7 +325,7 @@ export struct FavoriteListItem {
promptAction.showToast({
message: $r('app.string.no_simCardDailog'),
duration: 2000,
bottom:'60%'
bottom: '60%'
});
return;
} else {
@@ -337,8 +341,10 @@ export struct FavoriteListItem {
}
this.selectSimBuilder.lastSimId = this.mPresenter.lastUsedSlotId;
let spnList = AppStorage.Get<Array<string | Resource>>('spnList');
for (var index = 0; index < spnList.length; index++) {
this.selectSimBuilder.multiSimCardItems[index].name = spnList[index];
if (spnList !== undefined && spnList.length !== undefined) {
for (let index = 0; index < spnList.length; index++) {
this.selectSimBuilder.multiSimCardItems[index].name = spnList[index];
}
}
this.selectSimBuilder.controller?.open();
} else {
@@ -350,7 +356,7 @@ export struct FavoriteListItem {
@Component
export struct FavoriteEmptyPage {
@Link presenter: FavoriteListPresenter;
@Link isEdit: boolean ;
@Link isEdit: boolean;
build() {
Column() {
@@ -400,7 +406,8 @@ export struct FavoriteEmptyPage {
struct TitleGuide {
@Link mPresenter: FavoriteListPresenter;
@Builder MenuBuilder() {
@Builder
MenuBuilder() {
Column() {
Text($r('app.string.edit'))
.fontSize($r('app.float.id_corner_radius_card_mid'))
+81 -65
View File
@@ -24,13 +24,30 @@ import call from '@ohos.telephony.call';
import ContactListPresenter from '../presenter/contact/ContactListPresenter';
import CallRecordPresenter from '../presenter/dialer/callRecord/CallRecordPresenter';
import FavoriteListPresenter from '../presenter/favorite/FavoriteListPresenter';
import device from '@system.device';
import emitter from '@ohos.events.emitter';
import { TargetPageInter } from '../model';
import device from '@system.device';
import { DeviceResponse } from '@kit.BasicServicesKit';
const TAG = 'Index ';
class DeviceObj{
public windowHeight:number = -1;
public screenDensity:number = -1;
public data:string[] = [];
}
let storage = LocalStorage.GetShared()
interface GeneratedObjectLiteralInterface_1 {
eventId: number;
priority: EventPriority;
}
interface EventPriority{
}
@Entry(storage)
@Component
struct Index {
@@ -41,11 +58,7 @@ struct Index {
@StorageLink('teleNumber') @Watch('teleNumberChange') teleNumber: string = '';
mDialerPresenter: DialerPresenter = DialerPresenter.getInstance();
@State bottomTabIndex: number = call.hasVoiceCapability() ? 0 : 1;
@StorageLink('targetPage') @Watch('targetPageChange') targetPage: {
url?: string,
pageIndex?: number,
params?: any
} = {};
@StorageLink('targetPage') @Watch('targetPageChange') targetPage: TargetPageInter = {};
@LocalStorageProp('breakpoint') curBp: string = 'sm';
@State isContactSearch: boolean = false;
emitterId: number = 105;
@@ -111,12 +124,14 @@ struct Index {
this.getInfo();
this.onIndexChanged();
this.teleNumberChange()
let innerEvent = {
let innerEvent: emitter.InnerEvent = {
eventId: this.emitterId,
priority: emitter.EventPriority.HIGH
};
emitter.on(innerEvent, (data) => {
this.isContactSearch = data.data['isSearchPage'];
emitter.on(innerEvent, (data:emitter.EventData) => {
if(data.data !== undefined){
this.isContactSearch = data.data['isSearchPage'];
}
})
}
@@ -125,19 +140,20 @@ struct Index {
emitter.off(this.emitterId);
}
onBackPress() {
onBackPress() :boolean{
if (this.isContactSearch) {
ContactListPresenter.getInstance().sendEmitter(false);
return true;
}
return false;
}
getInfo() {
device.getInfo({
success: function (data) {
AppStorage.SetOrCreate('windowHeight', data.windowHeight / data.screenDensity)
success: (data:DeviceResponse) => {
AppStorage.SetOrCreate('windowHeight', data.windowHeight / data.screenDensity);
},
fail: function (data, code) {
fail: (data:DeviceObj, code:number) => {
HiLog.i(TAG, 'Failed to obtain device information. Error code:' + code + '; Error information: ' + data);
},
});
@@ -145,59 +161,59 @@ struct Index {
build() {
if (this.mPermissionManager.isAllPermissionsGranted()) {
Flex({
direction: this.curBp === 'lg' ? FlexDirection.Row : FlexDirection.Column,
alignItems: ItemAlign.Start,
justifyContent: FlexAlign.Start
Flex({
direction: this.curBp === 'lg' ? FlexDirection.Row : FlexDirection.Column,
alignItems: ItemAlign.Start,
justifyContent: FlexAlign.Start
}) {
if (this.curBp === 'lg') {
TabBars({ controller: this.controller, bottomTabIndex: $bottomTabIndex })
.visibility(this.isContactSearch ? Visibility.None : Visibility.Visible)
}
Tabs({
barPosition: BarPosition.End,
index: this.bottomTabIndex,
controller: this.controller
}) {
if (this.curBp === 'lg') {
TabBars({ controller: this.controller, bottomTabIndex: $bottomTabIndex })
.visibility(this.isContactSearch ? Visibility.None : Visibility.Visible)
}
Tabs({
barPosition: BarPosition.End,
index: this.bottomTabIndex,
controller: this.controller
}) {
if (this.curBp !== 'lg') {
TabContent() {
callPage()
}
} else {
TabContent() {
callTabletPage()
}
}
TabContent() {
contactPage()
}
TabContent() {
favoritePage()
}
}
.width(this.curBp === 'lg' ? null : '100%')
.height(this.curBp === 'lg' ? '100%' : null)
.vertical(false)
.barMode(BarMode.Fixed)
.barWidth(0)
.barHeight(0)
.scrollable(false)
.animationDuration(0)
.layoutWeight(1)
if (this.curBp !== 'lg') {
TabBars({ controller: this.controller, bottomTabIndex: $bottomTabIndex })
.backgroundColor($r('sys.color.ohos_id_color_sub_background'))
.visibility(this.isContactSearch ? Visibility.None : Visibility.Visible)
TabContent() {
callPage()
}
} else {
TabContent() {
callTabletPage()
}
}
TabContent() {
contactPage()
}
TabContent() {
favoritePage()
}
}
.backgroundColor($r('sys.color.ohos_fa_sub_background'))
.width(this.curBp === 'lg' ? null : '100%')
.height(this.curBp === 'lg' ? '100%' : null)
.vertical(false)
.barMode(BarMode.Fixed)
.barWidth(0)
.barHeight(0)
.scrollable(false)
.animationDuration(0)
.layoutWeight(1)
if (this.curBp !== 'lg') {
TabBars({ controller: this.controller, bottomTabIndex: $bottomTabIndex })
.backgroundColor($r('sys.color.ohos_id_color_sub_background'))
.visibility(this.isContactSearch ? Visibility.None : Visibility.Visible)
}
}
.backgroundColor($r('sys.color.ohos_fa_sub_background'))
.width('100%')
.height('100%')
} else {
Column()
.width('100%')
.height('100%')
} else {
Column()
.width('100%')
.height('100%')
}
}
}
@@ -205,7 +221,7 @@ struct Index {
@Component
struct TabBars {
private tabSrc: number[] = call.hasVoiceCapability() ? [0, 1, 2] : [1];
private controller: TabsController;
private controller: TabsController| undefined = undefined;
@Link bottomTabIndex: number;
@State mIndexPresenter: IndexPresenter = IndexPresenter.getInstance()
@LocalStorageProp('breakpoint') curBp: string = 'sm'
@@ -216,7 +232,7 @@ struct TabBars {
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center
}) {
ForEach(this.tabSrc, item => {
ForEach(this.tabSrc, (item:number) => {
Column() {
Column() {
Image(this.mIndexPresenter.getTabSrc(this.bottomTabIndex, item))
@@ -233,7 +249,7 @@ struct TabBars {
}
.onClick(() => {
if (this.bottomTabIndex != item) {
this.controller.changeIndex(item);
this.controller?.changeIndex(item);
this.bottomTabIndex = item;
AppStorage.SetOrCreate('mainTabsIndex', item);
if (item == 0) {
@@ -257,7 +273,7 @@ struct TabBars {
.height(this.curBp === 'lg' ?
'130vp' : $r('app.float.id_item_height_large'))
.layoutWeight(this.curBp === 'lg' ? 0 : 1)
}, item => item.toString())
}, (item:number) => item.toString())
}
.width(this.curBp === 'lg' ?
'96vp' : '100%')
@@ -14,11 +14,11 @@
*/
import CallRecord from '../../dialer/callRecord/CallRecord';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import DialerPresenter from './../../../presenter/dialer/DialerPresenter';
import { DialerButtonView } from '../../../component/dialer/DialerButtonView';
import { PhoneNumber } from '../../../../../../../feature/phonenumber/src/main/ets/PhoneNumber';
import MergedCallLog from '../../../../../../../feature/call/src/main/ets/entity/MergedCallLog';
const TAG = 'Dialer';
@Component
@@ -210,7 +210,7 @@ export default struct Call {
justifyContent: FlexAlign.Start
}) {
List({ space: 0, initialIndex: 0 }) {
LazyForEach(this.mPresenter.mAllCallRecordListDataSource, (item, index: number) => {
LazyForEach(this.mPresenter.mAllCallRecordListDataSource, (item:MergedCallLog, index: number) => {
ListItem() {
Flex({
direction: FlexDirection.Row,
@@ -219,7 +219,7 @@ export default struct Call {
}) {
Column() {
Row() {
ForEach(item.displayName.split(this.tele_number.replace(/\s*/g,'')), (displayName, idx: number) => {
ForEach(item.displayName.split(this.tele_number.replace(/\s*/g,'')), (displayName:string, idx: number) => {
Row() {
Text(displayName.toString())
.fontSize($r('sys.float.ohos_id_text_size_body1'))
@@ -248,7 +248,7 @@ export default struct Call {
}
Row() {
ForEach(item.phoneNumber.split(this.tele_number.replace(/\s*/g,'')), (phoneNumber, idx: number) => {
ForEach(item.phoneNumber.split(this.tele_number.replace(/\s*/g,'')), (phoneNumber:string, idx: number) => {
Row() {
Text(phoneNumber.toString())
.fontSize($r('sys.float.ohos_id_text_size_body1'))
@@ -279,7 +279,7 @@ export default struct Call {
.borderRadius($r('app.float.id_card_margin_xl'))
.onClick(() => {
this.mPresenter.jumpToContactDetail(item.phoneNumber);
})
})
}
.margin({
left: $r('app.float.id_card_image_small'),
@@ -287,7 +287,7 @@ export default struct Call {
})
}
.height($r('app.float.id_item_height_max'))
}, item => JSON.stringify(item))
}, (item:string) => JSON.stringify(item))
}
.divider({
strokeWidth: 0.5,
@@ -477,16 +477,16 @@ export default struct Call {
.opacity(this.tele_number.length > 0 ? 1 : 0.5)
.enabled(this.tele_number.length > 0 ? true : false)
.gesture(
LongPressGesture({ repeat: false, fingers: 1, duration: 700 })
.onAction((event: GestureEvent) => {
AppStorage.SetOrCreate('tele_number', '');
this.mPresenter.all_number = '';
this.mPresenter.editPhoneNumber('');
})
LongPressGesture({ repeat: false, fingers: 1, duration: 700 })
.onAction((event: GestureEvent) => {
AppStorage.SetOrCreate('tele_number', '');
this.mPresenter.all_number = '';
this.mPresenter.editPhoneNumber('');
})
)
.onClick(() => {
this.mPresenter.pressVibrate();
let number: string = AppStorage.Get('tele_number');
let number: string = AppStorage.Get('tele_number') as string;
this.mPresenter.all_number = number.substr(0, number.length - 1);
this.mPresenter.deleteTeleNum();
this.mPresenter.deleteAddSpace();
@@ -506,23 +506,23 @@ export default struct Call {
.width('100%')
.backgroundColor($r('sys.color.ohos_id_color_panel_bg'))
.clip(new Rect(this.tele_number.length >= 3 ? {
width: '100%',
height: '392',
radius: [[24, 24], [24, 24], [0, 0], [0, 0]]
} : {
width: '100%',
height: '336',
radius: [[24, 24], [24, 24], [0, 0], [0, 0]]
}))
width: '100%',
height: '392',
radius: [[24, 24], [24, 24], [0, 0], [0, 0]]
} : {
width: '100%',
height: '336',
radius: [[24, 24], [24, 24], [0, 0], [0, 0]]
}))
.zIndex(2)
.offset({ y: this.mPresenter.moveY })
.height(this.tele_number.length >= 3 ? 392 : 336)
.padding(this.curBp === 'lg' ? {} : { right: 24, left: 24 })
.gesture(
PanGesture({ fingers: 1, direction: PanDirection.Down, distance: 5 })
.onActionStart(() => {
this.mPresenter.moveY = 0
})
PanGesture({ fingers: 1, direction: PanDirection.Down, distance: 5 })
.onActionStart(() => {
this.mPresenter.moveY = 0
})
)
}
.width('100%')
@@ -15,14 +15,14 @@
import router from '@ohos.router';
import pasteboard from '@ohos.pasteboard';
import { HiLog } from '../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { StringUtil } from '../../../../../common/src/main/ets/util/StringUtil';
import StringFormatUtil from '../util/StringFormatUtil';
import { missedCallManager } from '../feature/missedCall/MissedCallManager';
import CallRecordPresenter from './dialer/callRecord/CallRecordPresenter';
import FavoriteListPresenter from './favorite/FavoriteListPresenter';
const TAG = 'IndexPresenter ';
const TAG = 'IndexPresenter ';
export default class IndexPresenter {
private static instance: IndexPresenter;
@@ -50,7 +50,7 @@ export default class IndexPresenter {
return url;
}
goToPage(url: string, pageIndex?: number, params?) {
goToPage(url: string, pageIndex?: number, params?:Record<string, string>) {
HiLog.i(TAG, 'goToPage: ' + url);
if (pageIndex != undefined && router.getState().index >= pageIndex) {
if (url == globalThis.presenterManager?.mainUrl || this.getCurrentUrl() == url) {
@@ -86,7 +86,7 @@ export default class IndexPresenter {
HiLog.i(TAG, 'aboutToDisappear !!!');
}
getCopy(phoneNumber) {
getCopy(phoneNumber:string) {
HiLog.i(TAG, 'Succeeded PasteData is ' + JSON.stringify(phoneNumber));
let pasteData = pasteboard.createPlainTextData(phoneNumber);
let systemPasteboard = pasteboard.getSystemPasteboard();
@@ -12,24 +12,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { HiLog } from '../../../../../common/src/main/ets/util/HiLog';
import Constants from '../../../../../common/src/main/ets/Constants';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import Constants from 'common/src/main/ets/Constants';
import ContactListPresenter from './contact/ContactListPresenter';
import CallRecordPresenter from './dialer/callRecord/CallRecordPresenter';
import WorkerWrapper from '../workers/base/WorkerWrapper';
import Want from '@ohos.app.ability.Want';
import { paramsInterface } from '../model/type';
const TAG = 'PageManager'
export default class PresenterManager {
mainUrl: string = 'pages/index';
context: Context;
worker: WorkerWrapper;
worker: WorkerWrapper | undefined;
callRecordPresenter: CallRecordPresenter = CallRecordPresenter.getInstance();
contactListPresenter: ContactListPresenter = ContactListPresenter.getInstance();
constructor(context: Context, worker: WorkerWrapper) {
constructor(context: Context, worker: WorkerWrapper | undefined) {
this.context = context;
this.worker = worker;
}
@@ -61,35 +61,29 @@ export default class PresenterManager {
}
// Go to a specified page.
onRequest(parameters: { [key: string]: Object }, isOnCreate: boolean) {
onRequest(parameters: Record<string, Object> | undefined, isOnCreate: boolean) {
HiLog.i(TAG, 'show pageRouteHandler routeMessage ');
let url = 'pages/index';
let params = {};
let params: paramsInterface = {};
let pageIndex = 1;
if (parameters?.pageFlag) {
HiLog.i(TAG, 'pageRouteHandler case is ' + parameters.pageFlag);
switch (parameters.pageFlag.toString()) {
// jump to index
// jump to index
case 'page_flag_dialer':
AppStorage.SetOrCreate(Constants.Storage.mainTabsIndex, 0);
params = {
mainTabsIndex: 0
}
AppStorage.SetOrCreate(Constants.storage.mainTabsIndex, 0);
params.mainTabsIndex = 0;
break;
case 'page_flag_choose_contacts':
AppStorage.SetOrCreate(Constants.Storage.mainTabsIndex, 1);
params = {
mainTabsIndex: 1
}
AppStorage.SetOrCreate(Constants.storage.mainTabsIndex, 1);
params.mainTabsIndex = 1;
break;
case 'page_flag_contact_details':
url = 'pages/contacts/details/ContactDetail';
pageIndex = 2;
if (parameters.contactId) {
params = {
'sourceHasId': true,
'contactId': parameters.contactId
}
params.sourceHasId = true;
params.contactId = parameters.contactId;
} else {
HiLog.i(TAG, 'SHOW pageRouteHandler and routeMessage.phoneNumber ');
params = {
@@ -99,8 +93,8 @@ export default class PresenterManager {
}
break;
case 'page_flag_edit_before_calling':
AppStorage.SetOrCreate(Constants.Storage.mainTabsIndex, 0);
AppStorage.SetOrCreate(Constants.Storage.teleNumber, parameters.phoneNumber);
AppStorage.SetOrCreate(Constants.storage.mainTabsIndex, 0);
AppStorage.SetOrCreate(Constants.storage.teleNumber, parameters.phoneNumber);
params = {
mainTabsIndex: 0, teleNumber: parameters.phoneNumber
}
@@ -156,7 +150,7 @@ export default class PresenterManager {
this.mainUrl = url;
AppStorage.SetOrCreate('params', params);
} else {
AppStorage.SetOrCreate(Constants.Storage.targetPage, {
AppStorage.SetOrCreate(Constants.storage.targetPage, {
url: url,
pageIndex: pageIndex,
params: params
@@ -12,9 +12,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import router from '@ohos.router';
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { ContactVo } from '../../model/bean/ContactVo';
import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil';
import { CallLogRepository } from '../../../../../../feature/call/src/main/ets/repo/CallLogRepository';
@@ -25,6 +24,7 @@ import WorkerWrapper from '../../workers/base/WorkerWrapper';
import { SearchContactsBean } from '../../model/bean/SearchContactsBean';
import SearchContactsSource from '../../model/bean/SearchContactsSource';
import AlphabetIndexerPresenter from './alphabetindex/AlphabetIndexerPresenter';
import LooseObject from '../../model/type/LooseObject';
const TAG = 'ContactListPresenter ';
const DELAY_TIME: number = 1000;
@@ -44,7 +44,8 @@ export enum ContactClickType {
*/
export default class ContactListPresenter {
private static sInstance: ContactListPresenter;
indexs: string[] = ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '…'];
indexs: string[] =
['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '…'];
contactListPages: Array<number> = [];
curItem: ContactVo = new ContactVo('', '', '', '', '', '', true, '', '');
page: number = 0;
@@ -57,22 +58,22 @@ export default class ContactListPresenter {
contactListDataSource: ContactListDataSource = new ContactListDataSource();
searchContactsSource: SearchContactsSource = new SearchContactsSource();
isShow: boolean = false;
context: Context;
worker: WorkerWrapper;
loading: boolean;
context: Context | undefined = undefined;
worker: WorkerWrapper | undefined;
loading: boolean = false;
initStarted: boolean = false;
contactSearchList: SearchContactsBean[] = [];
contactSearchCount: number = 0;
tempValue: string = '';
taskId: number = -1;;
taskId: number = -1;
isSearchBackgroundColor: boolean = true;
isSearchPage: boolean = false;
inputKeyword: string = '';
contactList: ContactVo[] = [];
alphabetIndexPresenter: AlphabetIndexerPresenter = AlphabetIndexerPresenter.getInstance();
refreshState: () => void
onContactChange = () => {
public refreshState?: () => void = () => {
}
public onContactChange = () => {
HiLog.i(TAG, 'onContactChange refresh');
this.setDelayTask();
}
@@ -91,7 +92,7 @@ export default class ContactListPresenter {
return ContactListPresenter.sInstance;
}
onCreate(context: Context, worker: WorkerWrapper) {
onCreate(context: Context, worker: WorkerWrapper | undefined) {
this.context = context;
this.worker = worker;
ContactRepository.getInstance().registerDataChangeObserver(this.onContactChange);
@@ -211,15 +212,18 @@ export default class ContactListPresenter {
refreshPage(page: number, limit: number, callback?: () => void) {
this.loading = true;
let actionData: any = {};
let actionData: LooseObject = {};
actionData.page = page;
actionData.limit = limit;
if (this.worker === undefined) {
return
}
this.worker.sendRequest('getAllContact', {
actionData: actionData,
context: this.context
}, (result) => {
}, (result: ContactVo[]) => {
HiLog.i(TAG, `refreshPage ${page} getAllContact, length is: ` + result.length);
if (Array.prototype.isPrototypeOf(result)) {
if (Array.isArray(result)) {
this.contactListDataSource.refresh(this.refreshIndex, this.contactListPages[page -1], result);
this.contactList.splice(this.refreshIndex, this.contactListPages[page -1], ...result);
this.alphabetIndexPresenter.initContactList(this.contactList);
@@ -285,16 +289,18 @@ export default class ContactListPresenter {
*
* @param result
*/
onDeleteDialogConfirm(index, item) {
onDeleteDialogConfirm(index: number, item: ContactVo) {
HiLog.i(TAG, 'onDeleteDialogConfirm !!! ');
this.worker.sendRequest('deleteContactById', {
context: this.context,
contactId: item.contactId
}, (result) => {
if (result) {
HiLog.w(TAG, 'deleteContactById error:' + JSON.stringify(result))
}
});
if (this.worker !== undefined) {
this.worker.sendRequest('deleteContactById', {
context: this.context,
contactId: item.contactId
}, (result: number | undefined) => {
if (result) {
HiLog.w(TAG, 'deleteContactById error:' + JSON.stringify(result))
}
});
}
this.contactListDataSource.remove(index);
}
@@ -318,7 +324,7 @@ export default class ContactListPresenter {
* @param item item
* @param index index
*/
onShareItemClick(item: any, index: number | null) {
onShareItemClick(item: string, index: number | null) {
HiLog.i(TAG, 'onShareItemClick !!! index is %s' + index);
}
@@ -377,7 +383,7 @@ export default class ContactListPresenter {
if ('' === value) {
this.isSearchBackgroundColor = true;
this.searchContactsSource.refresh(this.contactSearchList);
let innerEvent = {
let innerEvent: emitter.InnerEvent = {
eventId: 102,
priority: emitter.EventPriority.HIGH
};
@@ -389,17 +395,17 @@ export default class ContactListPresenter {
return;
}
this.tempValue = value;
let actionData: any = {};
let actionData: LooseObject = {};
actionData.value = this.tempValue;
globalThis.DataWorker.sendRequest('getSearchContact', {
actionData: actionData,
context: globalThis.context
}, (result) => {
}, (result: SearchContactsBean[]) => {
this.isSearchBackgroundColor = false;
this.contactSearchList = result;
this.contactSearchCount = this.contactSearchList.length;
this.searchContactsSource.refresh(this.contactSearchList);
let innerEvent = {
let innerEvent: emitter.InnerEvent = {
eventId: 102,
priority: emitter.EventPriority.HIGH
};
@@ -413,7 +419,7 @@ export default class ContactListPresenter {
}
sendEmitter(isSearchPage: boolean) {
let innerEvent = {
let innerEvent: emitter.InnerEvent = {
eventId: EMITTER_SEARCH_ID,
priority: emitter.EventPriority.HIGH
};
@@ -14,10 +14,10 @@
*/
import inputMethod from '@ohos.inputMethod';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { StringUtil } from '../../../../../../../common/src/main/ets/util/StringUtil';
import { ArrayUtil } from '../../../../../../../common/src/main/ets/util/ArrayUtil';
import { ObjectUtil } from '../../../../../../../common/src/main/ets/util/ObjectUtil';
import { ObjectUtil } from 'common/src/main/ets/util/ObjectUtil';
import { AccountTypeService } from '../../../../../../../feature/account/src/main/ets/AccountTypeService';
import { AccountType } from '../../../../../../../feature/account/src/main/ets/type/AccountType';
import { House } from '../../../../../../../feature/contact/src/main/ets/contract/House';
@@ -34,8 +34,12 @@ import { AIMBean } from '../../../model/bean/AIMBean';
import { EventBean } from '../../../model/bean/EventBean';
import { AssociatedPersonBean } from '../../../model/bean/AssociatedPersonBean';
import PreferencesUtil from './../../../util/PreferencesUtil'
import EditType from '../../../../../../../feature/account/src/main/ets/type/EditType';
import LooseObject from '../../../model/LooseObject ';
import { ContackPhoneSubInfoModel, ContactReturnObj } from '../../../model';
import { RichContactInfo } from '../../../model/bean/RichContactInfo';
const TAG = 'AccountantsPresenter ';
const TAG = 'AccountantsPresenter ';
/**
* Add Contact Presenter
@@ -43,29 +47,28 @@ const TAG = 'AccountantsPresenter ';
export default class AccountantsPresenter {
private static instance: AccountantsPresenter;
static readonly timeSub: number = 1000;
getPhones: Array<{ [key: string]: any }> = [];
getEmails: Array<{ [key: string]: any }> = [];
getPhones: Array = [];
getEmails: Array = [];
clickBefEvent: Date = new Date();
clickAftEvent: Date = new Date();
contactId: string = '';
routerAvtiveFlag: boolean = false;
// update mark
updateShow: boolean = false;
isShowPosition: boolean = false;
showMore: boolean = false;
addState: boolean = false;
phones: string = '';
phones: ContackPhoneSubInfoModel[] = [];
editContact: number = -1;
phoneNumberShow: string = '';
callId: string = '';
// refresh mark
changed: boolean = false;
originalContactInfo = JSON.stringify(new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0));
originalContactInfo = JSON.stringify(new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0, '', '', ''));
// contact detail
contactInfoBefore: ContactInfo = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0);
contactInfoAfter: ContactInfo = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0);
contactInfoBefore: ContactInfo = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0, '', '', '');
contactInfoAfter: ContactInfo = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0, '', '', '');
MagList: object = [];
private constructor() {
@@ -78,15 +81,15 @@ export default class AccountantsPresenter {
return AccountantsPresenter.instance
}
refreshState: (presenter: AccountantsPresenter) => void;
public refreshState?: (presenter: AccountantsPresenter) => void;
clickEnable = true;
init(refreshState?) {
init(refreshState?: (presenter: AccountantsPresenter) => void) {
this.contactId = '';
this.updateShow = false;
this.MagList = [1];
this.contactInfoBefore = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0);
this.contactInfoAfter = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0);
this.contactInfoBefore = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0, '', '', '');
this.contactInfoAfter = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0, '', '', '');
this.refreshState = refreshState;
this.routerAvtiveFlag = false;
}
@@ -120,7 +123,7 @@ export default class AccountantsPresenter {
}
getExistenceInfoString(afterInfo: ContactInfo) {
let temp = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0);
let temp = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0, '', '', '');
if (!afterInfo) {
return JSON.stringify(temp);
} else {
@@ -199,8 +202,8 @@ export default class AccountantsPresenter {
globalThis.DataWorker.sendRequest('getContactById', {
context: globalThis.context,
contactId: id
}, result => {
if (StringUtil.isEmpty(result)) {
}, (result: ContactReturnObj) => {
if (result.data == undefined) {
HiLog.e(TAG, 'The result in the database is empty.');
return;
}
@@ -208,64 +211,37 @@ export default class AccountantsPresenter {
});
}
private dealRecordDetailsData(data) {
let contactTemp = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0);
if (!data.hasOwnProperty('id') || data.id != this.contactId) {
private dealRecordDetailsData(data: RichContactInfo) {
let contactTemp = new ContactInfo('', '', '', [], [], '', '', '', [], [], [], [], [], [], 0, '', '', '');
if (!data.id || data.id != this.contactId) {
HiLog.e(TAG, 'Failed to query the database based on the ID.');
return;
}
contactTemp.setID(data.id);
let nameUpdate = 0;
if (data.hasOwnProperty('nameUpdate')) {
nameUpdate = data.nameUpdate;
}
if (data.hasOwnProperty('display_name') && nameUpdate == 0) {
let nameUpdate = data.nameUpdate;
if (nameUpdate == 0) {
contactTemp.setDisplayName(data.display_name);
}
if (data.hasOwnProperty('nickname')) {
contactTemp.setNickName(data.nickname);
}
if (data.hasOwnProperty('phones')) {
contactTemp.setPhones(data.phones);
}
if (data.hasOwnProperty('emails')) {
contactTemp.setEmails(data.emails);
}
if (data.hasOwnProperty('remarks')) {
contactTemp.setRemarks(data.remarks);
}
if (data.hasOwnProperty('position')) {
contactTemp.setPosition(data.position);
this.isShowPosition = true;
}
if (data.hasOwnProperty('company')) {
contactTemp.setCompany(data.company);
}
if (data.hasOwnProperty('aims')) {
contactTemp.setAims(data.aims);
}
if (data.hasOwnProperty('houses')) {
contactTemp.setHouses(data.houses);
}
if (data.hasOwnProperty('websites')) {
contactTemp.setWebsites(data.websites);
}
if (data.hasOwnProperty('relationships')) {
contactTemp.setRelationships(data.relationships);
}
if (data.hasOwnProperty('events')) {
contactTemp.setEvents(data.events);
}
if (data.hasOwnProperty('groups')) {
contactTemp.setGroups(data.groups);
}
contactTemp.setNickName(data.nickname);
contactTemp.setPhones(data.phones);
contactTemp.setEmails(data.emails);
contactTemp.setRemarks(data.remarks);
contactTemp.setPosition(data.position);
this.isShowPosition = true;
contactTemp.setCompany(data.company);
contactTemp.setAims(data.aims);
contactTemp.setHouses(data.houses);
contactTemp.setWebsites(data.websites);
contactTemp.setRelationships(data.relationships);
contactTemp.setEvents(data.events);
contactTemp.setGroups(data.groups);
this.contactInfoBefore = contactTemp;
this.originalContactInfo = this.getExistenceInfoString(contactTemp)
if (0 === this.editContact) {
if ('' !== this.phones) {
let saveTemp: Array<{ [key: string]: any }> = this.getArray(this.phones);
for(let i = 0; i < saveTemp?.length ; i ++){
let phoneNumBean: PhoneNumBean = new PhoneNumBean('','','','','');
if (!ArrayUtil.isEmpty(this.phones)) {
let saveTemp: LooseObject[] = this.getArray(this.phones);
for (let i = 0; i < saveTemp?.length; i++) {
let phoneNumBean: PhoneNumBean = new PhoneNumBean('', '', '', '', '');
phoneNumBean.id = saveTemp[i]?.item?.id;
phoneNumBean.num = saveTemp[i]?.item?.num;
phoneNumBean.numType = saveTemp[i]?.item?.type;
@@ -275,7 +251,7 @@ export default class AccountantsPresenter {
}
}
} else if (1 === this.editContact || 2 === this.editContact) {
let phoneNumBean: PhoneNumBean = new PhoneNumBean('','','','','');
let phoneNumBean: PhoneNumBean = new PhoneNumBean('', '', '', '', '');
phoneNumBean.id = this.callId;
phoneNumBean.num = this.phoneNumberShow;
phoneNumBean.numType = '';
@@ -289,8 +265,8 @@ export default class AccountantsPresenter {
this.refreshAddState()
}
public getData(type: string, index: number): { [key: string]: any } {
let data = new Array<{ [key: string]: any }>();
public getData(type: string, index: number): LooseObject {
let data: LooseObject[] = [];
switch (type) {
case 'phone':
if (!this.updateShow) {
@@ -329,21 +305,23 @@ export default class AccountantsPresenter {
};
}
public getArray(array): Array<{ [key: string]: any }> {
if (ArrayUtil.isEmpty(array)) {
array = [{}];
public getArray(array: Array<LooseObject>): Array<LooseObject> {
let itemList: LooseObject[] = array;
if (ArrayUtil.isEmpty(itemList)) {
itemList = [];
}
let itemList = ArrayUtil.isEmpty(array) ? this.MagList : array;
itemList = itemList.map((item, index) => {
return {
i: index + 1, item: item
};
itemList = itemList.map((item, index: number) => {
let result: LooseObject = {
i: index + 1,
item: item
}
return result;
})
return itemList;
}
public getDataArray(type: string) {
let data = new Array<{ [key: string]: any }>();
let data = new Array();
switch (type) {
case 'phone':
if (!this.updateShow) {
@@ -378,7 +356,7 @@ export default class AccountantsPresenter {
return data;
}
public addMore(type: any) {
public addMore(type: string) {
switch (type) {
case 'phone':
this.contactInfoAfter.phones.push(new PhoneNumBean('', '', '1', '', ''));
@@ -404,7 +382,7 @@ export default class AccountantsPresenter {
this.refresh();
}
public deleteItem(typeName: string, startIndex) {
public deleteItem(typeName: string, startIndex: number) {
HiLog.i(TAG, `deleteItem ${typeName} ${startIndex}`);
switch (typeName) {
case 'phone':
@@ -457,7 +435,7 @@ export default class AccountantsPresenter {
this.refresh();
}
public getTextDisplay(typeName: string, data: any) {
public getTextDisplay(typeName: string, data: LooseObject) {
let display: string = '';
if (data && data.item) {
switch (typeName) {
@@ -498,7 +476,7 @@ export default class AccountantsPresenter {
return display;
}
public listItemChange(typeName: string, data: any, arg: string) {
public listItemChange(typeName: string, data: LooseObject, arg: string) {
try {
switch (typeName) {
case 'phone':
@@ -540,7 +518,7 @@ export default class AccountantsPresenter {
}
}
public menuSelect(typeName: string, data: any) {
public menuSelect(typeName: string, data: LooseObject): Resource | string {
let typeId = 1;
switch (typeName) {
case 'phone':
@@ -587,26 +565,26 @@ export default class AccountantsPresenter {
getMenuList(typeName: string) {
let accountTypeService = new AccountTypeService();
let menuKindTypeList;
let menuKindTypeList: EditType[] = [];
let phoneType = accountTypeService.getAccountType(AccountType.PHONE_ACCOUNT_TYPE);
switch (typeName) {
case 'phone':
menuKindTypeList = phoneType.mineKinds.get(Phone.CONTENT_ITEM_TYPE).typeList;
menuKindTypeList = phoneType.mineKinds?.get(Phone.CONTENT_ITEM_TYPE)?.typeList as EditType[];
break;
case 'email':
menuKindTypeList = phoneType.mineKinds.get(Email.CONTENT_ITEM_TYPE).typeList;
menuKindTypeList = phoneType.mineKinds?.get(Email.CONTENT_ITEM_TYPE)?.typeList as EditType[];
break;
case 'AIM':
menuKindTypeList = phoneType.mineKinds.get(Aim.CONTENT_ITEM_TYPE).typeList;
menuKindTypeList = phoneType.mineKinds?.get(Aim.CONTENT_ITEM_TYPE)?.typeList as EditType[];
break;
case 'house':
menuKindTypeList = phoneType.mineKinds.get(House.CONTENT_ITEM_TYPE).typeList;
menuKindTypeList = phoneType.mineKinds?.get(House.CONTENT_ITEM_TYPE)?.typeList as EditType[];
break;
case 'relationships':
menuKindTypeList = phoneType.mineKinds.get(Relation.CONTENT_ITEM_TYPE).typeList;
menuKindTypeList = phoneType.mineKinds?.get(Relation.CONTENT_ITEM_TYPE)?.typeList as EditType[];
break;
case 'events':
menuKindTypeList = phoneType.mineKinds.get(Birthday.CONTENT_ITEM_TYPE).typeList;
menuKindTypeList = phoneType.mineKinds?.get(Birthday.CONTENT_ITEM_TYPE)?.typeList as EditType[];
break;
default:
break;
@@ -614,7 +592,7 @@ export default class AccountantsPresenter {
return menuKindTypeList;
}
public menuChange(typeName: string, data: any, item: any) {
public menuChange(typeName: string, data: LooseObject, item: EditType) {
switch (typeName) {
case 'phone':
if (ObjectUtil.isEmpty(this.contactInfoAfter.phones[data.i - 1])) {
@@ -675,7 +653,7 @@ export default class AccountantsPresenter {
context: globalThis.context,
contactInfoAfter: JSON.stringify(this.contactInfoAfter)
}
, (arg) => {
, (arg: object) => {
this.clickEnable = true
this.contactId = arg.toString();
this.routerAvtiveFlag = true;
@@ -683,12 +661,11 @@ export default class AccountantsPresenter {
PreferencesUtil.setIsUsed(true);
}
})
}
else {
} else {
globalThis.DataWorker.sendRequest('updateContact', {
context: globalThis.context,
contactInfoAfter: JSON.stringify(this.contactInfoAfter)
}, (arg) => {
}, (arg: string) => {
this.clickEnable = true
this.contactId = arg.toString();
this.routerAvtiveFlag = true;
@@ -15,7 +15,7 @@
import {ContactVo, NameVo } from '../../..//model/bean/ContactVo';
import { ArrayUtil } from '../../../../../../../common/src/main/ets/util/ArrayUtil';
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
const TAG = 'AlphabetIndexerPresenter';
const CHINESE_CHAR_CODE = 255;
@@ -23,8 +23,8 @@ const CHINESE_CHAR_CODE = 255;
export default class AlphabetIndexerPresenter {
private static sInstance: AlphabetIndexerPresenter;
alphabetIndexList: string[] = ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
private alphabetObj: {[key: string] : NameVo[]} = {};
private alphabetIndexObj: {[key: string] : number} = {};
private alphabetObj: Record<string, NameVo[]> = {};
private alphabetIndexObj: Record<string, number> = {};
private contactList: ContactVo[] = [];
public static getInstance(): AlphabetIndexerPresenter {
@@ -42,12 +42,12 @@ export default class AlphabetIndexerPresenter {
getAlphabetIndexData() {
if (ArrayUtil.isEmpty(this.contactList)) {
return null;
return;
}
// Get the position of the index in the list
// Get index data
this.contactList.forEach((item, index) => {
let preContact: ContactVo = null;
let preContact: ContactVo = new ContactVo('', '', '', '', '', '', true, '', '');
if (index > 0) {
preContact = this.contactList[index - 1];
}
@@ -86,14 +86,14 @@ export default class AlphabetIndexerPresenter {
return popData;
}
getListScrollIndex(selectedAlphabetIndex: number, popDataSource?: string[], popIndex?: number): number {
getListScrollIndex(selectedAlphabetIndex: number, popDataSource?: string[], popIndex?: number): number {
// get list scroll index
let selected = this.alphabetIndexList[selectedAlphabetIndex];
let alphabetIndex = this.alphabetIndexObj[selected];
let scrollIndex: number = alphabetIndex;
if (popIndex >= 0) {
if (popIndex !== undefined && popIndex >= 0) {
let alphabetContacts = this.alphabetObj[selected];
if (alphabetContacts) {
if (alphabetContacts && popDataSource !== undefined) {
let popData = popDataSource[popIndex];
for (let index = 0; index < alphabetContacts.length; index++) {
const element = alphabetContacts[index];
@@ -12,35 +12,94 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import callLogService from '../../../model/calllog/CalllogModel';
import MorandiColor from '../../../model/bean/MorandiColor';
import { ArrayUtil } from '../../../../../../../common/src/main/ets/util/ArrayUtil';
import { StringUtil } from '../../../../../../../common/src/main/ets/util/StringUtil';
import { ObjectUtil } from '../../../../../../../common/src/main/ets/util/ObjectUtil';
import { ObjectUtil } from 'common/src/main/ets/util/ObjectUtil';
import ContactAbilityModel from '../../../model/ContactAbilityModel';
import router from '@ohos.router';
import BatchSelectRecentSource from '../../../model/bean/BatchSelectRecentSource';
import BatchSelectContactSource from '../../../model/bean/BatchSelectContactSource';
import CallLogSetting from '../../../../../../../feature/call/src/main/ets/CallLogSetting'
import { ContactVo } from '../../../model/bean/ContactVo';
import { ContactVo, NameVo } from '../../../model/bean/ContactVo';
import AlphabetIndexerPresenter from '../alphabetindex/AlphabetIndexerPresenter';
import { FavoriteBean } from '../../../model/bean/FavoriteBean';
import MergedCallLog from '../../../../../../../feature/call/src/main/ets/entity/MergedCallLog';
class CallLogTempObj{
public checked:boolean = false;
public phoneNumber:number = 0;
public displayName:string = '';
public quickSearchKey:string = '';
}
class Contact{
public contactId:string = '';
public phoneNumbers:[] = [];
}
class ContactObj{
}
class PhoneNumber{
public checked:boolean = false;
}
class CheckedVo{
public name:string = '';
public number:number = 0;
constructor(name:string,number:number) {
this.name = name;
this.number = number
}
}
class FavoriteForm{
}
const TAG = 'BatchSelectContactsPresenter ';
/**
* Selecting a contact list by SMS
*/
interface GeneratedObjectLiteralInterface_2 {
contactObjects: string;
}
interface GeneratedObjectLiteralInterface_3 {
parameters: GeneratedObjectLiteralInterface_2;
}
interface GeneratedObjectLiteralInterface_4 {
resultCode: number;
want: GeneratedObjectLiteralInterface_3;
}
interface GeneratedObjectLiteralInterface_1 {
contactObjects: string;
}
interface GeneratedObjectLiteralInterface_5 {
parameters: GeneratedObjectLiteralInterface_1;
}
interface GeneratedObjectLiteralInterface_6 {
resultCode: number;
want: GeneratedObjectLiteralInterface_5;
}
export default class BatchSelectContactsPresenter {
private static sInstance: BatchSelectContactsPresenter;
sizeType: SizeType = SizeType.LG;
selectCount: number = 0;
// Recent Call Records
callLogTemp: Array<any> = [];
contactsList: Array<any> = [];
searchContactList: Array<any> = [];
groupList: Array<any> = [];
callLogTemp: Array<ContactVo> = [];
contactsList: Array<ContactVo> = [];
searchContactList: Array<ContactVo> = [];
groupList: Array<ContactVo> = [];
emptyViewText: Resource = $r('app.string.no_recent_contacts');
controller: TabsController = new TabsController();
currentIndex: number = 0;
@@ -52,7 +111,7 @@ export default class BatchSelectContactsPresenter {
// Search Keyword
searchText: string = '';
// Selected data for the current populationkey:phone numbervalue:name and number
selectedNumberMap: Map<number, any> = new Map();
selectedNumberMap: Map<string,CheckedVo>=new Map();
// Whether to display the search list
searchLayoutShow: boolean = false;
selectDisabled: boolean = true;
@@ -63,10 +122,10 @@ export default class BatchSelectContactsPresenter {
initialIndex: number = 0;
recentSource: BatchSelectRecentSource = new BatchSelectRecentSource();
contactsSource: BatchSelectContactSource = new BatchSelectContactSource();
actionData: { [key: string]: any } = {};
actionData: object|null = null;
alphabetIndexPresenter: AlphabetIndexerPresenter = AlphabetIndexerPresenter.getInstance();
editContact: number = -1;
contactId: number;
contactId: number = -1;
/** Contact Temporary */
callId: string = '';
phones: string = '';
@@ -122,27 +181,25 @@ export default class BatchSelectContactsPresenter {
}
cancel() {
let parameters = {
let parameters: GeneratedObjectLiteralInterface_1 = {
contactObjects: ''
};
let result = {
let result: GeneratedObjectLiteralInterface_6 = {
resultCode: 0,
want: {
parameters: parameters
}
want: ({ parameters: parameters } as GeneratedObjectLiteralInterface_5)
};
// Selecting a contact for creating an SMS message
globalThis.context?.terminateSelfWithResult(result)
.then((data) => {
.then(() => {
HiLog.i(TAG, 'terminateSelfWithResult Operation succeeded: ');
})
.catch((error) => {
.catch((error: Error) => {
HiLog.e(TAG, 'Operation failed. Cause: %s', JSON.stringify(error.message));
});
}
resetInitialIndex(firstIndex: number) {
HiLog.i(TAG, 'resetInitialIndex firstIndex is %s', firstIndex);
HiLog.i(TAG, 'resetInitialIndex firstIndex is %s', firstIndex.toString());
this.initialIndex = firstIndex;
}
@@ -156,10 +213,10 @@ export default class BatchSelectContactsPresenter {
addFavoriteContacts() {
HiLog.i(TAG, 'addFavoriteContacts start.');
let checkedList = [];
this.contactsList.forEach((value) => {
let checkedList:string[] = [];
this.contactsList.forEach((value:ContactVo) => {
if (value.phoneNumbers.length > 0) {
value.phoneNumbers.forEach((values) => {
value.phoneNumbers.forEach((values:PhoneNumber) => {
if (values.checked === true) {
checkedList.push(value.contactId);
}
@@ -172,26 +229,24 @@ export default class BatchSelectContactsPresenter {
}
comfirm() {
let checkedList = [];
this.selectedNumberMap.forEach((value) => {
let checkedList:CheckedVo[] = [];
this.selectedNumberMap.forEach((value:CheckedVo) => {
checkedList.push(value);
});
let contacts = this.dealContactName(checkedList);
let parameters = {
let parameters: GeneratedObjectLiteralInterface_2 = {
contactObjects: JSON.stringify(contacts)
};
let result = {
let result: GeneratedObjectLiteralInterface_4 = {
resultCode: 0,
want: {
parameters: parameters
}
want: ({ parameters: parameters } as GeneratedObjectLiteralInterface_3)
};
// Selecting a contact for creating an SMS message
globalThis.context?.terminateSelfWithResult(result)
.then((data) => {
.then(() => {
HiLog.i(TAG, 'terminateSelfWithResult Operation succeeded ');
})
.catch((error) => {
.catch((error:Error) => {
HiLog.e(TAG, 'Operation failed. Cause: %s', JSON.stringify(error.message));
});
}
@@ -216,29 +271,21 @@ export default class BatchSelectContactsPresenter {
},
});
}
dealContactSelectId(checkedList) {
let contacts = [];
dealContactSelectId(checkedList:ContactVo[]) {
let contacts:ContactVo[] = [];
for (let item of checkedList) {
if (item.phoneNumbers) {
}
let contact = {
contactId: item.contactId,
};
contacts.push(contact);
contacts.push(new ContactVo(item.contactId,'','','','','',false,'',''));
}
return contacts;
}
dealContactName(checkedList) {
let contacts = [];
dealContactName(checkedList: CheckedVo[]) {
let contacts:CheckedVo[] = [];
for (let item of checkedList) {
let contact = {
contactName: item.name,
telephone: item.number
};
contacts.push(contact);
contacts.push(new CheckedVo(item.name,item.number));
}
return contacts;
}
@@ -381,7 +428,7 @@ export default class BatchSelectContactsPresenter {
}
onTabChange(tabIndex: number) {
HiLog.i(TAG, 'onTabChange tabIndex is %s', tabIndex);
HiLog.i(TAG, 'onTabChange tabIndex is %s', tabIndex.toString());
this.tabInfo.tabIndex = tabIndex;
this.refreshPageMessage();
}
@@ -405,18 +452,16 @@ export default class BatchSelectContactsPresenter {
}
onRecentItemClicked(index: number) {
HiLog.i(TAG, 'onRecentItemClicked index is %s', index);
this.checkStateChange(index, {
checked: !(this.callLogTemp[index].checked)
});
HiLog.i(TAG, 'onRecentItemClicked index is %s', index.toString());
this.checkStateChange(index,
new EventObj(0,0,!(this.callLogTemp[index].checked))
);
}
onSingleContactItemClick(num: number, name: string, item: ContactVo) {
HiLog.i(TAG, 'onSingleContactItemClick in ');
this.selectedNumberMap.set(num, {
name: name,
number: num
});
this.selectedNumberMap.set(num.toString(),
new CheckedVo(name,num));
if (0 === this.editContact || 1 === this.editContact || 2 === this.editContact) {
this.updateContact(item.contactId);
} else {
@@ -427,17 +472,14 @@ export default class BatchSelectContactsPresenter {
onContactItemClicked(index: number, indexChild: number) {
HiLog.i(TAG, 'onContactItemClicked index is ' + index);
HiLog.i(TAG, 'onContactItemClicked indexChild is ' + indexChild);
let event = {
contactIndex: index,
numberIndex: indexChild,
checked: this.searchLayoutShow ? !(this.searchContactList[index].phoneNumbers[indexChild].checked)
: !(this.contactsList[index].phoneNumbers[indexChild].checked)
}
let event = new EventObj(index,indexChild,this.searchLayoutShow ? !(this.searchContactList[index].
phoneNumbers[indexChild].checked)
: !(this.contactsList[index].phoneNumbers[indexChild].checked));
this.checkStateChange(index, event);
}
checkStateChange(index, event) {
HiLog.i(TAG, 'checkStateChange event: ' + JSON.stringify(event));
checkStateChange(index:number, event:EventObj) {
HiLog.i(TAG, 'checkStateChange event: ' + JSON.stringify(event));
switch (this.tabInfo.tabIndex) {
case 0:
this.changeCallLogItemState(index, event);
@@ -451,12 +493,12 @@ export default class BatchSelectContactsPresenter {
this.refreshPageMessage();
}
changeContactState(event) {
changeContactState(event:EventObj) {
this.checkStateChange(event.contactIndex, event);
}
changeCallLogItemState(index, event) {
HiLog.i(TAG, 'changeCallLogItemState event : ' + JSON.stringify(event));
changeCallLogItemState(index:number, event:EventObj) {
HiLog.i(TAG, 'changeCallLogItemState event : ' + JSON.stringify(event));
if (this.callLogTemp[index]) {
this.callLogTemp[index].checked = event.checked;
this.recentSource.refreshSpecificOne(index, event.checked)
@@ -471,7 +513,7 @@ export default class BatchSelectContactsPresenter {
}
}
changeContactsItemState(index, event) {
changeContactsItemState(index:number, event:EventObj) {
HiLog.i(TAG, 'SHOW changeContactsItemState searchLayoutShow');
let contactId = '';
if (!this.contactsInfo.searchLayoutShow) {
@@ -482,7 +524,7 @@ export default class BatchSelectContactsPresenter {
this.checkContactsCount(event, contactId);
}
checkContactsCount(event, contactId) {
checkContactsCount(event:EventObj, contactId:string) {
HiLog.i(TAG, 'SHOW checkContactsCount searchLayoutShow');
if (this.contactsInfo.searchLayoutShow) {
this.contactsInfo.searchContactList.forEach(element => {
@@ -494,7 +536,7 @@ export default class BatchSelectContactsPresenter {
element.phoneNumbers[event.numberIndex].checked = true;
this.contactsInfo.contactsNumberCount++;
this.addOrUpdateSelectedNumberMap(element.phoneNumbers[event.numberIndex].phoneNumber,
element.name.fullName, false, element.contactId);
element.name.fullName, false, element.contactId);
} else {
element.phoneNumbers[event.numberIndex].checked = false;
this.contactsInfo.contactsNumberCount--;
@@ -515,7 +557,7 @@ export default class BatchSelectContactsPresenter {
element.phoneNumbers[event.numberIndex].checked = true;
this.contactsInfo.contactsNumberCount++;
this.addOrUpdateSelectedNumberMap(element.phoneNumbers[event.numberIndex].phoneNumber,
element.name.fullName, false, element.contactId);
element.name.fullName, false, element.contactId);
} else {
element.phoneNumbers[event.numberIndex].checked = false;
this.contactsInfo.contactsNumberCount--;
@@ -536,7 +578,7 @@ export default class BatchSelectContactsPresenter {
* @param {Object} contact
* @return {boolean} truefalse
*/
checkIfNeedCount(contact) {
checkIfNeedCount(contact:ContactVo):boolean{
if (contact.phoneNumbers.length > 0) {
for (let index = 0; index < contact.phoneNumbers.length; index++) {
const element = contact.phoneNumbers[index];
@@ -547,6 +589,7 @@ export default class BatchSelectContactsPresenter {
} else {
return false;
}
return false;
}
// Header Count Refresh Function
@@ -606,19 +649,18 @@ export default class BatchSelectContactsPresenter {
this.allSelectTextStyle = $r('sys.color.ohos_id_color_primary');
}
addOrUpdateSelectedNumberMap(number, name, isCalllogs, keyOrId) {
addOrUpdateSelectedNumberMap(number:string, name:string, isCalllogs:boolean, keyOrId:string) {
HiLog.i(TAG, 'addOrUpdateSelectedNumberMap isCalllogs is ' + isCalllogs + ' , keyOrId is ' + keyOrId);
if (StringUtil.isEmpty(number)) {
return;
}
this.selectedNumberMap.set((keyOrId + number.replace(/\s+/g, '')), {
name: name,
number: number.replace(/\s+/g, '')
});
this.selectedNumberMap.set((keyOrId + number.replace(/\s+/g, '')),
new CheckedVo(name,Number.parseInt(number.replace(/\s+/g, '')))
);
this.updataConnectedContact(number, name, isCalllogs, keyOrId, true);
}
deleteSelectedNumber(number, name, isCalllogs, keyOrId) {
deleteSelectedNumber(number:string, name:string, isCalllogs:boolean, keyOrId:string) {
HiLog.i(TAG, 'deleteSelectedNumber isCalllogs is ' + isCalllogs + ' , keyOrId is ' + keyOrId);
if (StringUtil.isEmpty(number)) {
return;
@@ -627,7 +669,7 @@ export default class BatchSelectContactsPresenter {
this.updataConnectedContact(number, name, isCalllogs, keyOrId, false);
}
updataConnectedContact(number, name, isCalllogs, keyOrId, isAdd) {
updataConnectedContact(number:string, name:string, isCalllogs:boolean, keyOrId:string, isAdd:boolean) {
HiLog.i(TAG, 'updataConnectedContact isCalllogs is ' + isCalllogs + ' , keyOrId is ' + keyOrId);
if (isCalllogs) {
this.contactsList.forEach(element => {
@@ -677,9 +719,12 @@ export default class BatchSelectContactsPresenter {
* */
initCallLog() {
HiLog.i(TAG, 'initCallLog start !');
let tempMap = new Map();
let tempList: any[] = [];
let favoriteForm: any = {}
let tempMap = new Map<string,string>();
let tempList: ContactVo[] = [];
let favoriteForm: Favorite = {
favorite: 0,
editContact: 0
}
if (0 === this.addFavorite) {
favoriteForm.favorite = 0;
} else {
@@ -690,9 +735,9 @@ export default class BatchSelectContactsPresenter {
mergeRule: CallLogSetting.getInstance().getMergeRule(),
actionData: this.actionData,
favoriteForm: JSON.stringify(favoriteForm)
}, (data) => {
if (data.hasOwnProperty('callLogList') && !ArrayUtil.isEmpty(data.callLogList)) {
HiLog.i(TAG, 'data has callLogList key');
}, (data: DataObj) => {
if (!ArrayUtil.isEmpty(data.callLogList)) {
HiLog.i(TAG, 'data has callLogList key');
for (let i = 0; i < data.callLogList.length; i++) {
let element = data.callLogList[i];
let bgColorIndex = parseInt(element.id, 10) % (MorandiColor.Color.length);
@@ -702,7 +747,7 @@ export default class BatchSelectContactsPresenter {
// 重复的号码无需显示
if (!tempMap.has(StringUtil.removeSpace(element.phoneNumber))) {
tempList.push(element);
tempMap.set(element.phoneNumber, null);
tempMap.set(element.phoneNumber, '');
}
//Displays the 50 numbers that have generated the latest call records.
if (tempList.length > 50) {
@@ -742,7 +787,10 @@ export default class BatchSelectContactsPresenter {
*/
initContactsList() {
HiLog.i(TAG, 'initContactsList start!');
let favoriteForm: any = {}
let favoriteForm: Favorite = {
favorite: 0,
editContact: 0
}
if (0 === this.addFavorite) {
favoriteForm.favorite = 0;
} else {
@@ -752,12 +800,12 @@ export default class BatchSelectContactsPresenter {
globalThis.DataWorker.sendRequest('getAllContactWithPhoneNumbers', {
context: globalThis.context,
favoriteForm: JSON.stringify(favoriteForm)
}, (resultList) => {
}, (resultList:ContactVo[]) => {
HiLog.i(TAG, 'initContactsList resultList success ' + resultList.length);
let listTemp: any[] = [];
let listTemp: ContactVo[] = [];
if (!ArrayUtil.isEmpty(resultList)) {
for (let element of resultList) {
element.name = {};
element.name = new NameVo('','','');
element.name.fullName = element.emptyNameData;
element.name.namePrefix = element.namePrefix;
element.name.nameSuffix = element.nameSuffix;
@@ -789,7 +837,7 @@ export default class BatchSelectContactsPresenter {
*
* @param {Object} item contacts data
*/
initVariableSpan(item) {
initVariableSpan(item:ContactVo) {
// Initialize Variable Names
let matchString = StringUtil.getMatchedString(item.emptyNameData, this.searchText);
if (StringUtil.isEmpty(matchString) || StringUtil.isEmpty(this.searchText.trim())) {
@@ -819,9 +867,8 @@ export default class BatchSelectContactsPresenter {
}
}
}
getPhoneLabelNameById(phoneLabelId: string, phoneNumber) {
let labelName: Resource;
getPhoneLabelNameById(phoneLabelId: string, phoneNumber:string):Resource |undefined {
let labelName: Resource|undefined = undefined;
switch (parseInt(phoneLabelId, 10)) {
case 1:
labelName = $r('app.string.phone_type_mobile_expansion', phoneNumber);
@@ -857,6 +904,50 @@ export default class BatchSelectContactsPresenter {
}
}
class SelectedNumberObj{
name:string = '';
}
class DataObj{
callLogList:ContactVo[] = [];
}
class CallLog{
id:string = '';
portraitColor:MorandiColor = MorandiColor.Color;
suffix:string = '';
displayName:string = '';
checked:boolean = false;
phoneNumber:string = '';
}
class Favorite{
favorite:number = 0;
editContact:number = -1;
}
class ChildEle{
public checked:boolean = false;
public labelName:Resource |undefined = undefined;
public numType:string = '';
public phoneNumber:string = '';
}
class EventObj{
public fullName:string = '';
public namePrefix:string = '';
public nameSuffix:string = '';
checked:boolean = false;
contactIndex:number = 0;
numberIndex:number = 0;
constructor(contactIndex:number,numberIndex:number,checked:boolean) {
this.contactIndex = contactIndex;
this.numberIndex = numberIndex;
this.checked = checked;
}
}
export class TabInfo {
tabIndex: number = 0;
recentTotal: number = 0;
@@ -881,9 +972,9 @@ export class TabInfo {
* Data related to the contact list
*/
export class ContactsInfo {
searchContactList = [];
searchContactList :ContactVo[] = [];
// List of selected contacts, which will be used for big data.
selectedContactMap = new Map();
selectedContactMap = new Map<number,number>();
// Whether to display the search page
searchLayoutShow: boolean = false;
// Number of Matched Search Records
File diff suppressed because it is too large Load Diff
@@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { HiLog } from '../../../../../../common/src/main/ets/util/HiLog';
import { HiLog } from 'common/src/main/ets/util/HiLog';
import { StringUtil } from '../../../../../../common/src/main/ets/util/StringUtil';
import audio from '@ohos.multimedia.audio';
import router from '@ohos.router';
@@ -21,20 +21,26 @@ import PreferencesUtil from '../../util/PreferencesUtil';
import { PhoneNumber } from '../../../../../../feature/phonenumber/src/main/ets/PhoneNumber';
import IndexPresenter from '../IndexPresenter';
import CallRecordListDataSource from '../../model/bean/CallRecordListDataSource';
import { call } from '@kit.TelephonyKit';
import { FavoriteBean } from '../../model/bean/FavoriteBean';
const TAG = 'DialerPresenter';
const SECRET_CODE_START: string = '*#*#';
const SECRET_CODE_END: string = '#*#*';
const SECRET_CODE_START: string = '##';
const SECRET_CODE_END: string = '##';
/**
* dialer presenter
*/
interface GeneratedTypeLiteralInterface_1 {
state;
number;
}
export default class DialerPresenter {
private static mPresenter: DialerPresenter;
private _isCallStateChangeObserved = false;
readonly NUM_TEXT_MAX_LENGTH = 20;
readonly NUM_TEXT_MAXSIZE_LENGTH = 14;
readonly NUM_TEXT_FONT_SIZE_MAX = 38;
private timer: any = null;
private timer: number | null = null;
btnShow: boolean = true;
isEmergencyNum: boolean = false;
tele_number: string = '';
@@ -46,25 +52,22 @@ export default class DialerPresenter {
dialerButtonWidth = 48;
dialerButtonHeight = 48;
dialerRadius = 24;
refreshView: boolean;
callBtnClick: boolean;
refreshView: boolean = false;
callBtnClick: boolean = false;
secretCode: string = '';
isPalyAudioing: boolean = false;
mAllCallRecordListDataSource: CallRecordListDataSource = new CallRecordListDataSource();
callLogSearchList: any[] = [];
callLogSearchList: string[] = [];
static getInstance() {
if (this.mPresenter == null) {
this.mPresenter = new DialerPresenter();
if (DialerPresenter.mPresenter == null) {
DialerPresenter.mPresenter = new DialerPresenter();
}
return this.mPresenter;
return DialerPresenter.mPresenter;
}
aboutToAppear() {
if (!PreferencesUtil.isUsed() && !this._isCallStateChangeObserved) {
observer.on('callStateChange', (callback: {
state,
number,
}) => {
observer.on('callStateChange', (callback: GeneratedTypeLiteralInterface_1) => {
HiLog.i(TAG, 'callStateChange state' + callback.state);
if (callback.state === 0) {
HiLog.i(TAG, 'callback.state:' + callback.state);
@@ -82,7 +85,7 @@ export default class DialerPresenter {
}
}
editPhoneNumber(phoneNum): void {
editPhoneNumber(phoneNum:string): void {
if (StringUtil.isEmpty(phoneNum)) {
return;
}
@@ -91,7 +94,7 @@ export default class DialerPresenter {
this.all_number = phoneNum;
this.viewNumberTextProc();
this.deleteAddSpace();
// this.callHistorySearch()
// this.callHistorySearch()
}
onDestroy() {
@@ -101,14 +104,17 @@ export default class DialerPresenter {
* Change the font size when deleting a number.
*/
deleteTeleNum() {
// this.callHistorySearch()
let number: string = AppStorage.Get('tele_number');
// this.callHistorySearch()
let number: string|undefined = AppStorage.Get('tele_number');
if(number === undefined){
return;
}
if (this.all_number.length < this.NUM_TEXT_MAX_LENGTH) {
AppStorage.SetOrCreate('tele_number', this.all_number);
} else {
AppStorage.SetOrCreate('tele_number', this.all_number.substr(this.all_number.length - this.NUM_TEXT_MAX_LENGTH));
}
if (number.length > this.NUM_TEXT_MAXSIZE_LENGTH) {
if (number?.length > this.NUM_TEXT_MAXSIZE_LENGTH) {
this.tele_num_size = this.NUM_TEXT_FONT_SIZE_MAX * this.NUM_TEXT_MAXSIZE_LENGTH / number.length;
} else if (number.length <= this.NUM_TEXT_MAXSIZE_LENGTH) {
this.tele_num_size = this.NUM_TEXT_FONT_SIZE_MAX;
@@ -119,7 +125,10 @@ export default class DialerPresenter {
* Add formatting spaces when deleting a number.
*/
deleteAddSpace() {
let number: string = AppStorage.Get('tele_number');
let number: string|undefined = AppStorage.Get('tele_number');
if(number === undefined){
return;
}
let teleNumberNoSpace = StringUtil.removeSpace(number);
this.all_number = StringUtil.removeSpace(this.all_number);
if (teleNumberNoSpace.length > this.NUM_TEXT_MAXSIZE_LENGTH - 2) {
@@ -153,25 +162,24 @@ export default class DialerPresenter {
/*
* Check whether formatting spaces are required when entering a number.
*/
checkNeedNumberSpace(numText) {
let isSpace = /[\+;,#\*]/g;
let isRule = /^\+.*/;
if (isSpace.test(numText)) {
// If the number string contains special characters, no space is added.
if (isRule.test(numText)) {
return true;
} else {
return false;
}
}
return true;
checkNeedNumberSpace(numText:string) {
let isSpace = /[+;,#*]/g;
let isRule = /^+./;
if (isSpace.test(numText)) {
// If the number string contains special characters, no space is added.
if (isRule.test(numText)) {
return true;
} else {
return false;
}
dialing(phoneNumber, options?: any) {
this.editPhoneNumber('');
PhoneNumber.fromString(phoneNumber).dial(options).then((rst) => {
this.refresh();
});
}
return true;
}
dialing(phoneNumber:string, options?: call.DialOptions) {
this.editPhoneNumber('');
PhoneNumber.fromString(phoneNumber).dial(options).then((rst) => {
this.refresh();
});
}
/*
@@ -184,8 +192,8 @@ export default class DialerPresenter {
* Add a space when entering a number.
*/
ifNeedSpace() {
let needNumber: string = AppStorage.Get('tele_number');
switch (needNumber.length) {
let needNumber: string | undefined = AppStorage.Get('tele_number');
switch (needNumber?.length) {
case 3:
if (this.checkNeedNumberSpace(needNumber)) {
AppStorage.SetOrCreate('tele_number', needNumber + ' ');
@@ -204,10 +212,13 @@ export default class DialerPresenter {
*/
viewNumberTextProc() {
let numStringNoSpace_all = StringUtil.removeSpace(this.all_number);
let number: string = AppStorage.Get('tele_number');
let number: string | undefined = AppStorage.Get('tele_number');
AppStorage.SetOrCreate('tele_number', numStringNoSpace_all.length > this.NUM_TEXT_MAX_LENGTH ?
numStringNoSpace_all.substr(numStringNoSpace_all.length - this.NUM_TEXT_MAX_LENGTH) : number
);
if(number === undefined){
return;
}
if (number.length > this.NUM_TEXT_MAXSIZE_LENGTH) {
AppStorage.SetOrCreate('tele_number', StringUtil.removeSpace(number));
}
@@ -221,7 +232,7 @@ export default class DialerPresenter {
/*
* Play different audio resources based on key digits.
*/
playAudio(number) {
playAudio(number: string) {
switch (number.toString()) {
case '1':
this.tonePlayer(audio.ToneType.TONE_TYPE_DIAL_1);
@@ -263,8 +274,7 @@ export default class DialerPresenter {
HiLog.e(TAG, 'keytone src is error');
}
}
async tonePlayer(type) {
async tonePlayer(type:audio.ToneType) {
HiLog.i(TAG, 'TonePlayer type: ' + type);
let that = this;
let tonePlayer = null;
@@ -274,17 +284,17 @@ export default class DialerPresenter {
rendererFlags: 0
};
if (!this.isPalyAudioing) {
this.isPalyAudioing = true;
tonePlayer = await audio.createTonePlayer(audioRendererInfo);
await tonePlayer.load(type);
await tonePlayer.start();
setTimeout(async () => {
that.isPalyAudioing = false;
await tonePlayer.stop();
await tonePlayer.release();
}, 15)
}
if (!this.isPalyAudioing) {
this.isPalyAudioing = true;
tonePlayer = await audio.createTonePlayer(audioRendererInfo);
await tonePlayer.load(type);
await tonePlayer.start();
setTimeout(async () => {
that.isPalyAudioing = false;
await tonePlayer.stop();
await tonePlayer.release();
}, 15)
}
};
/*
@@ -296,8 +306,8 @@ export default class DialerPresenter {
params: {
updataShow: false,
phoneNumbers: [{
phoneNumber: AppStorage.Get('tele_number')
}]
phoneNumber: AppStorage.Get('tele_number')
}]
},
})
}
@@ -328,37 +338,7 @@ export default class DialerPresenter {
}
}
callHistorySearch() {
let teleNumber: string = AppStorage.Get('tele_number');
globalThis.DataWorker.sendRequest('getQueryT9PhoneNumbers', {
favoriteForm: JSON.stringify({favorite:{teleNumber:teleNumber.replace(/\s*/g,'')}}),
context: globalThis.context
}, (result) => {
let nameArray = [];
for (let i = 0; i < result.length; i++) {
nameArray.push(result[i].showName);
result[i].displayName = result[i]?.showName || result[i]?.phoneNumbers[0]?.phoneNumber || '';
result[i].phoneNumber = result[i]?.phoneNumbers[0]?.phoneNumber || '';
}
const queryCall = {context: globalThis.context,mergeRule: '', actionData: {teleNumber:teleNumber.replace(/\s*/g,''), nameArray}};
globalThis.DataWorker?.sendRequest('getCallHistorySearch', queryCall, (data) => {
this.callLogSearchList = [];
if(data.callLogList.length > 0 || result.length > 0){
this.callLogSearchList = [...this.callLogSearchList,...result]
for (let i = 0; i < data.callLogList.length; i++) {
const displayName = data?.callLogList[i]?.displayName || data?.callLogList[i]?.phoneNumber;
if(!nameArray.includes(displayName)){
nameArray.push(displayName)
this.callLogSearchList.push({...data.callLogList[i], displayName});
}
}
}
this.mAllCallRecordListDataSource.refreshAll(this.callLogSearchList.sort((a: any, b: any)=> (a.count || 0) - (b.count || 0)));
})
})
}
jumpToContactDetail(phoneNumber) {
jumpToContactDetail(phoneNumber:string) {
router.pushUrl(
{
url: 'pages/contacts/details/ContactDetail',
@@ -18,10 +18,13 @@ import { PhoneNumber } from '../../../../../../../feature/phonenumber/src/main/e
import router from '@ohos.router';
import { CallLogRepository } from '../../../../../../../feature/call';
import { ContactRepository } from '../../../../../../../feature/contact/src/main/ets/repo/ContactRepository';
import CallRecordListDataSource from './../../../model/bean/CallRecordListDataSource';
import CallRecordListDataSource from '../../../model/bean/CallRecordListDataSource';
import CallLogSetting from '../../../../../../../feature/call/src/main/ets/CallLogSetting'
import DialerPresenter from '../../../presenter/dialer/DialerPresenter';
import WorkerWrapper from '../../../workers/base/WorkerWrapper';
import { call } from '@kit.TelephonyKit';
import { CallInfoGetParamsInCallback } from '../../../model/type/ContactParams';
import LooseObject from '../../../model/type/LooseObject';
const TAG = 'CallRecordPresenter'
const DELAY_TIME: number = 1000;
@@ -34,18 +37,19 @@ export default class CallRecordPresenter {
isShow: boolean = false;
page: number = 0;
limit: number = 0;
context: Context;
worker: WorkerWrapper;
refreshState: () => void
context: Context | undefined = undefined;
worker: WorkerWrapper | undefined;
public refreshState: (business: string) => void = () => {
};
loading: boolean = false;
callLogListPages: Array<number> = [];
missedListPages: Array<number> = [];
callLogListPages: Array = [];
missedListPages: Array = [];
callLogIndex: number = 0;
missedIndex: number = 0;
tabIndex: number = 0;
initStarted: boolean = false;
taskId: number = -1;
onCallsChange = () => {
public onCallsChange = () => {
HiLog.i(TAG, 'onCallsChange refresh');
this.setDelayTask();
}
@@ -54,7 +58,7 @@ export default class CallRecordPresenter {
this.setDelayTask();
}
static getInstance() {
static getInstance(): CallRecordPresenter {
if (globalThis.presenterManager?.callRecordPresenter) {
return globalThis.presenterManager.callRecordPresenter;
}
@@ -64,11 +68,11 @@ export default class CallRecordPresenter {
return CallRecordPresenter.mPresenter;
}
bindUI(refreshState?: () => void) {
bindUI(refreshState: (businessStr: string) => void) {
this.refreshState = refreshState;
}
onCreate(context: Context, worker: WorkerWrapper) {
onCreate(context: Context, worker: WorkerWrapper | undefined) {
this.context = context;
this.worker = worker;
CallLogRepository.getInstance().registerDataChangeObserver(this.onCallsChange);
@@ -145,7 +149,7 @@ export default class CallRecordPresenter {
}
}
setTabIndex(index) {
setTabIndex(index: number) {
if (this.tabIndex != index) {
this.tabIndex = index;
this.setTabShow();
@@ -210,31 +214,31 @@ export default class CallRecordPresenter {
refreshPage(page: number, limit: number, callback?: () => void) {
this.loading = true;
let actionData: any = {};
let actionData: LooseObject = {};
actionData.page = page;
actionData.limit = limit;
let favoriteForm: any = {};
let favoriteForm: LooseObject = {};
favoriteForm.favorite = -1;
this.worker?.sendRequest('getAllCalls', {
context: this.context,
mergeRule: CallLogSetting.getInstance().getMergeRule(),
actionData: actionData,
favoriteForm: JSON.stringify(favoriteForm)
}, (data) => {
let dateLength = data.callLogList.length;
HiLog.i(TAG, `refreshPage ${page} and getAllCalls, length is ` + dateLength);
if (Array.prototype.isPrototypeOf(data.callLogList)) {
}, (data: CallInfoGetParamsInCallback) => {
let dateLength: number = data.callLogList.length;
HiLog.i(TAG, `refreshPage ${page} and getAllCalls, length is + dateLength`);
if (Array.isArray(data.callLogList)) {
this.mAllCallRecordListDataSource.refresh(this.callLogIndex, this.callLogListPages[page-1], data.callLogList);
this.mDialerPresent.refresh();
}
if (Array.prototype.isPrototypeOf(data.missedList)) {
if (Array.isArray(data.missedList)) {
this.mMissCallRecordListDataSource.refresh(this.missedIndex, this.missedListPages[page - 1], data.missedList);
}
this.callLogListPages[page-1] = dateLength;
this.callLogIndex += this.callLogListPages[page-1];
this.missedListPages[page - 1] = data.missedList.length;
this.missedIndex += this.missedListPages[page - 1];
if (data.callLogTotal < limit) {
if (data.callLogList.length < limit) {
HiLog.i(TAG, 'CallLogs load completed: ' + this.mAllCallRecordListDataSource.totalCount());
if (this.callLogListPages.length > page) {
this.callLogListPages.splice(page, this.callLogListPages.length - page);
@@ -249,7 +253,7 @@ export default class CallRecordPresenter {
this.mMissCallRecordListDataSource.remove(this.missedIndex, this.mMissCallRecordListDataSource.totalCount() - this.missedIndex);
}
if (this.refreshState) {
this.refreshState();
this.refreshState('limitDataRefresh requestItem ');
}
this.page = 0;
this.callLogIndex = 0;
@@ -257,7 +261,7 @@ export default class CallRecordPresenter {
this.loading = false;
} else {
if (this.refreshState) {
this.refreshState();
this.refreshState('limitInterceptionCallsDataRefresh requestItem ');
}
if (this.taskId === -1) {
this.page = page + 1;
@@ -276,15 +280,15 @@ export default class CallRecordPresenter {
})
}
dialing(phoneNumber, options?: any) {
dialing(phoneNumber: string, options?: call.DialOptions) {
PhoneNumber.fromString(phoneNumber).dial(options);
}
deleteCallLog(id, index?) {
deleteCallLog(id: number[], index?: number) {
globalThis.DataWorker.sendRequest('deleteCallLogsById', {
context: globalThis.context,
ids: id
}, (data) => {
}, () => {
HiLog.i(TAG, 'deleteCallLog Success');
});
if (index != undefined) {
@@ -296,7 +300,7 @@ export default class CallRecordPresenter {
}
}
jumpToContactDetail(phoneNumber) {
jumpToContactDetail(phoneNumber: string) {
router.push(
{
url: 'pages/contacts/details/ContactDetail',
@@ -308,7 +312,7 @@ export default class CallRecordPresenter {
)
}
saveCallRecordExistingContact(phoneNumber, callId){
saveCallRecordExistingContact(phoneNumber: string, callId: string) {
HiLog.i(TAG, 'saveCallRecordExistingContact start.');
router.pushUrl({
url: 'pages/contacts/batchselectcontacts/SingleSelectContactPage',
@@ -18,6 +18,11 @@ import { HiLog, sharedPreferencesUtils } from '../../../../../../common';
import { FavoriteBean } from '../../model/bean/FavoriteBean';
import FavoriteDataSource from '../../model/bean/FavoriteDataSource';
class FavoriteFormObj{
favoriteOrder:number = 0;
id: string = '';
}
const TAG = 'EditFavoriteListPresenter ';
/**
@@ -34,8 +39,7 @@ export default class EditFavoriteListPresenter {
usuallyList: FavoriteBean[] = [] ;
isEdit: boolean = false;
isEditSelect: string[] = [];
selectFavoriteBean: FavoriteBean;
selectFavoriteBean: FavoriteBean | undefined;
private constructor() {
}
@@ -145,15 +149,18 @@ export default class EditFavoriteListPresenter {
HiLog.i(TAG, 'moveSortFavorite start.');
let favoriteLength: number = favoriteList.length;
for (let i = 0; i < favoriteLength; i++) {
let favoriteForm: any = {}
let favoriteForm: FavoriteFormObj = {
favoriteOrder: 0,
id: ''
}
favoriteForm.id = favoriteList[i].contactId;
favoriteForm.favoriteOrder = i + 1;
globalThis.DataWorker.sendRequest('moveSortFavorite', {
context: globalThis.context,
favoriteForm: JSON.stringify(favoriteForm)
}, (result) => {
}, () => {
if (favoriteLength === (i + 1)) {
AppStorage.SetOrCreate<number>('editFavoriteDrag', 1);
AppStorage.SetOrCreate('editFavoriteDrag', 1);
router.back();
}
})
@@ -165,10 +172,9 @@ export default class EditFavoriteListPresenter {
* Cancel Editing
*/
cancelEditFavorite() {
AppStorage.SetOrCreate<number>('cancelEditFavorite', 2);
AppStorage.SetOrCreate('cancelEditFavorite', 2);
router.back();
}
aboutToAppear() {
HiLog.i(TAG, 'EditFavoriteListPresenter aboutToAppear!');
this.isShow = true;
@@ -36,11 +36,12 @@ export default class FavoriteListPresenter {
favoriteDataSource: FavoriteDataSource = new FavoriteDataSource();
isShow: boolean = false;
isEditSelectList: string[] = [];
usuallySelectArray = new ArrayList();
usuallySelectArray = new ArrayList()
displayNameList: string[] = [];
usuallyDisplayNameParameterList: string[] = [];
usuallyPhoneParameterList: string[] = [];
usuallyTotalCount: number = 0;
lastUsedSlotId?: number = -1;
onContactChange = () => {
HiLog.i(TAG, 'onFavoriteChange refresh');
this.requestItem();
@@ -59,12 +60,12 @@ export default class FavoriteListPresenter {
refreshFavorite() {
HiLog.i(TAG, 'refreshFavorite start.');
let actionData: any = {};
let actionData: Record<string, number> = {};
actionData.favorite = 1
globalThis.DataWorker.sendRequest('getAllFavorite', {
actionData: actionData,
context: globalThis.context
}, (result) => {
}, (result:FavoriteBean[]) => {
HiLog.i(TAG, 'refreshFavorite sc.');
this.favoriteList = [];
this.favoriteList = result;
@@ -79,12 +80,12 @@ export default class FavoriteListPresenter {
refreshUsually() {
HiLog.i(TAG, 'refreshUsually start.');
let actionData: any = {};
let actionData: Record<string, number> = {};
actionData.favorite = 0;
globalThis.DataWorker.sendRequest('getAllUsually', {
actionData: actionData,
context: globalThis.context
}, (result) => {
}, (result:FavoriteBean[]) => {
HiLog.i(TAG, 'refreshUsually sc.');
let resultCount = result.length;
if (resultCount > 0) {
@@ -154,13 +155,13 @@ export default class FavoriteListPresenter {
displayName: displayNameList,
usuallyPhone: usuallyPhoneList,
context: globalThis.context
}, (result) => {
}, (result:FavoriteBean[]) => {
let totalCount = result.length;
HiLog.i(TAG, 'getDisplayNamesFindUsually sc');
if (null != result && totalCount > 0) {
this.favoriteList = this.favoriteList.concat(result);
this.refreshFavoriteList(this.favoriteList);
} else {
} else {
this.refreshFavoriteList(this.favoriteList);
}
})
@@ -176,7 +177,7 @@ export default class FavoriteListPresenter {
this.favoriteList[this.favoriteCount].isUsuallyShow = true;
}
this.favoriteDataSource.refresh(favoriteList);
let innerEvent = {
let innerEvent:emitter.InnerEvent = {
eventId: 100,
priority: emitter.EventPriority.HIGH
};
@@ -186,7 +187,6 @@ export default class FavoriteListPresenter {
}
});
}
goContactDetail(contactId: string) {
HiLog.i(TAG, 'goContactDetail start.');
router.pushUrl(
@@ -215,13 +215,14 @@ export default class FavoriteListPresenter {
async onPageShow() {
HiLog.i(TAG, 'onPageShow!');
this.isShow = true;
let editFavoriteDrag: number = AppStorage.Get<number>('editFavoriteDrag');
let addFavoriteContactData: string[] = AppStorage.Get<Array<string>>('addFavoriteContactData');
let deleteFavoriteContactData: string[] = AppStorage.Get<Array<string>>('deleteFavoriteContactData');
let cancelEditFavorite: number = AppStorage.Get<number>('cancelEditFavorite');
let editFavoriteDrag: number|undefined = AppStorage.Get('editFavoriteDrag');
let addFavoriteContactData: string[]|undefined = AppStorage.Get<Array<string>>('addFavoriteContactData');
let deleteFavoriteContactData: string[]|undefined = AppStorage.Get<Array<string>>('deleteFavoriteContactData');
let cancelEditFavorite: number|undefined = AppStorage.Get('cancelEditFavorite');
let that = this;
let usuallySelectData: Promise<string> = new Promise(async (resolve) => {
let usuallySelectDisplayNameList: string = <string> await sharedPreferencesUtils.getFromPreferences('usuallySelectDisplayNameList', '');
let usuallySelectDisplayNameList: string =
await sharedPreferencesUtils.getFromPreferences('usuallySelectDisplayNameList', '') as string;
if ('' !== usuallySelectDisplayNameList) {
let usuallySelectDisplayList: string[] = JSON.parse(usuallySelectDisplayNameList);
let count = usuallySelectDisplayList.length;
@@ -238,14 +239,14 @@ export default class FavoriteListPresenter {
if (editFavoriteDrag !== undefined && editFavoriteDrag === 1) {
HiLog.i(TAG, 'onPageShow editFavoriteDrag!');
this.requestItem();
AppStorage.SetOrCreate<number>('editFavoriteDrag', 0);
AppStorage.SetOrCreate('editFavoriteDrag', 0);
} else if (addFavoriteContactData !== undefined && addFavoriteContactData.length > 0) {
HiLog.i(TAG, 'onPageShow addFavoriteContactData!');
this.addFavoriteInfo(addFavoriteContactData);
AppStorage.SetOrCreate<Array<string>>('addFavoriteContactData', []);
} else if (cancelEditFavorite !== undefined && 2 === cancelEditFavorite) {
HiLog.i(TAG, 'onPageShow cancelEditFavorite!');
AppStorage.SetOrCreate<number>('cancelEditFavorite', 0);
AppStorage.SetOrCreate('cancelEditFavorite', 0);
} else if (deleteFavoriteContactData !== undefined && deleteFavoriteContactData.length > 0) {
HiLog.i(TAG, 'onPageShow deleteFavoriteContactData!');
this.deleteFavorite(deleteFavoriteContactData);
@@ -273,9 +274,10 @@ export default class FavoriteListPresenter {
async usuallySelectData(): Promise<string> {
let that = this;
//let usuallySelectData: Promise<string>
//let usuallySelectData: Promise
return await new Promise(async (resolve) => {
let usuallySelectDisplayNameList: string = <string> await sharedPreferencesUtils.getFromPreferences('usuallySelectDisplayNameList', '');
let usuallySelectDisplayNameList: string =
await sharedPreferencesUtils.getFromPreferences('usuallySelectDisplayNameList', '') as string;
if ('' !== usuallySelectDisplayNameList) {
let usuallySelectDisplayList: string[] = JSON.parse(usuallySelectDisplayNameList);
let count = usuallySelectDisplayList.length;
@@ -317,13 +319,13 @@ export default class FavoriteListPresenter {
HiLog.i(TAG, 'addFavoriteInfo start.');
let selectLength: number = selectFavoriteIdList.length;
for (let i = 0; i < selectLength; i++) {
let favoriteForm: any = {}
let favoriteForm: Record<string, string> = {};
favoriteForm.id = selectFavoriteIdList[i];
favoriteForm.favorite = 1;
favoriteForm.favorite = '1';
globalThis.DataWorker.sendRequest('updateFavorite', {
context: globalThis.context,
favoriteForm: JSON.stringify(favoriteForm)
}, (arg) => {
}, () => {
if (i === (selectLength - 1)) {
AppStorage.SetOrCreate<Array<string>>('addFavoriteContactData', [])
HiLog.i(TAG, 'addFavoriteInfo success refresh.');
@@ -338,13 +340,13 @@ export default class FavoriteListPresenter {
HiLog.i(TAG, 'deleteFavorite start.');
let favoriteLength: number = deleteFavoriteIdList.length;
for (let i = 0; i < favoriteLength; i++) {
let favoriteForm: any = {};
let favoriteForm: Record<string, string> = {};
favoriteForm.id = deleteFavoriteIdList[i];
favoriteForm.favorite = 0;
favoriteForm.favorite = '0';
globalThis.DataWorker.sendRequest('updateFavorite', {
context: globalThis.context,
favoriteForm: JSON.stringify(favoriteForm)
}, (arg) => {
}, (arg:string) => {
if(i === (favoriteLength - 1)){
HiLog.i(TAG, 'deleteFavoriteInfo success.');
AppStorage.SetOrCreate<Array<string>>('deleteFavoriteContactData', [])
+29 -14
View File
@@ -14,6 +14,7 @@
*/
import i18n from '@ohos.i18n';
import { GetLunarDateRe } from '../model';
const YEAR_CONVERT: number = 2697;
const YEAR_CYCLE: number = 60;
@@ -26,28 +27,46 @@ const NUM_CHAR = ['零', '一', '二', '三', '四', '五', '六', '七', '八',
class CalendarUtil {
//公历转农历
getLunarDate(date: Date) {
let calendar = i18n.getCalendar('zh-CN', 'chinese');
let calendar: i18n.Calendar = i18n.getCalendar('zh-CN', 'chinese');
calendar.setTime(date);
const lunarMonth = calendar.get('month');
const lunarDay = calendar.get('date');
let lunarYear = calendar.get('era') * YEAR_CYCLE + calendar.get('year') - YEAR_CONVERT;
return {
let lunarYear: number = calendar.get('era') * YEAR_CYCLE + calendar.get('year') - YEAR_CONVERT;
let lunarMonth: number = calendar.get('month');
let lunarDay: number = calendar.get('date');
let calendarHansPrev: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendarHansPrev.set(date.getFullYear(), date.getMonth(),
date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
calendarHansPrev.add('month', 1);
let nextMonthDate: Date = new Date(calendarHansPrev.get('year'), calendarHansPrev.get('month'),
calendarHansPrev.get('date'), calendarHansPrev.get('hour'), calendarHansPrev.get('minute'),
calendarHansPrev.get('second'));
calendar.setTime(nextMonthDate);
let lunarMonthNext: number = calendar.get('month');
let isLeapMonth: boolean = (lunarMonth === lunarMonthNext);
let getLunarDateReData: GetLunarDateRe = {
year: lunarYear,
month: lunarMonth,
day: lunarDay
day: lunarDay,
isLeapMonth
}
return getLunarDateReData
}
formatLunarDate(lunar: any) {
formatLunarDate(lunar: GetLunarDateRe, retYear:boolean = true) {
if (!lunar) {
return '';
}
let result: string = '';
if (lunar.year) {
if (lunar.year && retYear) {
result += `${lunar.year}年`
}
if (lunar.month != undefined) {
result += `${LUNAR_MONTH[lunar.month]}月`
if (lunar.isLeapMonth) {
result += `闰 + ${LUNAR_MONTH[lunar.month - 1]}月`
} else {
result += `${LUNAR_MONTH[lunar.month]}月`
}
}
if (lunar.day) {
result += ` ${LUNAR_DAY[lunar.day - 1]}`
@@ -56,8 +75,4 @@ class CalendarUtil {
}
}
export default new CalendarUtil();
export default new CalendarUtil();
+8 -8
View File
@@ -12,14 +12,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export default {
class PreferencesUtil {
isUsed() {
return AppStorage.Get('IsUsed') == 1;
},
return AppStorage.Get('IsUsed') == 1;
}
setIsUsed(isUsed) {
setIsUsed(isUsed: boolean) {
AppStorage.SetOrCreate('IsUsed', isUsed);
},
}
}
}
export default new PreferencesUtil()
+26
View File
@@ -0,0 +1,26 @@
/**
Copyright (c) 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import resourceManager from '@ohos.resourceManager';
import common from '@ohos.app.ability.common';
export class ResourceUtil {
static resourceToString(title: Resource, context: common.UIAbilityContext): string {
let resource: resourceManager.Resource = {
bundleName: title.bundleName,
moduleName: title.moduleName,
id: title.id
}
let titleString = context.resourceManager.getStringSync(resource.id);
return titleString;
}
}
+13 -13
View File
@@ -14,13 +14,12 @@
*/
import settings from '@ohos.settings';
import CalendarUtil from './CalendarUtil'
export default {
numberFormatDateString(year : number, month : number, day : number) : string {
export default class StringFormatUtil {
static numberFormatDateString(year : number, month : number, day : number) : string {
return year + '-' + month + '-' + day;
},
}
stringFormatDateResource(data: string, lunar: boolean): Resource | string {
static stringFormatDateResource(data: string, lunar: boolean): Resource | string {
let year: number = parseInt(data.substr(0, data.indexOf('-')));
let month: number = parseInt(data.substr(data.indexOf('-') + 1, data.lastIndexOf('-')));
let day: number = parseInt(data.substr(data.lastIndexOf('-') + 1, data.length));
@@ -28,11 +27,11 @@ export default {
return CalendarUtil.formatLunarDate(CalendarUtil.getLunarDate(new Date(year, month - 1, day)))
}
return $r('app.string.yearMonthDay', year, month, day);
},
}
judgeSysTime(context?: Context) {
static judgeSysTime(context?: Context): string {
return settings.getValueSync((context ? context : globalThis.context) as Context, settings.date.TIME_FORMAT, '24');
},
}
/**
* Obtain the description of the time within a day based on the hour.
@@ -40,7 +39,7 @@ export default {
* @param {number} hour
* @return {string} Time node
*/
getDayMessage(hour, minutes) {
static getDayMessage(hour: number, minutes: string) :Resource|undefined{
if (hour >= 0 && hour < 5) {
return $r('app.string.time_early_morning', hour, minutes);
}
@@ -51,18 +50,19 @@ export default {
return $r('app.string.time_noon', hour, minutes);
}
if (hour >= 13 && hour < 17) {
return $r('app.string.time_afternoon', (parseInt(hour) - 12).toString(), minutes);
return $r('app.string.time_afternoon', (hour - 12).toString(), minutes);
}
if (hour >= 17 && hour < 19) {
return $r('app.string.time_nightfall', (parseInt(hour) - 12).toString(), minutes);
return $r('app.string.time_nightfall', (hour - 12).toString(), minutes);
}
if (hour >= 19 && hour < 22) {
return $r('app.string.time_night', (parseInt(hour) - 12).toString(), minutes);
return $r('app.string.time_night', (hour - 12).toString(), minutes);
}
if (hour >= 22 && hour < 24) {
return $r('app.string.time_middle_night', (parseInt(hour) - 12).toString(), minutes);
return $r('app.string.time_middle_night', (hour - 12).toString(), minutes);
}
return undefined;
}
}
+51 -42
View File
@@ -21,11 +21,18 @@ import { ThreadWorkerGlobalScope } from '@ohos.worker';
import CallLog from '../model/calllog/CalllogModel';
import { CallLogRepository } from '../../../../../feature/call';
import { ContactRepository } from '../../../../../feature/contact';
import { CallLog as CallLogClass } from '../../../../../feature/call/src/main/ets/entity/CallLog';
import ContactAbilityModel from '../model/ContactAbilityModel';
import LooseObject from '../model/type/LooseObject';
import { ContactInfo } from '../model/bean/ContactInfo';
import { CallInfoGetParamsInCallback, ContactInfoGetParamsInCallback } from '../model/type/ContactParams';
import { ContactVo } from '../model/bean/ContactVo';
import { ContactReturnObj } from '../model/type';
import { FavoriteBean } from '../model/bean/FavoriteBean';
import { SearchContactsBean } from '../model/bean/SearchContactsBean';
const TAG = 'DataWorkerTask'
export enum DataWorkerConstant {
'deleteCallLogsById',
'getAllCalls',
@@ -48,13 +55,13 @@ export enum DataWorkerConstant {
}
export class DataWorkerTask extends WorkerTask {
private static sInstance: DataWorkerTask = undefined;
private static sInstance?: DataWorkerTask = undefined;
private constructor(workerPort: ThreadWorkerGlobalScope) {
private constructor(workerPort?: ThreadWorkerGlobalScope) {
super(workerPort)
}
static getInstance(workerPort: ThreadWorkerGlobalScope) {
static getInstance(workerPort?: ThreadWorkerGlobalScope) {
HiLog.i(TAG, 'getInstance in.')
if (DataWorkerTask.sInstance == undefined || DataWorkerTask.sInstance.workerPort == undefined) {
DataWorkerTask.sInstance = new DataWorkerTask(workerPort);
@@ -62,104 +69,106 @@ export class DataWorkerTask extends WorkerTask {
return DataWorkerTask.sInstance;
}
runInWorker(request: string, callBack: (v?: any) => void, param?: any) {
runInWorker(request: string, callBack: Function, param?: LooseObject) {
HiLog.i(TAG, `runInWorker ${request}`)
switch (request) {
case DataWorkerConstant[DataWorkerConstant.getAllCalls]:
CallLog.getAllCalls(JSON.parse(param.favoriteForm), param.actionData, param.mergeRule, (data) => {
CallLog.getAllCalls(JSON.parse(param?.favoriteForm), param?.actionData, param?.mergeRule,
(data: CallInfoGetParamsInCallback) => {
HiLog.i(TAG, `getAllCalls result: ${JSON.stringify(data).length}`)
callBack(data);
}, param.context);
}, param?.context);
break;
case DataWorkerConstant[DataWorkerConstant.findByNumberIn]:
CallLogRepository.getInstance().init(param.context);
CallLogRepository.getInstance().findByNumberIn(param.numbers, (resultList) => {
CallLogRepository.getInstance().init(param?.context);
CallLogRepository.getInstance().findByNumberIn(param?.actionData, (resultList) => {
callBack(resultList);
});
break
case DataWorkerConstant[DataWorkerConstant.deleteContactById]:
ContactRepository.getInstance().init(param.context);
ContactRepository.getInstance().deleteById(param.contactId, (result) => {
ContactRepository.getInstance().init(param?.context);
ContactRepository.getInstance().deleteById(param?.contactId, (result: number | undefined) => {
HiLog.i(TAG, `deleteContactById result ${result}`)
callBack(result);
});
break;
case DataWorkerConstant[DataWorkerConstant.deleteCallLogsById]:
CallLogRepository.getInstance().init(param.context);
CallLogRepository.getInstance().deleteByIdIn(param.ids, (result) => {
CallLogRepository.getInstance().init(param?.context);
CallLogRepository.getInstance().deleteByIdIn(param?.ids, (result) => {
callBack(result);
})
break;
case DataWorkerConstant[DataWorkerConstant.addContact]:
const contactInfoAfter = JSON.parse(param.contactInfoAfter)
ContactAbilityModel.addContact(contactInfoAfter, (arg) => {
const contactInfoAfter: ContactInfo = JSON.parse(param?.contactInfoAfter)
ContactAbilityModel.addContact(contactInfoAfter, (arg: string[]) => {
callBack(arg);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getAllContact]:
ContactAbilityModel.getAllContact(param.actionData, (result) => {
ContactAbilityModel.getAllContact(param?.actionData, (result: ContactVo[]) => {
callBack(result);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getAllContactWithPhoneNumbers]:
ContactAbilityModel.getAllContactWithPhoneNumbers((resultList) => {
ContactAbilityModel.getAllContactWithPhoneNumbers((resultList: ContactInfoGetParamsInCallback) => {
callBack(resultList);
}, JSON.parse(param.favoriteForm), param.context)
}, JSON.parse(param?.favoriteForm), param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getContactById]:
ContactAbilityModel.getContactById(param.contactId, result => {
ContactAbilityModel.getContactById(param?.contactId, (result: ContactReturnObj) => {
callBack(result);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getIdByTelephone]:
ContactAbilityModel.getIdByTelephone(param.phoneNumber, (contactId) => {
ContactAbilityModel.getIdByTelephone(param?.phoneNumber, (contactId: string) => {
callBack(contactId);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.updateContact]:
ContactAbilityModel.updateContact(null, JSON.parse(param.contactInfoAfter), (arg) => {
ContactAbilityModel.updateContact(null, JSON.parse(param?.contactInfoAfter), (arg: string) => {
callBack(arg);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.updateFavorite]:
ContactAbilityModel.updateFavorite(null, JSON.parse(param.favoriteForm), (arg) => {
ContactAbilityModel.updateFavorite(null, JSON.parse(param?.favoriteForm), (arg: number) => {
callBack(arg);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getAllFavorite]:
ContactAbilityModel.getAllFavorite(param.actionData, (result) => {
ContactAbilityModel.getAllFavorite((result: FavoriteBean[]) => {
callBack(result);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getAllUsually]:
ContactAbilityModel.getAllUsually(param.actionData, (result) => {
ContactAbilityModel.getAllUsually((result: CallLogClass[]) => {
callBack(result);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getDisplayNamesFindUsually]:
ContactAbilityModel.getDisplayNamesFindUsually(param.displayName, param.usuallyPhone, (result) => {
ContactAbilityModel.getDisplayNamesFindUsually(param?.displayName, param?.usuallyPhone,
(result: FavoriteBean[]) => {
callBack(result);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.moveSortFavorite]:
ContactAbilityModel.moveSortFavorite(null, JSON.parse(param.favoriteForm), (result) => {
ContactAbilityModel.moveSortFavorite(null, JSON.parse(param?.favoriteForm), (result: string) => {
callBack(result);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getSearchContact]:
ContactAbilityModel.getSearchContact(param.actionData, (result) => {
ContactAbilityModel.getSearchContact(param?.actionData, (result: SearchContactsBean[]) => {
callBack(result);
}, param.context)
}, param?.context)
break
case DataWorkerConstant[DataWorkerConstant.getCallHistorySearch]:
CallLog.getCallHistorySearch(param.actionData, param.mergeRule, (data) => {
CallLog.getCallHistorySearch(param?.actionData, param?.mergeRule, (data: CallInfoGetParamsInCallback) => {
callBack(data);
}, param.context);
}, param?.context);
break
case DataWorkerConstant[DataWorkerConstant.getQueryT9PhoneNumbers]:
ContactAbilityModel.getQueryT9PhoneNumbers((resultList) => {
ContactAbilityModel.getQueryT9PhoneNumbers((resultList: ContactVo[]) => {
callBack(resultList);
}, JSON.parse(param.favoriteForm), param.context)
}, JSON.parse(param?.favoriteForm), param?.context)
break
default:
HiLog.w(TAG, `${request} not allow!!!`)
+4 -4
View File
@@ -33,9 +33,9 @@ export default class WorkFactory {
* @param message worker message data
* @return WorkerTask for the message
*/
static getTask(type: WorkerType, workerPort?: ThreadWorkerGlobalScope): WorkerTask {
static getTask(type: WorkerType, workerPort?: ThreadWorkerGlobalScope): WorkerTask | undefined {
HiLog.i(TAG, `getTask in ${WorkerType[type]}.`)
let task: WorkerTask = undefined;
let task: WorkerTask | undefined = undefined;
if (type == WorkerType.DataWorker) {
task = DataWorkerTask.getInstance(workerPort);
}
@@ -49,9 +49,9 @@ export default class WorkFactory {
* @param type WorkerType
* @return WorkerWrapper for the WorkerType
*/
static getWorker(type: WorkerType): WorkerWrapper {
static getWorker(type: WorkerType): WorkerWrapper | undefined {
HiLog.i(TAG, `getWorker in ${WorkerType[type]}.`)
let worker: WorkerWrapper = undefined
let worker: WorkerWrapper | undefined = undefined
if (type == WorkerType.DataWorker) {
HiLog.w(TAG, 'getWorker ' + type)
worker = new WorkerWrapper(WorkerType.DataWorker, globalThis.config.useDataWorker);
+9 -9
View File
@@ -12,12 +12,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';
import { HiLog } from '../../../../../../common';
import WorkFactory from '../WorkFactory'
import LooseObject from '../../model/LooseObject ';
import WorkFactory, { WorkerType } from '../WorkFactory'
var workerPort: ThreadWorkerGlobalScope = worker.workerPort;
let workerPort: ThreadWorkerGlobalScope = worker.workerPort;
const TAG = 'Worker';
/**
* Defines the event handler to be called when the worker thread receives a message sent by the host thread.
@@ -25,11 +25,11 @@ const TAG = 'Worker';
*
* @param e message data
*/
workerPort.onmessage = function (e: MessageEvents) {
HiLog.w(TAG, 'onmessage');
workerPort.onmessage = (e: MessageEvents) => {
HiLog.w(TAG, 'onmessage' + ' time:' + (new Date()).valueOf());
if (e.data) {
let data = e.data;
let type = data.type;
let data: LooseObject = e.data;
let type: WorkerType = data.type;
let task = WorkFactory.getTask(type, workerPort)
task?.onmessage(e);
} else {
@@ -44,7 +44,7 @@ workerPort.onmessage = function (e: MessageEvents) {
*
* @param e message data
*/
workerPort.onmessageerror = function (e: MessageEvents) {
workerPort.onmessageerror = (e: MessageEvents) => {
HiLog.w(TAG, 'onmessageerror' + JSON.stringify(e));
}
@@ -54,6 +54,6 @@ workerPort.onmessageerror = function (e: MessageEvents) {
*
* @param e error message
*/
workerPort.onerror = function (e: ErrorEvent) {
workerPort.onerror = (e: ErrorEvent) => {
HiLog.w(TAG, 'onerror' + JSON.stringify(e));
}
@@ -17,6 +17,7 @@ import { WorkerMessage } from './WorkerWrapper'
import { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker';
import { HiLog } from '../../../../../../common'
import buffer from '@ohos.buffer'
import LooseObject from '../../model/type/LooseObject';
const TAG = 'WorkerTask'
/*
@@ -25,7 +26,7 @@ const TAG = 'WorkerTask'
* Work sub thread task
*/
export abstract class WorkerTask {
workerPort: ThreadWorkerGlobalScope
workerPort?: ThreadWorkerGlobalScope
constructor(workerPort?: ThreadWorkerGlobalScope) {
HiLog.i(TAG, `WorkerTask constructor`)
@@ -40,9 +41,9 @@ export abstract class WorkerTask {
*/
public onmessage(message: MessageEvents) {
try {
let data = <WorkerMessage> message.data
let data = message.data as WorkerMessage
HiLog.i(TAG, `onmessage ${data.request}`)
this.runInWorker(data.request, (v) => {
this.runInWorker(data.request, (v?: LooseObject) => {
HiLog.i(TAG, 'runInWorker callback in')
data.param = v;
const str = JSON.stringify(data)
@@ -53,8 +54,7 @@ export abstract class WorkerTask {
HiLog.e(TAG, 'runInWorker err = ' + JSON.stringify(err));
}
}
public abstract runInWorker(request: string, callBack: (v?: any) => void, param?: any);
public abstract runInWorker(request: string, callBack: Function, param?: LooseObject);
}
export default WorkerTask;
@@ -1,44 +1,42 @@
/**
* Copyright (c) 2022 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Copyright (c) 2022 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import WorkFactory, { WorkerType } from '../WorkFactory'
import worker from '@ohos.worker';
import { HiLog } from '../../../../../../common'
import buffer from '@ohos.buffer'
import { HiLog } from '../../../../../../common';
import buffer from '@ohos.buffer';
import LooseObject from '../../model/type/LooseObject';
const TAG = 'WorkerWrapper'
export class WorkerMessage {
request: string;
callBackId: number;
type?: WorkerType;
param?: any;
public request: string = '';
public callBackId: number = -1;
public type?: WorkerType;
public param?: LooseObject;
}
/*
* WorkerWrapper
*
* Processes sending tasks to workers and receiving work processing results.
*/
WorkerWrapper
Processes sending tasks to workers and receiving work processing results.
*/
export default class WorkerWrapper {
protected mWorker: worker.ThreadWorker = undefined;
private callBacks: Map<string, (result?: any) => void> = new Map();
protected mWorker?: worker.ThreadWorker = undefined;
private callBacks: Map<string, Function> = new Map();
private requestIndex: number = 0;
private workType: WorkerType;
private useWorker: boolean;
constructor(workType: WorkerType, useWorker: boolean) {
this.workType = workType;
this.useWorker = useWorker;
@@ -53,24 +51,24 @@ export default class WorkerWrapper {
name: WorkerType[this.getWorkerType()]
});
let that = this;
initWorker.onexit = function (message) {
HiLog.w(TAG, 'onexit')
initWorker.onexit = (message) => {
HiLog.w(TAG, 'onexit');
that.mWorker = undefined;
}
initWorker.onerror = function (e) {
HiLog.w(TAG, 'onerror:' + JSON.stringify(e))
initWorker.onerror = (e) => {
HiLog.w(TAG, 'onerror:' + JSON.stringify(e));
}
initWorker.onmessageerror = function (e) {
HiLog.w(TAG, 'onmessageerror:' + JSON.stringify(e))
initWorker.onmessageerror = (e) => {
HiLog.w(TAG, 'onmessageerror:' + JSON.stringify(e));
}
initWorker.onmessage = function (message) {
const buff = <ArrayBuffer> message.data;
initWorker.onmessage = (message) => {
const buff = message.data as ArrayBuffer;
const str = buffer.from(buff).toString();
let data = <WorkerMessage> JSON.parse(str)
HiLog.i(TAG, `onmessage ${data.request}`)
let data = JSON.parse(str) as WorkerMessage;
HiLog.i(TAG, `onmessage ${data.request}`);
const key = that.getCallBackKey(data);
if (that.callBacks.has(key)) {
HiLog.i(TAG, `onmessage notify result.`)
HiLog.i(TAG, `onmessage notify result.`);
const callback = that.callBacks.get(key);
if (callback) {
callback(data.param);
@@ -87,23 +85,22 @@ export default class WorkerWrapper {
}
/**
* SendRequest to worker thread.
*
* @param {string} request the request worker to do
* @param {Object} requestData request param Data
* @param {Object} callBack Call back from worker
SendRequest to worker thread.
@param {string} request the request worker to do
@param {Object} requestData request param Data
@param {Object} callBack Call back from worker
*/
public async sendRequest(request: string, requestData?: any, callBack?: (result?: any) => void) {
public async sendRequest(request: string, requestData?: LooseObject, callBack?: Function) {
HiLog.i(TAG, 'sendRequest in ' + request)
if (!this.useWorker) {
WorkFactory.getTask(this.getWorkerType()).runInWorker(request, callBack, requestData);
WorkFactory.getTask(this.getWorkerType())?.runInWorker(request, callBack as Function, requestData);
} else if (this.mWorker) {
const message = {
request: request,
callBackId: this.requestIndex,
type: this.getWorkerType(),
param: requestData
}
const message: WorkerMessage = new WorkerMessage();
message.request = request;
message.callBackId = this.requestIndex;
message.type = this.getWorkerType();
message.param = requestData;
if (callBack) {
this.callBacks.set(this.getCallBackKey(message), callBack);
}
@@ -114,9 +111,9 @@ export default class WorkerWrapper {
HiLog.w(TAG, `${this.getWorkerType()} ${request} send fail, worker has been closed!`);
}
}
/**
* Close close worker thread.
Close close worker thread.
*/
public close() {
HiLog.i(TAG, `${this.getWorkerType()} worker close!`);
@@ -124,8 +121,7 @@ export default class WorkerWrapper {
this.mWorker = undefined;
this.callBacks.clear();
}
private getCallBackKey(message: WorkerMessage): string {
return message.request + message.callBackId;
}
}
}
+149 -146
View File
@@ -24,8 +24,8 @@ import StringFormatUtil from '../../../../../entry/src/main/ets/util/StringForma
export class CallLogService implements ICallLogService {
private static instance: CallLogService;
private mergeRule: MergeRule;
private context: Context;
private mergeRule?: MergeRule;
private context?: Context;
private constructor() {
}
@@ -49,7 +49,7 @@ export class CallLogService implements ICallLogService {
this.mergeRule = mergeRule;
}
mergeCallLogs(callLogs: CallLog[]) {
mergeCallLogs(callLogs: CallLog[]): MergedCallLog[] {
if (this.getMergeRule() === MergeRule.CONTACT) {
return this.mergeByContact(callLogs);
} else {
@@ -57,17 +57,17 @@ export class CallLogService implements ICallLogService {
}
}
mergeMissedCalls(callLogs: CallLog[]) {
mergeMissedCalls(callLogs: CallLog[]): MergedCallLog[] {
let mergeRule = this.getMergeRule();
let callLogList: CallLog[] = [];
let missedList: CallLog[] = [];
for (let callLog of callLogs) {
callLogList.push(callLog);
if (callLog.callType == CallType.MISSED ||
callLog.callType == CallType.REJECTED) {
callLog.callType == CallType.REJECTED) {
//Filtering Missed Call Data
missedList.push(callLog);
let timeList = [];
let timeList: Record<string, string | number>[] = [];
// Filtering by Contact Missed Calls and Redialing
if (mergeRule === MergeRule.CONTACT) {
for (let k = 0; k < missedList.length; k++) {
@@ -76,7 +76,7 @@ export class CallLogService implements ICallLogService {
let allSpecialPhone = callLogList[i].phoneNumber;
if (missedPhone == allSpecialPhone) {
let timeNumber = callLogList[i].createTime;
let obj = {
let obj: Record<string, string | number> = {
'id': i,
'timeObj': timeNumber,
};
@@ -115,59 +115,59 @@ export class CallLogService implements ICallLogService {
* @param callLogList
* @return
*/
private mergeByTime(callLogList: CallLog[]) {
let resultList = [];
if (ArrayUtil.isEmpty(callLogList)) {
return resultList;
}
// Call records are cached from the first record.
let tempElement = new MergedCallLog(callLogList[0]);
// Indicates the creation time of the latest record.
// After call records are merged, the time is displayed.
let tempCallTime = callLogList[0].createTime;
// Type of the call record that retains the latest record.
// This type is displayed after the call record is combined.
let tempCallType = callLogList[0].callType;
let num = 1;
let ids = [];
ids.push(callLogList[0].id);
for (let i = 1; i < callLogList.length; i++) {
let element = callLogList[i];
// Whether the cached field needs to be combined with the current field
if (this.callLogMergeCheck(tempElement, element)) {
num++;
// Put the latest record ID into the merged array.
ids.push(element.id);
} else {
//If the latest data is inconsistent with the cached data,
// replace the num and ids data in the cached data and
// save the cached data to the result set.
tempElement.count = num;
tempElement.ids = ids;
// Displays the creation time of the latest saved record.
tempElement.createTime = this.formatTime(tempCallTime);
tempElement.callType = tempCallType;
resultList.push(tempElement);
/* Reset num and ids to the latest count and record,
and reset tempCallTime to the latest creation time of the next record.*/
num = 1;
ids = [];
tempCallTime = element.createTime;
tempCallType = element.callType;
ids.push(element.id);
}
tempElement = new MergedCallLog(element);
}
/* Put the last piece of cached data into the result set*/
if (tempElement != null) {
tempElement.count = num;
tempElement.ids = ids;
tempElement.createTime = this.formatTime(tempCallTime);
tempElement.callType = tempCallType;
resultList.push(tempElement);
}
return resultList;
}
private mergeByTime(callLogList: CallLog[]): MergedCallLog[] {
let resultList: MergedCallLog[] = [];
if (ArrayUtil.isEmpty(callLogList)) {
return resultList;
}
// Call records are cached from the first record.
let tempElement = new MergedCallLog(callLogList[0]);
// Indicates the creation time of the latest record.
// After call records are merged, the time is displayed.
let tempCallTime = callLogList[0].createTime;
// Type of the call record that retains the latest record.
// This type is displayed after the call record is combined.
let tempCallType = callLogList[0].callType;
let num = 1;
let ids: number[] = [];
ids.push(callLogList[0].id);
for (let i = 1; i < callLogList.length; i++) {
let element = callLogList[i];
// Whether the cached field needs to be combined with the current field
if (this.callLogMergeCheck(tempElement, element)) {
num++;
// Put the latest record ID into the merged array.
ids.push(element.id);
} else {
//If the latest data is inconsistent with the cached data,
// replace the num and ids data in the cached data and
// save the cached data to the result set.
tempElement.count = num;
tempElement.ids = ids;
// Displays the creation time of the latest saved record.
tempElement.createTime = this.formatTime(tempCallTime);
tempElement.callType = tempCallType;
resultList.push(tempElement);
/* Reset num and ids to the latest count and record,
and reset tempCallTime to the latest creation time of the next record.*/
num = 1;
ids = [];
tempCallTime = element.createTime;
tempCallType = element.callType;
ids.push(element.id);
}
tempElement = new MergedCallLog(element);
}
/* Put the last piece of cached data into the result set*/
if (tempElement != null) {
tempElement.count = num;
tempElement.ids = ids;
tempElement.createTime = this.formatTime(tempCallTime);
tempElement.callType = tempCallType;
resultList.push(tempElement);
}
return resultList;
}
/**
* In the case of merging by contact, the post-processing
@@ -176,37 +176,37 @@ export class CallLogService implements ICallLogService {
* @param {Array} callLogList
* @return {Array} callLogList
*/
private mergeByContact(callLogs: CallLog[]) {
let resultList = [];
if (ArrayUtil.isEmpty(callLogs)) {
return resultList;
}
let contactTempMap = new Map();
let phoneNumberMap = new Map();
for (let i = 0; i < callLogs.length; i++) {
let element = new MergedCallLog(callLogs[i]);
element.createTime = this.formatTime(callLogs[i].createTime);
// In the case of merging by contact, the combined record entry is fixed to 1.
element.count = 1;
// In the case of merging by contact, the IDs of
// the merging record are fixed to the ID of the record.
element.ids = [callLogs[i].id];
// Call records without contacts are combined by phone number.
if (StringUtil.isEmpty(element.quickSearchKey)) {
if (!phoneNumberMap.has(element.phoneNumber)) {
resultList.push(element);
phoneNumberMap.set(element.phoneNumber, callLogs[i].phoneNumber);
}
} else { // Call records with contacts are merged by contact.
let isContactKey = contactTempMap.has(element.quickSearchKey);
if (!isContactKey) {
resultList.push(element);
contactTempMap.set(element.quickSearchKey, callLogs[i].quickSearchKey);
}
}
}
private mergeByContact(callLogs: CallLog[]): MergedCallLog[] {
let resultList: MergedCallLog[] = [];
if (ArrayUtil.isEmpty(callLogs)) {
return resultList;
}
let contactTempMap: Map<string, string> = new Map();
let phoneNumberMap: Map<string, string> = new Map();
for (let i = 0; i < callLogs.length; i++) {
let element = new MergedCallLog(callLogs[i]);
element.createTime = this.formatTime(callLogs[i].createTime);
// In the case of merging by contact, the combined record entry is fixed to 1.
element.count = 1;
// In the case of merging by contact, the IDs of
// the merging record are fixed to the ID of the record.
element.ids = [callLogs[i].id];
// Call records without contacts are combined by phone number.
if (StringUtil.isEmpty(element.quickSearchKey)) {
if (!phoneNumberMap.has(element.phoneNumber)) {
resultList.push(element);
phoneNumberMap.set(element.phoneNumber, callLogs[i].phoneNumber);
}
} else { // Call records with contacts are merged by contact.
let isContactKey = contactTempMap.has(element.quickSearchKey);
if (!isContactKey) {
resultList.push(element);
contactTempMap.set(element.quickSearchKey, callLogs[i].quickSearchKey);
}
}
}
return resultList;
}
/**
* Obtain the call time.
@@ -214,53 +214,55 @@ export class CallLogService implements ICallLogService {
* @param date Call record creation timestamp
* @return {object} Talk time
*/
private formatTime(date) {
let result;
// If the value is not a number, the value is not parsed.
if (isNaN(date)) {
return date;
}
let timestamp = parseInt(date) * 1000;
let callTime = new Date(timestamp);
let now = new Date();
if (callTime.getTime() > now.getTime()) {
result = callTime.getFullYear() + '/' + (callTime.getMonth() + 1) + '/' + callTime.getDate();
} else if (callTime.getFullYear() == now.getFullYear()) {
if (callTime.getMonth() == now.getMonth()) {
// Same month of the same year
let timeDiff = parseInt(((now.getTime() - callTime.getTime()) / 60000).toString());
let dayDiff = now.getDate() - callTime.getDate();
let hour = callTime.getHours().toString();
let minutes = callTime.getMinutes() < 10 ? '0' + callTime.getMinutes() : callTime.getMinutes().toString();
if (dayDiff == 0) {
// 同天
if (timeDiff == 0) {
result = $r("app.string.justNow");
} else if (timeDiff < 60) {
result = $r("app.string.minutesAgo", timeDiff);
private formatTime(date: number): string | Resource {
let result: Resource | string = '';
// If the value is not a number, the value is not parsed.
if (isNaN(date)) {
return date.toString();
}
let timestamp = date * 1000;
let callTime = new Date(timestamp);
let now = new Date();
if (callTime.getTime() > now.getTime()) {
result = callTime.getFullYear() + '/' + (callTime.getMonth() + 1) + '/' + callTime.getDate();
} else if (callTime.getFullYear() == now.getFullYear()) {
if (callTime.getMonth() == now.getMonth()) {
// Same month of the same year
let timeDiff = parseInt(((now.getTime() - callTime.getTime()) / 60000).toString());
let dayDiff = now.getDate() - callTime.getDate();
let hour = callTime.getHours();
let minutes = callTime.getMinutes() < 10 ? '0' + callTime.getMinutes() : callTime.getMinutes().toString();
if (dayDiff == 0) {
// 同天
if (timeDiff == 0) {
result = $r("app.string.justNow");
} else if (timeDiff < 60) {
result = $r("app.string.minutesAgo", timeDiff);
} else {
let timeDetail: Record<string, Resource | string | undefined> = {};
if (parseInt(StringFormatUtil.judgeSysTime(this.context)) == 12) {
timeDetail.time = StringFormatUtil.getDayMessage(hour, minutes);
} else {
let timeDetail: any = {};
if (parseInt(StringFormatUtil.judgeSysTime(this.context)) == 12) {
timeDetail.time = StringFormatUtil.getDayMessage(hour, minutes);
} else {
timeDetail.time = $r("app.string.time_normal", hour, minutes);
}
timeDetail.time = $r("app.string.time_normal", hour, minutes);
}
if(timeDetail.time !== undefined){
result = timeDetail.time
}
} else if (dayDiff == 1) {
result = $r("app.string.yesterday");
} else {
result = (callTime.getMonth() + 1) + '/' + callTime.getDate(); // 'MM/dd'
}
} else if (dayDiff == 1) {
result = $r("app.string.yesterday");
} else {
result = (callTime.getMonth() + 1) + '/' + callTime.getDate();
result = (callTime.getMonth() + 1) + '/' + callTime.getDate(); // 'MM/dd'
}
} else {
// 'yyyy/MM/dd'
result = callTime.getFullYear() + '/' + (callTime.getMonth() + 1) + '/' + callTime.getDate();
result = (callTime.getMonth() + 1) + '/' + callTime.getDate();
}
return result;
} else {
// 'yyyy/MM/dd'
result = callTime.getFullYear() + '/' + (callTime.getMonth() + 1) + '/' + callTime.getDate();
}
return result;
}
/**
* Checks whether two call records need to be combined when the call records are combined by time.
@@ -270,27 +272,28 @@ export class CallLogService implements ICallLogService {
* @param newElement Combined call records
* @return
*/
private callLogMergeCheck(oldElement: MergedCallLog, newElement: CallLog) {
/* Merge Rules:
1. The phone numbers are combined only when the phone numbers are the same.
2. If the number is the same and the call type is 1, 2, 3, or 5,
the call is combined. Types 1, 2, 3, and 5 are not combined.
*/
if (oldElement.phoneNumber.trim() == newElement.phoneNumber.trim()) {
if (oldElement.callType == CallType.IN || oldElement.callType == CallType.OUT) {
if (newElement.callType == CallType.IN || newElement.callType == CallType.OUT) {
return true;
}
return false;
}
if (newElement.callType == CallType.MISSED || newElement.callType == CallType.REJECTED) {
return true;
}
private callLogMergeCheck(oldElement: MergedCallLog, newElement: CallLog) {
/* Merge Rules:
1. The phone numbers are combined only when the phone numbers are the same.
2. If the number is the same and the call type is 1, 2, 3, or 5,
the call is combined. Types 1, 2, 3, and 5 are not combined.
*/
if (oldElement.phoneNumber.trim() == newElement.phoneNumber.trim()) {
if (oldElement.callType == CallType.IN || oldElement.callType == CallType.OUT) {
if (newElement.callType == CallType.IN || newElement.callType == CallType.OUT) {
return true;
}
return false;
}
if (newElement.callType == CallType.MISSED || newElement.callType == CallType.REJECTED) {
return true;
}
}
return false;
}
private getMergeRule() {
return this.mergeRule;
}
}
}
}
export { MergeRule };
+3 -4
View File
@@ -12,9 +12,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ObjectUtil } from '../../../../../common/src/main/ets/util/ObjectUtil';
import { HiLog } from '../../../../../common/src/main/ets/util/HiLog';
import { ObjectUtil } from 'common/src/main/ets/util/ObjectUtil';
import { HiLog } from 'common/src/main/ets/util/HiLog';
const TAG = 'CallLogSetting';
@@ -47,7 +46,7 @@ export default class CallLogSetting {
if (!AppStorage.Has(CallLogSetting.KEY_MERGE_RULE)) {
return MergeRule.TIME;
}
let rst = AppStorage.Get(CallLogSetting.KEY_MERGE_RULE);
let rst: number | undefined = AppStorage.Get(CallLogSetting.KEY_MERGE_RULE);
if (rst == MergeRule.CONTACT) {
return MergeRule.CONTACT;
}
+4 -3
View File
@@ -29,7 +29,7 @@ export class CallLog {
readonly phoneNumber: string;
readonly displayName: string;
readonly callDirection: number;
readonly voicemailUri: string;
readonly voicemailUri: string = '';
readonly simId: number;
readonly simType: number;
readonly isHD: boolean;
@@ -48,7 +48,7 @@ export class CallLog {
readonly photoId: number;
readonly photoUri: string;
readonly countryIsoCode: number;
readonly callType: number;
readonly callType: CallType;
constructor(builder: CallLogBuilder) {
this.id = builder.id;
this.phoneNumber = builder.phoneNumber;
@@ -75,7 +75,7 @@ export class CallLog {
this.callType = this.getCallLogType();
}
private getCallLogType() {
private getCallLogType() : CallType {
if (this.callDirection == Direction.IN) {
if (this.answerState == AnswerState.RECEIVED) {
return CallType.IN;
@@ -86,6 +86,7 @@ export class CallLog {
if (this.answerState == AnswerState.REJECT) {
return CallType.REJECTED;
}
return CallType.IN;
} else {
return CallType.OUT;
}

Some files were not shown because too many files have changed in this diff Show More