diff --git a/scripts/build-harmony-genui-runtime.mjs b/scripts/build-harmony-genui-runtime.mjs index c253382..27f7860 100644 --- a/scripts/build-harmony-genui-runtime.mjs +++ b/scripts/build-harmony-genui-runtime.mjs @@ -30,7 +30,7 @@ const HTML = ` - + Local GenUI diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets index bc304a3..ea6b5a0 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets @@ -23,10 +23,16 @@ struct AppRoot { if (!hostContext) { throw new Error('App root host context is unavailable.'); } - this.showStartupBrand = StartupRevealPreference.claim(hostContext); this.hostAdapter.attach(hostContext, this.getUIContext()); - const firstLaunch = this.showStartupBrand; - const coldStartCandidate = ColdStartPresentationState.claimProcess() && !firstLaunch; + // A cold shortcut is delivered synchronously on subscription. A warm one can + // arrive while a reveal is running or while account restoration is pending. + this.runtime.subscribeToDesktopLaunch(() => { + this.coldStartConsumed = true; + this.showStartupBrand = false; + this.showColdStart = false; + }); + this.showStartupBrand = !this.coldStartConsumed && StartupRevealPreference.claim(hostContext); + const coldStartCandidate = !this.coldStartConsumed && ColdStartPresentationState.claimProcess() && !this.showStartupBrand; await this.runtime.aboutToAppear((signedIn: boolean): void => { if (!this.coldStartConsumed) { this.coldStartConsumed = true; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/LocalGenUIWebSurface.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/LocalGenUIWebSurface.ets index 6b11f33..b890f52 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/LocalGenUIWebSurface.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/LocalGenUIWebSurface.ets @@ -6,16 +6,12 @@ import { LocalGenUIRuntimeBridge } from '../../services/local-genui/LocalGenUIRu import { LOCAL_GENUI_ICON3D_ROOT } from '../../services/local-genui/LocalGenUIIcon3DStore'; import { LOCAL_GENUI_PHOTO_ROOT } from '../../services/local-genui/LocalGenUIImageSearch'; import { LOCAL_GENUI_COLLABORATION_ROOT } from '../../services/local-genui/LocalGenUICollaborationAssets'; +import { HTML_SANDBOX_URL, htmlSandboxResponse } from '../../services/local-genui/LocalGenUIHtmlSandbox'; import { RemoteLogger } from '../../services/RemoteLogger'; const LOCAL_GENUI_WEB_ID: string = 'local-genui-runtime-web'; -/** ArkWeb javaScriptProxy object. Every message is untrusted input. */ -class LocalGenUINativeChannel { - private readonly dispatch: (raw: string) => void; - constructor(dispatch: (raw: string) => void) { this.dispatch = dispatch; } - post(raw: string): void { this.dispatch(raw); } -} +const RUNTIME_URL: string = 'resource://rawfile/genui/runtime/index.html'; /** * Platform leaf for the Local GenUI runtime. It owns only the WebView @@ -31,9 +27,19 @@ export struct LocalGenUIWebSurface { private alive: boolean = true; // Offline documents repeat the same blocked-resource warning on every render. private loggedConsole: Set = new Set(); - private channel: LocalGenUINativeChannel = new LocalGenUINativeChannel((raw: string): void => { - if (this.alive) this.bridge.receive(raw); - }); + private port?: webview.WebMessagePort; + + private connectRuntime(url: string): void { + if (!this.alive || url !== RUNTIME_URL || this.controller.getUrl() !== RUNTIME_URL) return; + this.port?.close(); + const ports = this.controller.createWebMessagePorts(); + this.port = ports[0]; + this.port.onMessageEvent((data: webview.WebMessage): void => { + if (this.alive && typeof data === 'string') this.bridge.receive(data); + }); + // postMessage targets the main document. No JavaScript proxy is injected into frames. + this.controller.postMessage('local-genui-port', [ports[1]], '*'); + } aboutToAppear(): void { if (BuildProfile.DEBUG) { @@ -45,6 +51,8 @@ export struct LocalGenUIWebSurface { aboutToDisappear(): void { this.alive = false; + this.port?.close(); + this.port = undefined; this.bridge.detach(); } @@ -100,15 +108,15 @@ export struct LocalGenUIWebSurface { .darkMode(WebDarkMode.Off) .forceDarkAccess(false) .overScrollMode(OverScrollMode.NEVER) - .javaScriptProxy({ object: this.channel, name: 'genuiNative', methodList: ['post'], controller: this.controller }) + .onPageEnd((event) => { if (event) this.connectRuntime(event.url); }) .onControllerAttached(() => { this.bridge.attach((json: string): void => this.send(json)); this.bridge.attachSnapshot((): Promise => this.capture()); }) .onInterceptRequest((event: OnInterceptRequestEvent): WebResourceResponse | null => { - // Host-served 3D pictures; nothing else is intercepted. Answers are - // asynchronous: the picture may need one download before the cache has it. + // Both the sandbox document and host-served images are answered locally. const url = event.request.getRequestUrl(); + if (!event.request.isMainFrame() && url === HTML_SANDBOX_URL) return htmlSandboxResponse(); const collaborationImage = url.startsWith(LOCAL_GENUI_COLLABORATION_ROOT); const photo = url.startsWith(LOCAL_GENUI_PHOTO_ROOT); if (!url.startsWith(LOCAL_GENUI_ICON3D_ROOT) && !collaborationImage && !photo) { @@ -140,7 +148,7 @@ export struct LocalGenUIWebSurface { }) .onOverrideUrlLoading((request: WebResourceRequest) => { // The runtime never navigates. Generated content cannot open pages. - return request.getRequestUrl().indexOf('genui/runtime/index.html') < 0; + return request.isMainFrame() ? request.getRequestUrl() !== RUNTIME_URL : request.getRequestUrl() !== HTML_SANDBOX_URL; }) .onConsole((event) => { if (event && event.message.getMessageLevel() === MessageLevel.Error) { diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppGallery.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppGallery.ets index 9013655..9168c91 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppGallery.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppGallery.ets @@ -32,7 +32,7 @@ export struct MiniAppGallery { private originX: number = 0; private originY: number = 0; - private pinning: boolean = false; + @Local pinning: boolean = false; build() { Stack({ alignContent: Alignment.TopStart }) { @@ -71,10 +71,8 @@ export struct MiniAppGallery { .borderRadius(4).backgroundColor(index === this.currentIndex() ? INK : SUBTLE) .opacity(index === this.currentIndex() ? 1 : 0.4) }, (app: MiniAppGalleryItem): string => app.id) - }.justifyContent(FlexAlign.Center).padding({ top: 20, bottom: 12 }) + }.justifyContent(FlexAlign.Center).padding({ top: 20, bottom: this.bottomInset + 16 }) .opacity(this.state.drag.active ? 0 : 1).accessibilityLevel('no') - Text(RemoteI18n.t('miniapp.shortcutHint')).fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(SUBTLE).margin({ bottom: this.bottomInset + 16 }).opacity(this.state.drag.active ? 0 : 1) } }.width('100%').height('100%') diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntime.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntime.ets index edd1567..eb39e1c 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntime.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntime.ets @@ -42,16 +42,20 @@ export class AppRootRuntime extends AppRootRuntimeComposition { super(host); } - async aboutToAppear(onAccountRestored?: (signedIn: boolean) => void): Promise { + subscribeToDesktopLaunch(onLaunch: () => void): void { // A generated app opened from its home-screen card is local: it does not // wait for account, device, or remote restoration below. LocalGenUILaunchInbox.subscribe((appId: string): void => { + onLaunch(); if (BUILTIN_MINIAPP_IDS.includes(appId)) { void this.miniAppViewModel.openShortcut(appId); } else { void this.localGenUIViewModel.openGalleryApp(appId); } }); + } + + async aboutToAppear(onAccountRestored?: (signedIn: boolean) => void): Promise { // Account login can be tapped while the rest of the cold-start work is // still running. Initialize its secure store first so the login path never // races the asynchronous cache and onboarding setup below. diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountSessionStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountSessionStore.ets index 98e8cfa..757314a 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountSessionStore.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountSessionStore.ets @@ -1,4 +1,5 @@ import { GitHubAccountProfile, readCachedGitHubProfile } from './GitHubAccountProfile'; +import { BusinessError } from '@kit.BasicServicesKit'; import { huks } from '@kit.UniversalKeystoreKit'; import { preferences } from '@kit.ArkData'; import { Encoding } from './Encoding'; @@ -11,6 +12,16 @@ const CIPHER_KEY: string = 'github_device_session_v1_cipher'; const IV_KEY: string = 'github_device_session_v1_iv'; const HUKS_ALIAS: string = HarmonyUpgradeIdentityContract.CLOUD_ACCOUNT_HUKS_ALIAS; +const DEVICE_CIPHER_KEY: string = 'device_private_key_v1_cipher'; +const DEVICE_IV_KEY: string = 'device_private_key_v1_iv'; +const GENERATION_KEY: string = 'active_key_generation'; + +class MissingAccountKeyError extends Error {} + +function recordKey(key: string, generation: number): string { + return generation === 0 ? key : `g${generation}_${key}`; +} + export interface PersistedCloudAccountSession { relayUrl: string; username: string; @@ -32,11 +43,18 @@ export interface PersistedWatchProvisionIdentity { /** Persists only an HUKS-encrypted account session, never plaintext secrets. */ export class CloudAccountSessionStore { private store?: preferences.Preferences; + private generation: number = 0; private deviceKeyWork?: Promise; async init(context: Context): Promise { try { - this.store = await preferences.getPreferences(context, STORE_NAME); + const store = await preferences.getPreferences(context, STORE_NAME); + const generation = await store.get(GENERATION_KEY, 0); + if (typeof generation !== 'number' || !Number.isSafeInteger(generation) || generation < 0) { + throw new Error('Invalid cloud account key generation.'); + } + this.generation = generation; + this.store = store; } catch (err) { throw OhosError.wrap('cloud account session init', err); } @@ -49,17 +67,36 @@ export class CloudAccountSessionStore { } private async loadOrCreateDeviceSecret(): Promise { - const value = await this.readSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv'); + let value: string | undefined; + let previous: PersistedCloudAccountSession | undefined; + try { + value = await this.readSealed(DEVICE_CIPHER_KEY, DEVICE_IV_KEY); + if (!value) previous = await this.load(); + } catch (err) { + if (!(err instanceof MissingAccountKeyError) || await this.keyItemExists()) { + throw OhosError.wrap('device identity read', err); + } + // Only explicit sign-in calls deviceSecret(). Preserve every record from + // the previous generation, including its session and watch identities. + const next = this.generation + 1; + const secret = Encoding.randomBytes(32); + await this.writeSealed(DEVICE_CIPHER_KEY, DEVICE_IV_KEY, Encoding.bytesToBase64(secret), next); + const store = this.requireStore(); + await store.put(GENERATION_KEY, next); + await store.flush(); + this.generation = next; + RemoteLogger.warn('Cloud account sign-in created a new device identity after confirming the previous key is missing'); + return secret; + } if (value) { const secret = Encoding.base64ToBytes(value); if (secret.length !== 32) throw new Error('Stored device identity is invalid.'); return secret; } - const previous = await this.load(); const secret = previous ? Encoding.base64ToBytes(previous.masterKey) : Encoding.randomBytes(32); if (secret.length !== 32) throw new Error('Stored device identity is invalid.'); try { - await this.writeSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv', Encoding.bytesToBase64(secret)); + await this.writeSealed(DEVICE_CIPHER_KEY, DEVICE_IV_KEY, Encoding.bytesToBase64(secret)); } catch (err) { // A reinstall clears Preferences but HarmonyOS may retain the HUKS alias. // Only rotate the alias when there is no prior session record: existing @@ -67,14 +104,14 @@ export class CloudAccountSessionStore { if (previous) throw err instanceof Error ? err : new Error(OhosError.reason(err)); RemoteLogger.warn('cloud account device identity write failed on fresh install; recreating local key'); await this.recreateKeyForFreshInstall(); - await this.writeSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv', Encoding.bytesToBase64(secret)); + await this.writeSealed(DEVICE_CIPHER_KEY, DEVICE_IV_KEY, Encoding.bytesToBase64(secret)); } return secret; } private async recreateKeyForFreshInstall(): Promise { try { - await huks.deleteKeyItem(HUKS_ALIAS, {}); + await huks.deleteKeyItem(recordKey(HUKS_ALIAS, this.generation), {}); } catch (err) { const message = OhosError.reason(err); if (message.indexOf('12000011') < 0 && message.indexOf('-13') < 0 && @@ -120,13 +157,14 @@ export class CloudAccountSessionStore { return `watch_provision_v1_${encodeURIComponent(relayUrl)}_${encodeURIComponent(userId)}_${deviceId}`; } - private async writeSealed(cipherKey: string, ivKey: string, plaintext: string): Promise { + private async writeSealed(cipherKey: string, ivKey: string, plaintext: string, + generation: number = this.generation): Promise { try { const store = this.requireStore(); - await this.ensureKey(); + await this.ensureKey(generation); const iv = Encoding.randomBytes(16); const options = this.options(huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, iv); - const handle = await huks.initSession(HUKS_ALIAS, options); + const handle = await huks.initSession(recordKey(HUKS_ALIAS, generation), options); const encrypted = await huks.finishSession(handle.handle, { properties: options.properties, inData: Encoding.utf8ToBytes(plaintext) @@ -134,8 +172,8 @@ export class CloudAccountSessionStore { if (!encrypted.outData || encrypted.outData.length === 0) { throw new Error('Cloud account session encryption failed.'); } - await store.put(cipherKey, Encoding.bytesToBase64(encrypted.outData)); - await store.put(ivKey, Encoding.bytesToBase64(iv)); + await store.put(recordKey(cipherKey, generation), Encoding.bytesToBase64(encrypted.outData)); + await store.put(recordKey(ivKey, generation), Encoding.bytesToBase64(iv)); await store.flush(); } catch (err) { throw OhosError.wrap('cloud account session save', err); @@ -150,14 +188,23 @@ export class CloudAccountSessionStore { private async readSealed(cipherKey: string, ivKey: string): Promise { try { const store = this.requireStore(); - const cipher = await store.get(cipherKey, ''); - const ivText = await store.get(ivKey, ''); + const generation = this.generation; + const cipher = await store.get(recordKey(cipherKey, generation), ''); + const ivText = await store.get(recordKey(ivKey, generation), ''); if (typeof cipher !== 'string' || typeof ivText !== 'string' || cipher.length === 0 || ivText.length === 0) { return undefined; } const iv = Encoding.base64ToBytes(ivText); const options = this.options(huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, iv); - const handle = await huks.initSession(HUKS_ALIAS, options); + let handle: huks.HuksSessionHandle; + try { + handle = await huks.initSession(recordKey(HUKS_ALIAS, generation), options); + } catch (err) { + if ((err as BusinessError).code === huks.HuksExceptionErrCode.HUKS_ERR_CODE_ITEM_NOT_EXIST) { + throw new MissingAccountKeyError('The key for the saved cloud account is missing.'); + } + throw OhosError.wrap('cloud account decrypt init', err); + } const decrypted = await huks.finishSession(handle.handle, { properties: options.properties, inData: Encoding.base64ToBytes(cipher) @@ -174,20 +221,21 @@ export class CloudAccountSessionStore { async clear(): Promise { try { const store = this.requireStore(); - await store.delete(CIPHER_KEY); - await store.delete(IV_KEY); + const generation = this.generation; + await store.delete(recordKey(CIPHER_KEY, generation)); + await store.delete(recordKey(IV_KEY, generation)); await store.flush(); } catch (err) { throw OhosError.wrap('cloud account session clear', err); } } - private async ensureKey(): Promise { - if (await this.keyItemExists()) { + private async ensureKey(generation: number = this.generation): Promise { + if (await this.keyItemExists(generation)) { return; } try { - await huks.generateKeyItem(HUKS_ALIAS, { + await huks.generateKeyItem(recordKey(HUKS_ALIAS, generation), { properties: [ { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES }, { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }, @@ -201,16 +249,12 @@ export class CloudAccountSessionStore { } } - private async keyItemExists(): Promise { + private async keyItemExists(generation: number = this.generation): Promise { try { - return await huks.isKeyItemExist(HUKS_ALIAS, {}); + return await huks.isKeyItemExist(recordKey(HUKS_ALIAS, generation), {}); } catch (err) { - const message = err instanceof Error ? err.message : JSON.stringify(err); - if (message.indexOf('12000011') >= 0 || message.indexOf('-13') >= 0 || - message.toLowerCase().indexOf('does not exist') >= 0) { - return false; - } - throw new Error(message || 'HUKS key lookup failed.'); + if ((err as BusinessError).code === huks.HuksExceptionErrCode.HUKS_ERR_CODE_ITEM_NOT_EXIST) return false; + throw OhosError.wrap('cloud account key lookup', err); } } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MiniAppShortcut.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MiniAppShortcut.ets index c8c4312..6052f18 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MiniAppShortcut.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MiniAppShortcut.ets @@ -1,3 +1,4 @@ +import { DeviceApiLevelService } from './DeviceApiLevelService'; import { RemoteLogger } from './RemoteLogger'; import { common, Want } from '@kit.AbilityKit'; import { productViewManager } from '@kit.AppGalleryKit'; @@ -40,15 +41,62 @@ export class MiniAppShortcut { const result = await productViewManager.checkPinShortcutPermitted(context, id, want, title.slice(0, 255), path, ''); if (result.code !== 0 || !result.tid) return result.code || -1; - await productViewManager.requestNewPinShortcut(context, result.tid); if (revealDesktop) { - // Pinning has already succeeded if returning to the launcher is interrupted. - try { await context.moveAbilityToBackground(); } - catch (error) { RemoteLogger.warn('Unable to background mini app after pin: ' + String(error)); } + await MiniAppShortcut.pinAndReveal(context, id, result.tid); + } else { + await productViewManager.requestNewPinShortcut(context, result.tid); } return 0; } finally { if (fs.accessSync(path)) fs.unlinkSync(path); } } + + private static async containsShortcut(id: string): Promise { + const shortcuts = await productViewManager.getPinShortcutInfos(); + return shortcuts.some((shortcut: productViewManager.PinShortcutInfo) => shortcut.shortcutId === id); + } + + private static async pinAndReveal(context: common.UIAbilityContext, id: string, tid: string): Promise { + let watch = false; + if (DeviceApiLevelService.sdkApiVersion() >= 24) { + try { watch = !(await MiniAppShortcut.containsShortcut(id)); } + catch (error) { RemoteLogger.warn('Shortcut query unavailable: ' + String(error)); } + } + let settled = false; + let moved: Promise | undefined; + const reveal = (): Promise => { + if (!moved) { + moved = context.moveAbilityToBackground().catch((error: Error) => { + moved = undefined; + RemoteLogger.warn('Unable to background mini app after pin: ' + String(error)); + }); + } + return moved; + }; + const observe = async (): Promise => { + while (!settled) { + await new Promise((resolve) => setTimeout(resolve, 250)); + if (settled) return; + const present = await MiniAppShortcut.containsShortcut(id); + if (settled) return; + if (present) { + RemoteLogger.info('Newly pinned shortcut visible before confirmation callback'); + await reveal(); + return; + } + } + }; + const confirmation = productViewManager.requestNewPinShortcut(context, tid); + if (watch) { + void observe().catch((error: Error) => RemoteLogger.warn('Shortcut observation stopped: ' + String(error))); + } + try { + await confirmation; + RemoteLogger.info('Shortcut confirmation completed'); + } finally { + settled = true; + } + await reveal(); + } } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/local-genui/LocalGenUIHtmlSandbox.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/local-genui/LocalGenUIHtmlSandbox.ets new file mode 100644 index 0000000..ea82311 --- /dev/null +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/local-genui/LocalGenUIHtmlSandbox.ets @@ -0,0 +1,20 @@ +// A locally answered document with its own response policy. The parent keeps +// its rawfile script policy; only this opaque, offline frame runs authored JS. +export const HTML_SANDBOX_URL: string = 'https://genui-sandbox.openbitfun.invalid/view'; +const POLICY: string = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; " + + "style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data:; " + + "connect-src 'none'; frame-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'"; +export function htmlSandboxResponse(): WebResourceResponse { + const response = new WebResourceResponse(); + response.setResponseHeader([ + { headerKey: 'Content-Security-Policy', headerValue: POLICY }, + { headerKey: 'Cache-Control', headerValue: 'no-store' }, + { headerKey: 'Referrer-Policy', headerValue: 'no-referrer' } + ]); + response.setResponseMimeType('text/html'); + response.setResponseEncoding('utf-8'); + response.setResponseCode(200); + response.setReasonMessage('OK'); + response.setResponseData($rawfile('genui/html-view.html')); + return response; +} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/local-genui/LocalGenUIRuntimeBridge.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/local-genui/LocalGenUIRuntimeBridge.ets index 9c289e7..ba40b7c 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/local-genui/LocalGenUIRuntimeBridge.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/local-genui/LocalGenUIRuntimeBridge.ets @@ -134,7 +134,7 @@ export class LocalGenUIRuntimeBridge { return this.mount; } - /** Raw string from the `genuiNative.post` proxy. Treated as untrusted. */ + /** Raw string from the main document message port. Treated as untrusted. */ receive(raw: string): void { let message: LocalRuntimeInbound; try { diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json b/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json index 2111aeb..8e3f501 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json +++ b/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json @@ -10,7 +10,7 @@ }, { "name": "miniapp_releaseShortcut", - "value": "松开以添加桌面图标" + "value": "松手后确认添加" }, { "name": "miniapp_pinned", @@ -34,7 +34,7 @@ }, { "name": "miniapp_pinIcon", - "value": "添加桌面图标" + "value": "添加到桌面" }, { "name": "settings_genui_look", diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json b/src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json index 11372f5..9144efd 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json +++ b/src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json @@ -10,7 +10,7 @@ }, { "name": "miniapp_releaseShortcut", - "value": "Release to add a home screen icon" + "value": "Release to confirm" }, { "name": "miniapp_pinned", @@ -34,7 +34,7 @@ }, { "name": "miniapp_pinIcon", - "value": "Add home screen icon" + "value": "Add to home screen" }, { "name": "settings_genui_look", diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/rawfile/genui/html-view.html b/src/apps/mobile/harmonyos/entry/src/main/resources/rawfile/genui/html-view.html new file mode 100644 index 0000000..5c21827 --- /dev/null +++ b/src/apps/mobile/harmonyos/entry/src/main/resources/rawfile/genui/html-view.html @@ -0,0 +1,10 @@ + diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json b/src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json index 37cc196..c4c35c0 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json +++ b/src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json @@ -10,7 +10,7 @@ }, { "name": "miniapp_releaseShortcut", - "value": "松开以添加桌面图标" + "value": "松手后确认添加" }, { "name": "miniapp_pinned", @@ -34,7 +34,7 @@ }, { "name": "miniapp_pinIcon", - "value": "添加桌面图标" + "value": "添加到桌面" }, { "name": "settings_genui_look", diff --git a/src/apps/mobile/harmonyos/genui-runtime/src/components/HtmlSandboxFrame.tsx b/src/apps/mobile/harmonyos/genui-runtime/src/components/HtmlSandboxFrame.tsx new file mode 100644 index 0000000..93f6f56 --- /dev/null +++ b/src/apps/mobile/harmonyos/genui-runtime/src/components/HtmlSandboxFrame.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { useEffect, useMemo, useRef } from "react"; +import { useColorScheme } from "./openui/scheme"; + +// ArkWeb serves this URL locally. Its response policy applies to the whole +// authored document, independently of the stricter parent rawfile policy. +const SANDBOX_URL = "https://genui-sandbox.openbitfun.invalid/view"; +const REPORTER = ``; + +function documentFor(html: string, scheme: "light" | "dark") { + return `${REPORTER}${html}`; +} + +export function HtmlSandboxFrame({ html, height, title }: { html: string; height: number; title: string }) { + const frame = useRef(null); + const scheme = useColorScheme(frame); + const srcDoc = useMemo(() => documentFor(html, scheme), [html, scheme]); + + useEffect(() => { + const onMessage = (event: MessageEvent) => { + const iframe = frame.current; + if (!iframe || event.source !== iframe.contentWindow || event.origin !== "null") return; + const data = event.data; + if (data?.type === "html-view-error") { + iframe.dataset.htmlViewStatus = "error"; + iframe.dataset.htmlViewError = String(data.message || "Script error").slice(0, 200); + } else if (data?.type === "html-view-loaded" && iframe.dataset.htmlViewStatus !== "error") { + iframe.dataset.htmlViewStatus = "ready"; + } + }; + window.addEventListener("message", onMessage); + return () => window.removeEventListener("message", onMessage); + }, []); + + return ( +