@tarojs/plugin-platform-harmony-ets 4.0.0-alpha.3 → 4.0.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/apis/base/system.ts +73 -20
  2. package/dist/apis/canvas/index.ts +10 -1
  3. package/dist/apis/device/clipboard.ts +16 -8
  4. package/dist/apis/framework/index.ts +1 -5
  5. package/dist/apis/index.ts +25 -17
  6. package/dist/apis/media/image/index.ts +207 -44
  7. package/dist/apis/storage/index.ts +146 -78
  8. package/dist/apis/ui/animation/animation.ts +71 -29
  9. package/dist/apis/ui/background.ts +2 -1
  10. package/dist/apis/ui/interaction/index.ts +42 -59
  11. package/dist/apis/ui/navigation-bar/index.ts +1 -1
  12. package/dist/apis/ui/pull-down-refresh.ts +9 -3
  13. package/dist/apis/ui/scroll/index.ts +5 -5
  14. package/dist/apis/ui/tab-bar.ts +3 -3
  15. package/dist/apis/utils/index.ts +20 -2
  16. package/dist/apis/utils/permissions.ts +6 -0
  17. package/dist/apis/wxml/IntersectionObserver.ts +18 -10
  18. package/dist/apis/wxml/selectorQuery.ts +26 -13
  19. package/dist/components-harmony-ets/button.ets +64 -34
  20. package/dist/components-harmony-ets/canvas.ets +51 -0
  21. package/dist/components-harmony-ets/checkbox.ets +73 -62
  22. package/dist/components-harmony-ets/form.ets +51 -29
  23. package/dist/components-harmony-ets/icon.ets +31 -19
  24. package/dist/components-harmony-ets/image.ets +34 -14
  25. package/dist/components-harmony-ets/index.ets +92 -0
  26. package/dist/components-harmony-ets/innerHtml.ets +11 -6
  27. package/dist/components-harmony-ets/input.ets +63 -41
  28. package/dist/components-harmony-ets/label.ets +71 -44
  29. package/dist/components-harmony-ets/listView.ets +31 -0
  30. package/dist/components-harmony-ets/movableArea.ets +126 -0
  31. package/dist/components-harmony-ets/movableView.ets +93 -0
  32. package/dist/components-harmony-ets/navigationBar.ets +65 -0
  33. package/dist/components-harmony-ets/pageMeta.ets +94 -0
  34. package/dist/components-harmony-ets/picker.ets +43 -39
  35. package/dist/components-harmony-ets/progress.ets +52 -0
  36. package/dist/components-harmony-ets/pseudo.ets +80 -0
  37. package/dist/components-harmony-ets/radio.ets +78 -68
  38. package/dist/components-harmony-ets/richText.ets +14 -30
  39. package/dist/components-harmony-ets/scrollList.ets +103 -0
  40. package/dist/components-harmony-ets/scrollView.ets +61 -57
  41. package/dist/components-harmony-ets/slider.ets +19 -15
  42. package/dist/components-harmony-ets/stickySection.ets +42 -0
  43. package/dist/components-harmony-ets/style.ets +386 -130
  44. package/dist/components-harmony-ets/swiper.ets +61 -20
  45. package/dist/components-harmony-ets/switch.ets +36 -32
  46. package/dist/components-harmony-ets/{index.ts → tag.ts} +6 -0
  47. package/dist/components-harmony-ets/text.ets +112 -50
  48. package/dist/components-harmony-ets/textArea.ets +50 -35
  49. package/dist/components-harmony-ets/utils/AttributeManager.ets +2 -2
  50. package/dist/components-harmony-ets/utils/DynamicCenter.ts +2 -2
  51. package/dist/components-harmony-ets/utils/flexManager.ets +49 -19
  52. package/dist/components-harmony-ets/utils/helper.ets +20 -8
  53. package/dist/components-harmony-ets/utils/htmlParser/HarmonyHTMLParser.ts +1 -2
  54. package/dist/components-harmony-ets/utils/htmlParser/index.ts +1 -1
  55. package/dist/components-harmony-ets/utils/index.ts +54 -50
  56. package/dist/components-harmony-ets/utils/styles.ets +172 -93
  57. package/dist/components-harmony-ets/video.ets +34 -21
  58. package/dist/components-harmony-ets/view.ets +63 -52
  59. package/dist/components-harmony-ets/webView.ets +40 -34
  60. package/dist/index.d.ts +152 -0
  61. package/dist/index.js +102 -56
  62. package/dist/index.js.map +1 -1
  63. package/dist/runtime-ets/bom/document.ts +6 -4
  64. package/dist/runtime-ets/bom/getComputedStyle.ts +2 -2
  65. package/dist/runtime-ets/bom/window.ts +7 -0
  66. package/dist/runtime-ets/current.ts +5 -1
  67. package/dist/runtime-ets/dom/bind.ts +28 -12
  68. package/dist/runtime-ets/dom/class-list.ts +2 -2
  69. package/dist/runtime-ets/dom/cssNesting.ts +419 -0
  70. package/dist/runtime-ets/dom/cssStyleDeclaration.ts +28 -42
  71. package/dist/runtime-ets/dom/document.ts +8 -11
  72. package/dist/runtime-ets/dom/element/canvas.ts +136 -0
  73. package/dist/runtime-ets/dom/element/element.ts +376 -57
  74. package/dist/runtime-ets/dom/element/form.ts +31 -26
  75. package/dist/runtime-ets/dom/element/index.ts +30 -2
  76. package/dist/runtime-ets/dom/element/movableArea.ts +11 -0
  77. package/dist/runtime-ets/dom/element/movableView.ts +244 -0
  78. package/dist/runtime-ets/dom/element/normal.ts +35 -8
  79. package/dist/runtime-ets/dom/element/progress.ts +11 -0
  80. package/dist/runtime-ets/dom/element/scrollView.ts +1 -0
  81. package/dist/runtime-ets/dom/element/text.ts +1 -8
  82. package/dist/runtime-ets/dom/element/video.ts +5 -4
  83. package/dist/runtime-ets/dom/element/webView.ts +12 -5
  84. package/dist/runtime-ets/dom/event.ts +3 -5
  85. package/dist/runtime-ets/dom/eventTarget.ts +2 -3
  86. package/dist/runtime-ets/dom/node.ts +65 -32
  87. package/dist/runtime-ets/dom/stylesheet/covertWeb2Hm.ts +418 -237
  88. package/dist/runtime-ets/dom/stylesheet/index.ts +29 -311
  89. package/dist/runtime-ets/dom/stylesheet/type.ts +53 -11
  90. package/dist/runtime-ets/dom/stylesheet/util.ts +33 -27
  91. package/dist/runtime-ets/index.ts +2 -1
  92. package/dist/runtime-ets/interface/event.ts +1 -1
  93. package/dist/runtime-ets/utils/index.ts +74 -13
  94. package/dist/runtime-ets/utils/info.ts +2 -2
  95. package/dist/runtime-framework/react/app.ts +15 -10
  96. package/dist/runtime-framework/react/hooks.ts +0 -1
  97. package/dist/runtime-framework/react/index.ts +0 -2
  98. package/dist/runtime-framework/react/native-page.ts +185 -78
  99. package/dist/runtime-framework/react/page.ts +4 -9
  100. package/dist/runtime-framework/react/utils/index.ts +3 -3
  101. package/dist/runtime-framework/solid/app.ts +30 -46
  102. package/dist/runtime-framework/solid/connect.ts +21 -3
  103. package/dist/runtime-framework/solid/hooks.ts +16 -11
  104. package/dist/runtime-framework/solid/index.ts +6 -2
  105. package/dist/runtime-framework/solid/page.ts +85 -31
  106. package/dist/runtime-framework/solid/reconciler/props.ts +70 -25
  107. package/dist/runtime-framework/solid/reconciler/render.ts +16 -6
  108. package/dist/runtime-framework/solid/reconciler/use.ts +0 -1
  109. package/dist/runtime-framework/solid/utils/index.ts +3 -5
  110. package/dist/runtime-utils.d.ts +827 -0
  111. package/dist/runtime-utils.js +652 -283
  112. package/dist/runtime-utils.js.map +1 -1
  113. package/dist/runtime.d.ts +1 -0
  114. package/dist/runtime.js +652 -283
  115. package/dist/runtime.js.map +1 -1
  116. package/index.js +3 -1
  117. package/package.json +14 -15
  118. package/static/media/cancel.svg +1 -1
  119. package/static/media/circle.svg +1 -1
  120. package/static/media/clear.svg +1 -1
  121. package/static/media/download.svg +1 -1
  122. package/static/media/info.svg +1 -1
  123. package/static/media/info_circle.svg +1 -1
  124. package/static/media/search.svg +1 -1
  125. package/static/media/success.svg +1 -1
  126. package/static/media/success_no_circle.svg +1 -1
  127. package/static/media/warn.svg +1 -1
  128. package/types/harmony.d.ts +5 -0
  129. package/types/index.d.ts +4 -0
  130. package/types/runtime.d.ts +1 -1
  131. /package/dist/runtime-framework/solid/{contant.ts → constant.ts} +0 -0
@@ -1,26 +1,78 @@
1
+ import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'
1
2
  // 设备信息,从 API Version 6 开始支持
2
3
  import deviceInfo from '@ohos.deviceInfo'
3
4
  // 显示设备属性,从 API Version 7 开始支持
4
5
  import _display from '@ohos.display'
5
6
  // 从 API Version 7 开始支持
6
7
  import i18n from '@ohos.i18n'
7
- // 设备信息 从API Version 6开始,该接口不再维护,推荐使用新接口'@ohos.deviceInfo'进行设备信息查询
8
- import deviceMethod from '@system.device'
8
+ import { Current, window } from '@tarojs/runtime'
9
9
 
10
10
  import { callAsyncFail, callAsyncSuccess } from '../utils'
11
11
 
12
12
  import type Taro from '@tarojs/taro/types'
13
13
 
14
- const display = _display.getDefaultDisplaySync()
14
+ let display
15
+ let navigationIndicatorRect
16
+ let safeArea: TaroGeneral.SafeAreaResult | null = null
17
+ let statusBarHeight
18
+ let windowRect
15
19
 
16
- let device
20
+ (Current as any).contextPromise.then((context) => {
21
+ const win = window.__ohos.getLastWindow(context)
22
+ win.then(mainWindow => {
23
+ const topRect = mainWindow.getWindowAvoidArea(window.__ohos.AvoidAreaType.TYPE_SYSTEM).topRect
24
+ navigationIndicatorRect = mainWindow.getWindowAvoidArea(window.__ohos.AvoidAreaType.TYPE_NAVIGATION_INDICATOR).bottomRect
25
+ statusBarHeight = topRect.top + topRect.height
26
+ windowRect = mainWindow.getWindowProperties().windowRect
17
27
 
18
- deviceMethod.getInfo({
19
- success: data => {
20
- device = data
21
- }
28
+ try {
29
+ display = _display.getDefaultDisplaySync()
30
+
31
+ setSafeArea({
32
+ top: statusBarHeight,
33
+ left: 0,
34
+ right: display.width,
35
+ bottom: navigationIndicatorRect?.top
36
+ })
37
+
38
+ // @ts-ignore
39
+ display.getCutoutInfo((err, { boundingRects = [], waterfallDisplayAreaRects = {} }: _display.CutoutInfo = {}) => {
40
+ if (err?.code) {
41
+ console.error('Failed to get cutout info', JSON.stringify(err))
42
+ return
43
+ }
44
+
45
+ const top = Math.max(...boundingRects.map(rect => rect.top + rect.height), waterfallDisplayAreaRects.top?.top + waterfallDisplayAreaRects.top?.height, statusBarHeight)
46
+ const bottom = Math.min(display.height - waterfallDisplayAreaRects.bottom?.top, navigationIndicatorRect?.top)
47
+ const left = waterfallDisplayAreaRects.left?.left + waterfallDisplayAreaRects.left?.width
48
+ const right = display.width - waterfallDisplayAreaRects.right?.left
49
+
50
+ setSafeArea({
51
+ top,
52
+ left,
53
+ right,
54
+ bottom
55
+ })
56
+ })
57
+ } catch (e) {
58
+ console.error('Failed to get display', e)
59
+ }
60
+ })
22
61
  })
23
62
 
63
+
64
+ function setSafeArea({ top, left, right, bottom }) {
65
+ safeArea = {
66
+ top,
67
+ bottom,
68
+ left,
69
+ right,
70
+ height: bottom - top,
71
+ width: right - left,
72
+ }
73
+ }
74
+
75
+
24
76
  /* 同步版本 */
25
77
  export const getSystemInfoSync: typeof Taro.getSystemInfoSync = function () {
26
78
  const res: any = {}
@@ -32,7 +84,7 @@ export const getSystemInfoSync: typeof Taro.getSystemInfoSync = function () {
32
84
  res.cameraAuthorized = null // 允许使用摄像头的开关 boolean
33
85
  res.enableDebug = null // 是否已打开调试 boolean
34
86
  res.fontSizeSetting = null // 用户字体大小(单位px) number
35
- res.language = i18n && i18n.getSystemLanguage && i18n.getSystemLanguage() // string
87
+ res.language = i18n?.getSystemLanguage?.() // string
36
88
  res.locationAuthorized = null // 定位的开关 boolean
37
89
  res.locationEnabled = null // 地理位置的系统开关 boolean
38
90
  res.microphoneAuthorized = null // 麦克风的开关 boolean
@@ -43,17 +95,18 @@ export const getSystemInfoSync: typeof Taro.getSystemInfoSync = function () {
43
95
  res.notificationSoundAuthorized = false // 通知带有声音的开关(仅 iOS 有效)boolean
44
96
  res.phoneCalendarAuthorized = null // 使用日历的开关 boolean
45
97
  res.wifiEnabled = false // Wi-Fi 的系统开关 boolean
46
- res.pixelRatio = null // 设备像素比,number
47
- res.platform = 'android' // 客户端平台 string
48
- res.safeArea = null // 在竖屏正方向下的安全区域 General.SafeAreaResult
49
- res.screenHeight = display && display.height // 屏幕高度,单位px number
50
- res.screenWidth = display && display.width // 屏幕宽度,单位px number
51
- res.statusBarHeight = null // 状态栏的高度,单位px number
52
- res.system = deviceInfo && deviceInfo.osFullName // 操作系统及版本 string
53
- res.theme = null // 系统当前主题,取值为light或dark 'light' | 'dark'
54
- res.windowWidth = device && device.windowWidth // 可使用窗口宽度,单位px number
55
- res.windowHeight = device && device.windowHeight // 可使用窗口高度,单位px number
56
- res.version = deviceInfo && deviceInfo.displayVersion // 版本号 string
98
+ res.pixelRatio = display && display.densityPixels // 设备像素比,number
99
+ res.platform = 'harmony' // 客户端平台 string
100
+ res.safeArea = safeArea // 在竖屏正方向下的安全区域 General.SafeAreaResult
101
+ res.screenHeight = display?.height // 屏幕高度,单位px number
102
+ res.screenWidth = display?.width // 屏幕宽度,单位px number
103
+ res.statusBarHeight = statusBarHeight // 状态栏的高度,单位px number
104
+ res.system = deviceInfo?.osFullName // 操作系统及版本 string
105
+ // Note: 更新配置时才能记录
106
+ res.theme = AppStorage.get('__TARO_APP_CONFIG')?.colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK ? 'dark' : 'light' // 系统当前主题,取值为light或dark 'light' | 'dark'
107
+ res.windowHeight = windowRect?.height // 可使用窗口高度,单位px number
108
+ res.windowWidth = windowRect?.width // 可使用窗口宽度,单位px number
109
+ res.version = deviceInfo?.displayVersion // 版本号 string
57
110
 
58
111
  return res
59
112
  }
@@ -1,12 +1,21 @@
1
+ import { eventSource } from '@tarojs/runtime'
2
+
1
3
  import { temporarilyNotSupport } from '../utils'
2
4
 
5
+ // @ts-ignore
6
+ import type { TaroCanvasElement } from '@tarojs/runtime'
3
7
  // 画布
4
8
 
5
9
  /** 创建离屏 canvas 实例 */
6
10
  export const createOffscreenCanvas = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas')
7
11
 
8
12
  /** 创建 canvas 的绘图上下文 CanvasContext 对象 */
9
- export const createCanvasContext = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas')
13
+ // export const createCanvasContext = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas')
14
+ export const createCanvasContext = (canvasId: string) => {
15
+ const dom = eventSource.get(`canvasId-${canvasId}`)
16
+ // return dom as TaroCanvasElement
17
+ if (dom) return (dom as unknown as TaroCanvasElement).context
18
+ }
10
19
 
11
20
  /** 把当前画布指定区域的内容导出生成指定大小的图片 */
12
21
  export const canvasToTempFilePath = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas')
@@ -1,5 +1,6 @@
1
1
  // 从 API Version 6 开始支持
2
2
  import pasteboard from '@ohos.pasteboard'
3
+ import promptAction from '@ohos.promptAction'
3
4
  import { isString } from '@tarojs/shared'
4
5
 
5
6
  import { callAsyncFail, getParameterError, object2String } from '../utils'
@@ -27,9 +28,20 @@ export const setClipboardData: typeof Taro.setClipboardData = function (options)
27
28
 
28
29
  return new Promise((resolve, reject) => {
29
30
  const systemPasteboard = pasteboard.getSystemPasteboard()
30
- const pasteData = pasteboard.createPlainTextData(data)
31
+ const pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, data)
31
32
 
32
- systemPasteboard.setPasteData(pasteData, (error, data) => { // callback形式调用异步接口
33
+ try {
34
+ systemPasteboard.setDataSync(pasteData)
35
+ promptAction.showToast({
36
+ message: '内容已复制',
37
+ duration: 1500,
38
+ bottom: '50%',
39
+ showMode: 1 // 设置弹窗显示模式,显示在应用之上。
40
+ })
41
+ return handle.success({
42
+ data,
43
+ }, { resolve, reject })
44
+ } catch (error) {
33
45
  if (error) {
34
46
  console.error('Failed to set PasteData. Cause: ' + JSON.stringify(error))
35
47
  res = {
@@ -37,12 +49,8 @@ export const setClipboardData: typeof Taro.setClipboardData = function (options)
37
49
  error: error
38
50
  }
39
51
  callAsyncFail(reject, res, options)
40
- } else {
41
- return handle.success({
42
- data,
43
- }, { resolve, reject })
44
52
  }
45
- })
53
+ }
46
54
  })
47
55
  }
48
56
 
@@ -54,7 +62,7 @@ export const getClipboardData: typeof Taro.getClipboardData = function (options)
54
62
  const handle = new MethodHandler({ name: 'getClipboardData', success, fail, complete })
55
63
  return new Promise((resolve, reject) => {
56
64
  const systemPasteboard = pasteboard.getSystemPasteboard()
57
- systemPasteboard.getPasteData((error, pasteData) => { // callback 形式调用异步接口
65
+ systemPasteboard.getData((error, pasteData) => { // callback 形式调用异步接口
58
66
  if (error) {
59
67
  console.error('Failed to obtain PasteData. Cause: ' + JSON.stringify(error))
60
68
  return handle.fail({
@@ -1,5 +1,3 @@
1
- import { Current } from '@tarojs/runtime'
2
-
3
1
  import { temporarilyNotSupport } from '../utils'
4
2
 
5
3
  export const ENV_TYPE = {
@@ -19,12 +17,10 @@ export function getEnv () {
19
17
  return ENV_TYPE.HARMONY
20
18
  }
21
19
 
22
- export { Current }
23
-
24
20
  // TODO
25
21
  export const getCurrentPages = () => []
26
22
 
27
- export const getCurrentInstance = () => Current
23
+ export { Current, getCurrentInstance } from '@tarojs/runtime'
28
24
 
29
25
  export const requirePlugin = temporarilyNotSupport('requirePlugin')
30
26
 
@@ -33,7 +33,7 @@ const defaultUnitPrecision = 5
33
33
  const defaultTargetUnit = 'vp'
34
34
 
35
35
  export function getApp () {
36
- return Current.app
36
+ return Current.app || {}
37
37
  }
38
38
 
39
39
  export function initPxTransform ({
@@ -58,20 +58,25 @@ export function initPxTransform ({
58
58
 
59
59
  const display = _display.getDefaultDisplaySync()
60
60
 
61
+ let displayWidth = display.width
62
+ let ratioCache: number | false = false
61
63
  let designWidthFunc: (input: number) => number
64
+ let designWidth = defaultDesignWidth
62
65
  function getRatio (value: number) {
63
- const config = (Current as any).taro?.config || {}
64
- if (!isFunction(designWidthFunc)) {
65
- designWidthFunc = isFunction(config.designWidth)
66
- ? config.designWidth
67
- : () => config.designWidth
68
- }
69
- const designWidth = designWidthFunc(value) || defaultDesignWidth
70
- const deviceRatio = config.deviceRatio || defaultDesignRatio
71
- if (!(designWidth in deviceRatio)) {
72
- throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`)
66
+ // Note: 提前调用 display 可能无法获取正确值
67
+ if (ratioCache === false || displayWidth !== display.width) {
68
+ const config = (Current as any).taro?.config || {}
69
+ if (!isFunction(designWidthFunc)) {
70
+ designWidthFunc = isFunction(config.designWidth)
71
+ ? config.designWidth
72
+ : () => config.designWidth
73
+ designWidth = designWidthFunc(value) || defaultDesignWidth
74
+ }
75
+ displayWidth = display.width
76
+ ratioCache = Math.min(display.width, display.height) / designWidth
73
77
  }
74
- return Math.min(display.width, display.height) / designWidth / deviceRatio[designWidth]
78
+
79
+ return ratioCache
75
80
  }
76
81
 
77
82
  // Note: 设置为 style 单位时会自动完成设计稿转换,设计开发者调用 API 时也许抹平差异,例如 pageScrollTo[option.offsetTop]
@@ -79,6 +84,9 @@ export function pxTransformHelper (size: number, unit?: string, isNumber = false
79
84
  const config = (Current as any).taro?.config || {}
80
85
  const targetUnit = unit || config.targetUnit || defaultTargetUnit
81
86
 
87
+ if (targetUnit === 'PX') {
88
+ return px2vp(size * display.scaledDensity) + 'vp'
89
+ }
82
90
  const ratio = getRatio(size)
83
91
  let val = size * ratio
84
92
 
@@ -92,19 +100,19 @@ export function pxTransformHelper (size: number, unit?: string, isNumber = false
92
100
  return isNumber ? val : val + targetUnit
93
101
  }
94
102
 
95
- export function pxTransform (size: number): number {
103
+ export function pxTransform (size: number): number | string {
96
104
  const config = (Current as any).taro?.config || {}
97
105
  const targetUnit = config.targetUnit || defaultTargetUnit
98
106
 
99
- let val = size
107
+ const val = size
100
108
  switch (targetUnit) {
101
109
  case 'vp':
102
- val = px2vp(size)
103
- break
110
+ return pxTransformHelper(size, 'px')
111
+ // return `${size}lpx`
104
112
  default:
105
113
  // NOTE: 鸿蒙环境下 style 会自动完成设计稿转换,无需在方法内二次调整
106
114
  }
107
- return val + config.targetUnit
115
+ return val + targetUnit
108
116
  }
109
117
 
110
118
  export function canIUseWebp () {
@@ -9,11 +9,15 @@
9
9
  // ❌ wx.saveImageToPhotosAlbum(Object object) api 9+ HarmonyOS不支持
10
10
  // ❌ wx.previewImage(Object object) api 9+ HarmonyOS不支持
11
11
 
12
+ import fs from '@ohos.file.fs'
12
13
  import picker from '@ohos.file.picker'
13
14
  import image from '@ohos.multimedia.image'
15
+ import { Current } from '@tarojs/runtime'
14
16
  import { isNull } from '@tarojs/shared'
15
17
 
16
- import { callAsyncFail, callAsyncSuccess, temporarilyNotSupport, validateParams } from '../../utils'
18
+ import { getSystemInfoSync } from '../../base'
19
+ import { callAsyncFail, callAsyncSuccess, requestPermissions, temporarilyNotSupport, validateParams } from '../../utils'
20
+ import { IMAGE_PERMISSION } from '../../utils/permissions'
17
21
 
18
22
  import type Taro from '@tarojs/taro/types'
19
23
 
@@ -22,12 +26,21 @@ interface IPackingOptionOHOS {
22
26
  quality: number
23
27
  }
24
28
 
29
+ interface IChooseImageData {
30
+ tempFilePaths?: string[]
31
+
32
+ tempFiles?: {
33
+ path: string
34
+ size: number
35
+ }[]
36
+ }
37
+
25
38
  const getImageInfoSchema = {
26
- url: 'String'
39
+ src: 'String'
27
40
  }
28
41
 
29
42
  const compressImageSchema = {
30
- url: 'String'
43
+ src: 'String'
31
44
  }
32
45
 
33
46
  const chooseImageSchema = {
@@ -60,61 +73,211 @@ export const getImageInfo: typeof Taro.getImageInfo = function (options) {
60
73
  })
61
74
  }
62
75
 
76
+
77
+ class CompressedImageInfo {
78
+ imageUri = '' // 压缩后图片保存位置的uri
79
+ imageByteLength = 0 // 压缩后图片字节长度
80
+ }
81
+
82
+ async function saveImage(compressedImageData, compressedImageUri) {
83
+ const tempArr = compressedImageUri.split('/')
84
+ const name = tempArr[tempArr.length - 1]
85
+ const context = getContext(Current?.page)
86
+ const applicationContext = context.getApplicationContext()
87
+ const tempDir = applicationContext.tempDir
88
+ const filePath = `${tempDir}/${name}`
89
+
90
+ try {
91
+ const res = fs.accessSync(filePath)
92
+ if (res) {
93
+ // 如果图片afterCompressiona.jpeg已存在,则删除
94
+ fs.unlinkSync(filePath)
95
+ }
96
+ } catch (err) {
97
+ console.error(`[Taro] saveImage Error: AccessSync failed with error message: ${err.message}, error code: ${err.code}`)
98
+ }
99
+
100
+ // 知识点:保存图片。获取最终图片压缩数据compressedImageData,保存图片。
101
+ // 压缩图片数据写入文件
102
+ const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
103
+ fs.writeSync(file.fd, compressedImageData)
104
+ fs.closeSync(file)
105
+
106
+ // 获取压缩图片信息
107
+ const compressedImageInfo = new CompressedImageInfo()
108
+ compressedImageInfo.imageUri = filePath
109
+ compressedImageInfo.imageByteLength = compressedImageData.byteLength
110
+
111
+ return compressedImageInfo
112
+ }
113
+
63
114
  export const compressImage: typeof Taro.compressImage = function (options) {
64
115
  return new Promise((resolve, reject) => {
65
- try {
66
- validateParams('compressImage', options, compressImageSchema)
67
- } catch (error) {
68
- const res = { errMsg: error.message }
69
- return callAsyncFail(reject, res, options)
70
- }
71
- const { src, quality = 80 } = options
116
+ requestPermissions(IMAGE_PERMISSION).then(() => {
117
+ try {
118
+ validateParams('compressImage', options, compressImageSchema)
119
+ } catch (error) {
120
+ const res = { errMsg: error.message }
121
+ return callAsyncFail(reject, res, options)
122
+ }
123
+ const { src, quality = 80, compressedWidth, compressedHeight } = options
124
+ const srcAfterCompress = src.includes('_after_compress') ? src : src.split('.').join('_after_compress.')
125
+ const file = fs.openSync(src, fs.OpenMode.READ_ONLY)
72
126
 
73
- const source = image.createImageSource(src)
74
- if (isNull(source)) {
75
- const createImageSourceError = { errMsg: 'compressImage fail: createImageSource has failed.' }
76
- callAsyncFail(reject, createImageSourceError, options)
77
- return
78
- }
127
+ // const stat = fs.statSync(file.fd)
128
+ // console.log('[Taro] 压缩前图片的大小为:', stat.size)
79
129
 
80
- const packer = image.createImagePacker(src)
81
- if (isNull(packer)) {
82
- const createImagePackerError = { errMsg: 'compressImage fail: createImagePacker has failed.' }
83
- callAsyncFail(reject, createImagePackerError, options)
84
- }
130
+ const source = image.createImageSource(file.fd)
131
+ if (isNull(source)) {
132
+ const createImageSourceError = { errMsg: 'compressImage fail: createImageSource has failed.' }
133
+ callAsyncFail(reject, createImageSourceError, options)
134
+ return
135
+ }
85
136
 
86
- const packingOptionsOHOS: IPackingOptionOHOS = {
87
- // TODO:需要获取文件名后缀
88
- format: 'image/jpeg',
89
- quality: quality
90
- }
91
- packer.packing(source, packingOptionsOHOS).then((value) => {
92
- callAsyncSuccess(resolve, value, options)
93
- }).catch((error) => {
94
- callAsyncFail(reject, error, options)
137
+ const width = source.getImageInfoSync().size.width
138
+ const height = source.getImageInfoSync().size.height
139
+ let wantWidth = compressedWidth || compressedHeight || 0
140
+ let wantHeight = compressedHeight || compressedWidth || 0
141
+
142
+ if (width > wantWidth || height > wantHeight) {
143
+ const heightRatio = height / wantHeight
144
+ const widthRatio = width / wantWidth
145
+ const finalRatio = heightRatio < widthRatio ? heightRatio : widthRatio
146
+
147
+ wantWidth = Math.round(width / finalRatio)
148
+ wantHeight = Math.round(height / finalRatio)
149
+ }
150
+
151
+ const decodingOptions = {
152
+ editable: true,
153
+ desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
154
+ desiredSize: { width: wantWidth, height: wantHeight }
155
+ }
156
+ source.createPixelMap(decodingOptions, (error, pixelMap) => {
157
+ if (error !== undefined) {
158
+ fs.closeSync(file)
159
+ const res = { errMsg: error }
160
+ callAsyncFail(reject, res, options)
161
+ } else {
162
+ const packer = image.createImagePacker(file.fd)
163
+ if (isNull(packer)) {
164
+ fs.closeSync(file)
165
+ const createImagePackerError = { errMsg: 'compressImage fail: createImagePacker has failed.' }
166
+ callAsyncFail(reject, createImagePackerError, options)
167
+ return
168
+ }
169
+
170
+ const isPNG = src.endsWith('.png')
171
+ const packingOptionsOHOS: IPackingOptionOHOS = {
172
+ format: isPNG ? 'image/png' : 'image/jpeg',
173
+ quality: quality
174
+ }
175
+ packer.packing(pixelMap, packingOptionsOHOS).then((value) => {
176
+ fs.closeSync(file)
177
+ saveImage(value, srcAfterCompress).then(result => {
178
+ callAsyncSuccess(resolve, { tempFilePath: result.imageUri }, options)
179
+ })
180
+ }).catch((error) => {
181
+ fs.closeSync(file)
182
+ callAsyncFail(reject, error, options)
183
+ })
184
+ }
185
+ })
186
+ }, (error: string) => {
187
+ const res = { errMsg: error }
188
+ return callAsyncFail(reject, res, options)
95
189
  })
96
190
  })
97
191
  }
98
192
 
99
193
  export const chooseImage: typeof Taro.chooseImage = function (options) {
100
194
  return new Promise((resolve, reject) => {
101
- try {
102
- validateParams('chooseImage', options, chooseImageSchema)
103
- } catch (error) {
104
- const res = { errMsg: error.message }
105
- return callAsyncFail(reject, res, options)
106
- }
195
+ requestPermissions(IMAGE_PERMISSION).then(() => {
196
+ try {
197
+ validateParams('chooseImage', options, chooseImageSchema)
198
+ } catch (error) {
199
+ const res = { errMsg: error.message }
200
+ return callAsyncFail(reject, res, options)
201
+ }
107
202
 
108
- const { count = 9 } = options
109
- const photoViewPicker = new picker.PhotoViewPicker()
203
+ const { count = 9 } = options
204
+ const photoViewPicker = new picker.PhotoViewPicker()
205
+ let sizeType = options.sizeType
110
206
 
111
- photoSelectOptions.maxSelectNumber = count // 选择媒体文件的最大数目
112
- photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE // 过滤选择媒体文件类型为IMAGE
207
+ if (!sizeType || !sizeType.length) {
208
+ sizeType = ['compressed', 'original']
209
+ }
113
210
 
114
- photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
115
- callAsyncSuccess(resolve, { tempFilePaths: photoSelectResult.photoUris })
116
- }).catch((error) => {
117
- callAsyncFail(reject, error, options)
211
+ photoSelectOptions.maxSelectNumber = count // 选择媒体文件的最大数目
212
+ photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE // 过滤选择媒体文件类型为IMAGE
213
+
214
+ photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
215
+ const result: IChooseImageData = {}
216
+ const isOrigin = photoSelectResult.isOriginalPhoto
217
+
218
+ if (isOrigin) {
219
+ const tempFilePaths: string[] = []
220
+ const tempFiles = photoSelectResult.photoUris.map(uri => {
221
+ const file = fs.openSync(uri, fs.OpenMode.READ_ONLY)
222
+ const stat = fs.statSync(file.fd)
223
+ const size = stat.size
224
+
225
+ fs.closeSync(file)
226
+ tempFilePaths.push(uri)
227
+
228
+ return {
229
+ size,
230
+ path: uri,
231
+ }
232
+ })
233
+
234
+ result.tempFiles = tempFiles
235
+ result.tempFilePaths = tempFilePaths
236
+
237
+ callAsyncSuccess(resolve, result, options)
238
+ } else {
239
+ const actions: Promise<string>[] = photoSelectResult.photoUris.map(uri => {
240
+ return new Promise<string>(resolve => {
241
+ compressImage({
242
+ src: uri,
243
+ compressedWidth: getSystemInfoSync().screenWidth / 2,
244
+ compressedHeight: getSystemInfoSync().screenHeight / 2,
245
+ success: (compressResult) => {
246
+ resolve(compressResult.tempFilePath)
247
+ }
248
+ })
249
+ })
250
+ })
251
+
252
+ Promise.all(actions).then(tempFilePaths => {
253
+ const tempFiles = tempFilePaths.map(uri => {
254
+ const file = fs.openSync(uri, fs.OpenMode.READ_ONLY)
255
+ const stat = fs.statSync(file.fd)
256
+ const size: number = stat.size
257
+
258
+ fs.closeSync(file)
259
+
260
+ return {
261
+ size,
262
+ path: uri,
263
+ }
264
+ })
265
+
266
+ result.tempFilePaths = tempFilePaths
267
+ result.tempFiles = tempFiles
268
+
269
+ callAsyncSuccess(resolve, result, options)
270
+ }).catch(error => {
271
+ const res = { errMsg: error }
272
+ return callAsyncFail(reject, res, options)
273
+ })
274
+ }
275
+ }).catch((error) => {
276
+ callAsyncFail(reject, error, options)
277
+ })
278
+ }, (error: string) => {
279
+ const res = { errMsg: error }
280
+ return callAsyncFail(reject, res, options)
118
281
  })
119
282
  })
120
283
  }