前端 uni-app 重写: 9页面 H5

This commit is contained in:
zhiqui
2026-11-15 15:09:37 +08:00
parent 513b53672e
commit ea7c2529e9
24104 changed files with 3667749 additions and 0 deletions
@@ -0,0 +1,33 @@
<script setup>
let firstBackTime = 0
onLaunch(() => {
console.log('App Launch')
})
onAppShow(() => {
console.log('App Show')
})
onAppHide(() => {
console.log('App Hide')
})
// #ifdef APP-ANDROID
onLastPageBackPress(() => {
console.log('App LastPageBackPress')
if (firstBackTime == 0) {
uni.showToast({
title: '再按一次退出应用',
position: 'bottom',
})
firstBackTime = Date.now()
setTimeout(() => {
firstBackTime = 0
}, 2000)
} else if (Date.now() - firstBackTime < 2000) {
firstBackTime = Date.now()
uni.exit()
}
})
// #endif
onExit(() => {
console.log('App Exit')
})
</script>
@@ -0,0 +1,9 @@
import App from './App.uvue'
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
@@ -0,0 +1,11 @@
{
"name" : "NAME",
"appid" : "APPID",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : "100",
"uni-app-x" : {},
"app" : {
"defaultAppTheme": "auto"
}
}
@@ -0,0 +1,14 @@
{
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app x"
}
}
],
"globalStyle": {
"navigationStyle": "custom",
"pageOrientation": "auto"
}
}
@@ -0,0 +1,120 @@
<template>
<web-view
ref="webviewElement"
id="webview"
style="flex: 1;"
:webview-styles="webviewStyles"
<!-- #ifdef APP-ANDROID -->
android-layer-type="software"
@load="onWebviewLoad"
<!-- #endif -->
:src="src"
@message="message"
@error="error"
/>
</template>
<script setup lang='uts'>
// #ifdef APP-IOS || APP-ANDROID
import { applyWebViewSnapshotTextMetricsPatch } from '@/tools/webview-snapshot-text-metrics.uts'
// #endif
// #ifdef APP-ANDROID
import { applyAndroidWebViewSafeArea } from '@/tools/android-webview-safe-area.uts'
// #endif
const instance = getCurrentInstance()!.proxy!
const src = ref(process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC)
const webviewElement = ref<UniWebViewElement | null>(null)
const webviewContext = ref<WebViewContext | null>(null)
const webviewStyles = ref({
progress: false
})
const safeAreaTop = ref(0)
// #ifdef APP-ANDROID
const onWebviewLoad = () => {
applyAndroidWebViewSafeArea(webviewContext.value)
}
onPageShow(() => {
UniWebViewElement.enableWholeDraw()
})
// #endif
onReady(() => {
const windowInfo = uni.getWindowInfo()
safeAreaTop.value = windowInfo.safeAreaInsets.top
webviewContext.value = uni.createWebViewContext('webview')
})
const initAutomator = () => {
const options = {
wsEndpoint: process.env.UNI_AUTOMATOR_WS_ENDPOINT
}
webviewContext.value!.evalJS(`initRuntimeAutomator(${JSON.stringify(options)})`)
// #ifdef APP-IOS || APP-ANDROID
applyWebViewSnapshotTextMetricsPatch(webviewContext.value)
// #endif
console.log('initRuntimeAutomator...')
}
const callback = (id : number, res : any | null, error : string) => {
webviewContext.value!.evalJS(`onPostMessageFromUniXWebView(${id},${JSON.stringify(res)},${JSON.stringify(error)})`)
}
const message = (msg: UniWebViewMessageEvent) => {
// #ifdef APP
const data = msg.detail.data[0];
const id = data["id"] as number
const type = data["type"] as string
const dataObj = data["data"] as UTSJSONObject
const action = dataObj["action"]!
const args = dataObj["args"]
// #endif
// #ifdef WEB || MP
const data = msg.detail.data.length ? msg.detail.data[0].data : msg.detail.data
const id = data["id"] as number
const type = data["type"] as string
const dataObj = data["data"]
const action = dataObj["action"]!
const args = dataObj["args"]
// #endif
if (type != 'automator') {
return;
}
if (action == 'ready') {
initAutomator()
} else {
console.log(id, action, args)
if (action == 'captureScreenshot') {
// 调用截图
(instance as Page).$viewToTempFilePath({
id: 'webview',
offsetY: `${safeAreaTop.value + 44}`,
overwrite: true,
wholeContent: true,
success: (res) => {
const fileManager = uni.getFileSystemManager()
fileManager.readFile({
encoding: 'base64',
filePath: res.tempFilePath,
success: (readFileRes) => {
callback(id, { data: readFileRes.data }, '')
},
fail: (error) => {
callback(id, '', error.errMsg)
},
} as ReadFileOptions)
},
fail: (res) => {
callback(id, '', res.errMsg)
}
})
}
}
}
const error = (event : WebViewErrorEvent) => {
console.log('webview load error', JSON.stringify(event.detail));
}
</script>
@@ -0,0 +1,110 @@
function getAndroidStatusBarHeight(): number {
const windowInfo = uni.getWindowInfo()
return windowInfo.statusBarHeight
}
function createStatusBarPlaceholderScript(height: number): string {
return `
(function(){
var height=${height};
var id='uni-app-x-android-pad-statusbar-placeholder';
var maxAttempts=60;
var attempts=0;
var observer=null;
var observedBody=null;
function shouldInsert(){
var pageHead=document.querySelector('.uni-page-head');
if(!pageHead){
// navigationStyle: "custom" does not render a uni-page-head.
return true;
}
if(!pageHead.getBoundingClientRect){
return false;
}
// Pixel XL pageHead 高度为 44.000xxx,故判断小于45
return pageHead.getBoundingClientRect().height<45;
}
function apply(){
if(height<=0||document.body==null){
return false;
}
var body=document.body;
var spacer=document.getElementById(id);
if(!shouldInsert()){
if(spacer!=null&&spacer.parentNode!=null){
spacer.parentNode.removeChild(spacer);
}
return false;
}
if(spacer==null){
spacer=document.createElement('div');
spacer.id=id;
spacer.setAttribute('aria-hidden','true');
}
spacer.style.height=height+'px';
spacer.style.minHeight=height+'px';
spacer.style.width='100%';
spacer.style.display='block';
spacer.style.flexShrink='0';
spacer.style.pointerEvents='none';
spacer.style.background='transparent';
if(body.firstChild!==spacer){
body.insertBefore(spacer,body.firstChild);
}
return true;
}
function observeBody(){
if(document.body==null||typeof MutationObserver!='function'){
return;
}
if(observedBody===document.body){
return;
}
if(observer!=null){
observer.disconnect();
}
observedBody=document.body;
observer=new MutationObserver(function(){
var body=document.body;
var spacer=document.getElementById(id);
if(body==null||spacer==null||spacer.parentNode!==body||body.firstChild!==spacer){
apply();
}
});
observer.observe(observedBody,{childList:true});
}
function retry(){
apply();
observeBody();
attempts+=1;
if(attempts<maxAttempts){
setTimeout(retry,100);
}
}
if(document.readyState=='loading'){
document.addEventListener('DOMContentLoaded',retry);
}
setTimeout(retry,0);
})();
`
}
export function insertStatusBarPlaceholder(webview: WebViewContext | null): void {
if (webview == null) return
const webviewContext = webview as WebViewContext
const statusBarHeight = getAndroidStatusBarHeight()
const script = createStatusBarPlaceholderScript(statusBarHeight)
webviewContext.evalJS(script)
}
@@ -0,0 +1,121 @@
function createAndroidWebViewSafeAreaScript(
height: number,
safeAreaInsetBottom: number
): string {
return `
(function(){
var height=${height};
var safeAreaInsetBottom=${safeAreaInsetBottom};
var safeAreaProperty='--uni-safe-area-inset-bottom';
var safeAreaValue=safeAreaInsetBottom+'px';
var id='uni-app-x-android-pad-statusbar-placeholder';
var maxAttempts=60;
var attempts=0;
var observer=null;
var observedBody=null;
function shouldInsert(){
var pageHead=document.querySelector('.uni-page-head');
if(!pageHead){
// navigationStyle: "custom" does not render a uni-page-head.
return true;
}
if(!pageHead.getBoundingClientRect){
return false;
}
// Pixel XL pageHead 高度为 44.000xxx,故判断小于45
return pageHead.getBoundingClientRect().height<45;
}
function apply(){
if(document.body==null){
return false;
}
var body=document.body;
var spacer=document.getElementById(id);
if(body.style.getPropertyValue(safeAreaProperty)!==safeAreaValue){
body.style.setProperty(safeAreaProperty,safeAreaValue);
}
if(height<=0){
return true;
}
if(!shouldInsert()){
if(spacer!=null&&spacer.parentNode!=null){
spacer.parentNode.removeChild(spacer);
}
return false;
}
if(spacer==null){
spacer=document.createElement('div');
spacer.id=id;
spacer.setAttribute('aria-hidden','true');
}
spacer.style.height=height+'px';
spacer.style.minHeight=height+'px';
spacer.style.width='100%';
spacer.style.display='block';
spacer.style.flexShrink='0';
spacer.style.pointerEvents='none';
spacer.style.background='transparent';
if(body.firstChild!==spacer){
body.insertBefore(spacer,body.firstChild);
}
return true;
}
function observeBody(){
if(document.body==null||typeof MutationObserver!='function'){
return;
}
if(observedBody===document.body){
return;
}
if(observer!=null){
observer.disconnect();
}
observedBody=document.body;
observer=new MutationObserver(function(){
var body=document.body;
var spacer=document.getElementById(id);
var safeAreaApplied=body!=null&&body.style.getPropertyValue(safeAreaProperty)===safeAreaValue;
if(!safeAreaApplied||spacer==null||spacer.parentNode!==body||body.firstChild!==spacer){
apply();
}
});
observer.observe(observedBody,{childList:true,attributes:true,attributeFilter:['style']});
}
function retry(){
apply();
observeBody();
attempts+=1;
if(attempts<maxAttempts){
setTimeout(retry,100);
}
}
if(document.readyState=='loading'){
document.addEventListener('DOMContentLoaded',retry);
}
setTimeout(retry,0);
})();
`
}
export function applyAndroidWebViewSafeArea(webview: WebViewContext | null): void {
if (webview == null) return
const webviewContext = webview as WebViewContext
const windowInfo = uni.getWindowInfo()
const script = createAndroidWebViewSafeAreaScript(
windowInfo.statusBarHeight,
windowInfo.safeAreaInsets.bottom
)
webviewContext.evalJS(script)
}
@@ -0,0 +1,184 @@
const buildIOSWebViewSnapshotTextMetricsScript = (): string => {
return `
(function () {
var styleId = '__uni_snapshot_ios_text_metrics_style__';
var scriptId = '__uni_snapshot_ios_text_metrics_script__';
var defaultLineHeight = '1.20';
if (window.__uniSnapshotIOSTextObserver) {
window.__uniSnapshotIOSTextObserver.disconnect();
window.__uniSnapshotIOSTextObserver = null;
}
window.__uniSnapshotTextNormalizeInstalled = false;
Array.prototype.forEach.call(document.querySelectorAll('style'), function(style) {
var text = style.textContent || '';
if (style.id == styleId ||
text.indexOf('uni-ios-snapshot-text-metrics') >= 0 ||
text.indexOf('__uniSnapshotIOSTextMetrics') >= 0 ||
text.indexOf('__uni_snapshot_multiline_text__') >= 0 ||
text.indexOf('__uniSnapshotTextNormalizeInstalled') >= 0 ||
text.indexOf('local(".SF UI Text")') >= 0 ||
text.indexOf('body { line-height: 1.35') >= 0 ||
text.indexOf('body { line-height: 1.20') >= 0) {
style.parentNode && style.parentNode.removeChild(style);
}
});
Array.prototype.forEach.call(document.querySelectorAll('script'), function(script) {
var text = script.textContent || '';
if (script.id == scriptId ||
text.indexOf('__uniSnapshotIOSTextMetrics') >= 0 ||
text.indexOf('__uniSnapshotIOSTextObserver') >= 0 ||
text.indexOf('__uniSnapshotTextNormalizeInstalled') >= 0) {
script.parentNode && script.parentNode.removeChild(script);
}
});
Array.prototype.forEach.call(document.querySelectorAll('[data-uni-ios-line-height-patched="1"]'), function(element) {
element.style.removeProperty('line-height');
element.removeAttribute('data-uni-ios-line-height-patched');
});
Array.prototype.forEach.call(document.querySelectorAll('.__uni_snapshot_multiline_text__'), function(element) {
element.style.removeProperty('line-height');
element.style.removeProperty('display');
element.classList.remove('__uni_snapshot_multiline_text__');
});
function selectorMatchesLineHeightRule(element, rule) {
if (!rule || !rule.selectorText || !rule.style) {
return false;
}
if (!rule.style.getPropertyValue('line-height')) {
return false;
}
try {
return element.matches(rule.selectorText);
} catch (_) {
return false;
}
}
function hasAuthoredLineHeightInRules(element, rules) {
if (!rules) {
return false;
}
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (selectorMatchesLineHeightRule(element, rule)) {
return true;
}
if (rule.cssRules && hasAuthoredLineHeightInRules(element, rule.cssRules)) {
return true;
}
}
return false;
}
function hasAuthoredLineHeightInStylesheet(element) {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
var rules = null;
try {
rules = sheets[i].cssRules;
} catch (_) {
continue;
}
if (hasAuthoredLineHeightInRules(element, rules)) {
return true;
}
}
return false;
}
function hasInlineLineHeight(element) {
return !!element &&
!!element.style &&
element.style.getPropertyValue('line-height') != '';
}
var bodyHasAuthoredLineHeight =
hasInlineLineHeight(document.body) ||
hasAuthoredLineHeightInStylesheet(document.body);
var styleLines = [
'/* uni-ios-snapshot-text-metrics */',
'html, body {',
' -webkit-text-size-adjust: 100%;',
' text-size-adjust: 100%;',
'}'
];
if (!bodyHasAuthoredLineHeight) {
styleLines.push(
'body {',
' line-height: ' + defaultLineHeight + ';',
'}'
);
}
var style = document.createElement('style');
style.id = styleId;
style.textContent = styleLines.join('\\n');
document.head.appendChild(style);
var script = document.createElement('script');
script.id = scriptId;
script.type = 'text/javascript';
script.textContent = 'window.__uniSnapshotIOSTextMetrics=' + JSON.stringify({
installed: true,
defaultLineHeight: defaultLineHeight,
bodyHasAuthoredLineHeight: bodyHasAuthoredLineHeight,
bodyPatched: !bodyHasAuthoredLineHeight,
scope: 'default-line-height-with-custom-preserved',
keepFontCSS: true,
keepLetterSpacing: true,
preserveExplicitTextStyle: true,
time: Date.now()
}) + ';';
document.head.appendChild(script);
})();
`
}
const buildAndroidWebViewSnapshotTextMetricsScript = (): string => {
return `
(function () {
const style = document.createElement('style');
style.textContent = '@font-face { font-family: "system"; src: local("Roboto"); ascent-override: 92%; descent-override: 8%; } body { font-family: "system"; line-height: 1.35; }';
document.head.appendChild(style);
const script = document.createElement('script');
script.type = 'text/javascript';
script.textContent = 'const observer = new MutationObserver((_) => { const elements = document.querySelectorAll("span"); elements.forEach(element => { const range = document.createRange(); range.selectNodeContents(element); const rects = range.getClientRects(); if (rects.length > 1 && (parseFloat(getComputedStyle(element.parentElement).getPropertyValue("line-height")) / parseFloat(getComputedStyle(element.parentElement).getPropertyValue("font-size")) == 1.35 || getComputedStyle(element.parentElement).getPropertyValue("line-height") == "")) {element.parentElement.style.setProperty("line-height", 1.215); }; }); });observer.observe(document.body, { childList: true, subtree: true, attributes: true });';
document.head.appendChild(script);
})();
`
}
const buildWebViewSnapshotTextMetricsScript = (): string => {
// #ifdef APP-IOS
return buildIOSWebViewSnapshotTextMetricsScript()
// #endif
// #ifdef APP-ANDROID
return buildAndroidWebViewSnapshotTextMetricsScript()
// #endif
}
export const applyWebViewSnapshotTextMetricsPatch = (context : WebViewContext | null): void => {
if (context !== null) {
context.evalJS(buildWebViewSnapshotTextMetricsScript())
}
}
+68
View File
@@ -0,0 +1,68 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
exports.default = [
(0, uni_cli_shared_1.defineUniMainJsPlugin)((opts) => {
return {
name: 'uni:automator',
enforce: 'pre',
configResolved() {
if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
return;
}
const pkg = JSON.parse(fs_extra_1.default.readFileSync(path_1.default.resolve(__dirname, '../package.json'), 'utf8'));
const automatorJson = JSON.stringify({
version: pkg.version,
wsEndpoint: process.env.UNI_AUTOMATOR_WS_ENDPOINT,
});
fs_extra_1.default.outputFileSync(path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.automator/' + (0, uni_cli_shared_1.getPlatformDir)() + '/.automator.json'), automatorJson);
},
transform(code, id) {
if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
return null;
}
if (opts.filter(id)) {
const platform = process.env.UNI_PLATFORM;
// 仅 app-android
if ((platform === 'app' || platform === 'app-harmony') &&
process.env.UNI_APP_X === 'true') {
// app-webview,不增加 initAutomator
if (process.env.UNI_AUTOMATOR_APP_WEBVIEW === 'true') {
return null;
}
if (process.env.UNI_UTS_PLATFORM === 'app-android' &&
process.env.UNI_APP_X_DOM2 !== 'true') {
const automatorPath = (0, uni_cli_shared_1.normalizePath)((0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-app-uts/lib/automator/android/index.uts`));
return {
code:
// 增加个换行,避免最后是注释且无换行
code + `;\nimport { initAutomator } from '${automatorPath}';`,
map: null,
};
}
else if (process.env.UNI_UTS_PLATFORM === 'app-ios' ||
process.env.UNI_UTS_PLATFORM === 'app-harmony' ||
(process.env.UNI_UTS_PLATFORM === 'app-android' &&
process.env.UNI_APP_X_DOM2 === 'true')) {
const automatorPath = (0, uni_cli_shared_1.normalizePath)((0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-app-uts/lib/automator/ios/automator.js`));
return {
code: code + `;\nimport '${automatorPath}';`,
map: null,
};
}
}
const automatorPath = (0, uni_cli_shared_1.normalizePath)((0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-${platform === 'app' ? 'app-plus' : platform}/lib/automator.js`));
return {
code: code + `;\nimport '${automatorPath}';`,
map: null,
};
}
},
};
}),
];