Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ jobs:
else
pnpm test
fi
- name: H5 Harmony Hybrid integration
shell: bash
run: pnpm --filter @tarojs/taro-h5 run test:integration
env:
NODE_OPTIONS: --max_old_space_size=4096
# 以下 coverage 流程通过 artifact 拆分文件作为单独 job 上传时间损耗过长,因此在在 node test 后直接继续执行
- name: Upload [taro-cli] coverage to Codecov
uses: codecov/codecov-action@v5
Expand Down
76 changes: 76 additions & 0 deletions packages/taro-components/__tests__/offscreen-canvas.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { newE2EPage } from '@stencil/core/testing'
import { build } from 'esbuild'

it('draws an image and reads its pixel with the H5 HTML canvas fallback', async () => {
const { outputFiles } = await build({
stdin: {
contents: `
export { createOffscreenCanvas } from '../../taro-h5/src/api/canvas/createOffscreenCanvas'
`,
resolveDir: __dirname,
},
bundle: true,
globalName: 'h5Canvas',
write: false,
})
const page = await newE2EPage()
await page.addScriptTag({ content: outputFiles[0].text })
const result = await page.evaluate(async () => {
Object.defineProperty(window, 'OffscreenCanvas', { configurable: true, value: undefined })
const { h5Canvas } = window as unknown as {
h5Canvas: typeof import('../../taro-h5/src/api/canvas/createOffscreenCanvas')
}
const canvas = h5Canvas.createOffscreenCanvas({ type: '2d', width: 1, height: 1 })
const context = canvas.getContext('2d')
if (!context) throw new Error('2D context is unavailable')

const image = canvas.createImage()
await new Promise<void>((resolve, reject) => {
image.onload = () => resolve()
image.onerror = reject
image.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><rect width="1" height="1" fill="red"/></svg>'
})
context.clearRect(0, 0, 1, 1)
context.drawImage(image, 0, 0)
return {
pixel: Array.from(context.getImageData(0, 0, 1, 1).data),
detachedHtmlCanvas: context.canvas instanceof HTMLCanvasElement && !context.canvas.isConnected,
}
})
expect(result).toEqual({ pixel: [255, 0, 0, 255], detachedHtmlCanvas: true })
})

it('falls back to HTML WebGL when a native canvas only supports 2D', async () => {
const { outputFiles } = await build({
stdin: {
contents: "export { createOffscreenCanvas } from '../../taro-h5/src/api/canvas/createOffscreenCanvas'",
resolveDir: __dirname,
},
bundle: true,
globalName: 'h5Canvas',
write: false,
})
const page = await newE2EPage()
await page.addScriptTag({ content: outputFiles[0].text })
const result = await page.evaluate(() => {
class PartialOffscreenCanvas {
getContext () { return null }
}
Object.defineProperty(window, 'OffscreenCanvas', { configurable: true, value: PartialOffscreenCanvas })
const { h5Canvas } = window as unknown as {
h5Canvas: typeof import('../../taro-h5/src/api/canvas/createOffscreenCanvas')
}
const canvas = h5Canvas.createOffscreenCanvas({ type: 'webgl', width: 1, height: 1 })
const gl = canvas.getContext('webgl')
if (!gl) throw new Error('WebGL is unavailable')
gl.clearColor(1, 0, 0, 1)
gl.clear(gl.COLOR_BUFFER_BIT)
const pixel = new Uint8Array(4)
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel)
return {
pixel: Array.from(pixel),
detachedHtmlCanvas: gl.canvas instanceof HTMLCanvasElement && !gl.canvas.isConnected,
}
})
expect(result).toEqual({ pixel: [255, 0, 0, 255], detachedHtmlCanvas: true })
})
10 changes: 10 additions & 0 deletions packages/taro-h5/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,13 @@
暴露给 `@tarojs/taro` 的 H5 端 API。

需要配合 `babel-plugin-transform-taroapi` 才能使用 ES6 default import 的语法,相关配置详情在 `babel-preset-taro` 中。

## H5 离屏画布类型

H5 项目通过 `@tarojs/taro` 调用离屏画布时,可在 H5 专用 tsconfig 的 `compilerOptions.types` 中加入 `@tarojs/taro-h5/types/h5`,或在 H5 专用声明文件中引用:

```ts
/// <reference types="@tarojs/taro-h5/types/h5" />
```

此入口为 `Taro.createOffscreenCanvas().getContext()` 提供可空的浏览器 2D/WebGL 类型。调用方应先判断上下文是否存在。小程序项目继续使用默认类型入口。
24 changes: 24 additions & 0 deletions packages/taro-h5/__tests__/canvas/offscreen.h5.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Taro from '@tarojs/taro'

import type {} from '../../types/h5'

export async function drawWithPublicApi (url: string) {
const canvas = Taro.createOffscreenCanvas({ type: '2d', width: 300, height: 150 })
const context = canvas.getContext('2d')
// @ts-expect-error H5 contexts can be unavailable.
context.clearRect(0, 0, 300, 150)
if (!context) return
const image = canvas.createImage()
image.onload = null
image.onerror = null
await new Promise<void>((resolve, reject) => {
image.onload = () => resolve()
image.onerror = reject
image.src = url
})
context.clearRect(0, 0, 300, 150)
context.drawImage(image, 0, 0)
return context.getImageData(0, 0, 300, 150)
}
const gl = Taro.createOffscreenCanvas({ type: 'webgl' }).getContext('webgl')
if (gl) gl.clear(gl.COLOR_BUFFER_BIT)
52 changes: 52 additions & 0 deletions packages/taro-h5/__tests__/canvas/offscreen.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { createOffscreenCanvas } from '@tarojs/taro-h5'

describe('createOffscreenCanvas', () => {
const original = Object.getOwnPropertyDescriptor(globalThis, 'OffscreenCanvas')

afterEach(() => {
if (original) Object.defineProperty(globalThis, 'OffscreenCanvas', original)
else Reflect.deleteProperty(globalThis, 'OffscreenCanvas')
jest.restoreAllMocks()
})

it('keeps dimensions and context on the native canvas', () => {
const context = {}
const backing = { width: 0, height: 0, getContext: jest.fn().mockReturnValue(context) }
const native = jest.fn().mockReturnValue(backing)
Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: native })

const canvas = createOffscreenCanvas({ type: '2d', width: 20, height: 10 })
expect(native).toHaveBeenCalledWith(20, 10)
expect(canvas.height).toBe(10)
canvas.width = 30
expect(backing.width).toBe(30)
expect(canvas.getContext('webgl')).toBeNull()
expect(canvas.getContext('2d')).toBe(context)
expect(backing.getContext).toHaveBeenCalledTimes(2)
expect(canvas.createImage()).toBeInstanceOf(HTMLImageElement)
})

it('falls back when the native canvas cannot provide the requested WebGL context', () => {
const nativeContext = jest.fn().mockReturnValue(null)
const native = jest.fn().mockImplementation(() => ({ getContext: nativeContext }))
Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: native })
const context = { clear: jest.fn() }
const htmlContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as unknown as WebGLRenderingContext)
const canvas = createOffscreenCanvas({ type: 'webgl', width: 40, height: 30 })
expect(nativeContext).toHaveBeenCalledWith('webgl')
expect(canvas.getContext('webgl')).toBe(context)
expect(canvas.getContext('2d')).toBeNull()
expect([canvas.width, canvas.height]).toEqual([40, 30])
expect((htmlContext.mock.instances[0] as HTMLCanvasElement).isConnected).toBe(false)
})

it('falls back to a detached HTML canvas and defaults to WebGL', () => {
Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: undefined })
const getContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null)
const canvas = createOffscreenCanvas({})
expect([canvas.width, canvas.height]).toEqual([300, 150])
expect(canvas.getContext('webgl')).toBeNull()
expect(getContext).toHaveBeenCalledWith('webgl')
expect((getContext.mock.instances[0] as HTMLCanvasElement).isConnected).toBe(false)
})
})
22 changes: 22 additions & 0 deletions packages/taro-h5/__tests__/canvas/offscreen.types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { resolve } from 'node:path'

import * as ts from 'typescript'

it.each(['offscreen.types.ts', 'offscreen.h5.types.ts'])('compiles %s under strict null checking', filename => {
const fixture = resolve(__dirname, filename)
const program = ts.createProgram([fixture], {
noEmit: true,
strictNullChecks: true,
skipLibCheck: true,
esModuleInterop: true,
target: ts.ScriptTarget.ES2020,
module: ts.ModuleKind.CommonJS,
types: [],
})
const source = program.getSourceFile(fixture)!
const diagnostics = [
...program.getSyntacticDiagnostics(source),
...program.getSemanticDiagnostics(source),
]
expect(diagnostics.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([])
})
39 changes: 39 additions & 0 deletions packages/taro-h5/__tests__/canvas/offscreen.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import Taro from '@tarojs/taro'

import { createOffscreenCanvas } from '../../src/index'

declare function acceptContext(context: Taro.RenderingContext): void
declare function acceptHandler(handler: (...args: any[]) => any): void
declare const ordinaryCanvas: Taro.Canvas

const miniCanvas = Taro.createOffscreenCanvas({ type: '2d', width: 300, height: 150 })
acceptContext(miniCanvas.getContext('2d'))
acceptHandler(miniCanvas.createImage().onload)
acceptHandler(miniCanvas.createImage().onerror)
acceptHandler(ordinaryCanvas.createImage().onload)
acceptHandler(ordinaryCanvas.createImage().onerror)

export async function drawImage (url: string) {
const canvas = createOffscreenCanvas({ type: '2d', width: 300, height: 150 })
const context = canvas.getContext('2d')
// @ts-expect-error H5 callers must check for an unavailable context.
context.clearRect(0, 0, 300, 150)
if (!context) throw new Error('2D context is unavailable')

const image = canvas.createImage()
const initialOnload: typeof image.onload = null
const initialOnerror: typeof image.onerror = null
image.onload = initialOnload
image.onerror = initialOnerror
await new Promise<void>((resolve, reject) => {
image.onload = () => resolve()
image.onerror = reject
image.src = url
})
context.clearRect(0, 0, 300, 150)
context.drawImage(image, 0, 0)
return context.getImageData(0, 0, 300, 150)
}

const gl = createOffscreenCanvas({ type: 'webgl' }).getContext('webgl')
if (gl) gl.clear(gl.COLOR_BUFFER_BIT)
25 changes: 25 additions & 0 deletions packages/taro-h5/integration/canvas/offscreen.harmony.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Taro from '@tarojs/api'

import { loadHarmonyApi } from '../helpers/loadHarmonyApi'

afterEach(() => jest.restoreAllMocks())

it('keeps the Harmony Hybrid createOffscreenCanvas placeholder at the public entry', async () => {
jest.replaceProperty(process.env, 'NODE_ENV', 'production')
jest.spyOn(console, 'warn').mockImplementation(() => {})
const createElement = jest.spyOn(document, 'createElement')
const unsupported = jest.fn()
const createOffscreenCanvas = await loadHarmonyApi('createOffscreenCanvas')
const options = { type: '2d' as const, width: 20, height: 10 }

Taro.eventCenter.on('__taroNotSupport', unsupported)
try {
await expect(createOffscreenCanvas(options)).resolves.toEqual({ errMsg: '暂时不支持 API' })
expect(unsupported).toHaveBeenCalledWith({
name: 'createOffscreenCanvas', args: [options], type: 'method', category: 'temporarily',
})
expect(createElement).not.toHaveBeenCalled()
} finally {
Taro.eventCenter.off('__taroNotSupport', unsupported)
}
})
34 changes: 34 additions & 0 deletions packages/taro-h5/integration/helpers/loadHarmonyApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { existsSync } from 'node:fs'
import { isAbsolute, resolve } from 'node:path'
import { runInNewContext } from 'node:vm'

import { rollup } from 'rollup'

import type Taro from '@tarojs/api'

/** Import a named API from the generated public entry through a real Rollup consumer. */
export async function loadHarmonyApi<K extends keyof typeof Taro> (name: K): Promise<(typeof Taro)[K]> {
const publicApi = resolve(__dirname, '../../../taro-platform-harmony-hybrid/dist/api/index.js')
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (!existsSync(publicApi)) {
throw new Error('Build Harmony Hybrid first, or run pnpm --filter @tarojs/taro-h5 test:integration')
}
const consumer = '\0harmony-api-consumer'
const bundle = await rollup({
input: consumer,
external: (id, importer) => !!importer && !id.startsWith('.') && !isAbsolute(id),
treeshake: { moduleSideEffects: false },
plugins: [{
name: 'harmony-api-consumer',
resolveId: id => id === consumer ? id : null,
load: id => id === consumer ? `export { ${String(name)} } from ${JSON.stringify(publicApi)}` : null,
}],
})
const exports: Pick<typeof Taro, K> = Object.create(null)
try {
const { output } = await bundle.generate({ format: 'cjs', exports: 'named', interop: 'auto' })
runInNewContext(output[0].code, { exports, require, process, console, document, window })
return exports[name]
} finally {
await bundle.close()
}
}
1 change: 1 addition & 0 deletions packages/taro-h5/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"rollup": "rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript --bundleConfigAsCjs",
"test": "jest",
"test:ci": "jest --ci -i --coverage --silent",
"test:integration": "pnpm run build && pnpm --filter @tarojs/plugin-platform-harmony-hybrid run build && jest --ci -i --testMatch \"**/integration/**/*.test.ts\"",
"test:dev": "jest --watch",
"test:coverage": "jest --coverage"
},
Expand Down
49 changes: 49 additions & 0 deletions packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import Taro from '@tarojs/api'

import type { H5OffscreenCanvas } from '../../../types/canvas'

export type { H5OffscreenCanvas } from '../../../types/canvas'

type ContextType = '2d' | 'webgl'
type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D

export const createOffscreenCanvas = ({
type = 'webgl',
width = 300,
height = 150,
}: Taro.createOffscreenCanvas.Option = {}): H5OffscreenCanvas => {
if (type !== '2d' && type !== 'webgl') {
throw new TypeError('createOffscreenCanvas: expected type to be 2d or webgl')
}

const hasNativeCanvas = typeof OffscreenCanvas === 'function'
let canvas = hasNativeCanvas
? new OffscreenCanvas(width, height)
: document.createElement('canvas')
canvas.width = width
canvas.height = height

if (hasNativeCanvas &&
!(type === '2d' ? canvas.getContext('2d') : canvas.getContext('webgl'))) {
canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
}

function getContext (contextType: '2d'): Context2D | null
function getContext (contextType: 'webgl'): WebGLRenderingContext | null
function getContext (contextType: ContextType): Context2D | WebGLRenderingContext | null
function getContext (contextType: ContextType) {
if (contextType !== type) return null
return contextType === '2d' ? canvas.getContext('2d') : canvas.getContext('webgl')
}

return {
get width () { return canvas.width },
set width (value) { canvas.width = value },
get height () { return canvas.height },
set height (value) { canvas.height = value },
createImage: () => new Image(),
getContext,
}
}
4 changes: 1 addition & 3 deletions packages/taro-h5/src/api/canvas/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { temporarilyNotSupport } from '../../utils'

// 画布

/** 创建离屏 canvas 实例 */
export const createOffscreenCanvas = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas')
export * from './createOffscreenCanvas'

/** 创建 canvas 的绘图上下文 CanvasContext 对象 */
export * from './createCanvasContext'
Expand Down
9 changes: 9 additions & 0 deletions packages/taro-h5/types/canvas.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/** Browser-backed offscreen canvas. A requested context can be unavailable. */
export interface H5OffscreenCanvas {
width: number
height: number
createImage(): HTMLImageElement
getContext(contextType: '2d'): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null
getContext(contextType: 'webgl'): WebGLRenderingContext | null
getContext(contextType: '2d' | 'webgl'): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | WebGLRenderingContext | null
}
10 changes: 10 additions & 0 deletions packages/taro-h5/types/h5.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import Taro from '@tarojs/taro'

import type { H5OffscreenCanvas } from './canvas'

/** Opt in through the H5 tsconfig's types or a triple-slash reference. */
declare module '@tarojs/taro' {
interface TaroStatic {
createOffscreenCanvas(options: Taro.createOffscreenCanvas.Option): H5OffscreenCanvas
}
}
Loading
Loading