长按特定元素(例如图片,链接)或鼠标右键,跳出菜单。给Web组件绑定popup弹窗,并设置弹窗内容,交互逻辑和显示状态。
+ + 链接元素 + +diff --git a/AppScope/app.json5 b/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..b5799c22dafd81b7cd35be39fe503e2a1c0bae36 --- /dev/null +++ b/AppScope/app.json5 @@ -0,0 +1,10 @@ +{ + "app": { + "bundleName": "com.example.customizinglongpressmenu", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} \ No newline at end of file diff --git a/AppScope/resources/base/element/string.json b/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..c0d7d73d38e0f72c4aa8eceb43c47c6fc88df197 --- /dev/null +++ b/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "CustomizingLongPressMenu" + } + ] +} \ No newline at end of file diff --git a/AppScope/resources/base/media/app_icon.png b/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..a39445dc87828b76fed6d2ec470dd455c45319e3 Binary files /dev/null and b/AppScope/resources/base/media/app_icon.png differ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..338e5b0bc22082e0ffcc7121c2ed3897a3ddccb0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,78 @@ + Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved. + + 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. + +Apache License, Version 2.0 +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: +1.You must give any other recipients of the Work or Derivative Works a copy of this License; and +2.You must cause any modified files to carry prominent notices stating that You changed the files; and +3.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 +4.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 \ No newline at end of file diff --git a/README.en.md b/README.en.md deleted file mode 100644 index 2ec151b1f6278351d0c9dba4fc6140903a929584..0000000000000000000000000000000000000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# CustomizingLongPressMenu - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md index 16d49036351d0fc4ccee9da8f98c11b54a962621..ad8957a2a5311bc608c7a62d02e880c9b82b5291 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,49 @@ -# CustomizingLongPressMenu +# Web自定义长按菜单 -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} +### 介绍 -#### 软件架构 -软件架构说明 +本示例介绍了给Webview页面中可点击元素(超链接/图片)绑定长按/鼠标右击时的自定义菜单的方案。 +### 效果图预览 -#### 安装教程 + -1. xxxx -2. xxxx -3. xxxx +##### 使用说明 -#### 使用说明 +长按Web页面中的图片或者链接元素,弹出自定义的Menu菜单,创建自定义的操作,如复制图片、使用浏览器打开链接、复制链接等。 -1. xxxx -2. xxxx -3. xxxx +### 工程目录 -#### 参与贡献 +``` +├──entry/src/main/ets/ +│ ├──common +│ │ ├──CommonConstants.ets // 公共常量类 +│ │ └──Utils.ets // 工具函数 +│ ├──entryability +│ │ └──EntryAbility.ets // 程序入口类 +│ └──pages +│ └──Index.ets // 首页 +└──entry/src/main/resources // 应用静态资源目录 +``` -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request +### 具体实现 +1. 创建Web组件,导入示例HTML文件,绑定弹出菜单组件。 -#### 特技 +2. 调用Web组件的onContextMenuShow函数,获取当前页面元素弹窗菜单的信息,如位置信息、当前链接、以及是否存在图片等媒体元素、获取事件来源等。 -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) +3. 创建自定义菜单,在onContextMenuShow事件中能够获取触发菜单元素的信息和事件,根据这些内容动态创建自定义的弹出菜单。 + +### 相关权限 + +不涉及。 + +### 约束与限制 + +1. 本示例仅支持标准系统上运行,支持设备:华为手机。 + +2. HarmonyOS系统:HarmonyOS NEXT Developer Beta1及以上。 + +3. DevEco Studio版本:DevEco Studio NEXT Developer Beta1及以上。 + +4. HarmonyOS SDK版本:HarmonyOS NEXT Developer Beta1 SDK及以上。 \ No newline at end of file diff --git a/build-profile.json5 b/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..c033ce4278fb0641d84107c3c134047ac487368e --- /dev/null +++ b/build-profile.json5 @@ -0,0 +1,35 @@ +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS", + } + ], + "buildModeSet": [ + { + "name": "debug", + }, + { + "name": "release" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/entry/build-profile.json5 b/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..808380f3b726e2036a3d6cf5fb9b0fd9513a8215 --- /dev/null +++ b/entry/build-profile.json5 @@ -0,0 +1,25 @@ +{ + "apiType": "stageMode", + "buildOption": { + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": true, + "files": [ + "./obfuscation-rules.txt" + ] + } + } + } + }, + ], + "targets": [ + { + "name": "default" + } + ] +} \ No newline at end of file diff --git a/entry/hvigorfile.ts b/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6edcd90486dd5a853cf7d34c8647f08414ca7a3 --- /dev/null +++ b/entry/hvigorfile.ts @@ -0,0 +1,6 @@ +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. */ +} diff --git a/entry/oh-package.json5 b/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..803b25293388deda7b9a05a21b5aeadeb716b4d5 --- /dev/null +++ b/entry/oh-package.json5 @@ -0,0 +1,9 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": {} +} \ No newline at end of file diff --git a/entry/src/main/ets/common/CommonConstants.ets b/entry/src/main/ets/common/CommonConstants.ets new file mode 100644 index 0000000000000000000000000000000000000000..d883f7eb0b3105fb54740d074f3ba2344af80fe5 --- /dev/null +++ b/entry/src/main/ets/common/CommonConstants.ets @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class CommonConstants { + /** + * Tag. + */ + static readonly TAG: string = 'ContextMenu: '; + + /** + * Menu item width level1. + */ + static readonly MENU_ITEM_WIDTH_LEVEL1: number = 100; + + /** + * Menu item width level2. + */ + static readonly MENU_ITEM_WIDTH_LEVEL2: number = 120; + + /** + * Menu item height. + */ + static readonly MENU_ITEM_HEIGHT: number = 50; + + /** + * Finger offset x. + */ + static readonly FINGER_OFFSET_X: number = 30; + + /** + * Finger offset y. + */ + static readonly FINGER_OFFSET_Y: number = 30; + + /** + * One hundred percent. + */ + static readonly ONE_HUNDRED_PERCENT: string = '100%'; +} \ No newline at end of file diff --git a/entry/src/main/ets/common/Utils.ets b/entry/src/main/ets/common/Utils.ets new file mode 100644 index 0000000000000000000000000000000000000000..78ed404d9c0ed015f4cd8510a9729cd3a2cd67a7 --- /dev/null +++ b/entry/src/main/ets/common/Utils.ets @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; + +export class Logger { + private domain: number; + private prefix: string; + private format: string = '%{public}s, %{public}s'; + + constructor(prefix: string) { + this.prefix = prefix; + this.domain = 0xFF00; + this.format.toUpperCase(); + } + + debug(...args: string[]) { + hilog.debug(this.domain, this.prefix, this.format, args); + } + + info(...args: string[]) { + hilog.info(this.domain, this.prefix, this.format, args); + } + + warn(...args: string[]) { + hilog.warn(this.domain, this.prefix, this.format, args); + } + + error(...args: string[]) { + hilog.error(this.domain, this.prefix, this.format, args); + } +} + +export let logger = new Logger('[CommonAppDevelopment]'); \ No newline at end of file diff --git a/entry/src/main/ets/entryability/EntryAbility.ets b/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..6b0dbf8c224682b9b07ec1821cfeddca87315f88 --- /dev/null +++ b/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy(): void { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage): void { + // Main window is created, set main page for this ability + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (err) => { + 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.'); + }); + } + + onWindowStageDestroy(): void { + // Main window is destroyed, release UI related resources + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground(): void { + // Ability has brought to foreground + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground(): void { + // Ability has back to background + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/Index.ets b/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..c014f711ceb65160f485f703dbe11e2224d54896 --- /dev/null +++ b/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { webview } from '@kit.ArkWeb'; +import { pasteboard } from '@kit.BasicServicesKit'; +import { common, Want } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { logger } from '../common/Utils'; +import { CommonConstants } from '../common/CommonConstants'; + +@Entry +@Component +struct WebCustomPressMenu { + @State linkUrl: string | undefined = undefined; + @State showMenu: boolean = false; + @State isExistImage: boolean = false; + private result: WebContextMenuResult | undefined = undefined; + private param: WebContextMenuParam | undefined = undefined; + private inputType: ContextMenuInputFieldType = ContextMenuInputFieldType.None; + private pressPosX: number = 0; + private pressPosY: number = 0; + private webWidth: number = 0; + private webHeight: number = 0; + private context: common.UIAbilityContext = {} as common.UIAbilityContext; + + aboutToAppear() { + webview.WebviewController.initializeWebEngine(); + let context = getContext(this) as common.UIAbilityContext; + this.context = context; + } + + @Builder + menuBuilder() { + Menu() { + if (this.isExistImage) { + MenuItem({ + content: $r('app.string.web_press_copy_image') + }) + .width(CommonConstants.MENU_ITEM_WIDTH_LEVEL1) + .height(CommonConstants.MENU_ITEM_HEIGHT) + .onClick(() => { + this.result?.copyImage(); + this.showMenu = false; + }) + } + if (this.param?.getEditStateFlags() === ContextMenuEditStateFlags.CAN_CUT) { + MenuItem({ + content: $r('app.string.web_press_cut') + }) + .width(CommonConstants.MENU_ITEM_WIDTH_LEVEL1) + .height(CommonConstants.MENU_ITEM_HEIGHT) + .onClick(() => { + this.result?.cut(); + this.showMenu = false; + }) + } + if (this.param?.getEditStateFlags() === ContextMenuEditStateFlags.CAN_PASTE) { + MenuItem({ + content: $r('app.string.web_press_copy') + }) + .width(CommonConstants.MENU_ITEM_WIDTH_LEVEL1) + .height(CommonConstants.MENU_ITEM_HEIGHT) + .onClick(() => { + this.result?.copy(); + this.showMenu = false; + }) + } + if (this.param?.getEditStateFlags() === ContextMenuEditStateFlags.CAN_PASTE) { + MenuItem({ + content: $r('app.string.web_press_paste') + }) + .width(CommonConstants.MENU_ITEM_WIDTH_LEVEL1) + .height(CommonConstants.MENU_ITEM_HEIGHT) + .onClick(() => { + this.result?.paste(); + this.showMenu = false; + }) + } + if (this.param?.getEditStateFlags() === ContextMenuEditStateFlags.CAN_PASTE) { + MenuItem({ + content: $r('app.string.web_press_select_all') + }) + .width(CommonConstants.MENU_ITEM_WIDTH_LEVEL1) + .height(CommonConstants.MENU_ITEM_HEIGHT) + .onClick(() => { + this.result?.selectAll(); + this.showMenu = false; + }) + } + if (this.linkUrl) { + MenuItem({ + content: $r('app.string.web_press_open_link') + }) + .width(CommonConstants.MENU_ITEM_WIDTH_LEVEL2) + .height(CommonConstants.MENU_ITEM_HEIGHT) + .onClick(() => { + const wantInfo: Want = { + action: 'ohos.want.action.viewData', + entities: ['entity.system.browsable'], + uri: this.linkUrl + }; + this.context.startAbility(wantInfo).then(() => { + logger.info(CommonConstants.TAG, 'startAbility succeed'); + }).catch((err: BusinessError) => { + logger.error(CommonConstants.TAG, `startAbility failed, message is ${err.message}`); + return; + }); + this.showMenu = false; + }) + MenuItem({ + content: $r('app.string.web_press_copy_link'), + }) + .width(CommonConstants.MENU_ITEM_WIDTH_LEVEL1) + .height(CommonConstants.MENU_ITEM_HEIGHT) + .onClick(() => { + const pasteData = pasteboard.createData('text/plain', this.linkUrl); + pasteboard.getSystemPasteboard().setData(pasteData, (error) => { + if (error) { + logger.error(CommonConstants.TAG, 'Failed to set PasteData. Cause: ' + error.message); + return; + } + logger.info(CommonConstants.TAG, 'Succeeded in setting PasteData.'); + }); + this.showMenu = false; + }) + } + if (this.inputType !== ContextMenuInputFieldType.None) { + MenuItem({ + content: $r('app.string.web_press_input_field') + }) + .width(CommonConstants.MENU_ITEM_WIDTH_LEVEL1) + .height(CommonConstants.MENU_ITEM_HEIGHT) + .onClick(() => { + this.showMenu = false; + }) + } + } + } + + build() { + Column() { + Web({ src: $rawfile('index.html'), controller: new webview.WebviewController() }) + .width(CommonConstants.ONE_HUNDRED_PERCENT) + .height(CommonConstants.ONE_HUNDRED_PERCENT) + .onAreaChange((oldArea, newArea) => { + logger.info(CommonConstants.TAG, `${oldArea}`); + this.webWidth = newArea.width as number; + this.webHeight = newArea.height as number; + }) + .onContextMenuShow((event) => { + if (event) { + this.result = event.result; + this.param = event.param; + this.pressPosX = px2vp(event.param.x()); + this.pressPosY = px2vp(event.param.y()); + logger.debug(CommonConstants.TAG, `x coord = ${this.pressPosX}, y coord = ${this.pressPosY}`); + logger.info(CommonConstants.TAG, 'link url = ' + event.param.getLinkUrl()); + this.linkUrl = event.param.getLinkUrl(); + this.inputType = event.param.getInputFieldType(); + this.isExistImage = event.param.existsImageContents(); + } + this.showMenu = true; + return true; + }) + .bindPopup(this.showMenu, + { + builder: this.menuBuilder(), + enableArrow: false, + placement: Placement.TopLeft, + mask: false, + offset: this.getPopupPosition(), + onStateChange: (e) => { + if (!e.isVisible) { + this.showMenu = false; + this.result!.closeContextMenu(); + } + } + }) + } + .backgroundColor($r('app.color.background_color')) + .expandSafeArea([SafeAreaType.SYSTEM],[SafeAreaEdge.BOTTOM, SafeAreaEdge.TOP]) + .width($r('app.string.web_press_full_size')) + .height($r('app.string.web_press_full_size')) + } + + getPopupPosition(): Position { + let popupWidth: number = CommonConstants.MENU_ITEM_WIDTH_LEVEL1; + let popupHeight: number = 0; + if (this.param?.existsImageContents()) { + popupHeight += CommonConstants.MENU_ITEM_HEIGHT; + } + if (this.param?.getEditStateFlags() === ContextMenuEditStateFlags.CAN_CUT) { + popupHeight += CommonConstants.MENU_ITEM_HEIGHT; + } + if (this.param?.getEditStateFlags() === ContextMenuEditStateFlags.CAN_PASTE) { + popupHeight += CommonConstants.MENU_ITEM_HEIGHT; + } + if (this.param?.getEditStateFlags() === ContextMenuEditStateFlags.CAN_PASTE) { + popupHeight += CommonConstants.MENU_ITEM_HEIGHT; + } + if (this.param?.getEditStateFlags() === ContextMenuEditStateFlags.CAN_PASTE) { + popupHeight += CommonConstants.MENU_ITEM_HEIGHT; + } + if (this.linkUrl) { + popupWidth = + CommonConstants.MENU_ITEM_WIDTH_LEVEL2 > popupWidth ? CommonConstants.MENU_ITEM_WIDTH_LEVEL2 : popupWidth; + popupHeight += CommonConstants.MENU_ITEM_HEIGHT * 2; + } + if (this.inputType !== ContextMenuInputFieldType.None) { + popupHeight += CommonConstants.MENU_ITEM_HEIGHT; + } + logger.debug(CommonConstants.TAG, `popup width: ${popupWidth}, height: ${popupHeight}`); + + let offset: Position = { x: 0, y: 0 }; + if (this.pressPosX <= this.webWidth / 2) { + offset.x = -(this.webWidth / 2 - this.pressPosX) + popupWidth / 2 + CommonConstants.FINGER_OFFSET_X; + } else { + offset.x = -(this.webWidth / 2 - this.pressPosX) - popupWidth / 2 - CommonConstants.FINGER_OFFSET_X; + } + if (this.pressPosY <= this.webHeight / 2) { + offset.y = -(this.webHeight / 2 - this.pressPosY) + popupHeight / 2 + CommonConstants.FINGER_OFFSET_Y; + } else { + offset.y = (this.pressPosY - this.webHeight / 2) - popupHeight / 2 - CommonConstants.FINGER_OFFSET_Y; + } + logger.debug(CommonConstants.TAG, `popup offset: ${offset.x}, ${offset.y}`); + return offset; + } +} \ No newline at end of file diff --git a/entry/src/main/module.json5 b/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..787538399cc4f9f45c3833dcb034108d02858854 --- /dev/null +++ b/entry/src/main/module.json5 @@ -0,0 +1,47 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:layered_image", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.INTERNET", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "inuse" + }, + } + ] + } +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/color.json b/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..fa5eba75ba52ecbfebcfa4bb17405e7e9e89a8b3 --- /dev/null +++ b/entry/src/main/resources/base/element/color.json @@ -0,0 +1,12 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + }, + { + "name": "background_color", + "value": "#f3f5f7" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/string.json b/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..6bce4393d6542b49a5042b2394ca513334678a1b --- /dev/null +++ b/entry/src/main/resources/base/element/string.json @@ -0,0 +1,56 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "Web自定义长按菜单" + }, + { + "name": "web_press_full_size", + "value": "100%" + }, + { + "name": "web_press_common_menu_item_height", + "value": "50" + }, + { + "name": "web_press_copy_image", + "value": "复制图片" + }, + { + "name": "web_press_cut", + "value": "剪切" + }, + { + "name": "web_press_copy", + "value": "复制" + }, + { + "name": "web_press_paste", + "value": "粘贴" + }, + { + "name": "web_press_select_all", + "value": "全选" + }, + { + "name": "web_press_open_link", + "value": "浏览器打开" + }, + { + "name": "web_press_input_field", + "value": "输入框" + }, + { + "name": "web_press_copy_link", + "value": "复制链接" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/background.png b/entry/src/main/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..f939c9fa8cc8914832e602198745f592a0dfa34d Binary files /dev/null and b/entry/src/main/resources/base/media/background.png differ diff --git a/entry/src/main/resources/base/media/foreground.png b/entry/src/main/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..4483ddad1f079e1089d685bd204ee1cfe1d01902 Binary files /dev/null and b/entry/src/main/resources/base/media/foreground.png differ diff --git a/entry/src/main/resources/base/media/layered_image.json b/entry/src/main/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/entry/src/main/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/startIcon.png b/entry/src/main/resources/base/media/startIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b Binary files /dev/null and b/entry/src/main/resources/base/media/startIcon.png differ diff --git a/entry/src/main/resources/base/profile/main_pages.json b/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/entry/src/main/resources/en_US/element/string.json b/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..a174106912cb561da4450054b7f7a3489bc3de38 --- /dev/null +++ b/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,56 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "Web Custom Long Press Menu" + }, + { + "name": "web_press_full_size", + "value": "100%" + }, + { + "name": "web_press_common_menu_item_height", + "value": "50" + }, + { + "name": "web_press_copy_image", + "value": "Copy Picture" + }, + { + "name": "web_press_cut", + "value": "Cuts" + }, + { + "name": "web_press_copy", + "value": "Copying" + }, + { + "name": "web_press_paste", + "value": "Pastes" + }, + { + "name": "web_press_select_all", + "value": "Select All" + }, + { + "name": "web_press_open_link", + "value": "Browser Open" + }, + { + "name": "web_press_input_field", + "value": "Input box" + }, + { + "name": "web_press_copy_link", + "value": "Copy Link" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/rawfile/example.png b/entry/src/main/resources/rawfile/example.png new file mode 100644 index 0000000000000000000000000000000000000000..c678977f013dac1a1bbf4a42d6f961c683985080 Binary files /dev/null and b/entry/src/main/resources/rawfile/example.png differ diff --git a/entry/src/main/resources/rawfile/index.html b/entry/src/main/resources/rawfile/index.html new file mode 100644 index 0000000000000000000000000000000000000000..63f86fa80c3c9e093363f18935dec107f1e5a2db --- /dev/null +++ b/entry/src/main/resources/rawfile/index.html @@ -0,0 +1,93 @@ + + + + +
+ + +长按特定元素(例如图片,链接)或鼠标右键,跳出菜单。给Web组件绑定popup弹窗,并设置弹窗内容,交互逻辑和显示状态。
+ + 链接元素 + +