wangliang_wd

Merge branch 'main' of http://192.168.1.42/developOne/harmonyPool into main

* 'main' of http://192.168.1.42/developOne/harmonyPool: (32 commits)
  desc:热门评论相关 50%
  绑定手机号
  h5专题跳转 H5详情
  环境切换
  新增样式卡-小视频卡人民号
  desc:搜索结果
  desc:搜索结果 comp 展现
  样式卡作者信息展示优化
  权限管理工具类
  isFirstIn注释
  webview高度自适应
  删除冗余样式卡,样式卡集中在cardView和compView文件夹中
  样式卡底部来源、评论、发布日期抽离组件
  wdComponent Index.ets修改
  音频dialog开发抽取工具类
  视频频道入口修改
  优化通信工具
  播放器修改
  人民号单图卡ui
  直播与视频冲突,分开写
  ...
Showing 63 changed files with 2600 additions and 1377 deletions

Too many changes to show.

To preserve performance only 63 of 63+ files are displayed.

... ... @@ -13,6 +13,11 @@ export class SpConstants{
//协议相关
static USER_PROTOCOL = "user_protocol" //用户协议
static PRIVATE_PROTOCOL = "private_protocol" //隐私协议
static LOGOUT_PROTOCOL = "logout_protocol" //人民日报客户端app注销协议
static MESSAGE_BOARD_USER_PROTOCOL = "message_board_user_protocol" //"留言板-用户协议"
static MESSAGE_BOARD_NOTICE_PROTOCOL = "message_board_notice_protocol" //留言板-留言须知
static MESSAGE_BOARD_QUESTION_PROTOCOL = "message_board_question_protocol" //"留言板-发布提问规定""
static MESSAGE_BOARD_PRIVATE_PROTOCOL = "message_board_private_protocol" //"留言板-隐私政策"
//设置页面
static SETTING_WIFI_IMAGE_SWITCH = "setting_wifi_switch" //wifi 图片开关
static SETTING_WIFI_VIDEO_SWITCH = "setting_wifi_switch" //wifi 视频开关
... ...
/**
* https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-window-0000001820880785#ZH-CN_TOPIC_0000001811317218__systembarproperties
* 状态栏、导航栏的属性。
*/
/**
* 状态栏背景颜色 statusBarColor
* 导航栏背景颜色 navigationBarColor
*/
export const enum SysStatusBarColor {
WHITE = '#ffffff',
BLACK = '#000000',
DEFAULT = '#0x66000000'
}
/**
* 状态栏文字颜色 statusBarContentColor8
* 导航栏文字颜色 navigationBarContentColor8
*/
export const enum SysBarContentColor {
WHITE = '#ffffff',
BLACK = '#000000',
DEFAULT = '0xE5FFFFFF'
}
... ...
import { Action } from './Action';
interface dataObject {
webViewHeight?: string
dataJson?: string
}
/**
* 消息Message
*/
... ... @@ -7,7 +10,7 @@ export class Message {
callbackId: string = ""; //callbackId
responseId: string = ""; //responseId
responseData: string = ""; //responseData
data?: object; //data of message
data?: dataObject; //data of message
handlerName: string = ""; //name of handler
/**
... ...
... ... @@ -36,6 +36,10 @@ export { UserDataLocal } from './src/main/ets/utils/UserDataLocal'
export { NumberFormatterUtils } from './src/main/ets/utils/NumberFormatterUtils'
// export { PermissionUtils } from './src/main/ets/utils/PermissionUtils'
export { PermissionUtils } from './src/main/ets/utils/PermissionUtils'
export { ErrorToastUtils } from './src/main/ets/utils/ErrorToastUtils'
export { EmitterUtils } from './src/main/ets/utils/EmitterUtils'
export { EmitterEventId } from './src/main/ets/utils/EmitterEventId'
\ No newline at end of file
... ...
/**
* 线程间通信事件id枚举
*/
export enum EmitterEventId {
// 通知登出,事件id
FORCE_USER_LOGIN_OUT = 1
}
... ...
import emitter from '@ohos.events.emitter';
const TAG: string = 'EmitterUtils';
/**
* 线程间通信简单工具
*/
export class EmitterUtils {
/**
* 发送空消息
* @param eventId 事件id
*/
static sendEmptyEvent(eventId: number) {
let event: emitter.InnerEvent = {
eventId: eventId,
priority: emitter.EventPriority.LOW
};
emitter.emit(event);
}
/**
* 发送消息
* @param eventId 事件id
* @param str 字符串数据
*/
static sendEvent(eventId: number, str?: string) {
let event: emitter.InnerEvent = {
eventId: eventId,
priority: emitter.EventPriority.LOW
};
let eventData: emitter.EventData = {
data: {
jsonStr: str
}
};
emitter.emit(event, eventData);
}
/**
* 接收消息
* @param eventId 事件id
* @param callback 回调函数
*/
static receiveEvent(eventId: number, callback: (str?: string) => void) {
let event: emitter.InnerEvent = {
eventId: eventId
};
// 收到eventId事件后执行该回调
let callback1 = (eventData?: emitter.EventData): void => {
if (eventData && eventData.data) {
try {
let jsonObject: EmitterBean = JSON.parse(JSON.stringify(eventData.data))
callback(jsonObject.jsonStr)
} catch (err) {
callback()
}
} else {
callback()
}
};
// 订阅eventId事件
emitter.on(event, callback1);
}
}
interface EmitterBean {
jsonStr: string
}
... ...
// import { abilityAccessCtrl, bundleManager, common, Permissions, Want } from '@kit.AbilityKit'
// import { BusinessError } from '@kit.BasicServicesKit'
// import { AppUtils } from './AppUtils'
// import { Logger } from './Logger'
//
// /**
// * 权限工具类
// * */
// export class PermissionUtils {
// //相机权限
// static CAMERA: Permissions = 'ohos.permission.CAMERA'
// //文件权限
// static READ_MEDIA: Permissions = 'ohos.permission.READ_MEDIA'
// static WRITE_MEDIA: Permissions = 'ohos.permission.WRITE_MEDIA'
// private static tokenId: number = 0
//
// /**检查权限是否授权*/
// static async checkPermissions(permission: Permissions): Promise<boolean> {
// let hasPermissions = false;
// let grantStatus: abilityAccessCtrl.GrantStatus = await PermissionUtils.checkAccessToken(permission);
//
// if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
// // 已经授权,可以继续访问目标操作
// hasPermissions = true;
// } else {
// hasPermissions = false;
// // 申请日历权限
// }
// return hasPermissions;
// }
//
// /**动态申请权限*/
// static reqPermissionsFromUser(permissions: Array<Permissions>, component: Object): Promise<boolean> {
//
// return new Promise((resolve, fail) => {
// let context = getContext(component) as common.UIAbilityContext;
// let atManager = abilityAccessCtrl.createAtManager();
// atManager.requestPermissionsFromUser(context, permissions).then((data) => {
// let grantStatus: Array<number> = data.authResults;
// let length: number = grantStatus.length;
//
// for (let i = 0; i < length; i++) {
// if (grantStatus[i] === 0) {
// // 用户授权,可以继续访问目标操作
// resolve(true);
// } else {
// resolve(false)
// }
// }
// }).catch((err: Error) => {
// fail(err)
// })
// });
// }
//
// /**跳转设置页面*/
// static openPermissionsInSystemSettings(context: Object): void {
// let uiContext = getContext(context) as common.UIAbilityContext;
// let wantInfo: Want = {
// bundleName: 'com.huawei.hmos.settings',
// abilityName: 'com.huawei.hmos.settings.MainAbility',
// uri: 'application_info_entry',
// parameters: {
// pushParams: AppUtils.getPackageName(uiContext) // 打开指定应用的设置页面
// }
// }
// uiContext.startAbility(wantInfo)
// }
//
// private static async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
// let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
// let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
//
// // 获取应用程序的accessTokenID
// if (PermissionUtils.tokenId == 0) {
// try {
// let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
// let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
// PermissionUtils.tokenId = appInfo.accessTokenId;
// } catch (error) {
// const err: BusinessError = error as BusinessError;
// }
// }
// // 校验应用是否被授予权限
// try {
// grantStatus = await atManager.checkAccessToken(PermissionUtils.tokenId, permission);
// } catch (error) {
// const err: BusinessError = error as BusinessError;
// }
//
// return grantStatus;
// }
//
// }
\ No newline at end of file
import { abilityAccessCtrl, bundleManager, common, Permissions, Want } from '@kit.AbilityKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { AppUtils } from './AppUtils'
import { Logger } from './Logger'
/**
* 权限工具类
* */
export class PermissionUtils {
//相机权限
static CAMERA: Permissions = 'ohos.permission.CAMERA'
//文件权限
static READ_MEDIA: Permissions = 'ohos.permission.READ_MEDIA'
static WRITE_MEDIA: Permissions = 'ohos.permission.WRITE_MEDIA'
private static tokenId: number = 0
/**检查权限是否授权*/
static async checkPermissions(permission: Permissions): Promise<boolean> {
let hasPermissions = false;
let grantStatus: abilityAccessCtrl.GrantStatus = await PermissionUtils.checkAccessToken(permission);
if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
// 已经授权,可以继续访问目标操作
hasPermissions = true;
} else {
hasPermissions = false;
// 申请日历权限
}
return hasPermissions;
}
/**动态申请权限*/
static reqPermissionsFromUser(permissions: Array<Permissions>, component: Object): Promise<boolean> {
return new Promise((resolve, fail) => {
let context = getContext(component) as common.UIAbilityContext;
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(context, permissions).then((data) => {
let grantStatus: Array<number> = data.authResults;
let length: number = grantStatus.length;
for (let i = 0; i < length; i++) {
if (grantStatus[i] === 0) {
// 用户授权,可以继续访问目标操作
resolve(true);
} else {
resolve(false)
}
}
}).catch((err: Error) => {
fail(err)
})
});
}
/**跳转设置页面*/
static openPermissionsInSystemSettings(context: Object): void {
let uiContext = getContext(context) as common.UIAbilityContext;
let wantInfo: Want = {
bundleName: 'com.huawei.hmos.settings',
abilityName: 'com.huawei.hmos.settings.MainAbility',
uri: 'application_info_entry',
parameters: {
pushParams: AppUtils.getPackageName(uiContext) // 打开指定应用的设置页面
}
}
uiContext.startAbility(wantInfo)
}
private static async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
// 获取应用程序的accessTokenID
if (PermissionUtils.tokenId == 0) {
try {
let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
PermissionUtils.tokenId = appInfo.accessTokenId;
} catch (error) {
const err: BusinessError = error as BusinessError;
}
}
// 校验应用是否被授予权限
try {
grantStatus = await atManager.checkAccessToken(PermissionUtils.tokenId, permission);
} catch (error) {
const err: BusinessError = error as BusinessError;
}
return grantStatus;
}
}
\ No newline at end of file
... ...
... ... @@ -4,3 +4,5 @@ export { HttpRequest as WDHttp } from "./src/main/ets/http/HttpRequest"
export { HttpUrlUtils } from "./src/main/ets/http/HttpUrlUtils"
export { HttpBizUtil } from "./src/main/ets/http/HttpBizUtil"
... ...
/*
* refresh token接口返回
*/
export interface RefreshTokenRes {
jwtToken: string;
refreshToken: string;
}
\ No newline at end of file
... ...
import { SpConstants } from 'wdConstant/Index';
import { EmitterEventId, EmitterUtils, Logger, SPHelper, ToastUtils } from 'wdKit/Index';
import HashMap from '@ohos.util.HashMap';
import { ResponseDTO } from '../bean/ResponseDTO';
import { HttpUrlUtils, WDHttp } from '../../../../Index';
import { RefreshTokenRes } from '../bean/RefreshTokenRes';
const TAG: string = 'HttpBizUtil'
/**
* 网络请求工具,业务封装http,暂添加TokenInterceptor功能
* TODO 待优化,将HttpBizUtil接入 AxiosInstance.interceptors.response.use
*/
export class HttpBizUtil {
/**
* get请求,封装了刷新token逻辑,接口选用,不涉及业务接口可以用原来的接口(如page接口)。
*
* @param url 请求地址
* @param headers 请求header参数
* @returns 返回值
*/
static get<T = string>(url: string, headers?: HashMap<string, string>): Promise<ResponseDTO<T>> {
return new Promise<ResponseDTO<T>>((success, debug) => {
WDHttp.get<ResponseDTO<T>>(url, headers).then((resDTO: ResponseDTO<T>) => {
Logger.debug(TAG, 'get: ' + resDTO.code)
Logger.debug(TAG, 'get: ' + resDTO.message)
// 403:临时token;406:强制下线、封禁、清空登录信息还要跳转登录页面
if (resDTO.code == 403 || resDTO.code == 406) {
HttpBizUtil.refreshToken().then((token: string) => {
if (headers) {
headers.replace('RMRB-X-TOKEN', token)
headers.replace('cookie', 'RMRB-X-TOKEN=' + token)
}
Logger.debug(TAG, 'get again send: ' + token)
// refreshToken为空场景不处理,直接请求接口。
WDHttp.get<ResponseDTO<T>>(url, headers).then((resDTO: ResponseDTO<T>) => {
Logger.debug(TAG, 'get again: ' + resDTO.message)
success(resDTO)
}).catch((res: object) => {
debug(res)
})
});
} else {
success(resDTO)
}
}).catch((res: object) => {
debug(res)
})
})
}
/**
* post请求,封装了刷新token逻辑,接口选用,不涉及业务接口可以用原来的接口(如page接口)。
*
* @param url 请求地址
* @param headers 请求header参数
* @returns 返回值
*/
static post<T = string>(url: string, data?: object, headers?: HashMap<string, string>): Promise<ResponseDTO<T>> {
return new Promise<ResponseDTO<T>>((success, debug) => {
WDHttp.post<ResponseDTO<T>>(url, data, headers).then((resDTO: ResponseDTO<T>) => {
Logger.debug(TAG, 'post: ' + resDTO.code)
Logger.debug(TAG, 'post: ' + resDTO.message)
// 403:临时token;406:强制下线、封禁、清空登录信息还要跳转登录页面
if (resDTO.code == 0 || resDTO.code == 406) {
HttpBizUtil.refreshToken().then((token: string) => {
if (headers) {
headers.replace('RMRB-X-TOKEN', token)
headers.replace('cookie', 'RMRB-X-TOKEN=' + token)
}
// refreshToken为空场景不处理,直接请求接口。
WDHttp.post<ResponseDTO<T>>(url, headers).then((resDTO: ResponseDTO<T>) => {
success(resDTO)
}).catch((res: object) => {
debug(res)
})
});
} else {
success(resDTO)
}
}).catch((res: object) => {
debug(res)
})
})
}
/*
* 获取刷新后的token,可能为空
*/
static refreshToken(): Promise<string> {
let url = HttpUrlUtils.getRefreshTokenUrl();
let params: HashMap<string, string> = new HashMap<string, string>()
params.set('refreshToken', HttpUrlUtils.getRefreshToken())
params.set('deviceId', HttpUrlUtils.getDeviceId())
let headers: HashMap<string, string> = HttpUrlUtils.getCommonHeaders();
Logger.debug(TAG, 'refreshToken getRefreshToken: ' + HttpUrlUtils.getRefreshToken())
// // 请求刷新token接口
return new Promise<string>((success, debug) => {
WDHttp.post<ResponseDTO<RefreshTokenRes>>(url, params, headers).then((resDTO: ResponseDTO<RefreshTokenRes>) => {
let newToken = ''
if (resDTO) {
Logger.debug(TAG, 'refreshToken getRefreshToken: ' + resDTO.message)
Logger.debug(TAG, 'refreshToken getRefreshToken: ' + resDTO.code)
if (resDTO.code == 377) {
// 377强制用户下线、重新登录、封禁等场景;refreshToken 失效
ToastUtils.showToast("已登出,请重新登入", 1000);
EmitterUtils.sendEmptyEvent(EmitterEventId.FORCE_USER_LOGIN_OUT)
// WDRouterRule.jumpWithPage(WDRouterPage.loginPage)
} else if (resDTO.code == 0 && resDTO.data) {
newToken = resDTO.data.jwtToken
let refreshToken = resDTO.data.refreshToken
SPHelper.default.save(SpConstants.USER_JWT_TOKEN, newToken)
SPHelper.default.save(SpConstants.USER_REFRESH_TOKEN, refreshToken)
Logger.debug(TAG, 'refreshToken jwtToken: ' + resDTO.data.jwtToken)
Logger.debug(TAG, 'refreshToken refreshToken: ' + resDTO.data.refreshToken)
}
}
success(newToken)
});
})
}
}
\ No newline at end of file
... ...
... ... @@ -112,6 +112,10 @@ export class HttpUrlUtils {
*/
static readonly APPOINTMENT_userArea_PATH: string = "/api/rmrb-content-center/c/service/sys-area/treeselect";
/**
* 用户token刷新接口(token过期,需要刷新)
*/
static readonly REFRESH_TOKEN_PATH: string = "/api/rmrb-user-center/auth/zh/c/refreshToken";
/**
/**
* 个人中心 关注列表详情
*/
... ... @@ -188,7 +192,6 @@ export class HttpUrlUtils {
* 搜索主页 热词
*/
static readonly SEARCH_HOTS_DATA_PATH: string = "/api/rmrb-search-api/zh/c/hots";
/**
* 搜索联想词
*/
... ... @@ -198,7 +201,6 @@ export class HttpUrlUtils {
* 直播详情
*/
static readonly LIVE_DETAILS_PATH: string = "/api/rmrb-bff-display-zh/content/zh/c/content/detail";
/**
* 直播详情-直播间列表
*/
... ... @@ -215,6 +217,11 @@ export class HttpUrlUtils {
static readonly SEARCH_RESULT_COUNT_DATA_PATH: string = "/api/rmrb-search-api/zh/c/count?keyword=";
/**
* 搜索结果 显示list 详情
*/
static readonly SEARCH_RESULT_LIST_DATA_PATH: string = "/api/rmrb-search-api/zh/c/search";
/**
* 早晚报列表
* 根据页面id获取页面楼层列表
* https://pdapis.pdnews.cn/api/rmrb-bff-display-zh/display/zh/c/pageInfo?pageId=28927
... ... @@ -358,7 +365,7 @@ export class HttpUrlUtils {
return '';
}
private static getDeviceId() {
public static getDeviceId() {
// TODO
return '8a81226a-cabd-3e1b-b630-b51db4a720ed';
}
... ... @@ -452,6 +459,10 @@ export class HttpUrlUtils {
return url;
}
static getRefreshTokenUrl() {
let url = HttpUrlUtils._hostUrl + HttpUrlUtils.REFRESH_TOKEN_PATH;
return url;
}
static getResetPassworddUrl() {
let url = HttpUrlUtils._hostUrl + "/api/rmrb-user-center/user/zh/c/resetPassword";
... ... @@ -488,6 +499,21 @@ export class HttpUrlUtils {
return url;
}
/*优质评论页*/
static getQualityCommentUrl() {
let url = HttpUrlUtils._hostUrl + "/api/rmrb-comment/comment/zh/c/highQuality";
return url
}
/*获取详情页评论列表*/
static getContentCommentListDataUrl() {
let url = HttpUrlUtils._hostUrl + "/api/rmrb-comment/comment/zh/c/contentCommentList"
return url
}
//账户注销
static accountLogoutUrl() {
let url = HttpUrlUtils._hostUrl + "/api/rmrb-user-center/user/zh/c/logoff";
... ... @@ -500,6 +526,12 @@ export class HttpUrlUtils {
return url;
}
//获取用户安全页信息
static querySecurity() {
let url = HttpUrlUtils._hostUrl + "/api/rmrb-user-center/user/zh/c/security/query";
return url;
}
static getAppointmentListDataUrl() {
let url = HttpUrlUtils._hostUrl + HttpUrlUtils.APPOINTMENT_LIST_DATA_PATH
return url
... ... @@ -625,6 +657,11 @@ export class HttpUrlUtils {
return url
}
static getSearchResultListDataUrl() {
let url = HttpUrlUtils._hostUrl + HttpUrlUtils.SEARCH_RESULT_LIST_DATA_PATH
return url
}
// static getYcgCommonHeaders(): HashMap<string, string> {
// let headers: HashMap<string, string> = new HashMap<string, string>()
//
... ...
... ... @@ -53,6 +53,12 @@ export function registerRouter() {
return WDRouterPage.detailPlayLivePage
} else if (action.params?.detailPageType == 7 || action.params?.detailPageType == 8) {
return WDRouterPage.detailVideoListPage
}else if(action.params?.detailPageType == 9){
//图集详情页
return WDRouterPage.multiPictureDetailPage
}else if(action.params?.detailPageType == 14 || action.params?.detailPageType == 15){
//动态详情页
return WDRouterPage.dynamicDetailPage
} else if (action.params?.detailPageType == 17) {
return WDRouterPage.multiPictureDetailPage
} else if (action.params?.detailPageType == 13) {
... ... @@ -74,6 +80,8 @@ export function registerRouter() {
return WDRouterPage.imageTextDetailPage
} else if (action.params?.pageID == "BroadcastPage") {
return WDRouterPage.broadcastPage
} else if (action.params?.pageID == "SPACIAL_TOPIC_PAGE") {
return WDRouterPage.spacialTopicPage
}
return undefined
})
... ...
... ... @@ -32,6 +32,8 @@ export class WDRouterPage {
static morningEveningPaperPage = new WDRouterPage("phone", "ets/pages/MorningEveningPaperPage")
// 图文详情页
static imageTextDetailPage = new WDRouterPage("phone", "ets/pages/ImageAndTextDetailPage");
// 专题页
static spacialTopicPage = new WDRouterPage("phone", "ets/pages/SpacialTopicPage");
// 短视频详情页
static detailVideoListPage = new WDRouterPage("wdDetailPlayShortVideo", "ets/pages/DetailVideoListPage");
static detailPlayShortVideoPage = new WDRouterPage("wdDetailPlayShortVideo", "ets/pages/DetailPlayShortVideoPage");
... ... @@ -45,6 +47,8 @@ export class WDRouterPage {
static multiPictureDetailPage = new WDRouterPage("phone", "ets/pages/detail/MultiPictureDetailPage");
// 音乐详情页
static audioDetail = new WDRouterPage("phone", "ets/pages/detail/AudioDetail");
// 动态详情页
static dynamicDetailPage = new WDRouterPage("phone", "ets/pages/detail/DynamicDetailPage");
static loginPage = new WDRouterPage("wdLogin", "ets/pages/login/LoginPage");
static forgetPasswordPage = new WDRouterPage("wdLogin", "ets/pages/login/ForgetPasswordPage");
//我的 预约
... ...
... ... @@ -8,13 +8,17 @@ export class H5CallNativeType {
static jsCall_getAppPublicInfo = 'jsCall_getAppPublicInfo'
static jsCall_getArticleDetailBussinessData = 'jsCall_getArticleDetailBussinessData'
static jsCall_callAppService = 'jsCall_callAppService'
static jsCall_appInnerLinkMethod = 'jsCall_appInnerLinkMethod'
static jsCall_receiveH5Data = 'jsCall_receiveH5Data'
// TODO 业务自行新增类型、自行在JsBridgeBiz#performJSCallNative里添加接收分支处理。
static init() {
static {
H5CallNativeType.JsCallTypeList.push(H5CallNativeType.jsCall_currentPageOperate)
H5CallNativeType.JsCallTypeList.push(H5CallNativeType.jsCall_getAppPublicInfo)
H5CallNativeType.JsCallTypeList.push(H5CallNativeType.jsCall_getArticleDetailBussinessData)
H5CallNativeType.JsCallTypeList.push(H5CallNativeType.jsCall_callAppService)
H5CallNativeType.JsCallTypeList.push(H5CallNativeType.jsCall_appInnerLinkMethod)
H5CallNativeType.JsCallTypeList.push(H5CallNativeType.jsCall_receiveH5Data)
}
}
... ...
... ... @@ -2,6 +2,9 @@ import { Callback, BridgeWebViewControl } from 'wdJsBridge';
import { Message } from 'wdJsBridge/src/main/ets/bean/Message';
import { Logger, StringUtils, } from 'wdKit';
import { H5CallNativeType } from './H5CallNativeType';
import { ContentDTO } from 'wdBean';
//TODO 这里引用了 features模块,是否考虑将跳转抽到公共模块
import { ProcessUtils } from '../../../../../../features/wdComponent/src/main/ets/utils/ProcessUtils';
const TAG = 'JsBridgeBiz'
... ... @@ -11,7 +14,7 @@ const TAG = 'JsBridgeBiz'
* @param call
*/
export function performJSCallNative(data: Message, call: Callback) {
Logger.debug(TAG, 'performJSCallNative handlerName: ' + data.handlerName + ', data: ' + data.data)
Logger.debug(TAG, 'performJSCallNative handlerName: ' + data.handlerName + ', data: ' + JSON.stringify(data.data))
switch (data.handlerName) {
case H5CallNativeType.jsCall_currentPageOperate:
break;
... ... @@ -23,6 +26,9 @@ export function performJSCallNative(data: Message, call: Callback) {
break;
case H5CallNativeType.jsCall_callAppService:
break;
case H5CallNativeType.jsCall_receiveH5Data:
handleH5Data(JSON.parse(data?.data?.dataJson || '{}'))
break;
case 'changeNativeMessage':
call("this is change Web Message")
break;
... ... @@ -50,4 +56,7 @@ function getAppPublicInfo(): string {
return result;
}
function handleH5Data(content:ContentDTO) {
ProcessUtils.processPage(content)
}
... ...
import router from '@ohos.router';
import { Action } from 'wdBean';
import { ConfigConstants } from 'wdConstant';
import { Logger } from 'wdKit';
import { BridgeHandler, BridgeUtil, BridgeWebViewControl, Callback } from 'wdJsBridge';
import { BridgeUtil, BridgeWebViewControl, Callback } from 'wdJsBridge';
import { Logger } from 'wdKit/Index';
import { performJSCallNative } from './JsBridgeBiz';
import { setDefaultNativeWebSettings } from './WebComponentUtil';
import { H5CallNativeType } from './H5CallNativeType';
import { Message } from 'wdJsBridge/src/main/ets/bean/Message';
const TAG = 'WdWebComponent';
const TAG = 'WdWebLocalComponent';
@Component
export struct WdWebComponent {
private webviewControl: BridgeWebViewControl = new BridgeWebViewControl()
//TODO 默认网页
webUrl: string | Resource = ConfigConstants.DETAIL_URL
/**
* 对外暴露webview的回调,能力
*/
onPageBegin: (url?: string) => void = () => {
}
onPageEnd: (url?: string) => void = () => {
}
onLoadIntercept: (url?: string) => boolean = () => {
return false
}
onHttpErrorReceive: (url?: string) => boolean = () => {
return false
}
webviewControl: BridgeWebViewControl = new BridgeWebViewControl()
@Prop backVisibility: boolean = false
@Prop webUrl: string = ''
@Prop @Watch('onReloadStateChanged') reload: number = 0
/**
* 默认【CallNative】逻辑处理
*/
private defaultPerformJSCallNative: (data: Message, f: Callback) => void = (data: Message, f: Callback) => {
performJSCallNative(data, f)
}
/**
* jsBridge的处理
*/
handleInfo: [string, BridgeHandler][] = []
backVisibility: boolean = false
defaultRegisterHandler(): void {
this.webviewControl.registerHandler("CallNative", {
handle: (data: Message, f: Callback) => {
this.defaultPerformJSCallNative(data, f)
}
});
}
build() {
Column() {
... ... @@ -71,26 +36,13 @@ export struct WdWebComponent {
.zoomAccess(false)
.horizontalScrollBarAccess(false)
.verticalScrollBarAccess(false)
.onHttpErrorReceive((event) => {
//TODO 页面加载不成功的时候处理
Logger.info(TAG, 'onHttpErrorReceive event.request.getRequestUrl:' + event?.request.getRequestUrl());
Logger.info(TAG, 'onHttpErrorReceive event.response.getResponseCode:' + event?.response.getResponseCode());
.onPageBegin((event) => {
console.log(this.webUrl,"yzl")
this.onPageBegin(event?.url);
})
.onPageEnd((event) => {
this.onPageEnd(event?.url)
})
.onPageBegin((event) => {
// setDefaultNativeWebSettings(this.webviewControl, this.webUrl).then(()=>{
// this.handleInfo && this.handleInfo.length > 1 ? this.handleInfo.forEach(value => {
// this.webviewControl.registerHandler(value[0], value[1])
// }) : this.defaultRegisterHandler()
// setTimeout(()=>{
// BridgeUtil.webViewLoadLocalJs(getContext(this), this.webviewControl)
// },500)
// })
// this.onPageBegin(event?.url)
// this.webviewControl?.setCustomUserAgent('Mozilla/5.0 (Linux; Android 12; HarmonyOS; OXF-AN00; HMSCore 6.13.0.302) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.88 HuaweiBrowser/14.0.6.300 Mobile Safari/537.36')
})
.onLoadIntercept((event) => {
let url: string = event.data.getRequestUrl().toString()
url = url.replace("%(?![0-9a-fA-F]{2})", "%25")
... ... @@ -101,19 +53,51 @@ export struct WdWebComponent {
return true
}
if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) {
Logger.debug(TAG, 'flushMessageQueue');
this.webviewControl.flushMessageQueue()
return true
}
return this.onLoadIntercept(event.data.getRequestUrl().toString())
return this.onLoadIntercept(event.data.getRequestUrl().toString());
})
}
}
private registerHandlers(): void {
// 注册h5调用js相关
for (let i = 0; i < H5CallNativeType.JsCallTypeList.length; i++) {
let handleName = H5CallNativeType.JsCallTypeList[i];
console.log('handleName:', handleName)
let handle = (data: Message, f: Callback) => {
this.defaultPerformJSCallNative(data, f)
};
this.webviewControl.registerHandler(handleName, { handle: handle });
}
}
/**
* 默认【CallNative】逻辑处理
*/
private defaultPerformJSCallNative: (data: Message, f: Callback) => void = (data: Message, f: Callback) => {
performJSCallNative(data, f)
}
onPageBegin: (url?: string) => void = () => {
Logger.debug(TAG, 'onPageBegin');
this.registerHandlers();
BridgeUtil.webViewLoadLocalJs(getContext(this), this.webviewControl)
}
onPageEnd: (url?: string) => void = () => {
Logger.debug(TAG, 'onPageEnd');
}
onLoadIntercept: (url?: string) => boolean = () => {
Logger.debug(TAG, 'onLoadIntercept return false');
return false
}
onReloadStateChanged() {
Logger.info(TAG, `onReloadStateChanged:::refresh, this.reload: ${this.reload}`);
if (this.reload > 0) {
this.webviewControl.refresh()
}
}
}
... ...
... ... @@ -11,9 +11,10 @@ const TAG = 'WdWebLocalComponent';
@Component
export struct WdWebLocalComponent {
private webviewControl: BridgeWebViewControl = new BridgeWebViewControl()
backVisibility: boolean = false
webResource: Resource = {} as Resource
webviewControl: BridgeWebViewControl = new BridgeWebViewControl()
@Prop backVisibility: boolean = false
@Prop webResource: Resource = {} as Resource
@State webHeight : string = '100%'
build() {
Column() {
... ... @@ -31,30 +32,16 @@ export struct WdWebLocalComponent {
.visibility(this.backVisibility ? Visibility.Visible : Visibility.None)
Web({ src: this.webResource, controller: this.webviewControl })
.layoutMode(WebLayoutMode.FIT_CONTENT)
.domStorageAccess(true)
.databaseAccess(true)
.javaScriptAccess(true)
// .imageAccess(true)
// .onlineImageAccess(true)
// .fileAccess(true)
.imageAccess(true)
.mixedMode(MixedMode.All)
.onlineImageAccess(true)
.enableNativeEmbedMode(true)
.height(this.webHeight === '100%' ? '100%' : Number(this.webHeight))
.onPageBegin((event) => {
// setDefaultNativeWebSettings(this.webviewControl, this.webResource).then(()=>{
// this.handleInfo && this.handleInfo.length > 1 ? this.handleInfo.forEach(value => {
// this.webviewControl.registerHandler(value[0], value[1])
// }) : this.defaultRegisterHandler()
// setTimeout(()=>{
// BridgeUtil.webViewLoadLocalJs(getContext(this), this.webviewControl)
// },500)
// })
// this.onPageBegin(event?.url)
// BridgeUtil.webViewLoadLocalJs(getContext(this), this.webviewControl);
this.onPageBegin(event?.url);
this.registerHandlers();
setTimeout(() => {
BridgeUtil.webViewLoadLocalJs(getContext(this), this.webviewControl)
}, 200)
})
.onPageEnd((event) => {
this.onPageEnd(event?.url)
... ... @@ -79,25 +66,24 @@ export struct WdWebLocalComponent {
}
private registerHandlers(): void {
// TODO 待优化
H5CallNativeType.init();
// 注册h5调用js相关
for (let i = 0; i < H5CallNativeType.JsCallTypeList.length; i++) {
let handleName = H5CallNativeType.JsCallTypeList[i];
let handle = (data: Message, f: Callback) => {
this.setCurrentPageOperate(data)
this.defaultPerformJSCallNative(data, f)
} ;
};
this.webviewControl.registerHandler(handleName, { handle: handle });
}
// // TODO test
// this.webviewControl.registerHandler('changeNativeMessage', {
// handle: (data: Message, f: Callback) => {
// this.defaultPerformJSCallNative(data, f)
// }
// });
}
//webview 高度设置
private setCurrentPageOperate: (data: Message) => void = (data) => {
console.log("setCurrentPageOperate",JSON.stringify(data))
if (data.handlerName === H5CallNativeType.jsCall_currentPageOperate) {
this.webHeight = data?.data?.webViewHeight || '100%'
}
}
/**
* 默认【CallNative】逻辑处理
*/
... ... @@ -106,12 +92,16 @@ export struct WdWebLocalComponent {
}
onPageBegin: (url?: string) => void = () => {
Logger.debug(TAG, 'onPageBegin');
this.registerHandlers();
// setTimeout(() => {
BridgeUtil.webViewLoadLocalJs(getContext(this), this.webviewControl)
// }, 100)
}
onPageEnd: (url?: string) => void = () => {
Logger.debug(TAG, 'onPageEnd');
}
onLoadIntercept: (url?: string) => boolean = () => {
Logger.debug(TAG, 'onPageBegin return false');
Logger.debug(TAG, 'onLoadIntercept return false');
return false
}
}
... ...
... ... @@ -69,6 +69,8 @@ export interface ContentDTO {
isSelect: boolean;
rmhInfo: RmhInfoDTO; // 人民号信息
photoNum: number;
corner: string;
rmhPlatform: number;
newTags: string
}
\ No newline at end of file
... ...
... ... @@ -43,20 +43,14 @@ export { ImageAndTextWebComponent } from "./src/main/ets/components/ImageAndText
export { DetailViewModel } from "./src/main/ets/viewmodel/DetailViewModel"
export { SingleImageCardComponent } from "./src/main/ets/components/view/SingleImageCardComponent"
export { TriPicCardComponent } from "./src/main/ets/components/view/TriPicCardComponent"
export { BigPicCardComponent } from "./src/main/ets/components/view/BigPicCardComponent"
export { HeadPictureCardComponent } from "./src/main/ets/components/view/HeadPictureCardComponent"
export { ZhGridLayoutComponent } from "./src/main/ets/components/view/ZhGridLayoutComponent"
export { MultiPictureDetailPageComponent } from "./src/main/ets/components/MultiPictureDetailPageComponent"
export { AudioDetailComponent } from "./src/main/ets/components/AudioDetailComponent"
export { AudioSuspensionModel } from "./src/main/ets/viewmodel/AudioSuspensionModel"
export { BroadcastPageComponent } from "./src/main/ets/components/broadcast/BroadcastPageComponent"
export { FirstTabTopSearchComponent } from "./src/main/ets/components/search/FirstTabTopSearchComponent"
... ... @@ -64,3 +58,8 @@ export { FirstTabTopSearchComponent } from "./src/main/ets/components/search/Fir
export { ListHasNoMoreDataUI } from "./src/main/ets/components/reusable/ListHasNoMoreDataUI"
export { LottieView } from './src/main/ets/lottie/LottieView'
export { SpacialTopicPageComponent } from './src/main/ets/components/SpacialTopicPageComponent'
export { LogoutViewModel } from "./src/main/ets/viewmodel/LogoutViewModel"
... ...
... ... @@ -12,6 +12,7 @@ import { Card17Component } from './cardview/Card17Component';
import { Card15Component } from './cardview/Card15Component';
import { Card19Component } from './cardview/Card19Component';
import { Card20Component } from './cardview/Card20Component';
import { Card21Component } from './cardview/Card21Component';
/**
* card适配器,卡片样式汇总,依据ContentDTO#appStyle
... ... @@ -52,6 +53,8 @@ export struct CardParser {
Card19Component({ contentDTO })
} else if (contentDTO.appStyle === CompStyle.Card_20) {
Card20Component({ contentDTO })
} else if (contentDTO.appStyle === CompStyle.Card_21) {
Card21Component({ contentDTO })
}
else {
// todo:组件未实现 / Component Not Implemented
... ...
import { Logger } from 'wdKit';
import { MultiPictureDetailViewModel } from '../viewmodel/MultiPictureDetailViewModel';
import { ContentDetailDTO } from 'wdBean';
import media from '@ohos.multimedia.media';
import { OperRowListView } from './view/OperRowListView';
import { WDPlayerController } from 'wdPlayer/Index';
const TAG = 'DynamicDetailComponent'
@Preview
@Component
export struct DynamicDetailComponent {
//入参
private relId: string = ''
private contentId: string = ''
private relType: string = ''
//出参
@State contentDetailData: ContentDetailDTO[] = [] as ContentDetailDTO[]
async aboutToAppear() {
await this.getContentDetailData()
}
onPageHide() {
}
build() {
Row() {
Column(){
Text("this is a test!")
}
}
}
private async getContentDetailData() {
try {
let data = await MultiPictureDetailViewModel.getDetailData(this.relId, this.contentId, this.relType)
this.contentDetailData = data;
console.log('动态详情',JSON.stringify(this.contentDetailData))
} catch (exception) {
console.log('请求失败',JSON.stringify(exception))
}
}
}
\ No newline at end of file
... ...
... ... @@ -22,13 +22,6 @@ import { PageRepository } from '../repository/PageRepository';
const TAG = 'ImageAndTextPageComponent'
export interface OperationItem {
icon: Resource;
icon_check?: Resource;
text: string | Resource;
num?: number; // 个数
}
@Component
export struct ImageAndTextPageComponent {
scroller: Scroller = new Scroller();
... ... @@ -37,7 +30,6 @@ export struct ImageAndTextPageComponent {
@State recommendList: ContentDTO[] = []
@State newsStatusOfUser: batchLikeAndCollectResult | undefined = undefined // 点赞、收藏状态
@State interactData: InteractDataDTO = {} as InteractDataDTO
build() {
Column() {
// 发布时间
... ... @@ -64,66 +56,28 @@ export struct ImageAndTextPageComponent {
.objectFit(ImageFit.Cover)
.margin({ top: 10 })
}
.padding({ left: 15, right: 15, })
.padding({ left: 15, right: 15 })
.backgroundColor(Color.White)
Stack({ alignContent: Alignment.Bottom }) {
List() {
//详情展示区
ListItem() {
Scroll(this.scroller) {
Column() {
ImageAndTextWebComponent({
contentDetailData: this.contentDetailData,
action: this.action,
action: this.action
})
}.width(CommonConstants.FULL_WIDTH)
.height(CommonConstants.FULL_HEIGHT)
Column() {
if (this.recommendList.length > 0) {
RecommendList({ recommendList: this.recommendList })
}
if (this.contentDetailData[0]?.openLikes === 1) {
ListItem() {
// 点赞
Row() {
Row() {
if (this.newsStatusOfUser?.likeStatus === '1') {
Image(this.contentDetailData[0]?.likesStyle === 1 ? $r('app.media.ic_like_check') : (this.contentDetailData[0]?.likesStyle === 2 ? $r('app.media.icon_prayer_active') : $r('app.media.icon_candle_active')))
.width(24)
.height(24)
.margin({ right: 5 })
} else {
Image(this.contentDetailData[0]?.likesStyle === 1 ? $r('app.media.icon_like') : (this.contentDetailData[0]?.likesStyle === 2 ? $r('app.media.icon_prayer') : $r('app.media.icon_candle')))
.width(24)
.height(24)
.margin({ right: 5 })
}
Text(`${this.interactData?.likeNum || 0}`)
.fontSize(16)
.fontColor(this.newsStatusOfUser?.likeStatus === '1' ? '#ED2800' : '#999999')
.fontWeight(500)
}.alignItems(VerticalAlign.Center)
.onClick(() => {
this.toggleLikeStatus()
})
}.width(CommonConstants.FULL_WIDTH).height(80)
.justifyContent(FlexAlign.Center)
}
.border({
width: { bottom: 5 },
color: '#f5f5f5',
})
}
// 相关推荐区
ListItem() {
RecommendList({ recommendList: this.recommendList })
}
}
.width(CommonConstants.FULL_WIDTH)
.height(CommonConstants.FULL_HEIGHT)
.padding({ bottom: 56 })
.scrollBar(BarState.Off)
.edgeEffect(EdgeEffect.None)
.padding({ bottom: 76 })
// .scrollBar(BarState.Off)
//底部交互区
Row() {
... ... @@ -163,11 +117,143 @@ export struct ImageAndTextPageComponent {
.justifyContent(FlexAlign.SpaceBetween)
.backgroundColor(Color.White)
}
}.width(CommonConstants.FULL_WIDTH).height(CommonConstants.FULL_HEIGHT)
.backgroundColor(Color.White)
}
.width(CommonConstants.FULL_WIDTH)
.height(CommonConstants.FULL_HEIGHT)
}
// build() {
// Column() {
// // 发布时间
// Row() {
// Image($r('app.media.icon_ren_min_ri_bao'))
// .width(70)
// .height(28)
// Text(this.contentDetailData[0]?.publishTime)
// .fontColor($r('app.color.color_B0B0B0'))
// .fontSize($r('app.float.font_size_13'))
// .height('100%')
// .align(Alignment.End)
// }
// .width(CommonConstants.FULL_WIDTH)
// .height(32)
// .padding({ left: 15, right: 15, })
// .justifyContent(FlexAlign.SpaceBetween)
// .backgroundColor(Color.White)
//
// Row() {
// Image($r('app.media.line'))
// .width('100%')
// .height(6)
// .objectFit(ImageFit.Cover)
// .margin({ top: 10 })
// }
// .padding({ left: 15, right: 15, })
// .backgroundColor(Color.White)
//
// Stack({ alignContent: Alignment.Bottom }) {
//
// List() {
// //详情展示区
// ListItem() {
// Column() {
// ImageAndTextWebComponent({
// contentDetailData: this.contentDetailData,
// action: this.action,
// })
// }.width(CommonConstants.FULL_WIDTH)
// // .height(CommonConstants.FULL_HEIGHT)
// }
//
// if (this.contentDetailData[0]?.openLikes === 1) {
// ListItem() {
// // 点赞
// Row() {
// Row() {
// if (this.newsStatusOfUser?.likeStatus === '1') {
// Image(this.contentDetailData[0]?.likesStyle === 1 ? $r('app.media.ic_like_check') : (this.contentDetailData[0]?.likesStyle === 2 ? $r('app.media.icon_prayer_active') : $r('app.media.icon_candle_active')))
// .width(24)
// .height(24)
// .margin({ right: 5 })
// } else {
// Image(this.contentDetailData[0]?.likesStyle === 1 ? $r('app.media.icon_like') : (this.contentDetailData[0]?.likesStyle === 2 ? $r('app.media.icon_prayer') : $r('app.media.icon_candle')))
// .width(24)
// .height(24)
// .margin({ right: 5 })
// }
// Text(`${this.interactData?.likeNum || 0}`)
// .fontSize(16)
// .fontColor(this.newsStatusOfUser?.likeStatus === '1' ? '#ED2800' : '#999999')
// .fontWeight(500)
// }.alignItems(VerticalAlign.Center)
// .onClick(() => {
// this.toggleLikeStatus()
// })
//
// }.width(CommonConstants.FULL_WIDTH).height(80)
// .justifyContent(FlexAlign.Center)
// }
// .border({
// width: { bottom: 5 },
// color: '#f5f5f5',
// })
// }
//
// // 相关推荐区
// ListItem() {
// RecommendList({ recommendList: this.recommendList })
// }
// }
// .width(CommonConstants.FULL_WIDTH)
// .height(CommonConstants.FULL_HEIGHT)
// .padding({ bottom: 56 })
// .scrollBar(BarState.Off)
// .edgeEffect(EdgeEffect.None)
//
// //底部交互区
// Row() {
// Image($r('app.media.icon_arrow_left'))
// .width(24)
// .height(24)
// .onClick((event: ClickEvent) => {
// router.back()
// })
//
// Row() {
// Image($r('app.media.icon_comment'))
// .width(24)
// .height(24)
// .margin({ right: 24 })
// .id('comment')
//
// Image($r('app.media.icon_star'))
// .width(24)
// .height(24)
// .margin({ right: 24 })
//
// Image($r('app.media.icon_listen'))
// .width(24)
// .height(24)
// .margin({ right: 24 })
//
// Image($r('app.media.icon_forward'))
// .width(24)
// .height(24)
//
// }
// }
// .width(CommonConstants.FULL_WIDTH)
// .height(56)
// .padding({ left: 15, right: 15, bottom: 50, top: 20 })
// .justifyContent(FlexAlign.SpaceBetween)
// .backgroundColor(Color.White)
// }
//
// }.width(CommonConstants.FULL_WIDTH).height(CommonConstants.FULL_HEIGHT)
// .backgroundColor(Color.White)
//
// }
private async getDetail() {
let contentId: string = ''
let relId: string = ''
... ... @@ -199,7 +285,6 @@ export struct ImageAndTextPageComponent {
}
}
private async getRecommend() {
let params: postRecommendListParams = {
imei: "8272c108-4fa2-34ce-80b9-bc425a7c2a7e",
... ... @@ -211,10 +296,8 @@ export struct ImageAndTextPageComponent {
channelId: String(this.contentDetailData[0]?.reLInfo?.channelId)
}
let recommendList = await DetailViewModel.postRecommendList(params)
if (recommendList && recommendList.length > 0) {
this.recommendList = recommendList;
}
}
// 已登录->查询用户对作品点赞、收藏状态
private async getInteractDataStatus() {
... ...
... ... @@ -7,7 +7,7 @@ import {
ResponseBean
} from 'wdBean';
import { Logger } from 'wdKit';
import { WdWebComponent, WdWebLocalComponent } from 'wdWebComponent';
import { WdWebLocalComponent } from 'wdWebComponent';
import { NativeCallH5Type } from 'wdWebComponent/src/main/ets/pages/NativeCallH5Type';
import { BridgeWebViewControl } from 'wdJsBridge/Index';
... ... @@ -85,11 +85,6 @@ export struct ImageAndTextWebComponent {
webResource: $rawfile('apph5/index.html'),
backVisibility: false,
})
// WdWebLocalComponent({
// webviewControl: this.webviewControl,
// webResource: "http://pd-people-uat.pdnews.cn/articletopic/35398-10000015965",
// backVisibility: false,
// })
}
}
... ... @@ -97,7 +92,7 @@ export struct ImageAndTextWebComponent {
Logger.debug('ImageAndTextWebComponent', 'jsCall_receiveAppData');
this.webviewControl.callHandle(NativeCallH5Type.jsCall_receiveAppData,
JSON.stringify(h5ReceiveAppData), (data: string) => {
// Logger.debug('ImageAndTextWebComponent', "from js data = " + data);
Logger.debug('ImageAndTextWebComponent', "from js data = " + data);
})
}
}
\ No newline at end of file
... ...
import { Action, ContentDetailDTO, } from 'wdBean';
import DetailViewModel from '../viewmodel/DetailViewModel';
import { WdWebComponent } from 'wdWebComponent';
import router from '@ohos.router';
import { CommonConstants } from 'wdConstant'
import { BridgeWebViewControl } from 'wdJsBridge/Index';
const TAG = 'SpacialTopicPageComponent'
@Component
export struct SpacialTopicPageComponent {
webviewControl: BridgeWebViewControl = new BridgeWebViewControl()
scroller: Scroller = new Scroller();
action: Action = {} as Action
@State webUrl: string = '';
build() {
Column() {
Stack({ alignContent: Alignment.Bottom }) {
Column() {
WdWebComponent({
webviewControl: this.webviewControl,
webUrl: this.webUrl,
backVisibility: false,
})
}
.padding({ bottom: 56 })
.width(CommonConstants.FULL_WIDTH)
.height(CommonConstants.FULL_HEIGHT)
//底部交互区
Row() {
Image($r('app.media.icon_arrow_left'))
.width(24)
.height(24)
.onClick((event: ClickEvent) => {
router.back()
})
Row() {
Image($r('app.media.icon_comment'))
.width(24)
.height(24)
.margin({ right: 24 })
.id('comment')
Image($r('app.media.icon_star'))
.width(24)
.height(24)
.margin({ right: 24 })
Image($r('app.media.icon_listen'))
.width(24)
.height(24)
.margin({ right: 24 })
Image($r('app.media.icon_forward'))
.width(24)
.height(24)
}
}
.width(CommonConstants.FULL_WIDTH)
.height(56)
.padding({ left: 15, right: 15, bottom: 20, top: 20 })
.justifyContent(FlexAlign.SpaceBetween)
.backgroundColor(Color.White)
}
}.width(CommonConstants.FULL_WIDTH).height(CommonConstants.FULL_HEIGHT)
.backgroundColor(Color.White)
}
aboutToAppear() {
let action: Action = router.getParams() as Action
if (action) {
this.webUrl = action.params?.url || ''
}
}
aboutToDisappear() {
}
}
\ No newline at end of file
... ...
import { ContentDTO } from 'wdBean'
import { CommonConstants } from 'wdConstant/Index';
import { DateTimeUtils } from 'wdKit/Index';
@Component
export struct CardSourceInfo {
@State contentDTO: ContentDTO = {} as ContentDTO;
build() {
Flex() {
if(this.contentDTO.corner) {
Text(this.contentDTO.corner)
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_ED2800"))
.margin({right: 2})
}
if(this.contentDTO.rmhPlatform === 1) {
Text(this.contentDTO.rmhInfo.rmhName)
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
.maxLines(1)
.textOverflow({overflow: TextOverflow.Ellipsis})
Image($r("app.media.point"))
.width(16)
.height(16)
} else if(this.contentDTO.source) {
Text(`${this.contentDTO.source}`)
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
.maxLines(1)
.textOverflow({overflow: TextOverflow.Ellipsis})
Image($r("app.media.point"))
.width(16)
.height(16)
}
// TODO 这里还有个判断需要完善,依赖外部,新闻tab下的卡片,2天之前的不显示时间。但是如果是搜索情况下展示的卡片,显示时间
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
.margin({ right: 6 })
.flexShrink(0)
if(this.contentDTO?.interactData?.commentNum) {
Text(`${this.contentDTO.interactData.commentNum}评`)
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
.flexShrink(0)
}
}
.width(CommonConstants.FULL_WIDTH)
.margin({ top: 8 })
}
}
\ No newline at end of file
... ...
... ... @@ -2,7 +2,8 @@ import { ContentDTO, slideShows } from 'wdBean';
import { CommonConstants } from 'wdConstant'
import { DateTimeUtils } from 'wdKit';
import { ProcessUtils } from '../../utils/ProcessUtils';
import { CardSourceInfo } from '../cardCommon/CardSourceInfo'
import { CardMediaInfo } from '../cardCommon/CardMediaInfo'
/**
* 大专题卡--CompStyle: 10
... ... @@ -76,10 +77,10 @@ export struct Card10Component {
}
.width(CommonConstants.FULL_WIDTH)
.padding({
top: 14,
left: 16,
right: 16,
bottom: 14
left: $r('app.float.card_comp_pagePadding_lf'),
right: $r('app.float.card_comp_pagePadding_lf'),
top: $r('app.float.card_comp_pagePadding_tb'),
bottom: $r('app.float.card_comp_pagePadding_tb')
})
.backgroundColor($r("app.color.white"))
.margin({ bottom: 8 })
... ... @@ -95,25 +96,14 @@ export struct Card10Component {
.fontColor($r('app.color.color_222222'))
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Row() {
// 展示发稿人
if (item.source) {
Text(item.source)
.fontSize($r('app.float.font_size_12'))
.fontColor($r('app.color.color_B0B0B0'))
.textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(1)
.width(item.source.length > 10 ? '60%' : '')
Image($r('app.media.point'))
.width(16)
.height(16)
}
Text(DateTimeUtils.getCommentTime(Number.parseFloat(String(item.publishTime))))
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
CardSourceInfo(
{
contentDTO: {
publishTime: item.publishTime || '',
source: item.source || ''
} as ContentDTO
}
.margin({ top: 12 })
)
}
.layoutWeight(1)
.alignItems(HorizontalAlign.Start)
... ...
... ... @@ -3,7 +3,7 @@ import { CommonConstants } from 'wdConstant'
import { ContentDTO } from 'wdBean'
import { DateTimeUtils } from 'wdKit'
import { ProcessUtils } from '../../utils/ProcessUtils';
import { CardSourceInfo } from '../cardCommon/CardSourceInfo'
const TAG = 'Card11Component';
/**
... ... @@ -21,29 +21,8 @@ export struct Card11Component {
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.width(CommonConstants.FULL_WIDTH)
Row() {
if (this.contentDTO.source) {
Text(this.contentDTO.source)
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
.margin({ left: 6 })
Image($r("app.media.point"))
.width(16)
.height(16)
}
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
.margin({ right: 6 })
// TODO '评论取哪个字段'
// Text(`1806评`)
// .fontSize($r("app.float.font_size_12"))
// .fontColor($r("app.color.color_B0B0B0"))
}.width(CommonConstants.FULL_WIDTH)
.justifyContent(FlexAlign.Start)
.margin({ top: 8 })
// 评论等信息
CardSourceInfo({ contentDTO: this.contentDTO })
}.width(CommonConstants.FULL_WIDTH)
.padding({
left: $r('app.float.card_comp_pagePadding_lf'),
... ...
import { ContentDTO } from 'wdBean';
import { RmhTitle } from '../cardCommon/RmhTitle'
import { CardMediaInfo } from '../cardCommon/CardMediaInfo'
import { CommonConstants } from 'wdConstant/Index';
const TAG = 'Card12Component';
/**
* 人民号-动态---12:人民号无图卡;
*/
@Component
export struct Card12Component {
@State contentDTO: ContentDTO = {
appStyle: '20',
coverType: 1,
coverUrl: 'https://rmrbcmsonline.peopleapp.com/upload/user_app/gov_dynamic/video/default_image/202105/rmrb_default_image_4GdWrgSw1622451312.jpg?x-oss-process=image/resize,m_fill,h_480,w_360/quality,q_90',
fullColumnImgUrls: [
{
landscape: 1,
size: 1,
url: 'https://rmrbcmsonline.peopleapp.com/upload/user_app/gov_dynamic/video/default_image/202105/rmrb_default_image_4GdWrgSw1622451312.jpg?x-oss-process=image/resize,m_fill,h_480,w_360/quality,q_90',
weight: 1600
}
],
newsTitle: '好玩!》10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人',
rmhInfo: {
authIcon:
'https://cdnjdphoto.aikan.pdnews.cn/creator-category/icon/auth/yellow.png',
authTitle: '10后音乐人王烁然个人人民号',
authTitle2: '10后音乐人王烁然个人人民号',
banControl: 0,
cnIsAttention: 1,
rmhDesc: '10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人',
rmhHeadUrl: 'https://cdnjdphoto.aikan.pdnews.cn/image/creator/rmh/20221031/3d3419e86a.jpeg?x-oss-process=image/resize,l_100/auto-orient,1/quality,q_90/format,jpg',
rmhName: '王烁然',
userId: '522435359667845',
userType: '2'
},
objectType: '1',
videoInfo: {
firstFrameImageUri: '',
videoDuration: 37,
videoUrl: 'https://rmrbcmsonline.peopleapp.com/upload/user_app/gov_dynamic/video/mp4/202105/rmrb_GSNARt6P1622451310.mp4'
}
} as ContentDTO;
aboutToAppear(): void {
}
build() {
Column() {
// rmh信息
RmhTitle({ rmhInfo: this.contentDTO.rmhInfo })
// 标题
if (this.contentDTO.newsTitle) {
Text(this.contentDTO.newsTitle)
.fontSize($r('app.float.font_size_17'))
.fontColor($r('app.color.color_222222'))
.width(CommonConstants.FULL_WIDTH)
.textOverflowStyle(3)
.margin({ bottom: 8 })
.height(75)
.lineHeight(25)
.fontFamily('PingFang SC-Regular')
}
// if (this.contentDTO.fullColumnImgUrls?.[0]) {
// createImg({ contentDTO: this.contentDTO })
// }
//TODO 底部的:分享、评论、点赞 功能;需要引用一个公共组件
}
.padding({
left: $r('app.float.card_comp_pagePadding_lf'),
right: $r('app.float.card_comp_pagePadding_lf'),
top: $r('app.float.card_comp_pagePadding_tb'),
bottom: $r('app.float.card_comp_pagePadding_tb')
})
}
}
interface radiusType {
topLeft: number | Resource;
topRight: number | Resource;
bottomLeft: number | Resource;
bottomRight: number | Resource;
}
@Component
struct createImg {
@Prop contentDTO: ContentDTO
build() {
GridRow() {
if (this.contentDTO.fullColumnImgUrls[0].landscape === 1) {
// 横屏
GridCol({
span: { xs: 12 }
}) {
Stack() {
Image(this.contentDTO.coverUrl)
.width(CommonConstants.FULL_WIDTH)
.aspectRatio(16 / 9)
.borderRadius($r('app.float.image_border_radius'))
CardMediaInfo({ contentDTO: this.contentDTO })
}
.align(Alignment.BottomEnd)
}
} else {
// 竖图显示,宽度占50%,高度自适应
GridCol({
span: { xs: 6 }
}) {
Stack() {
Image(this.contentDTO.coverUrl)
.width(CommonConstants.FULL_WIDTH)
.borderRadius($r('app.float.image_border_radius'))
CardMediaInfo({ contentDTO: this.contentDTO })
}
.align(Alignment.BottomEnd)
}
}
}
}
}
@Extend(Text)
function textOverflowStyle(maxLine: number) {
.maxLines(maxLine)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
\ No newline at end of file
... ...
import { ContentDTO } from 'wdBean';
import { RmhTitle } from '../cardCommon/RmhTitle'
import { CardMediaInfo } from '../cardCommon/CardMediaInfo'
import { CommonConstants } from 'wdConstant/Index';
const TAG = 'Card12Component';
/**
* 人民号-动态---12:人民号无图卡;
*/
@Entry
@Component
export struct Card12Component {
@State contentDTO: ContentDTO = {
appStyle: '20',
coverType: 1,
coverUrl: 'https://rmrbcmsonline.peopleapp.com/upload/user_app/gov_dynamic/video/default_image/202105/rmrb_default_image_4GdWrgSw1622451312.jpg?x-oss-process=image/resize,m_fill,h_480,w_360/quality,q_90',
fullColumnImgUrls: [
{
landscape: 1,
size: 1,
url: 'https://rmrbcmsonline.peopleapp.com/upload/user_app/gov_dynamic/video/default_image/202105/rmrb_default_image_4GdWrgSw1622451312.jpg?x-oss-process=image/resize,m_fill,h_480,w_360/quality,q_90',
weight: 1600
}
],
newsTitle: '好玩!》10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人',
rmhInfo: {
authIcon:
'https://cdnjdphoto.aikan.pdnews.cn/creator-category/icon/auth/yellow.png',
authTitle: '10后音乐人王烁然个人人民号',
authTitle2: '10后音乐人王烁然个人人民号',
banControl: 0,
cnIsAttention: 1,
rmhDesc: '10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人10后少年音乐人',
rmhHeadUrl: 'https://cdnjdphoto.aikan.pdnews.cn/image/creator/rmh/20221031/3d3419e86a.jpeg?x-oss-process=image/resize,l_100/auto-orient,1/quality,q_90/format,jpg',
rmhName: '王烁然',
userId: '522435359667845',
userType: '2'
},
objectType: '1',
videoInfo: {
firstFrameImageUri: '',
videoDuration: 37,
videoUrl: 'https://rmrbcmsonline.peopleapp.com/upload/user_app/gov_dynamic/video/mp4/202105/rmrb_GSNARt6P1622451310.mp4'
}
} as ContentDTO;
aboutToAppear(): void {
}
build() {
Column() {
// rmh信息
RmhTitle({ rmhInfo: this.contentDTO.rmhInfo })
// 左标题,右图
Flex({ direction: FlexDirection.Row }) {
Text(this.contentDTO.newsTitle)
.fontSize($r('app.float.font_size_17'))
.fontColor($r('app.color.color_222222'))
.textOverflowStyle(3)
.lineHeight(25)
.fontFamily('PingFang SC-Regular')
.textAlign(TextAlign.Start)
.flexBasis('auto')
.margin({right: 12})
Image(this.contentDTO.coverUrl)
.flexBasis(174)
.height(75)
.borderRadius($r('app.float.image_border_radius'))
// .flexBasis(160)
.backgroundImageSize(ImageSize.Auto)
}
.width(CommonConstants.FULL_WIDTH)
.margin({ bottom: 8 })
.height(75)
//TODO 底部的:分享、评论、点赞 功能;需要引用一个公共组件
}
.padding({
left: $r('app.float.card_comp_pagePadding_lf'),
right: $r('app.float.card_comp_pagePadding_lf'),
top: $r('app.float.card_comp_pagePadding_tb'),
bottom: $r('app.float.card_comp_pagePadding_tb')
})
}
}
interface radiusType {
topLeft: number | Resource;
topRight: number | Resource;
bottomLeft: number | Resource;
bottomRight: number | Resource;
}
@Extend(Text)
function textOverflowStyle(maxLine: number) {
.maxLines(maxLine)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
\ No newline at end of file
... ...
... ... @@ -4,7 +4,7 @@ import { CommonConstants } from 'wdConstant/Index';
import { DateTimeUtils } from 'wdKit';
import { WDRouterRule } from 'wdRouter';
import { CardMediaInfo } from '../cardCommon/CardMediaInfo'
import { CardSourceInfo } from '../cardCommon/CardSourceInfo'
const TAG = 'Card17Component';
/**
... ... @@ -81,25 +81,8 @@ export struct Card17Component {
};
WDRouterRule.jumpWithAction(taskAction)
})
Row() {
if (this.contentDTO.source) {
Text(this.contentDTO.source)
.fontSize($r('app.float.font_size_13'))
.fontColor($r('app.color.color_B0B0B0'))
Image($r('app.media.point'))
.width(16)
.height(16)
}
if (this.contentDTO.publishTime && this.contentDTO.publishTime.length === 13) {
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
.fontSize($r('app.float.font_size_13'))
.fontColor($r('app.color.color_B0B0B0'))
}
}
.width(CommonConstants.FULL_WIDTH)
.height(16)
.id('label')
// 评论等信息
CardSourceInfo({ contentDTO: this.contentDTO })
}
.width(CommonConstants.FULL_WIDTH)
.padding({
... ...
import { ContentDTO } from 'wdBean';
import { CommonConstants, CompStyle } from 'wdConstant';
import { ProcessUtils } from '../../utils/ProcessUtils';
import { RmhTitle } from '../cardCommon/RmhTitle'
import { CardMediaInfo } from '../cardCommon/CardMediaInfo'
const TAG: string = 'Card6Component-Card13Component';
/**
* 卡片样式:"appStyle":"21" 小视频卡人民号
*/
@Component
export struct Card21Component {
@State contentDTO: ContentDTO = {} as ContentDTO;
build() {
Column() {
// 顶部 rmh信息
RmhTitle({ rmhInfo: this.contentDTO.rmhInfo })
// 中间内容
Grid() {
GridItem() {
Text(`${this.contentDTO.newsTitle}`)
.fontSize($r('app.float.selected_text_size'))
.fontColor($r('app.color.color_222222'))
.width(CommonConstants.FULL_WIDTH)
.maxLines(4)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.padding({ right: 12 })
.lineHeight(26)
}
GridItem() {
Stack() {
Image(this.contentDTO.coverUrl)
.width(CommonConstants.FULL_WIDTH)
.borderRadius($r('app.float.image_border_radius'))
CardMediaInfo({ contentDTO: this.contentDTO })
}
.alignContent(Alignment.BottomEnd)
}
}
.columnsTemplate('2fr 1fr')
.maxCount(1)
//TODO 底部的:分享、评论、点赞 功能;需要引用一个公共组件
}
.onClick((event: ClickEvent) => {
ProcessUtils.processPage(this.contentDTO)
})
.padding({
left: $r('app.float.card_comp_pagePadding_lf'),
right: $r('app.float.card_comp_pagePadding_lf'),
top: $r('app.float.card_comp_pagePadding_tb'),
bottom: $r('app.float.card_comp_pagePadding_tb')
})
.width(CommonConstants.FULL_WIDTH)
}
}
\ No newline at end of file
... ...
//全标题 "appStyle":"2",
import { ContentDTO } from 'wdBean';
import { CommonConstants } from 'wdConstant/Index';
import { DateTimeUtils } from 'wdKit/Index';
import { ProcessUtils } from '../../utils/ProcessUtils';
import { CardMediaInfo } from '../cardCommon/CardMediaInfo'
import { CardSourceInfo } from '../cardCommon/CardSourceInfo'
const TAG: string = 'Card2Component';
/**
... ... @@ -60,21 +59,8 @@ export struct Card2Component {
.alignItems(HorizontalAlign.Start)
//bottom
Row() {
Text(this.contentDTO.source)
.bottomTextStyle()
//间隔点
Image($r('app.media.point'))
.width(12)
.height(12)
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
.bottomTextStyle()
}
.width(CommonConstants.FULL_WIDTH)
.height(18)
.justifyContent(FlexAlign.Start)
.margin({ top: 8 })
// 评论等信息
CardSourceInfo({ contentDTO: this.contentDTO })
}
.width(CommonConstants.FULL_WIDTH)
.padding({
... ...
import { ContentDTO } from 'wdBean';
import { CommonConstants } from 'wdConstant'
import { DateTimeUtils } from 'wdKit/src/main/ets/utils/DateTimeUtils'
import { ProcessUtils } from '../../utils/ProcessUtils';
import { CardSourceInfo } from '../cardCommon/CardSourceInfo'
/**
* 卡片样式:"appStyle":"3"
... ... @@ -27,30 +27,8 @@ export struct Card3Component {
.fontSize($r("app.float.font_size_16"))
.fontColor($r("app.color.color_222222"))
.width(CommonConstants.FULL_WIDTH)
Row() {
// TODO "锐评"取得哪个字段,什么时候显示。
// Text("锐评")
// .fontSize($r("app.float.font_size_12"))
// .fontColor($r("app.color.color_ED2800"))
if(this.contentDTO.source) {
Text(this.contentDTO.source)
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
Image($r("app.media.point"))
.width(16)
.height(16)
}
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
.margin({ right: 6 })
// TODO '评论取哪个字段'
// Text(`1806评`)
// .fontSize($r("app.float.font_size_12"))
// .fontColor($r("app.color.color_B0B0B0"))
}.width(CommonConstants.FULL_WIDTH)
.justifyContent(FlexAlign.Start)
.margin({ top: 8 })
// 评论等信息
CardSourceInfo({ contentDTO: this.contentDTO })
}
.width(CommonConstants.FULL_WIDTH)
.padding({
... ...
import { ContentDTO, FullColumnImgUrlDTO } from 'wdBean';
import { CommonConstants } from 'wdConstant/Index';
import { ProcessUtils } from '../../utils/ProcessUtils';
import { DateTimeUtils } from 'wdKit/Index';
import { CardSourceInfo } from '../cardCommon/CardSourceInfo'
const TAG: string = 'Card4Component';
/**
... ... @@ -110,25 +109,8 @@ export struct Card4Component {
.onClick((event: ClickEvent) => {
ProcessUtils.processPage(this.contentDTO)
})
//bottom
Row() {
Text(this.contentDTO.source)
.bottomTextStyle()
//间隔点
Image($r('app.media.point'))
.width(12)
.height(12)
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
.bottomTextStyle()
// TODO 评论字段取值
// Text('518条评论')
// .bottomTextStyle()
}
.width('100%')
.justifyContent(FlexAlign.Start)
.margin({ top: 8 })
//bottom 评论等信息
CardSourceInfo({ contentDTO: this.contentDTO })
}
.width(CommonConstants.FULL_WIDTH)
.padding({
... ...
import { ContentDTO } from 'wdBean';
import { CommonConstants, CompStyle } from 'wdConstant';
import { DateTimeUtils } from 'wdKit';
import { ProcessUtils } from '../../utils/ProcessUtils';
import { CardSourceInfo } from '../cardCommon/CardSourceInfo'
import { CardMediaInfo } from '../cardCommon/CardMediaInfo'
const TAG: string = 'Card6Component-Card13Component';
const FULL_PARENT: string = '100%';
/**
* 卡片样式:"appStyle":"6"以及13
* 卡片样式:"appStyle":"6"以及13--- 小视频卡
*/
@Component
export struct Card6Component {
... ... @@ -17,7 +16,17 @@ export struct Card6Component {
Row() {
Column() {
Column() {
Text(this.contentDTO.newsTitle)
// TODO 这个tag涉及样式问题。待优化。
// if (this.contentDTO.newTags) {
// Text(this.contentDTO.newTags)
// .backgroundColor($r('app.color.color_ED2800'))
// .borderRadius($r('app.float.button_border_radius'))
// .fontColor($r('app.color.color_fff'))
// .fontSize($r('app.float.font_size_12'))
// .padding(2)
// .margin({ right: 2 })
// }
Text(`${this.contentDTO.newsTitle}`)
.fontSize(16)
.fontWeight(FontWeight.Normal)
.maxLines(3)//
... ... @@ -26,93 +35,35 @@ export struct Card6Component {
}.height("80%")
.justifyContent(FlexAlign.Start)
Row() {
if (this.contentDTO.source) {
Text(this.contentDTO.source)
.fontSize($r('app.float.font_size_12'))
.fontColor(Color.Gray)
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })// 超出的部分显示省略号。
.width(this.contentDTO.source.length > 8 ? '50%' : '')
Image($r('app.media.point'))
.width(16)
.height(16)
}
if (this.contentDTO.publishTime && this.contentDTO.publishTime.length === 13) {
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
.fontSize($r('app.float.font_size_12'))
.fontColor(Color.Gray)
}
Text(this.contentDTO.visitorComment + '评')
.fontSize($r('app.float.font_size_12'))
.fontColor(Color.Gray)
.padding({
left: 5
})
}.alignSelf(ItemAlign.Start)
.height("20%")
.justifyContent(FlexAlign.Start)
//bottom 评论等信息
CardSourceInfo({ contentDTO: this.contentDTO })
}
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Start)
.width('58%')
Blank(16)
if (this.contentDTO.coverUrl) {
Stack() {
Image(this.contentDTO.coverUrl)
.borderRadius(5)
.aspectRatio(this.contentDTO.appStyle === CompStyle.Card_13 ? 3 / 2 : 3 / 4)
.height(this.contentDTO.appStyle === CompStyle.Card_13 ? 90 : 180)
if (this.contentDTO.videoInfo) {
Row() {
Image($r('app.media.iv_card_play_yellow_flag'))
.width(22)
.height(18)
Text(DateTimeUtils.getFormattedDuration(this.contentDTO.videoInfo.videoDuration * 1000))
.fontSize($r('app.float.font_size_13'))
.fontWeight(400)
.fontColor($r('app.color.color_fff'))
CardMediaInfo({ contentDTO: this.contentDTO })
}
.alignItems(VerticalAlign.Bottom)
.height(18)
.padding({ right: 4 })
.margin({
right: 4,
bottom: 4
})
.backgroundColor($r('app.color.color_4d000000'))
} else if (this.contentDTO.voiceInfo) {
Row() {
Image($r('app.media.icon_listen'))
.width(22)
.height(18)
Text(DateTimeUtils.getFormattedDuration(this.contentDTO.voiceInfo
.voiceDuration * 1000))
.fontSize($r('app.float.font_size_13'))
.fontWeight(400)
.fontColor($r('app.color.color_fff'))
}
.alignItems(VerticalAlign.Bottom)
.height(18)
.padding({ right: 4 })
.margin({
right: 4,
bottom: 4
})
.backgroundColor($r('app.color.color_4d000000'))
}
}.alignContent(Alignment.BottomEnd)
.alignContent(Alignment.BottomEnd)
}
}
.onClick((event: ClickEvent) => {
ProcessUtils.processPage(this.contentDTO)
})
.padding(
{ top: 16, bottom: 16, left: 14, right: 14 })
.width(FULL_PARENT)
.padding({
left: $r('app.float.card_comp_pagePadding_lf'),
right: $r('app.float.card_comp_pagePadding_lf'),
top: $r('app.float.card_comp_pagePadding_tb'),
bottom: $r('app.float.card_comp_pagePadding_tb')
})
.width(CommonConstants.FULL_WIDTH)
.height(this.contentDTO.appStyle === CompStyle.Card_13 ? 127 : 217)
.justifyContent(FlexAlign.SpaceBetween)
}
}
\ No newline at end of file
... ...
import PageModel from '../../../viewmodel/PageModel'
/// 所有用户类型定义
/// 1--普通账户正常;--不能直播、点播
/// 2--视频号,可以直播、点播;显示查看修改都是自己的信息;
/// 3--矩阵号,是有视频号升级来的;可以登陆app,我的里面是自己的信息;发评论、发视频、直播都是自己;矩阵号下面可以挂视频号、运营子账号;
/// 4--运营子账号,登陆使用的是自己的userId手机,密码;显示是对应视频号的信息,我的里面是视频号的信息,无法更改基本信息,自己没有头像,昵称信息;发点播、发直播、发评论,都是对应视频号的身份发送的;还是需要记录子账号的userId;(评论表 userId,userType,creatorId)
export enum WDPublicUserType {
/// 未知类型
WDPublicUserType_Unkown = 0,
/// 普通用户
WDPublicUserType_NormalUser = 1,
/// 号主
WDPublicUserType_AccountOwner = 2,
/// 矩阵号
WDPublicUserType_Matrix = 3,
/// 运营子账号
WDPublicUserType_OperatingSubAccount = 4,
/// 内容源账号
WDPublicUserType_ContentSourceAccount = 5,
}
@Observed
export class commentListModel extends PageModel{
pageNum: number = 0
pageSize: number = 0
totalCount: number = 0
hasNext: number = 0
list: commentItemModel[] = []
}
@Observed
export class commentItemModel {
authorLike: string = ''
avatarFrame: string = ''
checkStatus: string = ''
childCommentNum: string = ''
childComments: commentItemModel[] = []
commentContent: string = ''
commentContentSensitive: string = ''
commentLevel: number = 0
commentPics: string = ''
commentSensitive: string = ''
commentType: number = 0
contentAuthor: number = 0
createTime: string = ''
creatorFlag: string = ''
fromCreatorId: string = ''
fromDeviceId: string = ''
fromUserHeader: string = ''
fromUserId: string = ''
fromUserName: string = ''
fromUserType: WDPublicUserType = 0
id: string = ''
likeNum: string = ''
/*是否点赞*/
isLike: boolean = false
mySelf: string = ''
parentId: string = ''
region: string = ''
replyNum: string = ''
rootCommentId: string = ''
sensitiveExist: string = ''
sensitiveShow: string = ''
toUserContentAuthor: string = ''
toUserId: string = ''
toUserName: string = ''
toUserType: string = ''
topFlag: string = ''
uuid: string = ''
/*本地使用,收起时默认3行 -1为不限制行数*/
maxLine: number = 3
/*是否有展示更多*/
hasMore:boolean = false
/*当有展示更多的时候,当前的状态是展开还是收起*/
expanded:boolean = false
highQualityExpireTime:string = '';
highQualityTime:string = '';
targetTitle:string = '';
targetStatus:string = '';
targetId:string = '';
targetRelId:string = '';
targetRelObjectId:string = '';
targetRelType:string = '';
targetType:string = '';
visitorComment:string = '';
shareInfo:commentItemShareInfoModel = new commentItemShareInfoModel;
// targetId:string = '';
// targetId:string = '';
// targetId:string = '';
}
export class commentItemShareInfoModel {
shareCoverUrl: string = ''
shareSummary: string = ''
shareTitle: string = ''
shareUrl: string = ''
}
\ No newline at end of file
... ...
import ArrayList from '@ohos.util.ArrayList'
import { ViewType } from 'wdConstant/Index';
import { DateTimeUtils, LazyDataSource } from 'wdKit/Index';
import PageModel from '../../../viewmodel/PageModel';
import { commentItemModel, commentListModel, WDPublicUserType } from '../model/CommentModel';
import commentViewModel from '../viewmodel/CommentViewModel'
import { CommentText } from './CommentText';
import measure from '@ohos.measure'
@Entry
@Preview
@Component
export struct CommentComponent {
@State private browSingModel: commentListModel = new commentListModel()
isloading: boolean = false
// @State allDatas :commentItemModel[] = [];
@State allDatas: LazyDataSource<commentItemModel> = new LazyDataSource();
aboutToAppear() {
this.getData();
this.getData();
this.getData();
this.getData();
}
/*标题:全部评论*/
@Builder
titleHeader() {
Row() {
Row() {
Image($r('app.media.redLine'))
.height(16)
.width(3)
Text('全部评论')
.fontSize(18)// .fontColor('#222222')
.fontColor($r('app.color.color_222222'))
.fontWeight(FontWeight.Medium)
.margin({ left: 5 })
}
.margin({ left: 16 })
}.height(44)
.width('100%')
.justifyContent(FlexAlign.SpaceBetween);
}
/*1级评论作为titleHeader*/
@Builder
CommentHeaderItem(item: commentItemModel) {
Column() {
Row() {
//头像
Stack() {
Image(item.fromUserHeader)
.alt($r('app.media.default_head'))
.width('32')
.height('32')
.objectFit(ImageFit.Cover)
.borderRadius(16)
Image($r('app.media.icon_border_test'))
.width('48')
.height('48')
.objectFit(ImageFit.Cover)
.borderRadius(24)
}
.width(48)
.height(48)
.margin({ left: 8 })
.alignContent(Alignment.Center)
.onClick(() => {
// TODO 跳转个人详情
})
//昵称
Text(item.fromUserName)
.fontSize(14)
.fontColor($r('app.color.color_222222'))
.fontWeight(FontWeight.Medium)
.margin({ left: 5 })
/// 暂时不显示 “我” 的标签了
/// 人民号>置顶>作者
//人民号
// if (item.fromUserType === WDPublicUserType.WDPublicUserType_Matrix) {
Image($r('app.media.comment_rmh_tag')).width(20).height(20).margin({ left: 5 });
// }
//置顶
// if (item.topFlag) {
Image($r('app.media.comment_icon_zhiding')).width(30).height(18).margin({ left: 5 });
// }
//作者
// if (item.contentAuthor === 1) {
Text('作者')
.fontSize(11)
.fontColor('#968562')
.backgroundColor('#F1EFEB')
.textAlign(TextAlign.Center)
.borderRadius(2)
.width(30)
.height(18)
.margin({ left: 5 });
// }
}
CommentText({
longMessage: item.commentContent,
maxline: 3,
fontSize: 16,
fontWeight: FontWeight.Regular,
marginWidth: (59 + 16)
})
.margin({ left: 59, right: 16 })
this.CommentFooterView(item);
}.alignItems(HorizontalAlign.Start)
}
/*查看更多和收起*/
@Builder
GroupFooterView(item: commentItemModel) {
Row() {
if (item.expanded){
Row() {
Text('收起').fontColor($r('app.color.color_222222')).fontSize(14)
Image($r('app.media.comment_pickUp')).width(12).height(12)
}.margin({ left: 213 })
}else {
Row() {
Text().backgroundColor($r('app.color.color_EDEDED')).width(24).height(1)
Text('查看更多回复').fontColor($r('app.color.color_222222')).fontSize(14).margin({ left: 6 })
Image($r('app.media.comment_unfold')).width(12).height(12)
}.margin({ left: 53 })
}
}.height(30)
}
/*评论内容下面的IP地址时间点赞*/
@Builder
CommentFooterView(item: commentItemModel) {
Row() {
Row({ space: 6 }) {
Text(item.region ? (item.region + '网友') : '人民日报客户端网友')
.fontColor($r('app.color.color_B0B0B0'))
.fontSize(12);
Image($r('app.media.comment_hyphen'))
.size({
width: 4,
height: 4
})
//TODO: 时间格式需要本地调整
// / 展现专用,用于获取多久之前
// ///小于1分钟:刚刚
// ///1~60分钟:x分钟前
// ///1小时~1天:x小时前
// ///1天~2天:1天前
// ///2天~:日期隐藏
Text(DateTimeUtils.getCommentTime(Number.parseFloat(item.createTime)))
.fontColor($r('app.color.color_B0B0B0'))
.fontSize(12)
Image($r('app.media.comment_hyphen_block'))
.size({
width: 4,
height: 4
})
Text('回复')
.fontColor($r('app.color.color_222222'))
.fontSize(12)
.onClick(() => {
//TODO: 回复
})
}
Row({ space: 6 }) {
Text(item.likeNum)
.fontColor($r('app.color.color_666666'))
.fontSize(14)
Image($r('app.media.comment_like_normal'))
.size({
width: 16,
height: 16
})
.onClick(() => {
//TODO: 点赞
})
}
}
.justifyContent(FlexAlign.SpaceBetween)
.height(30)
.margin({ left: 59, right: 16 })
}
build() {
Column() {
List() {
ListItemGroup({ header: this.titleHeader() })
LazyForEach(this.allDatas, (item: commentItemModel, index: number) => {
if (item.hasMore) {
ListItemGroup({ header: this.CommentHeaderItem(item), footer: this.GroupFooterView(item) }) {
ForEach(item.childComments, (childItem: commentItemModel, subIndex: number) => {
ListItem() {
ChildCommentItem();
}
})
}
}else {
ListItemGroup({ header: this.CommentHeaderItem(item)}) {
ForEach(item.childComments, (childItem: commentItemModel, subIndex: number) => {
ListItem() {
ChildCommentItem();
}
})
}
}
})
}.layoutWeight(1)
}
}
//获取数据
async getData() {
this.browSingModel.currentPage = 1
commentViewModel.getCommentLocal(getContext()).then(commentListModel => {
if (commentListModel && commentListModel.list && commentListModel.list.length > 0) {
commentListModel.hasMore = true;
this.browSingModel.viewType = ViewType.LOADED;
this.allDatas.push(...commentListModel.list)
if (commentListModel.list.length === this.browSingModel.pageSize) {
this.browSingModel.currentPage++;
this.browSingModel.hasMore = true;
} else {
this.browSingModel.hasMore = false;
}
} else {
this.browSingModel.viewType = ViewType.EMPTY;
}
})
}
/*回复评论*/
ReplyComment() {
}
}
@Component
struct ChildCommentItem {
build() {
Text('child')
}
}
... ...
import measure from '@ohos.measure'
import curves from '@ohos.curves';
import { BusinessError } from '@ohos.base';
import display from '@ohos.display';
const collapseString = '...展开全文'
const uncollapseString = '...收起'
@Component
@Preview
export struct CommentText {
// 长文本
@State longMessage: string = ''
// 最大显示行数
@State maxLineMesssage: string = '';
@State lines: number = 3;
@State maxline: number = 3;
@State marginWidth:number = 0;
// 长文本状态(展开 or 收起)
@State collapseText: string = collapseString
// 屏幕宽度(单位px)
screenWidth: number = 0;
// 是否需要显示"展开"字样(注:当文本长度较短时就不需要“展开”)
@State isExpanded: boolean = false
/*当前展开状态*/
@State expandedStates: boolean = false;
@State fontSize: number = 18;
@State fontWeight: FontWeight = FontWeight.Regular
fontColor: ResourceColor = $r('app.color.color_222222')
// 测量文本宽度(单位px)
@State textWidth: number = 0;
// constructor(longMessage?:string,) {
// super();
// this.longMessage = longMessage;
// }
// 获取当前所有的display对象
promise: Promise<Array<display.Display>> = display.getAllDisplays()
aboutToAppear() {
console.log(`文本宽度为:${this.textWidth}`)
let padding = vp2px(5 + this.marginWidth)
this.textWidth = measure.measureText({
textContent: this.longMessage,
fontSize: this.fontSize,
fontWeight: this.fontWeight,
constraintWidth:(this.screenWidth - padding)
})
console.log(`文本宽度为:${this.textWidth}`)
this.promise.then((data: Array<display.Display>) => {
console.log(`所有的屏幕信息:${JSON.stringify(data)}`)
//单位为像素
this.screenWidth = data[0]["width"]
// 屏幕宽度 * 最大行数 * 组件宽度比例 和 文字测量宽度
this.isExpanded = (this.screenWidth - padding) * this.lines <= this.textWidth
// this.expandedStates = this.isExpanded;
//需要展开的话计算3行需要显示的文字
if (this.isExpanded) {
let padding = vp2px(5 + this.marginWidth)
let maxLineTextWidth = (this.screenWidth - padding) * this.maxline;
for (let index = 0; index < this.longMessage.length; index++) {
const element = this.longMessage.substring(0, index)
const string = element + this.collapseText; //截取
const thisTextWidth = measure.measureText({
textContent: string,
fontSize: this.fontSize,
fontWeight: this.fontWeight,
constraintWidth:(this.screenWidth - padding)
})
//计算有误差20
if (thisTextWidth >= maxLineTextWidth) {
break
}
this.maxLineMesssage = element;
}
}
}).catch((err: BusinessError) => {
console.error(`Failed to obtain all the display objects. Code: ${JSON.stringify(err)}`)
})
}
build() {
Row() {
Column() {
if (this.isExpanded) {
// Stack({ alignContent: Alignment.BottomEnd }) {
Text(this.longMessage) {
Span(this.expandedStates ? this.longMessage : this.maxLineMesssage)
Span(this.collapseText).onClick(() => {
if (this.collapseText == collapseString) {
this.collapseText = uncollapseString;
this.expandedStates = true;
this.lines = -1; // 使得设置的最大行属性无效
// 展开动画
// animateTo({
// duration: 150,
// curve: curves.springMotion(),
// }, () => {
// this.lines = -1; // 使得设置的最大行属性无效
// })
} else {
this.collapseText = collapseString;
this.expandedStates = false;
this.lines = this.maxline; // 只显示3行
// 收起动画
// animateTo({
// duration: 100,
// curve: Curve.Friction,
// }, () => {
// this.lines = this.maxline; // 只显示3行
// })
}
})
}
.width('100%')
.fontSize(this.fontSize)
.fontWeight(this.fontWeight)
.fontColor(this.fontColor)
.maxLines(this.lines)
// .backgroundColor(Color.Red)
// }
}
else {
Text('我没有展开收起')
.width('100%')
.fontSize(this.fontSize)
.fontWeight(this.fontWeight)
.fontColor(this.fontColor)
}
}
// .backgroundColor(Color.Brown)
.width('100%')
}
// .height('100%')
}
}
// Index.ets
@Entry
@Component
struct Index {
build() {
Column() {
CommentText()
}
}
}
\ No newline at end of file
... ...
import { ViewType } from 'wdConstant/Index'
import { DateTimeUtils, LazyDataSource, WindowModel } from 'wdKit/Index'
import { commentItemModel, commentListModel } from '../model/CommentModel'
import commentViewModel from '../viewmodel/CommentViewModel'
import { window } from '@kit.ArkUI'
const TAG = 'QualityCommentsComponent';
@Entry
@Preview
@Component
export struct QualityCommentsComponent {
bottomSafeHeight: string = AppStorage.get<number>('bottomSafeHeight') + 'px';
@State private browSingModel: commentListModel = new commentListModel()
isloading: boolean = false
lastWindowColor:string = '#ffffff'
currentWindowColor:string = '#FF4202'
@State allDatas: LazyDataSource<commentItemModel> = new LazyDataSource();
aboutToDisappear(): void {
const windowStage = WindowModel.shared.getWindowStage() as window.WindowStage
const windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
windowClass.setWindowBackgroundColor(this.lastWindowColor)
windowClass.setWindowLayoutFullScreen(false)
// windowClass.setWindowSystemBarProperties({ statusBarColor: '#000' })
}
aboutToAppear(): void {
this.fullScreen();
commentViewModel.fetchQualityCommentListLocal(getContext()).then(commentListModel => {
this.allDatas.push(...commentListModel.list)
})
// commentViewModel.fetchQualityCommentList('1').then((commentListModel) => {
// if (commentListModel && commentListModel.list && commentListModel.list.length > 0) {
// // commentListModel.hasMore = true;
// // this.browSingModel.viewType = ViewType.LOADED;
// this.allDatas.push(...commentListModel.list)
// // if (commentListModel.list.length === this.browSingModel.pageSize) {
// // this.browSingModel.currentPage++;
// // this.browSingModel.hasMore = true;
// // } else {
// // this.browSingModel.hasMore = false;
// // }
// } else {
// this.browSingModel.viewType = ViewType.EMPTY;
// }
// })
}
fullScreen() {
const windowStage = WindowModel.shared.getWindowStage() as window.WindowStage
const windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
// windowClass.setWindowBackgroundColor(this.currentWindowColor)
windowClass.setWindowLayoutFullScreen(true)
// windowClass.setWindowSystemBarProperties({ statusBarColor: '#fff' })
// windowClass.setWindowLayoutFullScreen(true).then(() => {
// console.log(TAG + 'setWindowLayoutFullScreen');
// })
}
@Builder
titleHeader() {
Row() {
Image($r('app.media.comment_img_banner')).width('100%').aspectRatio(375 / 283);
}
}
build() {
Column() {
// this.titleHeader()
List({ space: 28 }) {
ListItemGroup({ header: this.titleHeader() })
LazyForEach(this.allDatas, (item: commentItemModel, index: number) => {
ListItem() {
QualityCommentItem({ item: item }).margin({ left: 12, right: 12 })
}
// .offset({
// y:-87
// })
})
}
// .contentStartOffset(- 87)
.edgeEffect(EdgeEffect.Spring)
.margin({bottom:this.bottomSafeHeight})
// .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
}.backgroundColor(this.currentWindowColor).height('100%').width('100%')
}
}
@Component
struct QualityCommentItem {
@ObjectLink item: commentItemModel
build() {
Column() {
/*头像以及昵称*/
RelativeContainer() {
Image(this.item.fromUserHeader)
.width(50)
.height(50)
.borderRadius(25)
.borderWidth(2)
.borderColor(Color.White)
.id('image1')
.alignRules({
top: { anchor: "__container__", align: VerticalAlign.Top },
left: { anchor: "__container__", align: HorizontalAlign.Start }
})
.offset(
{
y: -16
}
)
Text(this.item.fromUserName)
.fontSize(14)
.fontColor('#222222')
.fontWeight(FontWeight.Medium)
.id('text1')
.alignRules({
bottom: { anchor: "image1", align: VerticalAlign.Bottom },
left: { anchor: "image1", align: HorizontalAlign.End }
})
.offset(
{
x: 6,
y: -6 - 16
}
)
}.height(42)
Column() {
/*评论内容*/
Text() {
ImageSpan($r('app.media.WDBestCommentTitleDotIcon'))
.width(12)
.height(12)
.objectFit(ImageFit.Fill)
.offset({
y: -6
})
Span(' ' + this.item.commentContent)
.fontSize(16)
.fontColor('#222222')
.fontWeight(FontWeight.Medium)
}.margin({ top: 10 })
/*分割线*/
Row() {
}.width('100%').margin({ top: 10, left: 0, right: 0 }).backgroundColor('#EDEDED').height(2.5);
/*文章或者评论*/
Row() {
Row() {
Image($r('app.media.comment_img_link')).width(16).height(16)
Text(this.item.shareInfo.shareTitle)
.fontSize(14)
.fontColor('#666666')
.margin({ left: 6, right: 12 })
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}.height(40).layoutWeight(1)
Image($r('app.media.more')).width(12).height(12)
}.width('100%').height(40).justifyContent(FlexAlign.SpaceBetween)
}
.backgroundColor('#F9F9F9')
.width('100%')
.alignItems(HorizontalAlign.Start)
.borderRadius(4)
.padding({ left: 12, right: 12 })
/*时间 点赞评论*/
Row() {
Text(DateTimeUtils.getCommentTime(DateTimeUtils.getDateTimestamp(this.item.createTime))).fontSize(14).fontColor('#999999')
Row({space:16}){
Row(){
Image($r('app.media.comment_icon_pinglun')).width(16).height(16)
}
Row(){
//comment_like_select
Image($r(this.item.likeNum?'app.media.comment_like_select':'app.media.comment_like_normal')).width(16).height(16)
if (this.item.likeNum){Text(this.item.likeNum).fontColor(this.item.isLike?'#ED2800':'#999999').fontSize(14).margin({left:3})}
}
}
}.height(38).width('100%').justifyContent(FlexAlign.SpaceBetween)
}.backgroundColor('#FFFFFF').padding({ top: 0, left: 16, right: 16 }).borderRadius(4)
}
}
\ No newline at end of file
... ...
import { Logger, ResourcesUtils } from 'wdKit/Index';
import { HttpUrlUtils, ResponseDTO } from 'wdNetwork/Index';
import { HttpRequest } from 'wdNetwork/src/main/ets/http/HttpRequest';
import { commentItemModel, commentListModel } from '../model/CommentModel';
import HashMap from '@ohos.util.HashMap';
const TAG = "CommentViewModel"
class CommentViewModel {
private static instance: CommentViewModel
/**
* 单例模式
* @returns
*/
public static getInstance(): CommentViewModel {
if (!CommentViewModel.instance) {
CommentViewModel.instance = new CommentViewModel();
}
return CommentViewModel.instance;
}
/*获取本地mock数据*/
async getCommentLocal(context: Context): Promise<commentListModel> {
Logger.info(TAG, `getBottomNavDataMock start`);
let compRes: ResponseDTO<commentListModel> | null = await ResourcesUtils.getResourcesJson<ResponseDTO<commentListModel>>(context,'comment_local.json' );
if (!compRes || !compRes.data) {
Logger.info(TAG, `getAppointmentListDataLocal compRes is empty`);
return new commentListModel()
}
Logger.info(TAG, `getAppointmentListDataLocal getResourcesJsonSync compRes : ${JSON.stringify(compRes)}`);
return compRes.data
}
/*获取本地mock数据*/
async fetchQualityCommentListLocal(context: Context): Promise<commentListModel> {
Logger.info(TAG, `getBottomNavDataMock start`);
let compRes: ResponseDTO<commentListModel> | null = await ResourcesUtils.getResourcesJson<ResponseDTO<commentListModel>>(context,'qualityComment_local.json' );
if (!compRes || !compRes.data) {
Logger.info(TAG, `getAppointmentListDataLocal compRes is empty`);
return new commentListModel()
}
Logger.info(TAG, `getAppointmentListDataLocal getResourcesJsonSync compRes : ${JSON.stringify(compRes)}`);
return compRes.data
}
//qualityComment_local.json
fetchQualityCommentList(pageNum: string) {
let url = HttpUrlUtils.getQualityCommentUrl() + `?&pageSize=${10}&pageNum=${pageNum}`
let headers: HashMap<string, string> = HttpUrlUtils.getCommonHeaders();
return new Promise<commentListModel>((success, fail) => {
HttpRequest.get<ResponseDTO<commentListModel>>(url, headers).then((data: ResponseDTO<commentListModel>) => {
if (!data || !data.data) {
fail("数据为空")
return
}
if (data.code != 0) {
fail(data.message)
return
}
let listData = data.data as commentListModel
success(listData)
}, (error: Error) => {
fail(error.message)
Logger.debug(TAG, error.toString())
})
})
}
// BaseGetRequest(contentID:number,contentType:string,pageNum:string){
// let url = HttpUrlUtils.getMyCollectionListDataUrl()+ `?type=${type}&operateTag=${1}&pageSize=${10}&pageNum=${pageNum}`
// if (tagId.length > 0) {
// url = url + `&tagId=${tagId}`
// }
// let headers: HashMap<string, string> = HttpUrlUtils.getCommonHeaders()
// return WDHttp.get<ResponseDTO<commentListModel>>(url, headers)
// }
//
//
// fetchCommentList(contentID:number,contentType:string,pageNum:string):Promise<commentListModel>{
// return new Promise<commentListModel>((success,error) => {
// this.BaseGetRequest(contentID,contentType,pageNum).then((navResDTO: ResponseDTO<commentListModel>) => {
// if (!navResDTO || navResDTO.code != 0) {
// // success(this.getAppointmentListDataLocal(context))
// return
// }
// Logger.info(TAG, "getAppointmentList then,AppointmentResDTO.timeStamp:" + navResDTO.timestamp);
// let listData = navResDTO.data as commentListModel
// success(listData)
// }).catch((err: Error) => {
// Logger.error(TAG, `fetchAppointmentListDataApi catch, error.name : ${err.name}, error.message:${err.message}`);
// error("page data invalid");
// })
// })
// }
}
const commentViewModel = CommentViewModel.getInstance();
export default commentViewModel as CommentViewModel
\ No newline at end of file
... ...
... ... @@ -33,8 +33,8 @@ export default struct MinePageUserSimpleInfoUI {
Stack(){
Image(this.headPhotoUrl)
.alt($r('app.media.default_head'))
.width('108lpx')
.height('108lpx')
.width('100lpx')
.height('100lpx')
.objectFit(ImageFit.Cover)
.borderRadius(50)
Image(this.levelHead)
... ...
... ... @@ -18,7 +18,7 @@ export struct FollowFirstTabsComponent{
value.forEach((element)=>{
this.data.push(element)
})
console.log("ycg",this.data.length.toString());
if(this.controller != null && this.data.length>1 && this.changeIndex === 1){
//个人主页 跳转 关注页 tab 2
let intervalID = setInterval(() => {
... ...
... ... @@ -171,6 +171,7 @@ struct ChildComponent {
.fontSize('31lpx')
.lineHeight('38lpx')
.fontColor($r('app.color.color_222222'))
.maxLines(1)
Text(`粉丝${this.data.cnFansNum}`)
.fontColor($r('app.color.color_B0B0B0'))
.fontSize('23lpx')
... ...
... ... @@ -35,25 +35,45 @@ export struct FollowSecondTabsComponent{
@Builder FollowSecondUI(){
Row() {
Row(){
// 页签
Column({ space: 7 }) {
Scroll() {
Column() {
ForEach(this.data[this.firstIndex].children, (item: FollowSecondListItem, index: number ) => {
this.TabBuilder(index,item)
})
}
.justifyContent(FlexAlign.Start)
}
.align(Alignment.Top)
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.Off)
.height('100%')
}.height('100%')
.alignItems(HorizontalAlign.Center)
}
.alignItems(VerticalAlign.Top)
.height('100%')
Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
ForEach(this.data[this.firstIndex].children, (item: FollowSecondListItem, index: number ) => {
TabContent(){
FollowThirdTabsComponent({data:$data,firstIndex:$firstIndex,secondIndex:index})
}.tabBar(this.TabBuilder(index,item))
}
.backgroundColor($r('app.color.white'))
}, (item: FollowListItem, index: number) => index.toString())
}
.vertical(true)
.barMode(BarMode.Scrollable)
.barWidth('140lpx')
.animationDuration(0)
.onChange((index: number) => {
this.currentIndex = index
})
.width('100%')
.barWidth(0)
.height('100%')
.layoutWeight(1)
}.width('100%')
.alignItems(VerticalAlign.Top)
.backgroundColor('#0FF')
}
@Builder TabBuilder(index: number, item: FollowSecondListItem) {
... ... @@ -73,6 +93,7 @@ export struct FollowSecondTabsComponent{
})
.justifyContent(FlexAlign.Center)
.height('84lpx')
.width('140lpx')
.backgroundColor(this.currentIndex === index?$r('app.color.white'):$r('app.color.color_F9F9F9'))
}
... ...
... ... @@ -34,19 +34,45 @@ export struct FollowThirdTabsComponent{
.lineHeight('38lpx')
.backgroundColor($r('app.color.color_F9F9F9'))
.padding('13lpx')
.maxLines(1)
}
.onClick(()=>{
this.currentIndex = index
this.controller.changeIndex(this.currentIndex)
})
.height('100%')
.height('84lpx')
.margin({right:'9lpx'})
.padding({left:'20lpx',right:index === this.data[this.firstIndex].children[this.secondIndex].children.length-1?"20lpx":"0lpx"})
.justifyContent(FlexAlign.Center)
}
@Builder FollowThirdUI(){
Column(){
Column() {
// 页签
Row({ space: 7 }) {
Scroll() {
Row() {
ForEach(this.data[this.firstIndex].children[this.secondIndex].children, (item: FollowThirdListItem, index: number ) => {
this.TabBuilder(index,item)
})
}
.justifyContent(FlexAlign.Start)
}
.align(Alignment.Start)
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
.width('90%')
.padding({left:'11lpx'})
}
.alignItems(VerticalAlign.Bottom)
.width('100%')
}
.backgroundColor($r('app.color.white'))
.alignItems(HorizontalAlign.Start)
.width('100%')
Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
ForEach(this.data[this.firstIndex].children[this.secondIndex].children, (item: FollowThirdListItem, index: number ) => {
TabContent(){
... ... @@ -58,20 +84,19 @@ export struct FollowThirdTabsComponent{
.margin({left:'20lpx'})
FollowListDetailUI({creatorDirectoryId:this.data[this.firstIndex].children[this.secondIndex].children[index].id})
}
}.tabBar(this.TabBuilder(index,item))
}
.backgroundColor($r('app.color.white'))
}, (item: FollowListItem, index: number) => index.toString())
}
.barHeight(0)
.vertical(false)
.barMode(BarMode.Scrollable)
.barWidth('100%')
.barHeight('84lpx')
.animationDuration(0)
.onChange((index: number) => {
this.currentIndex = index
})
.width('100%')
}.width('100%')
}
}
}
\ No newline at end of file
... ...
... ... @@ -288,7 +288,6 @@ struct ChannelDialog {
.justifyContent(FlexAlign.Center)
.backgroundColor(item.homeChannel === '1' || item.movePermitted === 0 ? '#F5F5F5' : '#ffffff')
.onClick(() => {
console.log('onTouch')
if (this.isEditIng) {
if (item.delPermitted === 1) {
this.delChannelItem(index)
... ...
import { Logger, DateTimeUtils, CollectionUtils } from 'wdKit';
import { CollectionUtils, DateTimeUtils, Logger } from 'wdKit';
import { CommonConstants, CompStyle, ViewType } from 'wdConstant';
import PageViewModel from '../../viewmodel/PageViewModel';
import { EmptyComponent } from '../view/EmptyComponent';
... ... @@ -14,7 +13,7 @@ import CustomRefreshLoadLayout from './CustomRefreshLoadLayout';
import { CompParser } from '../CompParser';
import { GroupInfoDTO } from 'wdBean/src/main/ets/bean/navigation/PageInfoDTO';
import { VideoChannelDetail } from 'wdDetailPlayShortVideo/Index';
import { CompDTO, LiveReviewDTO, PageDTO ,PageInfoDTO} from 'wdBean';
import { CompDTO, LiveReviewDTO, PageDTO, PageInfoBean } from 'wdBean';
const TAG = 'PageComponent';
... ... @@ -72,6 +71,7 @@ export struct PageComponent {
@Builder
ListLayout() {
List() {
if (this.name !== '视频') {
// 下拉刷新
ListItem() {
RefreshLayout({
... ... @@ -79,22 +79,23 @@ export struct PageComponent {
this.pageModel.pullDownRefreshText, this.pageModel.pullDownRefreshHeight)
})
}
}
if (this.name === '视频') {
VideoChannelDetail()
} else {
LazyForEach(this.pageModel.compList, (compDTO: CompDTO, compIndex: number) => {
ListItem() {
Column() {
if (this.name == '视频') {
VideoChannelDetail()
} else {
CompParser({ compDTO: compDTO, compIndex: compIndex });
}
}
}
},
(compDTO: CompDTO, compIndex: number) => compDTO.id + compIndex.toString() + this.pageModel.timestamp
)
}
if (this.name !== '视频') {
// 加载更多
ListItem() {
if (this.pageModel.hasMore) {
... ... @@ -107,6 +108,8 @@ export struct PageComponent {
}
}
}
}
.scrollBar(BarState.Off)
.cachedCount(8)
.height(CommonConstants.FULL_PARENT)
... ... @@ -138,7 +141,8 @@ export struct PageComponent {
onChange() {
Logger.info(TAG, `onChangezz id: ${this.pageId} , ${this.channelId} , ${this.navIndex} , ${this.isFirstIn} , navIndex: ${this.currentTopNavSelectedIndex}`);
if (this.navIndex === this.currentTopNavSelectedIndex && !this.isFirstIn) {
// if (this.navIndex === this.currentTopNavSelectedIndex && !this.isFirstIn) {
if (this.navIndex === this.currentTopNavSelectedIndex) {
this.getData();
}
}
... ... @@ -158,6 +162,16 @@ export struct PageComponent {
this.pageModel.viewType = ViewType.EMPTY;
return;
}
if (this.navIndex === 0) {
await this.getVideoListData(pageInfo);
} else {
await this.getLiveListData(pageInfo);
}
}
private async getVideoListData(pageInfo: PageInfoBean) {
let groupInfo: GroupInfoDTO = CollectionUtils.getElement(pageInfo.groups, 0);
if (groupInfo != null) {
this.pageModel.isRecGroup = groupInfo.groupStrategy === 1;
... ... @@ -165,17 +179,17 @@ export struct PageComponent {
}
// pageInfo.groups.forEach(async (group) => { 不能按顺序加载用for...of替代
// for (const group of pageInfo.groups) {
this.pageDto = await PageViewModel.getPageData(this.pageModel, getContext(this))
this.pageModel.timestamp = DateTimeUtils.getTimeStamp().toString()
this.pageDto = await PageViewModel.getPageData(this.pageModel, getContext(this));
this.pageModel.timestamp = DateTimeUtils.getTimeStamp().toString();
if (this.pageDto && this.pageDto.compList && this.pageDto.compList.length > 0) {
this.pageDto.compList.forEach((comp) => {
if (comp.compStyle === CompStyle.Zh_Grid_Layout_02 && this.liveReviewDTO && this.liveReviewDTO.list && this.liveReviewDTO.list.length > 0) {
comp.operDataList.push(...this.liveReviewDTO.list)
comp.operDataList.push(...this.liveReviewDTO.list);
}
})
});
this.pageModel.viewType = ViewType.LOADED;
this.pageModel.compList.push(...this.pageDto.compList)
this.pageModel.compList.push(...this.pageDto.compList);
if (this.pageDto.compList.length === this.pageModel.pageSize) {
this.pageModel.currentPage++;
this.pageModel.hasMore = true;
... ... @@ -188,14 +202,94 @@ export struct PageComponent {
// this.pageModel.compList.replaceAll(...data)
// this.pageModel.timestamp = DateTimeUtils.getTimeStamp().toString()
// })
this.isFirstIn = false
this.isFirstIn = false;
Logger.debug(TAG, 'cj111');
// } else {
// Logger.debug(TAG, 'aboutToAppear, data response page ' + this.pageId + ', comp list is empty.');
// this.pageModel.viewType = ViewType.EMPTY;
// }
}
}
// private async getLiveListData(pageInfo: PageInfoBean) {
// // pageInfo.groups.forEach(async (group) => { 不能按顺序加载用for...of替代
// for (const group of pageInfo.groups) {
// this.pageDto = await PageViewModel.getPageData(this.pageModel, getContext(this));
// this.pageModel.timestamp = DateTimeUtils.getTimeStamp().toString();
// if (this.pageDto && this.pageDto.compList && this.pageDto.compList.length > 0) {
// this.pageDto.compList.forEach((comp) => {
// if (comp.compStyle === CompStyle.Zh_Grid_Layout_02 && this.liveReviewDTO && this.liveReviewDTO.list && this.liveReviewDTO.list.length > 0) {
// comp.operDataList.push(...this.liveReviewDTO.list);
// }
// });
//
// this.pageModel.viewType = ViewType.LOADED;
// this.pageModel.compList.push(...this.pageDto.compList);
// if (this.pageDto.compList.length === this.pageModel.pageSize) {
// this.pageModel.currentPage++;
// this.pageModel.hasMore = true;
// } else {
// this.pageModel.hasMore = false;
// }
// // // 二次请求,批查互动数据
// // PageViewModel.getInteractData(pageDto.compList).then((data: CompDTO[]) => {
// // // 刷新,替换所有数据
// // this.pageModel.compList.replaceAll(...data)
// // this.pageModel.timestamp = DateTimeUtils.getTimeStamp().toString()
// // })
// this.isFirstIn = false;
// Logger.debug(TAG, 'cj111');
// // } else {
// // Logger.debug(TAG, 'aboutToAppear, data response page ' + this.pageId + ', comp list is empty.');
// // this.pageModel.viewType = ViewType.EMPTY;
// }
// }
// }
async getLiveListData(pageInfo: PageInfoBean) {
// Logger.info(TAG, `getData id: ${this.pageId} , ${this.channelId} , navIndex: ${this.currentTopNavSelectedIndex}`);
// this.pageModel.pageId = this.pageId;
// this.pageModel.groupId = this.pageId;
// this.pageModel.channelId = this.channelId;
// this.pageModel.currentPage = 1;
// let pageInfo = await PageViewModel.getPageUrlData(this.pageModel.pageId);
// if (pageInfo == null) {
// this.pageModel.viewType = ViewType.EMPTY;
// return;
// }
Logger.debug(TAG, 'getPageUrlData ' + pageInfo.id);
// pageInfo.groups.forEach(async (group) => { 不能按顺序加载用for...of替代
for (const group of pageInfo.groups) {
this.pageDto = await PageViewModel.getLivePageData(this.pageModel.pageId, `${group.id}`, this.pageModel.channelId, group.groupStrategy
, this.pageModel.currentPage, this.pageModel.pageSize, getContext(this))
this.pageModel.timestamp = DateTimeUtils.getTimeStamp().toString()
if (this.pageDto && this.pageDto.compList && this.pageDto.compList.length > 0) {
this.pageDto.compList.forEach((comp) => {
if (comp.compStyle === CompStyle.Zh_Grid_Layout_02 && this.liveReviewDTO && this.liveReviewDTO.list && this.liveReviewDTO.list.length > 0) {
comp.operDataList.push(...this.liveReviewDTO.list)
}
})
this.pageModel.viewType = ViewType.LOADED;
this.pageModel.compList.push(...this.pageDto.compList)
if (this.pageDto.compList.length === this.pageModel.pageSize) {
this.pageModel.currentPage++;
this.pageModel.hasMore = true;
} else {
this.pageModel.hasMore = false;
}
// 二次请求,批查互动数据
PageViewModel.getInteractData(this.pageDto.compList).then((data: CompDTO[]) => {
// 刷新,替换所有数据
this.pageModel.compList.replaceAll(...data)
this.pageModel.timestamp = DateTimeUtils.getTimeStamp().toString()
})
this.isFirstIn = false
} else {
Logger.debug(TAG, 'aboutToAppear, data response page ' + this.pageId + ', comp list is empty.');
this.pageModel.viewType = ViewType.EMPTY;
}
}
}
async getPreviewData() {
... ...
... ... @@ -128,7 +128,7 @@ export struct SearchComponent {
* @param content
*/
getSearchHistoryResData(content:string,index:number){
//删除单记录
//删除单记录
SearcherAboutDataModel.delSearchSingleHistoryData(index)
this.isClickedHistory = true
this.searchResData(content)
... ... @@ -149,33 +149,6 @@ export struct SearchComponent {
this.getSearchResultCountData()
}
getSearchResultCountData() {
SearcherAboutDataModel.getSearchResultCountData(encodeURI(this.searchText),getContext(this)).then((value) => {
if (value != null) {
this.count = []
if(value.allTotal!=0){
this.count.push("全部")
}
if(value.cmsTotal!=0){
this.count.push("精选")
}
if(value.rmhTotal!=0){
this.count.push("人民号")
}
if(value.videoTotal!=0){
this.count.push("视频")
}
if(value.activityTotal!=0){
this.count.push("活动")
}
}
}).catch((err: Error) => {
console.log(TAG, JSON.stringify(err))
})
}
/**
* 点击联想搜索列表回调
* @param content
... ... @@ -291,4 +264,30 @@ export struct SearchComponent {
.padding({ left: '31lpx' })
.alignItems(VerticalAlign.Center)
}
getSearchResultCountData() {
SearcherAboutDataModel.getSearchResultCountData(encodeURI(this.searchText),getContext(this)).then((value) => {
if (value != null) {
this.count = []
if(value.allTotal!=0){
this.count.push("全部")
}
if(value.cmsTotal!=0){
this.count.push("精选")
}
if(value.rmhTotal!=0){
this.count.push("人民号")
}
if(value.videoTotal!=0){
this.count.push("视频")
}
if(value.activityTotal!=0){
this.count.push("活动")
}
}
}).catch((err: Error) => {
console.log(TAG, JSON.stringify(err))
})
}
}
\ No newline at end of file
... ...
import { SearchResultContentComponent } from './SearchResultContentComponent'
const TAG = "SearchResultComponent"
/**
... ... @@ -19,7 +20,7 @@ export struct SearchResultComponent{
Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
ForEach(this.count, (item: string, index: number ) => {
TabContent(){
Text(item)
SearchResultContentComponent({keywords:this.searchText,searchType:item})
}.tabBar(this.TabBuilder(index,item))
}, (item: string, index: number) => index.toString())
}
... ... @@ -63,4 +64,5 @@ export struct SearchResultComponent{
.margin({right:'9lpx'})
.padding({left:'31lpx',right:index === this.count.length-1?"31lpx":"0lpx"})
}
}
\ No newline at end of file
... ...
import { ContentDTO, FullColumnImgUrlDTO, InteractDataDTO, RmhInfoDTO, VideoInfoDTO } from 'wdBean/Index'
import { LiveInfoDTO } from 'wdBean/src/main/ets/bean/detail/LiveInfoDTO'
import { VoiceInfoDTO } from 'wdBean/src/main/ets/bean/detail/VoiceInfoDTO'
import { LazyDataSource, StringUtils } from 'wdKit/Index'
import SearcherAboutDataModel from '../../model/SearcherAboutDataModel'
import { CardParser } from '../CardParser'
import { ListHasNoMoreDataUI } from '../reusable/ListHasNoMoreDataUI'
const TAG = "SearchResultContentComponent"
@Component
export struct SearchResultContentComponent{
@State keywords:string = ""
@State searchType:string = ""
@State data: LazyDataSource<ContentDTO> = new LazyDataSource();
@State count:number = 0;
@State isLoading:boolean = false
@State hasMore:boolean = true
curPageNum:number = 1;
aboutToAppear(): void {
if(this.searchType == "全部"){
this.searchType = "all"
}else if(this.searchType == "精选"){
this.searchType = "cms"
}else if(this.searchType == "人民号"){
this.searchType = "rmh"
}else if(this.searchType == "视频"){
this.searchType = "video"
}else if(this.searchType == "活动"){
this.searchType = "activity"
}
this.keywords = encodeURI(this.keywords)
this.getNewSearchResultData()
}
getNewSearchResultData(){
this.isLoading = true
if(this.hasMore){
SearcherAboutDataModel.getSearchResultListData("20",`${this.curPageNum}`,this.searchType,this.keywords,getContext(this)).then((value)=>{
if (!this.data || value.list.length == 0){
this.hasMore = false
}else{
value.list.forEach((value)=>{
let photos:FullColumnImgUrlDTO[] = []
if(value.data.appStyle === 4){
value.data.appStyleImages.split("&&").forEach((value)=>{
photos.push({url:value} as FullColumnImgUrlDTO)
})
}
//TODO 48 个赋值
let contentDTO:ContentDTO = {
appStyle: value.data.appStyle + "",
cityCode: value.data.cityCode,
coverSize: "",
coverType: -1,
coverUrl: value.data.appStyleImages.split("&&")[0],
description: value.data.description,
districtCode: value.data.districtCode,
endTime: value.data.endTime,
hImageUrl: "",
heatValue: "",
innerUrl: "",
landscape: Number.parseInt(value.data.landscape),
// lengthTime:null,
linkUrl: value.data.linkUrl,
openLikes: Number.parseInt(value.data.openLikes),
openUrl: "",
pageId: value.data.pageId,
programAuth: "",
programId: "",
programName: "",
programSource: -1,
programType: -1,
provinceCode: value.data.provinceCode,
showTitleEd: value.data.showTitleEd,
showTitleIng: value.data.showTitleIng,
showTitleNo: value.data.showTitleNo,
startTime: value.data.startTime,
subType: "",
subtitle: "",
title: value.data.title,
vImageUrl: "",
screenType: "",
source: StringUtils.isEmpty(value.data.creatorName) ? value.data.sourceName : value.data.creatorName,
objectId: "",
objectType: value.data.type,
channelId: value.data.channelId,
relId: value.data.relId,
relType: value.data.relType,
newsTitle: value.data.titleLiteral,
publishTime: value.data.publishTime,
visitorComment: -1,
fullColumnImgUrls: photos,
newsSummary: "",
hasMore: -1,
slideShows: [],
voiceInfo: {} as VoiceInfoDTO,
tagWord: -1,
isSelect: true,
rmhInfo: {} as RmhInfoDTO,
photoNum: -1,
liveInfo: {} as LiveInfoDTO,
videoInfo: {
videoDuration: Number.parseInt(value.data.duration)
} as VideoInfoDTO,
interactData: {} as InteractDataDTO,
corner: '',
rmhPlatform: 0,
newTags: ''
}
this.data.push(contentDTO)
})
this.data.notifyDataReload()
this.count = this.data.totalCount()
if (this.data.totalCount() < value.totalCount) {
this.curPageNum++
}else {
this.hasMore = false
}
}
}).catch((err:Error)=>{
console.log(TAG,JSON.stringify(err))
})
}
this.isLoading = false
}
build() {
Column() {
if(this.count == 0){
ListHasNoMoreDataUI({style:2})
}else{
//List
List({ space: '6lpx' }) {
LazyForEach(this.data, (item: ContentDTO, index: number) => {
ListItem() {
CardParser({contentDTO:item})
}
.onClick(()=>{
//TODO 跳转
})
}, (item: ContentDTO, index: number) => index.toString())
//没有更多数据 显示提示
if(!this.hasMore){
ListItem(){
ListHasNoMoreDataUI()
}
}
}.cachedCount(4)
.scrollBar(BarState.Off)
.margin({top:'23lpx',left:'23lpx',right:'23lpx'})
.layoutWeight(1)
.onReachEnd(()=>{
console.log(TAG,"触底了");
if(!this.isLoading){
//加载分页数据
this.getNewSearchResultData()
}
})
}
}
.backgroundColor($r('app.color.white'))
.height('100%')
.width('100%')
}
}
\ No newline at end of file
... ...
import { Params } from 'wdBean';
import { WDRouterPage, WDRouterRule } from 'wdRouter';
import featureAbility from '@ohos.ability.featureAbility';
import { EnvironmentCustomDialog } from './EnvironmentCustomDialog';
const TAG = 'AboutPageUI';
... ... @@ -9,7 +9,18 @@ export struct AboutPageUI {
@State listData: Array<string | Array<string>> = ['隐私授权协议', '软件许可及用户协议'];
@State message: string = '京ICP备16066560号-6A Copyright © 人民日报客户端\nall rights reserved.'
@State version: string = '版本号:v'
clickTimes: number = 0
dialogController: CustomDialogController = new CustomDialogController({
builder: EnvironmentCustomDialog({
cancel: () => {
},
confirm: () => {
}
}),
customStyle: true,
alignment: DialogAlignment.Center
})
build() {
Navigation() {
... ... @@ -19,18 +30,24 @@ export struct AboutPageUI {
.title('关于')
}
aboutToAppear(){
aboutToAppear() {
let context = getContext();
context.getApplicationContext();
}
@Builder aboutUi() {
@Builder
aboutUi() {
Column() {
Image($r('app.media.setting_about_logo'))
.width('278lpx')
.height('154lpx')
.margin({top:'173lpx',bottom:'154lpx'})
.margin({ top: '173lpx', bottom: '154lpx' })
.onClick(() => {
this.clickTimes++
if (this.clickTimes > 2) {
this.dialogController.open()
}
})
// Row(){
//
// }.backgroundColor(Color.Yellow)
... ... @@ -44,19 +61,17 @@ export struct AboutPageUI {
// .height('97lpx')
List(){
ForEach(this.listData, (item:string, index : number) =>{
List() {
ForEach(this.listData, (item: string, index: number) => {
ListItem() {
this.getArrowCell(item, index)
}.onClick(() =>{
}.onClick(() => {
if (index == 0) {
let bean={contentId:"1",pageID:""} as Params
WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage,bean)
}else{
let bean={contentId:"2",pageID:""} as Params
WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage,bean)
let bean = { contentId: "1", pageID: "" } as Params
WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage, bean)
} else {
let bean = { contentId: "2", pageID: "" } as Params
WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage, bean)
}
})
})
... ... @@ -77,22 +92,21 @@ export struct AboutPageUI {
.fontSize('25lpx')
.textAlign(TextAlign.Center)
.fontColor($r("app.color.color_666666"))
.margin({bottom:'31lpx'})
.margin({ bottom: '31lpx' })
Text(this.message)
.fontSize('19lpx')
.textAlign(TextAlign.Center)
.fontColor($r("app.color.color_999999"))
.margin({bottom:'35lpx'})
.margin({ bottom: '35lpx' })
}
.width('100%')
.height('100%')
}
// 右文字+箭头cell
@Builder getArrowCell(item:string, index:number) {
@Builder
getArrowCell(item: string, index: number) {
Row() {
// 左侧标题
... ... @@ -109,10 +123,8 @@ export struct AboutPageUI {
.justifyContent(FlexAlign.SpaceBetween)
.height('97lpx')
.width('100%')
.padding({left:'29lpx',right:'29lpx'})
.padding({ left: '29lpx', right: '29lpx' })
}
}
... ...
... ... @@ -17,6 +17,7 @@ import { Router } from '@ohos.arkui.UIContext';
import promptAction from '@ohos.promptAction';
import { LogoutViewModel } from '../../viewmodel/LogoutViewModel';
import { CustomLogoutDialog } from './CustomLogoutDialog';
import { emitter } from '@kit.BasicServicesKit';
export { SettingPasswordParams } from "wdLogin"
... ... @@ -41,9 +42,11 @@ export struct AccountAndSecurityLayout {
alignment: DialogAlignment.Center
})
aboutToAppear() {
// 获取设置页面数据
this.getAccountAndSecurityData()
this.addEmitEvent()
}
async getAccountAndSecurityData() {
... ... @@ -56,6 +59,28 @@ export struct AccountAndSecurityLayout {
}
addEmitEvent(){
// 定义一个eventId为1的事件
let event: emitter.InnerEvent = {
eventId: 10010
};
// 收到eventId为1的事件后执行该回调
let callback = (eventData: emitter.EventData): void => {
promptAction.showToast({
message: JSON.stringify(eventData)
});
if(eventData&&eventData.data){
this.listData[0].subTitle = eventData.data['content']
}
Logger.debug( 'event callback:' + JSON.stringify(eventData));
};
// 订阅eventId为1的事件
emitter.on(event, callback);
}
build() {
Column(){
if(this.isAccountPage){
... ... @@ -106,7 +131,8 @@ export struct AccountAndSecurityLayout {
ListItem() {
if (item.type == 0) {
Column() {
this.getArrowCell(item)
// this.getArrowCell(item)
AccountArrowCell({ item:item})
}.padding({ left: '27lpx' }).height('117lpx').justifyContent(FlexAlign.Center)
} else if (item.type == 1) {
Column() {
... ... @@ -285,7 +311,7 @@ export struct AccountAndSecurityLayout {
}.alignItems(VerticalAlign.Center)
Row() {
Text("登录")
Text("注销账户")
.borderRadius(4)
.fontColor(this.protocolState ? "#FFFFFFFF" : "#66FFFFFF")
.fontSize(18)
... ... @@ -405,3 +431,46 @@ export struct AccountAndSecurityLayout {
return securityNum;
}
}
@Component
export struct AccountArrowCell{
@ObjectLink item: MineMainSettingFunctionItem
build() {
Column() {
Row() {
// 左侧logo和标题
Row() {
// 判断有没有图片
if (this.item.imgSrc) {
Image(this.item.imgSrc)
.height('38lpx')
.margin({ right: '5lpx' })
}
Text(`${this.item.title}`)
.margin({ top: '8lpx' })
.height('38lpx')
.fontColor('#333333')
.fontSize('29lpx')
}.width('60%')
// 右侧文案和右箭头
Row() {
Text(this.item.subTitle ? this.item.subTitle : '')
.fontColor('#999999')
.maxLines(1)
Image($r('app.media.mine_user_arrow'))
.width('27lpx')
.height('27lpx')
.objectFit(ImageFit.Auto)
Column().width('29lpx')
}.width('40%')
.margin({ right: '29lpx' })
.justifyContent(FlexAlign.End)
}
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.SpaceBetween)
}
.height('54lpx')
}
}
\ No newline at end of file
... ...
import { SPHelper } from 'wdKit/Index';
import { HttpUrlUtils } from 'wdNetwork/Index';
@CustomDialog
export struct EnvironmentCustomDialog {
currentEnvironment: string = HttpUrlUtils.HOST_PRODUCT;
controller: CustomDialogController
cancel: () => void = () => {
}
confirm: () => void = () => {
}
build() {
Column() {
Text("请选择环境")
.fontColor("#222222")
.fontSize(18)
.width("100%")
.fontWeight(FontWeight.Bold)
.textAlign(TextAlign.Center)
.margin({ top: 20 })
Row() {
Radio({ value: 'Radio1', group: 'radioGroup' })
.checked(true)
.height(20)
.width(20)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.currentEnvironment = HttpUrlUtils.HOST_SIT;
}
})
Text('切换到SIT(测试)环境,重启应用生效')
.fontSize(14)
}
.justifyContent(FlexAlign.Start)
.width('90%')
Row() {
Radio({ value: 'Radio1', group: 'radioGroup' })
.checked(true)
.height(20)
.width(20)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.currentEnvironment = HttpUrlUtils.HOST_UAT;
}
})
Text('切换到UAT(预发布)环境,重启应用生效')
.fontSize(14)
}
.width('90%')
.justifyContent(FlexAlign.Start)
Row() {
Radio({ value: 'Radio1', group: 'radioGroup' })
.checked(true)
.height(20)
.width(20)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.currentEnvironment = HttpUrlUtils.HOST_PRODUCT;
}
})
Text('切换到PROD(现网)环境,重启应用生效')
.fontSize(14)
}
.width('90%')
.justifyContent(FlexAlign.Start)
Row() {
Radio({ value: 'Radio1', group: 'radioGroup' })
.checked(true)
.height(20)
.width(20)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.currentEnvironment = HttpUrlUtils.HOST_DEV;
}
})
Text('切换到DEV(开发)环境,重启应用生效')
.fontSize(14)
}
.width('90%')
.justifyContent(FlexAlign.Start)
Button('确认')
.margin({ top: 20 })
.onClick(() => {
// HttpUrlUtils.hostUrl = this.currentEnvironment
SPHelper.default.saveSync('hostUrl', this.currentEnvironment);
this.controller.close()
this.confirm()
})
}.height(261).backgroundColor(Color.White).borderRadius(6).width('74%')
}
}
\ No newline at end of file
... ...
import { Action, CompDTO, Params } from 'wdBean';
import { ExtraDTO } from 'wdBean/src/main/ets/bean/component/extra/ExtraDTO';
import { CommonConstants } from 'wdConstant/Index';
import { DateTimeUtils, Logger } from 'wdKit';
import { WDRouterRule } from 'wdRouter';
const TAG = 'AlbumCardComponent';
@Preview
@Component
export struct AlbumCardComponent {
@State compDTO: CompDTO = {} as CompDTO
aboutToAppear() {
Logger.debug(TAG + "this.compDTO.operDataList" + JSON.stringify(this.compDTO.operDataList));
}
build() {
Column({ space: 8 }) {
Text(this.compDTO.operDataList[0].newsTitle)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.fontSize(17)
.fontColor(0x222222)
.lineHeight(25)
.maxLines(3)
.width(CommonConstants.FULL_WIDTH)
RelativeContainer() {
Image(this.compDTO.operDataList[0].fullColumnImgUrls[0].url)
.width('66.6%')
.aspectRatio(16/9)
.alignRules({
top: { anchor: "__container__", align: VerticalAlign.Top },
left: { anchor: "__container__", align: HorizontalAlign.Start }
})
.id('mainImage')
Image(this.compDTO.operDataList[0].fullColumnImgUrls[1].url)
.width('33%')
.aspectRatio(16/9)
.alignRules({
top: { anchor: "__container__", align: VerticalAlign.Top },
right: { anchor: "__container__", align: HorizontalAlign.End }
})
.id('subTopImage')
Image(this.compDTO.operDataList[0].fullColumnImgUrls[2].url)
.width('33%')
.aspectRatio(16/9)
.alignRules({
right: { anchor: "__container__", align: HorizontalAlign.End },
bottom: { anchor: "__container__", align: VerticalAlign.Bottom }
})
.id('subBottomImage')
// 下面是渲染右下角图标
Shape() {
Rect().width(33).height(18)
}
// .viewPort({ x: -2, y: -2, width: 304, height: 130 })
.fill(0x000000)
.fillOpacity(0.3)
// .strokeDashArray([20])
// .strokeDashOffset(10)
.strokeLineCap(LineCapStyle.Round)
.strokeLineJoin(LineJoinStyle.Round)
.antiAlias(true)
.id('shape')
.alignRules({
right: { anchor: "__container__", align: HorizontalAlign.End },
bottom: { anchor: "__container__", align: VerticalAlign.Bottom }
})
.margin({ right: 4,
bottom: 4 })
Image($r('app.media.album_card_shape'))
.width(22)
.height(18)
.alignRules({
left: { anchor: "shape", align: HorizontalAlign.Start },
top: { anchor: "shape", align: VerticalAlign.Top }
})
.id('shapeSubImage')
Text(this.compDTO.operDataList[0].fullColumnImgUrls.length + '')
.fontSize(13)
.fontColor(0xFFFFFF)
.id('pageIndex')
.alignRules({
right: { anchor: "shape", align: HorizontalAlign.End },
top: { anchor: "shape", align: VerticalAlign.Top }
})
.margin({ right: 2 })
.textAlign(TextAlign.Center)
.width(17)
.height(17)
}
.width(CommonConstants.FULL_WIDTH)
.aspectRatio(24/9)
.onClick((event: ClickEvent) => {
let taskAction: Action = {
type: 'JUMP_DETAIL_PAGE',
params: {
detailPageType: 17,
contentID: this.compDTO.operDataList?.[0].objectId,
extra: {
relType: this.compDTO.operDataList?.[0].relType,
relId: `${this.compDTO.operDataList?.[0].relId}`,
} as ExtraDTO
} as Params,
};
WDRouterRule.jumpWithAction(taskAction)
})
Row() {
if (this.compDTO.operDataList[0].source) {
Text(this.compDTO.operDataList[0].source)
.fontSize(13)
.fontColor(0xB0B0B0)
Image($r('app.media.point'))
.width(16)
.height(16)
}
if (this.compDTO.operDataList[0].publishTime && this.compDTO.operDataList[0].publishTime.length === 13) {
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.compDTO.operDataList[0].publishTime)))
.fontSize(13)
.fontColor(0xB0B0B0)
}
Text('328评')
.fontSize(13)
.fontColor(0xB0B0B0)
.margin({
left: 6
})
}
.width(CommonConstants.FULL_WIDTH)
.height(16)
.id('label')
}
.width(CommonConstants.FULL_WIDTH)
.padding({
top: 14,
left: 16,
right: 16,
bottom: 14
})
}
}
\ No newline at end of file
import { CompDTO, slideShows } from 'wdBean';
import { CommonConstants } from 'wdConstant'
import { DateTimeUtils } from 'wdKit';
import { ProcessUtils } from '../../utils/ProcessUtils';
/**
* 时间链卡--CompStyle: 09
*/
@Component
export struct CompStyle_09 {
@State compDTO: CompDTO = {} as CompDTO
build() {
Column(){
// 顶部标题,最多两行
if(this.compDTO.operDataList[0].newsTitle) {
Text(this.compDTO.operDataList[0].newsTitle)
.width(CommonConstants.FULL_WIDTH)
.fontSize($r('app.float.font_size_17'))
.fontWeight(600)
.maxLines(2)
.textOverflow({overflow: TextOverflow.Ellipsis})
.margin({ bottom: 19 })
}
// 大图
Stack(){
Image(this.compDTO.operDataList[0].coverUrl)
.width('100%')
.borderRadius({topLeft: $r('app.float.image_border_radius'), topRight: $r('app.float.image_border_radius')})
Text('专题')
.fontSize($r('app.float.font_size_12'))
.padding({left: 8, right: 8, top: 3, bottom: 3})
.backgroundColor(Color.Red)
.fontColor(Color.White)
.borderRadius($r('app.float.button_border_radius'))
.margin({left: 5, bottom: 5})
}.alignContent(Alignment.BottomStart)
// 时间线--后端返回三个,
Column(){
ForEach(this.compDTO.operDataList[0].slideShows, (item:slideShows, index:number) => {
this.timelineItem(item, index)
})
}
// 底部-查看更多。根据接口返回的isMore判断是否显示查看更多
if(this.compDTO.operDataList[0].hasMore == 1) {
Row() {
Text("查看更多")
.fontSize($r("app.float.font_size_14"))
.fontColor($r("app.color.color_222222"))
.margin({ right: 1 })
Image($r("app.media.more"))
.width(14)
.height(14)
}
.backgroundColor($r('app.color.color_F5F5F5'))
.width(CommonConstants.FULL_WIDTH)
.height(40)
.borderRadius($r('app.float.button_border_radius'))
.justifyContent(FlexAlign.Center)
.margin({top: 5})
}
}
.width(CommonConstants.FULL_WIDTH)
.padding({
top: 14,
left: 16,
right: 16,
bottom: 14
})
.backgroundColor($r("app.color.white"))
.margin({ bottom: 8 })
.onClick((event: ClickEvent) => {
ProcessUtils.processPage(this.compDTO?.operDataList[0])
})
}
@Builder timelineItem (item:slideShows, index:number) {
Column(){
Stack() {
if(index < this.compDTO.operDataList[0].slideShows.length - 1) {
Divider()
.vertical(true)
.color($r('app.color.color_EDEDED'))
.strokeWidth(1)
.margin({top: index > 0 ? 0 : 16, left: 4})
}
if(index > 0 && index == this.compDTO.operDataList[0].slideShows.length - 1) {
Divider()
.vertical(true)
.color($r('app.color.color_EDEDED'))
.strokeWidth(1)
.height(16)
.margin({left: 4})
}
Column(){
Row() {
// 标题
Image($r("app.media.point_icon"))
.width(9)
.height(9)
.margin({ right: 5 })
Text(DateTimeUtils.formatDate(item.publishTime, "MM月dd日 HH:mm"))
.fontSize($r('app.float.font_size_12'))
.fontColor($r('app.color.color_222222'))
.fontWeight(600)
}
.width(CommonConstants.FULL_WIDTH)
.height(32)
.alignItems(VerticalAlign.Center)
Row() {
Text(item.newsTitle)
.fontSize($r('app.float.font_size_17'))
.fontWeight(400)
.fontColor($r('app.color.color_222222'))
.layoutWeight(1)
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.alignSelf(ItemAlign.Center)
.margin({left: 12})
if(item.fullColumnImgUrls[0] && item.fullColumnImgUrls[0].url) {
Image(item.fullColumnImgUrls[0].url)
.width(90)
.height(60)
.borderRadius($r('app.float.image_border_radius'))
}
}
}
}
.alignContent(Alignment.TopStart)
}
.height(item.fullColumnImgUrls[0] && item.fullColumnImgUrls[0].url ? 100 : 78)
.alignItems(HorizontalAlign.Start)
}
}
\ No newline at end of file
import { CompDTO, ContentDTO, slideShows } from 'wdBean';
import { CommonConstants } from 'wdConstant'
import { DateTimeUtils } from 'wdKit';
import { ProcessUtils } from '../../utils/ProcessUtils';
/**
* 大专题卡--CompStyle: 10
*/
@Component
export struct CompStyle_10 {
@State compDTO: CompDTO = {} as CompDTO
build() {
Column(){
// 顶部标题,最多两行
if(this.compDTO.operDataList[0].newsTitle) {
Text(this.compDTO.operDataList[0].newsTitle)
.width(CommonConstants.FULL_WIDTH)
.fontSize($r('app.float.font_size_17'))
.fontWeight(600)
.maxLines(2)
.textOverflow({overflow: TextOverflow.Ellipsis})
.margin({ bottom: 19 })
}
// 大图
Stack(){
Image(this.compDTO.operDataList[0] && this.compDTO.operDataList[0].coverUrl)
.width('100%')
.borderRadius({topLeft: $r('app.float.image_border_radius'), topRight: $r('app.float.image_border_radius')})
.onClick((event: ClickEvent) => {
ProcessUtils.processPage(this.compDTO?.operDataList[0])
})
Text('专题')
.fontSize($r('app.float.font_size_12'))
.padding({left: 8, right: 8, top: 3, bottom: 3})
.backgroundColor(Color.Red)
.fontColor(Color.White)
.borderRadius($r('app.float.button_border_radius'))
.margin({left: 5, bottom: 5})
}.alignContent(Alignment.BottomStart)
// 专题列表--后端返回三个,
Column(){
ForEach(this.compDTO.operDataList[0].slideShows, (item:slideShows, index:number) => {
this.timelineItem(item, index)
})
}
// 底部-查看更多。根据接口返回的isMore判断是否显示查看更多
if(this.compDTO.operDataList[0].hasMore == 1) {
Row() {
Text("查看更多")
.fontSize($r("app.float.font_size_14"))
.fontColor($r("app.color.color_222222"))
.margin({ right: 1 })
Image($r("app.media.more"))
.width(14)
.height(14)
}
.backgroundColor($r('app.color.color_F5F5F5'))
.width(CommonConstants.FULL_WIDTH)
.height(40)
.borderRadius($r('app.float.button_border_radius'))
.justifyContent(FlexAlign.Center)
.margin({top: 5})
.onClick((event: ClickEvent) => {
ProcessUtils.processPage(this.compDTO?.operDataList[0])
})
}
}
.width(CommonConstants.FULL_WIDTH)
.padding({
top: 14,
left: 16,
right: 16,
bottom: 14
})
.backgroundColor($r("app.color.white"))
.margin({ bottom: 8 })
}
@Builder timelineItem (item:slideShows, index:number) {
Row() {
Column(){
Text(item.newsTitle)
.fontSize($r('app.float.font_size_17'))
.fontWeight(400)
.fontColor($r('app.color.color_222222'))
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Row(){
// 展示发稿人
if(item.source) {
Text(item.source)
.fontSize($r('app.float.font_size_12'))
.fontColor($r('app.color.color_B0B0B0'))
.textOverflow({overflow: TextOverflow.Ellipsis})
.maxLines(1)
.width(item.source.length > 10 ? '60%' : '')
Image($r('app.media.point'))
.width(16)
.height(16)
}
Text(DateTimeUtils.getCommentTime(Number.parseFloat(String(item.publishTime))))
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
}
.margin({top: 12})
}
.layoutWeight(1)
.alignItems(HorizontalAlign.Start)
// 右侧图片
if(item.fullColumnImgUrls[0] && item.fullColumnImgUrls[0].url) {
Image(item.fullColumnImgUrls[0].url)
.width(117)
.height(78)
.objectFit(ImageFit.Cover)
.borderRadius($r('app.float.image_border_radius'))
.margin({left: 12})
}
}
.padding({top: 10, bottom: 10})
.onClick((event: ClickEvent) => {
const str: string = JSON.stringify(this.compDTO.operDataList[0]);
const data: ContentDTO = JSON.parse(str)
data.objectId = item.newsId
data.relId = item.relId
data.objectType = String(item.objectType)
ProcessUtils.processPage(data)
})
}
}
\ No newline at end of file
import { CompDTO } from 'wdBean';
import { CommonConstants } from 'wdConstant';
import { ProcessUtils } from '../../utils/ProcessUtils';
@Component
export struct HeadPictureCardComponent {
@State compDTO: CompDTO = {} as CompDTO
build() {
Stack() {
Image(this.compDTO.operDataList[0].coverUrl)
.width(CommonConstants.FULL_WIDTH)
.autoResize(true)
.borderRadius($r('app.float.image_border_radius'))
if (this.compDTO.operDataList[0].newsTitle) {
Row()
.width(CommonConstants.FULL_WIDTH)
.height(59)
.linearGradient({
colors: [
['rgba(0, 0, 0, 0.0)', 0.0], ['rgba(0, 0, 0, 0.3)', 1.0]
]
})
Row() {
Text(this.compDTO.operDataList[0].newsTitle)
.width(CommonConstants.FULL_WIDTH)
.height(CommonConstants.FULL_HEIGHT)
.fontColor(Color.White)
.fontSize($r('app.float.normal_text_size'))
.fontWeight(FontWeight.Bold)
.maxLines(2)
.align(Alignment.Bottom)
}
.justifyContent(FlexAlign.Start)
.height(40)
.margin({ left: 12, bottom: 10, right: 12 })
}
}
.alignContent(Alignment.Bottom)
.width(CommonConstants.FULL_WIDTH)
.padding(
{ top: 16, bottom: 16, left: 14, right: 14 })
.onClick((event: ClickEvent) => {
ProcessUtils.processPage(this.compDTO?.operDataList[0])
})
}
}
... ... @@ -27,11 +27,11 @@ export struct RecommendList {
.width(CommonConstants.FULL_PARENT)
.justifyContent(FlexAlign.Start)
}
ForEach(this.recommendList, (item: ContentDTO) => {
Row(){
ForEach(this.recommendList, (item: ContentDTO, index: number) => {
Row() {
CardParser({ contentDTO: item });
}.border({
width:{bottom: 1},
width: { bottom: this.recommendList.length === index + 1 ? 0 : 1 },
color: '#f5f5f5'
})
}, (item: ContentDTO) => JSON.stringify(item))
... ...
import { Action, CompDTO, ContentDTO, Params } from 'wdBean';
import { CompStyle } from 'wdConstant';
import { Logger, DateTimeUtils } from 'wdKit';
import { WDRouterRule } from 'wdRouter';
const TAG = 'SingleImageCardAppComponent';
const FULL_PARENT: string = '100%';
/**
* 单图卡-3行标题/2行标题
* 枚举值13
*
* 重磅推荐/精选/电视剧/电影/综艺/短剧/更多>/
*/
@Entry
@Component
export struct SingleImageCardAppComponent {
// @State compDTO: CompDTO = {} as CompDTO
@State compDTO: CompDTO = {
operDataList: [
{
coverSize: '660*371',
coverType: 1,
visitorComment: 10,
coverUrl: 'https://cdnjdphoto.aikan.pdnews.cn/zhbj-20240116/image/content/a9028e7011bb440e94ba7c63d80b39b7.png?x-oss-process=image/resize,w_550/quality,q_90/format,jpg',
newsTitle: '一条江豚的自述',
newsSummary: '我是生活在长江里的一头江豚,是长江中唯一的水生哺乳动物,更是国家一级保护动物。但曾几何时,我和我的江中小伙伴出现了生存危机……直到有一天,我突然发现,打渔人变成护渔人,江水变清澈了,长江逐渐恢复了生机,我的家族数量上升到了1249头。当长江之水再一次悠悠流淌,我们相拥在清澈波光中起舞。长江,我的家园。',
videoInfo: {
// clarity: 1,
resolutionHeight: 20,
resolutionWidth: 20,
videoDuration: 229,
videoLandScape: 1,
videoType: 1,
videoUrl: "https://cdnjdout.aikan.pdnews.cn/zhbj-20240116/vod/content/output/c72f4170db2c4d34befa453f60d39a69_opt.mp4",
firstFrameImageUri: "", // 首帧图;【视频内容,contentPictures中】
},
} as ContentDTO
]
} as CompDTO
aboutToAppear() {
}
build() {
Column() {
Text(this.compDTO.operDataList[0].newsTitle)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.alignSelf(ItemAlign.Start)
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis }) // 超出的部分显示省略号。
if (this.compDTO.operDataList[0].coverUrl) {
Stack() {
Image(this.compDTO.operDataList[0].coverUrl)
.borderRadius(5)
.aspectRatio(16 / 9)
.padding({ top: 10 })
if (this.compDTO.operDataList[0].videoInfo) {
Row() {
Image($r('app.media.iv_card_play_yellow_flag'))
.width(22)
.height(18)
Text(DateTimeUtils.getFormattedDuration(this.compDTO.operDataList[0].videoInfo.videoDuration * 1000))
.fontSize($r('app.float.font_size_13'))
.fontWeight(400)
.fontColor($r('app.color.color_fff'))
}
.alignItems(VerticalAlign.Bottom)
.height(18)
.padding({ right: 4 })
.margin({
right: 4,
bottom: 4
})
.backgroundColor($r('app.color.color_4d000000'))
}
}.alignContent(Alignment.BottomEnd)
}
if (this.compDTO.operDataList[0].newsSummary) {
Text(this.compDTO.operDataList[0].newsSummary)
.fontSize(14)
.padding({ top: 10 })
.alignSelf(ItemAlign.Start)
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis }) // 超出的部分显示省略号。
}
Row() {
Text(this.compDTO.operDataList[0].visitorComment + "评")
.fontSize(12)
.fontColor(Color.Gray)
Image($r('app.media.icon_share'))
.width(16)
.height(16)
.margin(10)
}.width(FULL_PARENT)
.justifyContent(FlexAlign.SpaceBetween)
}
.margin(22)
}
}
\ No newline at end of file
import { Action, CompDTO, Params } from 'wdBean';
import { ExtraDTO } from 'wdBean/src/main/ets/bean/component/extra/ExtraDTO';
import { CompStyle } from 'wdConstant';
import { Logger, DateTimeUtils } from 'wdKit';
import { WDRouterRule } from 'wdRouter';
import { ProcessUtils } from '../../utils/ProcessUtils';
const TAG = 'SingleImageCardComponent';
const FULL_PARENT: string = '100%';
/**
* 单图卡-3行标题/2行标题
* 枚举值13
* ImageCard-03
* 重磅推荐/精选/电视剧/电影/综艺/短剧/更多>/
*/
@Component
export struct SingleImageCardComponent {
@State compDTO: CompDTO = {} as CompDTO
aboutToAppear() {
//Logger.debug(TAG + "" + JSON.stringify(this.compDTO.operDataList));
}
build() {
Row() {
Column() {
Column() {
Text(this.compDTO.operDataList[0].newsTitle)
.fontSize(16)
.fontWeight(FontWeight.Normal)
.maxLines(3)//
.alignSelf(ItemAlign.Start)
.textOverflow({ overflow: TextOverflow.Ellipsis }) // 超出的部分显示省略号。
}.height("80%")
.justifyContent(FlexAlign.Start)
Row() {
if (this.compDTO.operDataList[0].source) {
Text(this.compDTO.operDataList[0].source)
.fontSize($r('app.float.font_size_12'))
.fontColor(Color.Gray)
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })// 超出的部分显示省略号。
.width(this.compDTO.operDataList[0].source.length > 8 ? '50%' : '')
Image($r('app.media.point'))
.width(16)
.height(16)
}
if (this.compDTO.operDataList[0].publishTime && this.compDTO.operDataList[0].publishTime.length === 13) {
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.compDTO.operDataList[0].publishTime)))
.fontSize($r('app.float.font_size_12'))
.fontColor(Color.Gray)
}
Text(this.compDTO.operDataList[0].visitorComment + '评')
.fontSize($r('app.float.font_size_12'))
.fontColor(Color.Gray)
.padding({
left: 5
})
}.alignSelf(ItemAlign.Start)
.height("20%")
.justifyContent(FlexAlign.Start)
}
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Start)
.width('58%')
Blank(16)
if (this.compDTO.operDataList[0].coverUrl) {
Stack() {
Image(this.compDTO.operDataList[0].coverUrl)
.borderRadius(5)
.aspectRatio(this.compDTO.compStyle === CompStyle.Card_13 ? 3 / 2 : 3 / 4)
.height(this.compDTO.compStyle === CompStyle.Card_13 ? 90 : 180)
if (this.compDTO.operDataList[0].videoInfo) {
Row() {
Image($r('app.media.iv_card_play_yellow_flag'))
.width(22)
.height(18)
Text(DateTimeUtils.getFormattedDuration(this.compDTO.operDataList[0].videoInfo.videoDuration * 1000))
.fontSize($r('app.float.font_size_13'))
.fontWeight(400)
.fontColor($r('app.color.color_fff'))
}
.alignItems(VerticalAlign.Bottom)
.height(18)
.padding({ right: 4 })
.margin({
right: 4,
bottom: 4
})
.backgroundColor($r('app.color.color_4d000000'))
} else if(this.compDTO.operDataList[0].voiceInfo) {
Row() {
Image($r('app.media.icon_listen'))
.width(22)
.height(18)
Text(DateTimeUtils.getFormattedDuration(this.compDTO.operDataList[0].voiceInfo
.voiceDuration * 1000))
.fontSize($r('app.float.font_size_13'))
.fontWeight(400)
.fontColor($r('app.color.color_fff'))
}
.alignItems(VerticalAlign.Bottom)
.height(18)
.padding({ right: 4 })
.margin({
right: 4,
bottom: 4
})
.backgroundColor($r('app.color.color_4d000000'))
}
}.alignContent(Alignment.BottomEnd)
}
}
.onClick((event: ClickEvent) => {
ProcessUtils.processPage(this.compDTO?.operDataList[0])
})
.padding(
{ top: 16, bottom: 16, left: 14, right: 14 })
.width(FULL_PARENT)
.height(this.compDTO.compStyle === CompStyle.Card_13 ? 127 : 217)
.justifyContent(FlexAlign.SpaceBetween)
}
}
\ No newline at end of file
// import { CommonConstants } from 'wdConstant/src/main/ets/constants/CommonConstants'
@Entry
@Component
export struct SmallVideoCardComponent {
build() {
Row() {
Column() {
Text('“畅享亚运”新模式活动打卡,看杭州打开“金角银边活动启动 跟着体育明星云打卡,看杭州打开“金角银边')
.fontWeight(400)
.fontSize($r('app.float.font_size_17'))
.maxLines(4)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.fontColor($r('app.color.color_222222'))
.lineHeight(25)
Row() {
Text('人民日报')
.labelTextStyle()
Image($r('app.media.point'))
.width(16)
.height(16)
Text('20分钟前')
.labelTextStyle()
.margin({
right: 6
})
Text('2000评')
.labelTextStyle()
}
}
.height(156)
.layoutWeight(1)
.justifyContent(FlexAlign.SpaceBetween)
.alignItems(HorizontalAlign.Start)
.margin({ right: 12 })
Stack({ alignContent: Alignment.BottomEnd }) {
Image('https://www.harmonyos.com/resource/image/partner/harmonyos-connect/pic_shengtai_connect_qudao_xianxia.jpg')
.width(117)
.aspectRatio(117 / 156)
.border({ radius: 4 })
Row() {
Image($r('app.media.iv_card_play_yellow_flag'))
.width(22)
.height(18)
Text('10:00')
.fontSize($r('app.float.font_size_13'))
.fontWeight(400)
.fontColor($r('app.color.color_fff'))
}
.height(18)
.padding({ right: 4 })
.margin({
right: 4,
bottom: 4
})
.backgroundColor($r('app.color.color_4d000000'))
}
}
// .width(CommonConstants.FULL_WIDTH)
.width('100%')
.height(184)
.padding({
top: 14,
bottom: 14,
left: 16,
right: 16
})
}
}
@Extend(Text) function labelTextStyle() {
.fontSize($r('app.float.font_size_12'))
.fontWeight(400)
.fontColor($r('app.color.color_B0B0B0'))
}
\ No newline at end of file
//缩略标题
import { CommonConstants } from 'wdConstant'
import { CompDTO } from 'wdBean'
import { DateTimeUtils } from 'wdKit'
@Component
export struct TitleAbbrComponent {
@State compDTO: CompDTO = {} as CompDTO
build() {
Column() {
Text(this.compDTO.operDataList[0].newsTitle)
.fontSize($r("app.float.font_size_16"))
.fontColor($r("app.color.color_222222"))
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.width(CommonConstants.FULL_WIDTH)
Row() {
Text("锐评")
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_ED2800"))
Text(this.compDTO.operDataList[0].source)
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
.margin({ left: 6 })
Image($r("app.media.point"))
.width(16)
.height(16)
Text(DateTimeUtils.formatDate(Number.parseFloat(this.compDTO.operDataList[0].publishTime)))
.fontSize($r("app.float.font_size_12"))
.fontColor($r("app.color.color_B0B0B0"))
}.width(CommonConstants.FULL_WIDTH)
.justifyContent(FlexAlign.Start)
.margin({ top: 8 })
}.width(CommonConstants.FULL_WIDTH)
.padding({
top: 14,
left: 16,
right: 16,
bottom: 14
})
.backgroundColor($r("app.color.white"))
.margin({ bottom: 8 })
}
}
\ No newline at end of file