From 7abe44e843c03fec77894f0800c5b47a7ce05e51 Mon Sep 17 00:00:00 2001 From: yuandongping Date: Thu, 26 Jun 2025 19:36:53 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yuandongping --- .gitignore | 6 +- OAT.xml | 28 + README_zh.md | 8 + build-profile.json5 | 9 +- bundle.json | 40 + common/resources/.gitignore | 1 + common/resources/hvigorfile.js | 2 +- common/resources/oh-package.json5 | 11 + common/resources/package-lock.json | 5 - common/resources/package.json | 14 - .../main/resources/rawfile/editor_style.css | 2 +- .../src/main/resources/rawfile/rich_editor.js | 217 ++-- common/utils/.gitignore | 1 + common/utils/hvigorfile.js | 2 +- common/utils/oh-package.json5 | 13 + common/utils/package-lock.json | 11 - common/utils/package.json | 16 - .../ets/default/access/MediaLibraryAccess.ets | 24 +- .../main/ets/default/baseUtil/DateUtil.ets | 10 +- .../main/ets/default/baseUtil/FolderUtil.ets | 45 +- .../baseUtil/GlobalResourceManager.ets | 40 +- .../baseUtil/{LogUtil.ets => LogUtil.ts} | 0 .../main/ets/default/baseUtil/NoteUtil.ets | 118 +- .../ets/default/baseUtil/OperationUtils.ets | 217 ++-- .../ets/default/baseUtil/RdbStoreUtil.ets | 609 +++++----- .../main/ets/default/model/NoteBaseData.ets | 12 +- .../model/databaseModel/FolderData.ets | 3 +- .../default/model/databaseModel/NoteData.ets | 3 +- .../model/databaseModel/SysDefData.ets | 297 ++--- .../default/model/searchModel/SearchModel.ets | 36 +- features/.gitignore | 1 + features/build-profile.json5 | 4 - features/hvigorfile.js | 2 +- features/index.ets | 57 + features/{package.json => oh-package.json5} | 3 - features/package-lock.json | 22 - .../src/main/ets/components/CusDialogComp.ets | 142 ++- .../main/ets/components/FolderListComp.ets | 179 ++- .../src/main/ets/components/NoteContent.ets | 148 ++- .../main/ets/components/NoteContentComp.ets | 1065 ++++++++++------- .../components/NoteContentCompPortrait.ets | 432 ++++--- .../src/main/ets/components/NoteListComp.ets | 365 ++++-- hvigor/hvigor-config.json5 | 20 + hvigorfile.js | 17 +- oh-package.json5 | 27 + package.json | 20 - product/default/.gitignore | 1 + product/default/hvigorfile.js | 2 +- .../{package.json => oh-package.json5} | 5 - product/default/package-lock.json | 45 - .../src/main/ets/Application/AbilityStage.ts | 15 + .../src/main/ets/MainAbility/MainAbility.ts | 384 +++--- .../default/src/main/ets/pages/MyNoteHome.ets | 38 +- .../src/main/ets/pages/NoteContentHome.ets | 7 +- .../default/src/main/ets/pages/NoteHome.ets | 13 +- .../src/main/ets/pages/NoteHomePortrait.ets | 6 +- product/default/src/main/module.json5 | 59 +- .../main/resources/base/element/string.json | 16 +- .../main/resources/zh_CN/element/string.json | 16 +- signature/UnsgnedReleasedProfileTemplate.json | 2 +- 60 files changed, 2889 insertions(+), 2024 deletions(-) create mode 100644 bundle.json create mode 100644 common/resources/oh-package.json5 delete mode 100644 common/resources/package-lock.json delete mode 100644 common/resources/package.json create mode 100644 common/utils/oh-package.json5 delete mode 100644 common/utils/package-lock.json delete mode 100644 common/utils/package.json rename common/utils/src/main/ets/default/baseUtil/{LogUtil.ets => LogUtil.ts} (100%) create mode 100644 features/index.ets rename features/{package.json => oh-package.json5} (91%) delete mode 100644 features/package-lock.json create mode 100644 hvigor/hvigor-config.json5 create mode 100644 oh-package.json5 delete mode 100644 package.json rename product/default/{package.json => oh-package.json5} (76%) delete mode 100644 product/default/package-lock.json diff --git a/.gitignore b/.gitignore index fd58715..a4a85d0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,11 @@ /node_modules +/oh_modules /local.properties /.idea **/build /signature /.hvigor -/package.json \ No newline at end of file +/package.json +/.clang-format +**/oh-package-lock.json5 +**/BuildProfile.ets \ No newline at end of file diff --git a/OAT.xml b/OAT.xml index 75df75e..7dc37cd 100644 --- a/OAT.xml +++ b/OAT.xml @@ -36,11 +36,21 @@ + + + + + + + + + + @@ -64,6 +74,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/README_zh.md b/README_zh.md index b4acd1a..9eedf67 100644 --- a/README_zh.md +++ b/README_zh.md @@ -136,6 +136,14 @@ hilog | grep 过滤信息 hilog | grep Label ``` +## 5.约束与限制 + +1.本示例仅支持标准系统上运行,支持设备RK3568。 + +2.本示例已适配API14版本SDK,SDK版本号(API Version 14 5.0.2),镜像版本号(5.0.2)。 + +3.本示例需要使用DevEco Studio 5.0.2 Release版本才可编译运行。 + ## 相关仓 系统应用 diff --git a/build-profile.json5 b/build-profile.json5 index e0e91d4..1adbdc0 100644 --- a/build-profile.json5 +++ b/build-profile.json5 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 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 @@ -16,12 +16,13 @@ { "app": { - "compileSdkVersion": 10, - "compatibleSdkVersion": 9, "products": [ { "name": "default", - "signingConfig": "default" + "signingConfig": "default", + "compileSdkVersion": 14, + "compatibleSdkVersion": 14, + "runtimeOS": "OpenHarmony" } ], "signingConfigs": [ diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000..69e5203 --- /dev/null +++ b/bundle.json @@ -0,0 +1,40 @@ +{ + "name": "@ohos/notes", + "description": "notes app for standard system.", + "version": "3.0", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "applications/standard/notes" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "notes", + "subsystem": "applications", + "syscap": [], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "0KB", + "ram": "0KB", + "deps": { + "components": [ + "ability_base", + "ability_runtime", + "relational_store", + "hiviewdfx_hilog_native", + "web_webview", + "resourceManager", + "medialibrary_standard" + ], + "third_party": [] + }, + "build": { + "sub_component": [], + "inner_kits": [], + "test": [] + } + } +} \ No newline at end of file diff --git a/common/resources/.gitignore b/common/resources/.gitignore index a5c564a..725ae70 100644 --- a/common/resources/.gitignore +++ b/common/resources/.gitignore @@ -1,4 +1,5 @@ /node_modules +/oh_modules /.preview /build /package.json \ No newline at end of file diff --git a/common/resources/hvigorfile.js b/common/resources/hvigorfile.js index 42ed4b4..29ad39f 100644 --- a/common/resources/hvigorfile.js +++ b/common/resources/hvigorfile.js @@ -1,3 +1,3 @@ // Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. -module.exports = require('@ohos/hvigor-ohos-plugin').harTasks +module.exports = require('@ohos/hvigor-ohos-plugin').harTasks; diff --git a/common/resources/oh-package.json5 b/common/resources/oh-package.json5 new file mode 100644 index 0000000..c326fe6 --- /dev/null +++ b/common/resources/oh-package.json5 @@ -0,0 +1,11 @@ +{ + "license": "ISC", + "types": "", + "devDependencies": {}, + "name": "@ohos/resources", + "description": "a npm package which contains arkUI2.0 page", + "main": "index.ets", + "repository": {}, + "version": "1.0.0", + "dependencies": {} +} diff --git a/common/resources/package-lock.json b/common/resources/package-lock.json deleted file mode 100644 index e254bc2..0000000 --- a/common/resources/package-lock.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "@ohos/resources", - "version": "1.0.0", - "lockfileVersion": 1 -} diff --git a/common/resources/package.json b/common/resources/package.json deleted file mode 100644 index 58e3ac4..0000000 --- a/common/resources/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "license": "ISC", - "types": "", - "devDependencies": {}, - "name": "@ohos/resources", - "description": "a npm package which contains arkUI2.0 page", - "ohos": { - "org": "" - }, - "main": "index.ets", - "repository": {}, - "version": "1.0.0", - "dependencies": {} -} diff --git a/common/resources/src/main/resources/rawfile/editor_style.css b/common/resources/src/main/resources/rawfile/editor_style.css index d1b0ec6..65144b1 100644 --- a/common/resources/src/main/resources/rawfile/editor_style.css +++ b/common/resources/src/main/resources/rawfile/editor_style.css @@ -98,7 +98,7 @@ body { background-color: white; display: none; justify-content: space-around; - padding-bottom: 6px; + padding-bottom: 50px; } .button-box div { diff --git a/common/resources/src/main/resources/rawfile/rich_editor.js b/common/resources/src/main/resources/rawfile/rich_editor.js index affaa66..79e28e5 100644 --- a/common/resources/src/main/resources/rawfile/rich_editor.js +++ b/common/resources/src/main/resources/rawfile/rich_editor.js @@ -13,12 +13,16 @@ * limitations under the License. */ -var RICH_EDITOR = {}; - +let RICH_EDITOR = {}; +let storage = window.localStorage; RICH_EDITOR.editor = document.getElementById('editorjs_box'); RICH_EDITOR.setHtml = function (contents) { - var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + let paddingLeft = storage.getItem('paddingLeft'); + if (contents) { + RICH_EDITOR.editor.style.paddingLeft = paddingLeft + 'px'; + } + let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; if (base64regex.test(contents)) { RICH_EDITOR.editor.innerHTML = decodeURIComponent(escape(atob(contents))); } else { @@ -63,18 +67,18 @@ RICH_EDITOR.setUnderline = function () { }; RICH_EDITOR.getListStyle = function () { - var selection; - var type; + let selection; + let type; if (window.getSelection) { selection = getSelection(); } if (!selection) { - return + return; } - var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); + let range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); try { - var child = range.commonAncestorContainer; - for (var i = 0; i < 10; i++) { + let child = range.commonAncestorContainer; + for (let i = 0; i < 10; i++) { if (child.nodeName === 'OL') { console.info('insertOrderedList'); document.execCommand('insertOrderedList', false, null); @@ -100,19 +104,21 @@ RICH_EDITOR.setNumbers = function () { if (listStyle === 'decimal') { return; } + let fontSize = document.queryCommandValue('fontSize'); document.execCommand('insertOrderedList', false, null); - var selection; - var type; + document.execCommand('fontSize', false, fontSize); + let selection; + let type; if (window.getSelection) { selection = getSelection(); } if (!selection) { - return + return; } - var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); + let range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); try { - var child = range.commonAncestorContainer; - for (var i = 0; i < 10; i++) { + let child = range.commonAncestorContainer; + for (let i = 0; i < 10; i++) { if (child.nodeName === 'OL') { child.style['list-style'] = 'decimal'; break; @@ -131,19 +137,21 @@ RICH_EDITOR.setABC = function () { if (listStyle === 'lower-alpha') { return; } + let fontSize = document.queryCommandValue('fontSize'); document.execCommand('insertOrderedList', false, null); - var selection; - var type; + document.execCommand('fontSize', false, fontSize); + let selection; + let type; if (window.getSelection) { selection = getSelection(); } if (!selection) { - return + return; } - var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); + let range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); try { - var child = range.commonAncestorContainer; - for (var i = 0; i < 10; i++) { + let child = range.commonAncestorContainer; + for (let i = 0; i < 10; i++) { if (child.nodeName === 'OL') { child.style['list-style'] = 'lower-alpha'; break; @@ -162,19 +170,21 @@ RICH_EDITOR.setBullets = function () { if (listStyle === 'disc') { return; } + let fontSize = document.queryCommandValue('fontSize'); document.execCommand('insertUnorderedList', false, null); - var selection; - var type; + document.execCommand('fontSize', false, fontSize); + let selection; + let type; if (window.getSelection) { selection = getSelection(); } if (!selection) { - return + return; } - var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); + let range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); try { - var child = range.commonAncestorContainer; - for (var i = 0; i < 10; i++) { + let child = range.commonAncestorContainer; + for (let i = 0; i < 10; i++) { if (child.nodeName === 'UL') { child.style['list-style'] = 'disc'; break; @@ -193,19 +203,21 @@ RICH_EDITOR.setSquare = function () { if (listStyle === 'square') { return; } + let fontSize = document.queryCommandValue('fontSize'); document.execCommand('insertUnorderedList', false, null); - var selection; - var type; + document.execCommand('fontSize', false, fontSize); + let selection; + let type; if (window.getSelection) { selection = getSelection(); } if (!selection) { - return + return; } - var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); + let range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); try { - var child = range.commonAncestorContainer; - for (var i = 0; i < 10; i++) { + let child = range.commonAncestorContainer; + for (let i = 0; i < 10; i++) { if (child.nodeName === 'UL') { child.style['list-style'] = 'square'; break; @@ -241,25 +253,37 @@ RICH_EDITOR.execFontSize = function (size, unit) { } }; -var pad = 24; +let pad = 24; RICH_EDITOR.setIndent = function () { - var parents = document.getElementById('editorjs_box'); + let parents = document.getElementById('editorjs_box'); parents.removeAttribute('padding-left'); if (pad >= 408) { - return + return; } pad = pad + 24; parents.style.paddingLeft = pad + 'px'; + if (!storage) { + return; + } + storage.setItem('paddingLeft', pad); }; RICH_EDITOR.setOutdent = function () { - var parents = document.getElementById('editorjs_box'); + let parents = document.getElementById('editorjs_box'); parents.removeAttribute('padding-left'); if (pad === 24) { parents.style.paddingLeft = 24 + 'px'; + if (!storage) { + return; + } + storage.setItem('paddingLeft', pad); } else { pad = pad - 24; parents.style.paddingLeft = pad + 'px'; + if (!storage) { + return; + } + storage.setItem('paddingLeft', pad); } }; @@ -276,10 +300,10 @@ RICH_EDITOR.setJustifyRight = function () { }; RICH_EDITOR.insertImage = function (url) { - var html = '

picvision

'; - document.getElementById('editorjs_box').innerHTML += html + let html = '

picvision

'; + document.getElementById('editorjs_box').innerHTML += html; document.getElementById('editorjs_box').scrollIntoView(false); }; @@ -288,20 +312,20 @@ RICH_EDITOR.insertHTML = function (html) { }; RICH_EDITOR.setDone = function () { - var html = '  '; + let html = '  '; document.execCommand('insertHTML', false, html); }; RICH_EDITOR.addTodo = function (e) { - var KEY_ENTER; + let KEY_ENTER; KEY_ENTER = 13; if (e.which === KEY_ENTER) { - var node = RICH_EDITOR.getSelectedAnchorNode(); + let node = RICH_EDITOR.getSelectedAnchorNode(); if (node && node.nodeName === '#text') { node = node.parentElement; } - if (node && node.nodeName === 'SPAN' && node.previousElementSibling - && node.previousElementSibling.className === 'note-checkbox') { + if (node && node.nodeName === 'SPAN' && node.previousElementSibling && + node.previousElementSibling.className === 'note-checkbox') { RICH_EDITOR.setTodo(); e.preventDefault(); } @@ -309,11 +333,12 @@ RICH_EDITOR.addTodo = function (e) { }; RICH_EDITOR.setTodo = function () { - var parent = document.getElementById('editorjs_box'); - var isContentEmpty = parent.innerHTML.trim().length === 0 || parent.innerHTML === '
'; - var html = (isContentEmpty ? '' : '
') - + '' - + ' '; + let parent = document.getElementById('editorjs_box'); + let isContentEmpty = parent.innerHTML.trim().length === 0 || parent.innerHTML === '
'; + let html = (isContentEmpty ? '' : '
') + + ' ' + + '' + + ' '; document.execCommand('insertHTML', false, html); }; @@ -326,9 +351,9 @@ function onCheckChange(checkbox) { } RICH_EDITOR.restorerange = function () { - var selection = window.getSelection(); + let selection = window.getSelection(); selection.removeAllRanges(); - var range = document.createRange(); + let range = document.createRange(); range.setStart(RICH_EDITOR.currentSelection.startContainer, RICH_EDITOR.currentSelection.startOffset); range.setEnd(RICH_EDITOR.currentSelection.endContainer, RICH_EDITOR.currentSelection.endOffset); selection.addRange(range); @@ -337,15 +362,15 @@ RICH_EDITOR.restorerange = function () { // 获取光标开始位置归属节点 RICH_EDITOR.getSelectedAnchorNode = function () { - var node; - var selection; + let node; + let selection; if (window.getSelection) { selection = getSelection(); node = selection.anchorNode; } if (!node && document.selection) { selection = document.selection; - var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); + let range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); node = range.commonAncestorContainer ? range.commonAncestorContainer : range.parentElement ? range.parentElement() : range.item(0); } @@ -353,36 +378,36 @@ RICH_EDITOR.getSelectedAnchorNode = function () { }; RICH_EDITOR.cancelSelection = function () { - var selection = window.getSelection(); + let selection = window.getSelection(); selection.removeAllRanges(); -} +}; -var callBackToApp; +let callBackToApp = window.callBackToApp; function getHtmlContent() { console.log('getHtmlContent'); - var htmlString = RICH_EDITOR.getHtml(); + let htmlString = RICH_EDITOR.getHtml(); let imgName = getImagePathFromContent(htmlString); htmlString = window.btoa(unescape(encodeURIComponent(htmlString))); callBackToApp.callbackImagePath(imgName); - var str = callBackToApp.callbackhtml(htmlString); + let str = callBackToApp.callbackhtml(htmlString); console.log('getHtmlContent end'); } function saveHtmlContent() { console.log('saveHtmlContent'); - var htmlString = RICH_EDITOR.getHtml(); + let htmlString = RICH_EDITOR.getHtml(); let imgName = getImagePathFromContent(htmlString); htmlString = window.btoa(unescape(encodeURIComponent(htmlString))); callBackToApp.callbackImagePath(imgName); - var str = callBackToApp.callbackhtmlSave(htmlString); + let str = callBackToApp.callbackhtmlSave(htmlString); console.log('saveHtmlContent end'); } function getImagePathFromContent(contentInfo) { let imgReg = /]+>/g; - let imgName = ""; + let imgName = ''; let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; let imgArray = contentInfo.match(imgReg); // 取第一张图片做为标题栏后的缩略图 @@ -391,7 +416,7 @@ function getImagePathFromContent(contentInfo) { if (src != null && src.length > 1) { imgName = src[1]; if (imgName.indexOf('shuxue.png') >= 0 || imgName.indexOf('cake.png') >= 0) { - imgName = "/res/" + imgName; + imgName = '/res/' + imgName; } } } @@ -399,13 +424,15 @@ function getImagePathFromContent(contentInfo) { } function scheduledSaveContent() { - console.info('scheduledSaveContent'); - var htmlString = RICH_EDITOR.getHtml(); - let imgName = getImagePathFromContent(htmlString); - htmlString = window.btoa(unescape(encodeURIComponent(htmlString))); - callBackToApp.callbackImagePath(imgName); - var str = callBackToApp.callbackScheduledSave(htmlString); - console.info('scheduledSaveContent end'); + if (callBackToApp !== undefined) { + console.info('scheduledSaveContent'); + let htmlString = RICH_EDITOR.getHtml(); + let imgName = getImagePathFromContent(htmlString); + htmlString = window.btoa(unescape(encodeURIComponent(htmlString))); + callBackToApp.callbackImagePath(imgName); + let str = callBackToApp.callbackScheduledSave(htmlString); + console.info('scheduledSaveContent end'); + } } document.body.addEventListener('paste', (event) => { @@ -415,7 +442,7 @@ document.body.addEventListener('paste', (event) => { const reader = new FileReader(); reader.onloadend = () => { callBackToApp.callbackPasteImage(reader.result); - } + }; reader.readAsDataURL(file); event.preventDefault(); } @@ -423,40 +450,42 @@ document.body.addEventListener('paste', (event) => { RICH_EDITOR.getFontSizes = function () { document.execCommand('fontSize', false, null); - var fontElements = window.getSelection().anchorNode.parentNode; - var getSize = parseInt(window.getComputedStyle(fontElements, null).fontSize) - var str = callBackToApp.callbackGetSize(getSize); + let fontElements = window.getSelection().anchorNode.parentNode; + let getSize = parseInt(window.getComputedStyle(fontElements, null).fontSize); + let str = callBackToApp.callbackGetSize(getSize); }; RICH_EDITOR.insertImageHtml = function (contents) { let selection = window.getSelection(); - if (!selection.rangeCount) - return false; + if (!selection.rangeCount) { + return false; + } selection.deleteFromDocument(); let img = document.createElement('img'); img.src = contents; selection.getRangeAt(0).insertNode(img); + return true; }; document.addEventListener('click', (e) => { - console.info(`lsq: e is ${JSON.stringify(e)}`) - var parent = document.getElementById('editorjs_box'); + console.info(`lsq: e is ${JSON.stringify(e)}`); + let parent = document.getElementById('editorjs_box'); if (parent.id !== 'editorjs_box') { - e.preventDefault() + e.preventDefault(); } -}) +}); document.getElementById('addToDo').addEventListener('click', () => { - callBackToApp.addToDo() -}) + callBackToApp.addToDo(); +}); document.getElementById('chooseStyle').addEventListener('click', () => { - callBackToApp.chooseStyle() -}) + callBackToApp.chooseStyle(); +}); document.getElementById('openAlbum').addEventListener('click', () => { - callBackToApp.openAlbum() -}) + callBackToApp.openAlbum(); +}); function changeSizeToRk() { document.getElementById('img1').style.width = '40px'; @@ -500,10 +529,12 @@ function hiddenButton() { RICH_EDITOR.getFocus = function () { return document.getElementById('editorjs_box').focus(); -} +}; + +RICH_EDITOR.getBlur = function () { + return document.getElementById('editorjs_box').blur(); +}; document.getElementById('editorjs_box').addEventListener('click', () => { - if (callBackToApp.getBreakPoint() === 'sm') { - document.getElementById('buttonBox').style.display = 'flex'; - } -}) \ No newline at end of file + document.getElementById('buttonBox').style.display = 'flex'; +}); \ No newline at end of file diff --git a/common/utils/.gitignore b/common/utils/.gitignore index a5c564a..725ae70 100644 --- a/common/utils/.gitignore +++ b/common/utils/.gitignore @@ -1,4 +1,5 @@ /node_modules +/oh_modules /.preview /build /package.json \ No newline at end of file diff --git a/common/utils/hvigorfile.js b/common/utils/hvigorfile.js index 42ed4b4..29ad39f 100644 --- a/common/utils/hvigorfile.js +++ b/common/utils/hvigorfile.js @@ -1,3 +1,3 @@ // Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. -module.exports = require('@ohos/hvigor-ohos-plugin').harTasks +module.exports = require('@ohos/hvigor-ohos-plugin').harTasks; diff --git a/common/utils/oh-package.json5 b/common/utils/oh-package.json5 new file mode 100644 index 0000000..1e5164d --- /dev/null +++ b/common/utils/oh-package.json5 @@ -0,0 +1,13 @@ +{ + "license": "ISC", + "types": "", + "devDependencies": {}, + "name": "@ohos/utils", + "description": "a npm package which contains arkUI2.0 page", + "main": "index.ets", + "repository": {}, + "version": "1.0.0", + "dependencies": { + "@ohos/source": "file:../resources" + } +} diff --git a/common/utils/package-lock.json b/common/utils/package-lock.json deleted file mode 100644 index 1da89db..0000000 --- a/common/utils/package-lock.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@ohos/utils", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@ohos/source": { - "version": "file:../resources" - } - } -} diff --git a/common/utils/package.json b/common/utils/package.json deleted file mode 100644 index 6581745..0000000 --- a/common/utils/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "license": "ISC", - "types": "", - "devDependencies": {}, - "name": "@ohos/utils", - "description": "a npm package which contains arkUI2.0 page", - "ohos": { - "org": "" - }, - "main": "index.ets", - "repository": {}, - "version": "1.0.0", - "dependencies": { - "@ohos/source": "file:../resources" - } -} diff --git a/common/utils/src/main/ets/default/access/MediaLibraryAccess.ets b/common/utils/src/main/ets/default/access/MediaLibraryAccess.ets index 8028896..17b4ed3 100644 --- a/common/utils/src/main/ets/default/access/MediaLibraryAccess.ets +++ b/common/utils/src/main/ets/default/access/MediaLibraryAccess.ets @@ -13,14 +13,20 @@ * limitations under the License. */ -import {LogUtil} from '../baseUtil/LogUtil' -import MediaLib from '@ohos.multimedia.mediaLibrary'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; +import common from '@ohos.app.ability.common'; +import { LogUtil } from '../baseUtil/LogUtil'; -const TAG = "MediaLibraryAccess" -export class MediaLibraryAccess { +const TAG: string = 'MediaLibraryAccess'; + +interface albumType { + count: number; + obj: photoAccessHelper.PhotoAsset | null; +} - static async getFirstObject(fetchOpt, context) { - let album = { +export class MediaLibraryAccess { + static async getFirstObject(fetchOpt: photoAccessHelper.FetchOptions, context: common.UIAbilityContext) { + let album: albumType = { count: 0, obj: null, } @@ -28,7 +34,7 @@ export class MediaLibraryAccess { // 通过Uri拷贝图片到指定指定的包路径下 // 1、获取本地路径 - let fileResult = await MediaLib.getMediaLibrary(context).getFileAssets(fetchOpt) + let fileResult = await photoAccessHelper.getPhotoAccessHelper(context).getAssets(fetchOpt) if (fileResult != undefined) { album.count = fileResult.getCount(); if (album.count <= 0) { @@ -51,7 +57,7 @@ export class MediaLibraryAccess { } } - static async openAsset(mode: string, fileAsset: any) { + static async openAsset(mode: string, fileAsset: photoAccessHelper.PhotoAsset) { LogUtil.info(TAG, 'openAsset start') let fd = await fileAsset.open(mode); LogUtil.info(TAG, `openAsset end. fd: ${fd}`) @@ -64,7 +70,7 @@ export class MediaLibraryAccess { return fd; } - static async closeAsset(fd: number, fileAsset: any) { + static async closeAsset(fd: number, fileAsset: photoAccessHelper.PhotoAsset) { LogUtil.info(TAG, 'closeAsset start') if (fd <= 0) { diff --git a/common/utils/src/main/ets/default/baseUtil/DateUtil.ets b/common/utils/src/main/ets/default/baseUtil/DateUtil.ets index 75a1864..f5c29dc 100644 --- a/common/utils/src/main/ets/default/baseUtil/DateUtil.ets +++ b/common/utils/src/main/ets/default/baseUtil/DateUtil.ets @@ -13,15 +13,15 @@ * limitations under the License. */ -import {LogUtil} from './LogUtil' +import { LogUtil } from './LogUtil'; -const TAG = "DateUtil" +const TAG: string = 'DateUtil'; /** * 日期和时间均显示为2位数 * @param time */ -function getUnifiedTime(time: number): any { +function getUnifiedTime(time: number): string | number { return time > 9 ? time : "0" + time } @@ -33,7 +33,7 @@ export class DateUtil { * 获取笔记标题的格式化时间 * @param date note modified time */ - formateDateForNoteTitle(date: Date): string{ + formateDateForNoteTitle(date: Date): string { let nowDate = new Date() let diffMin = Math.floor((nowDate.getTime() - date.getTime()) / 1000 / 60) if (diffMin < 0) { @@ -88,7 +88,7 @@ export class DateUtil { * 获取笔记内容的格式化时间 * @param date note modified time */ - formateDateForNoteContent(date: Date): string{ + formateDateForNoteContent(date: Date): string { // formatted time let noteContentTime = "" // note modified time diff --git a/common/utils/src/main/ets/default/baseUtil/FolderUtil.ets b/common/utils/src/main/ets/default/baseUtil/FolderUtil.ets index ab9190b..4160725 100644 --- a/common/utils/src/main/ets/default/baseUtil/FolderUtil.ets +++ b/common/utils/src/main/ets/default/baseUtil/FolderUtil.ets @@ -98,7 +98,14 @@ export class FolderUtil { * @return boolean - fottom fixed folder: deleted or favorite return true. else return false */ isBottomFixedFolder(folderData: FolderData): boolean { - LogUtil.info(TAG, "folderDataUuid " + folderData.uuid) + if (folderData === undefined || folderData === null) { + LogUtil.info(TAG, "isBottomFixedFolder folderData undefined") + } + if (folderData.uuid === undefined || folderData.uuid === null) { + LogUtil.info(TAG, "isBottomFixedFolder folderData uuid undefined") + folderData.uuid = 'sys_def_unClassified_uuid'; + } + LogUtil.info(TAG, "isBottomFixedFolder folderDataUuid " + folderData.uuid) return (folderData.folder_type == FolderType.FeatureDef) } @@ -109,8 +116,15 @@ export class FolderUtil { * @return boolean - can be moved into notes return true. else return false */ isFolderMoveIn(folderData: FolderData): boolean { - LogUtil.info(TAG, "folderDataUuid " + folderData.uuid) - return (folderData.uuid == SysDefFolderUuid.UnClassified || folderData.folder_type == FolderType.CusDef) + if (folderData === undefined || folderData === null) { + LogUtil.info(TAG, "isFolderMoveIn folderData undefined") + } + if (folderData.uuid! === undefined || folderData.uuid! === null) { + LogUtil.info(TAG, "isFolderMoveIn folderData uuid undefined") + folderData.uuid! == 'sys_def_unClassified_uuid'; + } + LogUtil.info(TAG, "isFolderMoveIn folderDataUuid " + folderData.uuid!); + return (folderData.uuid! == SysDefFolderUuid.UnClassified || folderData!.folder_type == FolderType.CusDef); } /** @@ -141,18 +155,18 @@ export class FolderUtil { */ getNoteCount(noteDataArray: NoteData[], folderUuid: string): number { let count = 0; - const folderTextMap = { - "sys_def_allNotes_uuid": (noteData) => { - noteData.is_deleted == Delete.No ? ++count : count + const folderTextMap: Record void> = { + "sys_def_allNotes_uuid": (noteData: NoteData) => { + noteData.is_deleted == Delete.No ? ++count : count; }, - "sys_def_recentDeletes_uuid": (noteData) => { - noteData.is_deleted == Delete.Yes ? ++count : count + "sys_def_recentDeletes_uuid": (noteData: NoteData) => { + noteData.is_deleted == Delete.Yes ? ++count : count; }, - "sys_def_myFavorites_uuid": (noteData) => { - noteData.is_favorite == Favorite.Yes && noteData.is_deleted == Delete.No ? ++count : count + "sys_def_myFavorites_uuid": (noteData: NoteData) => { + noteData.is_favorite == Favorite.Yes && noteData.is_deleted == Delete.No ? ++count : count; }, - "sys_def_other_uuid": (noteData) => { - noteData.folder_uuid == folderUuid && noteData.is_deleted == Delete.No ? ++count : count + "sys_def_other_uuid": (noteData: NoteData) => { + noteData.folder_uuid == folderUuid && noteData.is_deleted == Delete.No ? ++count : count; }, } if (folderUuid == SysDefFolderUuid.AllNotes || folderUuid == SysDefFolderUuid.RecentDeletes || folderUuid == SysDefFolderUuid.MyFavorites) { @@ -171,12 +185,12 @@ export class FolderUtil { * @param selectedNoteArray - Selected note data list * @return FolderData - return folder when note data list belong to the same folder, else return null */ - getCommonFolder(folderDataArray: FolderData[], selectedNoteArray: NoteData[]): FolderData { + getCommonFolder(folderDataArray: FolderData[], selectedNoteArray: NoteData[]): FolderData | null { if (selectedNoteArray.length == 0) { return null } let folderData: FolderData = this.getFolderData(folderDataArray, selectedNoteArray[0].folder_uuid) - let currentFolderData = null + let currentFolderData: string | null = null; selectedNoteArray.forEach((noteItem) => { if (folderData != this.getFolderData(folderDataArray, noteItem.folder_uuid)) { currentFolderData = this.getFolderData(folderDataArray, noteItem.folder_uuid).name @@ -197,11 +211,12 @@ export class FolderUtil { if (folderDataArray[index].folder_type == FolderType.CusDef && folderDataArray[index].name == inputStr) { return true } else { - let temp = GlobalResourceManager.getStringByResource(this.getFolderText(folderDataArray[index])) + let temp = GlobalResourceManager.getStringByResource(this.getFolderText(folderDataArray[index]) as Resource); temp.then(result => { if (result == inputStr) { return true } + return false; }) } } diff --git a/common/utils/src/main/ets/default/baseUtil/GlobalResourceManager.ets b/common/utils/src/main/ets/default/baseUtil/GlobalResourceManager.ets index 1676f3f..317f809 100644 --- a/common/utils/src/main/ets/default/baseUtil/GlobalResourceManager.ets +++ b/common/utils/src/main/ets/default/baseUtil/GlobalResourceManager.ets @@ -13,34 +13,34 @@ * limitations under the License. */ -import Rsm from '@ohos.resourceManager'; -import {LogUtil} from './LogUtil' +import common from '@ohos.app.ability.common'; +import { BusinessError } from '@ohos.base'; +import { LogUtil } from './LogUtil'; -const TAG = "Note_GlobalResourceManager" +const TAG: string = 'Note_GlobalResourceManager'; +let context = getContext(this) as common.UIAbilityContext; export class GlobalResourceManager { - public async getStringByResource(res: any): Promise { - let json = JSON.parse(JSON.stringify(res)); - let id = json.id; + public async getStringByResource(res: Resource): Promise { + let json: Resource = JSON.parse(JSON.stringify(res)); + let id: number = json.id; LogUtil.info(TAG, "ResourceID = " + id) return await this.getStringById(id); } - public getStringById(id: number): Promise{ + public getStringById(id: number): Promise { let promise = new Promise(resolve => { - let resourceMgr = Rsm.getResourceManager("com.example.note"); - resourceMgr.then((result) => { - result.getString(id) - .then((resource) => { - resolve(resource); - LogUtil.info(TAG, 'getStringById resolve(resource) : ' + resolve(resource)); - LogUtil.info(TAG, 'getStringById resource : ' + resource); - LogUtil.info(TAG, 'getStringById resource2 : ' + JSON.stringify(resource)); - }) - .catch((err) => { - LogUtil.info(TAG, 'getStringById err : ' + JSON.stringify(err)); - }); - }); + let resourceMgr = context.resourceManager; + resourceMgr.getStringValue(id) + .then((resource) => { + resolve(resource); + LogUtil.info(TAG, 'getStringById resolve(resource) : ' + resolve(resource)); + LogUtil.info(TAG, 'getStringById resource : ' + resource); + LogUtil.info(TAG, 'getStringById resource2 : ' + JSON.stringify(resource)); + }) + .catch((err: BusinessError) => { + LogUtil.error(TAG, 'getStringById err : ' + JSON.stringify(err)); + }); }); LogUtil.info(TAG, 'getStringById promise: ' + JSON.stringify(promise)); return promise; diff --git a/common/utils/src/main/ets/default/baseUtil/LogUtil.ets b/common/utils/src/main/ets/default/baseUtil/LogUtil.ts similarity index 100% rename from common/utils/src/main/ets/default/baseUtil/LogUtil.ets rename to common/utils/src/main/ets/default/baseUtil/LogUtil.ts diff --git a/common/utils/src/main/ets/default/baseUtil/NoteUtil.ets b/common/utils/src/main/ets/default/baseUtil/NoteUtil.ets index df10ebb..8b477f9 100644 --- a/common/utils/src/main/ets/default/baseUtil/NoteUtil.ets +++ b/common/utils/src/main/ets/default/baseUtil/NoteUtil.ets @@ -13,17 +13,24 @@ * limitations under the License. */ -import {unSelectedNoteBgColorMap, selectedNoteBgColorMap} from '../model/NoteBaseData' -import FolderData from '../model/databaseModel/FolderData' -import NoteData from '../model/databaseModel/NoteData' -import {SysDefFolderUuid, FolderType, Favorite, Delete, TableName, NoteTableColumn, -} from '../model/databaseModel/EnumData' -import StyleConstants from '../constants/StyleConstants' -import {LogUtil} from './LogUtil' -import FolderUtil from './FolderUtil' -import RdbStoreUtil from './RdbStoreUtil' +import { unSelectedNoteBgColorMap, selectedNoteBgColorMap } from '../model/NoteBaseData'; +import FolderData from '../model/databaseModel/FolderData'; +import NoteData from '../model/databaseModel/NoteData'; +import { + SysDefFolderUuid, + FolderType, + Favorite, + Delete, + TableName, + NoteTableColumn +} from '../model/databaseModel/EnumData'; +import StyleConstants from '../constants/StyleConstants'; +import { LogUtil } from './LogUtil'; +import FolderUtil from './FolderUtil'; +import RdbStoreUtil from './RdbStoreUtil'; +import buffer from '@ohos.buffer'; -const TAG = "NoteUtil" +const TAG: string = 'NoteUtil'; export class NoteUtil { /** @@ -104,18 +111,18 @@ export class NoteUtil { */ getNoteCount(noteDataArray: NoteData[], folderData: FolderData): number { let count = 0; - const folderTextMap = { - "sys_def_allNotes_uuid": (noteData) => { - noteData.is_deleted == Delete.No ? ++count : count + const folderTextMap: Record void> = { + "sys_def_allNotes_uuid": (noteData: NoteData) => { + noteData.is_deleted == Delete.No ? ++count : count; }, - "sys_def_recentDeletes_uuid": (noteData) => { - noteData.is_deleted == Delete.Yes ? ++count : count + "sys_def_recentDeletes_uuid": (noteData: NoteData) => { + noteData.is_deleted == Delete.Yes ? ++count : count; }, - "sys_def_myFavorites_uuid": (noteData) => { - noteData.is_favorite == Favorite.Yes && noteData.is_deleted == Delete.No ? ++count : count + "sys_def_myFavorites_uuid": (noteData: NoteData) => { + noteData.is_favorite == Favorite.Yes && noteData.is_deleted == Delete.No ? ++count : count; }, - "sys_def_other_uuid": (noteData) => { - noteData.folder_uuid == folderData.uuid && noteData.is_deleted == Delete.No ? ++count : count + "sys_def_other_uuid": (noteData: NoteData) => { + noteData.folder_uuid == folderData.uuid && noteData.is_deleted == Delete.No ? ++count : count; } } if (folderData.uuid == SysDefFolderUuid.AllNotes || folderData.folder_type == FolderType.FeatureDef) { @@ -184,7 +191,7 @@ export class NoteUtil { // delete note from db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, allNoteDataArray[index].uuid) - RdbStoreUtil.delete(predicates_note, null) + RdbStoreUtil.delete(predicates_note, null); allNoteDataArray.splice(index, 1); } index++ @@ -202,25 +209,25 @@ export class NoteUtil { LogUtil.info(TAG, "folderUuid " + folderUuid) this.autoDeleteNote(allNoteDataArray) let noteDataArray: NoteData[] = []; - let func = (noteData) => noteDataArray.push(noteData) - const folderTextMap = { - "sys_def_allNotes_uuid": (noteData) => { - noteData.is_deleted == Delete.No ? func(noteData) : null + let func = (noteData: NoteData) => noteDataArray.push(noteData); + const folderTextMap: Record void> = { + "sys_def_allNotes_uuid": (noteData: NoteData) => { + noteData.is_deleted == Delete.No ? func(noteData) : null; }, - "sys_def_recentDeletes_uuid": (noteData) => { - noteData.is_deleted == Delete.Yes ? func(noteData) : null + "sys_def_recentDeletes_uuid": (noteData: NoteData) => { + noteData.is_deleted == Delete.Yes ? func(noteData) : null; }, - "sys_def_myFavorites_uuid": (noteData) => { - noteData.is_favorite == Favorite.Yes && noteData.is_deleted == Delete.No ? func(noteData) : null + "sys_def_myFavorites_uuid": (noteData: NoteData) => { + noteData.is_favorite == Favorite.Yes && noteData.is_deleted == Delete.No ? func(noteData) : null; }, - "sys_def_other_uuid": (noteData) => { - noteData.folder_uuid == folderUuid && noteData.is_deleted == Delete.No ? func(noteData) : null + "sys_def_other_uuid": (noteData: NoteData) => { + noteData.folder_uuid == folderUuid && noteData.is_deleted == Delete.No ? func(noteData) : null; }, } if (folderUuid == SysDefFolderUuid.AllNotes || folderUuid == SysDefFolderUuid.RecentDeletes || folderUuid == SysDefFolderUuid.MyFavorites) { - allNoteDataArray.forEach(folderTextMap[folderUuid]) + allNoteDataArray.forEach(folderTextMap[folderUuid]); } else { - allNoteDataArray.forEach(folderTextMap["sys_def_other_uuid"]) + allNoteDataArray.forEach(folderTextMap.sys_def_other_uuid); } // Sort priority: 1、Top or not 2、created time noteDataArray.sort((noteItemLeft: NoteData, noteItemRight: NoteData) => { @@ -240,14 +247,14 @@ export class NoteUtil { * @param folderUuid * @return NoteData */ - getFirstNoteData(allNoteDataArray: NoteData[], folderUuid: string): NoteData { + getFirstNoteData(allNoteDataArray: NoteData[], folderUuid: string): NoteData | undefined { let noteDataArray: NoteData[] = this.getNoteDataArray(allNoteDataArray, folderUuid); - LogUtil.info(TAG, "get noteDataArray size " + noteDataArray.length.toString()) + LogUtil.info(TAG, "get noteDataArray size " + noteDataArray.length.toString()); if (noteDataArray.length == 0) { - LogUtil.info(TAG, "get noteDataArray empty") - return undefined; + LogUtil.info(TAG, "get noteDataArray empty"); + return; } - return noteDataArray == undefined ? null : noteDataArray[0] + return noteDataArray == undefined ? undefined : noteDataArray[0]; } /** @@ -267,23 +274,36 @@ export class NoteUtil { deleteEmptyNote(selectedNoteData: NoteData, AllNoteArray: NoteData[], controllerShow: WebController): boolean { if (selectedNoteData.title == "标题" && selectedNoteData.content_text == "") { // delete note from db - noteUtil.removeNoteData(AllNoteArray, selectedNoteData.uuid) - LogUtil.info(TAG, "delete note:" + selectedNoteData.uuid) - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, selectedNoteData.uuid) - RdbStoreUtil.delete(predicates_note, null) - LogUtil.info(TAG, "delete note success:" + selectedNoteData.uuid) - return true + noteUtil.removeNoteData(AllNoteArray, selectedNoteData.uuid); + LogUtil.info(TAG, "delete note:" + selectedNoteData.uuid); + let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicates_note.equalTo(NoteTableColumn.Uuid, selectedNoteData.uuid); + RdbStoreUtil.delete(predicates_note, null); + LogUtil.info(TAG, "delete note success:" + selectedNoteData.uuid); + return true; } - return false + return false; } refreshAll() { - let isRefresh = AppStorage.Get('isUpdate') - AppStorage.Set('isUpdate',!isRefresh) + let isRefresh: boolean = AppStorage.Get('isUpdate')!; + AppStorage.Set('isUpdate',!isRefresh); } + + /** + * Format conversion + * @param initContent + */ + contrastInitType(initContent: string): string { + let base64regex = new RegExp('/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/'); + if (!base64regex.test(initContent)) { + const inputBuffer = buffer.from(initContent, 'utf-8'); + initContent = inputBuffer.toString('base64'); + } + return initContent; + }; } -let noteUtil = new NoteUtil() +let noteUtil = new NoteUtil(); -export default noteUtil as NoteUtil \ No newline at end of file +export default noteUtil as NoteUtil; \ No newline at end of file diff --git a/common/utils/src/main/ets/default/baseUtil/OperationUtils.ets b/common/utils/src/main/ets/default/baseUtil/OperationUtils.ets index cf462b6..10b3b67 100644 --- a/common/utils/src/main/ets/default/baseUtil/OperationUtils.ets +++ b/common/utils/src/main/ets/default/baseUtil/OperationUtils.ets @@ -13,125 +13,124 @@ * limitations under the License. */ -import {LogUtil} from './LogUtil' -import {MediaLibraryAccess} from '../access/MediaLibraryAccess'; +import { LogUtil } from './LogUtil'; +import { MediaLibraryAccess } from '../access/MediaLibraryAccess'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; import fileio from '@ohos.fileio'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; +import common from '@ohos.app.ability.common'; -const TAG = "OperationUtils" -export class OperationUtils { - - - async copy(uri: string):Promise { - try { - let numId = this.getIdByUri(uri) - var context = globalThis.noteContext - let fileAsset = await this.getFileAssetById(numId,context); - if (fileAsset == null || fileAsset == undefined) { - LogUtil.warn(TAG, "Failed to get fileAsset") - return; - } - - let fd = await MediaLibraryAccess.openAsset('RW', fileAsset); - if (fd <= 0) { - LogUtil.warn(TAG, "fd is invaild") - return; - } - LogUtil.info(TAG, 'copyAsset read end!') +const TAG: string = 'OperationUtils'; +let noteContext = AppStorage.Get('noteContext')!; - // 通过Uri拷贝图片到指定指定的包路径下 - // 1、获取本地路径 - var dir = context.filesDir - // 2、生成本地文件名 - var time = new Date().getTime() - var imagePath = dir + "/" + time.toString() + "_note" + ".jpg" - // 3、拷贝 - await fileio.copyFile(fd, imagePath) - // 4、关闭安fd,Asset - await MediaLibraryAccess.closeAsset(fd, fileAsset); - } catch (error) { - LogUtil.info(TAG, "create error: " + error); - return; - } - LogUtil.debug(TAG, 'copy end'); - - return imagePath.toString() +export class OperationUtils { + async copy(uri: string): Promise { + let imagePath: string = ''; + try { + let context = noteContext; + let fileAsset = await this.getFileAssetById(uri, context); + if (fileAsset == null || fileAsset == undefined) { + LogUtil.warn(TAG, "Failed to get fileAsset"); + return; + } + + let fd = await MediaLibraryAccess.openAsset('RW', fileAsset); + if (fd !== undefined && fd <= 0) { + LogUtil.warn(TAG, "fd is invaild"); + return; + } + LogUtil.info(TAG, 'copyAsset read end!'); + + // 通过Uri拷贝图片到指定指定的包路径下 + // 1、获取本地路径 + let dir = context.filesDir; + // 2、生成本地文件名 + let time = new Date().getTime(); + imagePath = dir + '/' + time.toString() + '_note' + '.jpg'; + // 3、拷贝 + await fileio.copyFile(fd, imagePath); + // 4、关闭fd,Asset + await MediaLibraryAccess.closeAsset(fd!, fileAsset); + } catch (error) { + LogUtil.error(TAG, "create error: " + error); } - - saveImageData(dataArray: Uint8Array, imageType: string): string { - try { - var context = globalThis.noteContext - // 1、获取本地路径 - var dir = context.filesDir - var time = new Date().getTime() - var imagePath = dir + "/" + time.toString() + "_note" + "." + imageType - let fd = fileio.openSync(imagePath, 0o100 | 0o2, 0o666) - // 3、把image数据写入本地图片文件中 - fileio.writeSync(fd, dataArray.buffer) - } catch (error) { - LogUtil.info(TAG, "create error: " + error); - return; - } - LogUtil.info(TAG, 'save image end'); - - return imagePath.toString() + LogUtil.debug(TAG, 'copy end'); + return imagePath.toString(); + } + + saveImageData(dataArray: Uint8Array, imageType: string): string { + let imagePath: string = ''; + try { + let context = noteContext; + // 1、获取本地路径 + let dir = context.filesDir; + let time = new Date().getTime(); + imagePath = dir + '/' + time.toString() + '_note' + '.' + imageType; + let fd = fileio.openSync(imagePath, 0o100 | 0o2, 0o666); + // 3、把image数据写入本地图片文件中 + fileio.writeSync(fd, dataArray.buffer); + } catch (error) { + LogUtil.error(TAG, "create error: " + error); } - - saveImage(imageData: string, imageType: string): string { - try { - var context = globalThis.noteContext - // 1、获取本地路径 - var dir = context.filesDir - // 2、生成本地文件名 - var time = new Date().getTime() - var imagePath = dir + "/" + time.toString() + "_note" + "." + imageType - let fd = fileio.openSync(imagePath, 0o100 | 0o2, 0o666) - let arrayBuffer = new ArrayBuffer(imageData.length) - let ia = new Uint8Array(arrayBuffer) - for(let i = 0; i < imageData.length; i++) { - ia[i] = imageData.charCodeAt(i) - } - - // 3、把image数据写入本地图片文件中 - fileio.writeSync(fd, ia.buffer) - - } catch (error) { - LogUtil.info(TAG, "create error: " + error); - return; - } - LogUtil.debug(TAG, 'save image end'); - - return imagePath.toString() + LogUtil.info(TAG, 'save image end'); + return imagePath.toString(); + } + + saveImage(imageData: string, imageType: string): string { + let imagePath: string = ''; + try { + let context = noteContext; + // 1、获取本地路径 + let dir = context.filesDir; + // 2、生成本地文件名 + let time = new Date().getTime(); + imagePath = dir + '/' + time.toString() + '_note' + '.' + imageType; + let fd = fileio.openSync(imagePath, 0o100 | 0o2, 0o666); + let arrayBuffer = new ArrayBuffer(imageData.length); + let ia = new Uint8Array(arrayBuffer); + for (let i = 0; i < imageData.length; i++) { + ia[i] = imageData.charCodeAt(i); + } + // 3、把image数据写入本地图片文件中 + fileio.writeSync(fd, ia.buffer); + } catch (error) { + LogUtil.error(TAG, "create error: " + error); } - - getIdByUri(uri:string): number { - let srcIndex = uri.lastIndexOf('/'); - let srcEnd = uri.length; - let srcId = uri.substring(srcIndex + 1, srcEnd); - let numId = new Number(srcId); - LogUtil.debug(TAG, `getIdByUri numId: ${numId}`); - return numId.valueOf(); + LogUtil.debug(TAG, 'save image end'); + return imagePath.toString(); + } + + getIdByUri(uri: string): number { + let srcIndex = uri.lastIndexOf('/'); + let srcEnd = uri.length; + let srcId = uri.substring(srcIndex + 1, srcEnd); + let numId = new Number(srcId); + LogUtil.debug(TAG, `getIdByUri numId: ${numId}`); + return numId.valueOf(); + } + + async getFileAssetById(imagePath: string, context: common.UIAbilityContext) { + LogUtil.info(TAG, 'getFileAssetById', imagePath); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOpt: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates.equalTo('uri', imagePath) } - async getFileAssetById(id,context){ - LogUtil.info(TAG, 'getFileAssetById', id); - let fetchOpt = { - selections : 'file_id =?', - selectionArgs : [`${id}`], - } - - try { - let result = await MediaLibraryAccess.getFirstObject(fetchOpt,context); - if (result == null) { - LogUtil.info(TAG, 'getFileAssetByUri fail'); - return null; - } - return result.obj; - } catch (error) { - LogUtil.info(TAG, 'getFileAssetById error'); - return null; - } + try { + let result = await MediaLibraryAccess.getFirstObject(fetchOpt, context); + if (result == null) { + LogUtil.info(TAG, 'getFileAssetByUri fail'); + return null; + } + return result.obj; + } catch (error) { + LogUtil.error(TAG, 'getFileAssetById error'); + return null; } + } } let mOperationUtils = new OperationUtils(); + export default mOperationUtils as OperationUtils; diff --git a/common/utils/src/main/ets/default/baseUtil/RdbStoreUtil.ets b/common/utils/src/main/ets/default/baseUtil/RdbStoreUtil.ets index 3de444c..2ddf915 100644 --- a/common/utils/src/main/ets/default/baseUtil/RdbStoreUtil.ets +++ b/common/utils/src/main/ets/default/baseUtil/RdbStoreUtil.ets @@ -13,7 +13,6 @@ * limitations under the License. */ -import { atob } from 'js-base64' import fileio from '@ohos.fileio' import { LogUtil } from './LogUtil' import FolderUtil from './FolderUtil' @@ -26,316 +25,329 @@ import { TableName, FolderTableColumn, NoteTableColumn, - SysDefFolderUuid -} from '../model/databaseModel/EnumData' -import relationalStore from '@ohos.data.relationalStore' + SysDefFolderUuid, + FolderType, + Delete, + Favorite, + NoteType, + Top +} from '../model/databaseModel/EnumData'; +import relationalStore from '@ohos.data.relationalStore'; +import util from '@ohos.util'; +import { BusinessError, Callback } from '@ohos.base'; +import common from '@ohos.app.ability.common'; -const TAG = "RdbStoreUtil" +const TAG: string = 'RdbStoreUtil'; -const FileMaxSize: number = 20 * 1024 * 1024 +const FileMaxSize: number = 20 * 1024 * 1024; +let rdbStore = AppStorage.Get('rdbStore'); /** * db instance */ - -export default { +class RdbStoreUtil { /** * create db and table */ - createRdbStore(context) { - relationalStore.getRdbStore(context, SysDefData.dbInfo.db_name) - .then(async (store) => { - // add sys-def folder and note to AppStorage - let folderDataArray = [] - let sysDefFolderArray = [SysDefData.sys_def_allNotes, SysDefData.sys_def_unClassified, - SysDefData.sys_def_myFavorites, SysDefData.sys_def_recentDeletes, - SysDefData.sys_def_personal, SysDefData.sys_def_life, SysDefData.sys_def_work] - sysDefFolderArray.forEach((sysDefFolder) => { - let folderData = new FolderData(sysDefFolder.id, sysDefFolder.name, sysDefFolder.uuid, sysDefFolder.color, - sysDefFolder.folder_type, sysDefFolder.is_deleted, sysDefFolder.created_time, - sysDefFolder.modified_time) - folderDataArray.push(folderData) - }) - LogUtil.info(TAG, "folderDataArray[sysdef] : " + folderDataArray.length) + createRdbStore(context: common.UIAbilityContext) { + try { + relationalStore.getRdbStore(context, SysDefData.dbInfo.db_name) + .then(async (store) => { + // add sys-def folder and note to AppStorage + let folderDataArray: FolderData[] = []; + let sysDefFolderArray = [SysDefData.sys_def_allNotes, SysDefData.sys_def_unClassified, + SysDefData.sys_def_myFavorites, SysDefData.sys_def_recentDeletes, + SysDefData.sys_def_personal, SysDefData.sys_def_life, SysDefData.sys_def_work]; + sysDefFolderArray.forEach((sysDefFolder) => { + let folderData = new FolderData(sysDefFolder.id as number, sysDefFolder.name as string, sysDefFolder.uuid as string, sysDefFolder.color as string, + sysDefFolder.folder_type as FolderType, sysDefFolder.is_deleted as Delete, sysDefFolder.created_time as number, + sysDefFolder.modified_time as number); + folderDataArray.push(folderData); + }) + LogUtil.info(TAG, "folderDataArray[sysdef] : " + folderDataArray.length); - let noteDataArray = [] - let sysDefNoteArray = [SysDefData.sys_def_note1, SysDefData.sys_def_note2, - SysDefData.sys_def_note3, SysDefData.sys_def_note4] - sysDefNoteArray.forEach((sysDefNote) => { - let noteData = new NoteData(sysDefNote.id, sysDefNote.title, sysDefNote.uuid, sysDefNote.folder_uuid, sysDefNote.content_text, - sysDefNote.content_img, sysDefNote.note_type, sysDefNote.is_top, sysDefNote.is_favorite, - sysDefNote.is_deleted, sysDefNote.created_time, sysDefNote.modified_time, sysDefNote.deleted_time, sysDefNote.slider_value) - noteDataArray.push(noteData) - }) - LogUtil.info(TAG, "noteDataArray[sysdef] : " + noteDataArray.length) + let noteDataArray: NoteData[] = []; + let sysDefNoteArray = [SysDefData.sys_def_note1, SysDefData.sys_def_note2, + SysDefData.sys_def_note3, SysDefData.sys_def_note4]; + sysDefNoteArray.forEach((sysDefNote) => { + let noteData = new NoteData(sysDefNote.id as number, sysDefNote.title as string, sysDefNote.uuid as string, sysDefNote.folder_uuid as string, sysDefNote.content_text as string, + sysDefNote.content_img as string, sysDefNote.note_type as NoteType, sysDefNote.is_top as Top, sysDefNote.is_favorite as Favorite, + sysDefNote.is_deleted as Delete, sysDefNote.created_time as number, sysDefNote.modified_time as number, sysDefNote.deleted_time as number, sysDefNote.slider_value as number); + noteDataArray.push(noteData); + }) + LogUtil.info(TAG, "noteDataArray[sysdef] : " + noteDataArray.length) - AppStorage.SetOrCreate('AllFolderArray', folderDataArray) - AppStorage.SetOrCreate('AllNoteArray', noteDataArray) - LogUtil.info(TAG, "AppStorage[sysdef] set AllFolderArray and AllNoteArray success") + AppStorage.SetOrCreate('AllFolderArray', folderDataArray) + AppStorage.SetOrCreate('AllNoteArray', noteDataArray) + LogUtil.info(TAG, "AppStorage[sysdef] set AllFolderArray and AllNoteArray success") - // save continue data - let isContinue = AppStorage.Get('IsContinue'); - LogUtil.info(TAG, "createRdbStore, isContinue is " + isContinue) - if (isContinue) { - let continueNote: string = AppStorage.Get('ContinueNote') - let continueSection = AppStorage.Get('ContinueSection') - let noteObj = JSON.parse(continueNote) - let noteData = new NoteData(noteObj.uuid, noteObj.title, noteObj.uuid, noteObj.folder_uuid, - noteObj.content_text, noteObj.content_img, noteObj.note_type, noteObj.is_top, noteObj.is_favorite, - noteObj.is_deleted, noteObj.created_time, noteObj.modified_time, noteObj.deleted_time, noteObj.slider_value) + // save continue data + let isContinue = AppStorage.Get('IsContinue'); + LogUtil.info(TAG, "createRdbStore, isContinue is " + isContinue) + if (isContinue) { + let continueNote: string = AppStorage.Get('ContinueNote')!; + let continueSection: number = AppStorage.Get('ContinueSection')!; + let noteObj: NoteData = JSON.parse(continueNote); + let noteData: NoteData = new NoteData(noteObj.id, noteObj.title, noteObj.uuid, noteObj.folder_uuid, + noteObj.content_text, noteObj.content_img, noteObj.note_type, noteObj.is_top, noteObj.is_favorite, + noteObj.is_deleted, noteObj.created_time, noteObj.modified_time, noteObj.deleted_time, noteObj.slider_value); - // save img to FileDir - LogUtil.info(TAG, "createRdbStore, save img to FileDir") - let imgNameArray = this.getImgNameFromHtml(noteData) - imgNameArray.forEach((imgName: string) => { - this.writeToFileDir(imgName) - }) + // save img to FileDir + LogUtil.info(TAG, "createRdbStore, save img to FileDir") + let imgNameArray = this.getImgNameFromHtml(noteData) + imgNameArray.forEach((imgName: string) => { + this.writeToFileDir(imgName) + }) - // if not exit this note - let exist = false - let folderUuid = "" - for (let note of noteDataArray) { - if (noteData.created_time == note.created_time) { - exist = true - folderUuid = note.folder_uuid - break - } - } - LogUtil.info(TAG, "createRdbStore, exist : " + exist) - if (!exist) { - // 迁移过来的笔记在本地不存在,则保存在未分类文件夹 - noteData.folder_uuid = SysDefFolderUuid.UnClassified - noteDataArray.push(noteData) - AppStorage.SetOrCreate('AllNoteArray', noteDataArray) - this.insert(TableName.NoteTable, noteData.toNoteObject(), null) - AppStorage.SetOrCreate('Folder', FolderUtil.getFolderData(folderDataArray, SysDefFolderUuid.UnClassified)) - } else { - // 迁移过来的笔记在本地存在,则进行修改 - for (let i = 0; i < noteDataArray.length; i++) { - if (noteData.created_time == noteDataArray[i].created_time) { - noteDataArray[i] = noteData - LogUtil.info(TAG, "createRdbStore, update noteData in noteDataArray success") + // if not exit this note + let exist = false + let folderUuid = "" + for (let note of noteDataArray) { + if (noteData.created_time == note.created_time) { + exist = true + folderUuid = note.folder_uuid break } } - let predicates_note = this.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.CreatedTime, noteData.created_time) - this.update(noteData.toNoteObject(), predicates_note, null) - AppStorage.SetOrCreate('Folder', FolderUtil.getFolderData(folderDataArray, folderUuid)) - } - AppStorage.SetOrCreate('Note', noteData) - AppStorage.SetOrCreate('ContinueNote', JSON.stringify(noteData.toNoteObject())) - AppStorage.SetOrCreate('Section', continueSection) - AppStorage.SetOrCreate('NewNote', noteData) - } else { - LogUtil.info(TAG, "createRdbStore, IsContinue false") - AppStorage.SetOrCreate('Folder', AppStorage.Get('AllFolderArray')[0]) - let note = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), SysDefFolderUuid.AllNotes) - AppStorage.SetOrCreate('Note', note) - if (note) { - AppStorage.SetOrCreate('ContinueNote', JSON.stringify(note.toNoteObject())) + LogUtil.info(TAG, "createRdbStore, exist : " + exist) + if (!exist) { + // 迁移过来的笔记在本地不存在,则保存在未分类文件夹 + noteData.folder_uuid = SysDefFolderUuid.UnClassified + noteDataArray.push(noteData) + AppStorage.SetOrCreate('AllNoteArray', noteDataArray) + this.insert(TableName.NoteTable, noteData.toNoteObject(), null); + AppStorage.SetOrCreate('Folder', FolderUtil.getFolderData(folderDataArray, SysDefFolderUuid.UnClassified)) + } else { + // 迁移过来的笔记在本地存在,则进行修改 + for (let i = 0; i < noteDataArray.length; i++) { + if (noteData.created_time == noteDataArray[i].created_time) { + noteDataArray[i] = noteData + LogUtil.info(TAG, "createRdbStore, update noteData in noteDataArray success") + break + } + } + let predicates_note = this.getRdbPredicates(TableName.NoteTable) + predicates_note.equalTo(NoteTableColumn.CreatedTime, noteData.created_time) + this.update(noteData.toNoteObject(), predicates_note, null); + AppStorage.SetOrCreate('Folder', FolderUtil.getFolderData(folderDataArray, folderUuid)) + } + AppStorage.SetOrCreate('Note', noteData) + AppStorage.SetOrCreate('ContinueNote', JSON.stringify(noteData.toNoteObject())) + AppStorage.SetOrCreate('Section', continueSection) + AppStorage.SetOrCreate('NewNote', noteData) + } else { + LogUtil.info(TAG, "createRdbStore, IsContinue false") + AppStorage.SetOrCreate('Folder', (AppStorage.Get('AllFolderArray') as FolderData[])[0]); + let note = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, SysDefFolderUuid.AllNotes); + AppStorage.SetOrCreate('Note', note) + if (note) { + AppStorage.SetOrCreate('ContinueNote', JSON.stringify(note.toNoteObject())) + } + AppStorage.SetOrCreate('Section', 3) } - AppStorage.SetOrCreate('Section', 3) - } - AppStorage.SetOrCreate('DBQueryFinished', 1) - LogUtil.info(TAG, "createRdbStore, set DBQueryFinished 1") - LogUtil.info(TAG, "createRdbStore, store is " + store) - globalThis.rdbStore = store - // create table - await globalThis.rdbStore.executeSql(TableSql.FolderTableSQL, null) - await globalThis.rdbStore.executeSql(TableSql.NoteTableSQL, null) - await globalThis.rdbStore.executeSql(TableSql.AttachmentTableSQL, null) - await globalThis.rdbStore.executeSql(TableSql.FormTableSQL, null) - LogUtil.info(TAG, "create table success") - // insert system defined folder - await globalThis.rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_allNotes) - await globalThis.rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_unClassified) - await globalThis.rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_myFavorites) - await globalThis.rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_recentDeletes) - await globalThis.rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_personal) - await globalThis.rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_life) - await globalThis.rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_work) - LogUtil.info(TAG, "insert system defined folder success") - // insert system defined note and attachment - await globalThis.rdbStore.insert(TableName.NoteTable, SysDefData.sys_def_note1) - await globalThis.rdbStore.insert(TableName.NoteTable, SysDefData.sys_def_note2) - await globalThis.rdbStore.insert(TableName.NoteTable, SysDefData.sys_def_note3) - await globalThis.rdbStore.insert(TableName.NoteTable, SysDefData.sys_def_note4) - LogUtil.info(TAG, "insert system defined note and attachment success") - }) - .catch((err) => { - LogUtil.warn(TAG, "createRdbStore, error : " + err) - }) - }, + AppStorage.SetOrCreate('DBQueryFinished', 1) + LogUtil.info(TAG, "createRdbStore, set DBQueryFinished 1") + LogUtil.info(TAG, "createRdbStore, store is " + store) + rdbStore = store; + + // create table + rdbStore.executeSql(TableSql.FolderTableSQL.toString(), null); + rdbStore.executeSql(TableSql.NoteTableSQL.toString(), null); + rdbStore.executeSql(TableSql.AttachmentTableSQL.toString(), null); + rdbStore.executeSql(TableSql.FormTableSQL.toString(), null); + LogUtil.info(TAG, "create table success") + // insert system defined folder + await rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_allNotes); + await rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_unClassified); + await rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_myFavorites); + await rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_recentDeletes); + await rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_personal); + await rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_life); + await rdbStore.insert(TableName.FolderTable, SysDefData.sys_def_work); + LogUtil.info(TAG, "insert system defined folder success") + // insert system defined note and attachment + await rdbStore.insert(TableName.NoteTable, SysDefData.sys_def_note1); + await rdbStore.insert(TableName.NoteTable, SysDefData.sys_def_note2); + await rdbStore.insert(TableName.NoteTable, SysDefData.sys_def_note3); + await rdbStore.insert(TableName.NoteTable, SysDefData.sys_def_note4); + LogUtil.info(TAG, "insert system defined note and attachment success") + }) + } catch (err) { + LogUtil.warn(TAG, "createRdbStore, error : " + err) + } + } /** * query folders and notes from the database, then save them to the AppStorage. */ - initAppStorage(context) { - let folderDataArray = [] - let noteDataArray = [] - relationalStore.getRdbStore(context, SysDefData.dbInfo.db_name) - .then(async (store) => { - LogUtil.info(TAG, "initAppStorage, store is " + store) - globalThis.rdbStore = store - // query folder - let columns_folder = [] - let predicates_folder = new relationalStore.RdbPredicates(TableName.FolderTable) - let resultSet_folder = await globalThis.rdbStore.query(predicates_folder, columns_folder) - while (resultSet_folder.goToNextRow()) { - let id = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.Id)) - let name = resultSet_folder.getString(resultSet_folder.getColumnIndex(FolderTableColumn.Name)) - let uuid = resultSet_folder.getString(resultSet_folder.getColumnIndex(FolderTableColumn.Uuid)) - let color = resultSet_folder.getString(resultSet_folder.getColumnIndex(FolderTableColumn.Color)) - let folder_type = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.FolderType)) - let is_deleted = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.IsDeleted)) - let created_time = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.CreatedTime)) - let modified_time = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.ModifiedTime)) - let folderData = new FolderData(id, name, uuid, color, folder_type, is_deleted, created_time, modified_time) - folderDataArray.push(folderData) - } - resultSet_folder.close(); - LogUtil.info(TAG, "folderDataArray[query] : " + folderDataArray.length) - // query note - let columns_note = [] - let predicates_note = new relationalStore.RdbPredicates(TableName.NoteTable) - let resultSet_note = await globalThis.rdbStore.query(predicates_note, columns_note) - while (resultSet_note.goToNextRow()) { - let id = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.Id)) - let title = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.Title)) - let uuid = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.Uuid)) - let folder_uuid = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.FolderUuid)) - // 暂时规避备忘录二次打开白屏问题,后续数据库解决 - let content_text = ''; - let content_img = ''; - try { - content_text = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.ContentText)) - content_img = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.ContentImg)) - } catch (err) { - LogUtil.error(TAG, "initAppStorage, content_img = error : " + err) - } - let noteType = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.NoteType)) - let is_top = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.IsTop)) - let is_favorite = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.IsFavorite)) - let is_deleted = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.IsDeleted)) - let created_time = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.CreatedTime)) - let modified_time = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.ModifiedTime)) - let deleted_time = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.DeletedTime)) - let slider_value = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.SliderValue)) - let noteData = new NoteData(id, title, uuid, folder_uuid, content_text, content_img, noteType, is_top, is_favorite, is_deleted, created_time, modified_time, deleted_time, slider_value) - noteDataArray.push(noteData) - } - resultSet_note.close(); - LogUtil.info(TAG, "noteDataArray[query] : " + noteDataArray.length) - if (folderDataArray === null || folderDataArray === undefined || folderDataArray.length === 0) { - LogUtil.info(TAG, "folderDataArray is null") - let sysDefFolderArray = [SysDefData.sys_def_allNotes, SysDefData.sys_def_unClassified, - SysDefData.sys_def_myFavorites, SysDefData.sys_def_recentDeletes, - SysDefData.sys_def_personal, SysDefData.sys_def_life, SysDefData.sys_def_work] - sysDefFolderArray.forEach((sysDefFolder) => { - let folderData = new FolderData(sysDefFolder.id, sysDefFolder.name, sysDefFolder.uuid, sysDefFolder.color, - sysDefFolder.folder_type, sysDefFolder.is_deleted, sysDefFolder.created_time, - sysDefFolder.modified_time) + initAppStorage(context: common.UIAbilityContext) { + let folderDataArray: FolderData[] = []; + let noteDataArray: NoteData[] = []; + try { + relationalStore.getRdbStore(context, SysDefData.dbInfo.db_name) + .then(async (store) => { + LogUtil.info(TAG, "initAppStorage, store is " + store) + rdbStore = store; + // query folder + let columns_folder: string[] = []; + let predicates_folder = new relationalStore.RdbPredicates(TableName.FolderTable) + let resultSet_folder: relationalStore.ResultSet = await rdbStore.query(predicates_folder, columns_folder); + while (resultSet_folder.goToNextRow()) { + let id = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.Id)) + let name = resultSet_folder.getString(resultSet_folder.getColumnIndex(FolderTableColumn.Name)) + let uuid = resultSet_folder.getString(resultSet_folder.getColumnIndex(FolderTableColumn.Uuid)) + let color = resultSet_folder.getString(resultSet_folder.getColumnIndex(FolderTableColumn.Color)) + let folder_type = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.FolderType)) + let is_deleted = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.IsDeleted)) + let created_time = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.CreatedTime)) + let modified_time = resultSet_folder.getLong(resultSet_folder.getColumnIndex(FolderTableColumn.ModifiedTime)) + let folderData = new FolderData(id, name, uuid, color, folder_type, is_deleted, created_time, modified_time) folderDataArray.push(folderData) - }) + } + resultSet_folder.close(); LogUtil.info(TAG, "folderDataArray[query] : " + folderDataArray.length) - } - AppStorage.SetOrCreate('AllFolderArray', folderDataArray) - AppStorage.SetOrCreate('AllNoteArray', noteDataArray) - LogUtil.info(TAG, "AppStorage[query] set AllFolderArray and AllNoteArray success") + // query note + let columns_note: string[] = []; + let predicates_note = new relationalStore.RdbPredicates(TableName.NoteTable); + let resultSet_note: relationalStore.ResultSet = await rdbStore.query(predicates_note, columns_note); + while (resultSet_note.goToNextRow()) { + let id = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.Id)) + let title = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.Title)) + let uuid = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.Uuid)) + let folder_uuid = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.FolderUuid)) + // 暂时规避备忘录二次打开白屏问题,后续数据库解决 + let content_text = ''; + let content_img = ''; + try { + content_text = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.ContentText)) + content_img = resultSet_note.getString(resultSet_note.getColumnIndex(NoteTableColumn.ContentImg)) + } catch (err) { + LogUtil.error(TAG, "initAppStorage, content_img = error : " + err) + } + let noteType = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.NoteType)) + let is_top = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.IsTop)) + let is_favorite = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.IsFavorite)) + let is_deleted = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.IsDeleted)) + let created_time = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.CreatedTime)) + let modified_time = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.ModifiedTime)) + let deleted_time = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.DeletedTime)) + let slider_value = resultSet_note.getLong(resultSet_note.getColumnIndex(NoteTableColumn.SliderValue)) + let noteData = new NoteData(id, title, uuid, folder_uuid, content_text, content_img, noteType, is_top, is_favorite, is_deleted, created_time, modified_time, deleted_time, slider_value) + noteDataArray.push(noteData) + } + resultSet_note.close(); + LogUtil.info(TAG, "noteDataArray[query] : " + noteDataArray.length) + if (folderDataArray === null || folderDataArray === undefined || folderDataArray.length === 0) { + LogUtil.info(TAG, "folderDataArray is null") + let sysDefFolderArray = [SysDefData.sys_def_allNotes, SysDefData.sys_def_unClassified, + SysDefData.sys_def_myFavorites, SysDefData.sys_def_recentDeletes, + SysDefData.sys_def_personal, SysDefData.sys_def_life, SysDefData.sys_def_work]; + sysDefFolderArray.forEach((sysDefFolder) => { + let folderData = new FolderData(sysDefFolder.id as number, sysDefFolder.name as string, sysDefFolder.uuid as string, sysDefFolder.color as string, + sysDefFolder.folder_type as FolderType, sysDefFolder.is_deleted as Delete, sysDefFolder.created_time as number, + sysDefFolder.modified_time as number); + folderDataArray.push(folderData) + }) + LogUtil.info(TAG, "folderDataArray[query] : " + folderDataArray.length) + } + AppStorage.SetOrCreate('AllFolderArray', folderDataArray) + AppStorage.SetOrCreate('AllNoteArray', noteDataArray) + LogUtil.info(TAG, "AppStorage[query] set AllFolderArray and AllNoteArray success") - // save continue data - let isContinue = AppStorage.Get('IsContinue'); - LogUtil.info(TAG, "initAppStorage, isContinue is " + isContinue) - if (isContinue) { - let continueNote: string = AppStorage.Get('ContinueNote') - let continueSection = AppStorage.Get('ContinueSection') + // save continue data + let isContinue = AppStorage.Get('IsContinue'); + LogUtil.info(TAG, "initAppStorage, isContinue is " + isContinue) + if (isContinue) { + let continueNote: string = AppStorage.Get('ContinueNote')!; + let continueSection: number = AppStorage.Get('ContinueSection')!; - let noteObj = JSON.parse(continueNote) - let noteData = new NoteData(noteObj.uuid, noteObj.title, noteObj.uuid, noteObj.folder_uuid, - noteObj.content_text, noteObj.content_img, noteObj.note_type, noteObj.is_top, noteObj.is_favorite, - noteObj.is_deleted, noteObj.created_time, noteObj.modified_time, noteObj.deleted_time, noteObj.slider_value) + let noteObj: NoteData = JSON.parse(continueNote); + let noteData: NoteData = new NoteData(noteObj.id, noteObj.title, noteObj.uuid, noteObj.folder_uuid, + noteObj.content_text, noteObj.content_img, noteObj.note_type, noteObj.is_top, noteObj.is_favorite, + noteObj.is_deleted, noteObj.created_time, noteObj.modified_time, noteObj.deleted_time, noteObj.slider_value); - // save img to FileDir - LogUtil.info(TAG, "initAppStorage, save img to FileDir") - let imgNameArray = this.getImgNameFromHtml(noteData) - imgNameArray.forEach((imgName: string) => { - this.writeToFileDir(imgName) - }) + // save img to FileDir + LogUtil.info(TAG, "initAppStorage, save img to FileDir") + let imgNameArray = this.getImgNameFromHtml(noteData) + imgNameArray.forEach((imgName: string) => { + this.writeToFileDir(imgName) + }) - // if not exit this note - let exist = false - let folderUuid = "" - for (let note of noteDataArray) { - if (noteData.created_time == note.created_time) { - exist = true - folderUuid = note.folder_uuid - break - } - } - LogUtil.info(TAG, "initAppStorage, exist : " + exist) - if (!exist) { - // 迁移过来的笔记在本地不存在,则保存在未分类文件夹 - noteData.folder_uuid = SysDefFolderUuid.UnClassified - noteDataArray.push(noteData) - AppStorage.SetOrCreate('AllNoteArray', noteDataArray) - this.insert(TableName.NoteTable, noteData.toNoteObject(), null) - AppStorage.SetOrCreate('Folder', FolderUtil.getFolderData(folderDataArray, SysDefFolderUuid.UnClassified)) - } else { - // 迁移过来的笔记在本地存在,则进行修改 - for (let i = 0; i < noteDataArray.length; i++) { - if (noteData.created_time == noteDataArray[i].created_time) { - noteDataArray[i] = noteData - LogUtil.info(TAG, "initAppStorage, update noteData in noteDataArray success") + // if not exit this note + let exist = false + let folderUuid = "" + for (let note of noteDataArray) { + if (noteData.created_time == note.created_time) { + exist = true + folderUuid = note.folder_uuid break } } - let predicates_note = this.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.CreatedTime, noteData.created_time) - this.update(noteData.toNoteObject(), predicates_note, null) - AppStorage.SetOrCreate('Folder', FolderUtil.getFolderData(folderDataArray, folderUuid)) - } - AppStorage.SetOrCreate('Note', noteData) - AppStorage.SetOrCreate('ContinueNote', JSON.stringify(noteData.toNoteObject())) - AppStorage.SetOrCreate('Section', continueSection) - AppStorage.SetOrCreate('NewNote', noteData) - } else { - LogUtil.info(TAG, "initAppStorage, IsContinue false") - AppStorage.SetOrCreate('Folder', AppStorage.Get('AllFolderArray')[0]) - let note = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), SysDefFolderUuid.AllNotes) - AppStorage.SetOrCreate('Note', note) - if (note) { - AppStorage.SetOrCreate('ContinueNote', JSON.stringify(note.toNoteObject())) + LogUtil.info(TAG, "initAppStorage, exist : " + exist) + if (!exist) { + // 迁移过来的笔记在本地不存在,则保存在未分类文件夹 + noteData.folder_uuid = SysDefFolderUuid.UnClassified + noteDataArray.push(noteData) + AppStorage.SetOrCreate('AllNoteArray', noteDataArray) + this.insert(TableName.NoteTable, noteData.toNoteObject(), null); + AppStorage.SetOrCreate('Folder', FolderUtil.getFolderData(folderDataArray, SysDefFolderUuid.UnClassified)) + } else { + // 迁移过来的笔记在本地存在,则进行修改 + for (let i = 0; i < noteDataArray.length; i++) { + if (noteData.created_time == noteDataArray[i].created_time) { + noteDataArray[i] = noteData + LogUtil.info(TAG, "initAppStorage, update noteData in noteDataArray success") + break + } + } + let predicates_note = this.getRdbPredicates(TableName.NoteTable) + predicates_note.equalTo(NoteTableColumn.CreatedTime, noteData.created_time) + this.update(noteData.toNoteObject(), predicates_note, null); + AppStorage.SetOrCreate('Folder', FolderUtil.getFolderData(folderDataArray, folderUuid)) + } + AppStorage.SetOrCreate('Note', noteData) + AppStorage.SetOrCreate('ContinueNote', JSON.stringify(noteData.toNoteObject())) + AppStorage.SetOrCreate('Section', continueSection) + AppStorage.SetOrCreate('NewNote', noteData) + } else { + LogUtil.info(TAG, "initAppStorage, IsContinue false") + AppStorage.SetOrCreate('Folder', (AppStorage.Get('AllFolderArray') as FolderData[])[0]); + let note = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, SysDefFolderUuid.AllNotes); + AppStorage.SetOrCreate('Note', note) + if (note) { + AppStorage.SetOrCreate('ContinueNote', JSON.stringify(note.toNoteObject())) + } + AppStorage.SetOrCreate('Section', 3) } - AppStorage.SetOrCreate('Section', 3) - } - AppStorage.SetOrCreate('DBQueryFinished', 1) - LogUtil.info(TAG, "initAppStorage, set DBQueryFinished 1") - }) - .catch((err) => { - LogUtil.error(TAG, "initAppStorage, error : " + err) - }) - }, + AppStorage.SetOrCreate('DBQueryFinished', 1) + LogUtil.info(TAG, "initAppStorage, set DBQueryFinished 1") + }) + } catch (err) { + LogUtil.error(TAG, "initAppStorage, error : " + err) + } + } - getImgNameFromHtml(noteData: NoteData): any { - let newModuleName = "file://" + globalThis.noteContext.filesDir - let imgNameArray = [] + getImgNameFromHtml(noteData: NoteData): string[] { + let noteContext = AppStorage.Get('noteContext')!; + let newModuleName = 'file://' + noteContext.filesDir; + let imgNameArray: string[] = []; if (noteData.content_text == undefined || noteData.content_text == null || noteData.content_text == "") { LogUtil.info(TAG, "noteData.content_text is null or undefined") return imgNameArray } - let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/ - let html = "" + let base64regex = new RegExp('/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/'); + let html: string = ''; if (base64regex.test(noteData.content_text)) { - html = atob(noteData.content_text) + let base64 = new util.Base64Helper + html = base64.decodeSync(noteData.content_text).toString() } else { html = noteData.content_text } if (html == undefined || html == null || html == "") { return imgNameArray } - let imgReg = /]+>/g - let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i + let imgReg = new RegExp('/]+>/g'); + let srcReg = new RegExp('/src=[\'\"]?([^\'\"]*)[\'\"]?/i'); let imgArray = html.match(imgReg) if (imgArray != null) { let hasFirstImg: boolean = false @@ -358,12 +370,12 @@ export default { } } return imgNameArray - }, + } writeToFileDir(fileName: string) { LogUtil.info(TAG, "writeToFileDir fileName : " + fileName) - - let desPath = globalThis.noteContext.filesDir + "/" + fileName + let noteContext = AppStorage.Get('noteContext')!; + let desPath = noteContext.filesDir + '/' + fileName; LogUtil.info(TAG, "desPath : " + desPath) try { fileio.accessSync(desPath) @@ -372,10 +384,10 @@ export default { } catch (err) { LogUtil.warn(TAG, "desPath has not existed, need to write") } - let srcPath - let size + let srcPath: string = ''; + let size: number = 0; try { - srcPath = globalThis.noteContext.distributedFilesDir + "/" + fileName + srcPath = noteContext.distributedFilesDir + '/' + fileName; LogUtil.info(TAG, "srcPath : " + srcPath) size = fileio.statSync(srcPath).size LogUtil.info(TAG, "srcPath size : " + size) @@ -390,7 +402,7 @@ export default { } - let srcFd + let srcFd: number = 0; try { srcFd = fileio.openSync(srcPath, 0o0) LogUtil.info(TAG, "open srcPath success : " + srcFd) @@ -399,7 +411,7 @@ export default { return } - let desFd + let desFd: number = 0; try { desFd = fileio.openSync(desPath, 0o2 | 0o100, 0o400 | 0o200 | 0o040 | 0o020) LogUtil.info(TAG, "open desPath success : " + srcFd) @@ -417,7 +429,7 @@ export default { } catch (err) { LogUtil.warn(TAG, "read or write error : " + err) } - }, + } /** * insert @@ -425,32 +437,32 @@ export default { * @param valueBucket * @param callback */ - insert(tableName, valueBucket, callback) { - globalThis.rdbStore.insert(tableName, valueBucket).then((rowId) => { + insert(tableName: string, valueBucket: relationalStore.ValuesBucket, callback: Callback | null) { + rdbStore!.insert(tableName, valueBucket).then((rowId: number) => { LogUtil.info(TAG, "insert success, rowId is " + rowId) if (callback != null) { callback(rowId) } - }).catch((err) => { - LogUtil.warn(TAG, "insert error : " + err) + }).catch((err: BusinessError) => { + LogUtil.error(TAG, 'insert error:' + err); }) - }, + } /** * delete * @param predicates * @param callback */ - delete(predicates, callback) { - globalThis.rdbStore.delete(predicates).then((affectedRowCount) => { + delete(predicates: relationalStore.RdbPredicates, callback: Callback | null) { + rdbStore!.delete(predicates).then((affectedRowCount: number) => { LogUtil.info(TAG, "delete success, affectedRowCount is " + affectedRowCount) if (callback != null) { callback(affectedRowCount) } - }).catch((err) => { + }).catch((err: BusinessError) => { LogUtil.warn(TAG, "delete error : " + err) }) - }, + } /** * update @@ -458,19 +470,20 @@ export default { * @param predicates * @param callback */ - update(valueBucket, predicates, callback) { - if (!globalThis.rdbStore) { + update(valueBucket: relationalStore.ValuesBucket, predicates: relationalStore.RdbPredicates, + callback: Callback | null) { + if (!rdbStore) { return; } - globalThis.rdbStore.update(valueBucket, predicates).then((affectedRowCount) => { + rdbStore!.update(valueBucket, predicates).then((affectedRowCount: number) => { LogUtil.info(TAG, "update success, affectedRowCount is " + affectedRowCount) if (callback != null) { callback(affectedRowCount) } - }).catch((err) => { + }).catch((err: BusinessError) => { LogUtil.warn(TAG, "update error : " + err) }) - }, + } /** * query @@ -478,24 +491,24 @@ export default { * @param predicates * @param callback */ - query(columns, predicates, callback) { - globalThis.rdbStore.query(predicates, columns).then((resultSet) => { + query(columns: string[], predicates: relationalStore.RdbPredicates, callback: Callback) { + rdbStore!.query(predicates, columns).then((resultSet: relationalStore.ResultSet) => { LogUtil.info(TAG, "query success, row count : " + resultSet.rowCount) if (callback != null) { callback(resultSet) } - }).catch((err) => { + }).catch((err: BusinessError) => { LogUtil.warn(TAG, "query error : " + err) }) - }, + } /** * get RdbPredicates by table name * @param tableName */ - getRdbPredicates(tableName) { + getRdbPredicates(tableName: string) { return new relationalStore.RdbPredicates(tableName) - }, + } updataNoteImage(noteData: NoteData): string { let content_img = "" @@ -511,4 +524,6 @@ export default { LogUtil.info(TAG, "updataNoteImage, content_img : " + content_img) return content_img } -} \ No newline at end of file +} + +export default new RdbStoreUtil(); \ No newline at end of file diff --git a/common/utils/src/main/ets/default/model/NoteBaseData.ets b/common/utils/src/main/ets/default/model/NoteBaseData.ets index 3c2de8f..c24c3ab 100644 --- a/common/utils/src/main/ets/default/model/NoteBaseData.ets +++ b/common/utils/src/main/ets/default/model/NoteBaseData.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import NoteData from '../model/databaseModel/NoteData' +import NoteData from '../model/databaseModel/NoteData'; export const circleColorArray: string[] = [ "#f86d05", // 深红 @@ -36,7 +36,7 @@ export const fontColorArray: string[] = [ "#182431", //黑色 ] -export const unSelectedNoteBgColorMap = { +export const unSelectedNoteBgColorMap: Record = { "#f86d05": "#fff8eceb", "#ff7500": "#f3d9c4", "#ffbf00": "#f3e8c4", @@ -48,7 +48,7 @@ export const unSelectedNoteBgColorMap = { "#ffffff": "#ffffff" } -export const selectedNoteBgColorMap = { +export const selectedNoteBgColorMap: Record = { "#f86d05": "#eec4b8", "#ff7500": "#f1d8c7", "#ffbf00": "#f3cdb1", @@ -60,14 +60,14 @@ export const selectedNoteBgColorMap = { "#ffffff": "#19007dff" } -export const folderTextMap = { +export const folderTextMap: Record = { "sys_def_allNotes_uuid": $r('app.string.allNotes'), "sys_def_unClassified_uuid": $r('app.string.unClassified'), "sys_def_myFavorites_uuid": $r('app.string.myFavorites'), "sys_def_recentDeletes_uuid": $r('app.string.recentDeletes'), } -export const folderIconMap = { +export const folderIconMap: Record = { "sys_def_allNotes_uuid": $r('app.media.allNotes'), "sys_def_unClassified_uuid": $r('app.media.unClassified'), "sys_def_myFavorites_uuid": $r('app.media.favorite_cancel'), @@ -101,7 +101,7 @@ let widthWeightOneSection: WidthWeightMessage = new WidthWeightMessage("0%", 0, let widthWeightTwoSection = new WidthWeightMessage("0%", 0, "34%", 1, "66%", 1) let widthWeightThreeSection = new WidthWeightMessage("16%", 1, "34%", 1, "50%", 1) -export const widthWeightMessageMap = { +export const widthWeightMessageMap: Record = { 1: widthWeightOneSection, 2: widthWeightTwoSection, 3: widthWeightThreeSection diff --git a/common/utils/src/main/ets/default/model/databaseModel/FolderData.ets b/common/utils/src/main/ets/default/model/databaseModel/FolderData.ets index fdf5ad4..24089e7 100644 --- a/common/utils/src/main/ets/default/model/databaseModel/FolderData.ets +++ b/common/utils/src/main/ets/default/model/databaseModel/FolderData.ets @@ -14,6 +14,7 @@ */ import {FolderType, Delete} from './EnumData' +import relationalStore from '@ohos.data.relationalStore'; /** * 文件夹类 @@ -43,7 +44,7 @@ export default class FolderData { /** * 转化为folder_table表的valueBucket */ - toFolderObject(): any{ + toFolderObject(): relationalStore.ValuesBucket { return { "name": this.name, "uuid": this.uuid, diff --git a/common/utils/src/main/ets/default/model/databaseModel/NoteData.ets b/common/utils/src/main/ets/default/model/databaseModel/NoteData.ets index 4edcb19..16c1223 100644 --- a/common/utils/src/main/ets/default/model/databaseModel/NoteData.ets +++ b/common/utils/src/main/ets/default/model/databaseModel/NoteData.ets @@ -14,6 +14,7 @@ */ import { NoteType, Favorite, Delete, Top } from './EnumData' +import relationalStore from '@ohos.data.relationalStore'; /** * 笔记类 @@ -56,7 +57,7 @@ export default class NoteData { /** * 转化为note_table表的valueBucket */ - toNoteObject(): any{ + toNoteObject(): relationalStore.ValuesBucket { return { "title": this.title, "uuid": this.uuid, diff --git a/common/utils/src/main/ets/default/model/databaseModel/SysDefData.ets b/common/utils/src/main/ets/default/model/databaseModel/SysDefData.ets index 68fe7be..2ebd762 100644 --- a/common/utils/src/main/ets/default/model/databaseModel/SysDefData.ets +++ b/common/utils/src/main/ets/default/model/databaseModel/SysDefData.ets @@ -13,168 +13,179 @@ * limitations under the License. */ -import {SysDefFolder, SysDefFolderUuid, FolderType, NoteType, Favorite, Top, Delete} from './EnumData' -import relationalStore from '@ohos.data.relationalStore' +import { SysDefFolder, SysDefFolderUuid, FolderType, NoteType, Favorite, Top, Delete } from './EnumData'; +import relationalStore from '@ohos.data.relationalStore'; -export default { +interface DbInfoType { + db_name: DbNameType; + db_verison: number; +} + +interface DbNameType { + name: string; + securityLevel: relationalStore.SecurityLevel; +} + +class SysDefData { /** * db info */ - dbInfo: { + public dbInfo: DbInfoType = { db_name: { name: "note.db", // 数据库名称 securityLevel: relationalStore.SecurityLevel.S1 }, db_verison: 1 // 数据库版本 - }, + }; /** * system defined folder */ - sys_def_allNotes: { - "id": 1, - "name": SysDefFolder.AllNotes, - "uuid": SysDefFolderUuid.AllNotes, - "color": "#ffffff", - "folder_type": FolderType.SysDef, - "is_deleted": Delete.No, - "created_time": 1641863695000, - "modified_time": 1641863695000 - }, - - sys_def_unClassified: { - "id": 2, - "name": SysDefFolder.UnClassified, - "uuid": SysDefFolderUuid.UnClassified, - "color": "#ffffff", - "folder_type": FolderType.SysDef, - "is_deleted": Delete.No, - "created_time": 1641860095000, - "modified_time": 1641860095000 - }, - - sys_def_myFavorites: { - "id": 3, - "name": SysDefFolder.MyFavorites, - "uuid": SysDefFolderUuid.MyFavorites, - "color": "#ffffff", - "folder_type": FolderType.FeatureDef, - "is_deleted": Delete.No, - "created_time": 1641856088000, - "modified_time": 1641856088000 - }, + public sys_def_allNotes: relationalStore.ValuesBucket = { + "id": 1, + "name": SysDefFolder.AllNotes, + "uuid": SysDefFolderUuid.AllNotes, + "color": "#ffffff", + "folder_type": FolderType.SysDef, + "is_deleted": Delete.No, + "created_time": 1641863695000, + "modified_time": 1641863695000 + }; - sys_def_recentDeletes: { - "id": 4, - "name": SysDefFolder.RecentDeletes, - "uuid": SysDefFolderUuid.RecentDeletes, - "color": "#ffffff", - "folder_type": FolderType.FeatureDef, - "is_deleted": Delete.No, - "created_time": 1641848898000, - "modified_time": 1641848898000 - }, - - sys_def_personal: { - "id": 5, - "name": "个人", - "uuid": SysDefFolderUuid.Personal, - "color": "#41ba41", - "folder_type": FolderType.CusDef, - "is_deleted": Delete.No, - "created_time": 1641677288000, - "modified_time": 1641677288000 - }, - - sys_def_life: { - "id": 6, - "name": "生活", - "uuid": SysDefFolderUuid.Life, - "color": "#00aaee", - "folder_type": FolderType.CusDef, - "is_deleted": Delete.No, - "created_time": 1641676108000, - "modified_time": 1641676108000 - }, - - sys_def_work: { - "id": 7, - "name": "工作", - "uuid": SysDefFolderUuid.Work, - "color": "#f86d05", - "folder_type": FolderType.CusDef, - "is_deleted": Delete.No, - "created_time": 1641636508000, - "modified_time": 1641636508000 - }, + public sys_def_unClassified: relationalStore.ValuesBucket = { + "id": 2, + "name": SysDefFolder.UnClassified, + "uuid": SysDefFolderUuid.UnClassified, + "color": "#ffffff", + "folder_type": FolderType.SysDef, + "is_deleted": Delete.No, + "created_time": 1641860095000, + "modified_time": 1641860095000 + }; + + public sys_def_myFavorites: relationalStore.ValuesBucket = { + "id": 3, + "name": SysDefFolder.MyFavorites, + "uuid": SysDefFolderUuid.MyFavorites, + "color": "#ffffff", + "folder_type": FolderType.FeatureDef, + "is_deleted": Delete.No, + "created_time": 1641856088000, + "modified_time": 1641856088000 + }; + + public sys_def_recentDeletes: relationalStore.ValuesBucket = { + "id": 4, + "name": SysDefFolder.RecentDeletes, + "uuid": SysDefFolderUuid.RecentDeletes, + "color": "#ffffff", + "folder_type": FolderType.FeatureDef, + "is_deleted": Delete.No, + "created_time": 1641848898000, + "modified_time": 1641848898000 + }; + + public sys_def_personal: relationalStore.ValuesBucket = { + "id": 5, + "name": "个人", + "uuid": SysDefFolderUuid.Personal, + "color": "#41ba41", + "folder_type": FolderType.CusDef, + "is_deleted": Delete.No, + "created_time": 1641677288000, + "modified_time": 1641677288000 + }; + + public sys_def_life: relationalStore.ValuesBucket = { + "id": 6, + "name": "生活", + "uuid": SysDefFolderUuid.Life, + "color": "#00aaee", + "folder_type": FolderType.CusDef, + "is_deleted": Delete.No, + "created_time": 1641676108000, + "modified_time": 1641676108000 + }; + + public sys_def_work: relationalStore.ValuesBucket = { + "id": 7, + "name": "工作", + "uuid": SysDefFolderUuid.Work, + "color": "#f86d05", + "folder_type": FolderType.CusDef, + "is_deleted": Delete.No, + "created_time": 1641636508000, + "modified_time": 1641636508000 + }; /** * system defined note */ - sys_def_note1: { - "id": 1, - "title": "数学公式", - "uuid": "note1_uuid", - "folder_uuid": SysDefFolderUuid.UnClassified, - "content_text": '好好学习,天天向上', - "content_img": "", - "note_type": NoteType.SysDef, - "is_top": Top.Yes, - "is_favorite": Favorite.Yes, - "is_deleted": Delete.No, - "created_time": 1641869573000, - "modified_time": 1641869573000, - "deleted_time": 0, - "slider_value":0 - }, - - sys_def_note2: { - "id": 2, - "title": "UX会议纪要", - "uuid": "note2_uuid", - "folder_uuid": SysDefFolderUuid.Work, - "content_text": "", - "content_img": "", - "note_type": NoteType.SysDef, - "is_top": Top.Yes, - "is_favorite": Favorite.No, - "is_deleted": Delete.No, - "created_time": 1640999288000, - "modified_time": 1640999288000, - "deleted_time": 0, - "slider_value":0 - }, - - sys_def_note3: { - "id": 3, - "title": "旅游心得", - "uuid": "note3_uuid", - "folder_uuid": SysDefFolderUuid.Work, - "content_text": '
要想整个旅程无遗憾,关键是心态,首先要对即将到的目的地有一个正确的认识和恰当的期望。
', - "content_img": "", - "note_type": NoteType.SysDef, - "is_top": Top.No, - "is_favorite": Favorite.No, - "is_deleted": Delete.No, - "created_time": 1641385708000, - "modified_time": 1641385708000, - "deleted_time": 0, - "slider_value":0 - }, + public sys_def_note1: relationalStore.ValuesBucket = { + "id": 1, + "title": "数学公式", + "uuid": "note1_uuid", + "folder_uuid": SysDefFolderUuid.UnClassified, + "content_text": '好好学习,天天向上', + "content_img": "", + "note_type": NoteType.SysDef, + "is_top": Top.Yes, + "is_favorite": Favorite.Yes, + "is_deleted": Delete.No, + "created_time": 1641869573000, + "modified_time": 1641869573000, + "deleted_time": 0, + "slider_value": 0 + }; - sys_def_note4: { + public sys_def_note2: relationalStore.ValuesBucket = { + "id": 2, + "title": "UX会议纪要", + "uuid": "note2_uuid", + "folder_uuid": SysDefFolderUuid.Work, + "content_text": "", + "content_img": "", + "note_type": NoteType.SysDef, + "is_top": Top.Yes, + "is_favorite": Favorite.No, + "is_deleted": Delete.No, + "created_time": 1640999288000, + "modified_time": 1640999288000, + "deleted_time": 0, + "slider_value": 0 + }; + + public sys_def_note3: relationalStore.ValuesBucket = { + "id": 3, + "title": "旅游心得", + "uuid": "note3_uuid", + "folder_uuid": SysDefFolderUuid.Work, + "content_text": '
要想整个旅程无遗憾,关键是心态,首先要对即将到的目的地有一个正确的认识和恰当的期望。
', + "content_img": "", + "note_type": NoteType.SysDef, + "is_top": Top.No, + "is_favorite": Favorite.No, + "is_deleted": Delete.No, + "created_time": 1641385708000, + "modified_time": 1641385708000, + "deleted_time": 0, + "slider_value": 0 + }; + + public sys_def_note4: relationalStore.ValuesBucket = { "id": 4, "title": "蛋糕做法", "uuid": "note4_uuid", "folder_uuid": SysDefFolderUuid.Life, - "content_text": '
' + - '' + - '糖60g
' + - '' + - '玉米油40g
' + - '
 1.   添加鸡蛋、盐、糖、蛋糕粉
' + - ' 2.   加入玉米油、牛奶,烤箱预热15分钟
' + - ' 3.   加入葡萄干、核桃仁,烤箱定时40分钟

', + "content_text": ' ' + + '' + + '糖60g
' + + ' ' + + '' + + '玉米油40g
' + + '
 1.   添加鸡蛋、盐、糖、蛋糕粉
' + + ' 2.   加入玉米油、牛奶,烤箱预热15分钟
' + + ' 3.   加入葡萄干、核桃仁,烤箱定时40分钟

', "content_img": "", "note_type": NoteType.CusDef, "is_top": Top.No, @@ -183,6 +194,8 @@ export default { "created_time": 1640909288000, "modified_time": 1640909288000, "deleted_time": 0, - "slider_value":0 - } -} \ No newline at end of file + "slider_value": 0 + }; +} + +export default new SysDefData(); \ No newline at end of file diff --git a/common/utils/src/main/ets/default/model/searchModel/SearchModel.ets b/common/utils/src/main/ets/default/model/searchModel/SearchModel.ets index 7fba116..d4d8fbd 100644 --- a/common/utils/src/main/ets/default/model/searchModel/SearchModel.ets +++ b/common/utils/src/main/ets/default/model/searchModel/SearchModel.ets @@ -13,17 +13,23 @@ * limitations under the License. */ -import {LogUtil} from '../../baseUtil/LogUtil' +import { LogUtil } from '../../baseUtil/LogUtil' import NoteData from '../../model/databaseModel/NoteData' import util from '@ohos.util' +import relationalStore from '@ohos.data.relationalStore'; -const TAG = "SearchModel" +const TAG: string = 'SearchModel'; + +interface TextSpan { + type: 0 | 1; // 0 表示正常文本,1 表示高亮关键词 + text: string; +} /** * Search service class */ export class SearchModel { - private rdbStore; + private rdbStore: relationalStore.RdbStore | undefined = undefined; /** * Search @@ -38,9 +44,9 @@ export class SearchModel { } let searchData: NoteData[] = []; noteDataArray.forEach((noteData) => { - let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/ + let base64regex = new RegExp('/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/'); let contentTextValue: string - if (base64regex.test(noteData.content_text)) { + if (base64regex.test(noteData.content_text) && noteData.content_text.length > 0) { let Base64 = new util.Base64() let textDecoder = new util.TextDecoder("utf-8", { ignoreBOM: true }) // utf-8:编码格式为utf-8,ignoreBOM:是否忽略BOM标记 let decodeStr = Base64.decodeSync(noteData.content_text) @@ -48,8 +54,8 @@ export class SearchModel { } else { contentTextValue = noteData.content_text } - if (contentTextValue.replace(/<[^>]+>/g, "").toLowerCase().indexOf(query.toLowerCase()) != -1 - || noteData.title.toLowerCase().indexOf(query.toLowerCase()) != -1) { + if (contentTextValue.replace(new RegExp('/<[^>]+>/g'), "").toLowerCase().indexOf(query.toLowerCase()) != -1 + || noteData.title.toLowerCase().indexOf(query.toLowerCase()) != -1) { LogUtil.info(TAG, "uuid " + noteData.uuid) searchData.push(noteData); } @@ -58,14 +64,14 @@ export class SearchModel { return searchData; } - splitToHighlightText(text: string, highlightKeyword): any[] { - let spans: any[] = [] - var lowerSpans: string[] = text.toLowerCase().split(highlightKeyword.toLowerCase()) - var keywordStartIndex = 0 - var keywordLength = highlightKeyword.length + splitToHighlightText(text: string, highlightKeyword: string): TextSpan[] { + let spans: TextSpan[] = []; + let lowerSpans: string[] = text.toLowerCase().split(highlightKeyword.toLowerCase()); + let keywordStartIndex = 0; + let keywordLength = highlightKeyword.length; - for (var i = 0; i < lowerSpans.length; i++) { - var normalText = text.substr(keywordStartIndex, lowerSpans[i].length) + for (let i = 0; i < lowerSpans.length; i++) { + let normalText = text.substr(keywordStartIndex, lowerSpans[i].length); spans.push({ type: 0, text: normalText @@ -73,7 +79,7 @@ export class SearchModel { // if not at last, append highlight keyword if (i != lowerSpans.length - 1) { keywordStartIndex += lowerSpans[i].length - var keywordText = text.substr(keywordStartIndex, keywordLength) + let keywordText = text.substr(keywordStartIndex, keywordLength); spans.push({ type: 1, text: keywordText diff --git a/features/.gitignore b/features/.gitignore index 9924c4f..fd0ce92 100644 --- a/features/.gitignore +++ b/features/.gitignore @@ -1,4 +1,5 @@ /node_modules +/oh_modules /.preview /build /.cxx diff --git a/features/build-profile.json5 b/features/build-profile.json5 index d862153..bfc9563 100644 --- a/features/build-profile.json5 +++ b/features/build-profile.json5 @@ -18,10 +18,6 @@ "apiType": 'stageMode', "buildOption": { }, - "entryModules": [ - "phone", - "tablet" - ], "targets": [ { "name": "default" diff --git a/features/hvigorfile.js b/features/hvigorfile.js index 42ed4b4..29ad39f 100644 --- a/features/hvigorfile.js +++ b/features/hvigorfile.js @@ -1,3 +1,3 @@ // Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. -module.exports = require('@ohos/hvigor-ohos-plugin').harTasks +module.exports = require('@ohos/hvigor-ohos-plugin').harTasks; diff --git a/features/index.ets b/features/index.ets new file mode 100644 index 0000000..6db6bab --- /dev/null +++ b/features/index.ets @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023-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 { NewOrEditFolderDialog } from './src/main/ets/components/CusDialogComp'; + +export { DeleteDialog } from './src/main/ets/components/CusDialogComp'; + +export { NoteDataMoveDialog } from './src/main/ets/components/CusDialogComp'; + +export { EditContentDialog } from './src/main/ets/components/CusDialogComp'; + +export { EditTitleDialog } from './src/main/ets/components/CusDialogComp'; + +export { EditContentDialogPortrait } from './src/main/ets/components/CusDialogComp'; + +export { FolderListComp } from './src/main/ets/components/FolderListComp'; + +export { NoteAndCreateComp } from './src/main/ets/components/FolderListComp'; + +export { NoteContent } from './src/main/ets/components/NoteContent'; + +export { NoteContentComp } from './src/main/ets/components/NoteContentComp'; + +export { NoteContentCompPortrait } from './src/main/ets/components/NoteContentCompPortrait'; + +export { NoteContentOverViewComp } from './src/main/ets/components/NoteContentCompPortrait'; + +export { ToolBarComp } from './src/main/ets/components/NoteContentCompPortrait'; + +export { DeleteNoteComp } from './src/main/ets/components/NoteContentCompPortrait'; + +export { NoteListComp } from './src/main/ets/components/NoteListComp'; + +export { NoteItemComp } from './src/main/ets/components/NoteListComp'; + +export { NoteItemListComp } from './src/main/ets/components/NoteListComp'; + +export { OperateNoteComp } from './src/main/ets/components/NoteListComp'; + +export { AddNoteComp } from './src/main/ets/components/NoteListComp'; + +export { SearchComp } from './src/main/ets/components/NoteListComp'; + +export { OperateNoteCompForPortrait } from './src/main/ets/components/NoteListComp'; + diff --git a/features/package.json b/features/oh-package.json5 similarity index 91% rename from features/package.json rename to features/oh-package.json5 index 77cec25..62ab66b 100644 --- a/features/package.json +++ b/features/oh-package.json5 @@ -4,9 +4,6 @@ "devDependencies": {}, "name": "@ohos/component", "description": "a npm package which contains arkUI2.0 page", - "ohos": { - "org": "" - }, "main": "index.ets", "repository": {}, "version": "1.0.0", diff --git a/features/package-lock.json b/features/package-lock.json deleted file mode 100644 index bf24415..0000000 --- a/features/package-lock.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "@ohos/component", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@ohos/source": { - "version": "file:../common/resources" - }, - "@ohos/utils": { - "version": "file:../common/utils", - "requires": { - "@ohos/source": "file:../common/resources" - }, - "dependencies": { - "@ohos/source": { - "version": "file:../common/resources" - } - } - } - } -} diff --git a/features/src/main/ets/components/CusDialogComp.ets b/features/src/main/ets/components/CusDialogComp.ets index a7d6226..0f3ac9a 100644 --- a/features/src/main/ets/components/CusDialogComp.ets +++ b/features/src/main/ets/components/CusDialogComp.ets @@ -18,7 +18,15 @@ import FolderData from '@ohos/utils/src/main/ets/default/model/databaseModel/Fol import FolderUtil from '@ohos/utils/src/main/ets/default/baseUtil/FolderUtil' import NoteData from '@ohos/utils/src/main/ets/default/model/databaseModel/NoteData' import NoteUtil from '@ohos/utils/src/main/ets/default/baseUtil/NoteUtil' -import { circleColorArray, fontColorArray, SysDefFolderUuid, DeleteFileType, FolderType, LogUtil } from '@ohos/utils' +import { + circleColorArray, + fontColorArray, + SysDefFolderUuid, + DeleteFileType, + FolderType, + Delete, + LogUtil +} from '@ohos/utils'; import inputMethod from '@ohos.inputMethod' const TAG = "CusDialogComp" @@ -26,7 +34,8 @@ const TAG = "CusDialogComp" @CustomDialog export struct NewOrEditFolderDialog { newOrEditFolderDialogCtl: CustomDialogController - confirm: (color: string, name: string) => void + confirm: (color: string, name: string) => void = (color: string, name: string) => { + }; @State inputName: string = "" private oriInputName: string = "" private oriSelectedColor: string = "" @@ -47,8 +56,9 @@ export struct NewOrEditFolderDialog { Flex({ wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.SpaceBetween }) { ForEach(circleColorArray, (colorStr: string) => { ColorCircleComp({ circleColor: colorStr }) - }, colorStr => colorStr) + }, (colorStr: string) => colorStr) }.margin({ bottom: 12, left: 24, right: 24 }) + // folder name input Flex({ wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.SpaceBetween }) { Image($r("app.media.folder")) @@ -107,21 +117,21 @@ export struct NewOrEditFolderDialog { .strokeWidth(1) .color($r("app.color.divider_color_e4e4e4")) Text($r("app.string.save")) - .opacity(this.inputName == "" - || (this.oriSelectedColor == this.selectedColor && this.inputName == this.oriInputName && this.dialogType == 1) - || (this.isExisted && this.dialogType == 0) - || (this.isExisted && this.dialogType == 1 && this.inputName != this.oriInputName) ? 0.4 : 1) - .enabled(this.inputName == "" - || (this.oriSelectedColor == this.selectedColor && this.inputName == this.oriInputName && this.dialogType == 1) - || (this.isExisted && this.dialogType == 0) - || (this.isExisted && this.dialogType == 1 && this.inputName != this.oriInputName) ? false : true) + .opacity(this.inputName == "" || (this.oriSelectedColor == this.selectedColor && + this.inputName == this.oriInputName && this.dialogType == 1) || + (this.isExisted && this.dialogType == 0) || + (this.isExisted && this.dialogType == 1 && this.inputName != this.oriInputName) ? 0.4 : 1) + .enabled(this.inputName == "" || (this.oriSelectedColor == this.selectedColor && + this.inputName == this.oriInputName && this.dialogType == 1) || + (this.isExisted && this.dialogType == 0) || (this.isExisted && this.dialogType == 1 && + this.inputName != this.oriInputName) ? false : true) .fontSize(18) .textAlign(TextAlign.Center) .fontColor($r("app.color.button_color_f86d05")) .width('48%') .onClick(() => { this.newOrEditFolderDialogCtl.close() - if (this.inputName.replace(/\s+/g, '') == '') { + if (this.inputName.replace(new RegExp('/\s+/g'), '') == '') { return } else { this.confirm(this.selectedColor, this.inputName) @@ -136,10 +146,11 @@ export struct NewOrEditFolderDialog { .backgroundColor($r("app.color.create_folder_bg_color")) .alignItems(HorizontalAlign.Start) .margin({ bottom: 16, left: 12, right: 12 }) + .offset({ y: -50 }) } aboutToAppear(): void { - var currentFolder: FolderData = FolderUtil.getFolderData(this.AllFolderArray, this.editFolderUuid) // 获取当前选中的文件夹 + let currentFolder: FolderData = FolderUtil.getFolderData(this.AllFolderArray, this.editFolderUuid); // 获取当前选中的文件夹 if (currentFolder == null) { return } @@ -148,7 +159,7 @@ export struct NewOrEditFolderDialog { this.oriInputName = this.inputName this.oriSelectedColor = currentFolder.color } else { - GlobalResourceManager.getStringByResource(FolderUtil.getFolderText(currentFolder)).then(result => { + GlobalResourceManager.getStringByResource(FolderUtil.getFolderText(currentFolder) as Resource).then(result => { this.inputName = result this.oriInputName = this.inputName this.oriSelectedColor = currentFolder.color @@ -159,7 +170,7 @@ export struct NewOrEditFolderDialog { @Component struct ColorCircleComp { - private circleColor: string + private circleColor: string = ''; @Consume('SelectedColor') selectedColor: string build() { @@ -173,7 +184,7 @@ struct ColorCircleComp { try { this.selectedColor = this.circleColor } catch (error) { - console.log("selectedColor error: ", error.toString()); + LogUtil.error(TAG, "selectedColor error: ", error.toString()); } }) } @@ -189,7 +200,8 @@ export struct DeleteDialog { private multiSelect: boolean = false private deleteFileType = DeleteFileType.NoteData noteDataDeleteDialogCtl: CustomDialogController - onConfirm: () => void + onConfirm: () => void = () => { + }; build() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween }) { @@ -200,30 +212,35 @@ export struct DeleteDialog { .textAlign(TextAlign.Center) .maxLines(1) } else { - Text(this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? $r("app.string.deleteNoteComplete") : $r("app.string.deleteNote")) + Text(this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? + $r("app.string.deleteNoteComplete") : $r("app.string.deleteNote")) .fontSize(14) .textAlign(TextAlign.Center) .maxLines(1) - .visibility(this.multiSelect == false || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? Visibility.Visible : Visibility.None) + .visibility(this.multiSelect == false || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? + Visibility.Visible : Visibility.None) if (this.CheckedNoteArray.length == NoteUtil.getNoteDataArray(this.AllNoteArray, this.selectedFolderData.uuid).length) { Text($r("app.string.deleteAllNote")) .fontSize(14) .textAlign(TextAlign.Center) .maxLines(1) - .visibility(this.multiSelect == false || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? Visibility.None : Visibility.Visible) + .visibility(this.multiSelect == false || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? + Visibility.None : Visibility.Visible) } else if (this.CheckedNoteArray.length > 1) { Text($r("app.string.deletePartNote", this.CheckedNoteArray.length)) .fontSize(14) .textAlign(TextAlign.Center) .maxLines(1) - .visibility(this.multiSelect == false || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? Visibility.None : Visibility.Visible) + .visibility(this.multiSelect == false || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? + Visibility.None : Visibility.Visible) } else { Text($r("app.string.deleteNote")) .fontSize(14) .textAlign(TextAlign.Center) .maxLines(1) - .visibility(this.multiSelect == false || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? Visibility.None : Visibility.Visible) + .visibility(this.multiSelect == false || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? + Visibility.None : Visibility.Visible) } } } @@ -267,6 +284,7 @@ export struct DeleteDialog { .padding({ top: 24, bottom: 16, left: 16, right: 16 }) .backgroundColor($r("app.color.delete_note_bg_color")) .margin({ bottom: 16, left: 12, right: 12 }) + .offset({ y: -50 }) } } @@ -274,24 +292,25 @@ export struct DeleteDialog { struct NoteDataMoveItemComp { @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = [] @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = [] - private folderItem: FolderData + private folderItem: FolderData = new FolderData(0, '', new Date().getTime() + '', '', FolderType.CusDef, Delete.No, + new Date().getTime(), new Date().getTime()); dividerShow: boolean = true build() { Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.NoWrap }) { Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.NoWrap }) { - Image(FolderUtil.getFolderIcon(this.folderItem.uuid)) + Image(FolderUtil.getFolderIcon(this.folderItem.uuid!)) .objectFit(ImageFit.Fill) .width(24) .height(24) .flexShrink(0) - .fillColor(FolderUtil.getFolderIconColor(this.AllFolderArray, this.folderItem.uuid, false)) + .fillColor(FolderUtil.getFolderIconColor(this.AllFolderArray, this.folderItem.uuid!, false)) } .width(24) Column() { Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.SpaceBetween }) { - Text(FolderUtil.getFolderText(this.folderItem)) + Text(FolderUtil.getFolderText(this.folderItem!)) .fontSize(16) .textAlign(TextAlign.Center) .maxLines(1) @@ -299,7 +318,8 @@ struct NoteDataMoveItemComp { .flexShrink(1) .fontWeight(FontWeight.Medium) Image((FolderUtil.getCommonFolder(this.AllFolderArray, this.CheckedNoteArray) == null - || FolderUtil.getCommonFolder(this.AllFolderArray, this.CheckedNoteArray) != this.folderItem) ? $r("app.media.foldMove_unselect") : $r("app.media.foldMove_select")) + || FolderUtil.getCommonFolder(this.AllFolderArray, this.CheckedNoteArray) != this.folderItem!) ? + $r("app.media.foldMove_unselect") : $r("app.media.foldMove_select")) .objectFit(ImageFit.Fill) .width(24) .height(24) @@ -319,19 +339,24 @@ struct NoteDataMoveItemComp { } .width(288) .height(56) - .visibility(FolderUtil.isFolderMoveIn(this.folderItem) ? Visibility.Visible : Visibility.None) + .visibility(FolderUtil.isFolderMoveIn(this.folderItem!) ? Visibility.Visible : Visibility.None) } } @CustomDialog export struct NoteDataMoveDialog { noteDataMoveDialogCtl: CustomDialogController - onConfirm: (folderUuid: string) => void - NoteDataMoveArray: FolderData[] + onConfirm: (folderUuid: string) => void = (folderUuid: string) => { + }; + NoteDataMoveArray: FolderData[] = []; @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = [] aboutToAppear() { this.NoteDataMoveArray = this.AllFolderArray.slice(2, this.AllFolderArray.length); + if (this.AllFolderArray[1] === undefined || this.AllFolderArray[1] === null) { + LogUtil.info(TAG, 'this AllFolderArray[1] undefined'); + return; + } this.NoteDataMoveArray.push(this.AllFolderArray[1]); } @@ -346,15 +371,18 @@ export struct NoteDataMoveDialog { .width(288) List() { - ForEach(this.NoteDataMoveArray.slice(0, this.NoteDataMoveArray.length - 1), (item) => { - ListItem() { - NoteDataMoveItemComp({ folderItem: item }) - } - .onClick(() => { - this.noteDataMoveDialogCtl.close() - this.onConfirm(item.uuid) - }) - }, noteItem => noteItem.uuid) + if (this.NoteDataMoveArray !== undefined && this.NoteDataMoveArray !== null && + this.NoteDataMoveArray.length > 0) { + ForEach(this.NoteDataMoveArray.slice(0, this.NoteDataMoveArray.length - 1), (item: FolderData) => { + ListItem() { + NoteDataMoveItemComp({ folderItem: item }) + } + .onClick(() => { + this.noteDataMoveDialogCtl.close() + this.onConfirm(item.uuid) + }) + }, (noteItem: FolderData) => noteItem.uuid) + } ListItem() { NoteDataMoveItemComp({ folderItem: this.NoteDataMoveArray[this.NoteDataMoveArray.length - 1], @@ -385,22 +413,24 @@ export struct NoteDataMoveDialog { .padding({ left: 24, right: 24 }) .backgroundColor($r("app.color.choose_folder_bg_color")) .margin({ bottom: 16, left: 12, right: 12 }) + .offset({ y: -50 }) } } -let inSetValue = AppStorage.Link('inSetValue') +let inSetValue: string = AppStorage.Link('inSetValue'); @CustomDialog export struct EditContentDialog { editContentDialogCtl: CustomDialogController - confirm: (excuteJs: string) => void + confirm: (excuteJs: string) => void = (excuteJs: string) => { + }; @State selectFontColor: string = fontColorArray[0] @Consume('SelectedNoteData') selectedNoteData: NoteData - private circleColor: string - private fontSize: number + private circleColor: string = ''; + private fontSize: number = 0; aboutToAppear() { - this.confirm("javascript:RICH_EDITOR.getFontSizes()") + this.confirm('javascript:RICH_EDITOR.getFontSizes()'); } build() { @@ -602,7 +632,7 @@ export struct EditContentDialog { this.selectFontColor = colorStr this.confirm("javascript:RICH_EDITOR.setTextColor('" + this.selectFontColor + "')") }) - }, colorStr => colorStr) + }, (colorStr: string) => colorStr) }.padding({ bottom: 11 }) } .alignItems(VerticalAlign.Top) @@ -659,7 +689,8 @@ export struct EditContentDialog { @CustomDialog export struct EditTitleDialog { editTitleDialog: CustomDialogController - confirm: (newTitle: string) => void + confirm: (newTitle: string) => void = (newTitle: string) => { + }; @State inputName: string = "" @State isEquivalentVal: boolean = true @@ -716,7 +747,7 @@ export struct EditTitleDialog { .onClick(() => { this.editTitleDialog.close() inputMethod.getController().stopInputSession(); - if (this.inputName.replace(/\s+/g, '') == '') { + if (this.inputName.replace(new RegExp('/\s+/g'), '') == '') { return } else { this.confirm(this.inputName) @@ -736,14 +767,20 @@ export struct EditTitleDialog { @CustomDialog export struct EditContentDialogPortrait { editContentDialogCtl: CustomDialogController; - confirm: (excuteJs: string) => void + confirm: (excuteJs: string) => void = (excuteJs: string) => { + }; @State selectFontColor: string = fontColorArray[0] @Consume('SelectedNoteData') selectedNoteData: NoteData - private circleColor: string - private fontSize: number + private circleColor: string = ''; + private fontSize: number = 0; aboutToAppear() { - this.confirm("javascript:RICH_EDITOR.getFontSizes()") + try { + this.confirm('javascript:RICH_EDITOR.getFontSizes()'); + LogUtil.info(TAG, `runJavaScript success.`); + } catch (error) { + LogUtil.error(TAG, `runJavaScript failed.code:${JSON.stringify(error.code)},message:${JSON.stringify(error.message)}`); + } } build() { @@ -933,7 +970,7 @@ export struct EditContentDialogPortrait { this.selectFontColor = colorStr this.confirm("javascript:RICH_EDITOR.setTextColor('" + this.selectFontColor + "')") }) - }, colorStr => colorStr) + }, (colorStr: string) => colorStr) } } .height(48) @@ -973,5 +1010,6 @@ export struct EditContentDialogPortrait { .height(266) .backgroundColor($r("app.color.color_ffffff")) .borderRadius(36) + .offset({ y: -35 }) } } \ No newline at end of file diff --git a/features/src/main/ets/components/FolderListComp.ets b/features/src/main/ets/components/FolderListComp.ets index 9ccc36d..f74c555 100644 --- a/features/src/main/ets/components/FolderListComp.ets +++ b/features/src/main/ets/components/FolderListComp.ets @@ -29,6 +29,7 @@ import RdbStoreUtil from '@ohos/utils/src/main/ets/default/baseUtil/RdbStoreUtil import FolderUtil from '@ohos/utils/src/main/ets/default/baseUtil/FolderUtil' import NoteUtil from '@ohos/utils/src/main/ets/default/baseUtil/NoteUtil' import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil' +import webview from '@ohos.web.webview'; // Folder list component @Component @@ -37,7 +38,7 @@ export struct FolderListComp { @Consume('SectionStatus') sectionStatus: number @Consume('ExpandStatus') expandStatus: boolean // 笔记本折叠展开状态 @StorageLink('breakPoint') breakPoints: string = 'lg' - controllerShow: WebviewController + controllerShow: webview.WebviewController = new webview.WebviewController(); TAG = "FolderListComp" @Consume('AsideWidth') asideWidth: number @@ -78,7 +79,7 @@ export struct FolderListComp { FolderItemComp({ folderItem: folderItem, controllerShow: this.controllerShow }) } } - }, folderItem => folderItem.name.toString()) + }, (folderItem: FolderData) => folderItem.name.toString()) } .width('100%') .height(500) @@ -90,18 +91,19 @@ export struct FolderListComp { Column() { FolderItemComp({ - folderItem: FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), SysDefFolderUuid.MyFavorites), + folderItem: FolderUtil.getFolderData(AppStorage.Get('AllFolderArray')!, SysDefFolderUuid.MyFavorites), controllerShow: this.controllerShow }) FolderItemComp({ - folderItem: FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), SysDefFolderUuid.RecentDeletes), + folderItem: FolderUtil.getFolderData(AppStorage.Get('AllFolderArray')!, SysDefFolderUuid.RecentDeletes), controllerShow: this.controllerShow }) } .backgroundColor($r("app.color.folderlist_bgcolor_f1f3f5")) .flexGrow(0) .width("100%") - .padding({ left: 12, right: 12, bottom: 24 }) + .padding({ left: 12, right: 12, bottom: 60 }) + .margin({ bottom: 65 }) } .height("100%") .backgroundColor($r('app.color.folder_color_d6d6d6')) @@ -122,24 +124,33 @@ export struct NoteAndCreateComp { @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = AppStorage.Link('AllFolderArray') @Consume('SelectedColor') selectedColor: string @Consume('PortraitModel') portraitModel: boolean - folderCreateDialogCtl: CustomDialogController = new CustomDialogController({ - builder: NewOrEditFolderDialog({ confirm: this.onCreateConfirm.bind(this), dialogType: 0 }), + folderCreateDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: NewOrEditFolderDialog({ confirm: (color: string, name: string) => { + this.onCreateConfirm(color, name) + }, dialogType: 0 }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, }) - folderCreateDialogCtlBottom: CustomDialogController = new CustomDialogController({ - builder: NewOrEditFolderDialog({ confirm: this.onCreateConfirm.bind(this), dialogType: 0 }), + folderCreateDialogCtlBottom: CustomDialogController | null = new CustomDialogController({ + builder: NewOrEditFolderDialog({ confirm: (color: string, name: string) => { + this.onCreateConfirm(color, name) + }, dialogType: 0 }), alignment: DialogAlignment.Bottom, autoCancel: false, customStyle: true, }) + aboutToDisappear() { + this.folderCreateDialogCtl = null + this.folderCreateDialogCtlBottom = null + } + onCreateConfirm(color: string, name: string) { let folderData = new FolderData(0, name, new Date().getTime() + "", color, FolderType.CusDef, Delete.No, new Date().getTime(), new Date().getTime()) // 新的的笔记本都是自定义类型 type为1 this.AllFolderArray.push(folderData) // insert folder to db - RdbStoreUtil.insert(TableName.FolderTable, folderData.toFolderObject(), null) + RdbStoreUtil.insert(TableName.FolderTable, folderData.toFolderObject(), null); AppStorage.SetOrCreate('isUpdate', true) } @@ -158,9 +169,9 @@ export struct NoteAndCreateComp { .onClick(() => { this.selectedColor = "#e84026" // 新建的时候选中第一个颜色 if (this.portraitModel) { - this.folderCreateDialogCtlBottom.open() + this.folderCreateDialogCtlBottom!.open(); } else { - this.folderCreateDialogCtl.open() + this.folderCreateDialogCtl!.open(); } }).padding({ right: 0 }) }.width(50) @@ -183,15 +194,17 @@ struct FolderItemComp { @Consume('Longpress') longpress: boolean @Consume('SelectedColor') selectedColor: string @Consume('PortraitModel') portraitModel: boolean - controllerShow: WebviewController + controllerShow: webview.WebviewController = new webview.WebviewController(); @State isLongPress: boolean = false - TAG = "FolderListComp" + TAG = "FolderItemComp" @StorageLink('isUpdate') isUpdate: boolean = false // Folder Edit Dialog - folderEditDialogCtl: CustomDialogController = new CustomDialogController({ + folderEditDialogCtl: CustomDialogController | null = new CustomDialogController({ builder: NewOrEditFolderDialog({ editFolderUuid: this.folderItem.uuid, - confirm: this.onEditConfirm.bind(this), + confirm: (color: string, name: string) => { + this.onEditConfirm(color, name); + }, dialogType: 1 }), alignment: DialogAlignment.Center, @@ -199,16 +212,28 @@ struct FolderItemComp { customStyle: true, }) // Folder Edit Dialog for portrait model - folderEditDialogCtlBottom: CustomDialogController = new CustomDialogController({ + folderEditDialogCtlBottom: CustomDialogController | null = new CustomDialogController({ builder: NewOrEditFolderDialog({ editFolderUuid: this.folderItem.uuid, - confirm: this.onEditConfirm.bind(this), + confirm: (color: string, name: string) => { + this.onEditConfirm(color, name); + }, dialogType: 1 }), alignment: DialogAlignment.Bottom, autoCancel: false, customStyle: true, }) + + aboutToDisappear() { + this.folderEditDialogCtl = null + this.folderEditDialogCtlBottom = null + this.folderDeleteDialogCtl = null + this.folderDeleteDialogCtlBottom = null + this.folderCreateDialogCtl = null + this.folderCreateDialogCtlBottom = null + } + // Folder Edit Callback onEditConfirm(color: string, name: string) { this.folderItem.color = color @@ -217,19 +242,24 @@ struct FolderItemComp { // update folder to db let predicates_folder = RdbStoreUtil.getRdbPredicates(TableName.FolderTable) predicates_folder.equalTo(FolderTableColumn.Uuid, this.folderItem.uuid) - RdbStoreUtil.update(this.folderItem.toFolderObject(), predicates_folder, null) + RdbStoreUtil.update(this.folderItem.toFolderObject(), predicates_folder, null); this.isUpdate = true } + // Folder Delete Dialog - folderDeleteDialogCtl: CustomDialogController = new CustomDialogController({ - builder: DeleteDialog({ onConfirm: this.onDeleteConfirm.bind(this), deleteFileType: DeleteFileType.FolderData }), + folderDeleteDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: DeleteDialog({ onConfirm: () => { + this.onDeleteConfirm(); + }, deleteFileType: DeleteFileType.FolderData }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, }) // Folder Delete Dialog for portrait model - folderDeleteDialogCtlBottom: CustomDialogController = new CustomDialogController({ - builder: DeleteDialog({ onConfirm: this.onDeleteConfirm.bind(this), deleteFileType: DeleteFileType.FolderData }), + folderDeleteDialogCtlBottom: CustomDialogController | null = new CustomDialogController({ + builder: DeleteDialog({ onConfirm: () => { + this.onDeleteConfirm(); + }, deleteFileType: DeleteFileType.FolderData }), alignment: DialogAlignment.Bottom, autoCancel: false, customStyle: true, @@ -238,8 +268,8 @@ struct FolderItemComp { onDeleteConfirm() { let currentFolder = FolderUtil.getFolderData(this.AllFolderArray, this.folderItem.uuid) let index = this.AllFolderArray.indexOf(currentFolder) - let currentNoteDataArray = NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.folderItem.uuid) - let deleteNoteDataArray = NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), 'sys_def_recentDeletes_uuid') + let currentNoteDataArray = NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, this.folderItem.uuid); + let deleteNoteDataArray = NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, 'sys_def_recentDeletes_uuid'); if (index > -1) { this.AllFolderArray.splice(index, 1) if (deleteNoteDataArray.length != 0) { @@ -250,7 +280,7 @@ struct FolderItemComp { // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); } }) } @@ -262,24 +292,29 @@ struct FolderItemComp { // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) } // delete folder from db let predicates_folder = RdbStoreUtil.getRdbPredicates(TableName.FolderTable) predicates_folder.equalTo(FolderTableColumn.Uuid, this.folderItem.uuid) - RdbStoreUtil.delete(predicates_folder, null) + RdbStoreUtil.delete(predicates_folder, null); // update selectedFolderData and selectedNoteData this.selectedFolderData = FolderUtil.getFolderData(this.AllFolderArray, SysDefFolderUuid.AllNotes) - this.selectedNoteData = NoteUtil.getFirstNoteData(this.AllNoteArray, SysDefFolderUuid.AllNotes) + this.selectedNoteData = NoteUtil.getFirstNoteData(this.AllNoteArray, SysDefFolderUuid.AllNotes)!; if (!this.selectedNoteData) { return } // 刷新web界面 if (this.portraitModel == false) { - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" - ) + try { + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" + ) + LogUtil.info(this.TAG, `runJavaScript success.`); + } catch (error) { + LogUtil.error(this.TAG, `runJavaScript failed.code:${JSON.stringify(error.code)},message:${JSON.stringify(error.message)}`); + } } // save continue data let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) @@ -288,26 +323,32 @@ struct FolderItemComp { } this.isUpdate = true } + // Folder Create Dialog - folderCreateDialogCtl: CustomDialogController = new CustomDialogController({ - builder: NewOrEditFolderDialog({ confirm: this.onCreateConfirm.bind(this), dialogType: 0 }), + folderCreateDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: NewOrEditFolderDialog({ confirm: (color: string, name: string) => { + this.onCreateConfirm(color, name); + }, dialogType: 0 }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, }) // Folder Create Dialog for portrait model - folderCreateDialogCtlBottom: CustomDialogController = new CustomDialogController({ - builder: NewOrEditFolderDialog({ confirm: this.onCreateConfirm.bind(this), dialogType: 0 }), + folderCreateDialogCtlBottom: CustomDialogController | null = new CustomDialogController({ + builder: NewOrEditFolderDialog({ confirm: (color: string, name: string) => { + this.onCreateConfirm(color, name); + }, dialogType: 0 }), alignment: DialogAlignment.Bottom, autoCancel: false, customStyle: true, }) + // Folder Create Callback onCreateConfirm(color: string, name: string) { let folderData = new FolderData(0, name, new Date().getTime() + "", color, FolderType.CusDef, Delete.No, new Date().getTime(), new Date().getTime()) // 新的的笔记本都是自定义类型 type为1 this.AllFolderArray.push(folderData) // insert folder to db - RdbStoreUtil.insert(TableName.FolderTable, folderData.toFolderObject(), null) + RdbStoreUtil.insert(TableName.FolderTable, folderData.toFolderObject(), null); this.isUpdate = true } @@ -322,9 +363,9 @@ struct FolderItemComp { .onClick(() => { this.selectedColor = this.folderItem.color if (this.portraitModel) { - this.folderEditDialogCtlBottom.open() + this.folderEditDialogCtlBottom!.open(); } else { - this.folderEditDialogCtl.open() + this.folderEditDialogCtl!.open(); } ContextMenu.close() }) @@ -339,9 +380,9 @@ struct FolderItemComp { .fontColor($r("app.color.folder_color_182431")) .onClick(() => { if (this.portraitModel) { - this.folderDeleteDialogCtlBottom.open() + this.folderDeleteDialogCtlBottom!.open(); } else { - this.folderDeleteDialogCtl.open() + this.folderDeleteDialogCtl!.open(); } ContextMenu.close() }) @@ -357,9 +398,9 @@ struct FolderItemComp { .onClick(() => { this.selectedColor = "#e84026" // 新建的时候选中第一个颜色 if (this.portraitModel) { - this.folderCreateDialogCtlBottom.open() + this.folderCreateDialogCtlBottom!.open(); } else { - this.folderCreateDialogCtl.open() + this.folderCreateDialogCtl!.open(); } ContextMenu.close() }) @@ -416,15 +457,21 @@ struct FolderItemComp { NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) } else { this.selectedFolderData = this.folderItem - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), this.folderItem.uuid) + this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, this.folderItem.uuid)!; if (!this.selectedNoteData) { return } // 刷新web界面 if (this.portraitModel == false) { - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" - ) + try { + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" + ); + LogUtil.info(this.TAG, `onClick runJavaScript setHtml success.`); + } catch (error) { + LogUtil.error(this.TAG, `onClick runJavaScript setHtml failed,code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}.`); + } } // save continue data let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) @@ -468,22 +515,28 @@ struct FolderItemComp { .height(56) .padding({ left: 12, right: 12 }) .backgroundColor(this.isLongPress ? $r("app.color.folder_color_19182431") : this.selectedFolderData.uuid == this.folderItem.uuid - ? $r("app.color.folder_color_ffffff") : "#00FFFFFF") + ? $r("app.color.folder_color_ffffff") : "#00FFFFFF") .onClick(() => { if (this.longpress) { this.longpress = false NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) } else { this.selectedFolderData = this.folderItem - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), this.folderItem.uuid) + this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, this.folderItem.uuid)!; if (!this.selectedNoteData) { return } // 刷新web界面 if (this.portraitModel == false) { - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" - ) + try { + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" + ); + LogUtil.info(this.TAG, `else runJavaScript setHtml success.`); + } catch (error) { + LogUtil.info(this.TAG, `else runJavaScript setHtml failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); + } } // save continue data let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) @@ -498,17 +551,17 @@ struct FolderItemComp { .width('100%') .height(56) .parallelGesture( - GestureGroup(GestureMode.Exclusive, - LongPressGesture() - .onAction(() => { - this.isLongPress = true - this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) - }) - .onActionEnd(() => { - this.isLongPress = false - this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) - }) - ) + GestureGroup(GestureMode.Exclusive, + LongPressGesture() + .onAction(() => { + this.isLongPress = true; + this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0); + }) + .onActionEnd(() => { + this.isLongPress = false; + this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0); + }) + ) ) } } \ No newline at end of file diff --git a/features/src/main/ets/components/NoteContent.ets b/features/src/main/ets/components/NoteContent.ets index aefe438..b0482ea 100644 --- a/features/src/main/ets/components/NoteContent.ets +++ b/features/src/main/ets/components/NoteContent.ets @@ -23,8 +23,9 @@ import { NoteTableColumn, SysDefFolderUuid, Favorite, - Delete -} from '@ohos/utils/src/main/ets/default/model/databaseModel/EnumData' + Delete, + FolderType +} from '@ohos/utils/src/main/ets/default/model/databaseModel/EnumData'; import StyleConstants from '@ohos/utils/src/main/ets/default/constants/StyleConstants' import { EditContentDialog, EditTitleDialog } from './CusDialogComp' import FolderUtil from '@ohos/utils/src/main/ets/default/baseUtil/FolderUtil' @@ -34,19 +35,30 @@ import OperationUtils from '@ohos/utils/src/main/ets/default/baseUtil/OperationU import router from '@system.router'; import inputMethod from '@ohos.inputMethod'; import { folderTextMap } from '@ohos/utils/src/main/ets/default/model/NoteBaseData' +import webview from '@ohos.web.webview'; +import common from '@ohos.app.ability.common'; -const TAG = "NoteContent" +const TAG: string = 'NoteContent'; -var timeID: number +let timeID: number = 0; +let noteContext = AppStorage.Get('noteContext')!; + +interface NoteContentType { + callbackhtml: (html: string) => void; + callbackImagePath: (imgName: string) => void; + callbackScheduledSave: (html: string) => void; + callbackPasteImage: (html: string) => void; + callbackGetSize: (fontSize: number) => void; +} @Component export struct NoteContent { - @Provide('SelectedNoteData') selectedNoteData: NoteData = AppStorage.Get('NewNote') + @Provide('SelectedNoteData') selectedNoteData: NoteData = AppStorage.Get('NewNote')!; @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray') @Provide('Issave') issave: number = 0 @Provide('EditModel') editModel: boolean = false @StorageLink('dpi') dpi: number = 240 - controllerShow: WebviewController + controllerShow: webview.WebviewController = new webview.WebviewController(); private editContentFlag = false @StorageLink('ScrollTopPercent') scrollTopPercent: number = 0.0 @@ -61,7 +73,7 @@ export struct NoteContent { if (!AppStorage.Has('remoteScrollTopPercent')) { return } - var scrollTopPercent = AppStorage.Get('remoteScrollTopPercent') + let scrollTopPercent = AppStorage.Get('remoteScrollTopPercent')!; if (scrollTopPercent < 0) { return } @@ -82,14 +94,18 @@ export struct NoteContent { AppStorage.Delete('isRemoteFocusOnSearch') } - noteContent = { - callbackhtml: (html) => { + noteContent: NoteContentType = { + callbackhtml: (html: string) => { LogUtil.info(TAG, 'note uuid is:' + this.selectedNoteData.uuid) + this.selectedNoteData.content_text = NoteUtil.contrastInitType(this.selectedNoteData.content_text); + if (this.selectedNoteData.content_text === html ) { + return; + }; this.selectedNoteData.content_text = html this.selectedNoteData.modified_time = new Date().getTime() let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null); LogUtil.info(TAG, 'update note success:' + this.selectedNoteData.uuid) AppStorage.SetOrCreate('NewNote', this.selectedNoteData) AppStorage.SetOrCreate('needRefresh', true) @@ -98,13 +114,13 @@ export struct NoteContent { AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "callbackhtml, set continue note success") }, - callbackImagePath: (imgName) => { + callbackImagePath: (imgName: string) => { // updata note image LogUtil.info(TAG, 'note imgPath is:' + imgName) this.selectedNoteData.content_img = imgName }, - callbackScheduledSave: (html) => { + callbackScheduledSave: (html: string) => { LogUtil.info(TAG, 'callbackScheduledSave') if (this.selectedNoteData.content_text == html) { LogUtil.info(TAG, 'callbackScheduledSave the same value return') @@ -114,7 +130,7 @@ export struct NoteContent { this.selectedNoteData.modified_time = new Date().getTime() let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null); LogUtil.info(TAG, 'callbackScheduledSave, update note success:' + this.selectedNoteData.uuid) // save continue data let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) @@ -122,14 +138,14 @@ export struct NoteContent { AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, 'callbackScheduledSave, set continue note success') }, - callbackPasteImage: (html) => { + callbackPasteImage: (html: string) => { if (html) { LogUtil.info(TAG, 'paste info' + html) let realHtml = "" - let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/ + let base64regex: RegExp = new RegExp('/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/'); if (html && html.indexOf("base64") > 0) { LogUtil.info(TAG, " getSrcFromHtml, src[1] : " + html) - let imgData = html.split(',')[1]; + let imgData: string = html.split(',')[1]; let imgType = 'png' if (html.indexOf("jpeg") > 0) { imgType = 'jpg' @@ -152,7 +168,7 @@ export struct NoteContent { LogUtil.info(TAG, 'paste info22223') } }, - callbackGetSize: (fontSize) => { + callbackGetSize: (fontSize: number) => { if (fontSize === 16) { this.selectedNoteData.slider_value = 0 } else if (fontSize === 18) { @@ -204,7 +220,7 @@ export struct NoteContent { "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')", () => { // wait for the image in the note to load - setTimeout(function () { + setTimeout(() => { self.restoreScrollTop() self.restoreFocus() }, 100) @@ -228,7 +244,13 @@ export struct NoteContent { clearInterval(timeID) } timeID = setInterval(() => { - this.controllerShow.runJavaScript("scheduledSaveContent()") + try { + this.controllerShow.runJavaScript("scheduledSaveContent()"); + LogUtil.info(TAG, `runJavaScript scheduledSaveContent success.`); + } catch (error) { + LogUtil.info(TAG, `runJavaScript scheduledSaveContent failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); + } }, 3000) LogUtil.info(TAG, "setInterval timeID : " + timeID) this.issave = 0 @@ -261,14 +283,20 @@ export struct ToolBarComp { @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray') @Consume('Issave') issave: number @Consume('EditModel') editModel: boolean - controllerShow: WebviewController - editContentDialogCtl: CustomDialogController = new CustomDialogController({ - builder: EditContentDialog({ confirm: this.confirm.bind(this) }), + controllerShow: webview.WebviewController = new webview.WebviewController(); + editContentDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: EditContentDialog({ confirm: (newTitle: string) => { + this.confirm(newTitle); + } }), alignment: DialogAlignment.Bottom, autoCancel: true, customStyle: true, }) + aboutToDisappear() { + this.editContentDialogCtl = null + } + confirm(excuteJs: string) { this.controllerShow.runJavaScript(excuteJs) } @@ -280,8 +308,15 @@ export struct ToolBarComp { .height(24) .width(24) .onClick(() => { - this.controllerShow.runJavaScript("RICH_EDITOR.setInputEnabled(false)") - this.controllerShow.runJavaScript("getHtmlContent()") + try { + this.controllerShow.runJavaScript("RICH_EDITOR.setInputEnabled(false)"); + this.controllerShow.runJavaScript("getHtmlContent()"); + LogUtil.info(TAG, `runJavaScript setInputEnabled and getHtmlContent success.`); + } catch (error) { + LogUtil.info(TAG, `runJavaScript setInputEnabled and getHtmlContent fail.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); + } + // 清除定时器 if (timeID != undefined) { LogUtil.info(TAG, "zoom, clearInterval timeID : " + timeID) @@ -298,16 +333,20 @@ export struct ToolBarComp { Image(this.selectedNoteData.is_favorite == Favorite.Yes ? $r('app.media.favorite') : $r('app.media.favorite_cancel')) .height(24).width(24) .onClick(() => { - this.selectedNoteData.is_favorite = (this.selectedNoteData.is_favorite == Favorite.Yes ? Favorite.No : Favorite.Yes) - // update note to db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, 'ToolBarComp, set continue note success') - NoteUtil.refreshAll() + try { + this.selectedNoteData.is_favorite = (this.selectedNoteData.is_favorite == Favorite.Yes ? Favorite.No : Favorite.Yes) + // update note to db + let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) + predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + AppStorage.SetOrCreate('ContinueNote', continueNote) + LogUtil.info(TAG, 'ToolBarComp, set continue note success') + NoteUtil.refreshAll() + } catch (error) { + LogUtil.error(TAG, 'favorite error: ' + JSON.stringify(error)); + } }) }.width(36) .visibility(this.selectedNoteData.is_deleted == Delete.Yes ? Visibility.None : Visibility.Visible) @@ -319,7 +358,6 @@ export struct ToolBarComp { .width(24) .onClick(() => { // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); // 清单 this.controllerShow.runJavaScript("javascript:RICH_EDITOR.setTodo()") @@ -335,10 +373,9 @@ export struct ToolBarComp { .width(24) .onClick(() => { // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); LogUtil.info(TAG, 'editContentDialogCtl start') - this.editContentDialogCtl.open() + this.editContentDialogCtl!.open(); }) }.width(42) .height(42) @@ -349,27 +386,26 @@ export struct ToolBarComp { Image($r('app.media.picture_white')).height(24).width(24) .onClick(async () => { // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); LogUtil.info(TAG, 'startAbility start') - await globalThis.noteContext.startAbilityForResult({ + await noteContext.startAbilityForResult({ parameters: { uri: "singleselect" }, bundleName: "com.ohos.photos", abilityName: "com.ohos.photos.MainAbility", }) - .then(v => { + .then((v: common.AbilityResult) => { let want = v['want']; if (want != null && want != undefined) { let param = want['parameters']; let imageUri = "" if (param != null && param != undefined) { - let uri = param['select-item-list']; + let uri = param['select-item-list'] as Record; imageUri = uri[0]; } // 拷贝 if (imageUri != null && imageUri != "") { OperationUtils.copy(imageUri).then((uriPath) => { - var path = "file://" + uriPath + let path = 'file://' + uriPath; LogUtil.info(TAG, 'image uri is:' + path) this.controllerShow.runJavaScript( "javascript:RICH_EDITOR.insertImage('" + path + "')" @@ -393,7 +429,6 @@ export struct ToolBarComp { .width(24) .onClick(() => { // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); this.controllerShow.runJavaScript("RICH_EDITOR.undo()") }) @@ -408,7 +443,6 @@ export struct ToolBarComp { .width(24) .onClick(() => { // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); this.controllerShow.runJavaScript("RICH_EDITOR.redo()") }) @@ -446,19 +480,25 @@ export struct NoteContentOverViewComp { @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = [] @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = [] @StorageLink('isUpdate') isUpdate: boolean = false - editTitleDialogCtl: CustomDialogController = new CustomDialogController({ - builder: EditTitleDialog({ confirm: this.confirm.bind(this) }), + editTitleDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: EditTitleDialog({ confirm: (newTitle: string) => { + this.confirm(newTitle); + } }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, }) + aboutToDisappear() { + this.editTitleDialogCtl = null + } + confirm(newTitle: string) { this.selectedNoteData.title = newTitle this.selectedNoteData.modified_time = new Date().getTime() let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null); // save continue data let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) @@ -469,7 +509,7 @@ export struct NoteContentOverViewComp { @Builder MenuBuilder() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { List() { - ForEach(this.AllFolderArray, (item) => { + ForEach(this.AllFolderArray, (item: FolderData) => { ListItem() { NoteDataMoveItemComp({ folderItem: item }) } @@ -477,14 +517,14 @@ export struct NoteContentOverViewComp { this.selectedNoteData.folder_uuid = item.uuid let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null); // save continue data let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "NoteContentOverViewComp MenuBuilder, set continue note success") NoteUtil.refreshAll() }) - }, noteItem => JSON.stringify(noteItem)) + }, (noteItem: NoteData) => JSON.stringify(noteItem)) }.listDirection(Axis.Vertical) .edgeEffect(EdgeEffect.Spring) .height(this.AllFolderArray.length > 12 ? 504 : (this.AllFolderArray.length - 3) * 56) @@ -505,7 +545,7 @@ export struct NoteContentOverViewComp { .margin({ left: 12, right: 24 }) .onClick(() => { clearInterval(timeID) - this.editTitleDialogCtl.open() + this.editTitleDialogCtl!.open(); }) }.height(40) .width(StyleConstants.PERCENTAGE_100) @@ -519,7 +559,7 @@ export struct NoteContentOverViewComp { .margin({ left: 12 }) Row() { Text(FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid)) == - folderTextMap["sys_def_myFavorites_uuid"] ? folderTextMap["sys_def_unClassified_uuid"] : + folderTextMap.sys_def_myFavorites_uuid ? folderTextMap.sys_def_unClassified_uuid : FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid))) .id(this.isUpdate + '') .fontSize(12) @@ -532,7 +572,7 @@ export struct NoteContentOverViewComp { .padding({ left: 8, right: 8, top: 4, bottom: 4 }) .margin({ left: 8 }) .borderRadius(16) - .backgroundColor(NoteUtil.getNoteBgColor(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid, SysDefFolderUuid.AllNotes, false)) + .backgroundColor(NoteUtil.getNoteBgColor(AppStorage.Get('AllFolderArray')!, this.selectedNoteData.folder_uuid, SysDefFolderUuid.AllNotes, false)) .bindMenu(this.MenuBuilder) }.alignItems(VerticalAlign.Top).height(40).width(StyleConstants.PERCENTAGE_100) } @@ -547,7 +587,7 @@ export struct NoteContentOverViewComp { struct NoteDataMoveItemComp { @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = [] @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = [] - private folderItem: FolderData + private folderItem: FolderData = new FolderData(0, '', new Date().getTime() + '', '', FolderType.CusDef, Delete.No, new Date().getTime(), new Date().getTime()); build() { Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.Center }) { diff --git a/features/src/main/ets/components/NoteContentComp.ets b/features/src/main/ets/components/NoteContentComp.ets index b6341e4..9654e7c 100644 --- a/features/src/main/ets/components/NoteContentComp.ets +++ b/features/src/main/ets/components/NoteContentComp.ets @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 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 @@ -13,204 +13,263 @@ * limitations under the License. */ -import DateUtil from '@ohos/utils/src/main/ets/default/baseUtil/DateUtil' -import RdbStoreUtil from '@ohos/utils/src/main/ets/default/baseUtil/RdbStoreUtil' -import FolderData from '@ohos/utils/src/main/ets/default/model/databaseModel/FolderData' -import NoteData from '@ohos/utils/src/main/ets/default/model/databaseModel/NoteData' +import DateUtil from '@ohos/utils/src/main/ets/default/baseUtil/DateUtil'; +import RdbStoreUtil from '@ohos/utils/src/main/ets/default/baseUtil/RdbStoreUtil'; +import FolderData from '@ohos/utils/src/main/ets/default/model/databaseModel/FolderData'; +import NoteData from '@ohos/utils/src/main/ets/default/model/databaseModel/NoteData'; import { TableName, NoteTableColumn, SysDefFolderUuid, Favorite, - Delete -} from '@ohos/utils/src/main/ets/default/model/databaseModel/EnumData' -import StyleConstants from '@ohos/utils/src/main/ets/default/constants/StyleConstants' -import { EditContentDialog, DeleteDialog, EditTitleDialog } from './CusDialogComp' -import FolderUtil from '@ohos/utils/src/main/ets/default/baseUtil/FolderUtil' -import NoteUtil from '@ohos/utils/src/main/ets/default/baseUtil/NoteUtil' -import prompt from '@system.prompt' -import util from '@ohos.util' -import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil' -import OperationUtils from '@ohos/utils/src/main/ets/default/baseUtil/OperationUtils' -import mediaquery from '@ohos.mediaquery' + Delete, + FolderType +} from '@ohos/utils/src/main/ets/default/model/databaseModel/EnumData'; +import StyleConstants from '@ohos/utils/src/main/ets/default/constants/StyleConstants'; +import { EditContentDialog, DeleteDialog, EditTitleDialog } from './CusDialogComp'; +import FolderUtil from '@ohos/utils/src/main/ets/default/baseUtil/FolderUtil'; +import NoteUtil from '@ohos/utils/src/main/ets/default/baseUtil/NoteUtil'; +import { promptAction } from '@kit.ArkUI'; +import util from '@ohos.util'; +import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil'; +import OperationUtils from '@ohos/utils/src/main/ets/default/baseUtil/OperationUtils'; +import mediaquery from '@ohos.mediaquery'; import inputMethod from '@ohos.inputMethod'; -import { folderTextMap } from '@ohos/utils/src/main/ets/default/model/NoteBaseData' -import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { folderTextMap } from '@ohos/utils/src/main/ets/default/model/NoteBaseData'; +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; +import webview from '@ohos.web.webview'; +import common from '@ohos.app.ability.common'; +import { BusinessError } from '@ohos.base'; +import resourceManager from '@ohos.resourceManager'; -const TAG = "NoteContentComp" +const TAG = 'NoteContentComp'; -var timeId: number +let timeId: number = 0; +let noteContext = AppStorage.Get('noteContext')!; // Note content component -let inSetValue = AppStorage.Link('inSetValue') +let inSetValue: string = AppStorage.Link('inSetValue'); + +interface NoteContentType { + callbackhtml: (html: string) => void; + callbackImagePath: (imgName: string) => void; + callbackhtmlSave: (html: string) => void; + callbackScheduledSave: (html: string) => void; + callbackPasteImage: (html: string) => void; + callbackGetSize: (fontSize: number) => void; +} @Component export struct NoteContentComp { - @Consume('SelectedNoteData') selectedNoteData: NoteData - @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray') - @Consume('SelectedFolderData') selectedFolderData: FolderData - @Consume('RefreshFlag') refreshFlag: number - @Consume('EditModel') editModel: boolean - @Consume('SectionStatus') sectionStatus: number - @Consume('LastSectionStatus') lastSectionStatus: number - @Consume('Issave') issave: number - @Consume('Search') search: boolean - @StorageLink('dpi') dpi: number = 240 - controllerShow: WebviewController - private editContentFlag = false - @State uri1: string = "" - private context = getContext(this) - @StorageLink('ScrollTopPercent') scrollTopPercent: number = 0.0 - @StorageLink('isUpdate') isUpdate: boolean = false - @StorageLink('refreshCurrentNote') @Watch('isDataChange') refreshCurrentNote: boolean = false - @Consume('AsideWidth') asideWidth: number + @Consume('SelectedNoteData') selectedNoteData: NoteData; + @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray'); + @Consume('SelectedFolderData') selectedFolderData: FolderData; + @Consume('RefreshFlag') refreshFlag: number; + @Consume('EditModel') editModel: boolean; + @Consume('SectionStatus') sectionStatus: number; + @Consume('LastSectionStatus') lastSectionStatus: number; + @Consume('Issave') issave: number; + @Consume('Search') search: boolean; + @StorageLink('dpi') dpi: number = 240; + controllerShow: webview.WebviewController = new webview.WebviewController(); + private editContentFlag = false; + @State uri1: string = ""; + private context = getContext(this); + @StorageLink('ScrollTopPercent') scrollTopPercent: number = 0.0; + @StorageLink('isUpdate') isUpdate: boolean = false; + @StorageLink('refreshCurrentNote') @Watch('isDataChange') refreshCurrentNote: boolean = false; + @Consume('AsideWidth') asideWidth: number; isDataChange() { if (!this.refreshCurrentNote) { - return + return; } - this.controllerShow.runJavaScript("RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')") - this.refreshCurrentNote = false + try { + this.controllerShow.runJavaScript("RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')"); + LogUtil.info(TAG, `runJavaScript setHtml success.`); + } catch (error) { + LogUtil.error(TAG, `runJavaScript setHtml failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); + } + this.refreshCurrentNote = false; } storeScrollTop(scrollTop: number) { if (scrollTop < 0) { - return + return; } - AppStorage.SetOrCreate('ScrollTopPercent', scrollTop / this.controllerShow.getPageHeight()) + AppStorage.SetOrCreate('ScrollTopPercent', scrollTop / this.controllerShow.getPageHeight()); } restoreScrollTop() { - if (!AppStorage.Has('remoteScrollTopPercent')) { - return - } - var scrollTopPercent = AppStorage.Get('remoteScrollTopPercent') - if (scrollTopPercent < 0) { - return + try { + if (!AppStorage.Has('remoteScrollTopPercent')) { + return; + } + let scrollTopPercent = AppStorage.Get('remoteScrollTopPercent')!; + if (scrollTopPercent < 0) { + return; + } + this.controllerShow.runJavaScript( + 'document.documentElement.scrollTop = ' + this.controllerShow.getPageHeight() * scrollTopPercent + ) + } catch (error) { + LogUtil.error(TAG, `restoreScrollTop failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); } - this.controllerShow.runJavaScript( - 'document.documentElement.scrollTop = ' + this.controllerShow.getPageHeight() * scrollTopPercent - ) } restoreFocus() { if (!AppStorage.Has('isRemoteFocusOnSearch')) { - return + return; } - let isRemoteFocusOnSearch = AppStorage.Get('isRemoteFocusOnSearch') + let isRemoteFocusOnSearch = AppStorage.Get('isRemoteFocusOnSearch'); if (isRemoteFocusOnSearch) { - focusControl.requestFocus('searchInput') + focusControl.requestFocus('searchInput'); } - AppStorage.Delete('isRemoteFocusOnSearch') + AppStorage.Delete('isRemoteFocusOnSearch'); } - noteContent = { + noteContent: NoteContentType = { callbackhtml: (html) => { - LogUtil.info(TAG, 'note uuid is:' + this.selectedNoteData.uuid) - this.selectedNoteData.content_text = html - this.selectedNoteData.modified_time = new Date().getTime() - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - LogUtil.info(TAG, 'update note success:' + this.selectedNoteData.uuid) - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, "callbackhtml, set continue note success") - return "AceString" + try { + LogUtil.info(TAG, 'note uuid is:' + this.selectedNoteData.uuid); + this.selectedNoteData.content_text = NoteUtil.contrastInitType(this.selectedNoteData.content_text); + if (this.selectedNoteData.content_text === html) { + return; + } + ; + this.selectedNoteData.content_text = html; + this.selectedNoteData.modified_time = new Date().getTime(); + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicatesNote, null); + LogUtil.info(TAG, 'update note success:' + this.selectedNoteData.uuid); + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()); + AppStorage.SetOrCreate('ContinueNote', continueNote); + LogUtil.info(TAG, 'callbackhtml, set continue note success'); + return 'AceString'; + } catch (error) { + LogUtil.error(TAG, 'callbackhtml error: ' + JSON.stringify(error)); + return 'AceString'; + } }, callbackImagePath: (imgName) => { // updata note image - LogUtil.info(TAG, 'note imgName is:' + imgName) - this.selectedNoteData.content_img = imgName + try { + LogUtil.info(TAG, 'note imgName is:' + imgName); + this.selectedNoteData.content_img = imgName; + LogUtil.info(TAG, 'set content_img success'); + } catch (error) { + LogUtil.error(TAG, 'callbackImagePath error: ' + JSON.stringify(error)); + } }, callbackhtmlSave: (html) => { - LogUtil.info(TAG, 'note uuid is:' + this.selectedNoteData.uuid) - this.selectedNoteData.content_text = html - this.selectedNoteData.modified_time = new Date().getTime() - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - LogUtil.info(TAG, 'update note success:' + this.selectedNoteData.uuid) - this.sectionStatus = this.lastSectionStatus - this.sectionStatus = mediaquery.matchMediaSync('(width < 2000)').matches ? 2 : 3 - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - AppStorage.SetOrCreate('ContinueSection', this.sectionStatus) - LogUtil.info(TAG, "callbackhtmlSave, set continue note and section success") - return "AceString" + try { + LogUtil.info(TAG, 'note uuid is:' + this.selectedNoteData.uuid); + this.selectedNoteData.content_text = html; + this.selectedNoteData.modified_time = new Date().getTime(); + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicatesNote, null); + LogUtil.info(TAG, 'update note success:' + this.selectedNoteData.uuid); + this.sectionStatus = this.lastSectionStatus; + this.sectionStatus = mediaquery.matchMediaSync('(width < 2000)').matches ? 2 : 3; + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()); + AppStorage.SetOrCreate('ContinueNote', continueNote); + AppStorage.SetOrCreate('ContinueSection', this.sectionStatus); + LogUtil.info(TAG, 'callbackhtmlSave, set continue note and section success'); + return 'AceString'; + } catch (error) { + LogUtil.error(TAG, 'callbackhtmlSave error: ' + JSON.stringify(error)); + return 'AceString'; + } }, callbackScheduledSave: (html) => { - LogUtil.info(TAG, 'callbackScheduledSave') - if (this.selectedNoteData.content_text == html) { - LogUtil.info(TAG, 'callbackScheduledSave the same value return') - return; + try { + LogUtil.info(TAG, 'callbackScheduledSave'); + if (this.selectedNoteData.content_text == html) { + LogUtil.info(TAG, 'callbackScheduledSave the same value return'); + return; + } + this.selectedNoteData.content_text = html; + this.selectedNoteData.modified_time = new Date().getTime(); + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicatesNote, null); + LogUtil.info(TAG, 'callbackScheduledSave, update note success:' + this.selectedNoteData.uuid); + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()); + AppStorage.SetOrCreate('ContinueNote', continueNote); + LogUtil.info(TAG, 'callbackScheduledSave, set continue note success'); + } catch (error) { + LogUtil.error(TAG, 'callbackScheduledSave error: ' + JSON.stringify(error)); } - this.selectedNoteData.content_text = html - this.selectedNoteData.modified_time = new Date().getTime() - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - LogUtil.info(TAG, 'callbackScheduledSave, update note success:' + this.selectedNoteData.uuid) - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, 'callbackScheduledSave, set continue note success') }, callbackPasteImage: (html) => { - if (html) { - LogUtil.info(TAG, 'paste info' + html) - let realHtml = "" - let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/ - if (html && html.indexOf("base64") > 0) { - LogUtil.info(TAG, " getSrcFromHtml, src[1] : " + html) - let imgData = html.split(',')[1]; - let imgType = 'png' - if (html.indexOf("jpeg") > 0) { - imgType = 'jpg' - } else if (html.indexOf("gif") > 0) { - imgType = 'gif' - } - let filePath = "" - if (base64regex.test(imgData)) { - let base64 = new util.Base64() - let decodeArr = base64.decodeSync(imgData) - filePath = OperationUtils.saveImageData(decodeArr, imgType) - } else { - filePath = OperationUtils.saveImage(imgData, imgType) + try { + if (html) { + LogUtil.info(TAG, 'paste info' + html); + let realHtml = ""; + let base64regex: RegExp = new RegExp('/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/'); + if (html && html.indexOf('base64') > 0) { + LogUtil.info(TAG, ' getSrcFromHtml, src[1] : ' + html); + let imgData = html.split(',')[1]; + let imgType = 'png'; + if (html.indexOf('jpeg') > 0) { + imgType = 'jpg'; + } else if (html.indexOf('gif') > 0) { + imgType = 'gif'; + } + let filePath = ""; + if (base64regex.test(imgData)) { + let base64 = new util.Base64(); + let decodeArr = base64.decodeSync(imgData); + filePath = OperationUtils.saveImageData(decodeArr, imgType); + } else { + filePath = OperationUtils.saveImage(imgData, imgType); + } + realHtml = 'file://' + filePath; } - realHtml = "file://" + filePath + LogUtil.info(TAG, 'paste info11-' + realHtml); + this.controllerShow.runJavaScript("javascript:RICH_EDITOR.insertImageHtml('" + realHtml + "')"); + LogUtil.info(TAG, 'paste info11--' + realHtml); + } else { + LogUtil.info(TAG, 'paste info22225'); } - LogUtil.info(TAG, 'paste info11-' + realHtml) - this.controllerShow.runJavaScript("javascript:RICH_EDITOR.insertImageHtml('" + realHtml + "')") - LogUtil.info(TAG, 'paste info11--' + realHtml) - } else { - LogUtil.info(TAG, 'paste info22225') + } catch (error) { + LogUtil.error(TAG, `callbackPasteImage failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); } }, callbackGetSize: (fontSize) => { if (fontSize === 16) { - this.selectedNoteData.slider_value = 0 + this.selectedNoteData.slider_value = 0; } else if (fontSize === 18) { - this.selectedNoteData.slider_value = 4 + this.selectedNoteData.slider_value = 4; } else if (fontSize === 24) { - this.selectedNoteData.slider_value = 8 + this.selectedNoteData.slider_value = 8; } else if (fontSize === 32) { - this.selectedNoteData.slider_value = 12 + this.selectedNoteData.slider_value = 12; } else if (fontSize === 48) { - this.selectedNoteData.slider_value = 16 + this.selectedNoteData.slider_value = 16; } } } build() { Stack({ alignContent: Alignment.Bottom }) { - Flex({ direction: FlexDirection.Column, wrap: FlexWrap.NoWrap, - alignItems: ItemAlign.Start, alignContent: FlexAlign.SpaceAround }) { + Flex({ + direction: FlexDirection.Column, + wrap: FlexWrap.NoWrap, + alignItems: ItemAlign.Start, + alignContent: FlexAlign.SpaceAround + }) { Column() { ToolBarComp({ controllerShow: this.controllerShow }) } @@ -225,39 +284,45 @@ export struct NoteContentComp { .javaScriptAccess(true) .javaScriptProxy({ object: this.noteContent, - name: "callBackToApp", // html--> name.method - methodList: ["callbackhtml", "callbackhtmlSave", "callbackScheduledSave", "callbackGetSize", "callbackPasteImage", "callbackImagePath"], + name: 'callBackToApp', // html--> name.method + methodList: ['callbackhtml', 'callbackhtmlSave', 'callbackScheduledSave', 'callbackGetSize', + 'callbackPasteImage', 'callbackImagePath'], controller: this.controllerShow }) .enabled(this.sectionStatus !== 1 ? false : true) .onPageEnd((e) => { - if (this.dpi <= 240) { - this.controllerShow.runJavaScript("changeSizeToRk()") - } else if (this.dpi <= 320 && this.dpi > 240) { - this.controllerShow.runJavaScript("changeSizeToPhone()") - } else { - this.controllerShow.runJavaScript("changeSizeToTablet()") - } - if (AppStorage.Get('breakPoint') !== 'sm') { - this.controllerShow.runJavaScript("hiddenButton()") - } - LogUtil.info(TAG, "finish loadurl") - if (this.selectedNoteData) { - let self = this - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')", - () => { - // wait for the image in the note to load - setTimeout(function () { - self.restoreScrollTop() - self.restoreFocus() - }, 100) - } - ) - } - // 初次加载为为小屏预览模式 - if (this.sectionStatus != 1) { - this.controllerShow.runJavaScript("RICH_EDITOR.setInputEnabled(false)") + try { + if (this.dpi <= 240) { + this.controllerShow.runJavaScript('changeSizeToRk()'); + } else if (this.dpi <= 320 && this.dpi > 240) { + this.controllerShow.runJavaScript('changeSizeToPhone()'); + } else { + this.controllerShow.runJavaScript('changeSizeToTablet()'); + } + if (AppStorage.Get('breakPoint') !== 'sm') { + this.controllerShow.runJavaScript('hiddenButton()'); + } + LogUtil.info(TAG, 'finish loadurl'); + if (this.selectedNoteData) { + let self = this; + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')", + () => { + // wait for the image in the note to load + setTimeout(() => { + self.restoreScrollTop(); + self.restoreFocus(); + }, 100) + } + ); + } + // 初次加载为为小屏预览模式 + if (this.sectionStatus != 1) { + this.controllerShow.runJavaScript('RICH_EDITOR.setInputEnabled(false)'); + } + } catch (error) { + LogUtil.info(TAG, + `runJavaScript onPageEnd error. code:${JSON.stringify(error.code)},message:${error.message}`); } }) .imageAccess(true) @@ -268,48 +333,54 @@ export struct NoteContentComp { .height('88%') .width('100%') .onScroll((event) => { - this.storeScrollTop(event.yOffset) + this.storeScrollTop(event.yOffset); }) } .margin({ left: 24, right: 24 }) // .width(StyleConstants.PERCENTAGE_100) .enabled(this.selectedNoteData && this.selectedNoteData.is_deleted == Delete.Yes ? false : true) .onClick(() => { - this.issave = 0 - LogUtil.info(TAG, "editModel : " + this.editModel + ", sectionStatus : " + this.sectionStatus) - let isContinue = AppStorage.Get('IsContinue') - LogUtil.info(TAG, "isContinue : " + isContinue) - // 点击第三屏进入全屏编辑模式 - if (this.sectionStatus != 1 || isContinue) { - this.asideWidth = 0 - this.lastSectionStatus = this.sectionStatus - this.sectionStatus = 1 - this.controllerShow.runJavaScript("RICH_EDITOR.setInputEnabled(true)") - // 添加定时器:3s自动保存 - if (timeId) { - clearInterval(timeId) + try { + this.issave = 0; + LogUtil.info(TAG, 'editModel : ' + this.editModel + ', sectionStatus : ' + this.sectionStatus); + let isContinue = AppStorage.Get('IsContinue'); + LogUtil.info(TAG, 'isContinue : ' + isContinue); + // 点击第三屏进入全屏编辑模式 + if (this.sectionStatus != 1 || isContinue) { + this.asideWidth = 0; + this.lastSectionStatus = this.sectionStatus; + this.sectionStatus = 1; + this.controllerShow.runJavaScript('RICH_EDITOR.setInputEnabled(true)'); + // 添加定时器:3s自动保存 + if (timeId) { + clearInterval(timeId); + } + timeId = setInterval(() => { + this.controllerShow.runJavaScript('scheduledSaveContent()'); + }, 3000) + LogUtil.info(TAG, 'setInterval timeId : ' + timeId); + // save continue data + AppStorage.SetOrCreate('ContinueSection', this.sectionStatus); + LogUtil.info(TAG, 'set continue section success'); + this.editModel = !this.editModel; + AppStorage.SetOrCreate('IsContinue', false); } - timeId = setInterval(() => { - this.controllerShow.runJavaScript("scheduledSaveContent()") - }, 3000) - LogUtil.info(TAG, "setInterval timeId : " + timeId) - // save continue data - AppStorage.SetOrCreate('ContinueSection', this.sectionStatus) - LogUtil.info(TAG, "set continue section success") - this.editModel = !this.editModel - AppStorage.SetOrCreate('IsContinue', false) + } catch (error) { + LogUtil.error(TAG, `Column failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); } }) } .id(this.isUpdate + '') .height(StyleConstants.PERCENTAGE_100) - .visibility(FolderUtil.getNoteCount(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) == 0 ? Visibility.Hidden : Visibility.Visible) + .visibility(FolderUtil.getNoteCount(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) == 0 ? + Visibility.Hidden : Visibility.Visible) Column() { } - .height("100%") - .width("100%") - .backgroundColor("#18181A") + .height('100%') + .width('100%') + .backgroundColor('#18181A') .opacity(0.1) .visibility(this.search ? Visibility.Visible : Visibility.Hidden) } @@ -318,30 +389,34 @@ export struct NoteContentComp { } aboutToAppear(): void { - LogUtil.info(TAG, "aboutToAppear") + LogUtil.info(TAG, 'aboutToAppear') } aboutToDisappear(): void { clearInterval(timeId) - LogUtil.info(TAG, "aboutToDisappear") + LogUtil.info(TAG, 'aboutToDisappear') } } @Component export struct NoteContentOverViewComp { - @Consume('SelectedNoteData') selectedNoteData: NoteData - @StorageLink('AllFolderArray') @Watch('getArray') AllFolderArray: FolderData[] = [] - @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = [] - @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray') - @Consume('SelectedFolderData') selectedFolderData: FolderData - @Consume('EditModel') editModel: boolean - @Consume('SectionStatus') sectionStatus: number - @Consume('RefreshFlag') refreshFlag: number - @StorageLink('isUpdate') isUpdate: boolean = false - NoteDataMoveArray: FolderData[] - controllerShow: WebviewController - editTitleDialogCtl: CustomDialogController = new CustomDialogController({ - builder: EditTitleDialog({ confirm: this.confirm.bind(this) }), + @Consume('SelectedNoteData') selectedNoteData: NoteData; + @StorageLink('AllFolderArray') @Watch('getArray') AllFolderArray: FolderData[] = []; + @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = []; + @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray'); + @Consume('SelectedFolderData') selectedFolderData: FolderData; + @Consume('EditModel') editModel: boolean; + @Consume('SectionStatus') sectionStatus: number; + @Consume('RefreshFlag') refreshFlag: number; + @StorageLink('isUpdate') isUpdate: boolean = false; + NoteDataMoveArray: FolderData[] = []; + controllerShow: webview.WebviewController = new webview.WebviewController(); + editTitleDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: EditContentDialog({ + confirm: (newTitle: string) => { + this.confirm(newTitle); + } + }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, @@ -349,75 +424,103 @@ export struct NoteContentOverViewComp { getArray() { this.NoteDataMoveArray = this.AllFolderArray.slice(2, this.AllFolderArray.length); + if (this.AllFolderArray[1] === undefined || this.AllFolderArray[1] === null) { + LogUtil.info(TAG, 'this AllFolderArray[1] undefined'); + return; + } this.NoteDataMoveArray.push(this.AllFolderArray[1]); } aboutToAppear() { this.NoteDataMoveArray = this.AllFolderArray.slice(2, this.AllFolderArray.length); + if (this.AllFolderArray[1] === undefined || this.AllFolderArray[1] === null) { + LogUtil.info(TAG, 'this AllFolderArray[1] undefined'); + return; + } this.NoteDataMoveArray.push(this.AllFolderArray[1]); } + aboutToDisappear() { + this.editTitleDialogCtl = null; + } + confirm(newTitle: string) { - this.selectedNoteData.title = newTitle - this.selectedNoteData.modified_time = new Date().getTime() - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - NoteUtil.refreshAll() + try { + this.selectedNoteData.title = newTitle; + this.selectedNoteData.modified_time = new Date().getTime(); + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicatesNote, null); + NoteUtil.refreshAll(); + } catch (error) { + LogUtil.error(TAG, 'confirm error: ' + JSON.stringify(error)); + } } - @Builder MenuBuilder() { + @Builder + MenuBuilder() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { List() { - ForEach(this.NoteDataMoveArray, (item) => { - ListItem() { - NoteDataMoveItemCompTablet({ folderItem: item, uuid: this.selectedNoteData.folder_uuid }) - } - .onClick(() => { - this.selectedNoteData.folder_uuid = item.uuid - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - if (this.sectionStatus != 1) { - this.selectedNoteData = NoteUtil.getFirstNoteData(this.AllNoteArray, this.selectedFolderData.uuid) - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" - ) - this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) - } else { - this.selectedFolderData = FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), item.uuid) + if (this.NoteDataMoveArray !== undefined && this.NoteDataMoveArray !== null && + this.NoteDataMoveArray.length > 0) { + ForEach(this.NoteDataMoveArray, (item: FolderData) => { + ListItem() { + NoteDataMoveItemCompTablet({ folderItem: item, uuid: this.selectedNoteData.folder_uuid }) } - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, "NoteContentOverViewComp, MenuBuilder, set continue note success") - NoteUtil.refreshAll() - }) - }, noteItem => noteItem.uuid) + .onClick(() => { + try { + this.selectedNoteData.folder_uuid = item.uuid; + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicatesNote, null); + if (this.sectionStatus != 1) { + this.selectedNoteData = NoteUtil.getFirstNoteData(this.AllNoteArray, this.selectedFolderData.uuid)!; + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" + ) + this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0); + } else { + this.selectedFolderData = FolderUtil.getFolderData(AppStorage.Get('AllFolderArray')!, item.uuid); + } + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()); + AppStorage.SetOrCreate('ContinueNote', continueNote); + LogUtil.info(TAG, 'NoteContentOverViewComp, MenuBuilder, set continue note success'); + NoteUtil.refreshAll(); + } catch (error) { + LogUtil.error(TAG, 'ListItem click error: ' + JSON.stringify(error)); + } + }) + }, (noteItem: NoteData) => noteItem.uuid) + } }.listDirection(Axis.Vertical) .edgeEffect(EdgeEffect.Spring) .height(this.AllFolderArray.length > 12 ? 504 : (this.AllFolderArray.length - 3) * 56) } .width(148) - .backgroundColor($r("app.color.color_fffffB")) + .backgroundColor($r('app.color.color_fffffB')) .padding({ left: 24, right: 24 }) } build() { if (this.selectedNoteData) { - Flex({ direction: FlexDirection.Column, wrap: FlexWrap.NoWrap, - justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Flex({ + direction: FlexDirection.Column, + wrap: FlexWrap.NoWrap, + justifyContent: FlexAlign.SpaceBetween, + alignItems: ItemAlign.Center + }) { Row() { Text(this.selectedNoteData.title) .id(this.isUpdate + '') .fontSize(30) .margin({ left: 0, right: 24 }) .onClick(() => { - clearInterval(timeId) - this.editTitleDialogCtl.open() + clearInterval(timeId); + this.editTitleDialogCtl!.open(); // save continue data - AppStorage.SetOrCreate('ContinueSection', this.sectionStatus) - LogUtil.info(TAG, "NoteContentComp, set continue section success") + AppStorage.SetOrCreate('ContinueSection', this.sectionStatus); + LogUtil.info(TAG, 'NoteContentComp, set continue section success'); }) }.height(40) .width(StyleConstants.PERCENTAGE_100) @@ -427,15 +530,17 @@ export struct NoteContentOverViewComp { .id(this.isUpdate + '') .fontSize(12) .padding({ top: 4, bottom: 4 }) - .fontColor($r("app.color.modified_time_font_color")) + .fontColor($r('app.color.modified_time_font_color')) .margin({ left: 0 }) Row() { - Text(FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid)) == - folderTextMap["sys_def_myFavorites_uuid"] ? folderTextMap["sys_def_unClassified_uuid"] : - FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid))) + Text(FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), + this.selectedNoteData.folder_uuid)) == + folderTextMap.sys_def_myFavorites_uuid ? folderTextMap.sys_def_unClassified_uuid : + FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), + this.selectedNoteData.folder_uuid))) .id(this.isUpdate + '') .fontSize(12) - .fontColor($r("app.color.list_modified_time_font_color")) + .fontColor($r('app.color.list_modified_time_font_color')) .padding({ top: 1 }) Image($r('app.media.triangle')) .width(6) @@ -443,10 +548,16 @@ export struct NoteContentOverViewComp { .margin({ left: 4 }) } .id(this.isUpdate + '') - .padding({ left: 8, right: 8, top: 4, bottom: 4 }) + .padding({ + left: 8, + right: 8, + top: 4, + bottom: 4 + }) .margin({ left: 8 }) .borderRadius(16) - .backgroundColor(NoteUtil.getNoteBgColor(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid, SysDefFolderUuid.AllNotes, false)) + .backgroundColor(NoteUtil.getNoteBgColor(AppStorage.Get('AllFolderArray')!, this.selectedNoteData.folder_uuid, + SysDefFolderUuid.AllNotes, false)) .bindMenu(this.MenuBuilder) }.alignItems(VerticalAlign.Top).height(40).width(StyleConstants.PERCENTAGE_100) } @@ -459,103 +570,134 @@ export struct NoteContentOverViewComp { @Component export struct ToolBarComp { - @Consume('SelectedNoteData') selectedNoteData: NoteData - @Consume('RefreshFlag') refreshFlag: number - @Consume('SectionStatus') sectionStatus: number - @Consume('LastSectionStatus') lastSectionStatus: number - @Consume('SelectedFolderData') selectedFolderData: FolderData - @Consume('ChooseNote') chooseNote: boolean - @Consume('PortraitModel') portraitModel: boolean - @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray') - @Consume('EditModel') editModel: boolean - @Consume('Issave') issave: number - controllerShow: WebviewController - private context = getContext(this) - noteDataDeleteDialogCtl: CustomDialogController = new CustomDialogController({ - builder: DeleteDialog({ onConfirm: this.onDeleteConfirm.bind(this) }), + @Consume('SelectedNoteData') selectedNoteData: NoteData; + @Consume('RefreshFlag') refreshFlag: number; + @Consume('SectionStatus') sectionStatus: number; + @Consume('LastSectionStatus') lastSectionStatus: number; + @Consume('SelectedFolderData') selectedFolderData: FolderData; + @Consume('ChooseNote') chooseNote: boolean; + @Consume('PortraitModel') portraitModel: boolean; + @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray'); + @Consume('EditModel') editModel: boolean; + @Consume('Issave') issave: number; + controllerShow: webview.WebviewController = new webview.WebviewController(); + private context = getContext(this); + noteDataDeleteDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: DeleteDialog({ + onConfirm: () => { + this.onDeleteConfirm(); + } + }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, - }) - @Consume('AsideWidth') asideWidth: number + }); + @Consume('AsideWidth') asideWidth: number; + + aboutToDisappear() { + this.noteDataDeleteDialogCtl = null; + this.editContentDialogCtl = null; + } onDeleteConfirm() { - if (this.selectedFolderData.uuid != SysDefFolderUuid.RecentDeletes) { - this.selectedNoteData.is_deleted = Delete.Yes - this.selectedNoteData.deleted_time = new Date().getTime() - // update note to db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - } else { - NoteUtil.removeNoteData(this.AllNoteArray, this.selectedNoteData.uuid) - // delete note from db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.delete(predicates_note, null) + try { + if (this.selectedFolderData.uuid != SysDefFolderUuid.RecentDeletes) { + this.selectedNoteData.is_deleted = Delete.Yes; + this.selectedNoteData.deleted_time = new Date().getTime(); + // update note to db + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicatesNote, null); + } else { + NoteUtil.removeNoteData(this.AllNoteArray, this.selectedNoteData.uuid); + // delete note from db + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.delete(predicatesNote, null); + } + this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0); + this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid)!; + try { + this.controllerShow.runJavaScript("RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text! + "')"); + } catch (error) { + LogUtil.info(TAG, `setHtml error. code:${JSON.stringify(error.code)},message:${error.message}`); + } + this.chooseNote = false; + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()); + AppStorage.SetOrCreate('ContinueNote', continueNote); + LogUtil.info(TAG, 'NoteContentOverViewComp, set continue note success'); + AppStorage.SetOrCreate('isUpdate', true); + } catch (error) { + LogUtil.error(TAG, 'onDeleteConfirm error: ' + JSON.stringify(error)); } - this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) - this.controllerShow.runJavaScript("RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')") - this.chooseNote = false - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, "NoteContentOverViewComp, set continue note success") - AppStorage.SetOrCreate('isUpdate', true) } - editContentDialogCtl: CustomDialogController = new CustomDialogController({ - builder: EditContentDialog({ confirm: this.confirm.bind(this) }), + editContentDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: EditContentDialog({ + confirm: (newTitle: string) => { + this.confirm(newTitle); + } + }), alignment: DialogAlignment.Bottom, autoCancel: true, customStyle: true, }) confirm(excuteJs: string) { - this.controllerShow.runJavaScript(excuteJs) + this.controllerShow.runJavaScript(excuteJs); } build() { - Flex({ direction: FlexDirection.Row, wrap: FlexWrap.NoWrap, - justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Flex({ + direction: FlexDirection.Row, + wrap: FlexWrap.NoWrap, + justifyContent: FlexAlign.SpaceBetween, + alignItems: ItemAlign.Center + }) { Image(this.sectionStatus == 1 ? $r('app.media.narrow') : $r('app.media.zoom')) .height(24) .width(24) .onClick(() => { - if (this.sectionStatus != 1) { - this.lastSectionStatus = this.sectionStatus - this.sectionStatus = 1 - this.asideWidth = 0 - this.controllerShow.runJavaScript("RICH_EDITOR.setInputEnabled(true)") - } else { - if (this.lastSectionStatus != undefined) { - this.asideWidth = 200 - // 切换为小屏预览模式 - this.controllerShow.runJavaScript("RICH_EDITOR.setInputEnabled(false)") - this.sectionStatus = this.lastSectionStatus - // 退出全屏时存库 - LogUtil.info(TAG, "close note" + this.selectedNoteData.uuid) - this.controllerShow.runJavaScript("saveHtmlContent()") - //退出键盘 - // @ts-ignore - inputMethod.getController().stopInputSession(); - // 清除定时器 - if (timeId != undefined) { - LogUtil.info(TAG, "zoom, clearInterval timeId : " + timeId) - clearInterval(timeId) - } + try { + if (this.sectionStatus != 1) { + this.lastSectionStatus = this.sectionStatus; + this.sectionStatus = 1; + this.asideWidth = 0; + this.controllerShow.runJavaScript('RICH_EDITOR.setInputEnabled(true)'); } else { - this.sectionStatus = 3 + if (this.lastSectionStatus != undefined) { + this.asideWidth = 200; + // 切换为小屏预览模式 + this.controllerShow.runJavaScript('RICH_EDITOR.setInputEnabled(false)'); + this.sectionStatus = this.lastSectionStatus; + // 退出全屏时存库 + LogUtil.info(TAG, 'close note' + this.selectedNoteData.uuid); + this.controllerShow.runJavaScript('saveHtmlContent()'); + //退出键盘 + inputMethod.getController().stopInputSession(); + // 清除定时器 + if (timeId != undefined) { + LogUtil.info(TAG, 'zoom, clearInterval timeId : ' + timeId); + clearInterval(timeId); + } + } else { + this.sectionStatus = 3; + } } + this.editModel = !this.editModel; + // save continue data + AppStorage.SetOrCreate('ContinueSection', this.sectionStatus); + LogUtil.info(TAG, 'ToolBarComp, set continue section success'); + NoteUtil.refreshAll(); + } catch (error) { + LogUtil.error(TAG, + `Image ${this.sectionStatus == 1 ? 'narrow' : 'zoom'} click failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); } - this.editModel = !this.editModel - // save continue data - AppStorage.SetOrCreate('ContinueSection', this.sectionStatus) - LogUtil.info(TAG, "ToolBarComp, set continue section success") - NoteUtil.refreshAll() }) - .visibility(!this.selectedNoteData ? Visibility.None : this.selectedNoteData.is_deleted == Delete.Yes ? Visibility.None : Visibility.Visible) + .visibility(!this.selectedNoteData ? Visibility.None : + this.selectedNoteData.is_deleted == Delete.Yes ? Visibility.None : Visibility.Visible) if (this.selectedNoteData) { if (this.selectedNoteData.is_deleted == Delete.Yes) { @@ -564,43 +706,49 @@ export struct ToolBarComp { .height(24) .width(24) .onClick(() => { - this.noteDataDeleteDialogCtl.open() + this.noteDataDeleteDialogCtl!.open(); }) Image($r('app.media.recover')) .height(24) .width(24) .onClick(() => { - this.selectedNoteData.is_deleted = Delete.No - this.selectedNoteData.deleted_time = 0 - let context: any = getContext(this) - let resource = { - bundleName: "com.ohos.note", - moduleName: "default", - id: $r('app.string.restore').id - }; - context.resourceManager.getString(resource, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - prompt.showToast({ message: value, duration: 2000 }); - } - }); - this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) - this.chooseNote = false - // update note to db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" - ) - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, "recover, set continue note success") - NoteUtil.refreshAll() + try { + this.selectedNoteData.is_deleted = Delete.No; + this.selectedNoteData.deleted_time = 0; + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + let resource: resourceManager.Resource = { + bundleName: 'com.ohos.note', + moduleName: 'default', + id: $r('app.string.restore').id + }; + context.resourceManager.getStringValue(resource, (error: BusinessError, value: string) => { + if (error != null) { + LogUtil.error(TAG, 'error is ' + error); + } else { + promptAction.showToast({ message: value, duration: 2000 }); + } + }); + this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0); + this.chooseNote = false; + // update note to db + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicatesNote, null); + + this.selectedNoteData = + NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid)!; + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData!.content_text + "')" + ) + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()); + AppStorage.SetOrCreate('ContinueNote', continueNote); + LogUtil.info(TAG, 'recover, set continue note success'); + NoteUtil.refreshAll(); + } catch (error) { + LogUtil.error(TAG, + `recover failed.code:${JSON.stringify(error.code)}, message:${JSON.stringify(error.message)}`); + } }) }.width(72) } else if (this.editModel == true) { @@ -610,11 +758,15 @@ export struct ToolBarComp { .height(24) .width(24) .onClick(() => { - // 清单 - this.controllerShow.runJavaScript("javascript:RICH_EDITOR.setTodo()") - // 退出键盘 - // @ts-ignore - inputMethod.getController().stopInputSession(); + try { + // 清单 + this.controllerShow.runJavaScript('javascript:RICH_EDITOR.setTodo()'); + // 退出键盘 + inputMethod.getController().stopInputSession(); + } catch (error) { + LogUtil.error(TAG, `Image circle_tick1 click failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); + } }) }.width(42) .height(42) @@ -627,9 +779,8 @@ export struct ToolBarComp { .width(24) .onClick(() => { // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); - this.editContentDialogCtl.open() + this.editContentDialogCtl!.open(); }) }.width(42) .height(42) @@ -641,57 +792,60 @@ export struct ToolBarComp { .height(24) .width(24) .onClick(async () => { - let permissionList: Array = [ - "ohos.permission.READ_MEDIA", - "ohos.permission.WRITE_MEDIA", - ] - let context: any = getContext(this); + let permissionList: Permissions[] = [ + 'ohos.permission.READ_MEDIA', + 'ohos.permission.WRITE_MEDIA', + ]; + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; let AtManager = abilityAccessCtrl.createAtManager(); - // @ts-ignore await AtManager.requestPermissionsFromUser(context, permissionList).then((data) => { - LogUtil.info(TAG, 'data permissions : ' + data.permissions) - LogUtil.info(TAG, 'data result: ' + data.authResults) - let sum = 0 + LogUtil.info(TAG, 'data permissions : ' + data.permissions); + LogUtil.info(TAG, 'data result: ' + data.authResults); + let sum = 0; for (let i = 0; i < data.authResults.length; i++) { - sum += data.authResults[i] + sum += data.authResults[i]; } - LogUtil.info(TAG, 'request permissions sum: ' + sum) - }).catch((err) => { + LogUtil.info(TAG, 'request permissions sum: ' + sum); + }).catch((err: BusinessError) => { LogUtil.warn(TAG, 'failed to requestPermissionsFromUser : ' + err.code); }) // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); - LogUtil.info(TAG, 'startAbility start') - await globalThis.noteContext.startAbilityForResult({ - parameters: { uri: "singleselect" }, - bundleName: "com.ohos.photos", - abilityName: "com.ohos.photos.MainAbility", + LogUtil.info(TAG, 'startAbility start'); + await noteContext.startAbilityForResult({ + parameters: { uri: 'singleselect' }, + bundleName: 'com.ohos.photos', + abilityName: 'com.ohos.photos.MainAbility', }) - .then(v => { - let want = v['want']; - if (want != null && want != undefined) { - let param = want['parameters']; - let imageUri = "" - if (param != null && param != undefined) { - let uri = param['select-item-list']; - imageUri = uri; - } - // 拷贝 - if (imageUri != null && imageUri != "") { - OperationUtils.copy(imageUri).then((uriPath) => { - var path = "file://" + uriPath - LogUtil.info(TAG, 'image uri is:' + path) - this.controllerShow.runJavaScript( - "javascript:RICH_EDITOR.insertImage('" + path + "')" - ) - this.issave = 1 - // 保存笔记信息到数据库 - this.controllerShow.runJavaScript("getHtmlContent()") - }) + .then((v: common.AbilityResult) => { + try { + let want = v['want']; + if (want != null && want != undefined) { + let param = want['parameters']; + let imageUri = ""; + if (param != null && param != undefined) { + let uri = param['select-item-list']; + imageUri = uri as string; + } + // 拷贝 + if (imageUri != null && imageUri != "") { + OperationUtils.copy(imageUri).then((uriPath) => { + let path = 'file://' + uriPath; + LogUtil.info(TAG, 'image uri is:' + path); + this.controllerShow.runJavaScript( + "javascript:RICH_EDITOR.insertImage('" + path + "')" + ); + this.issave = 1; + // 保存笔记信息到数据库 + this.controllerShow.runJavaScript('getHtmlContent()'); + }) + } } + NoteUtil.refreshAll(); + } catch (error) { + LogUtil.error(TAG, `startAbilityForResult failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); } - NoteUtil.refreshAll() }); }) }.width(42) @@ -704,10 +858,14 @@ export struct ToolBarComp { .height(24) .width(24) .onClick(() => { - // 退出键盘 - // @ts-ignore - inputMethod.getController().stopInputSession(); - this.controllerShow.runJavaScript("RICH_EDITOR.undo()") + try { + // 退出键盘 + inputMethod.getController().stopInputSession(); + this.controllerShow.runJavaScript('RICH_EDITOR.undo()'); + } catch (error) { + LogUtil.error(TAG, `Image undo click failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); + } }) }.width(42) .height(42) @@ -719,10 +877,14 @@ export struct ToolBarComp { .height(24) .width(24) .onClick(() => { - // 退出键盘 - // @ts-ignore - inputMethod.getController().stopInputSession(); - this.controllerShow.runJavaScript("RICH_EDITOR.redo()") + try { + // 退出键盘 + inputMethod.getController().stopInputSession(); + this.controllerShow.runJavaScript('RICH_EDITOR.redo()'); + } catch (error) { + LogUtil.error(TAG, `Image todo click failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); + } }) }.width(42) .height(42) @@ -736,12 +898,18 @@ export struct ToolBarComp { .width(24) .fillColor(this.issave == 0 ? Color.Black : Color.Grey) .onClick(() => { - // 保存笔记信息到数据库 - this.controllerShow.runJavaScript("getHtmlContent()") - if (this.selectedNoteData.title == "标题" && this.selectedNoteData.content_text == "") { - LogUtil.info(TAG, "note is empty,save note failed") + try { + // 保存笔记信息到数据库 + this.controllerShow.runJavaScript('getHtmlContent()'); + this.controllerShow.runJavaScript('javascript:RICH_EDITOR.getBlur()'); + if (this.selectedNoteData.title == '标题' && this.selectedNoteData.content_text == "") { + LogUtil.info(TAG, 'note is empty,save note failed'); + } + this.issave = 1; + } catch (error) { + LogUtil.error(TAG, `Image tick_thin click failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); } - this.issave = 1 }) }.width(42) .height(42) @@ -750,33 +918,46 @@ export struct ToolBarComp { }.width(274) } else { Row({ space: StyleConstants.SPACE_24 }) { - Image(this.selectedNoteData.is_favorite == Favorite.Yes ? $r('app.media.favorite') : $r('app.media.favorite_cancel')) + Image(this.selectedNoteData.is_favorite == Favorite.Yes ? $r('app.media.favorite') : + $r('app.media.favorite_cancel')) .height(24) .width(24) .onClick(() => { - this.selectedNoteData.is_favorite = (this.selectedNoteData.is_favorite == Favorite.Yes ? Favorite.No : Favorite.Yes) - this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) - // update note to db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - if (this.selectedFolderData.uuid === SysDefFolderUuid.MyFavorites) { - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), SysDefFolderUuid.MyFavorites) - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" - ) - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, "ToolBarComp, set continue note success") + try { + this.selectedNoteData.is_favorite = + (this.selectedNoteData.is_favorite == Favorite.Yes ? Favorite.No : Favorite.Yes); + this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0); + // update note to db + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid); + RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicatesNote, null); + if (this.selectedFolderData.uuid === SysDefFolderUuid.MyFavorites) { + this.selectedNoteData = + NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, SysDefFolderUuid.MyFavorites)!; + try { + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" + ); + LogUtil.info(TAG, `setHtml success`); + } catch (error) { + LogUtil.error(TAG, `setHtml failed.code:${JSON.stringify(error.code)}, + message:${JSON.stringify(error.message)}`); + } + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()); + AppStorage.SetOrCreate('ContinueNote', continueNote); + LogUtil.info(TAG, 'ToolBarComp, set continue note success'); + } + NoteUtil.refreshAll(); + } catch (error) { + LogUtil.error(TAG, 'favorite error: ' + JSON.stringify(error)); } - NoteUtil.refreshAll() }) Image($r('app.media.delete')) .height(24) .width(24) .onClick(() => { - this.noteDataDeleteDialogCtl.open() + this.noteDataDeleteDialogCtl!.open(); }) }.width(72) } @@ -789,11 +970,13 @@ export struct ToolBarComp { @Component struct NoteDataMoveItemCompTablet { - @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = [] - @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = [] - @StorageLink('isUpdate') isUpdate: boolean = false - folderItem: FolderData - uuid: String + @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = []; + @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = []; + @StorageLink('isUpdate') isUpdate: boolean = false; + folderItem: FolderData = + new FolderData(0, '', new Date().getTime() + '', '', FolderType.CusDef, Delete.No, new Date().getTime(), + new Date().getTime()); + uuid: string = ''; build() { Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.Center }) { @@ -804,7 +987,8 @@ struct NoteDataMoveItemCompTablet { .width(24) .height(24) .flexShrink(0) - .fillColor(FolderUtil.getFolderIconColor(this.AllFolderArray, this.folderItem.uuid, this.folderItem.uuid == this.uuid)) + .fillColor(FolderUtil.getFolderIconColor(this.AllFolderArray, this.folderItem.uuid, + this.folderItem.uuid == this.uuid)) } .width(24) @@ -814,7 +998,8 @@ struct NoteDataMoveItemCompTablet { .id(this.isUpdate + '') .padding({ top: 3 }) .fontSize(16) - .fontColor(FolderUtil.getFolderIconColor(this.AllFolderArray, this.folderItem.uuid == this.uuid ? this.folderItem.uuid : '', this.folderItem.uuid == this.uuid)) + .fontColor(FolderUtil.getFolderIconColor(this.AllFolderArray, + this.folderItem.uuid == this.uuid ? this.folderItem.uuid : '', this.folderItem.uuid == this.uuid)) .textAlign(TextAlign.Center) .maxLines(1) .textOverflow({ overflow: TextOverflow.Ellipsis }) @@ -825,7 +1010,7 @@ struct NoteDataMoveItemCompTablet { if (this.folderItem.uuid != SysDefFolderUuid.UnClassified) { Divider() - .color($r("app.color.divider_color_e4e4e4")) + .color($r('app.color.divider_color_e4e4e4')) .strokeWidth(1) } } diff --git a/features/src/main/ets/components/NoteContentCompPortrait.ets b/features/src/main/ets/components/NoteContentCompPortrait.ets index 32833d5..1eb3eb7 100644 --- a/features/src/main/ets/components/NoteContentCompPortrait.ets +++ b/features/src/main/ets/components/NoteContentCompPortrait.ets @@ -23,50 +23,75 @@ import { NoteTableColumn, SysDefFolderUuid, Favorite, - Delete -} from '@ohos/utils/src/main/ets/default/model/databaseModel/EnumData' + Delete, + FolderType +} from '@ohos/utils/src/main/ets/default/model/databaseModel/EnumData'; import StyleConstants from '@ohos/utils/src/main/ets/default/constants/StyleConstants' import { EditContentDialogPortrait, DeleteDialog, EditTitleDialog } from './CusDialogComp' import FolderUtil from '@ohos/utils/src/main/ets/default/baseUtil/FolderUtil' import NoteUtil from '@ohos/utils/src/main/ets/default/baseUtil/NoteUtil' -import prompt from '@system.prompt' +import { promptAction } from '@kit.ArkUI'; import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil' import OperationUtils from '@ohos/utils/src/main/ets/default/baseUtil/OperationUtils' import router from '@system.router' import inputMethod from '@ohos.inputMethod'; import { folderTextMap } from '@ohos/utils/src/main/ets/default/model/NoteBaseData' -import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; - -var time_id: number - -const TAG = "NoteContentCompPortrait" +import abilityAccessCtrl,{ Permissions } from '@ohos.abilityAccessCtrl'; +import webview from '@ohos.web.webview'; +import { BusinessError } from '@ohos.base'; +import resourceManager from '@ohos.resourceManager'; +import common from '@ohos.app.ability.common'; +import window from '@ohos.window'; +import { wantAgent, WantAgent } from '@kit.AbilityKit'; +import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; + +let time_id: number = 0; +let noteContext = AppStorage.Get('noteContext')!; + +const TAG = 'NoteContentCompPortrait'; + +interface NoteContentType { + callbackhtml: (html: string) => void; + callbackImagePath: (imgName: string) => void; + callbackScheduledSave: (html: string) => void; + callbackPasteImage: (html: string) => void; + callbackGetSize: (fontSize: number) => void; + addToDo: () => void; + chooseStyle: () => void; + openAlbum: () => Promise; + getBreakPoint: () => void; +} async function routePage() { try { await router.back() } catch (err) { - LogUtil.info(TAG, "fail callback") + LogUtil.info(TAG, 'fail callback'); } } // Note content component @Component export struct NoteContentCompPortrait { - @Provide('SelectedNoteData') selectedNoteData: NoteData = AppStorage.Get('NewNote') - @Provide('SelectedFolderData') selectedFolderData: FolderData = AppStorage.Get("NewFolder") + @Provide('SelectedNoteData') selectedNoteData: NoteData = AppStorage.Get('NewNote')!; + @Provide('SelectedFolderData') selectedFolderData: FolderData = AppStorage.Get('NewFolder')!; @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray') @Provide('EditModel') editModel: boolean = false @StorageLink('dpi') dpi: number = 240 - controllerShow: WebviewController + controllerShow: webview.WebviewController = new webview.WebviewController(); private editContentFlag = false private isClickBack: boolean = false @StorageLink('ScrollTopPercent') scrollTopPercent: number = 0.0 - editContentDialogCtl: CustomDialogController = new CustomDialogController({ - builder: EditContentDialogPortrait({ confirm: this.confirm.bind(this) }), + editContentDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: EditContentDialogPortrait({ confirm: (newTitle: string) => { + this.confirm(newTitle); + } }), alignment: DialogAlignment.Bottom, autoCancel: true, customStyle: true, }) + @StorageLink('topHeight') topHeight: number = 0; // 窗口规避区域高 + @StorageLink('topWidth') topWidth: number = 0; // 窗口规避区域宽 confirm(excuteJs: string) { this.controllerShow.runJavaScript(excuteJs) @@ -84,7 +109,7 @@ export struct NoteContentCompPortrait { if (!AppStorage.Has('remoteScrollTopPercent')) { return } - var scrollTopPercent = AppStorage.Get('remoteScrollTopPercent') + let scrollTopPercent = AppStorage.Get('remoteScrollTopPercent')!; if (scrollTopPercent < 0) { return } @@ -108,19 +133,23 @@ export struct NoteContentCompPortrait { AppStorage.Delete('isRemoteFocusOnSearch') } - noteContent = { + noteContent: NoteContentType = { callbackhtml: (html) => { - LogUtil.info(TAG, 'note uuid is:' + this.selectedNoteData.uuid) + LogUtil.info(TAG, 'note uuid is:' + this.selectedNoteData?.uuid) + this.selectedNoteData.content_text = NoteUtil.contrastInitType(this.selectedNoteData.content_text); + if (this.selectedNoteData.content_text === html ) { + return; + }; this.selectedNoteData.content_text = html this.selectedNoteData.modified_time = new Date().getTime() - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - LogUtil.info(TAG, 'update note success:' + this.selectedNoteData.uuid) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.update(this.selectedNoteData?.toNoteObject(), predicatesNote, null); + LogUtil.info(TAG, 'update note success:' + this.selectedNoteData?.uuid) // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, "callbackhtml, set continue note success") + LogUtil.info(TAG, 'callbackhtml, set continue note success'); }, callbackImagePath: (imgName) => { // updata note image @@ -130,36 +159,36 @@ export struct NoteContentCompPortrait { callbackScheduledSave: (html) => { LogUtil.info(TAG, 'callbackScheduledSave') - if (this.selectedNoteData.content_text == html) { + if (this.selectedNoteData?.content_text == html) { LogUtil.info(TAG, 'callbackScheduledSave the same value return') return; } this.selectedNoteData.content_text = html this.selectedNoteData.modified_time = new Date().getTime() - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - LogUtil.info(TAG, 'callbackScheduledSave, update note success:' + this.selectedNoteData.uuid) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.update(this.selectedNoteData?.toNoteObject(), predicatesNote, null); + LogUtil.info(TAG, 'callbackScheduledSave, update note success:' + this.selectedNoteData?.uuid) // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, 'callbackScheduledSave, set continue note success') }, callbackPasteImage: (html) => { if (html) { LogUtil.info(TAG, 'paste info' + html) - let realHtml = "" - let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/ - if (html && html.indexOf("base64") > 0) { - LogUtil.info(TAG, " getSrcFromHtml, src[1] : " + html) + let realHtml = ''; + let base64regex: RegExp = new RegExp('/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/'); + if (html && html.indexOf('base64') > 0) { + LogUtil.info(TAG, ' getSrcFromHtml, src[1] : ' + html); let imgData = html.split(',')[1]; let imgType = 'png' - if (html.indexOf("jpeg") > 0) { + if (html.indexOf('jpeg') > 0) { imgType = 'jpg' - } else if (html.indexOf("gif") > 0) { + } else if (html.indexOf('gif') > 0) { imgType = 'gif' } - let filePath = "" + let filePath = ''; if (base64regex.test(imgData)) { let base64 = new util.Base64() let decodeArr = base64.decodeSync(imgData) @@ -167,7 +196,7 @@ export struct NoteContentCompPortrait { } else { filePath = OperationUtils.saveImage(imgData, imgType) } - realHtml = "file://" + filePath + realHtml = 'file://' + filePath; } LogUtil.info(TAG, 'paste info11' + realHtml) this.controllerShow.runJavaScript("javascript:RICH_EDITOR.insertImageHtml('" + realHtml + "')") @@ -190,19 +219,44 @@ export struct NoteContentCompPortrait { }, addToDo: () => { // 清单 - this.controllerShow.runJavaScript("javascript:RICH_EDITOR.setTodo()") + this.controllerShow.runJavaScript('javascript:RICH_EDITOR.setTodo()'); }, chooseStyle: () => { - this.editContentDialogCtl.open() + this.editContentDialogCtl!.open(); }, openAlbum: async () => { - let permissionList: Array = [ - "ohos.permission.READ_MEDIA", - "ohos.permission.WRITE_MEDIA", + let context: common.UIAbilityContext = AppStorage.Get('context')!; + // 申请长时任务 + let wantAgentInfo: wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: 'com.ohos.note', + abilityName: 'com.ohos.note.MainAbility' + } + ], + actionType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { + backgroundTaskManager.startBackgroundRunning(context, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + LogUtil.info(TAG, `Operation startBackgroundRunning succeeded`); + }).catch((error: BusinessError) => { + LogUtil.error(TAG, `Operation startBackgroundRunning failed. code is ${JSON.stringify(error.code)}, + message is ${JSON.stringify(error.message)}`); + }); + }); + } catch (error) { + LogUtil.error(TAG, `Operation getWantAgent failed. code is ${(error as BusinessError).code}, + message is ${(error as BusinessError).message}`); + } + let permissionList: Permissions[] = [ + 'ohos.permission.READ_IMAGEVIDEO', + 'ohos.permission.WRITE_IMAGEVIDEO' ] - let context: any = getContext(this); let AtManager = abilityAccessCtrl.createAtManager(); - // @ts-ignore await AtManager.requestPermissionsFromUser(context, permissionList).then((data) => { LogUtil.info(TAG, 'data permissions : ' + data.permissions) LogUtil.info(TAG, 'data result: ' + data.authResults) @@ -211,34 +265,46 @@ export struct NoteContentCompPortrait { sum += data.authResults[i] } LogUtil.info(TAG, 'request permissions sum: ' + sum) - }).catch((err) => { + }).catch((err: BusinessError) => { LogUtil.warn(TAG, 'failed to requestPermissionsFromUser : ' + err.code); }) LogUtil.info(TAG, 'startAbility start') - await globalThis.noteContext.startAbilityForResult({ - parameters: { uri: "singleselect" }, - bundleName: "com.ohos.photos", - abilityName: "com.ohos.photos.MainAbility", - }).then(v => { + await noteContext.startAbilityForResult({ + parameters: { uri: 'singleselect', filterMediaType: 'FILTER_MEDIA_TYPE_IMAGE' }, + bundleName: 'com.ohos.photos', + abilityName: 'com.ohos.photos.MainAbility', + }).then((v: common.AbilityResult) => { let want = v['want']; if (want != null && want != undefined) { let param = want['parameters']; - let imageUri = "" + let imageUri = ''; if (param != null && param != undefined) { - let uri = param['select-item-list']; + let uri = param['select-item-list'] as Record; imageUri = uri[0]; } - LogUtil.info(TAG, "image url" + imageUri) + LogUtil.info(TAG, 'image url' + imageUri); // 拷贝 - if (imageUri != null && imageUri != "") { + if (imageUri != null && imageUri != '') { OperationUtils.copy(imageUri).then((uriPath) => { - var path = "file://" + uriPath + let path = 'file://' + uriPath; LogUtil.info(TAG, 'image uri is:' + path) - this.controllerShow.runJavaScript("javascript:RICH_EDITOR.getFocus()") + this.controllerShow.runJavaScript('javascript:RICH_EDITOR.getFocus()'); this.controllerShow.runJavaScript("javascript:RICH_EDITOR.insertImage('" + path + "')") }) } } + // 取消长时任务 + try { + backgroundTaskManager.stopBackgroundRunning(context).then(() => { + LogUtil.info(TAG, `Operation stopBackgroundRunning succeeded`); + }).catch((error: BusinessError) => { + LogUtil.error(TAG, `Operation stopBackgroundRunning failed. code is ${JSON.stringify(error.code)}, + message is ${JSON.stringify(error.message)}`); + }); + } catch (error) { + LogUtil.error(TAG, `Operation stopBackgroundRunning failed. code is ${JSON.stringify(error.code)}, + message is ${JSON.stringify(error.message)}`); + } }); }, getBreakPoint: () => { @@ -251,9 +317,13 @@ export struct NoteContentCompPortrait { Flex({ direction: FlexDirection.Column, wrap: FlexWrap.NoWrap, alignItems: ItemAlign.Start, alignContent: FlexAlign.SpaceAround }) { Column() { + // 窗口顶部规避区域 + Row() + .width(px2vp(this.topWidth)) + .height(px2vp(this.topHeight)) ToolBarComp({ controllerShow: this.controllerShow }) NoteContentOverViewComp() - .enabled(this.selectedNoteData && this.selectedNoteData.is_deleted == Delete.Yes ? false : true) + .enabled(this.selectedNoteData && this.selectedNoteData?.is_deleted == Delete.Yes ? false : true) } Column() { @@ -262,26 +332,27 @@ export struct NoteContentCompPortrait { .javaScriptAccess(true) .javaScriptProxy({ object: this.noteContent, - name: "callBackToApp", // html--> name.method - methodList: ["callbackhtml", "callbackScheduledSave", "callbackPasteImage", "callbackImagePath", "addToDo", "chooseStyle", "openAlbum", "callbackGetSize", "getBreakPoint"], + name: 'callBackToApp', // html--> name.method + methodList: ['callbackhtml', 'callbackScheduledSave', 'callbackPasteImage', 'callbackImagePath', + 'addToDo', 'chooseStyle', 'openAlbum', 'callbackGetSize', 'getBreakPoint'], controller: this.controllerShow }) .onPageEnd((e) => { try { if (this.dpi <= 240) { - this.controllerShow.runJavaScript("changeSizeToRk()") + this.controllerShow.runJavaScript('changeSizeToRk()'); } else if (this.dpi <= 320 && this.dpi > 240) { - this.controllerShow.runJavaScript("changeSizeToPhone()") + this.controllerShow.runJavaScript('changeSizeToPhone()'); } else { - this.controllerShow.runJavaScript("changeSizeToTablet()") + this.controllerShow.runJavaScript('changeSizeToTablet()'); } - LogUtil.info(TAG, "finish loadurl") + LogUtil.info(TAG, 'finish loadurl'); let self = this this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')", + "RICH_EDITOR.setHtml('" + this.selectedNoteData?.content_text + "')", () => { // wait for the image in the note to load - setTimeout(function () { + setTimeout(() => { self.restoreScrollTop() self.restoreFocus() }, 100) @@ -310,40 +381,45 @@ export struct NoteContentCompPortrait { time_id = setInterval(() => { try { if (!this.isClickBack) { - this.controllerShow.runJavaScript("scheduledSaveContent()") + this.controllerShow.runJavaScript('scheduledSaveContent()'); } } catch (error) { LogUtil.info(TAG, 'setInterval error') } }, 3000) - LogUtil.info(TAG, "setInterval time_id : " + time_id) + LogUtil.info(TAG, 'setInterval time_id : ' + time_id) this.editModel = true }) } - .enabled(this.selectedNoteData && this.selectedNoteData.is_deleted == Delete.Yes ? false : true) + .height('100%') + .enabled(this.selectedNoteData && this.selectedNoteData?.is_deleted == Delete.Yes ? false : true) .flexShrink(1) .margin({ top: 16 }) .width(StyleConstants.PERCENTAGE_100) } .flexShrink(1) .padding({ left: 24, right: 24 }) - DeleteNoteComp() } + .expandSafeArea([SafeAreaType.KEYBOARD, SafeAreaType.SYSTEM]) .height(StyleConstants.PERCENTAGE_100) .width(StyleConstants.PERCENTAGE_100) } aboutToAppear(): void { this.isClickBack = false - LogUtil.info(TAG, "aboutToAppear") + LogUtil.info(TAG, 'aboutToAppear'); + window.getLastWindow(getContext(this)).then(currentWindow => { + currentWindow.setWindowLayoutFullScreen(true); + }) } aboutToDisappear(): void { this.isClickBack = true clearInterval(time_id) NoteUtil.refreshAll() - LogUtil.info(TAG, "aboutToDisappear") + LogUtil.info(TAG, 'aboutToDisappear'); + this.editContentDialogCtl = null } } @@ -353,9 +429,11 @@ export struct NoteContentOverViewComp { @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = [] @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = [] @StorageLink('isUpdate') isUpdate: boolean = false - NoteDataMoveArray: FolderData[] - editTitleDialogCtl: CustomDialogController = new CustomDialogController({ - builder: EditTitleDialog({ confirm: this.confirm.bind(this) }), + NoteDataMoveArray: FolderData[] = []; + editTitleDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: EditTitleDialog({ confirm: (newTitle: string) => { + this.confirm(newTitle); + } }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, @@ -363,42 +441,54 @@ export struct NoteContentOverViewComp { aboutToAppear() { this.NoteDataMoveArray = this.AllFolderArray.slice(2, this.AllFolderArray.length); + if (this.AllFolderArray[1] === undefined || this.AllFolderArray[1] === null) { + LogUtil.info(TAG, 'this AllFolderArray[1] undefined'); + return + } this.NoteDataMoveArray.push(this.AllFolderArray[1]); } + aboutToDisappear() { + this.editTitleDialogCtl = null + } + confirm(newTitle: string) { this.selectedNoteData.title = newTitle this.selectedNoteData.modified_time = new Date().getTime() - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.update(this.selectedNoteData?.toNoteObject(), predicatesNote, null); // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, 'NoteContentOverViewComp, MenuBuilder, set continue note success') NoteUtil.refreshAll() } - @Builder MenuBuilder() { + @Builder + MenuBuilder() { Column() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { List() { - ForEach(this.NoteDataMoveArray, (item) => { - ListItem() { - NoteDataMoveItemCompMenu({ folderItem: item, uuid: this.selectedNoteData.folder_uuid }) - } - .onClick(() => { - this.selectedNoteData.folder_uuid = item.uuid - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) - AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, 'MenuBuilder, set continue note success') - NoteUtil.refreshAll() - }) - }, noteItem => noteItem.uuid) + if (this.NoteDataMoveArray !== undefined && this.NoteDataMoveArray !== null && + this.NoteDataMoveArray.length > 0) { + ForEach(this.NoteDataMoveArray, (item: FolderData) => { + ListItem() { + NoteDataMoveItemCompMenu({ folderItem: item, uuid: this.selectedNoteData?.folder_uuid }) + } + .onClick(() => { + this.selectedNoteData.folder_uuid = item.uuid + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.update(this.selectedNoteData?.toNoteObject(), predicatesNote, null); + // save continue data + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) + AppStorage.SetOrCreate('ContinueNote', continueNote) + LogUtil.info(TAG, 'MenuBuilder, set continue note success') + NoteUtil.refreshAll() + }) + }, (noteItem: NoteData) => noteItem?.uuid) + } } .margin({ top: 4, bottom: 4 }) .listDirection(Axis.Vertical) @@ -416,26 +506,26 @@ export struct NoteContentOverViewComp { Flex({ direction: FlexDirection.Column, wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { Row() { - Text(this.selectedNoteData.title) + Text(this.selectedNoteData?.title) .id(this.isUpdate + '') .fontSize(30).fontWeight(FontWeight.Medium) .onClick(() => { clearInterval(time_id) - this.editTitleDialogCtl.open() + this.editTitleDialogCtl!.open(); }) }.height(40) .width(StyleConstants.PERCENTAGE_100) Row() { - Text(DateUtil.formateDateForNoteContent(new Date(this.selectedNoteData.modified_time))) + Text(DateUtil.formateDateForNoteContent(new Date(this.selectedNoteData?.modified_time))) .id(this.isUpdate + '') .fontSize(12) .padding({ top: 4, bottom: 4 }) - .fontColor($r("app.color.modified_time_font_color")) + .fontColor($r('app.color.modified_time_font_color')) Row() { - Text(FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid)) == - folderTextMap["sys_def_myFavorites_uuid"] ? folderTextMap["sys_def_unClassified_uuid"] : - FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid))) + Text(FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), this.selectedNoteData?.folder_uuid)) == + folderTextMap.sys_def_myFavorites_uuid ? folderTextMap.sys_def_unClassified_uuid : + FolderUtil.getFolderText(FolderUtil.getFolderData(AppStorage.Get('AllFolderArray'), this.selectedNoteData?.folder_uuid))) .id(this.isUpdate + '') .fontColor($r('app.color.folder_color_99182431')) .fontSize(12) @@ -448,11 +538,11 @@ export struct NoteContentOverViewComp { .padding({ left: 8, right: 8, top: 4, bottom: 4 }) .margin({ left: 8 }) .borderRadius(16) - .backgroundColor(NoteUtil.getNoteBgColor(AppStorage.Get('AllFolderArray'), this.selectedNoteData.folder_uuid, SysDefFolderUuid.AllNotes, false)) + .backgroundColor(NoteUtil.getNoteBgColor(AppStorage.Get('AllFolderArray')!, this.selectedNoteData?.folder_uuid, SysDefFolderUuid.AllNotes, false)) .bindMenu(this.MenuBuilder) }.alignItems(VerticalAlign.Top).height(40).width(StyleConstants.PERCENTAGE_100) } - .opacity(this.selectedNoteData.is_deleted == Delete.Yes ? 0.4 : 1) + .opacity(this.selectedNoteData?.is_deleted == Delete.Yes ? 0.4 : 1) .width(StyleConstants.PERCENTAGE_100) .height(82) } @@ -465,35 +555,41 @@ export struct ToolBarComp { @Consume('SelectedFolderData') selectedFolderData: FolderData @Consume('EditModel') editModel: boolean @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray') - controllerShow: WebviewController + controllerShow: webview.WebviewController = new webview.WebviewController(); onDeleteConfirm() { if (this.selectedFolderData.uuid != SysDefFolderUuid.RecentDeletes) { this.selectedNoteData.is_deleted = Delete.Yes this.selectedNoteData.deleted_time = new Date().getTime() // update note to db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.update(this.selectedNoteData?.toNoteObject(), predicatesNote, null); routePage() } else { - NoteUtil.removeNoteData(this.AllNoteArray, this.selectedNoteData.uuid) + NoteUtil.removeNoteData(this.AllNoteArray, this.selectedNoteData?.uuid) // delete note from db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.delete(predicates_note, null) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.delete(predicatesNote, null); routePage() } AppStorage.SetOrCreate('isUpdate', true) } - noteDataDeleteDialogCtl: CustomDialogController = new CustomDialogController({ - builder: DeleteDialog({ onConfirm: this.onDeleteConfirm.bind(this), multiSelect: true }), + noteDataDeleteDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: DeleteDialog({ onConfirm: () => { + this.onDeleteConfirm(); + }, multiSelect: true }), alignment: DialogAlignment.Bottom, autoCancel: false, customStyle: true, }) + aboutToDisappear() { + this.noteDataDeleteDialogCtl = null + } + build() { Flex({ direction: FlexDirection.Row, wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { @@ -504,14 +600,14 @@ export struct ToolBarComp { .responseRegion({ width: 54, height: 54 }) .onClick(() => { try { - this.controllerShow.runJavaScript("getHtmlContent()") + this.controllerShow.runJavaScript('getHtmlContent()'); // 清除定时器 if (time_id != undefined) { - LogUtil.info(TAG, "back, clearInterval time_id : " + time_id) + LogUtil.info(TAG, 'back, clearInterval time_id : ' + time_id); clearInterval(time_id) } setTimeout(() => { - LogUtil.info(TAG, "wait save cotext") + LogUtil.info(TAG, 'wait save cotext'); router.back() }, 50) NoteUtil.refreshAll() @@ -522,24 +618,28 @@ export struct ToolBarComp { if (this.editModel == false) { Row({ space: StyleConstants.SPACE_24 }) { - Image(this.selectedNoteData.is_favorite == Favorite.Yes ? $r('app.media.favorite') : $r('app.media.favorite_cancel')) + Image(this.selectedNoteData?.is_favorite == Favorite.Yes ? $r('app.media.favorite') : $r('app.media.favorite_cancel')) .height(24).width(24) .onClick(() => { try { - this.selectedNoteData.is_favorite = (this.selectedNoteData.is_favorite == Favorite.Yes ? Favorite.No : Favorite.Yes) + this.selectedNoteData.is_favorite = (this.selectedNoteData?.is_favorite == Favorite.Yes ? + Favorite.No : Favorite.Yes) // update note to db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) - if (this.selectedFolderData.uuid === SysDefFolderUuid.MyFavorites) { - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), SysDefFolderUuid.MyFavorites) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.update(this.selectedNoteData?.toNoteObject(), predicatesNote, null); + if (this.selectedFolderData?.uuid === SysDefFolderUuid.MyFavorites) { + this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, SysDefFolderUuid.MyFavorites)!; + if (!this.selectedNoteData) { + routePage() + } this.controllerShow.runJavaScript( "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" ) // save continue data let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) - LogUtil.info(TAG, "ToolBarComp, set continue note success") + LogUtil.info(TAG, 'ToolBarComp, set continue note success'); } NoteUtil.refreshAll() } catch (error) { @@ -548,10 +648,10 @@ export struct ToolBarComp { }) Image($r('app.media.delete')).height(24).width(24) .onClick(() => { - this.noteDataDeleteDialogCtl.open() + this.noteDataDeleteDialogCtl!.open(); }) }.width(72) - .visibility(this.selectedNoteData.is_deleted == Delete.Yes ? Visibility.None : Visibility.Visible) + .visibility(this.selectedNoteData?.is_deleted == Delete.Yes ? Visibility.None : Visibility.Visible) } else { Row({ space: StyleConstants.SPACE_6 }) { Button({ type: ButtonType.Normal, stateEffect: true }) { @@ -559,9 +659,8 @@ export struct ToolBarComp { .onClick(() => { try { // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); - this.controllerShow.runJavaScript("javascript:RICH_EDITOR.undo()") + this.controllerShow.runJavaScript('javascript:RICH_EDITOR.undo()'); } catch (error) { LogUtil.info(TAG, 'undo error') } @@ -576,9 +675,8 @@ export struct ToolBarComp { .onClick(() => { try { // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); - this.controllerShow.runJavaScript("javascript:RICH_EDITOR.redo()") + this.controllerShow.runJavaScript('javascript:RICH_EDITOR.redo()'); } catch (error) { LogUtil.info(TAG, 'todo error') } @@ -593,8 +691,9 @@ export struct ToolBarComp { .onClick(() => { try { // 保存笔记信息到数据库 - this.controllerShow.runJavaScript("getHtmlContent()") + this.controllerShow.runJavaScript('getHtmlContent()'); this.editModel = false + this.controllerShow.runJavaScript('javascript:RICH_EDITOR.getBlur()'); } catch (error) { LogUtil.info(TAG, 'tick_thin error') } @@ -605,7 +704,7 @@ export struct ToolBarComp { .backgroundColor($r('app.color.color_fffffB')) } .width(130) - .visibility(this.selectedNoteData.is_deleted == Delete.Yes ? Visibility.None : Visibility.Visible) + .visibility(this.selectedNoteData?.is_deleted == Delete.Yes ? Visibility.None : Visibility.Visible) } } .width(StyleConstants.PERCENTAGE_100) @@ -620,28 +719,34 @@ export struct DeleteNoteComp { @Consume('SelectedFolderData') selectedFolderData: FolderData @Consume('RefreshFlag') refreshFlag: number @Consume('SelectedNoteData') selectedNoteData: NoteData; - noteDataDeleteDialogCtlBottom: CustomDialogController = new CustomDialogController({ - builder: DeleteDialog({ onConfirm: this.onDeleteConfirm.bind(this), multiSelect: true }), + noteDataDeleteDialogCtlBottom: CustomDialogController | null = new CustomDialogController({ + builder: DeleteDialog({ onConfirm: () => { + this.onDeleteConfirm(); + }, multiSelect: true }), alignment: DialogAlignment.Bottom, autoCancel: false, customStyle: true, }) + aboutToDisappear() { + this.noteDataDeleteDialogCtlBottom = null + } + onDeleteConfirm() { if (this.selectedFolderData.uuid != SysDefFolderUuid.RecentDeletes) { this.selectedNoteData.is_deleted = Delete.Yes this.selectedNoteData.deleted_time = new Date().getTime() // update note to db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.update(this.selectedNoteData?.toNoteObject(), predicatesNote, null); routePage() } else { - NoteUtil.removeNoteData(this.AllNoteArray, this.selectedNoteData.uuid) + NoteUtil.removeNoteData(this.AllNoteArray, this.selectedNoteData?.uuid) // delete note from db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.delete(predicates_note, null) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.delete(predicatesNote, null); NoteUtil.refreshAll() routePage() } @@ -656,17 +761,18 @@ export struct DeleteNoteComp { .height(24) .responseRegion({ x: -15.0, y: -15.0, width: 54, height: 54 }) .onClick(() => { - this.noteDataDeleteDialogCtlBottom.open() + this.noteDataDeleteDialogCtlBottom!.open(); }) - Text($r("app.string.delete")) + Text($r('app.string.delete')) .fontSize(10) .fontColor($r('app.color.delete_font_color')) .padding({ top: 5 }) } - .height("100%") + .height('100%') .width(180) .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center) + .offset({ y: -50 }) Column() { Image($r('app.media.recover')) @@ -676,39 +782,40 @@ export struct DeleteNoteComp { .onClick(() => { this.selectedNoteData.is_deleted = Delete.No this.selectedNoteData.deleted_time = 0 - let context: any = getContext(this) - let resource = { - bundleName: "com.ohos.note", - moduleName: "default", + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + let resource: resourceManager.Resource = { + bundleName: 'com.ohos.note', + moduleName: 'default', id: $r('app.string.restore').id }; - context.resourceManager.getString(resource, (error, value) => { + context.resourceManager.getStringValue(resource, (error: BusinessError, value: string) => { if (error != null) { - console.log("error is " + error); + LogUtil.error(TAG, 'error is' + error); } else { - prompt.showToast({ message: value, duration: 2000 }); + promptAction.showToast({ message: value, duration: 2000 }); } }); this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) // update note to db - let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) - predicates_note.equalTo(NoteTableColumn.Uuid, this.selectedNoteData.uuid) - RdbStoreUtil.update(this.selectedNoteData.toNoteObject(), predicates_note, null) + let predicatesNote = RdbStoreUtil.getRdbPredicates(TableName.NoteTable); + predicatesNote.equalTo(NoteTableColumn.Uuid, this.selectedNoteData?.uuid); + RdbStoreUtil.update(this.selectedNoteData?.toNoteObject(), predicatesNote, null); NoteUtil.refreshAll() }) - Text($r("app.string.recover")) + Text($r('app.string.recover')) .fontSize(10) .fontColor($r('app.color.recover_font_color')) .padding({ top: 5 }) } - .height("100%") + .height('100%') .width(180) .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center) + .offset({ y: -50 }) } .width(360) .height(56) - .visibility(this.selectedNoteData.is_deleted == Delete.Yes ? + .visibility(this.selectedNoteData?.is_deleted == Delete.Yes ? Visibility.Visible : Visibility.None) } } @@ -718,8 +825,8 @@ struct NoteDataMoveItemCompMenu { @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = [] @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = [] @StorageLink('isUpdate') isUpdate: boolean = false - folderItem: FolderData - uuid: String + folderItem: FolderData = new FolderData(0, '', new Date().getTime() + '', '', FolderType.CusDef, Delete.No, new Date().getTime(), new Date().getTime()); + uuid: string = ''; build() { Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.Center }) { @@ -730,7 +837,8 @@ struct NoteDataMoveItemCompMenu { .width(24) .height(24) .flexShrink(0) - .fillColor(FolderUtil.getFolderIconColor(this.AllFolderArray, this.folderItem.uuid, this.folderItem.uuid == this.uuid)) + .fillColor(FolderUtil.getFolderIconColor(this.AllFolderArray, this.folderItem.uuid, + this.folderItem.uuid == this.uuid)) } .width(24) @@ -750,7 +858,7 @@ struct NoteDataMoveItemCompMenu { if (this.folderItem.uuid != SysDefFolderUuid.UnClassified) { Divider() - .color($r("app.color.divider_color_e4e4e4")) + .color($r('app.color.divider_color_e4e4e4')) .strokeWidth(1) } diff --git a/features/src/main/ets/components/NoteListComp.ets b/features/src/main/ets/components/NoteListComp.ets index 73c4ac6..8621e93 100644 --- a/features/src/main/ets/components/NoteListComp.ets +++ b/features/src/main/ets/components/NoteListComp.ets @@ -23,38 +23,156 @@ import { Favorite, Delete, Top, - NoteType -} from '@ohos/utils/src/main/ets/default/model/databaseModel/EnumData' + NoteType, + FolderType +} from '@ohos/utils/src/main/ets/default/model/databaseModel/EnumData'; import { NoteDataMoveDialog, DeleteDialog } from './CusDialogComp' import RdbStoreUtil from '@ohos/utils/src/main/ets/default/baseUtil/RdbStoreUtil' -import prompt from '@system.prompt' +import { promptAction } from '@kit.ArkUI'; import NoteUtil from '@ohos/utils/src/main/ets/default/baseUtil/NoteUtil' import FolderUtil from '@ohos/utils/src/main/ets/default/baseUtil/FolderUtil' import SearchModel from '@ohos/utils/src/main/ets/default/model/searchModel/SearchModel' import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil' -import router from '@system.router'; +import router from '@ohos.router'; import inputMethod from '@ohos.inputMethod'; +import webview from '@ohos.web.webview'; +import resourceManager from '@ohos.resourceManager'; +import common from '@ohos.app.ability.common'; +import { BusinessError } from '@ohos.base'; const TAG = "NoteListComp" -async function routePage() { - let options = { - uri: 'pages/NoteContentHome' +interface RouteOption { + url: string; +} + +function routePage() { + let options: RouteOption = { + url: 'pages/NoteContentHome' } try { - await router.push(options) + router.pushUrl(options) } catch (err) { LogUtil.info(TAG, "fail callback") } } +interface TextSpan { + type: 0 | 1; // 0 表示正常文本,1 表示高亮关键词 + text: string; +} + +abstract class BasicDataSource implements IDataSource { + private listeners: DataChangeListener[] = []; + + public abstract totalCount(): number; + + public getData(index: number): T | void { + LogUtil.info(TAG, 'getDataindex: '+index); + }; + + registerDataChangeListener(listener: DataChangeListener): void { + if (this.listeners.indexOf(listener) < 0) { + this.listeners.push(listener); + }; + }; + + unregisterDataChangeListener(listener: DataChangeListener): void { + const pos = this.listeners.indexOf(listener); + if (pos >= 0) { + this.listeners.splice(pos, 1); + }; + }; + + notifyDataReload(): void { + this.listeners.forEach((listener: DataChangeListener) => { + listener.onDataReloaded(); + }); + }; + + notifyDataAdd(index: number): void { + this.listeners.forEach((listener: DataChangeListener) => { + listener.onDataAdd(index); + }); + }; + + notifyDataChange(index: number): void { + this.listeners.forEach((listener: DataChangeListener) => { + listener.onDataChange(index); + }); + }; + + notifyDataDelete(index: number): void { + this.listeners.forEach((listener: DataChangeListener) => { + listener.onDataDelete(index); + }); + }; + + notifyDataMove(from: number, to: number): void { + this.listeners.forEach((listener: DataChangeListener) => { + listener.onDataMove(from, to); + }); + }; +}; + +class noteListData extends BasicDataSource { + private noteList: Array = []; + + public totalCount(): number { + return this.noteList.length; + }; + + public getData(index: number): NoteData { + LogUtil.info(TAG, 'getData, index=' + index); + return this.noteList[index]; + }; + + public addData(index: number, data: NoteData): void { + this.noteList.splice(index, 0, data); + this.notifyDataAdd(index); + }; + + public pushData(data: NoteData): void { + this.noteList.push(data); + this.notifyDataAdd(this.noteList.length - 1); + }; + + // 查找列表中对象的index + public indexOf(data: NoteData): number { + LogUtil.info(TAG, `indexOf data , id = ${data.id} , name = ${data.title}`); + return this.noteList.indexOf(data); + }; + + // 删除列表中处于index位置的对象 + public deleteDataByIndex(index: number): void { + LogUtil.info(TAG, `delete data , index = ${index}}`); + this.noteList.splice(index, 1); + this.notifyDataDelete(index); + }; + + // 删除列表中的对象 + public deleteData(data: NoteData): void { + LogUtil.info(TAG, `delete data , data = ${data.id}}`); + let index = this.indexOf(data); + this.deleteDataByIndex(index); + }; + + // 修改列表中所有对象 + public modifyAllData(data: NoteData[]): void { + LogUtil.info(TAG, `all data modified`); + this.noteList = data; + this.notifyDataReload(); + } +}; + // Note list component @Component export struct NoteListComp { + @StorageLink('topHeight') topHeight: number = 0; @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = AppStorage.Link('AllFolderArray') @Consume('SelectedFolderData') selectedFolderData: FolderData @Consume('Search') search: boolean - controllerShow: WebviewController + controllerShow: webview.WebviewController = new webview.WebviewController(); @Consume('AsideWidth') asideWidth: number build() { @@ -74,6 +192,7 @@ export struct NoteListComp { OperateNoteCompForPortrait() } .flexShrink(0) + .padding({ bottom: 90}) } .height('100%') .width('100%') @@ -91,8 +210,8 @@ export struct NoteListComp { @Component struct NoteOverViewComp { - @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray') - @StorageLink('breakPoint') breakPoints: string = AppStorage.Get('breakPoint') + @StorageLink('AllNoteArray') AllNoteArray: NoteData[] = AppStorage.Link('AllNoteArray')!; + @StorageLink('breakPoint') breakPoints: string = AppStorage.Get('breakPoint')!; @StorageLink('CheckedNoteArray') CheckedNoteArray: NoteData[] = [] @Consume('SelectedFolderData') selectedFolderData: FolderData @Consume('RefreshFlag') refreshFlag: number @@ -101,14 +220,14 @@ struct NoteOverViewComp { @Consume('ExpandStatus') expandStatus: boolean @Consume('Search') search: boolean @Consume('PortraitModel') portraitModel: boolean - controllerShow: WebviewController - @State noteNumber: number = undefined + controllerShow: webview.WebviewController = new webview.WebviewController(); + @State noteNumber: number = 0; @StorageLink('isUpdate') @Watch('notesNumberChange') isUpdate: boolean = false @Consume('AsideWidth') asideWidth: number @State isShow: boolean = false notesNumberChange() { - let noteNumbers = FolderUtil.getNoteCount(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) + let noteNumbers = FolderUtil.getNoteCount(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid); if (noteNumbers == 0) { this.isShow = false } else { @@ -216,9 +335,9 @@ struct NoteOverViewComp { @Component export struct NoteItemComp { - public noteItem: NoteData - public spans: any[] - controllerShow: WebviewController + public noteItem: NoteData = new NoteData(0, '标题', new Date().getTime() + '', '', '', '', NoteType.SysDef, Top.No, Favorite.No, Delete.No, new Date().getTime(), new Date().getTime(), 0, 0); + public spans: TextSpan[] = []; + controllerShow: webview.WebviewController = new webview.WebviewController(); @Consume('SelectedFolderData') selectedFolderData: FolderData @Consume('SelectedNoteData') selectedNoteData: NoteData @StorageLink('AllFolderArray') AllFolderArray: FolderData[] = AppStorage.Link('AllFolderArray') @@ -228,7 +347,7 @@ export struct NoteItemComp { @Consume('Search') search: boolean @Consume('selectedAll') selectedAll: boolean @Consume('PortraitModel') portraitModel: boolean - @State isChecked: boolean = undefined + @State isChecked: boolean = false; @Consume('Longpress') @Watch('isLongPress') longpress: boolean @StorageLink('isUpdate') isUpdate: boolean = false @@ -253,7 +372,7 @@ export struct NoteItemComp { .id(this.isUpdate + '') .height(16) .width(4) - .fillColor(NoteUtil.getVerticalBarBgColor(AppStorage.Get('AllFolderArray'), this.noteItem.folder_uuid)) + .fillColor(NoteUtil.getVerticalBarBgColor(AppStorage.Get('AllFolderArray')!, this.noteItem.folder_uuid)) Text(this.noteItem.title) .fontSize(16) .maxLines(1) @@ -320,7 +439,7 @@ export struct NoteItemComp { .borderRadius(24) .linearGradient({ direction: GradientDirection.Right, - colors: this.selectedNoteData.uuid == this.noteItem.uuid ? [[0xffcdae, 0.0], [0xFfece2, 1.0]] : [[0xffffff, 0.0], [0xffffff, 1.0]] + colors: this.selectedNoteData?.uuid == this.noteItem.uuid ? [[0xffcdae, 0.0], [0xFfece2, 1.0]] : [[0xffffff, 0.0], [0xffffff, 1.0]] }) .onClick(() => { if (this.search) { @@ -343,17 +462,23 @@ export struct NoteItemComp { this.selectedNoteData = this.noteItem this.chooseNote = true // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "NoteItemComp, set continue note success") } if (this.portraitModel == false) { - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" - ) - this.controllerShow.runJavaScript( - "RICH_EDITOR.cancelSelection()" - ) + try { + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData?.content_text + "')" + ) + this.controllerShow.runJavaScript( + "RICH_EDITOR.cancelSelection()" + ) + LogUtil.info(TAG, `runJavaScript setHtml and cancelSelection success`); + } catch (error) { + LogUtil.error(TAG, `runJavaScript setHtml and cancelSelection failed. + code:${JSON.stringify(error.code)},message:${JSON.stringify(error.message)}`); + } } if (this.portraitModel == true) { AppStorage.SetOrCreate('NewNote', this.selectedNoteData) @@ -361,7 +486,7 @@ export struct NoteItemComp { routePage() } this.selectedAll = this.CheckedNoteArray.length == - NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid).length + NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid).length; this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) }) .gesture( @@ -392,13 +517,14 @@ export struct NoteItemListComp { @Consume('SearchResultList') searchResultList: NoteData[] @Consume('SelectedNoteData') selectedNoteData: NoteData @Consume('PortraitModel') portraitModel: boolean - @State dateList: NoteData[] = [] - controllerShow: WebviewController + @State @Watch('setNoteListLazy') dateList: NoteData[] = []; + @State noteList: noteListData = new noteListData(); + controllerShow: webview.WebviewController = new webview.WebviewController(); @StorageLink('isUpdate') @Watch('updateList') isUpdate: boolean = false updateList() { if (this.isUpdate) { - this.dateList = NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) + this.dateList = NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid); } this.isUpdate = false this.doSearch() @@ -407,35 +533,43 @@ export struct NoteItemListComp { aboutToAppear() { LogUtil.info(TAG, "inputKeyWord:" + this.inputKeyword) this.inputKeyword = '' - this.dateList = NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) + this.dateList = NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid); } doSearch() { if (this.inputKeyword.length == 0) { - return - } - SearchModel.search(NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid), this.inputKeyword) + this.setNoteListLazy() + return; + }; + SearchModel.search(NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid), this.inputKeyword) .then((result: NoteData[]) => { LogUtil.info(TAG, "result size " + result.length.toString()) this.searchResultList = result + this.setNoteListLazy() if (this.searchResultList.length != 0) { this.selectedNoteData = this.searchResultList[0] } else { - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) + this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid)!; } if (this.portraitModel == false) { this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" + "RICH_EDITOR.setHtml('" + this.selectedNoteData?.content_text + "')" ) } // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "doSearch, set continue note success") this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) }) } + setNoteListLazy() { + let noteLazySource: NoteData[]; + this.inputKeyword.length === 0 ? noteLazySource = this.dateList : noteLazySource = this.searchResultList; + this.noteList.modifyAllData(noteLazySource); + } + build() { Column() { Text(this.refreshFlag.toString()).visibility(Visibility.None) @@ -477,8 +611,7 @@ export struct NoteItemListComp { .padding({ bottom: 120 }) .visibility((FolderUtil.getNoteCount(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) == 0) ? Visibility.Visible : Visibility.None) - ForEach(this.inputKeyword.length == 0 ? - this.dateList : this.searchResultList, (noteItem) => { + LazyForEach(this.noteList, (noteItem: NoteData) => { ListItem() { Column() { NoteItemComp({ @@ -489,7 +622,8 @@ export struct NoteItemListComp { } .padding({ left: 24, right: 24, bottom: 12 }) } - }, noteItem => JSON.stringify(noteItem)) + .visibility((FolderUtil.getNoteCount(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) == 0) ? Visibility.None : Visibility.Visible) + }, (noteItem: NoteData) => JSON.stringify(noteItem)) } .id(this.isUpdate + '') .margin((FolderUtil.getNoteCount(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) == 0) ? { @@ -500,6 +634,7 @@ export struct NoteItemListComp { .layoutWeight(1) .listDirection(Axis.Vertical) .edgeEffect(EdgeEffect.Spring) + .cachedCount(10) } .layoutWeight(1) .height("100%") @@ -537,29 +672,36 @@ export struct OperateNoteComp { @Consume('PortraitModel') portraitModel: boolean @Consume('selectedAll') selectedAll: boolean @StorageLink('isUpdate') isUpdate: boolean = false - controllerShow: WebviewController - noteDataMoveDialogCtl: CustomDialogController = new CustomDialogController({ - builder: NoteDataMoveDialog({ onConfirm: this.onMoveConfirm.bind(this) }), + controllerShow: webview.WebviewController = new webview.WebviewController(); + noteDataMoveDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: NoteDataMoveDialog({ onConfirm: (folderUuid: string) => { + this.onMoveConfirm(folderUuid); + } }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, }) + aboutToDisappear() { + this.noteDataMoveDialogCtl = null + this.noteDataDeleteDialogCtl = null + } + onMoveConfirm(folderUuid: string) { this.CheckedNoteArray.forEach((noteItem) => { noteItem.folder_uuid = folderUuid // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) - this.selectedNoteData = NoteUtil.getFirstNoteData(this.AllNoteArray, this.selectedFolderData.uuid) + this.selectedNoteData = NoteUtil.getFirstNoteData(this.AllNoteArray, this.selectedFolderData.uuid)!; // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "onMoveConfirm, set continue note success") if (this.portraitModel == false) { - this.controllerShow.runJavaScript("RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')") + this.controllerShow.runJavaScript("RICH_EDITOR.setHtml('" + this.selectedNoteData?.content_text + "')") } this.longpress = false this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) @@ -567,8 +709,10 @@ export struct OperateNoteComp { NoteUtil.refreshAll() } - noteDataDeleteDialogCtl: CustomDialogController = new CustomDialogController({ - builder: DeleteDialog({ onConfirm: this.onDeleteConfirm.bind(this), multiSelect: true }), + noteDataDeleteDialogCtl: CustomDialogController | null = new CustomDialogController({ + builder: DeleteDialog({ onConfirm: () => { + this.onDeleteConfirm(); + }, multiSelect: true }), alignment: DialogAlignment.Center, autoCancel: false, customStyle: true, @@ -582,7 +726,7 @@ export struct OperateNoteComp { // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) } else { this.CheckedNoteArray.forEach((noteItem: NoteData) => { @@ -590,18 +734,18 @@ export struct OperateNoteComp { // delete note from db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.delete(predicates_note, null) + RdbStoreUtil.delete(predicates_note, null); }) } NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) this.longpress = false - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) + this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid)!; if (this.portraitModel == false) { - this.controllerShow.runJavaScript("RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')") + this.controllerShow.runJavaScript("RICH_EDITOR.setHtml('" + this.selectedNoteData?.content_text + "')") } // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "OperateNoteComp, set continue note success") NoteUtil.refreshAll() @@ -622,7 +766,7 @@ export struct OperateNoteComp { // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) this.longpress = false NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) @@ -636,7 +780,7 @@ export struct OperateNoteComp { .margin({ right: this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? 0 : 18 }) .visibility(this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? Visibility.None : Visibility.Visible) .onClick(() => { - this.noteDataMoveDialogCtl.open() + this.noteDataMoveDialogCtl!.open(); }) Image($r('app.media.delete')) .width(24) @@ -645,7 +789,7 @@ export struct OperateNoteComp { .opacity(this.CheckedNoteArray.length == 0 ? 0.4 : 1) .enabled(this.CheckedNoteArray.length == 0 ? false : true) .onClick(() => { - this.noteDataDeleteDialogCtl.open() + this.noteDataDeleteDialogCtl!.open(); }) Image($r('app.media.recover')) .width(24) @@ -658,37 +802,38 @@ export struct OperateNoteComp { this.CheckedNoteArray.forEach((noteItem) => { noteItem.is_deleted = Delete.No noteItem.deleted_time = 0 - let context: any = getContext(this) - let resource = { + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + let resource: resourceManager.Resource = { bundleName: "com.ohos.note", moduleName: "default", id: $r('app.string.restore').id }; - context.resourceManager.getString(resource, (error, value) => { + context.resourceManager.getStringValue(resource, (error: BusinessError, value: string) => { if (error != null) { - console.log("error is " + error); + LogUtil.error(TAG, "error is " + error); } else { - prompt.showToast({ message: value, duration: 2000 }); + promptAction.showToast({ message: value, duration: 2000 }); } }); // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) this.longpress = false NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) NoteUtil.refreshAll() }) - Image(this.CheckedNoteArray.length == NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid).length ? $r('app.media.check_all1') : $r('app.media.check_all')) + Image(this.CheckedNoteArray.length == NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) + .length ? $r('app.media.check_all1') : $r('app.media.check_all')) .width(24) .height(24) .id(this.isUpdate + '') .onClick(() => { LogUtil.info(TAG, "select all click") if (this.CheckedNoteArray.length < - NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid).length) { - NoteUtil.setAllNotesChecked(this.CheckedNoteArray, NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid)) + NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid).length) { + NoteUtil.setAllNotesChecked(this.CheckedNoteArray, NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid)); } else { NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) } @@ -713,7 +858,7 @@ export struct AddNoteComp { @Consume('EditModel') editModel: boolean @Consume('ChooseNote') chooseNote: boolean @Consume('PortraitModel') portraitModel: boolean - controllerShow: WebviewController + controllerShow: webview.WebviewController = new webview.WebviewController(); build() { Image($r('app.media.addNote')) @@ -722,7 +867,7 @@ export struct AddNoteComp { .margin({ right: 12 }) .responseRegion({ x: -15.0, y: -15.0, width: 54, height: 54 }) .onClick(() => { - let noteData + let noteData: NoteData; if (this.selectedFolderData.uuid == SysDefFolderUuid.AllNotes || this.selectedFolderData.uuid == SysDefFolderUuid.MyFavorites) { noteData = new NoteData(0, "标题", new Date().getTime() + "", SysDefFolderUuid.UnClassified, "", "", NoteType.SysDef, Top.No, Favorite.No, Delete.No, new Date().getTime(), new Date().getTime(), 0, 0) } else { @@ -730,27 +875,32 @@ export struct AddNoteComp { } this.AllNoteArray.push(noteData) - RdbStoreUtil.insert(TableName.NoteTable, noteData.toNoteObject(), null) + RdbStoreUtil.insert(TableName.NoteTable, noteData.toNoteObject(), null); LogUtil.info(TAG, 'insert new note is:' + noteData.uuid) this.selectedNoteData = noteData AppStorage.SetOrCreate('NewNote', noteData) if (this.portraitModel == false) { - this.controllerShow.runJavaScript( - "RICH_EDITOR.setHtml('" + this.selectedNoteData.content_text + "')" - ) + try { + this.controllerShow.runJavaScript( + "RICH_EDITOR.setHtml('" + this.selectedNoteData?.content_text + "')" + ) + } catch (error) { + LogUtil.error(TAG, `runJavaScript setHtml content_text failed. + code:${JSON.stringify(error.code)},message:${JSON.stringify(error.message)}`); + } } if (this.portraitModel == true) { this.editModel = true } this.chooseNote = true // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('NewFolder', this.selectedFolderData) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "addNote, set continue note success") - routePage() AppStorage.SetOrCreate('isUpdate', true) + routePage() }) .visibility(this.longpress || this.selectedFolderData.uuid == SysDefFolderUuid.RecentDeletes ? Visibility.None : Visibility.Visible) } @@ -776,13 +926,14 @@ export struct SearchComp { focusControl.requestFocus('searchFocus') this.search = false // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); AppStorage.SetOrCreate('Search', this.search) }) Flex({ justifyContent: FlexAlign.Start }) { - Image($r('app.media.search')).width(20).height(20) + Image($r('app.media.search')) + .width(20) + .height(20) .focusable(true) .key('searchFocus') .defaultFocus(true) @@ -790,8 +941,7 @@ export struct SearchComp { .backgroundColor(this.longpress ? $r("app.color.search_longpress_bgcolor_f7f8f9") : $r("app.color.color_ffffff")) .caretColor($r("app.color.search_note_caret_color")) .enabled(this.longpress ? false : true) - .padding({ left: 6, top: 1 }) - .padding({ left: 6 }) + .padding({ left: 6, top: 0, bottom: 0, right: 0 }) .onEditChange((isEditing: boolean) => { // this.search = isEditing }) @@ -844,13 +994,20 @@ export struct OperateNoteCompForPortrait { @Consume('PortraitModel') portraitModel: boolean @State greyOpacity: boolean = false @StorageLink('isUpdate') isUpdate: boolean = false - noteDataMoveDialogCtlBottom: CustomDialogController = new CustomDialogController({ - builder: NoteDataMoveDialog({ onConfirm: this.onMoveConfirm.bind(this) }), + noteDataMoveDialogCtlBottom: CustomDialogController | null = new CustomDialogController({ + builder: NoteDataMoveDialog({ onConfirm: (folderUuid: string) => { + this.onMoveConfirm(folderUuid); + } }), alignment: DialogAlignment.Bottom, autoCancel: false, customStyle: true, }) + aboutToDisappear() { + this.noteDataMoveDialogCtlBottom = null + this.noteDataDeleteDialogCtlBottom = null + } + opacityChange() { if (this.CheckedNoteArray.length == 0 && this.longpress == true) { this.greyOpacity = true @@ -867,11 +1024,11 @@ export struct OperateNoteCompForPortrait { // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) - this.selectedNoteData = NoteUtil.getFirstNoteData(this.AllNoteArray, this.selectedFolderData.uuid) + this.selectedNoteData = NoteUtil.getFirstNoteData(this.AllNoteArray, this.selectedFolderData.uuid)!; // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "onMoveConfirm, set continue note success") this.longpress = false @@ -880,8 +1037,10 @@ export struct OperateNoteCompForPortrait { NoteUtil.refreshAll() } - noteDataDeleteDialogCtlBottom: CustomDialogController = new CustomDialogController({ - builder: DeleteDialog({ onConfirm: this.onDeleteConfirm.bind(this), multiSelect: true }), + noteDataDeleteDialogCtlBottom: CustomDialogController | null = new CustomDialogController({ + builder: DeleteDialog({ onConfirm: () => { + this.onDeleteConfirm(); + }, multiSelect: true }), alignment: DialogAlignment.Bottom, autoCancel: false, customStyle: true, @@ -895,7 +1054,7 @@ export struct OperateNoteCompForPortrait { // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) } else { this.CheckedNoteArray.forEach((noteItem: NoteData) => { @@ -903,15 +1062,15 @@ export struct OperateNoteCompForPortrait { // delete note from db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.delete(predicates_note, null) + RdbStoreUtil.delete(predicates_note, null); }) } NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) this.longpress = false this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) - this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) + this.selectedNoteData = NoteUtil.getFirstNoteData(AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid)!; // save continue data - let continueNote: string = JSON.stringify(this.selectedNoteData.toNoteObject()) + let continueNote: string = JSON.stringify(this.selectedNoteData?.toNoteObject()) AppStorage.SetOrCreate('ContinueNote', continueNote) LogUtil.info(TAG, "OperateNoteCompForPortrait, set continue note success") NoteUtil.refreshAll() @@ -932,7 +1091,7 @@ export struct OperateNoteCompForPortrait { // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) this.longpress = false this.refreshFlag = (this.refreshFlag == 0 ? 1 : 0) @@ -960,7 +1119,7 @@ export struct OperateNoteCompForPortrait { .height(24) .responseRegion({ x: -15.0, y: -15.0, width: 54, height: 54 }) .onClick(() => { - this.noteDataDeleteDialogCtlBottom.open() + this.noteDataDeleteDialogCtlBottom!.open(); AppStorage.SetOrCreate('isUpdate', true) }) Text($r("app.string.delete")) @@ -984,7 +1143,7 @@ export struct OperateNoteCompForPortrait { .height(24) .responseRegion({ x: -15.0, y: -15.0, width: 54, height: 54 }) .onClick(() => { - this.noteDataMoveDialogCtlBottom.open() + this.noteDataMoveDialogCtlBottom!.open(); AppStorage.SetOrCreate('isUpdate', true) }) Text($r("app.string.move")) @@ -1012,23 +1171,23 @@ export struct OperateNoteCompForPortrait { this.CheckedNoteArray.forEach((noteItem) => { noteItem.is_deleted = Delete.No noteItem.deleted_time = 0 - let context: any = getContext(this) - let resource = { + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + let resource: resourceManager.Resource = { bundleName: "com.ohos.note", moduleName: "default", id: $r('app.string.restore').id }; - context.resourceManager.getString(resource, (error, value) => { + context.resourceManager.getStringValue(resource, (error: BusinessError, value: string) => { if (error != null) { - console.log("error is " + error); + LogUtil.error(TAG, "error is " + error); } else { - prompt.showToast({ message: value, duration: 2000 }); + promptAction.showToast({ message: value, duration: 2000 }); } }); // update note to db let predicates_note = RdbStoreUtil.getRdbPredicates(TableName.NoteTable) predicates_note.equalTo(NoteTableColumn.Uuid, noteItem.uuid) - RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null) + RdbStoreUtil.update(noteItem.toNoteObject(), predicates_note, null); }) this.longpress = false NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) @@ -1056,10 +1215,10 @@ export struct OperateNoteCompForPortrait { .responseRegion({ x: -15.0, y: -15.0, width: 54, height: 54 }) .id(this.isUpdate + '') .onClick(() => { - if (this.CheckedNoteArray.length < - NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid) - .length) { - NoteUtil.setAllNotesChecked(this.CheckedNoteArray, NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray'), this.selectedFolderData.uuid)) + if (this.CheckedNoteArray.length < NoteUtil.getNoteDataArray(AppStorage.Get('AllNoteArray')!, + this.selectedFolderData.uuid).length) { + NoteUtil.setAllNotesChecked(this.CheckedNoteArray, NoteUtil.getNoteDataArray( + AppStorage.Get('AllNoteArray')!, this.selectedFolderData.uuid)); } else { NoteUtil.unsetAllNotesChecked(this.CheckedNoteArray) } diff --git a/hvigor/hvigor-config.json5 b/hvigor/hvigor-config.json5 new file mode 100644 index 0000000..6ebda67 --- /dev/null +++ b/hvigor/hvigor-config.json5 @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022-2025 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. + */ + +{ + "modelVersion": "5.0.2", + "dependencies": { + } +} \ No newline at end of file diff --git a/hvigorfile.js b/hvigorfile.js index 5f2735e..c7d411d 100644 --- a/hvigorfile.js +++ b/hvigorfile.js @@ -1,2 +1,17 @@ +/* + * 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. + */ + // Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. -module.exports = require('@ohos/hvigor-ohos-plugin').appTasks \ No newline at end of file +module.exports = require('@ohos/hvigor-ohos-plugin').appTasks; \ No newline at end of file diff --git a/oh-package.json5 b/oh-package.json5 new file mode 100644 index 0000000..2675be4 --- /dev/null +++ b/oh-package.json5 @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022-2025 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. + */ + +{ + "modelVersion": "5.0.2", + "license": "ISC", + "devDependencies": { + "@ohos/hypium": "1.0.6" + }, + "name": "ohos_note", + "description": "example description", + "repository": {}, + "version": "1.0.0", + "dependencies": {} +} \ No newline at end of file diff --git a/package.json b/package.json deleted file mode 100644 index 984f794..0000000 --- a/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "license": "ISC", - "devDependencies": {}, - "name": "ohos_note", - "ohos": { - "org": "huawei", - "directoryLevel": "project", - "buildTool": "hvigor" - }, - "description": "example description", - "repository": {}, - "version": "1.0.0", - "dependencies": { - "@ohos/hvigor": "1.2.2", - "@ohos/hvigor-ohos-plugin": "1.2.2", - "hypium": "^1.0.0", - "js-base64": "^3.7.2", - "@ohos/hypium": "1.0.2" - } -} diff --git a/product/default/.gitignore b/product/default/.gitignore index a5c564a..725ae70 100644 --- a/product/default/.gitignore +++ b/product/default/.gitignore @@ -1,4 +1,5 @@ /node_modules +/oh_modules /.preview /build /package.json \ No newline at end of file diff --git a/product/default/hvigorfile.js b/product/default/hvigorfile.js index d7720ee..c12d7a8 100644 --- a/product/default/hvigorfile.js +++ b/product/default/hvigorfile.js @@ -1,2 +1,2 @@ // Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. -module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks +module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks; diff --git a/product/default/package.json b/product/default/oh-package.json5 similarity index 76% rename from product/default/package.json rename to product/default/oh-package.json5 index 654e795..2ed8e33 100644 --- a/product/default/package.json +++ b/product/default/oh-package.json5 @@ -2,11 +2,6 @@ "license": "ISC", "devDependencies": {}, "name": "default", - "ohos": { - "org": "huawei", - "directoryLevel": "module", - "buildTool": "hvigor" - }, "description": "example description", "repository": {}, "version": "1.0.0", diff --git a/product/default/package-lock.json b/product/default/package-lock.json deleted file mode 100644 index 3d7999a..0000000 --- a/product/default/package-lock.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "default", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@ohos/component": { - "version": "file:../../features", - "requires": { - "@ohos/source": "file:../../common/resources", - "@ohos/utils": "file:../../common/utils" - }, - "dependencies": { - "@ohos/source": { - "version": "file:../../common/resources" - }, - "@ohos/utils": { - "version": "file:../../common/utils", - "requires": { - "@ohos/source": "file:../../common/resources" - }, - "dependencies": { - "@ohos/source": { - "version": "file:../../common/resources" - } - } - } - } - }, - "@ohos/source": { - "version": "file:../../common/resources" - }, - "@ohos/utils": { - "version": "file:../../common/utils", - "requires": { - "@ohos/source": "file:../../common/resources" - }, - "dependencies": { - "@ohos/source": { - "version": "file:../../common/resources" - } - } - } - } -} diff --git a/product/default/src/main/ets/Application/AbilityStage.ts b/product/default/src/main/ets/Application/AbilityStage.ts index 5f781ee..03d46a9 100644 --- a/product/default/src/main/ets/Application/AbilityStage.ts +++ b/product/default/src/main/ets/Application/AbilityStage.ts @@ -1,3 +1,18 @@ +/* + * 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 AbilityStage from '@ohos.app.ability.AbilityStage'; export default class MyAbilityStage extends AbilityStage { diff --git a/product/default/src/main/ets/MainAbility/MainAbility.ts b/product/default/src/main/ets/MainAbility/MainAbility.ts index f5687b7..4631775 100644 --- a/product/default/src/main/ets/MainAbility/MainAbility.ts +++ b/product/default/src/main/ets/MainAbility/MainAbility.ts @@ -15,209 +15,231 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import deviceInfo from '@ohos.deviceInfo'; -import AbilityConstant from '@ohos.app.ability.AbilityConstant' -import fileio from '@ohos.fileio' +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +import fileio from '@ohos.fileio'; import inputMethod from '@ohos.inputMethod'; -import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil' -import { atob } from 'js-base64' +import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil'; import display from '@ohos.display'; import window from '@ohos.window'; +import util from '@ohos.util'; +import common from '@ohos.app.ability.common'; +import relationalStore from '@ohos.data.relationalStore'; -globalThis.rdbStore = undefined +AppStorage.SetOrCreate('rdbStore', undefined); export default class MainAbility extends UIAbility { - private Tag = "MainAbility_Tablet" - - onCreate(want, launchParam) { - // @ts-ignore - window.getLastWindow(this.context, (err, data) => { - if (data && data.getWindowProperties()) { - let windowWidth = data.getWindowProperties().windowRect.width - LogUtil.info(this.Tag, " getLastWindow:" + windowWidth) - this.screenBreakPoints(windowWidth) - } else { - LogUtil.info(this.Tag, "getWindowProperties error:" + JSON.stringify(err)) - } - }) - LogUtil.info(this.Tag, " onCreate, launchReason is " + launchParam.launchReason + ", deviceType" + deviceInfo.deviceType) - if (deviceInfo.deviceType === 'phone' || deviceInfo.deviceType === 'default') { - AppStorage.SetOrCreate('Expand', false) - AppStorage.SetOrCreate('Choose', true) - } - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // 设置迁移标记 - AppStorage.SetOrCreate('IsContinue', true) - // 获取对端的迁移数据 - let Search: boolean = want.parameters["Search"] - let continueNote: string = want.parameters["ContinueNote"] - let continueSection: number = want.parameters["ContinueSection"] - let scrollTopPercent: number = want.parameters["ScrollTopPercent"] - let isFocusOnSearch: boolean = want.parameters["isFocusOnSearch"] - LogUtil.info(this.Tag, " continueSection : " + continueSection) - AppStorage.SetOrCreate('Search', Search) - AppStorage.SetOrCreate('ContinueNote', continueNote) - AppStorage.SetOrCreate('ContinueSection', continueSection) - // 使用新的key保存数据,防止迁移过来的数据在使用前被本地操作覆盖 - AppStorage.SetOrCreate('remoteScrollTopPercent', scrollTopPercent) - AppStorage.SetOrCreate('isRemoteFocusOnSearch', isFocusOnSearch) - // 来自手机的迁移 - let continueChoose: boolean = want.parameters["ContinueChoose"] - if (continueChoose) { - LogUtil.info(this.Tag, " continue from phone") - AppStorage.SetOrCreate('ContinueFromPhone', true) - } else { - AppStorage.SetOrCreate('ContinueFromTablet', true) - LogUtil.info(this.Tag, " continue from tablet") - } - this.context.restoreWindowStage(null) - } - globalThis.noteContext = this.context - } + private Tag = 'MainAbility_Tablet'; - onDestroy() { - LogUtil.info(this.Tag, " onDestroy") + onCreate(want, launchParam) { + + AppStorage.SetOrCreate('context', this.context); + LogUtil.info(this.Tag, " onCreate, launchReason is " + launchParam.launchReason + ", deviceType" + deviceInfo.deviceType); + if (deviceInfo.deviceType === 'phone' || deviceInfo.deviceType === 'default') { + AppStorage.SetOrCreate('Expand', false); + AppStorage.SetOrCreate('Choose', true); + } + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // 设置迁移标记 + AppStorage.SetOrCreate('IsContinue', true); + // 获取对端的迁移数据 + let Search: boolean = want.parameters["Search"]; + let continueNote: string = want.parameters["ContinueNote"]; + let continueSection: number = want.parameters["ContinueSection"]; + let scrollTopPercent: number = want.parameters["ScrollTopPercent"]; + let isFocusOnSearch: boolean = want.parameters["isFocusOnSearch"]; + LogUtil.info(this.Tag, " continueSection : " + continueSection); + AppStorage.SetOrCreate('Search', Search); + AppStorage.SetOrCreate('ContinueNote', continueNote); + AppStorage.SetOrCreate('ContinueSection', continueSection); + // 使用新的key保存数据,防止迁移过来的数据在使用前被本地操作覆盖 + AppStorage.SetOrCreate('remoteScrollTopPercent', scrollTopPercent); + AppStorage.SetOrCreate('isRemoteFocusOnSearch', isFocusOnSearch); + // 来自手机的迁移 + let continueChoose: boolean = want.parameters["ContinueChoose"]; + if (continueChoose) { + LogUtil.info(this.Tag, " continue from phone"); + AppStorage.SetOrCreate('ContinueFromPhone', true); + } else { + AppStorage.SetOrCreate('ContinueFromTablet', true); + LogUtil.error(this.Tag, " continue from tablet"); + } + this.context.restoreWindowStage(null); } + AppStorage.SetOrCreate('noteContext', this.context); - onWindowStageCreate(windowStage) { - windowStage.getMainWindow((err, data) => { - let windowClass = data - try { - windowClass.on('windowSizeChange', (data) => { - this.screenBreakPoints(data.width) - }) - } catch (exception) { - LogUtil.info(this.Tag, 'windowSizeChange fail') - } - }) + } - LogUtil.info(this.Tag, " onWindowStageCreate") - windowStage.setUIContent(this.context, "pages/MyNoteHome", null) - } + onDestroy() { + LogUtil.info(this.Tag, " onDestroy"); + } - onWindowStageDestroy() { - LogUtil.info(this.Tag, " onWindowStageDestroy") + onWindowStageCreate(windowStage) { + windowStage.getMainWindow((err, data) => { + let windowClass = data; + try { + windowClass.on('windowSizeChange', (data) => { + this.screenBreakPoints(data.width); + }) + // 窗口规避区域 + windowClass.on('avoidAreaChange', ({ type, area }) => { + if (type === window.AvoidAreaType.TYPE_SYSTEM) { + AppStorage.setOrCreate('topHeight', area.topRect.height); + AppStorage.setOrCreate('topWidth', area.topRect.width); + } + }); + windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); + // 设置主窗口沉浸式 + windowClass.setWindowLayoutFullScreen(true); + // 设置主窗口导航栏、状态栏、文字颜色等属性 + const sysBarProps: window.SystemBarProperties = { + statusBarColor: "#ffffff", + navigationBarColor: '#ffffff', + statusBarContentColor: '#000000', + navigationBarContentColor: '#000000' + }; + // 加载状态变量 + windowClass.setWindowSystemBarProperties(sysBarProps); + } catch (exception) { + LogUtil.error(this.Tag, 'windowSizeChange fail'); + } + }) + window.getLastWindow(this.context, (err, data) => { + if (data && data.getWindowProperties()) { + let windowWidth = data.getWindowProperties().windowRect.width; + LogUtil.info(this.Tag, " getLastWindow:" + windowWidth); + this.screenBreakPoints(windowWidth); + } else { + LogUtil.error(this.Tag, "getWindowProperties error:" + JSON.stringify(err)); + } + }) + LogUtil.info(this.Tag, " onWindowStageCreate"); + windowStage.setUIContent(this.context, "pages/MyNoteHome", null); + } + + onWindowStageDestroy() { + LogUtil.info(this.Tag, " onWindowStageDestroy"); + } + + onForeground() { + LogUtil.info(this.Tag, " onForeground"); + } + + onBackground() { + LogUtil.info(this.Tag, " onBackground"); + // 退出键盘 + inputMethod.getController().stopInputSession(); + } + + onContinue(wantParam: { [key: string]: any }) { + LogUtil.info(this.Tag, " onContinue"); + // 获取本端的迁移数据 + let Search = AppStorage.Get('Search'); + let continueNote = AppStorage.Get('ContinueNote'); + if (continueNote == undefined || continueNote == null) { + LogUtil.info(this.Tag, " onContinue, continueNote is error, default [0]"); + continueNote = JSON.stringify(AppStorage.Get('AllNoteArray')[0].toNoteObject()); } - onForeground() { - LogUtil.info(this.Tag, " onForeground") + let continueSection = AppStorage.Get('ContinueSection'); + if (continueSection == undefined || continueSection == null) { + LogUtil.info(this.Tag, " onContinue, continueSection is error, default 3"); + continueSection = 3; } + LogUtil.info(this.Tag, " onContinue, continueSection : " + continueSection); - onBackground() { - LogUtil.info(this.Tag, " onBackground") - // 退出键盘 - // @ts-ignore - inputMethod.getController().stopInputSession(); + let scrollTopPercent = AppStorage.Get('ScrollTopPercent'); + if (scrollTopPercent == undefined || scrollTopPercent == null) { + LogUtil.info(this.Tag, " onContinue, scrollTopPercent is error, default 0"); + scrollTopPercent = 0; } - onContinue(wantParam: { [key: string]: any }) { - LogUtil.info(this.Tag, " onContinue") - // 获取本端的迁移数据 - let Search = AppStorage.Get('Search') - let continueNote = AppStorage.Get('ContinueNote') - if (continueNote == undefined || continueNote == null) { - LogUtil.info(this.Tag, " onContinue, continueNote is error, default [0]") - continueNote = JSON.stringify(AppStorage.Get('AllNoteArray')[0].toNoteObject()) - } - - let continueSection = AppStorage.Get('ContinueSection') - if (continueSection == undefined || continueSection == null) { - LogUtil.info(this.Tag, " onContinue, continueSection is error, default 3") - continueSection = 3 - } - LogUtil.info(this.Tag, " onContinue, continueSection : " + continueSection) - - let scrollTopPercent = AppStorage.Get('ScrollTopPercent') - if (scrollTopPercent == undefined || scrollTopPercent == null) { - LogUtil.info(this.Tag, " onContinue, scrollTopPercent is error, default 0") - scrollTopPercent = 0 - } - - let isFocusOnSearch = AppStorage.Get('isFocusOnSearch') - if (isFocusOnSearch == undefined || isFocusOnSearch == null) { - LogUtil.info(this.Tag, " onContinue, isFocusOnSearch is error, default true") - isFocusOnSearch = true - } - - // 保存本端的迁移数据 - wantParam["Search"] = Search - wantParam["ContinueNote"] = continueNote - wantParam["ContinueSection"] = continueSection - wantParam["ScrollTopPercent"] = scrollTopPercent - wantParam["isFocusOnSearch"] = isFocusOnSearch - if (deviceInfo.deviceType === 'phone' || deviceInfo.deviceType === 'default') { - wantParam["ContinueChoose"] = true - } - - // save img to DisFileDir - LogUtil.info(this.Tag, " onContinue, save img to DisFileDir") - let continueNoteObj = JSON.parse(continueNote) - let srcArray = this.getSrcFromHtml(continueNoteObj.content_text) - srcArray.forEach((src: string) => { - let lastIndex = src.lastIndexOf('/') - if (lastIndex != -1) { - let imgName = src.substring(lastIndex + 1) - this.writeToDisFileDir(imgName) - } - }) - LogUtil.info(this.Tag, " onContinue end") - return AbilityConstant.OnContinueResult.AGREE + let isFocusOnSearch = AppStorage.Get('isFocusOnSearch'); + if (isFocusOnSearch == undefined || isFocusOnSearch == null) { + LogUtil.info(this.Tag, " onContinue, isFocusOnSearch is error, default true"); + isFocusOnSearch = true; } - getSrcFromHtml(html: string): any { - let srcArray = [] - if (html == undefined || html == null || html == "") { - return srcArray - } - let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/ - let realHtml = "" - if (base64regex.test(html)) { - realHtml = atob(html) - } else { - realHtml = html; - } - let imgReg = /]+>/g - let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i - let imgArray = realHtml.match(imgReg) - if (imgArray != null) { - for (let i = 0; i < imgArray.length; i++) { - let src = imgArray[i].match(srcReg) - if (src != null && src.length > 1) { - LogUtil.info(this.Tag, " getSrcFromHtml, src[1] : " + src[1]) - srcArray.push(src[1]) - } - } - } - return srcArray + // 保存本端的迁移数据 + wantParam["Search"] = Search; + wantParam["ContinueNote"] = continueNote; + wantParam["ContinueSection"] = continueSection; + wantParam["ScrollTopPercent"] = scrollTopPercent; + wantParam["isFocusOnSearch"] = isFocusOnSearch; + if (deviceInfo.deviceType === 'phone' || deviceInfo.deviceType === 'default') { + wantParam["ContinueChoose"] = true; } - writeToDisFileDir(fileName: string) { - LogUtil.info(this.Tag, " writeToDisFileDir, fileName : " + fileName) - let filesDir = this.context.filesDir - let srcPath = filesDir + "/" + fileName - let distributedFilesDir = this.context.distributedFilesDir - let desPath = distributedFilesDir + "/" + fileName - try { - fileio.copyFileSync(srcPath, desPath) - LogUtil.info(this.Tag, " onContinue, writeToDisFileDir, copyFile successfully" + desPath + " " + srcPath) - } catch (err) { - LogUtil.warn(this.Tag, " onContinue, writeToDisFileDir, copyFile failed : " + err) - } + // save img to DisFileDir + LogUtil.info(this.Tag, " onContinue, save img to DisFileDir"); + let continueNoteObj = JSON.parse(continueNote); + let srcArray = this.getSrcFromHtml(continueNoteObj.content_text); + srcArray.forEach((src: string) => { + let lastIndex = src.lastIndexOf('/'); + if (lastIndex != -1) { + let imgName = src.substring(lastIndex + 1); + this.writeToDisFileDir(imgName); + } + }) + LogUtil.info(this.Tag, " onContinue end"); + return AbilityConstant.OnContinueResult.AGREE; + } + + getSrcFromHtml(html: string): any { + let srcArray = []; + if (html == undefined || html == null || html == "") { + return srcArray; } - - screenBreakPoints(data) { - let displayClass = null - let screenDpi = null - displayClass = display.getDefaultDisplaySync() - screenDpi = displayClass.densityDPI - AppStorage.SetOrCreate('dpi', screenDpi) - let windowWidth = data / (screenDpi / 160) - LogUtil.debug(this.Tag, " screenBreakPoints windowWidth: " + windowWidth) - if (windowWidth >= 320 && windowWidth < 520 || windowWidth < 320) { - AppStorage.SetOrCreate('breakPoint', 'sm') - } else if (windowWidth >= 520 && windowWidth < 840) { - AppStorage.SetOrCreate('breakPoint', 'md') - } else if (windowWidth >= 840) { - AppStorage.SetOrCreate('breakPoint', 'lg') + let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + let realHtml; + if (base64regex.test(html)) { + let base64 = new util.Base64Helper; + realHtml = base64.decodeSync(html).toString(); + } else { + realHtml = html; + } + let imgReg = /]+>/g; + let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; + let imgArray = realHtml.match(imgReg); + if (imgArray != null) { + for (let i = 0; i < imgArray.length; i++) { + let src = imgArray[i].match(srcReg); + if (src != null && src.length > 1) { + LogUtil.info(this.Tag, " getSrcFromHtml, src[1] : " + src[1]); + srcArray.push(src[1]); } + } + } + return srcArray + } + + writeToDisFileDir(fileName: string) { + LogUtil.info(this.Tag, " writeToDisFileDir, fileName : " + fileName); + let filesDir = this.context.filesDir; + let srcPath = filesDir + "/" + fileName; + let distributedFilesDir = this.context.distributedFilesDir; + let desPath = distributedFilesDir + "/" + fileName; + try { + fileio.copyFileSync(srcPath, desPath); + LogUtil.info(this.Tag, " onContinue, writeToDisFileDir, copyFile successfully" + desPath + " " + srcPath); + } catch (err) { + LogUtil.error(this.Tag, " onContinue, writeToDisFileDir, copyFile failed : " + err); + } + } + + screenBreakPoints(data) { + let displayClass = null; + let screenDpi = null; + displayClass = display.getDefaultDisplaySync(); + screenDpi = displayClass.densityDPI; + AppStorage.SetOrCreate('dpi', screenDpi); + let windowWidth = data / (screenDpi / 160); + LogUtil.debug(this.Tag, " screenBreakPoints windowWidth: " + windowWidth); + if (windowWidth >= 320 && windowWidth < 520 || windowWidth < 320) { + AppStorage.SetOrCreate('breakPoint', 'sm'); + } else if (windowWidth >= 520 && windowWidth < 840) { + AppStorage.SetOrCreate('breakPoint', 'md'); + } else if (windowWidth >= 840) { + AppStorage.SetOrCreate('breakPoint', 'lg'); } + } } \ No newline at end of file diff --git a/product/default/src/main/ets/pages/MyNoteHome.ets b/product/default/src/main/ets/pages/MyNoteHome.ets index 6aa3804..875cce5 100644 --- a/product/default/src/main/ets/pages/MyNoteHome.ets +++ b/product/default/src/main/ets/pages/MyNoteHome.ets @@ -22,15 +22,19 @@ import inputMethod from '@ohos.inputMethod'; import router from '@system.router'; import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; import webview from '@ohos.web.webview'; +import { BusinessError } from '@ohos.base'; +import common from '@ohos.app.ability.common'; @Entry @Component export struct MyNoteHomeComp { + @StorageLink('topHeight') topHeight: number = 0; // 窗口规避区域高 + @StorageLink('topWidth') topWidth: number = 0; // 窗口规避区域宽 @StorageLink('DBQueryFinished') dBQueryFinished: number = 0 @Provide('PortraitModel') portraitModel: boolean = true @Provide('RefreshFlag') refreshFlag: number = 0 private controllerShow: WebviewController = new webview.WebviewController() - private context = getContext(this) + private context = getContext(this) as common.UIAbilityContext; TAG = "MyNoteHomeComp_Tablet" @StorageLink('breakPoint') @Watch('onBreakPointChange') breakPoints: string = 'lg' @@ -43,23 +47,29 @@ export struct MyNoteHomeComp { } build() { - Row() { - if (this.dBQueryFinished == 1) { - if (this.breakPoints == 'sm') { - NoteHomePortraitComp() - } else { - NoteHomeComp({ controllerShow: this.controllerShow }) - } + Column() { + // 窗口顶部规避区域 + Row() + .width(px2vp(this.topWidth)) + .height(px2vp(this.topHeight)) + Row() { + if (this.dBQueryFinished == 1) { + if (this.breakPoints == 'sm') { + NoteHomePortraitComp() + } else { + NoteHomeComp({ controllerShow: this.controllerShow }) + } + } } + .width('100%') + .height('100%') } - .width('100%') - .height('100%') } aboutToAppear(): void { LogUtil.info(this.TAG, "aboutToAppear") - this.breakPoints = AppStorage.Get('breakPoint') + this.breakPoints = AppStorage.Get('breakPoint')!; if (this.breakPoints == 'sm' || this.breakPoints == 'md') { this.portraitModel = true } else { @@ -73,10 +83,9 @@ export struct MyNoteHomeComp { "ohos.permission.DISTRIBUTED_DATASYNC" ] LogUtil.info(this.TAG, 'permissions need to require from user') - let context: any = getContext(this); + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; let AtManager = abilityAccessCtrl.createAtManager(); //requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 - // @ts-ignore AtManager.requestPermissionsFromUser(context, ["ohos.permission.MANAGE_DISPOSED_APP_STATUS"]).then((data) => { LogUtil.info(this.TAG, 'data permissions : ' + data.permissions) LogUtil.info(this.TAG, 'data result: ' + data.authResults) @@ -85,7 +94,7 @@ export struct MyNoteHomeComp { sum += data.authResults[i] } LogUtil.info(this.TAG, 'request permissions sum: ' + sum) - }).catch((err) => { + }).catch((err: BusinessError) => { LogUtil.warn(this.TAG, 'failed to requestPermissionsFromUser : ' + err.code); }) let dbExist = false; @@ -132,7 +141,6 @@ export struct MyNoteHomeComp { onBackPress() { LogUtil.info(this.TAG, "onBackPress") // 退出键盘 - // @ts-ignore inputMethod.getController().stopInputSession(); setTimeout(() => { LogUtil.info(this.TAG, "wait save cotext") diff --git a/product/default/src/main/ets/pages/NoteContentHome.ets b/product/default/src/main/ets/pages/NoteContentHome.ets index 0733cca..4e732a9 100644 --- a/product/default/src/main/ets/pages/NoteContentHome.ets +++ b/product/default/src/main/ets/pages/NoteContentHome.ets @@ -20,6 +20,7 @@ import { LogUtil } from '@ohos/utils/src/main/ets/default/baseUtil/LogUtil' import RdbStoreUtil from '@ohos/utils/src/main/ets/default/baseUtil/RdbStoreUtil' import inputMethod from '@ohos.inputMethod' import webview from '@ohos.web.webview'; +import common from '@ohos.app.ability.common'; @Entry @Component @@ -53,7 +54,6 @@ struct NoteContentHome { this.controllerShow.runJavaScript("RICH_EDITOR.setInputEnabled(false)") this.controllerShow.runJavaScript("getHtmlContent()") if (deviceInfo.deviceType !== 'phone' && deviceInfo.deviceType !== 'default') { - // @ts-ignore inputMethod.getController().stopInputSession(); } } catch (error) { @@ -62,12 +62,13 @@ struct NoteContentHome { } aboutToAppear(): void { - this.breakPoints = AppStorage.Get('breakPoint') + let noteContext = AppStorage.Get('noteContext')!; + this.breakPoints = AppStorage.Get('breakPoint')!; LogUtil.info(this.TAG, "aboutToAppear") let isContinue = AppStorage.Get('IsContinue') LogUtil.info(this.TAG, "aboutToAppear, isContinue : " + isContinue) if (isContinue) { - RdbStoreUtil.initAppStorage(globalThis.noteContext) + RdbStoreUtil.initAppStorage(noteContext); } if (deviceInfo.deviceType === 'phone' || deviceInfo.deviceType === 'default') { AppStorage.SetOrCreate('NoteContentHomeExist', true) diff --git a/product/default/src/main/ets/pages/NoteHome.ets b/product/default/src/main/ets/pages/NoteHome.ets index 0dcbb1e..b2b6e24 100644 --- a/product/default/src/main/ets/pages/NoteHome.ets +++ b/product/default/src/main/ets/pages/NoteHome.ets @@ -22,27 +22,28 @@ import { circleColorArray } from '@ohos/utils/src/main/ets/default/model/NoteBas import FolderData from '@ohos/utils/src/main/ets/default/model/databaseModel/FolderData' import NoteData from '@ohos/utils/src/main/ets/default/model/databaseModel/NoteData' import LayoutUtil from '@ohos/utils/src/main/ets/default/baseUtil/LayoutUtil' +import webview from '@ohos.web.webview'; @Entry @Component export struct NoteHomeComp { // 当前文件夹、笔记、分栏 - @Provide('SelectedFolderData') selectedFolderData: FolderData = AppStorage.Get('Folder') - @Provide('SelectedNoteData') selectedNoteData: NoteData = AppStorage.Get('Note') - @Provide('SectionStatus') sectionStatus: number = AppStorage.Get('Section') + @Provide('SelectedFolderData') selectedFolderData: FolderData = AppStorage.Get('Folder')!; + @Provide('SelectedNoteData') selectedNoteData: NoteData = AppStorage.Get('Note')!; + @Provide('SectionStatus') sectionStatus: number = AppStorage.Get('Section')!; @Provide('SelectedColor') selectedColor: string = circleColorArray[0] @Provide('LastSectionStatus') lastSectionStatus: number = 3 // 记录分栏上一次的状态 @Provide('Longpress') longpress: boolean = false // 第二栏长按状态 @Provide('ExpandStatus') expandStatus: boolean = false // 笔记本折叠展开状态 @Provide('ChooseNote') chooseNote: boolean = true // 是否选择笔记进行打开 - @Provide('Search') search: boolean = AppStorage.Get('Search') // 是否处于搜索状态 + @Provide('Search') search: boolean = AppStorage.Get('Search')!; // 是否处于搜索状态 @Provide('SearchResultList') searchResultList: NoteData[] = [] // 搜索得到的笔记列表 @Provide('InputKeyword') inputKeyword: string = '' // 搜索的字串 @Provide('SelectedAll') selectedAll: boolean = false @Provide('EditModel') editModel: boolean = false //编辑模式:临时方案 @Provide('Issave') issave: number = 0 @StorageLink('breakPoint') breakPoints: string = 'lg' - controllerShow: WebviewController + controllerShow: webview.WebviewController = new webview.WebviewController(); TAG = "NoteHomeComp_Tablet" @Provide('AsideWidth') asideWidth: number = 200 @@ -159,7 +160,7 @@ export struct NoteHomeComp { let isContinue = AppStorage.Get('IsContinue') LogUtil.info(this.TAG, "aboutToAppear, isContinue : " + isContinue) if (isContinue) { - this.sectionStatus = AppStorage.Get('Section') + this.sectionStatus = AppStorage.Get('Section')!; } // continue from phone let continueFromPhone = AppStorage.Get('ContinueFromPhone') diff --git a/product/default/src/main/ets/pages/NoteHomePortrait.ets b/product/default/src/main/ets/pages/NoteHomePortrait.ets index 37d9867..6fd5960 100644 --- a/product/default/src/main/ets/pages/NoteHomePortrait.ets +++ b/product/default/src/main/ets/pages/NoteHomePortrait.ets @@ -25,8 +25,8 @@ import NoteData from '@ohos/utils/src/main/ets/default/model/databaseModel/NoteD @Component export struct NoteHomePortraitComp { // 当前文件夹、笔记、分栏 - @Provide('SelectedFolderData') selectedFolderData: FolderData = AppStorage.Get('Folder') - @Provide('SelectedNoteData') selectedNoteData: NoteData = AppStorage.Get('Note') + @Provide('SelectedFolderData') selectedFolderData: FolderData = AppStorage.Get('Folder')!; + @Provide('SelectedNoteData') selectedNoteData: NoteData = AppStorage.Get('Note')!; @Provide('SectionStatus') sectionStatus: number = 1; // 表示分栏状态, 3表示三分栏, 2表示二分栏,1表示一分栏 @Provide('LastSectionStatus') lastSectionStatus: number = 1; // 记录分栏上一次的状态 @Provide('SelectedColor') selectedColor: string = circleColorArray[0]; @@ -34,7 +34,7 @@ export struct NoteHomePortraitComp { // 分栏状态 @Provide('ExpandStatus') expandStatus: boolean = false // 笔记本折叠展开状态 - @Provide('ChooseNote') chooseNote: boolean = AppStorage.Get('Choose') // 是否选择笔记进行打开 + @Provide('ChooseNote') chooseNote: boolean = AppStorage.Get('Choose')!; // 是否选择笔记进行打开 @Provide('Search') search: boolean = false // 是否处于搜索状态 @Provide('SearchResultList') searchResultList: NoteData[] = [] // 搜索得到的笔记列表 diff --git a/product/default/src/main/module.json5 b/product/default/src/main/module.json5 index 90ee051..7ca6009 100644 --- a/product/default/src/main/module.json5 +++ b/product/default/src/main/module.json5 @@ -18,7 +18,7 @@ "module": { "name": "default", "type": "entry", - "srcEntrance": "./ets/Application/AbilityStage.ts", + "srcEntry": "./ets/Application/AbilityStage.ts", "description": "$string:entry_MainAbility", "mainElement": "MainAbility", "deviceTypes": [ @@ -30,23 +30,57 @@ "name": "ohos.permission.INTERNET" }, { - "name": "ohos.permission.READ_MEDIA", - "reason": "$string:read_media_permission" + "name": "ohos.permission.MEDIA_LOCATION", + "reason": "$string:media_location_permission", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when":"inuse" + } }, { - "name": "ohos.permission.WRITE_MEDIA", - "reason": "$string:write_media_permission" + "name": "ohos.permission.DISTRIBUTED_DATASYNC", + "reason": "$string:distributed_dataSync_permission", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when":"inuse" + } }, { - "name": "ohos.permission.MEDIA_LOCATION", - "reason": "$string:media_location_permission" + "name": "ohos.permission.START_ABILITIES_FROM_BACKGROUND" }, { - "name": "ohos.permission.DISTRIBUTED_DATASYNC", - "reason": "$string:distributed_dataSync_permission" + "name": "ohos.permission.READ_IMAGEVIDEO", + "reason": "$string:read_image_video_permission", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when":"inuse" + } }, { - "name": "ohos.permission.START_ABILITIES_FROM_BACKGROUND" + "name": "ohos.permission.WRITE_IMAGEVIDEO", + "reason": "$string:write_image_video_permission", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when":"inuse" + } + }, + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING", + "reason": "$string:keep_background_running_permission", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when":"always" + } } ], "deliveryWithInstall": true, @@ -62,7 +96,7 @@ "abilities": [ { "name": "MainAbility", - "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "srcEntry": "./ets/MainAbility/MainAbility.ts", "description": "$string:entry_MainAbility", "icon": "$media:note", "label": "$string:entry_MainAbility", @@ -78,6 +112,9 @@ ] } ], + "backgroundModes": [ + "dataTransfer" + ], "startWindowBackground": "$color:color_1", "startWindowIcon": "$media:note" } diff --git a/product/default/src/main/resources/base/element/string.json b/product/default/src/main/resources/base/element/string.json index 5a03f94..b71cead 100644 --- a/product/default/src/main/resources/base/element/string.json +++ b/product/default/src/main/resources/base/element/string.json @@ -4,10 +4,6 @@ "name": "entry_MainAbility", "value": "备忘录" }, - { - "name": "read_media_permission", - "value": "Used to read media file information in external storage of users" - }, { "name": "media_location_permission", "value": "Used for memo access to geographic location information in user media files" @@ -17,8 +13,16 @@ "value": "Used for memo data exchange between different equipment" }, { - "name": "write_media_permission", - "value": "Used to write media file information in external storage of users" + "name": "read_image_video_permission", + "value": "Used to read images or video files from the user's public directory" + }, + { + "name": "write_image_video_permission", + "value": "Used to modify image or video files in the user's public directory" + }, + { + "name": "keep_background_running_permission", + "value": "Allow Service Ability to run continuously in the background" } ] } \ No newline at end of file diff --git a/product/default/src/main/resources/zh_CN/element/string.json b/product/default/src/main/resources/zh_CN/element/string.json index 2629b77..9538ea3 100644 --- a/product/default/src/main/resources/zh_CN/element/string.json +++ b/product/default/src/main/resources/zh_CN/element/string.json @@ -1,9 +1,5 @@ { "string": [ - { - "name": "read_media_permission", - "value": "用于备忘录读取用户外部存储中的媒体文件信息" - }, { "name": "media_location_permission", "value": "用于备忘录访问用户媒体文件中的地理位置信息" @@ -13,8 +9,16 @@ "value": "用于备忘录进行不同设备间的数据交换" }, { - "name": "write_media_permission", - "value": "用于备忘录记录用户外部存储中的图片文件信息" + "name": "read_image_video_permission", + "value": "用于备忘录读取用户公共目录的图片或视频文件" + }, + { + "name": "write_image_video_permission", + "value": "用于备忘录修改用户公共目录的图片或视频文件" + }, + { + "name": "keep_background_running_permission", + "value": "允许Service Ability在后台持续运行" } ] } \ No newline at end of file diff --git a/signature/UnsgnedReleasedProfileTemplate.json b/signature/UnsgnedReleasedProfileTemplate.json index 198eac0..cb3463b 100644 --- a/signature/UnsgnedReleasedProfileTemplate.json +++ b/signature/UnsgnedReleasedProfileTemplate.json @@ -13,7 +13,7 @@ "distribution-certificate": "-----BEGIN CERTIFICATE-----\nMIICFDCCAZmgAwIBAgIEfc9FYzAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO\nMRQwEgYDVQQKEwtPcGVuSGFybW9ueTEZMBcGA1UECxMQT3Blbkhhcm1vbnkgVGVh\nbTEjMCEGA1UEAxMaT3Blbkhhcm1vbnkgQXBwbGljYXRpb24gQ0EwHhcNMjIxMjIx\nMDM0MjA3WhcNMzIxMjE4MDM0MjA3WjBKMRUwEwYDVQQDDAxpZGVfZGVtb19hcHAx\nDTALBgNVBAsTBFVuaXQxFTATBgNVBAoTDE9yZ2FuaXphdGlvbjELMAkGA1UEBhMC\nQ04wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATB+nRPXBTqJciFQWBaHGoEZFUs\nB2g+vVAkO2mqzvC4EvHSZXABHQ9TfmNn5G2ew2pzIvzhVhpD+4Vgt6xLhlQPo1Iw\nUDAdBgNVHQ4EFgQUc1K0TS4hsnNYulx1ZK65mBYoTSMwDgYDVR0PAQH/BAQDAgeA\nMB8GA1UdIwQYMBaAFNuGtyIW1QuhS7fdJXu58QV9oi1HMAwGCCqGSM49BAMDBQAD\nZwAwZAIwH7iB1wE7x0wAQcyqOcycLi7BTyL9hWkTkp4CSRew6xdOfPDmYuPKv/85\nQw8tj4n2AjAPbFMRSrs4cJEIix5PDGxfe89u/JtAmlvKQCmIze1ivrbiXVu3nVsA\nZ0RDZPYTSqc\u003d\n-----END CERTIFICATE-----\n", "bundle-name": "com.ohos.note", "apl": "normal", - "app-feature": "hos_normal_app" + "app-feature": "hos_system_app" }, "acls": { "allowed-acls": [ -- Gitee