Repository: wangchenyan/wan-harmony
Branch: master
Commit: da0dfc78746c
Files: 77
Total size: 138.2 KB
Directory structure:
gitextract_eaol0spx/
├── .gitignore
├── AppScope/
│ ├── app.json5
│ └── resources/
│ └── base/
│ └── element/
│ └── string.json
├── LICENSE
├── README.md
├── build-profile.json5
├── code-linter.json5
├── entry/
│ ├── .gitignore
│ ├── build-profile.json5
│ ├── hvigorfile.ts
│ ├── obfuscation-rules.txt
│ ├── oh-package.json5
│ └── src/
│ ├── main/
│ │ ├── ets/
│ │ │ ├── Routes.ets
│ │ │ ├── common/
│ │ │ │ ├── CollectUtils.ets
│ │ │ │ ├── EntryContext.ets
│ │ │ │ ├── OHPermission.ets
│ │ │ │ ├── Pair.ets
│ │ │ │ ├── Preferences.ets
│ │ │ │ ├── Toast.ets
│ │ │ │ └── WindowUtils.ets
│ │ │ ├── entryability/
│ │ │ │ └── EntryAbility.ets
│ │ │ ├── net/
│ │ │ │ ├── Api.ets
│ │ │ │ ├── Headers.ets
│ │ │ │ ├── HttpClient.ets
│ │ │ │ ├── Response.ets
│ │ │ │ ├── cookie/
│ │ │ │ │ ├── Cookie.ets
│ │ │ │ │ ├── CookieJar.ets
│ │ │ │ │ ├── CookiePersistor.ets
│ │ │ │ │ ├── CookieUtils.ets
│ │ │ │ │ ├── KVCookiePersistor.ets
│ │ │ │ │ └── PersistentCookieJar.ets
│ │ │ │ └── model/
│ │ │ │ ├── Article.ets
│ │ │ │ ├── Harmony.ets
│ │ │ │ ├── RankingList.ets
│ │ │ │ ├── Search.ets
│ │ │ │ ├── Tree.ets
│ │ │ │ └── WeChat.ets
│ │ │ ├── pages/
│ │ │ │ ├── CollectList.ets
│ │ │ │ ├── Harmony.ets
│ │ │ │ ├── Home.ets
│ │ │ │ ├── Index.ets
│ │ │ │ ├── Login.ets
│ │ │ │ ├── Mine.ets
│ │ │ │ ├── RankingList.ets
│ │ │ │ ├── SearchEntry.ets
│ │ │ │ ├── SearchResult.ets
│ │ │ │ ├── Square.ets
│ │ │ │ ├── TreeTab.ets
│ │ │ │ ├── WebPage.ets
│ │ │ │ ├── Wechat.ets
│ │ │ │ └── WechatTab.ets
│ │ │ ├── router/
│ │ │ │ ├── HRouter.ets
│ │ │ │ ├── RouteExecutor.ets
│ │ │ │ ├── RouteInfo.ets
│ │ │ │ └── RouteRequest.ets
│ │ │ ├── service/
│ │ │ │ └── UserService.ets
│ │ │ └── widgets/
│ │ │ ├── ArticleItemComponent.ets
│ │ │ ├── PageLoading.ets
│ │ │ └── TitleLayout.ets
│ │ ├── module.json5
│ │ └── resources/
│ │ ├── base/
│ │ │ ├── element/
│ │ │ │ ├── color.json
│ │ │ │ └── string.json
│ │ │ └── profile/
│ │ │ └── main_pages.json
│ │ ├── en_US/
│ │ │ └── element/
│ │ │ └── string.json
│ │ └── zh_CN/
│ │ └── element/
│ │ └── string.json
│ └── ohosTest/
│ ├── ets/
│ │ ├── test/
│ │ │ ├── Ability.test.ets
│ │ │ └── List.test.ets
│ │ ├── testability/
│ │ │ ├── TestAbility.ets
│ │ │ └── pages/
│ │ │ └── Index.ets
│ │ └── testrunner/
│ │ └── OpenHarmonyTestRunner.ts
│ ├── module.json5
│ └── resources/
│ └── base/
│ ├── element/
│ │ ├── color.json
│ │ └── string.json
│ └── profile/
│ └── test_pages.json
├── hvigor/
│ └── hvigor-config.json5
├── hvigorfile.ts
└── oh-package.json5
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
/node_modules
/oh_modules
/local.properties
/.idea
**/build
/.hvigor
.cxx
/.clangd
/.clang-format
/.clang-tidy
**/.test
**/oh-package-lock.json5
**/oh_modules
**/.preview
/Users
================================================
FILE: AppScope/app.json5
================================================
{
"app": {
"bundleName": "top.wangchenyan.wanharmony",
"vendor": "wanharmony",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",
"label": "$string:app_name"
}
}
================================================
FILE: AppScope/resources/base/element/string.json
================================================
{
"string": [
{
"name": "app_name",
"value": "WanHarmony"
}
]
}
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# wan-harmony
鸿蒙版玩 Android 客户端
[鸿蒙即将抛弃Android,你还不来学习一下?](https://juejin.cn/post/7340307629891616808)
**当前适配版本为 Harmony OS API 12**
## 环境
- DevEco Studio NEXT Developer Beta1
- Build Version: 5.0.3.403
- Harmony OS Api 12
- hvigor 5.0.0
## 功能
- 登录
- 等级、排名、积分、收藏
- 首页、搜索
- 体系
- 广场
- 体系
- 公众号
## 截图

================================================
FILE: build-profile.json5
================================================
{
"app": {
"signingConfigs": [],
"products": [
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "5.0.2(14)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
"caseSensitiveCheck": true,
"useNormalizedOHMUrl": true
}
}
}
],
"buildModeSet": [
{
"name": "debug",
},
{
"name": "release"
}
]
},
"modules": [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
}
]
}
================================================
FILE: code-linter.json5
================================================
{
"files": [
"**/*.ets"
],
"ignore": [
"**/src/ohosTest/**/*",
"**/src/test/**/*",
"**/src/mock/**/*",
"**/node_modules/**/*",
"**/oh_modules/**/*",
"**/build/**/*",
"**/.preview/**/*"
],
"ruleSet": [
"plugin:@performance/recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"@security/no-unsafe-aes": "error",
"@security/no-unsafe-hash": "error",
"@security/no-unsafe-mac": "warn",
"@security/no-unsafe-dh": "error",
"@security/no-unsafe-dsa": "error",
"@security/no-unsafe-ecdsa": "error",
"@security/no-unsafe-rsa-encrypt": "error",
"@security/no-unsafe-rsa-sign": "error",
"@security/no-unsafe-rsa-key": "error",
"@security/no-unsafe-dsa-key": "error",
"@security/no-unsafe-dh-key": "error",
"@security/no-unsafe-3des": "error"
}
}
================================================
FILE: entry/.gitignore
================================================
/node_modules
/oh_modules
/.preview
/build
/.cxx
/.test
================================================
FILE: entry/build-profile.json5
================================================
{
"apiType": "stageMode",
"buildOption": {
},
"buildOptionSet": [
{
"name": "release",
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": false,
"files": [
"./obfuscation-rules.txt"
]
}
}
}
},
],
"targets": [
{
"name": "default"
},
{
"name": "ohosTest",
}
]
}
================================================
FILE: entry/hvigorfile.ts
================================================
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
================================================
FILE: entry/obfuscation-rules.txt
================================================
# Define project specific obfuscation rules here.
# You can include the obfuscation configuration files in the current module's build-profile.json5.
#
# For more details, see
# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5
# Obfuscation options:
# -disable-obfuscation: disable all obfuscations
# -enable-property-obfuscation: obfuscate the property names
# -enable-toplevel-obfuscation: obfuscate the names in the global scope
# -compact: remove unnecessary blank spaces and all line feeds
# -remove-log: remove all console.* statements
# -print-namecache: print the name cache that contains the mapping from the old names to new names
# -apply-namecache: reuse the given cache file
# Keep options:
# -keep-property-name: specifies property names that you want to keep
# -keep-global-name: specifies names that you want to keep in the global scope
-enable-property-obfuscation
-enable-toplevel-obfuscation
-enable-filename-obfuscation
-enable-export-obfuscation
================================================
FILE: entry/oh-package.json5
================================================
{
"name": "entry",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "",
"author": "",
"license": "",
"dependencies": {
"@ohos/pulltorefresh": "^2.0.5",
"@ohmos/json-bigint": "^1.0.0"
}
}
================================================
FILE: entry/src/main/ets/Routes.ets
================================================
import { collectListNavDesBuilder } from './pages/CollectList'
import { HarmonyNavDesBuilder } from './pages/Harmony'
import { loginNavDesBuilder } from './pages/Login'
import { RankingListNavDesBuilder } from './pages/RankingList'
import { searchEntryNavDesBuilder } from './pages/SearchEntry'
import { searchResultNavDesBuilder } from './pages/SearchResult'
import { webPageNavDesBuilder } from './pages/WebPage'
import { HRouter } from './router/HRouter'
export enum Routes {
Login = '/login',
Web = '/web',
SearchEntry = '/search_entry',
SearchResult = '/search_result',
CollectList = '/collect_list',
Harmony = '/Harmony',
RankingList = '/RankingList'
}
export function registerRoutes() {
HRouter.register(Routes.Login, wrapBuilder(loginNavDesBuilder))
HRouter.register(Routes.Web, wrapBuilder(webPageNavDesBuilder))
HRouter.register(Routes.SearchEntry, wrapBuilder(searchEntryNavDesBuilder))
HRouter.register(Routes.SearchResult, wrapBuilder(searchResultNavDesBuilder))
HRouter.register(Routes.CollectList, wrapBuilder(collectListNavDesBuilder))
HRouter.register(Routes.Harmony, wrapBuilder(HarmonyNavDesBuilder))
HRouter.register(Routes.RankingList, wrapBuilder(RankingListNavDesBuilder))
}
================================================
FILE: entry/src/main/ets/common/CollectUtils.ets
================================================
import Api from '../net/Api';
import { Article } from '../net/model/Article';
import UserService from '../service/UserService';
import { toast } from './Toast';
export default class CollectUtils {
static async collect(article: Article, id?: number): Promise<boolean> {
if (!UserService.get().isLogin()) {
UserService.get().checkLogin();
return Promise.resolve(false);
}
if (!id) {
id = article.id;
}
if (article.collect) {
const res = await Api.get().unCollect(id);
if (res.isSuccess()) {
article.collect = false;
} else {
toast(res.errorMsg);
}
return Promise.resolve(res.isSuccess());
} else {
const res = await Api.get().collect(id);
if (res.isSuccess()) {
article.collect = true;
} else {
toast(res.errorMsg);
}
return Promise.resolve(res.isSuccess());
}
}
}
================================================
FILE: entry/src/main/ets/common/EntryContext.ets
================================================
export default class EntryContext {
private static context: Context
static setContext(context: Context) {
EntryContext.context = context
}
static getContext(): Context {
if (!EntryContext.context) {
throw Error("context is not init")
}
return EntryContext.context
}
}
================================================
FILE: entry/src/main/ets/common/OHPermission.ets
================================================
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import bundleManager from '@ohos.bundle.bundleManager';
import { BusinessError } from '@kit.BasicServicesKit';
export default class OHPermission {
static requestPermission(context: Context, permissionList: Permissions[]): Promise<void> {
return new Promise<void>((resolve, reject) => {
const atManager = abilityAccessCtrl.createAtManager();
// requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
atManager.requestPermissionsFromUser(context, permissionList)
.then((data) => {
const grantStatus: number[] = data.authResults;
const length: number = grantStatus.length;
for (let i = 0; i < length; i++) {
if (grantStatus[i] !== 0) {
// 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
reject()
}
}
// 授权成功
resolve()
})
.catch((err: BusinessError) => {
console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
reject()
})
});
}
static async checkPermission(permission: Permissions): Promise<boolean> {
const grantStatus: abilityAccessCtrl.GrantStatus = await OHPermission.checkAccessToken(permission);
if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
// 已经授权,可以继续访问目标操作
return true
} else {
return false
}
}
private static async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
const atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
// 获取应用程序的accessTokenID
let tokenId: number = 0;
try {
const bundleInfo: bundleManager.BundleInfo =
await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
const appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
tokenId = appInfo.accessTokenId;
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`);
}
// 校验应用是否被授予权限
try {
grantStatus = await atManager.checkAccessToken(tokenId, permission);
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`);
}
return grantStatus;
}
}
================================================
FILE: entry/src/main/ets/common/Pair.ets
================================================
export class Pair<T, U> {
first: T;
second: U;
constructor(first: T, second: U) {
this.first = first;
this.second = second;
}
}
================================================
FILE: entry/src/main/ets/common/Preferences.ets
================================================
import dataPreferences from '@ohos.data.preferences';
import JSON from '@ohmos/json-bigint';
import { User } from '../service/UserService';
import { Pair } from './Pair';
const PREFERENCES_NAME = "top.wangchenyan.wanharmony"
const KEY_USER_INFO = "user_info";
const KEY_SEARCH_HISTORY = "search_history";
const KEY_SELECTED_TREE_ID_1 = "selected_tree_id_1";
const KEY_SELECTED_TREE_ID_2 = "selected_tree_id_2";
export default class Preferences {
private static instance: Preferences;
private preferences: dataPreferences.Preferences;
private constructor(context: Context) {
this.preferences = dataPreferences.getPreferencesSync(context, {
name: PREFERENCES_NAME
});
}
getUser(): User | undefined {
const json = this.preferences.getSync(KEY_USER_INFO, "");
if (json) {
const user: User = JSON.parse(json)
return user;
} else {
return undefined;
}
}
putUser(user?: User) {
if (user) {
this.preferences.putSync(KEY_USER_INFO, JSON.stringify(user, undefined, undefined));
} else {
this.preferences.deleteSync(KEY_USER_INFO);
}
this.preferences.flush();
}
getSearchHistory(): string[] {
return this.preferences.getSync(KEY_SEARCH_HISTORY, []) as string[];
}
putSearchHistory(historyKeys: string[]) {
this.preferences.putSync(KEY_SEARCH_HISTORY, historyKeys)
this.preferences.flush()
}
getSelectedTreeId(): Pair<number, number> {
const id1 = this.preferences.getSync(KEY_SELECTED_TREE_ID_1, 0) as number;
const id2 = this.preferences.getSync(KEY_SELECTED_TREE_ID_2, 0) as number;
if (id1 > 0 && id2 > 0) {
return new Pair(id1, id2);
} else {
return new Pair(0, 0);
}
}
putSelectedTreeId(treeId1: number, treeId2: number) {
this.preferences.putSync(KEY_SELECTED_TREE_ID_1, treeId1);
this.preferences.putSync(KEY_SELECTED_TREE_ID_2, treeId2);
this.preferences.flush()
}
static get(context: Context): Preferences {
if (Preferences.instance === undefined) {
Preferences.instance = new Preferences(context);
}
return Preferences.instance;
}
}
================================================
FILE: entry/src/main/ets/common/Toast.ets
================================================
import promptAction from '@ohos.promptAction';
import WindowUtils from './WindowUtils';
export function toast(message: ResourceStr | undefined) {
if (message) {
const bottom = WindowUtils.windowHeight > 0 ? (WindowUtils.windowHeight / 2 + 'px') : undefined;
promptAction.showToast({
message: message,
bottom: bottom
})
}
}
================================================
FILE: entry/src/main/ets/common/WindowUtils.ets
================================================
import window from '@ohos.window'
export default class WindowUtils {
static statusBarHeight: number = 0
static navigationBarHeight: number = 0
static windowWidth: number = 0
static windowHeight: number = 0
static init(windowClass: window.Window) {
const windowRect = windowClass.getWindowProperties().windowRect;
WindowUtils.windowWidth = windowRect.width;
WindowUtils.windowHeight = windowRect.height;
const statusBarAvoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
WindowUtils.statusBarHeight = statusBarAvoidArea.topRect.height;
const navigationBarAvoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
WindowUtils.navigationBarHeight = navigationBarAvoidArea.bottomRect.height;
}
}
================================================
FILE: entry/src/main/ets/entryability/EntryAbility.ets
================================================
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import EntryContext from '../common/EntryContext';
import WindowUtils from '../common/WindowUtils';
import { AbilityConstant, Want } from '@kit.AbilityKit';
const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
private static TAG: string = "EntryAbility"
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
EntryContext.setContext(this.context)
}
async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
// Main window is created, set main page for this ability
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
const windowClass = await windowStage.getMainWindow();
hilog.info(0x0000, EntryAbility.TAG,
'Succeeded in obtaining the main window. Data: ' + JSON.stringify(windowClass));
windowClass.setWindowLayoutFullScreen(true);
WindowUtils.init(windowClass);
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
return;
}
hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
}
onDestroy(): void {
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
}
}
================================================
FILE: entry/src/main/ets/net/Api.ets
================================================
import { Article, ArticleList, HomeBannerData } from './model/Article';
import { User } from '../service/UserService';
import PersistentCookieJar from './cookie/PersistentCookieJar';
import CookieJar from './cookie/CookieJar';
import EntryContext from '../common/EntryContext';
import { Response } from './Response';
import { HotKey } from './model/Search';
import { WeChatAuthor } from './model/WeChat';
import { Tree } from './model/Tree';
import { Rank } from './model/RankingList';
import { Harmony } from './model/Harmony';
import { HttpClient } from './HttpClient';
const BASE_URL: string = "https://www.wanandroid.com";
export default class Api {
private static instance: Api;
private readonly cookieJar: CookieJar;
private readonly httpClient: HttpClient;
private constructor() {
this.cookieJar = new PersistentCookieJar(EntryContext.getContext());
this.httpClient = new HttpClient(BASE_URL, this.cookieJar);
}
static get(): Api {
if (Api.instance === undefined) {
Api.instance = new Api();
}
return Api.instance;
}
clearCookie() {
this.cookieJar.clear();
}
async getHomeArticleList(page: number): Promise<Response<ArticleList>> {
return this.httpClient.get(`/article/list/${page}/json`);
}
async getTopArticle(): Promise<Response<Article[]>> {
return this.httpClient.get("/article/top/json");
}
async getHomeBanner(): Promise<Response<HomeBannerData[]>> {
return this.httpClient.get("/banner/json");
}
async getSquareArticleList(page: number): Promise<Response<ArticleList>> {
return this.httpClient.get(`/user_article/list/${page}/json`);
}
async getWeChatAuthorList(): Promise<Response<WeChatAuthor[]>> {
return this.httpClient.get("/wxarticle/chapters/json")
}
async getWeChatArticleList(id: number, page: number): Promise<Response<ArticleList>> {
return this.httpClient.get(`/wxarticle/list/${id}/${page}/json`);
}
async login(username: string, password: string): Promise<Response<User>> {
return this.httpClient.post(`/user/login?username=${username}&password=${password}`);
}
async logout(): Promise<Response<string>> {
return this.httpClient.get("/user/logout/json");
}
async getUserInfo(): Promise<Response<User>> {
return this.httpClient.get("/lg/coin/userinfo/json");
}
async getSearchHotKey(): Promise<Response<HotKey[]>> {
return this.httpClient.get("/hotkey/json")
}
async search(keyword: string, page: number): Promise<Response<ArticleList>> {
return this.httpClient.post(`/article/query/${page}/json?k=${encodeURIComponent(keyword)}`)
}
async collect(id: number): Promise<Response<object>> {
return this.httpClient.post(`/lg/collect/${id}/json`)
}
async unCollect(id: number): Promise<Response<object>> {
return this.httpClient.post(`/lg/uncollect_originId/${id}/json`)
}
async getCollectList(page: number): Promise<Response<ArticleList>> {
return this.httpClient.get(`/lg/collect/list/${page}/json`)
}
async getTree(): Promise<Response<Tree[]>> {
return this.httpClient.get(`/tree/json`)
}
async getTreeArticleList(cid: number, page: number): Promise<Response<ArticleList>> {
return this.httpClient.get(`/article/list/${page}/json?cid=${cid}`)
}
async getHarmony(): Promise<Response<Harmony>> {
return this.httpClient.get(`/harmony/index/json`)
}
async getRankingList(page: number): Promise<Response<Rank>> {
const url = `/coin/rank/${page}/json`;
return this.httpClient.get(url);
}
}
================================================
FILE: entry/src/main/ets/net/Headers.ets
================================================
export class Headers {
contentType?: string;
cookie?: string;
}
================================================
FILE: entry/src/main/ets/net/HttpClient.ets
================================================
import CookieJar from './cookie/CookieJar'
import { http } from '@kit.NetworkKit'
import { Response } from './Response'
import { Headers } from './Headers'
import { uri } from '@kit.ArkTS'
import CookieUtils from './cookie/CookieUtils'
import { hilog } from '@kit.PerformanceAnalysisKit'
import UserService from '../service/UserService'
const TAG = "HttpClient";
const CODE_UNAUTH = -1001;
export class HttpClient {
readonly baseUrl: string
readonly cookieJar: CookieJar
constructor(baseUrl: string, cookieJar: CookieJar) {
this.baseUrl = baseUrl
this.cookieJar = cookieJar
}
async get<T>(path: string): Promise<Response<T>> {
return this.requestSync(path, http.RequestMethod.GET);
}
async post<T>(path: string, extraData?: object): Promise<Response<T>> {
return this.requestSync(path, http.RequestMethod.POST, extraData);
}
async requestSync<T>(
path: string,
method: http.RequestMethod,
extraData?: object
): Promise<Response<T>> {
const headers = new Headers();
const url = this.baseUrl + path;
const uri = this.parseUri(url);
const cookies = this.cookieJar.loadForRequest(uri);
if (cookies.length > 0) {
headers.cookie = CookieUtils.cookieHeader(cookies);
}
if (method === http.RequestMethod.POST) {
headers.contentType = "application/x-www-form-urlencoded"
if (!extraData) {
// POST 必须有请求体,否则会报 Parameter error
extraData = new Object();
}
}
const httpRequest = http.createHttp();
hilog.info(0, TAG,
`start request, path: ${path}, method: ${method}, extraData: ` + JSON.stringify(extraData, undefined, undefined));
const res = new Response<T>()
let resp: http.HttpResponse
try {
resp = await httpRequest.request(
url,
{
method: method,
expectDataType: http.HttpDataType.OBJECT,
header: headers,
extraData: extraData
})
} catch (err) {
hilog.error(0, TAG, `request error, path: ${path}, error: ${JSON.stringify(err, undefined, undefined)}`)
res.errorCode = -1
res.errorMsg = err?.message ?? ""
return res;
}
if (resp.responseCode === 200) {
this.cookieJar.saveFromResponse(uri, CookieUtils.parseHttpRequestCookies(resp.cookies))
if (resp.resultType === http.HttpDataType.STRING) {
const result: Response<T> = JSON.parse(resp.result as string);
res.errorCode = result.errorCode;
res.errorMsg = result.errorMsg;
res.data = result.data;
} else if (resp.resultType === http.HttpDataType.OBJECT) {
const result = resp.result as Response<T>;
res.errorCode = result.errorCode;
res.errorMsg = result.errorMsg;
res.data = result.data;
} else {
res.errorCode = -1
res.errorMsg = `UnSupport data type: ${resp.resultType}`
}
hilog.info(0, TAG, `request success, path: ${path}, result: ${JSON.stringify(res, undefined, undefined)}`)
if (res.errorCode === CODE_UNAUTH) {
// token 失效
UserService.get().clearUser();
}
} else {
hilog.error(0, TAG, `request error, path: ${path}, http code: ${resp.responseCode}`)
res.errorCode = resp.responseCode
}
return res;
}
private parseUri(url: string): uri.URI {
return new uri.URI(url);
}
}
================================================
FILE: entry/src/main/ets/net/Response.ets
================================================
export class Response<T> {
errorCode: number = 0
errorMsg: string = ""
data?: T = undefined
isSuccess(): boolean {
return this.errorCode === 0
}
isSuccessWithData(): boolean {
return this.errorCode === 0 && this.data !== undefined;
}
getDataOrThrow(): T {
return this.data!!
}
}
================================================
FILE: entry/src/main/ets/net/cookie/Cookie.ets
================================================
/**
* Cookie 对象,参考 OkHttp 中 Cookie 结构
*/
export default interface Cookie {
domain: string;
path: string;
expiresAt: number;
name: string;
value: string;
httpOnly: boolean;
persistent: boolean;
}
================================================
FILE: entry/src/main/ets/net/cookie/CookieJar.ets
================================================
import uri from '@ohos.uri';
import Cookie from './Cookie';
export default interface CookieJar {
saveFromResponse(url: uri.URI, cookies: Cookie[]): void;
loadForRequest(url: uri.URI): Cookie[];
clear(): void;
}
================================================
FILE: entry/src/main/ets/net/cookie/CookiePersistor.ets
================================================
import Cookie from './Cookie';
export default interface CookiePersistor {
loadAll(): Cookie[];
saveAll(cookies: Cookie[]): void;
removeAll(cookies: Cookie[]): void;
clear(): void;
}
================================================
FILE: entry/src/main/ets/net/cookie/CookieUtils.ets
================================================
import Cookie from './Cookie';
import { uri } from '@kit.ArkTS';
export default class CookieUtils {
/**
* httpRequest 返回的 cookie 格式:
* ```
* #HttpOnly_www.wanandroid.com FALSE / TRUE 0 JSESSIONID 564CB756D6C2F19456141DA377A0D692
* www.wanandroid.com FALSE / FALSE 1705495544 loginUserName chaywong
* www.wanandroid.com FALSE / FALSE 1705495544 token_pass d4fb1b1219a552003c5ec2e93221b0b0
* .wanandroid.com TRUE / FALSE 1705495544 loginUserName_wanandroid_com chaywong
* .wanandroid.com TRUE / FALSE 1705495544 token_pass_wanandroid_com d4fb1b1219a552003c5ec2e93221b0b0
* ```
*/
static parseHttpRequestCookies(cookieString: string): Cookie[] {
if (!cookieString) {
return [];
}
const cookies: Cookie[] = [];
const lines = cookieString.split("\r\n");
lines.forEach((line) => {
const attrs = line.split("\t");
if (attrs.length !== 7 || !attrs[0]) {
return;
}
let domain = attrs[0];
let httpOnly = false;
if (domain.startsWith("#HttpOnly_")) {
domain = domain.substring("#HttpOnly_".length);
httpOnly = true;
}
cookies.push({
domain: domain,
path: attrs[2],
expiresAt: parseInt(attrs[4]),
name: attrs[5],
value: attrs[6],
httpOnly: httpOnly,
persistent: true
});
})
return cookies;
}
static cookieHeader(cookies: Cookie[]): string {
let str = "";
cookies.forEach((cookie, index) => {
if (index > 0) {
str += "; ";
}
str += cookie.name + "=" + cookie.value;
});
return str;
}
static matches(cookie: Cookie, url: uri.URI): boolean {
const domainMatch = CookieUtils.domainMatch(url.host, cookie.domain);
if (!domainMatch) {
return false;
}
if (!CookieUtils.pathMatch(url, cookie.path)) {
return false;
}
return true;
}
static createCookieKey(cookie: Cookie): string {
return `https://${cookie.domain}${cookie.path}|${cookie.name}`;
}
static isExpired(cookie: Cookie): boolean {
const nowTime = Date.now() / 1000;
return cookie.expiresAt < nowTime;
}
static fromJson(json: string): Cookie | undefined {
if (json.length === 0) {
return undefined;
}
const temp: Cookie | undefined = JSON.parse(json);
return temp;
}
private static domainMatch(urlHost: string, domain: string): boolean {
if (urlHost === domain) {
return true; // As in 'example.com' matching 'example.com'.
}
return urlHost.endsWith(domain) && urlHost[urlHost.length - domain.length - 1] === ".";
}
private static pathMatch(url: uri.URI, path: string): boolean {
const urlPath = url.path;
if (urlPath === path) {
return true; // As in '/foo' matching '/foo'.
}
if (urlPath.startsWith(path)) {
if (path.endsWith("/")) {
return true;
} // As in '/' matching '/foo'.
if (urlPath[path.length] === "/") {
return true;
} // As in '/foo' matching '/foo/bar'.
}
return false;
}
}
================================================
FILE: entry/src/main/ets/net/cookie/KVCookiePersistor.ets
================================================
import Cookie from './Cookie';
import dataPreferences from '@ohos.data.preferences';
import CookiePersistor from './CookiePersistor';
import JSON from '@ohmos/json-bigint';
import CookieUtils from './CookieUtils';
const PREFERENCES_NAME = "top.wangchenyan.cookie.persistor"
const KEY_COOKIE_KEYS = "COOKIE_KEYS";
export default class KVCookiePersistor implements CookiePersistor {
private static TAG = "KVCookiePersistor";
private preferences: dataPreferences.Preferences;
constructor(context: Context) {
this.preferences = dataPreferences.getPreferencesSync(context, {
name: PREFERENCES_NAME
});
}
loadAll(): Cookie[] {
const cookies: Cookie[] = [];
const keys = this.preferences.getSync(KEY_COOKIE_KEYS, []) as string[]
keys.forEach((key) => {
const value = this.preferences.getSync(key, "") as string
if (value.length > 0) {
const cookie = CookieUtils.fromJson(value);
if (cookie) {
cookies.push(cookie);
}
}
})
return cookies;
}
saveAll(cookies: Cookie[]) {
cookies.forEach((cookie) => {
this.preferences.putSync(CookieUtils.createCookieKey(cookie), JSON.stringify(cookie, undefined, undefined));
});
const keys = this.preferences.getSync(KEY_COOKIE_KEYS, []) as string[]
cookies.forEach((cookie) => {
const key = CookieUtils.createCookieKey(cookie);
if (keys.indexOf(key) < 0) {
keys.push(key)
}
})
this.preferences.putSync(KEY_COOKIE_KEYS, keys);
this.preferences.flush();
}
removeAll(cookies: Cookie[]) {
const keys = this.preferences.getSync(KEY_COOKIE_KEYS, []) as string[]
cookies.forEach((cookie) => {
const key = CookieUtils.createCookieKey(cookie);
this.preferences.deleteSync(key);
const index = keys.indexOf(key);
if (index >= 0) {
keys.splice(index, 1);
}
});
this.preferences.putSync(KEY_COOKIE_KEYS, keys);
this.preferences.flush();
}
clear() {
this.preferences.clearSync();
this.preferences.flush();
}
}
================================================
FILE: entry/src/main/ets/net/cookie/PersistentCookieJar.ets
================================================
import HashMap from '@ohos.util.HashMap';
import uri from '@ohos.uri';
import Cookie from './Cookie';
import CookieJar from './CookieJar';
import CookiePersistor from './CookiePersistor';
import KVCookiePersistor from './KVCookiePersistor';
import CookieUtils from './CookieUtils';
export default class PersistentCookieJar implements CookieJar {
private static TAG = "PersistentCookieJar";
private cache: HashMap<string, Cookie> = new HashMap();
private persistor: CookiePersistor;
constructor(context: Context) {
this.persistor = new KVCookiePersistor(context);
const cookies = this.persistor.loadAll();
cookies.forEach((cookie) => {
this.cache.set(CookieUtils.createCookieKey(cookie), cookie);
})
}
saveFromResponse(url: uri.URI, cookies: Cookie[]): void {
cookies.forEach((cookie) => {
this.cache.set(CookieUtils.createCookieKey(cookie), cookie);
})
this.persistor.saveAll(PersistentCookieJar.filterPersistentCookies(cookies));
}
private static filterPersistentCookies(cookies: Cookie[]): Cookie[] {
return cookies.filter((item) => {
return item.persistent;
})
}
loadForRequest(url: uri.URI): Cookie[] {
const cookiesToRemove: Cookie[] = [];
const validCookies: Cookie[] = [];
const iterator: IterableIterator<Cookie> = this.cache.values();
let result = iterator.next();
while (!result.done) {
const currentCookie: Cookie = result.value;
if (CookieUtils.isExpired(currentCookie)) {
cookiesToRemove.push(currentCookie);
} else if (CookieUtils.matches(currentCookie, url)) {
validCookies.push(currentCookie);
}
result = iterator.next();
}
cookiesToRemove.forEach((item) => {
this.cache.remove(CookieUtils.createCookieKey(item));
})
this.persistor.removeAll(cookiesToRemove);
return validCookies;
}
clear(): void {
this.cache.clear();
this.persistor.clear();
}
}
================================================
FILE: entry/src/main/ets/net/model/Article.ets
================================================
export class ArticleList {
curPage: number = 0
datas: Article[] = []
offset: number = 0
over: boolean = false
pageCount: number = 0
size: number = 0
total: number = 0
}
export class Article {
id: number = 0
apkLink: string = ""
audit: number = 0
author: string = ""
canEdit: boolean = false
chapterId: number = 0
chapterName: string = ""
collect: boolean = false
courseId: number = 0
desc: string = ""
descMd: string = ""
envelopePic: string = ""
fresh: boolean = false
host: string = ""
link: string = ""
niceDate: string = ""
niceShareDate: string = ""
origin: string = ""
prefix: string = ""
projectLink: string = ""
publishTime: number = 0
realSuperChapterId: number = 0
selfVisible: number = 0
shareDate: number = 0
shareUser: string = ""
superChapterId: number = 0
superChapterName: string = ""
title: string = ""
type: number = 0
userId: number = 0
visible: number = 0
zan: number = 0
adminAdd: boolean = false;
isAdminAdd: boolean = false;
originId: number = 0;
tags: ArticleTag[] = [];
}
export function getArticleAuthor(article: Article): string {
return article.author ?? article.shareUser;
}
export function getArticleChapter(article: Article): string {
let chapter = article.superChapterName ?? "";
if (chapter && article.chapterName) {
chapter = chapter + " / ";
}
chapter = chapter + article.chapterName ?? "";
return chapter;
}
export class ArticleTag {
name: string = ""
url: string = ""
}
export function getTagColor(tag: ArticleTag): Resource {
switch (tag.name) {
case "置顶":
return $r("app.color.red")
case "本站发布":
return $r("app.color.blue")
case "问答":
return $r("app.color.cyan")
case "公众号":
return $r("app.color.main")
case "项目":
return $r("app.color.teal")
default:
return $r("app.color.main")
}
}
export class HomeBannerData {
id: number = 0
desc: string = ""
imagePath: string = ""
isVisible: number = 0
order: number = 0
title: string = ""
type: number = 0
url: string = ""
}
================================================
FILE: entry/src/main/ets/net/model/Harmony.ets
================================================
import { Article } from "./Article";
export class Links {
articleList: Article[] = []
author: string = ""
children: [] = []
courseId: number = 0
cover: string = ""
desc: string = ""
id: number = 0
lisense: string = ""
lisenseLink: string = ""
name: string = ""
order: number = 0
parentChapterId: number = 0
type: number = 0
userControlSetTop: boolean = false
visible: number = 0
}
export class Open_sources {
articleList: Article[] = []
author: string = ""
children: [] = []
courseId: number = 0
cover: string= ""
desc: string = ""
id: number = 0
lisense: string = ""
lisenseLink: string = ""
name: string = ""
order: number = 0
parentChapterId: number = 0
type: number = 0
userControlSetTop: boolean = false
visible: number = 0
}
export class Tools {
articleList: Article[] = []
author: string = ""
children: [] = []
courseId: number = 0
cover: string = ""
desc: string = ""
id: number = 0
lisense: string = ""
lisenseLink: string = ""
name: string = ""
order: number = 0
parentChapterId: number = 0
type: number = 0
userControlSetTop: boolean = false
visible: number = 0
}
export class Harmony {
links: Links | null = new Links();
open_sources: Open_sources | null = new Open_sources();
tools: Tools | null = new Tools();
}
================================================
FILE: entry/src/main/ets/net/model/RankingList.ets
================================================
export class RankingList {
coinCount: number = 0
level: number = 0
nickname: string = ""
rank: string = ""
userId: number = 0
username: string = ""
}
export class Rank {
curPage: number = 0
datas: RankingList[] = []
offset: number = 0
over: boolean = false
pageCount: number = 0
size: number = 0
total: number = 0
}
================================================
FILE: entry/src/main/ets/net/model/Search.ets
================================================
export class HotKey {
id: number = 0
name: string = ""
}
================================================
FILE: entry/src/main/ets/net/model/Tree.ets
================================================
import { Article } from './Article'
export class Tree {
articleList: Article[] = []
author: string = ""
children: Tree[] = []
courseId: number = 0
cover: string = ""
desc: string = ""
id: number = 0
lisense: string = ""
lisenseLink: string = ""
name: string = ""
order: number = 0
parentChapterId: number = 0
type: number = 0
userControlSetTop: boolean = false
visible: number = 0
}
================================================
FILE: entry/src/main/ets/net/model/WeChat.ets
================================================
export class WeChatAuthor {
id: number = 0
name: string = ""
}
================================================
FILE: entry/src/main/ets/pages/CollectList.ets
================================================
import { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';
import hilog from '@ohos.hilog';
import Api from '../net/Api';
import { Article } from '../net/model/Article';
import { LoadState, PageLoading } from '../widgets/PageLoading';
import { TitleLayout } from '../widgets/TitleLayout';
import { ArticleItemComponent } from '../widgets/ArticleItemComponent';
import CollectUtils from '../common/CollectUtils';
import { RouteParams } from '../router/RouteInfo';
@Component
struct CollectList {
@State loadState: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
@State title: string = "我的收藏";
@State data: Article[] = [];
private static TAG = "CollectList"
private scroller: Scroller = new Scroller();
private refreshConfig = new PullToRefreshConfigurator();
private nextPage: number = 1;
private hasMore: boolean = true;
aboutToAppear() {
this.loadData();
}
build() {
Column() {
TitleLayout({
title: this.title
})
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, CollectList.TAG, "onReload");
this.loadData();
}
}) {
Column() {
PullToRefresh({
data: $data,
scroller: this.scroller,
refreshConfigurator: this.refreshConfig,
customList: () => {
this.listViewBuilder();
},
onRefresh: () => {
return new Promise<string>((resolve, reject) => {
this.loadDataByPage(0).then(
(data) => {
this.nextPage = 1;
this.data = data;
resolve('刷新成功');
},
() => {
resolve('刷新失败');
}
)
});
},
onLoadMore: () => {
return new Promise<string>((resolve, reject) => {
if (this.hasMore) {
this.loadDataByPage(this.nextPage).then(
(data) => {
if (data.length > 0) {
this.nextPage++
this.data = this.data.concat(data);
resolve('加载成功');
} else {
this.hasMore = false;
resolve('没有更多了');
}
},
() => {
resolve('加载失败');
}
)
} else {
resolve('没有更多了');
}
});
},
customLoad: null,
customRefresh: null,
})
}
.width('100%')
.height('100%')
}
}
.width('100%')
.height('100%')
}
@Builder
private listViewBuilder() {
List({ scroller: this.scroller }) {
ForEach(this.data, (item: Article) => {
ListItem() {
ArticleItemComponent({
article: item,
onCollectClick: (article: Article) => {
CollectUtils.collect(article, article.originId)
.then((success) => {
if (success) {
this.data = this.data.map(item => item);
}
})
}
})
}
})
}
.width('100%')
.height('100%')
.listDirection(Axis.Vertical)
.divider({
strokeWidth: 0.5,
color: $r("app.color.divider"),
startMargin: 16,
endMargin: 16
})
.edgeEffect(EdgeEffect.None) // 必须设置列表为滑动到边缘无效果
}
private loadData() {
this.loadState = LoadState.LOADING
this.loadDataByPage(0).then(
(data) => {
this.data = data;
if (this.data.length === 0) {
this.loadState = LoadState.EMPTY;
} else {
this.loadState = LoadState.SUCCESS;
}
},
() => {
this.loadState = LoadState.FAIL;
})
}
private async loadDataByPage(page: number): Promise<Article[]> {
const res = await Api.get().getCollectList(page);
if (res.isSuccessWithData()) {
const list = res.getDataOrThrow().datas;
list.forEach((item) => {
item.collect = true;
})
return Promise.resolve(list);
} else {
return Promise.reject();
}
}
}
@Builder
export function collectListNavDesBuilder(params: RouteParams) {
NavDestination() {
CollectList()
}
.hideTitleBar(true)
}
================================================
FILE: entry/src/main/ets/pages/Harmony.ets
================================================
import hilog from '@ohos.hilog';
import Api from '../net/Api';
import { LoadState, PageLoading } from '../widgets/PageLoading';
import { TitleLayout } from '../widgets/TitleLayout';
import { ArticleItemComponent } from '../widgets/ArticleItemComponent';
import CollectUtils from '../common/CollectUtils';
import { HRouter } from '../router/HRouter';
import { RouteMode, RouteParams } from '../router/RouteInfo';
import { Article } from '../net/model/Article';
import { Harmony, Links, Open_sources, Tools } from '../net/model/Harmony';
import { Response } from '../net/Response';
import { Routes } from '../Routes';
interface HarmonyCategory {
name: string;
key: 'links' | 'open_sources' | 'tools';
}
interface GeneratedTypeLiteralInterface_1 {
categoryData: Links | Open_sources | Tools | null;
}
@Component
struct HarmonyTab {
@Prop categoryData: Links | Open_sources | Tools | null;
private static TAG = "HarmonyTab";
private scroller: Scroller = new Scroller();
@State articleList: Article[] = [];
onParameterChanged(params: GeneratedTypeLiteralInterface_1): void {
this.categoryData = params.categoryData;
this.updateArticleList();
}
aboutToAppear() {
this.updateArticleList();
}
private updateArticleList() {
this.articleList = this.categoryData?.articleList || [];
hilog.info(0, HarmonyTab.TAG, `加载分类文章数:${this.articleList.length}`);
}
private async handleCollectClick(article: Article) {
const success: boolean = await CollectUtils.collect(article);
if (success) {
this.articleList = this.articleList.map(item => item);
}
}
build() {
List({ scroller: this.scroller }) {
ForEach(this.articleList, (item: Article) => {
ListItem() {
ArticleItemComponent({
article: item,
clearTop: true,
onCollectClick: (article): Promise<void> => this.handleCollectClick(article)
})
}
.padding({ top: 8, bottom: 8 })
})
if (this.articleList.length === 0) {
ListItem() {
Column({ space: 8 }) {
Text('暂无相关文章')
.fontSize(14)
.fontColor($r("app.color.navi_bar_bg")) // 确保资源存在
}
.width('100%')
.height(100)
.justifyContent(FlexAlign.Center)
}
}
}
.width('100%')
.height('100%')
.listDirection(Axis.Vertical)
.divider({
strokeWidth: 0.5,
color: $r("app.color.divider"),
startMargin: 16,
endMargin: 16
})
.edgeEffect(EdgeEffect.None)
}
}
@Component
export struct HarmonyPage {
@State title: string = "鸿蒙开发专栏";
@State loadState: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
clearTop: boolean = false;
@State categories: HarmonyCategory[] = [
{ name: '链接', key: 'links' },
{ name: '开源项目', key: 'open_sources' },
{ name: '工具', key: 'tools' }
];
@State harmonyData: Harmony | null = null;
private static TAG = "HarmonyPage";
aboutToAppear() {
this.loadData();
}
private getTabData(categoryKey: 'links' | 'open_sources' | 'tools'): Links | Open_sources | Tools | null {
if (!this.harmonyData) {
return null;
}
switch (categoryKey) {
case 'links':
return this.harmonyData.links;
case 'open_sources':
return this.harmonyData.open_sources;
case 'tools':
return this.harmonyData.tools;
default:
return null;
}
}
build() {
Column() {
TitleLayout({
title: this.title,
showBack: false,
menuIcon: $r("app.media.ic_search"),
onMenuClick: () => {
HRouter.with().url(Routes.Web).params('url', "https://ohpm.openharmony.cn/#/cn/home")
.mode(this.clearTop ? RouteMode.ClearTop : RouteMode.Standard)
.start();
}
})
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, HarmonyPage.TAG, "重新加载数据");
this.loadData();
}
}) {
if (this.categories.length > 0) {
Tabs({ barPosition: BarPosition.Start }) {
ForEach(this.categories, (category: HarmonyCategory) => {
TabContent() {
// 传递数据给子组件的@Prop属性(无private初始化问题)
HarmonyTab({
categoryData: this.getTabData(category.key)
})
}
.tabBar(category.name)
})
}
.width('100%')
.height('100%')
.scrollable(true)
.barMode(BarMode.Scrollable)
.barHeight(44)
}
}
}
.width('100%')
.height('100%')
}
private loadData() {
this.loadState = LoadState.LOADING;
Api.get().getHarmony()
.then((res: Response<Harmony>) => {
if (res.errorCode === 0 && res.data) {
this.harmonyData = res.data;
this.loadState = LoadState.SUCCESS;
hilog.info(0, HarmonyPage.TAG, "数据加载成功");
} else {
this.loadState = LoadState.FAIL;
hilog.error(0, HarmonyPage.TAG, `加载失败:${res.errorMsg}`);
}
})
.catch((error: Error) => {
this.loadState = LoadState.FAIL;
hilog.error(0, HarmonyPage.TAG, `加载异常:${error.message}`);
});
}
}
@Builder
export function HarmonyNavDesBuilder(params: RouteParams) {
NavDestination() {
HarmonyPage()
}
.hideTitleBar(true)
}
export { Harmony };
================================================
FILE: entry/src/main/ets/pages/Home.ets
================================================
import hilog from '@ohos.hilog'
import Api from '../net/Api'
import { Article, ArticleTag, HomeBannerData, } from '../net/model/Article'
import { LoadState, PageLoading } from '../widgets/PageLoading'
import { PullToRefresh } from '@ohos/pulltorefresh'
import { TitleLayout } from '../widgets/TitleLayout'
import { ArticleItemComponent } from '../widgets/ArticleItemComponent'
import CollectUtils from '../common/CollectUtils'
import { HRouter } from '../router/HRouter'
import { Routes } from '../Routes'
import { RouteMode } from '../router/RouteInfo'
declare type HomeItemData = Article | HomeBannerData[];
@Component
export struct Home {
@State data: HomeItemData[] = [];
@State loadState: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
@State bannerPosition: number = 0;
@State title: string = "首页";
private static TAG = "Home";
private scroller: Scroller = new Scroller();
private nextPage: number = 1;
private hasMore: boolean = true;
async aboutToAppear() {
hilog.info(0, Home.TAG, "aboutToAppear")
this.loadData();
}
build() {
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, Home.TAG, "onReload");
this.loadData();
}
}) {
Column() {
TitleLayout({
title: this.title,
showBack: false,
menuIcon: $r("app.media.ic_search"),
onMenuClick: () => {
HRouter.with()
.url(Routes.SearchEntry)
.start();
}
});
PullToRefresh({
data: $data,
scroller: this.scroller,
customList: () => {
this.listViewBuilder();
},
onRefresh: () => {
return new Promise<string>((resolve, reject) => {
this.loadDataByPage(0).then(
(data) => {
this.nextPage = 1;
this.data = data;
resolve('刷新成功');
},
() => {
resolve('刷新失败');
}
)
});
},
onLoadMore: () => {
return new Promise<string>((resolve, reject) => {
if (this.hasMore) {
this.loadDataByPage(this.nextPage).then(
(data) => {
if (data.length > 0) {
this.nextPage++
this.data = this.data.concat(data);
resolve('加载成功');
} else {
this.hasMore = false;
resolve('没有更多了')
}
},
() => {
resolve('加载失败');
}
)
} else {
resolve('没有更多了')
}
});
},
customLoad: null,
customRefresh: null,
})
}
.width('100%')
.height('100%')
}
}
@Builder
private listViewBuilder() {
List({ scroller: this.scroller }) {
ForEach(this.data, (item: HomeItemData) => {
ListItem() {
if (item instanceof Array) {
BannerComponent({
bannerList: item
})
} else {
ArticleItemComponent({
article: item as Article,
clearTop: true,
onCollectClick: async (article: Article) => {
const success = await CollectUtils.collect(article)
if (success) {
this.data = this.data.map(item => item);
}
}
})
}
}
})
}
.width('100%')
.height('100%')
.listDirection(Axis.Vertical)
.divider({
strokeWidth: 0.5,
color: $r("app.color.divider"),
startMargin: 16,
endMargin: 16
})
.edgeEffect(EdgeEffect.None) // 必须设置列表为滑动到边缘无效果
}
async loadData() {
this.loadState = LoadState.LOADING
this.loadDataByPage(0).then(
(data) => {
this.data = data;
if (this.data.length === 0) {
this.loadState = LoadState.EMPTY;
} else {
this.loadState = LoadState.SUCCESS;
}
},
() => {
this.loadState = LoadState.FAIL;
})
}
async loadDataByPage(page: number): Promise<HomeItemData[]> {
if (page === 0) {
const bannerRes = await Api.get().getHomeBanner();
const topRes = await Api.get().getTopArticle();
const articleRes = await Api.get().getHomeArticleList(page);
if (bannerRes.isSuccessWithData() && topRes.isSuccessWithData() && articleRes.isSuccessWithData()) {
const bannerList = bannerRes.getDataOrThrow();
let articleList: Article[] = [];
topRes.getDataOrThrow().forEach((item) => {
const tag = new ArticleTag();
tag.name = "置顶";
item.tags = [tag].concat(item.tags);
articleList.push(item);
})
articleList = articleList.concat(articleRes.getDataOrThrow().datas);
let dataList: HomeItemData[] = [];
dataList.push(bannerList);
dataList = dataList.concat(articleList);
return Promise.resolve(dataList);
} else {
return Promise.reject();
}
} else {
const articleRes = await Api.get().getHomeArticleList(page);
if (articleRes.isSuccessWithData()) {
return Promise.resolve(articleRes.getDataOrThrow().datas);
} else {
return Promise.reject();
}
}
}
}
@Component
struct BannerComponent {
private swiperController: SwiperController = new SwiperController()
@State private bannerPosition: number = 0
bannerList: HomeBannerData[] = []
build() {
Stack() {
Swiper(this.swiperController) {
ForEach(this.bannerList, (item: HomeBannerData) => {
this.bannerItemBuilder(item)
})
}
.autoPlay(true)
.index(this.bannerPosition)
.loop(true)
.indicatorStyle({
right: 16,
bottom: 0
})
.onChange((index) => {
this.bannerPosition = index;
})
}
.width('100%')
.height(220)
}
@Builder
private bannerItemBuilder(data: HomeBannerData) {
Stack({ alignContent: Alignment.Bottom }) {
Image(data.imagePath)
.objectFit(ImageFit.Cover)
.width('100%')
.height('100%')
Text(data.title)
.width('100%')
.padding({
left: 16,
top: 6,
right: 16,
bottom: 6
})
.fontColor($r("app.color.white"))
.fontSize(15)
.maxLines(1)
.backgroundColor($r("app.color.translucent_black_40"))
}
.width('100%')
.height('100%')
.onClick((event) => {
HRouter.with()
.url(Routes.Web)
.params('url', data.url)
.mode(RouteMode.ClearTop)
.start()
})
}
}
================================================
FILE: entry/src/main/ets/pages/Index.ets
================================================
import { Home } from './Home'
import { Square } from './Square'
import { Mine } from './Mine'
import { Wechat } from './Wechat'
import OHPermission from '../common/OHPermission'
import { TreeTab } from './TreeTab'
import WindowUtils from '../common/WindowUtils'
import { HRouter } from '../router/HRouter'
import { registerRoutes } from '../Routes'
import { RouteParams } from '../router/RouteInfo'
import { HarmonyPage } from './Harmony'
@Entry
@Component
struct Index {
private static TAG = "Index"
private tabsController = new TabsController()
@State currentIndex: number = 0
@State isPermissionGrant: boolean = false
aboutToAppear() {
registerRoutes()
OHPermission.requestPermission(getContext(this), ['ohos.permission.INTERNET'])
.then((v) => {
this.isPermissionGrant = true;
})
.catch(() => {
this.isPermissionGrant = false;
})
}
build() {
Navigation(HRouter.pathStack) {
this.tabContainerBuilder()
}
.mode(NavigationMode.Auto)
.navBarWidth(360)
.navBarWidthRange([360, 640])
.minContentWidth(640)
.navDestination(this.navDestination)
.hideTitleBar(true)
}
@Builder
tabContainerBuilder() {
Column() {
if (this.isPermissionGrant) {
Tabs({ barPosition: BarPosition.End, controller: this.tabsController }) {
TabContent() {
Home()
}.tabBar(this.tabBuilder("首页", 0, $r("app.media.ic_tab_home_fill"), $r("app.media.ic_tab_home")))
TabContent() {
HarmonyPage()
}.tabBar(this.tabBuilder("鸿蒙", 1, $r("app.media.harmony_tab_fill"), $r("app.media.harmony_tab")))
TabContent() {
Square()
}.tabBar(this.tabBuilder("广场", 2, $r("app.media.ic_tab_discover_fill"), $r("app.media.ic_tab_discover")))
TabContent() {
TreeTab()
}.tabBar(this.tabBuilder("体系", 3, $r("app.media.ic_tab_tree_fill"), $r("app.media.ic_tab_tree")))
TabContent() {
Wechat()
}.tabBar(this.tabBuilder("公众号", 4, $r("app.media.ic_tab_wechat_fill"), $r("app.media.ic_tab_wechat")))
TabContent() {
Mine()
}.tabBar(this.tabBuilder("我的", 5, $r("app.media.ic_tab_my_fill"), $r("app.media.ic_tab_my")))
}
.layoutWeight(1)
.scrollable(false)
.animationDuration(0)
.onChange((index) => {
this.currentIndex = index
})
.backgroundColor($r("app.color.start_window_background"))
} else {
Text("No Permission")
.width('100%')
.layoutWeight(1)
.textAlign(TextAlign.Center)
}
Row()
.width('100%')
.height(WindowUtils.navigationBarHeight + 'px')
.backgroundColor($r("app.color.navi_bar_bg"))
}
.width('100%')
.height('100%')
}
@Builder
tabBuilder(title: string, targetIndex: number, selectedImg: Resource, normalImg: Resource) {
Column() {
Image(this.currentIndex === targetIndex ? selectedImg : normalImg)
.size({ width: 24, height: 24 })
.fillColor(this.currentIndex === targetIndex ? $r("app.color.main") : $r("app.color.navi_tab_unselect"))
Text(title)
.fontColor(this.currentIndex === targetIndex ? $r("app.color.main") : $r("app.color.navi_tab_unselect"))
.fontSize(11)
}
.width('100%')
.height('100%')
.backgroundColor($r("app.color.navi_bar_bg"))
.justifyContent(FlexAlign.Center)
.onClick(() => {
this.currentIndex = targetIndex
this.tabsController.changeIndex(targetIndex)
})
}
@Builder
navDestination(url: string, params: RouteParams) {
HRouter.getNavDesBuilder(url)!.builder(params)
}
}
================================================
FILE: entry/src/main/ets/pages/Login.ets
================================================
import { toast } from '../common/Toast'
import Api from '../net/Api'
import { HRouter } from '../router/HRouter'
import { RouteParams } from '../router/RouteInfo'
import UserService from '../service/UserService'
import { LoadState, PageLoading } from '../widgets/PageLoading'
import { TitleLayout } from '../widgets/TitleLayout'
@Component
struct Login {
@State loadState: LoadState = LoadState.SUCCESS;
@State showLoading: boolean = false;
@State title: string = "登录";
private account: string = "";
private password: string = "";
build() {
Stack() {
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading
}) {
Column() {
TitleLayout({
title: this.title
})
Column() {
TextInput({
placeholder: "请输入用户名"
})
.fontSize(15)
.fontColor($r("app.color.text_h1"))
.type(InputType.Email)
.onChange((value) => {
this.account = value
})
TextInput({
placeholder: "请输入密码"
})
.margin({ top: 16 })
.fontSize(15)
.fontColor($r("app.color.text_h1"))
.type(InputType.Password)
.onChange((value) => {
this.password = value
})
Button("登录", {
type: ButtonType.Capsule
})
.width('100%')
.margin({ top: 50 })
.fontSize(15)
.fontColor($r("app.color.white"))
.backgroundColor($r("app.color.main"))
.onClick((e) => {
this.login().catch();
})
}
.width('100%')
.margin({ top: 120 })
.padding({ left: 16, right: 16 })
}
.width('100%')
.height('100%')
}
}
.width('100%')
.height('100%')
}
async login() {
if (!this.account) {
toast("请输入用户名");
return;
}
if (!this.password) {
toast("请输入密码");
return;
}
this.showLoading = true;
const res = await Api.get().login(this.account, this.password);
this.showLoading = false;
if (res.isSuccessWithData()) {
toast("登录成功");
UserService.get().setUser(res.data);
const user = await UserService.get().updateUser();
if (user) {
HRouter.with()
.params('success', true)
.back();
}
} else {
toast(res.errorMsg);
}
}
}
@Builder
export function loginNavDesBuilder(params: RouteParams) {
NavDestination() {
Login()
}
.hideTitleBar(true)
}
================================================
FILE: entry/src/main/ets/pages/Mine.ets
================================================
import promptAction from '@ohos.promptAction'
import Api from '../net/Api'
import UserService, { User } from '../service/UserService'
import { LoadState, PageLoading } from '../widgets/PageLoading'
import { TitleLayout } from '../widgets/TitleLayout'
import { HRouter } from '../router/HRouter'
import { Routes } from '../Routes'
class UserInfo {
name: string = ""
level: string = ""
rank: string = ""
point: string = ""
}
@Component
export struct Mine {
@State loadState: LoadState = LoadState.SUCCESS;
@State showLoading: boolean = false;
@State title: string = "";
private unLoginInfo: UserInfo = {
name: "未登录",
level: "",
rank: "",
point: ""
}
@State userInfo: UserInfo = this.unLoginInfo;
@State isLogin: boolean = false;
private userObserver = (user?: User) => {
if (user) {
this.isLogin = true;
this.userInfo = {
name: user.nickname,
level: user.level,
rank: user.rank,
point: user.coinCount.toString()
}
} else {
this.isLogin = false;
this.userInfo = this.unLoginInfo
}
}
aboutToAppear() {
UserService.get().addUserObserver(this.userObserver);
const user = UserService.get().getUser();
this.userObserver(user);
}
aboutToDisappear() {
UserService.get().removeUserObserver(this.userObserver);
}
build() {
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading
}) {
Column() {
TitleLayout({
title: this.title,
isJustShowStatusBar: true
})
Column() {
Image($r("app.media.harmony_os"))
.width(100)
.height(100)
Text(this.userInfo.name)
.fontColor($r("app.color.text_h1"))
.fontSize(17)
.margin({ top: 16 })
Row({ space: 5 }) {
Text("LV" + this.userInfo.level)
.fontColor($r("app.color.white"))
.fontSize(15)
.backgroundColor($r("app.color.green"))
.padding({
left: 4,
top: 2,
right: 4,
bottom: 2
})
Text("排名" + this.userInfo.rank)
.fontColor($r("app.color.white"))
.fontSize(15)
.backgroundColor($r("app.color.blue"))
.padding({
left: 4,
top: 2,
right: 4,
bottom: 2
})
}
.margin({ top: 16 })
}
.margin({ top: 30 })
.alignItems(HorizontalAlign.Center)
.onClick((e) => {
UserService.get().checkLogin()
})
Row() {
Text("我的积分")
.layoutWeight(1)
.fontSize(15)
.fontColor($r("app.color.text_h1"))
Text(this.userInfo.point)
.fontSize(15)
.fontColor($r("app.color.text_h1"))
}
.width('100%')
.height(50)
.margin({ top: 50 })
.alignItems(VerticalAlign.Center)
.padding({ left: 16, right: 16 })
.backgroundColor($r("app.color.white"))
.onClick((e) => {
UserService.get().checkLogin()
})
Row()
.width('100%')
.height(0.5)
.backgroundColor($r("app.color.divider"))
Row() {
Text("我的收藏")
.layoutWeight(1)
.fontSize(15)
.fontColor($r("app.color.text_h1"))
Image($r("app.media.ic_arrow_right"))
.fillColor($r("app.color.text_h1"))
.width(20)
.height(20)
}
.width('100%')
.height(50)
.alignItems(VerticalAlign.Center)
.padding({ left: 16, right: 16 })
.backgroundColor($r("app.color.white"))
.onClick((event) => {
UserService.get().checkLogin(() => {
HRouter.with()
.url(Routes.CollectList)
.start()
})
})
Row()
.width('100%')
.height(0.5)
.backgroundColor($r("app.color.divider"))
Row() {
Text("积分排行榜")
.layoutWeight(1)
.fontSize(15)
.fontColor($r("app.color.text_h1"))
Image($r("app.media.ic_arrow_right"))
.fillColor($r("app.color.text_h1"))
.width(20)
.height(20)
}
.width('100%')
.height(50)
.alignItems(VerticalAlign.Center)
.padding({ left: 16, right: 16 })
.backgroundColor($r("app.color.white"))
.onClick((event) => {
UserService.get().checkLogin(() => {
HRouter.with()
.url(Routes.RankingList)
.start()
})
})
if (this.isLogin) {
Column() {
Button("退出登录", {
type: ButtonType.Capsule
})
.width('100%')
.fontSize(15)
.fontColor($r("app.color.white"))
.backgroundColor($r("app.color.red"))
.onClick((e) => {
this.logout();
})
}
.width('100%')
.margin({ top: 50 })
.padding({ left: 16, right: 16 })
}
}
.width('100%')
.height('100%')
}
}
async logout() {
const res = await promptAction.showDialog({
title: "提示",
message: "确认退出登录?",
buttons: [
{
text: "确认",
color: $r("app.color.main")
},
{
text: "取消",
color: $r("app.color.text_h2")
}
]
})
if (res.index === 0) {
await Api.get().logout();
UserService.get().clearUser();
}
}
}
================================================
FILE: entry/src/main/ets/pages/RankingList.ets
================================================
import hilog from '@ohos.hilog';
import Api from '../net/Api';
import { LoadState, PageLoading } from '../widgets/PageLoading';
import { PullToRefresh } from '@ohos/pulltorefresh';
import { TitleLayout } from '../widgets/TitleLayout';
import { HRouter } from '../router/HRouter';
import { RouteParams } from '../router/RouteInfo';
import { RankingList, Rank } from '../net/model/RankingList';
import { Response } from '../net/Response';
@Component
export struct RankingListPage {
@State title: string = "积分排行榜";
@State loadState: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
@State rankingList: RankingList[] = [];
private static TAG = "RankingListPage";
private scroller: Scroller = new Scroller();
private currentPage: number = 1;
private hasMore: boolean = true;
async aboutToAppear() {
hilog.info(0, RankingListPage.TAG, "aboutToAppear:开始加载排行榜数据");
this.loadData();
}
build() {
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, RankingListPage.TAG, "onReload:重新加载排行榜");
this.loadData();
}
}) {
Column() {
TitleLayout({
title: this.title,
showBack: true,
onBack: () => {
HRouter.with().back();
},
menuIcon: undefined,
onMenuClick: undefined
});
PullToRefresh({
data: $rankingList,
scroller: this.scroller,
customList: () => {
this.listViewBuilder();
},
onRefresh: () => {
return new Promise<string>((resolve) => {
this.loadDataByPage(1).then(
(rankData) => {
this.currentPage = 1;
this.rankingList = rankData.datas;
this.hasMore = !rankData.over;
resolve('刷新成功');
},
() => {
resolve('刷新失败');
}
);
});
},
onLoadMore: () => {
return new Promise<string>((resolve) => {
if (this.hasMore) {
this.loadDataByPage(this.currentPage + 1).then(
(rankData) => {
if (rankData.datas.length > 0) {
this.currentPage++;
this.rankingList = this.rankingList.concat(rankData.datas);
this.hasMore = !rankData.over;
resolve('加载成功');
} else {
this.hasMore = false;
resolve('没有更多数据了');
}
},
() => {
resolve('加载失败');
}
);
} else {
resolve('没有更多数据了');
}
});
},
customLoad: null,
customRefresh: null,
})
}
.width('100%')
.height('100%')
}
}
@Builder
private listViewBuilder() {
List({ scroller: this.scroller }) {
ForEach(this.rankingList, (item: RankingList, index: number) => {
ListItem() {
this.rankItemBuilder(item, index + 1);
}
.padding({ top: 12, bottom: 12 })
});
if (this.rankingList.length === 0 && this.loadState === LoadState.SUCCESS) {
ListItem() {
Column({ space: 8 }) {
Text('暂无排行榜数据')
.fontSize(14)
.fontColor($r("app.color.gray600"))
}
.width('100%')
.height(100)
.justifyContent(FlexAlign.Center)
}
}
}
.width('100%')
.height('100%')
.listDirection(Axis.Vertical)
.divider({
strokeWidth: 0.5,
color: $r("app.color.divider"),
startMargin: 16,
endMargin: 16
})
.edgeEffect(EdgeEffect.None);
}
@Builder
private rankItemBuilder(item: RankingList, actualRank: number) {
Row({ space: 16 }) {
Text(actualRank.toString())
.width(24)
.textAlign(TextAlign.Center)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.fontColor(this.getRankColor(actualRank));
Column({ space: 4 }) {
Text(item.username)
.fontSize(15)
.fontColor($r("app.color.text_h1"))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.flexGrow(1);
Text(`等级:${item.level}`)
.fontSize(12)
.fontColor($r("app.color.gray600"));
}
.flexGrow(1);
Text(`积分:${item.coinCount}`)
.fontSize(15)
.fontColor($r("app.color.main"))
.fontWeight(FontWeight.Medium);
}
.width('100%')
.padding({ left: 16, right: 16 });
}
private getRankColor(rank: number): Resource {
switch (rank) {
case 1:
return $r("app.color.rank_gold");
case 2:
return $r("app.color.rank_silver");
case 3:
return $r("app.color.rank_bronze");
default:
return $r("app.color.gray600");
}
}
private async loadData() {
this.loadState = LoadState.LOADING;
try {
const rankData = await this.loadDataByPage(1);
this.rankingList = rankData.datas;
this.currentPage = 1;
this.hasMore = !rankData.over;
this.loadState = this.rankingList.length === 0 ? LoadState.EMPTY : LoadState.SUCCESS;
} catch (error) {
this.loadState = LoadState.FAIL;
// 确保catch中打印的是Error实例的message(避免类型问题)
const errorMsg = error instanceof Error ? error.message : '未知加载错误';
hilog.error(0, RankingListPage.TAG, `初始加载失败:${errorMsg}`);
}
}
private async loadDataByPage(page: number): Promise<Rank> {
try {
hilog.info(0, RankingListPage.TAG, `加载第${page}页排行榜数据`);
const response: Response<Rank> = await Api.get().getRankingList(page);
if (response.errorCode === 0 && response.data) {
return response.data;
} else {
// 2. 修复throw错误:将内容封装成Error实例(原错误位置)
const errorMsg = `接口返回异常:${response.errorMsg || '未知错误'}`;
throw new Error(errorMsg); // 仅抛出Error类型,符合ArkTS规范
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : '网络请求失败';
hilog.error(0, RankingListPage.TAG, `第${page}页加载失败:${errorMsg}`);
// 再次抛出时也确保是Error实例(若上层需要处理)
throw error instanceof Error ? error : new Error(errorMsg);
}
}
}
@Builder
export function RankingListNavDesBuilder(params: RouteParams) {
NavDestination() {
RankingListPage()
}
.hideTitleBar(true);
}
================================================
FILE: entry/src/main/ets/pages/SearchEntry.ets
================================================
import WindowUtils from '../common/WindowUtils'
import Api from '../net/Api'
import { HotKey } from '../net/model/Search'
import Preferences from '../common/Preferences'
import { toast } from '../common/Toast'
import { HRouter } from '../router/HRouter'
import { Routes } from '../Routes'
import { RouteParams } from '../router/RouteInfo'
@Component
struct SearchEntry {
@State showKeyword: string = ""
@State hotKeys: HotKey[] = []
@State historyKeys: string[] = []
private keyword: string = ""
async aboutToAppear() {
this.historyKeys = Preferences.get(getContext()).getSearchHistory()
const res = await Api.get().getSearchHotKey()
if (res.isSuccessWithData()) {
this.hotKeys = res.getDataOrThrow();
}
}
build() {
Column() {
Row()
.width('100%')
.height(WindowUtils.statusBarHeight + 'px')
Row() {
Image($r("app.media.ic_back"))
.width(48)
.height(48)
.padding(14)
.fillColor($r("app.color.text_h1"))
.objectFit(ImageFit.Contain)
.onClick((event) => {
HRouter.with().back();
})
TextInput({
placeholder: "关键词以空格隔开",
text: this.showKeyword
})
.layoutWeight(1)
.fontSize(17)
.fontColor($r("app.color.text_h1"))
.padding({ left: 16, right: 16 })
.onChange((value) => {
this.keyword = value;
})
.onSubmit((keyType) => {
this.search();
})
Image($r("app.media.ic_search"))
.width(48)
.height(48)
.padding(14)
.fillColor($r("app.color.text_h1"))
.objectFit(ImageFit.Contain)
.onClick((event) => {
this.search();
})
}
.width('100%')
.height(48)
.alignItems(VerticalAlign.Center)
Column() {
Text("热门搜索")
.fontColor($r("app.color.text_h1"))
.fontSize(16)
.width('100%')
.margin({ top: 16 })
.padding({ left: 16, right: 16 })
Flex({
direction: FlexDirection.Row,
wrap: FlexWrap.Wrap
}) {
ForEach(this.hotKeys, (key: HotKey) => {
Text(key.name)
.fontColor($r("app.color.text_h1"))
.fontSize(14)
.padding({
left: 12,
top: 6,
right: 12,
bottom: 6
})
.maxLines(1)
.backgroundColor($r("app.color.hot_key_bg"))
.borderRadius(50)
.margin({ top: 8, right: 8 })
.onClick((event) => {
this.showKeyword = key.name;
this.keyword = key.name;
this.search();
})
})
}
.width('100%')
.margin({ top: 8 })
.padding({ left: 16, right: 16 })
Text("搜索历史")
.fontColor($r("app.color.text_h1"))
.fontSize(16)
.width('100%')
.margin({ top: 16 })
.padding({ left: 16, right: 16 })
List() {
ForEach(this.historyKeys, (item: string, index: number) => {
ListItem() {
Row() {
Text(item)
.fontColor($r("app.color.text_h2"))
.fontSize(14)
.layoutWeight(1)
.maxLines(1)
Image($r("app.media.ic_close"))
.width(20)
.height(20)
.fillColor($r("app.color.text_h2"))
.onClick((event) => {
this.deleteHistory(index);
})
}
.width('100%')
.padding({
left: 16,
top: 12,
right: 16,
bottom: 12
})
.onClick((event) => {
this.showKeyword = item;
this.keyword = item;
this.search();
})
}
})
}
.listDirection(Axis.Vertical)
.width('100%')
.height('100%')
.margin({ top: 16 })
}
.width('100%')
}
.width('100%')
.height('100%')
}
search() {
if (!this.keyword) {
toast("请输入关键词");
return;
}
let historyKeys: string[] = [];
historyKeys = historyKeys.concat(this.historyKeys)
const existIndex = historyKeys.findIndex((value) => {
return this.keyword === value;
})
if (existIndex >= 0) {
historyKeys.splice(existIndex, 1);
}
historyKeys.unshift(this.keyword);
this.historyKeys = historyKeys;
Preferences.get(getContext()).putSearchHistory(historyKeys);
HRouter.with()
.url(Routes.SearchResult)
.params('keyword', this.keyword)
.start()
}
deleteHistory(index: number) {
let historyKeys: string[] = [];
historyKeys = historyKeys.concat(this.historyKeys)
historyKeys.splice(index, 1);
this.historyKeys = historyKeys;
Preferences.get(getContext()).putSearchHistory(historyKeys);
}
}
@Builder
export function searchEntryNavDesBuilder(params: RouteParams) {
NavDestination() {
SearchEntry()
}
.hideTitleBar(true)
}
================================================
FILE: entry/src/main/ets/pages/SearchResult.ets
================================================
import hilog from '@ohos.hilog';
import { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';
import CollectUtils from '../common/CollectUtils';
import Api from '../net/Api';
import { Article } from '../net/model/Article';
import { HRouter } from '../router/HRouter';
import { RouteParams } from '../router/RouteInfo';
import { ArticleItemComponent } from '../widgets/ArticleItemComponent';
import { LoadState, PageLoading } from '../widgets/PageLoading';
import { TitleLayout } from '../widgets/TitleLayout';
@Component
struct SearchResult {
@State loadState: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
@State title: string = "";
@State data: Article[] = [];
private static TAG = "SearchResult"
private keyword: string = ""
private scroller: Scroller = new Scroller();
private refreshConfig = new PullToRefreshConfigurator();
private nextPage: number = 1;
private hasMore: boolean = true;
aboutToAppear() {
let routeParams = HRouter.with(this.queryNavDestinationInfo()).getCurrentParams()
this.keyword = routeParams.get('keyword') as string;
this.title = this.keyword;
this.refreshConfig.setHasRefresh(false);
this.loadData();
}
build() {
Column() {
TitleLayout({
title: this.title
})
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, SearchResult.TAG, "onReload");
this.loadData();
}
}) {
Column() {
PullToRefresh({
data: $data,
scroller: this.scroller,
refreshConfigurator: this.refreshConfig,
customList: () => {
this.listViewBuilder();
},
onLoadMore: () => {
return new Promise<string>((resolve, reject) => {
if (this.hasMore) {
this.loadDataByPage(this.nextPage).then(
(data) => {
if (data.length > 0) {
this.nextPage++
this.data = this.data.concat(data);
resolve('加载成功');
} else {
this.hasMore = false;
resolve('没有更多了');
}
},
() => {
resolve('加载失败');
}
)
} else {
resolve('没有更多了');
}
});
},
customLoad: null,
customRefresh: null,
})
}
.width('100%')
.height('100%')
}
}
.width('100%')
.height('100%')
}
@Builder
private listViewBuilder() {
List({ scroller: this.scroller }) {
ForEach(this.data, (item: Article) => {
ListItem() {
ArticleItemComponent({
article: item,
onCollectClick: (article: Article) => {
CollectUtils.collect(article)
.then((success) => {
if (success) {
this.data = this.data.map(item => item);
}
})
}
})
}
})
}
.width('100%')
.height('100%')
.listDirection(Axis.Vertical)
.divider({
strokeWidth: 0.5,
color: $r("app.color.divider"),
startMargin: 16,
endMargin: 16
})
.edgeEffect(EdgeEffect.None) // 必须设置列表为滑动到边缘无效果
}
private loadData() {
this.loadState = LoadState.LOADING
this.loadDataByPage(0).then(
(data) => {
this.data = data;
if (this.data.length === 0) {
this.loadState = LoadState.EMPTY;
} else {
this.loadState = LoadState.SUCCESS;
}
},
() => {
this.loadState = LoadState.FAIL;
})
}
private async loadDataByPage(page: number): Promise<Article[]> {
const res = await Api.get().search(this.keyword, page);
if (res.isSuccessWithData()) {
const list = res.getDataOrThrow().datas;
list.forEach((item) => {
item.title = this.removeHtmlTags(item.title);
})
return Promise.resolve(list);
} else {
return Promise.reject();
}
}
private removeHtmlTags(text: string): string {
// 使用正则表达式将 < 开头到 > 结尾之间的部分全部替换成空字符串
return text.replace(/<[^>]+>/g, '')
.replace('>', '>')
.replace('<', '<');
}
}
@Builder
export function searchResultNavDesBuilder(params: RouteParams) {
NavDestination() {
SearchResult()
}
.hideTitleBar(true)
}
================================================
FILE: entry/src/main/ets/pages/Square.ets
================================================
import hilog from '@ohos.hilog';
import { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';
import CollectUtils from '../common/CollectUtils';
import Api from '../net/Api';
import { Article } from '../net/model/Article';
import { ArticleItemComponent } from '../widgets/ArticleItemComponent';
import { LoadState, PageLoading } from '../widgets/PageLoading';
import { TitleLayout } from '../widgets/TitleLayout';
@Component
export struct Square {
@State loadState: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
@State title: string = "广场";
@State data: Article[] = [];
private static TAG = "Square"
private scroller: Scroller = new Scroller();
private refreshConfig = new PullToRefreshConfigurator();
private nextPage: number = 1;
private hasMore: boolean = true;
aboutToAppear() {
this.loadData();
}
build() {
Column() {
TitleLayout({
title: this.title,
showBack: false,
})
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, Square.TAG, "onReload");
this.loadData();
}
}) {
Column() {
PullToRefresh({
data: $data,
scroller: this.scroller,
refreshConfigurator: this.refreshConfig,
customList: () => {
this.listViewBuilder();
},
onRefresh: () => {
return new Promise<string>((resolve, reject) => {
this.loadDataByPage(0).then(
(data) => {
this.nextPage = 1;
this.data = data;
resolve('刷新成功');
},
() => {
resolve('刷新失败');
}
)
});
},
onLoadMore: () => {
return new Promise<string>((resolve, reject) => {
if (this.hasMore) {
this.loadDataByPage(this.nextPage).then(
(data) => {
if (data.length > 0) {
this.nextPage++
this.data = this.data.concat(data);
resolve('加载成功');
} else {
this.hasMore = false;
resolve('没有更多了');
}
},
() => {
resolve('加载失败');
}
)
} else {
resolve('没有更多了');
}
});
},
customLoad: null,
customRefresh: null,
})
}
.width('100%')
.height('100%')
}
}
.width('100%')
.height('100%')
}
@Builder
private listViewBuilder() {
List({ scroller: this.scroller }) {
ForEach(this.data, (item: Article) => {
ListItem() {
ArticleItemComponent({
article: item,
clearTop: true,
onCollectClick: (article: Article) => {
CollectUtils.collect(article)
.then((success) => {
if (success) {
this.data = this.data.map(item => item);
}
})
}
})
}
})
}
.width('100%')
.height('100%')
.listDirection(Axis.Vertical)
.divider({
strokeWidth: 0.5,
color: $r("app.color.divider"),
startMargin: 16,
endMargin: 16
})
.edgeEffect(EdgeEffect.None) // 必须设置列表为滑动到边缘无效果
}
private loadData() {
this.loadState = LoadState.LOADING
this.loadDataByPage(0).then(
(data) => {
this.data = data;
if (this.data.length === 0) {
this.loadState = LoadState.EMPTY;
} else {
this.loadState = LoadState.SUCCESS;
}
},
() => {
this.loadState = LoadState.FAIL;
})
}
private async loadDataByPage(page: number): Promise<Article[]> {
const res = await Api.get().getSquareArticleList(page);
if (res.isSuccessWithData()) {
const list = res.getDataOrThrow().datas;
return Promise.resolve(list);
} else {
return Promise.reject();
}
}
}
================================================
FILE: entry/src/main/ets/pages/TreeTab.ets
================================================
import { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';
import hilog from '@ohos.hilog';
import { Pair } from '../common/Pair';
import Api from '../net/Api';
import { Article } from '../net/model/Article';
import { Tree } from '../net/model/Tree';
import { LoadState, PageLoading } from '../widgets/PageLoading';
import { TitleLayout } from '../widgets/TitleLayout';
import { ArticleItemComponent } from '../widgets/ArticleItemComponent';
import CollectUtils from '../common/CollectUtils';
import Preferences from '../common/Preferences';
@Component
export struct TreeTab {
@State loadStateTree: LoadState = LoadState.LOADING;
@State loadStateArticle: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
@State title: string = "体系";
@State treeList: Tree[] = [];
@State data: Article[] = [];
@State selectTrees: Pair<Tree | undefined, Tree | undefined> = new Pair(undefined, undefined);
@State selectTreeTemp?: Tree = undefined;
@State showSelectLayer: boolean = false;
private static TAG = "Tree"
private treeScroll1: Scroller = new Scroller();
private treeScroll2: Scroller = new Scroller();
private articleScroller: Scroller = new Scroller();
private refreshConfig = new PullToRefreshConfigurator();
private nextPage: number = 1;
private hasMore: boolean = true;
aboutToAppear() {
this.refreshConfig.setHasRefresh(false);
this.loadTreeData();
}
build() {
Column() {
TitleLayout({
title: this.title,
isJustShowStatusBar: true
})
PageLoading({
loadState: this.loadStateTree,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, TreeTab.TAG, "onReloadTree");
this.loadTreeData();
}
}) {
Column() {
if (this.selectTrees.first && this.selectTrees.second) {
Row() {
Text(`${this.selectTrees.first.name} > ${this.selectTrees.second.name}`)
.fontColor($r("app.color.text_h1"))
.fontSize(17)
.layoutWeight(1)
Text(`更换 ${this.showSelectLayer ? "🔼" : "🔽"}`)
.margin({ left: 12 })
.fontColor($r("app.color.main"))
.fontSize(16)
}
.width('100%')
.height(48)
.padding({ left: 16, right: 16 })
.alignItems(VerticalAlign.Center)
.onClick((event) => {
if (this.showSelectLayer) {
this.showSelectLayer = false;
this.selectTreeTemp = this.selectTrees.first;
} else {
this.showSelectLayer = true;
setTimeout(() => {
// 滚动到选中位置的前一个
const selectedIndex1 = this.treeList.findIndex(item => item.id === this.selectTrees.first!.id);
if (selectedIndex1 >= 0) {
this.treeScroll1.scrollToIndex(Math.max(selectedIndex1 - 1, 0));
}
const selectedIndex2 =
this.selectTrees.first!.children.findIndex(item => item.id === this.selectTrees.second!.id);
if (selectedIndex2 >= 0) {
this.treeScroll2.scrollToIndex(Math.max(selectedIndex2 - 1, 0));
}
}, 16)
}
})
}
Stack() {
PageLoading({
loadState: this.loadStateArticle,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, TreeTab.TAG, "onReloadArticle");
this.loadArticleData();
}
}) {
Column() {
PullToRefresh({
data: $data,
scroller: this.articleScroller,
refreshConfigurator: this.refreshConfig,
customList: () => {
this.listViewBuilder();
},
onLoadMore: () => {
return new Promise<string>((resolve, reject) => {
if (this.hasMore) {
this.loadArticleDataByPage(this.nextPage).then(
(data) => {
if (data.length > 0) {
this.nextPage++
this.data = this.data.concat(data);
resolve('加载成功');
} else {
this.hasMore = false;
resolve('没有更多了');
}
},
() => {
resolve('加载失败');
}
)
} else {
resolve('没有更多了');
}
});
},
customLoad: null,
customRefresh: null,
})
}
.width('100%')
.height('100%')
}
if (this.showSelectLayer) {
Column() {
Row() {
List({ scroller: this.treeScroll1 }) {
ForEach(this.treeList, (tree: Tree, index: number) => {
ListItem() {
Text(tree.name)
.width('100%')
.padding({
left: 12,
top: 8,
right: 12,
bottom: 8
})
.fontColor((this.selectTreeTemp!.id === tree.id) ? $r("app.color.main") :
$r("app.color.text_h1"))
.fontSize(14)
.textAlign(TextAlign.Center)
.backgroundColor((index % 2 === 0) ? Color.Transparent : $r("app.color.hot_key_bg"))
.onClick((event) => {
this.selectTreeTemp = tree;
})
}
})
}
.width('50%')
.height('100%')
.onClick((event) => {
})
Line()
.width(0.5)
.height('100%')
.backgroundColor($r("app.color.divider"))
List({ scroller: this.treeScroll2 }) {
ForEach(this.selectTreeTemp!.children, (tree: Tree, index: number) => {
ListItem() {
Text(tree.name)
.width('100%')
.padding({
left: 12,
top: 8,
right: 12,
bottom: 8
})
.fontColor((this.selectTrees.second!.id === tree.id) ? $r("app.color.main") :
$r("app.color.text_h1"))
.fontSize(14)
.textAlign(TextAlign.Center)
.backgroundColor((index % 2 === 1) ? Color.Transparent : $r("app.color.hot_key_bg"))
.onClick((event) => {
this.selectTrees = new Pair(this.selectTreeTemp, tree);
Preferences.get(getContext())
.putSelectedTreeId(this.selectTrees.first!.id, this.selectTrees.second!.id)
this.showSelectLayer = false;
this.hasMore = true;
this.loadArticleData();
})
}
})
}
.width('50%')
.height('100%')
.onClick((event) => {
})
}
.width('100%')
.height('70%')
.backgroundColor($r("app.color.start_window_background"))
}
.width('100%')
.height('100%')
.backgroundColor($r("app.color.translucent_black_50"))
.onClick((event) => {
this.showSelectLayer = false;
this.selectTreeTemp = this.selectTrees.first;
})
}
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
.width('100%')
.height('100%')
}
@Builder
private listViewBuilder() {
List({ scroller: this.articleScroller }) {
ForEach(this.data, (item: Article) => {
ListItem() {
ArticleItemComponent({
article: item,
clearTop: true,
onCollectClick: (article: Article) => {
CollectUtils.collect(article)
.then((success) => {
if (success) {
this.data = this.data.map(item => item);
}
})
}
})
}
})
}
.width('100%')
.height('100%')
.listDirection(Axis.Vertical)
.divider({
strokeWidth: 0.5,
color: $r("app.color.divider"),
startMargin: 16,
endMargin: 16
})
.edgeEffect(EdgeEffect.None) // 必须设置列表为滑动到边缘无效果
}
private async loadTreeData() {
this.loadStateTree = LoadState.LOADING
const res = await Api.get().getTree();
if (res.isSuccessWithData()) {
if (res.getDataOrThrow().length > 0) {
this.treeList = res.getDataOrThrow();
const selectedIds = Preferences.get(getContext()).getSelectedTreeId();
const selectedTree1 = this.treeList.find((item) => item.id === selectedIds.first);
const selectedTree2 = selectedTree1?.children?.find((item) => item.id === selectedIds.second);
if (selectedTree1 !== undefined && selectedTree2 !== undefined) {
this.selectTreeTemp = selectedTree1;
this.selectTrees = new Pair(selectedTree1, selectedTree2);
} else {
this.selectTreeTemp = this.treeList[0];
this.selectTrees = new Pair(this.treeList[0], this.treeList[0].children[0]);
}
this.loadStateTree = LoadState.SUCCESS;
this.loadArticleData();
} else {
this.loadStateTree = LoadState.EMPTY;
}
} else {
this.loadStateTree = LoadState.FAIL;
}
}
private loadArticleData() {
this.loadStateArticle = LoadState.LOADING;
this.nextPage = 1;
this.loadArticleDataByPage(0).then(
(data) => {
this.data = data;
if (this.data.length === 0) {
this.loadStateArticle = LoadState.EMPTY;
} else {
this.loadStateArticle = LoadState.SUCCESS;
}
},
() => {
this.loadStateArticle = LoadState.FAIL;
})
}
private async loadArticleDataByPage(page: number): Promise<Article[]> {
const res = await Api.get().getTreeArticleList(this.selectTrees.second!.id, page);
if (res.isSuccessWithData()) {
const list = res.getDataOrThrow().datas;
return Promise.resolve(list);
} else {
return Promise.reject();
}
}
}
================================================
FILE: entry/src/main/ets/pages/WebPage.ets
================================================
import web_webview from '@ohos.web.webview';
import { TitleLayout } from '../widgets/TitleLayout';
import { HRouter } from '../router/HRouter';
import { RouteParams } from '../router/RouteInfo';
@Component
export struct WebPage {
private webController: web_webview.WebviewController = new web_webview.WebviewController()
url: string = ''
@State title: string = "加载中…"
@State progress: number = 0
build() {
NavDestination() {
Column() {
TitleLayout({
title: this.title,
onBack: () => {
if (this.webController.accessBackward()) {
this.webController.backward()
} else {
HRouter.with().back();
}
}
})
Stack({ alignContent: Alignment.Top }) {
Web({
src: this.url,
controller: this.webController
})
.width('100%')
.height('100%')
.onlineImageAccess(true)
.javaScriptAccess(true)
.domStorageAccess(true)
.databaseAccess(true)
.mixedMode(MixedMode.All)
.onTitleReceive((event) => {
this.title = event?.title ?? ""
})
.onProgressChange((event) => {
this.progress = event?.newProgress ?? 0
})
if (this.progress !== 100) {
Progress({ value: this.progress, total: 100, type: ProgressType.Linear })
.width('100%')
}
}
.width('100%')
.layoutWeight(1)
}
.width('100%')
.height('100%')
}
.hideTitleBar(true)
.onBackPressed(() => {
if (this.webController.accessBackward()) {
this.webController.backward()
return true;
}
return false;
})
}
}
@Builder
export function webPageNavDesBuilder(params: RouteParams) {
WebPage({
url: params.get('url') as string
})
}
================================================
FILE: entry/src/main/ets/pages/Wechat.ets
================================================
import hilog from '@ohos.hilog';
import Api from '../net/Api';
import { WeChatAuthor } from '../net/model/WeChat';
import { LoadState, PageLoading } from '../widgets/PageLoading';
import { TitleLayout } from '../widgets/TitleLayout';
import { WechatTab } from './WechatTab';
@Component
export struct Wechat {
@State title: string = "公众号";
@State loadState: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
@State authors: WeChatAuthor[] = []
private static TAG = "Square"
aboutToAppear() {
this.loadData();
}
build() {
Column() {
TitleLayout({
title: this.title,
showBack: false,
})
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, Wechat.TAG, "onReload");
this.loadData();
}
}) {
if (this.authors.length > 0) {
Tabs({
barPosition: BarPosition.Start
}) {
ForEach(this.authors, (author: WeChatAuthor) => {
TabContent() {
WechatTab({
authorId: author.id
})
}
.tabBar(author.name)
})
}
.width('100%')
.height('100%')
.scrollable(true)
.barMode(BarMode.Scrollable)
.barHeight(44)
}
}
}
.width('100%')
.height('100%')
}
private loadData() {
this.loadState = LoadState.LOADING
Api.get().getWeChatAuthorList()
.then((res) => {
if (res.isSuccessWithData()) {
this.authors = res.getDataOrThrow();
if (this.authors.length === 0) {
this.loadState = LoadState.EMPTY;
} else {
this.loadState = LoadState.SUCCESS;
}
} else {
this.loadState = LoadState.FAIL;
}
})
}
}
================================================
FILE: entry/src/main/ets/pages/WechatTab.ets
================================================
import hilog from '@ohos.hilog';
import { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';
import CollectUtils from '../common/CollectUtils';
import Api from '../net/Api';
import { Article } from '../net/model/Article';
import { ArticleItemComponent } from '../widgets/ArticleItemComponent';
import { LoadState, PageLoading } from '../widgets/PageLoading';
@Component
export struct WechatTab {
authorId: number = 0;
@State loadState: LoadState = LoadState.LOADING;
@State showLoading: boolean = false;
@State data: Article[] = [];
private static TAG = "WechatTab"
private scroller: Scroller = new Scroller();
private refreshConfig = new PullToRefreshConfigurator();
private nextPage: number = 1;
private hasMore: boolean = true;
aboutToAppear() {
this.refreshConfig.setHasRefresh(false);
this.loadData();
}
build() {
Column() {
PageLoading({
loadState: this.loadState,
showLoading: this.showLoading,
onReload: () => {
hilog.debug(0, WechatTab.TAG, "onReload");
this.loadData();
}
}) {
Column() {
PullToRefresh({
data: $data,
scroller: this.scroller,
refreshConfigurator: this.refreshConfig,
customList: () => {
this.listViewBuilder();
},
onLoadMore: () => {
return new Promise<string>((resolve, reject) => {
if (this.hasMore) {
this.loadDataByPage(this.nextPage).then(
(data) => {
if (data.length > 0) {
this.nextPage++
this.data = this.data.concat(data);
resolve('加载成功');
} else {
this.hasMore = false;
resolve('没有更多了');
}
},
() => {
resolve('加载失败');
}
)
} else {
resolve('没有更多了');
}
});
},
customLoad: null,
customRefresh: null,
})
}
.width('100%')
.height('100%')
}
}
.width('100%')
.height('100%')
}
@Builder
private listViewBuilder() {
List({ scroller: this.scroller }) {
ForEach(this.data, (item: Article) => {
ListItem() {
ArticleItemComponent({
article: item,
clearTop: true,
onCollectClick: (article: Article) => {
CollectUtils.collect(article)
.then((success) => {
if (success) {
this.data = this.data.map(item => item);
}
})
}
})
}
})
}
.width('100%')
.height('100%')
.listDirection(Axis.Vertical)
.divider({
strokeWidth: 0.5,
color: $r("app.color.divider"),
startMargin: 16,
endMargin: 16
})
.edgeEffect(EdgeEffect.None) // 必须设置列表为滑动到边缘无效果
}
private loadData() {
if (this.authorId) {
this.loadState = LoadState.LOADING
this.loadDataByPage(0).then(
(data) => {
this.data = data;
if (this.data.length === 0) {
this.loadState = LoadState.EMPTY;
} else {
this.loadState = LoadState.SUCCESS;
}
},
() => {
this.loadState = LoadState.FAIL;
})
} else {
this.loadState = LoadState.FAIL;
}
}
private async loadDataByPage(page: number): Promise<Article[]> {
const res = await Api.get().getWeChatArticleList(this.authorId, page);
if (res.isSuccessWithData()) {
const list = res.getDataOrThrow().datas;
return Promise.resolve(list);
} else {
return Promise.reject();
}
}
}
================================================
FILE: entry/src/main/ets/router/HRouter.ets
================================================
import { RouteRequest } from './RouteRequest'
import { RouteParams } from './RouteInfo'
class _HRouter {
readonly pathStack: NavPathStack = new NavPathStack()
private readonly navDesBuilderMap: Map<string, WrappedBuilder<[RouteParams]>> = new Map()
register(url: string, builder: WrappedBuilder<[RouteParams]>) {
this.navDesBuilderMap.set(url, builder)
}
getNavDesBuilder(url: string): WrappedBuilder<[RouteParams]> | undefined {
return this.navDesBuilderMap.get(url)
}
with(info?: NavDestinationInfo): RouteRequest {
return new RouteRequest(info)
}
clearStack() {
this.pathStack.clear(false)
}
}
export const HRouter: _HRouter = new _HRouter()
================================================
FILE: entry/src/main/ets/router/RouteExecutor.ets
================================================
import { HRouter } from './HRouter'
import { RouteInfo, RouteMode, RouteParams } from './RouteInfo'
class _RouteExecutor {
start(info: RouteInfo) {
let builder = HRouter.getNavDesBuilder(info.targetUrl)
if (!builder) {
return
}
switch (info.mode) {
case RouteMode.ClearTop:
this.startWithClearTop(info)
break;
case RouteMode.MoveToTop:
this.startWithMoveToTop(info)
break;
case RouteMode.Standard:
default:
this.startWithStandardMode(info)
break;
}
}
back(info: RouteInfo) {
HRouter.pathStack.pop(info.targetParams, info.animated)
}
private startWithStandardMode(info: RouteInfo) {
if (info.onPop) {
let onPopListener = info.onPop
HRouter.pathStack.pushPathByName(info.targetUrl, info.targetParams, (popInfo) => {
onPopListener(popInfo.result as RouteParams)
}, info.animated)
} else {
HRouter.pathStack.pushPathByName(info.targetUrl, info.targetParams, info.animated)
}
}
private startWithClearTop(info: RouteInfo) {
let indices = HRouter.pathStack.getIndexByName(info.targetUrl)
if (indices.length) {
let lastIndex = indices[indices.length - 1]
while (lastIndex <= HRouter.pathStack.size() - 1) {
HRouter.pathStack.pop(false)
}
setTimeout(() => {
this.startWithStandardMode(info)
}, 16)
} else {
this.startWithStandardMode(info)
}
}
private startWithMoveToTop(info: RouteInfo) {
let indices = HRouter.pathStack.getIndexByName(info.targetUrl)
if (indices.length) {
HRouter.pathStack.moveIndexToTop(indices[indices.length - 1], info.animated)
} else {
this.startWithStandardMode(info)
}
}
}
export const RouteExecutor: _RouteExecutor = new _RouteExecutor();
================================================
FILE: entry/src/main/ets/router/RouteInfo.ets
================================================
export class RouteInfo {
targetUrl: string = ''
currentParams: RouteParams = new Map()
targetParams: RouteParams = new Map()
mode: RouteMode = RouteMode.Standard
animated: boolean = true
onPop?: (params: RouteParams) => void
}
export type RouteParams = Map<string, Object>
export enum RouteMode {
Standard = 'Standard',
MoveToTop = 'MoveToTop',
ClearTop = 'ClearTop',
}
================================================
FILE: entry/src/main/ets/router/RouteRequest.ets
================================================
import { RouteExecutor } from './RouteExecutor'
import { RouteInfo, RouteMode, RouteParams } from './RouteInfo'
export class RouteRequest {
private readonly routeInfo: RouteInfo = new RouteInfo()
constructor(navDesInfo?: NavDestinationInfo) {
if (navDesInfo) {
this.routeInfo.currentParams = (navDesInfo.param ?? new Map()) as RouteParams
}
}
getRouteInfo(): RouteInfo {
return this.routeInfo
}
getCurrentParams(): RouteParams {
return this.routeInfo.currentParams
}
url(url: string): RouteRequest {
this.routeInfo.targetUrl = url
return this
}
params(key: string, value: Object): RouteRequest {
this.routeInfo.targetParams.set(key, value)
return this
}
mode(value: RouteMode): RouteRequest {
this.routeInfo.mode = value
return this
}
animated(value: boolean): RouteRequest {
this.routeInfo.animated = value
return this
}
start(onPop?: (params: RouteParams) => void) {
this.routeInfo.onPop = onPop
RouteExecutor.start(this.routeInfo)
}
back() {
RouteExecutor.back(this.routeInfo)
}
}
================================================
FILE: entry/src/main/ets/service/UserService.ets
================================================
import promptAction from '@ohos.promptAction';
import EntryContext from '../common/EntryContext';
import Api from '../net/Api';
import Preferences from '../common/Preferences';
import { HRouter } from '../router/HRouter';
import { Routes } from '../Routes';
export default class UserService {
private static instance: UserService
private static TAG = "UserService"
private user?: User
private userObservers: ((user?: User) => void)[] = []
static get(): UserService {
if (UserService.instance === undefined) {
UserService.instance = new UserService()
}
return UserService.instance
}
private constructor() {
const context = EntryContext.getContext();
const user = Preferences.get(context).getUser()
if (user) {
this.user = user;
this.notifyObserver();
this.updateUser().catch();
}
}
isLogin(): boolean {
if (this.user) {
return true;
}
return false;
}
checkLogin(onLogin?: () => void) {
if (this.isLogin()) {
if (onLogin) {
onLogin()
}
} else {
promptAction.showDialog({
title: "提示",
message: "当前操作需要登录",
buttons: [
{
text: "立即登录",
color: $r("app.color.main")
},
{
text: "取消",
color: $r("app.color.text_h2")
}
]
}).then((resp) => {
if (resp.index === 0) {
HRouter.with()
.url(Routes.Login)
.start((params) => {
if (params.get('success') && onLogin) {
onLogin()
}
})
}
})
}
}
getUser(): User | undefined {
return this.user;
}
setUser(user?: User) {
this.user = user;
this.notifyObserver();
const context = EntryContext.getContext();
Preferences.get(context).putUser(user);
}
async updateUser(): Promise<User> {
if (this.isLogin()) {
const res = await Api.get().getUserInfo()
if (res.isSuccessWithData()) {
const user = this.user!!;
user.coinCount = res.getDataOrThrow().coinCount;
user.level = res.getDataOrThrow().level;
user.rank = res.getDataOrThrow().rank;
this.setUser(user);
return Promise.resolve(user);
} else {
return Promise.reject(res.errorMsg);
}
} else {
return Promise.reject()
}
}
addUserObserver(observer: (user?: User) => void) {
if (!this.userObservers.includes(observer)) {
this.userObservers.push(observer);
}
}
removeUserObserver(observer: (user?: User) => void) {
const index = this.userObservers.indexOf(observer);
if (index >= 0) {
this.userObservers.splice(index, 1);
}
}
private notifyObserver() {
this.userObservers.forEach((observer) => {
if (observer) {
observer(this.user);
}
});
}
clearUser() {
this.setUser(undefined);
Api.get().clearCookie();
}
}
export class User {
id: number = 0
username: string = ""
nickname: string = ""
chapterTops: object[] = []
coinCount: number = 0
collectIds: number[] = []
email: string = ""
icon: string = ""
level: string = ""
rank: string = ""
}
================================================
FILE: entry/src/main/ets/widgets/ArticleItemComponent.ets
================================================
import { Article, ArticleTag, getArticleAuthor, getArticleChapter, getTagColor } from '../net/model/Article';
import { HRouter } from '../router/HRouter';
import { RouteMode } from '../router/RouteInfo';
import { Routes } from '../Routes';
@Component
export struct ArticleItemComponent {
article: Article = new Article();
clearTop: boolean = false
onCollectClick?: (article: Article) => void;
build() {
Column() {
Row() {
ForEach(this.article.tags, (item: ArticleTag) => {
Text(item.name)
.fontColor(getTagColor(item))
.fontSize(10)
.textAlign(TextAlign.Center)
.borderWidth(0.5)
.border({
width: 0.5,
color: getTagColor(item),
radius: 3
})
.padding({
left: 2,
top: 1,
right: 2,
bottom: 1
})
Divider()
.width(8)
.height(0)
.color(Color.Transparent)
})
Text(getArticleAuthor(this.article))
.layoutWeight(1)
.fontColor($r("app.color.text_h1"))
.fontSize(12)
Divider()
.width(8)
.height(0)
.color(Color.Transparent)
Text(this.article.niceDate)
.fontColor($r("app.color.text_h2"))
.fontSize(12)
}
Divider()
.width('100%')
.height(4)
.color(Color.Transparent)
Text(this.article.title)
.width('100%')
.fontColor($r("app.color.text_h1"))
.fontSize(15)
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Divider()
.width('100%')
.height(5)
.color(Color.Transparent)
Row() {
Text(getArticleChapter(this.article))
.fontColor($r("app.color.text_h2"))
.fontSize(12)
Blank()
Image(this.article.collect ? $r("app.media.ic_like_fill") : $r("app.media.ic_like"))
.fillColor(this.article.collect ? $r("app.color.red") : $r("app.color.text_h2"))
.width(24)
.height(24)
.onClick((event) => {
if (this.onCollectClick !== undefined) {
this.onCollectClick(this.article);
}
})
}
.justifyContent(FlexAlign.Center)
.width('100%')
}
.width('100%')
.padding({
left: 16,
top: 10,
right: 16,
bottom: 10
})
.onClick((e) => {
HRouter.with()
.url(Routes.Web)
.params('url', this.article.link)
.mode(this.clearTop ? RouteMode.ClearTop : RouteMode.Standard)
.start()
})
}
}
================================================
FILE: entry/src/main/ets/widgets/PageLoading.ets
================================================
export enum LoadState {
LOADING,
SUCCESS,
FAIL,
EMPTY
}
@Component
export struct PageLoading {
@Prop loadState: LoadState;
onReload?: () => void;
@Prop showLoading: boolean;
@BuilderParam content: () => void;
build() {
Stack() {
if (this.loadState === LoadState.LOADING) {
LoadingProgress()
.width(50)
.height(50)
.color($r("app.color.main"))
} else if (this.loadState === LoadState.SUCCESS) {
this.content();
if (this.showLoading) {
Stack() {
Stack() {
LoadingProgress()
.width(50)
.height(50)
.color($r("app.color.white"))
}
.width(100)
.height(100)
.backgroundColor($r("app.color.translucent_black_50"))
.borderRadius(8)
}
.width('100%')
.height('100%')
}
} else if (this.loadState === LoadState.FAIL) {
Stack() {
Text("加载失败,点击重试")
}
.width('100%')
.height('100%')
.onClick(() => {
if (this.onReload) {
this.onReload();
}
})
} else {
Stack() {
Text("这里什么都没有")
}
.width('100%')
.height('100%')
.onClick(() => {
if (this.onReload) {
this.onReload();
}
})
}
}
.width('100%')
.height('100%')
}
}
================================================
FILE: entry/src/main/ets/widgets/TitleLayout.ets
================================================
import WindowUtils from '../common/WindowUtils';
import { HRouter } from '../router/HRouter';
@Component
export struct TitleLayout {
@Prop
title: string;
isJustShowStatusBar: boolean = false;
showBack: boolean = true;
onBack: () => void = () => {
HRouter.with().back();
}
menuIcon?: Resource;
onMenuClick?: () => void;
build() {
Column() {
Row()
.width('100%')
.height(WindowUtils.statusBarHeight + 'px')
if (this.isJustShowStatusBar === false) {
Row() {
if (this.showBack) {
Image($r("app.media.ic_back"))
.width(48)
.height(48)
.padding(14)
.fillColor($r("app.color.text_h1"))
.objectFit(ImageFit.Contain)
.onClick((event) => {
if (this.onBack !== undefined) {
this.onBack();
}
})
}
Text(this.title)
.layoutWeight(1)
.fontSize(17)
.fontColor($r("app.color.text_h1"))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.padding({ left: 16, right: 16 })
if (this.menuIcon !== undefined) {
Image(this.menuIcon)
.width(48)
.height(48)
.padding(14)
.fillColor($r("app.color.text_h1"))
.objectFit(ImageFit.Contain)
.onClick((event) => {
if (this.onMenuClick !== undefined) {
this.onMenuClick();
}
})
}
}
.width('100%')
.height(48)
.alignItems(VerticalAlign.Center)
}
}
.width('100%')
.backgroundColor($r("app.color.title_bar_bg"))
}
}
================================================
FILE: entry/src/main/module.json5
================================================
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"phone",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"reason": "$string:internet_permission_reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
}
],
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
]
}
}
================================================
FILE: entry/src/main/resources/base/element/color.json
================================================
{
"color": [
{
"name": "start_window_background",
"value": "#FAFAFA"
},
{
"name": "white",
"value": "#FFFFFF"
},
{
"name": "translucent_black_40",
"value": "#66000000"
},
{
"name": "translucent_black_50",
"value": "#80000000"
},
{
"name": "main",
"value": "#4CAF50"
},
{
"name": "text_h1",
"value": "#212121"
},
{
"name": "text_h2",
"value": "#757575"
},
{
"name": "divider",
"value": "#EEEEEE"
},
{
"name": "navi_tab_unselect",
"value": "#424242"
},
{
"name": "navi_bar_bg",
"value": "#FFFFFF"
},
{
"name": "title_bar_bg",
"value": "#FAFAFA"
},
{
"name": "red",
"value": "#F44336"
},
{
"name": "blue",
"value": "#2196F3"
},
{
"name": "green",
"value": "#4CAF50"
},
{
"name": "cyan",
"value": "#00BCD4"
},
{
"name": "teal",
"value": "#009688"
},
{
"name": "hot_key_bg",
"value": "#DDDDDD"
},
{
"name": "rank_gold",
"value": "#FFD700"
},
{
"name": "rank_silver",
"value": "#C0C0C0"
},
{
"name": "rank_bronze",
"value": "#CD7F32"
},
{
"name": "gray600",
"value": "#999999"
}
]
}
================================================
FILE: entry/src/main/resources/base/element/string.json
================================================
{
"string": [
{
"name": "module_desc",
"value": "module description"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "WanHarmony"
},
{
"name": "internet_permission_reason",
"value": "获取网络数据"
}
]
}
================================================
FILE: entry/src/main/resources/base/profile/main_pages.json
================================================
{
"src": [
"pages/Index"
]
}
================================================
FILE: entry/src/main/resources/en_US/element/string.json
================================================
{
"string": [
{
"name": "module_desc",
"value": "module description"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "WanHarmony"
}
]
}
================================================
FILE: entry/src/main/resources/zh_CN/element/string.json
================================================
{
"string": [
{
"name": "module_desc",
"value": "模块描述"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "玩Harmony"
}
]
}
================================================
FILE: entry/src/ohosTest/ets/test/Ability.test.ets
================================================
import hilog from '@ohos.hilog';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
export default function abilityTest() {
describe('ActsAbilityTest', function () {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(function () {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach(function () {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach(function () {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll(function () {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('assertContain',0, function () {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
const a = 'abc'
const b = 'b'
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b)
expect(a).assertEqual(a)
})
})
}
================================================
FILE: entry/src/ohosTest/ets/test/List.test.ets
================================================
import abilityTest from './Ability.test'
export default function testsuite() {
abilityTest()
}
================================================
FILE: entry/src/ohosTest/ets/testability/TestAbility.ets
================================================
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
import hilog from '@ohos.hilog';
import { Hypium } from '@ohos/hypium';
import testsuite from '../test/List.test';
import window from '@ohos.window';
export default class TestAbility extends UIAbility {
onCreate(want, launchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate');
hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');
hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:'+ JSON.stringify(launchParam) ?? '');
var abilityDelegator: any
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator()
var abilityDelegatorArguments: any
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments()
hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!');
Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite)
}
onDestroy() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage) {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageCreate');
windowStage.loadContent('testability/pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s',
JSON.stringify(data) ?? '');
});
}
onWindowStageDestroy() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageDestroy');
}
onForeground() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onForeground');
}
onBackground() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onBackground');
}
}
================================================
FILE: entry/src/ohosTest/ets/testability/pages/Index.ets
================================================
import hilog from '@ohos.hilog';
@Entry
@Component
struct Index {
aboutToAppear() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility index aboutToAppear');
}
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('next page')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('35%')
.height('5%')
.onClick(()=>{
})
}
.width('100%')
}
.height('100%')
}
}
================================================
FILE: entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts
================================================
import hilog from '@ohos.hilog';
import TestRunner from '@ohos.application.testRunner';
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
var abilityDelegator = undefined
var abilityDelegatorArguments = undefined
async function onAbilityCreateCallback() {
hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback');
}
async function addAbilityMonitorCallback(err: any) {
hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? '');
}
export default class OpenHarmonyTestRunner implements TestRunner {
constructor() {
}
onPrepare() {
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare ');
}
async onRun() {
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run');
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments()
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator()
var testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility'
const lMonitor = {
abilityName: testAbilityName,
onAbilityCreate: onAbilityCreateCallback,
};
abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback)
var cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName
var debug = abilityDelegatorArguments.parameters['-D']
if (debug == 'true')
{
cmd += ' -D'
}
hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd);
abilityDelegator.executeShellCommand(cmd,
(err: any, d: any) => {
hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? '');
hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? '');
hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? '');
})
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end');
}
}
================================================
FILE: entry/src/ohosTest/module.json5
================================================
{
"module": {
"name": "entry_test",
"type": "feature",
"description": "$string:module_test_desc",
"mainElement": "TestAbility",
"deviceTypes": [
"phone",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:test_pages",
"abilities": [
{
"name": "TestAbility",
"srcEntry": "./ets/testability/TestAbility.ets",
"description": "$string:TestAbility_desc",
"icon": "$media:icon",
"label": "$string:TestAbility_label",
"exported": true,
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"skills": [
{
"actions": [
"action.system.home"
],
"entities": [
"entity.system.home"
]
}
]
}
]
}
}
================================================
FILE: entry/src/ohosTest/resources/base/element/color.json
================================================
{
"color": [
{
"name": "start_window_background",
"value": "#FFFFFF"
}
]
}
================================================
FILE: entry/src/ohosTest/resources/base/element/string.json
================================================
{
"string": [
{
"name": "module_test_desc",
"value": "test ability description"
},
{
"name": "TestAbility_desc",
"value": "the test ability"
},
{
"name": "TestAbility_label",
"value": "test label"
}
]
}
================================================
FILE: entry/src/ohosTest/resources/base/profile/test_pages.json
================================================
{
"src": [
"testability/pages/Index"
]
}
================================================
FILE: hvigor/hvigor-config.json5
================================================
{
"modelVersion": "5.0.2",
"dependencies": {
},
"execution": {
// "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */
// "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */
// "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */
// "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */
// "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */
},
"logging": {
// "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */
},
"debugging": {
// "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */
},
"nodeOptions": {
// "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/
// "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/
}
}
================================================
FILE: hvigorfile.ts
================================================
import { appTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
================================================
FILE: oh-package.json5
================================================
{
"modelVersion": "5.0.2",
"license": "",
"devDependencies": {
"@ohos/hypium": "1.0.21",
"@ohos/hamock": "1.0.0"
},
"author": "wangchenyan.top",
"name": "myapplication",
"description": "Please describe the basic information.",
"main": "",
"version": "1.0.0",
"dependencies": {
},
"dynamicDependencies": {}
}
gitextract_eaol0spx/ ├── .gitignore ├── AppScope/ │ ├── app.json5 │ └── resources/ │ └── base/ │ └── element/ │ └── string.json ├── LICENSE ├── README.md ├── build-profile.json5 ├── code-linter.json5 ├── entry/ │ ├── .gitignore │ ├── build-profile.json5 │ ├── hvigorfile.ts │ ├── obfuscation-rules.txt │ ├── oh-package.json5 │ └── src/ │ ├── main/ │ │ ├── ets/ │ │ │ ├── Routes.ets │ │ │ ├── common/ │ │ │ │ ├── CollectUtils.ets │ │ │ │ ├── EntryContext.ets │ │ │ │ ├── OHPermission.ets │ │ │ │ ├── Pair.ets │ │ │ │ ├── Preferences.ets │ │ │ │ ├── Toast.ets │ │ │ │ └── WindowUtils.ets │ │ │ ├── entryability/ │ │ │ │ └── EntryAbility.ets │ │ │ ├── net/ │ │ │ │ ├── Api.ets │ │ │ │ ├── Headers.ets │ │ │ │ ├── HttpClient.ets │ │ │ │ ├── Response.ets │ │ │ │ ├── cookie/ │ │ │ │ │ ├── Cookie.ets │ │ │ │ │ ├── CookieJar.ets │ │ │ │ │ ├── CookiePersistor.ets │ │ │ │ │ ├── CookieUtils.ets │ │ │ │ │ ├── KVCookiePersistor.ets │ │ │ │ │ └── PersistentCookieJar.ets │ │ │ │ └── model/ │ │ │ │ ├── Article.ets │ │ │ │ ├── Harmony.ets │ │ │ │ ├── RankingList.ets │ │ │ │ ├── Search.ets │ │ │ │ ├── Tree.ets │ │ │ │ └── WeChat.ets │ │ │ ├── pages/ │ │ │ │ ├── CollectList.ets │ │ │ │ ├── Harmony.ets │ │ │ │ ├── Home.ets │ │ │ │ ├── Index.ets │ │ │ │ ├── Login.ets │ │ │ │ ├── Mine.ets │ │ │ │ ├── RankingList.ets │ │ │ │ ├── SearchEntry.ets │ │ │ │ ├── SearchResult.ets │ │ │ │ ├── Square.ets │ │ │ │ ├── TreeTab.ets │ │ │ │ ├── WebPage.ets │ │ │ │ ├── Wechat.ets │ │ │ │ └── WechatTab.ets │ │ │ ├── router/ │ │ │ │ ├── HRouter.ets │ │ │ │ ├── RouteExecutor.ets │ │ │ │ ├── RouteInfo.ets │ │ │ │ └── RouteRequest.ets │ │ │ ├── service/ │ │ │ │ └── UserService.ets │ │ │ └── widgets/ │ │ │ ├── ArticleItemComponent.ets │ │ │ ├── PageLoading.ets │ │ │ └── TitleLayout.ets │ │ ├── module.json5 │ │ └── resources/ │ │ ├── base/ │ │ │ ├── element/ │ │ │ │ ├── color.json │ │ │ │ └── string.json │ │ │ └── profile/ │ │ │ └── main_pages.json │ │ ├── en_US/ │ │ │ └── element/ │ │ │ └── string.json │ │ └── zh_CN/ │ │ └── element/ │ │ └── string.json │ └── ohosTest/ │ ├── ets/ │ │ ├── test/ │ │ │ ├── Ability.test.ets │ │ │ └── List.test.ets │ │ ├── testability/ │ │ │ ├── TestAbility.ets │ │ │ └── pages/ │ │ │ └── Index.ets │ │ └── testrunner/ │ │ └── OpenHarmonyTestRunner.ts │ ├── module.json5 │ └── resources/ │ └── base/ │ ├── element/ │ │ ├── color.json │ │ └── string.json │ └── profile/ │ └── test_pages.json ├── hvigor/ │ └── hvigor-config.json5 ├── hvigorfile.ts └── oh-package.json5
SYMBOL INDEX (6 symbols across 1 files)
FILE: entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts
function onAbilityCreateCallback (line 8) | async function onAbilityCreateCallback() {
function addAbilityMonitorCallback (line 12) | async function addAbilityMonitorCallback(err: any) {
class OpenHarmonyTestRunner (line 16) | class OpenHarmonyTestRunner implements TestRunner {
method constructor (line 17) | constructor() {
method onPrepare (line 20) | onPrepare() {
method onRun (line 24) | async onRun() {
Condensed preview — 77 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (155K chars).
[
{
"path": ".gitignore",
"chars": 177,
"preview": "/node_modules\n/oh_modules\n/local.properties\n/.idea\n**/build\n/.hvigor\n.cxx\n/.clangd\n/.clang-format\n/.clang-tidy\n**/.test\n"
},
{
"path": "AppScope/app.json5",
"chars": 214,
"preview": "{\n \"app\": {\n \"bundleName\": \"top.wangchenyan.wanharmony\",\n \"vendor\": \"wanharmony\",\n \"versionCode\": 1000000,\n "
},
{
"path": "AppScope/resources/base/element/string.json",
"chars": 88,
"preview": "{\n \"string\": [\n {\n \"name\": \"app_name\",\n \"value\": \"WanHarmony\"\n }\n ]\n}\n"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 396,
"preview": "# wan-harmony\n\n鸿蒙版玩 Android 客户端\n\n[鸿蒙即将抛弃Android,你还不来学习一下?](https://juejin.cn/post/7340307629891616808)\n\n**当前适配版本为 Harmon"
},
{
"path": "build-profile.json5",
"chars": 716,
"preview": "{\n \"app\": {\n \"signingConfigs\": [],\n \"products\": [\n {\n \"name\": \"default\",\n \"signingConfig\": \"de"
},
{
"path": "code-linter.json5",
"chars": 854,
"preview": "{\n \"files\": [\n \"**/*.ets\"\n ],\n \"ignore\": [\n \"**/src/ohosTest/**/*\",\n \"**/src/test/**/*\",\n \"**/src/mock/**"
},
{
"path": "entry/.gitignore",
"chars": 55,
"preview": "/node_modules\n/oh_modules\n/.preview\n/build\n/.cxx\n/.test"
},
{
"path": "entry/build-profile.json5",
"chars": 422,
"preview": "{\n \"apiType\": \"stageMode\",\n \"buildOption\": {\n },\n \"buildOptionSet\": [\n {\n \"name\": \"release\",\n \"arkOptio"
},
{
"path": "entry/hvigorfile.ts",
"chars": 230,
"preview": "import { hapTasks } from '@ohos/hvigor-ohos-plugin';\n\nexport default {\n system: hapTasks, /* Built-in plugin of Hvigor"
},
{
"path": "entry/obfuscation-rules.txt",
"chars": 1008,
"preview": "# Define project specific obfuscation rules here.\n# You can include the obfuscation configuration files in the current m"
},
{
"path": "entry/oh-package.json5",
"chars": 247,
"preview": "{\n \"name\": \"entry\",\n \"version\": \"1.0.0\",\n \"description\": \"Please describe the basic information.\",\n \"main\": \"\",\n \"a"
},
{
"path": "entry/src/main/ets/Routes.ets",
"chars": 1228,
"preview": "import { collectListNavDesBuilder } from './pages/CollectList'\nimport { HarmonyNavDesBuilder } from './pages/Harmony'\nim"
},
{
"path": "entry/src/main/ets/common/CollectUtils.ets",
"chars": 906,
"preview": "import Api from '../net/Api';\nimport { Article } from '../net/model/Article';\nimport UserService from '../service/UserSe"
},
{
"path": "entry/src/main/ets/common/EntryContext.ets",
"chars": 301,
"preview": "export default class EntryContext {\n private static context: Context\n\n static setContext(context: Context) {\n Entry"
},
{
"path": "entry/src/main/ets/common/OHPermission.ets",
"chars": 2620,
"preview": "import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';\nimport bundleManager from '@ohos.bundle.bundle"
},
{
"path": "entry/src/main/ets/common/Pair.ets",
"chars": 145,
"preview": "export class Pair<T, U> {\n first: T;\n second: U;\n\n constructor(first: T, second: U) {\n this.first = first;\n thi"
},
{
"path": "entry/src/main/ets/common/Preferences.ets",
"chars": 2127,
"preview": "import dataPreferences from '@ohos.data.preferences';\nimport JSON from '@ohmos/json-bigint';\nimport { User } from '../se"
},
{
"path": "entry/src/main/ets/common/Toast.ets",
"chars": 352,
"preview": "import promptAction from '@ohos.promptAction';\nimport WindowUtils from './WindowUtils';\n\nexport function toast(message: "
},
{
"path": "entry/src/main/ets/common/WindowUtils.ets",
"chars": 793,
"preview": "import window from '@ohos.window'\n\nexport default class WindowUtils {\n static statusBarHeight: number = 0\n static navi"
},
{
"path": "entry/src/main/ets/entryability/EntryAbility.ets",
"chars": 1947,
"preview": "import UIAbility from '@ohos.app.ability.UIAbility';\nimport hilog from '@ohos.hilog';\nimport window from '@ohos.window';"
},
{
"path": "entry/src/main/ets/net/Api.ets",
"chars": 3528,
"preview": "import { Article, ArticleList, HomeBannerData } from './model/Article';\nimport { User } from '../service/UserService';\ni"
},
{
"path": "entry/src/main/ets/net/Headers.ets",
"chars": 67,
"preview": "export class Headers {\n contentType?: string;\n cookie?: string;\n}"
},
{
"path": "entry/src/main/ets/net/HttpClient.ets",
"chars": 3361,
"preview": "import CookieJar from './cookie/CookieJar'\nimport { http } from '@kit.NetworkKit'\nimport { Response } from './Response'\n"
},
{
"path": "entry/src/main/ets/net/Response.ets",
"chars": 312,
"preview": "export class Response<T> {\n errorCode: number = 0\n errorMsg: string = \"\"\n data?: T = undefined\n\n isSuccess(): boolea"
},
{
"path": "entry/src/main/ets/net/cookie/Cookie.ets",
"chars": 210,
"preview": "/**\n * Cookie 对象,参考 OkHttp 中 Cookie 结构\n */\nexport default interface Cookie {\n domain: string;\n path: string;\n expires"
},
{
"path": "entry/src/main/ets/net/cookie/CookieJar.ets",
"chars": 220,
"preview": "import uri from '@ohos.uri';\nimport Cookie from './Cookie';\n\nexport default interface CookieJar {\n saveFromResponse(url"
},
{
"path": "entry/src/main/ets/net/cookie/CookiePersistor.ets",
"chars": 193,
"preview": "import Cookie from './Cookie';\n\nexport default interface CookiePersistor {\n loadAll(): Cookie[];\n\n saveAll(cookies: Co"
},
{
"path": "entry/src/main/ets/net/cookie/CookieUtils.ets",
"chars": 3095,
"preview": "import Cookie from './Cookie';\nimport { uri } from '@kit.ArkTS';\n\nexport default class CookieUtils {\n /**\n * httpRequ"
},
{
"path": "entry/src/main/ets/net/cookie/KVCookiePersistor.ets",
"chars": 2065,
"preview": "import Cookie from './Cookie';\nimport dataPreferences from '@ohos.data.preferences';\nimport CookiePersistor from './Cook"
},
{
"path": "entry/src/main/ets/net/cookie/PersistentCookieJar.ets",
"chars": 1952,
"preview": "import HashMap from '@ohos.util.HashMap';\nimport uri from '@ohos.uri';\nimport Cookie from './Cookie';\nimport CookieJar f"
},
{
"path": "entry/src/main/ets/net/model/Article.ets",
"chars": 2094,
"preview": "export class ArticleList {\n curPage: number = 0\n datas: Article[] = []\n offset: number = 0\n over: boolean = false\n "
},
{
"path": "entry/src/main/ets/net/model/Harmony.ets",
"chars": 1331,
"preview": "import { Article } from \"./Article\";\n\nexport class Links {\n articleList: Article[] = []\n author: string = \"\"\n child"
},
{
"path": "entry/src/main/ets/net/model/RankingList.ets",
"chars": 344,
"preview": "\nexport class RankingList {\n coinCount: number = 0\n level: number = 0\n nickname: string = \"\"\n rank: string = \"\"\n us"
},
{
"path": "entry/src/main/ets/net/model/Search.ets",
"chars": 60,
"preview": "export class HotKey {\n id: number = 0\n name: string = \"\"\n}"
},
{
"path": "entry/src/main/ets/net/model/Tree.ets",
"chars": 413,
"preview": "import { Article } from './Article'\n\nexport class Tree {\n articleList: Article[] = []\n author: string = \"\"\n children:"
},
{
"path": "entry/src/main/ets/net/model/WeChat.ets",
"chars": 66,
"preview": "export class WeChatAuthor {\n id: number = 0\n name: string = \"\"\n}"
},
{
"path": "entry/src/main/ets/pages/CollectList.ets",
"chars": 4582,
"preview": "import { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';\nimport hilog from '@ohos.hilog';\nimport "
},
{
"path": "entry/src/main/ets/pages/Harmony.ets",
"chars": 5506,
"preview": "import hilog from '@ohos.hilog';\nimport Api from '../net/Api';\nimport { LoadState, PageLoading } from '../widgets/PageLo"
},
{
"path": "entry/src/main/ets/pages/Home.ets",
"chars": 6971,
"preview": "import hilog from '@ohos.hilog'\nimport Api from '../net/Api'\nimport { Article, ArticleTag, HomeBannerData, } from '../ne"
},
{
"path": "entry/src/main/ets/pages/Index.ets",
"chars": 3730,
"preview": "import { Home } from './Home'\nimport { Square } from './Square'\nimport { Mine } from './Mine'\nimport { Wechat } from './"
},
{
"path": "entry/src/main/ets/pages/Login.ets",
"chars": 2689,
"preview": "import { toast } from '../common/Toast'\nimport Api from '../net/Api'\nimport { HRouter } from '../router/HRouter'\nimport "
},
{
"path": "entry/src/main/ets/pages/Mine.ets",
"chars": 5755,
"preview": "import promptAction from '@ohos.promptAction'\nimport Api from '../net/Api'\nimport UserService, { User } from '../service"
},
{
"path": "entry/src/main/ets/pages/RankingList.ets",
"chars": 6613,
"preview": "import hilog from '@ohos.hilog';\nimport Api from '../net/Api';\nimport { LoadState, PageLoading } from '../widgets/PageLo"
},
{
"path": "entry/src/main/ets/pages/SearchEntry.ets",
"chars": 5305,
"preview": "import WindowUtils from '../common/WindowUtils'\nimport Api from '../net/Api'\nimport { HotKey } from '../net/model/Search"
},
{
"path": "entry/src/main/ets/pages/SearchResult.ets",
"chars": 4643,
"preview": "import hilog from '@ohos.hilog';\nimport { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';\nimport "
},
{
"path": "entry/src/main/ets/pages/Square.ets",
"chars": 4352,
"preview": "import hilog from '@ohos.hilog';\nimport { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';\nimport "
},
{
"path": "entry/src/main/ets/pages/TreeTab.ets",
"chars": 11359,
"preview": "import { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';\nimport hilog from '@ohos.hilog';\nimport "
},
{
"path": "entry/src/main/ets/pages/WebPage.ets",
"chars": 1933,
"preview": "import web_webview from '@ohos.web.webview';\nimport { TitleLayout } from '../widgets/TitleLayout';\nimport { HRouter } fr"
},
{
"path": "entry/src/main/ets/pages/Wechat.ets",
"chars": 1913,
"preview": "import hilog from '@ohos.hilog';\nimport Api from '../net/Api';\nimport { WeChatAuthor } from '../net/model/WeChat';\nimpor"
},
{
"path": "entry/src/main/ets/pages/WechatTab.ets",
"chars": 3949,
"preview": "import hilog from '@ohos.hilog';\nimport { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh';\nimport "
},
{
"path": "entry/src/main/ets/router/HRouter.ets",
"chars": 687,
"preview": "import { RouteRequest } from './RouteRequest'\nimport { RouteParams } from './RouteInfo'\n\nclass _HRouter {\n readonly pat"
},
{
"path": "entry/src/main/ets/router/RouteExecutor.ets",
"chars": 1825,
"preview": "import { HRouter } from './HRouter'\nimport { RouteInfo, RouteMode, RouteParams } from './RouteInfo'\n\nclass _RouteExecuto"
},
{
"path": "entry/src/main/ets/router/RouteInfo.ets",
"chars": 390,
"preview": "export class RouteInfo {\n targetUrl: string = ''\n currentParams: RouteParams = new Map()\n targetParams: RouteParams ="
},
{
"path": "entry/src/main/ets/router/RouteRequest.ets",
"chars": 1097,
"preview": "import { RouteExecutor } from './RouteExecutor'\nimport { RouteInfo, RouteMode, RouteParams } from './RouteInfo'\n\nexport "
},
{
"path": "entry/src/main/ets/service/UserService.ets",
"chars": 3224,
"preview": "import promptAction from '@ohos.promptAction';\nimport EntryContext from '../common/EntryContext';\nimport Api from '../ne"
},
{
"path": "entry/src/main/ets/widgets/ArticleItemComponent.ets",
"chars": 2699,
"preview": "import { Article, ArticleTag, getArticleAuthor, getArticleChapter, getTagColor } from '../net/model/Article';\nimport { H"
},
{
"path": "entry/src/main/ets/widgets/PageLoading.ets",
"chars": 1479,
"preview": "export enum LoadState {\n LOADING,\n SUCCESS,\n FAIL,\n EMPTY\n}\n\n@Component\nexport struct PageLoading {\n @Prop loadStat"
},
{
"path": "entry/src/main/ets/widgets/TitleLayout.ets",
"chars": 1801,
"preview": "import WindowUtils from '../common/WindowUtils';\nimport { HRouter } from '../router/HRouter';\n\n@Component\nexport struct "
},
{
"path": "entry/src/main/module.json5",
"chars": 1174,
"preview": "{\n \"module\": {\n \"name\": \"entry\",\n \"type\": \"entry\",\n \"description\": \"$string:module_desc\",\n \"mainElement\": \""
},
{
"path": "entry/src/main/resources/base/element/color.json",
"chars": 1400,
"preview": "{\n \"color\": [\n {\n \"name\": \"start_window_background\",\n \"value\": \"#FAFAFA\"\n },\n {\n \"name\": \"white"
},
{
"path": "entry/src/main/resources/base/element/string.json",
"chars": 333,
"preview": "{\n \"string\": [\n {\n \"name\": \"module_desc\",\n \"value\": \"module description\"\n },\n {\n \"name\": \"Entry"
},
{
"path": "entry/src/main/resources/base/profile/main_pages.json",
"chars": 37,
"preview": "{\n \"src\": [\n \"pages/Index\"\n ]\n}\n"
},
{
"path": "entry/src/main/resources/en_US/element/string.json",
"chars": 252,
"preview": "{\n \"string\": [\n {\n \"name\": \"module_desc\",\n \"value\": \"module description\"\n },\n {\n \"name\": \"Entry"
},
{
"path": "entry/src/main/resources/zh_CN/element/string.json",
"chars": 236,
"preview": "{\n \"string\": [\n {\n \"name\": \"module_desc\",\n \"value\": \"模块描述\"\n },\n {\n \"name\": \"EntryAbility_desc\","
},
{
"path": "entry/src/ohosTest/ets/test/Ability.test.ets",
"chars": 1748,
"preview": "import hilog from '@ohos.hilog';\nimport { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos"
},
{
"path": "entry/src/ohosTest/ets/test/List.test.ets",
"chars": 97,
"preview": "import abilityTest from './Ability.test'\n\nexport default function testsuite() {\n abilityTest()\n}"
},
{
"path": "entry/src/ohosTest/ets/testability/TestAbility.ets",
"chars": 2065,
"preview": "import UIAbility from '@ohos.app.ability.UIAbility';\nimport AbilityDelegatorRegistry from '@ohos.app.ability.abilityDele"
},
{
"path": "entry/src/ohosTest/ets/testability/pages/Index.ets",
"chars": 835,
"preview": "import hilog from '@ohos.hilog';\n\n@Entry\n@Component\nstruct Index {\n aboutToAppear() {\n hilog.info(0x0000, 'testTag',"
},
{
"path": "entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts",
"chars": 2121,
"preview": "import hilog from '@ohos.hilog';\nimport TestRunner from '@ohos.application.testRunner';\nimport AbilityDelegatorRegistry "
},
{
"path": "entry/src/ohosTest/module.json5",
"chars": 906,
"preview": "{\n \"module\": {\n \"name\": \"entry_test\",\n \"type\": \"feature\",\n \"description\": \"$string:module_test_desc\",\n \"mai"
},
{
"path": "entry/src/ohosTest/resources/base/element/color.json",
"chars": 98,
"preview": "{\n \"color\": [\n {\n \"name\": \"start_window_background\",\n \"value\": \"#FFFFFF\"\n }\n ]\n}"
},
{
"path": "entry/src/ohosTest/resources/base/element/string.json",
"chars": 266,
"preview": "{\n \"string\": [\n {\n \"name\": \"module_test_desc\",\n \"value\": \"test ability description\"\n },\n {\n \"na"
},
{
"path": "entry/src/ohosTest/resources/base/profile/test_pages.json",
"chars": 49,
"preview": "{\n \"src\": [\n \"testability/pages/Index\"\n ]\n}\n"
},
{
"path": "hvigor/hvigor-config.json5",
"chars": 1301,
"preview": "{\n \"modelVersion\": \"5.0.2\",\n \"dependencies\": {\n },\n \"execution\": {\n // \"analyze\": \"normal\", /"
},
{
"path": "hvigorfile.ts",
"chars": 230,
"preview": "import { appTasks } from '@ohos/hvigor-ohos-plugin';\n\nexport default {\n system: appTasks, /* Built-in plugin of Hvigor"
},
{
"path": "oh-package.json5",
"chars": 339,
"preview": "{\n \"modelVersion\": \"5.0.2\",\n \"license\": \"\",\n \"devDependencies\": {\n \"@ohos/hypium\": \"1.0.21\",\n \"@ohos/hamock\": \""
}
]
About this extraction
This page contains the full source code of the wangchenyan/wan-harmony GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 77 files (138.2 KB), approximately 36.5k tokens, and a symbol index with 6 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.