提交 16f7cbd1 编写于 作者: fxy060608's avatar fxy060608

feat(app): add onResize

上级 d0b28cb2
...@@ -27,7 +27,7 @@ import type { ...@@ -27,7 +27,7 @@ import type {
import { hasOwn } from '@vue/shared' import { hasOwn } from '@vue/shared'
import { once } from '@dcloudio/uni-shared' import { once, ON_ERROR } from '@dcloudio/uni-shared'
import { import {
getPageIdByVm, getPageIdByVm,
...@@ -1036,7 +1036,7 @@ export const createCanvasContext = ...@@ -1036,7 +1036,7 @@ export const createCanvasContext =
if (pageId) { if (pageId) {
return new CanvasContext(canvasId, pageId) return new CanvasContext(canvasId, pageId)
} else { } else {
UniServiceJSBridge.emit('onError', 'createCanvasContext:fail') UniServiceJSBridge.emit(ON_ERROR, 'createCanvasContext:fail')
} }
}, },
CreateCanvasContextProtocol CreateCanvasContextProtocol
......
...@@ -1008,7 +1008,29 @@ var serviceContext = (function (vue) { ...@@ -1008,7 +1008,29 @@ var serviceContext = (function (vue) {
const PRIMARY_COLOR = '#007aff'; const PRIMARY_COLOR = '#007aff';
const BACKGROUND_COLOR = '#f7f7f7'; // 背景色,如标题栏默认背景色 const BACKGROUND_COLOR = '#f7f7f7'; // 背景色,如标题栏默认背景色
const SCHEME_RE = /^([a-z-]+:)?\/\//i; const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const DATA_RE = /^data:.*,.*/; const DATA_RE = /^data:.*,.*/;
// lifecycle
// App and Page
const ON_SHOW = 'onShow';
const ON_HIDE = 'onHide';
//App
const ON_LAUNCH = 'onLaunch';
const ON_ERROR = 'onError';
const ON_THEME_CHANGE = 'onThemeChange';
//Page
const ON_LOAD = 'onLoad';
const ON_READY = 'onReady';
const ON_UNLOAD = 'onUnload';
const ON_RESIZE = 'onResize';
const ON_BACK_PRESS = 'onBackPress';
const ON_PAGE_SCROLL = 'onPageScroll';
const ON_TAB_ITEM_TAP = 'onTabItemTap';
const ON_REACH_BOTTOM = 'onReachBottom';
// navigationBar
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap';
// framework
const ON_APP_ENTER_FOREGROUND = 'onAppEnterForeground';
const ON_APP_ENTER_BACKGROUND = 'onAppEnterBackground';
const isObject = (val) => val !== null && typeof val === 'object'; const isObject = (val) => val !== null && typeof val === 'object';
class BaseFormatter { class BaseFormatter {
...@@ -1761,8 +1783,14 @@ var serviceContext = (function (vue) { ...@@ -1761,8 +1783,14 @@ var serviceContext = (function (vue) {
}); });
function initOn() { function initOn() {
UniServiceJSBridge.on('onAppEnterForeground', onAppEnterForeground); const { on } = UniServiceJSBridge;
UniServiceJSBridge.on('onAppEnterBackground', onAppEnterBackground); on(ON_RESIZE, onResize);
on(ON_APP_ENTER_FOREGROUND, onAppEnterForeground);
on(ON_APP_ENTER_BACKGROUND, onAppEnterBackground);
}
function onResize(res) {
invokeHook(getCurrentPage(), ON_RESIZE, res);
UniServiceJSBridge.invokeOnCallback('onWindowResize', res); // API
} }
function onAppEnterForeground() { function onAppEnterForeground() {
const page = getCurrentPage(); const page = getCurrentPage();
...@@ -1774,15 +1802,15 @@ var serviceContext = (function (vue) { ...@@ -1774,15 +1802,15 @@ var serviceContext = (function (vue) {
showOptions.path = page.$page.route; showOptions.path = page.$page.route;
showOptions.query = page.$page.options; showOptions.query = page.$page.options;
} }
invokeHook(getApp(), 'onShow', showOptions); invokeHook(getApp(), ON_SHOW, showOptions);
invokeHook(page, 'onShow'); invokeHook(page, ON_SHOW);
} }
function onAppEnterBackground() { function onAppEnterBackground() {
invokeHook(getApp(), 'onHide'); invokeHook(getApp(), ON_HIDE);
invokeHook(getCurrentPage(), 'onHide'); invokeHook(getCurrentPage(), ON_HIDE);
} }
const SUBSCRIBE_LIFECYCLE_HOOKS = ['onPageScroll', 'onReachBottom']; const SUBSCRIBE_LIFECYCLE_HOOKS = [ON_PAGE_SCROLL, ON_REACH_BOTTOM];
function initSubscribe() { function initSubscribe() {
SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) => UniServiceJSBridge.subscribe(name, createPageEvent(name))); SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) => UniServiceJSBridge.subscribe(name, createPageEvent(name)));
} }
...@@ -3154,7 +3182,7 @@ var serviceContext = (function (vue) { ...@@ -3154,7 +3182,7 @@ var serviceContext = (function (vue) {
return new CanvasContext(canvasId, pageId); return new CanvasContext(canvasId, pageId);
} }
else { else {
UniServiceJSBridge.emit('onError', 'createCanvasContext:fail'); UniServiceJSBridge.emit(ON_ERROR, 'createCanvasContext:fail');
} }
}, CreateCanvasContextProtocol); }, CreateCanvasContextProtocol);
const canvasGetImageData = defineAsyncApi(API_CANVAS_GET_IMAGE_DATA, ({ canvasId, x, y, width, height }, { resolve, reject }) => { const canvasGetImageData = defineAsyncApi(API_CANVAS_GET_IMAGE_DATA, ({ canvasId, x, y, width, height }, { resolve, reject }) => {
...@@ -7829,8 +7857,8 @@ var serviceContext = (function (vue) { ...@@ -7829,8 +7857,8 @@ var serviceContext = (function (vue) {
} }
}); });
if (publicThis.$mpType === 'page') { if (publicThis.$mpType === 'page') {
invokeHook(publicThis, 'onLoad', instance.attrs.__pageQuery); invokeHook(publicThis, ON_LOAD, instance.attrs.__pageQuery);
invokeHook(publicThis, 'onShow'); invokeHook(publicThis, ON_SHOW);
} }
} }
...@@ -7847,7 +7875,7 @@ var serviceContext = (function (vue) { ...@@ -7847,7 +7875,7 @@ var serviceContext = (function (vue) {
throw err; throw err;
} }
{ {
invokeHook(app.$vm, 'onError', err); invokeHook(app.$vm, ON_ERROR, err);
} }
} }
...@@ -8100,7 +8128,7 @@ var serviceContext = (function (vue) { ...@@ -8100,7 +8128,7 @@ var serviceContext = (function (vue) {
openType: 'switchTab', openType: 'switchTab',
from: 'tabBar', from: 'tabBar',
success() { success() {
invokeHook('onTabItemTap', { invokeHook(ON_TAB_ITEM_TAP, {
index, index,
text: item.text, text: item.text,
pagePath: item.pagePath, pagePath: item.pagePath,
...@@ -8115,6 +8143,7 @@ var serviceContext = (function (vue) { ...@@ -8115,6 +8143,7 @@ var serviceContext = (function (vue) {
} }
} }
const EVENT_BACKBUTTON = 'backbutton';
function backbuttonListener() { function backbuttonListener() {
uni.navigateBack({ uni.navigateBack({
from: 'backbutton', from: 'backbutton',
...@@ -8126,24 +8155,24 @@ var serviceContext = (function (vue) { ...@@ -8126,24 +8155,24 @@ var serviceContext = (function (vue) {
const weexGlobalEvent = weex.requireModule('globalEvent'); const weexGlobalEvent = weex.requireModule('globalEvent');
const emit = UniServiceJSBridge.emit; const emit = UniServiceJSBridge.emit;
if (weex.config.preload) { if (weex.config.preload) {
plus.key.addEventListener('backbutton', backbuttonListener); plus.key.addEventListener(EVENT_BACKBUTTON, backbuttonListener);
} }
else { else {
plusGlobalEvent.addEventListener('splashclosed', () => { plusGlobalEvent.addEventListener('splashclosed', () => {
plus.key.addEventListener('backbutton', backbuttonListener); plus.key.addEventListener(EVENT_BACKBUTTON, backbuttonListener);
}); });
} }
plusGlobalEvent.addEventListener('pause', () => { plusGlobalEvent.addEventListener('pause', () => {
emit('onAppEnterBackground'); emit(ON_APP_ENTER_BACKGROUND);
}); });
plusGlobalEvent.addEventListener('resume', () => { plusGlobalEvent.addEventListener('resume', () => {
emit('onAppEnterForeground'); emit(ON_APP_ENTER_FOREGROUND);
}); });
weexGlobalEvent.addEventListener('uistylechange', function (event) { weexGlobalEvent.addEventListener('uistylechange', function (event) {
const args = { const args = {
theme: event.uistyle, theme: event.uistyle,
}; };
emit('onThemeChange', args); emit(ON_THEME_CHANGE, args);
}); });
plusGlobalEvent.addEventListener('plusMessage', subscribePlusMessage); plusGlobalEvent.addEventListener('plusMessage', subscribePlusMessage);
// nvue webview post message // nvue webview post message
...@@ -8167,8 +8196,8 @@ var serviceContext = (function (vue) { ...@@ -8167,8 +8196,8 @@ var serviceContext = (function (vue) {
query: {}, query: {},
scene: 1001, scene: 1001,
}; };
invokeHook(appVm, 'onLaunch', args); invokeHook(appVm, ON_LAUNCH, args);
invokeHook(appVm, 'onShow', args); invokeHook(appVm, ON_SHOW, args);
} }
// 统一处理路径 // 统一处理路径
...@@ -8350,7 +8379,7 @@ var serviceContext = (function (vue) { ...@@ -8350,7 +8379,7 @@ var serviceContext = (function (vue) {
function createTitleNViewBtnClick(index) { function createTitleNViewBtnClick(index) {
return function onClick(btn) { return function onClick(btn) {
btn.index = index; btn.index = index;
invokeHook('onNavigationBarButtonTap', btn); invokeHook(ON_NAVIGATION_BAR_BUTTON_TAP, btn);
}; };
} }
...@@ -9236,7 +9265,7 @@ var serviceContext = (function (vue) { ...@@ -9236,7 +9265,7 @@ var serviceContext = (function (vue) {
if (!page) { if (!page) {
return reject(`getCurrentPages is empty`); return reject(`getCurrentPages is empty`);
} }
if (invokeHook(page, 'onBackPress', { if (invokeHook(page, ON_BACK_PRESS, {
from: args.from, from: args.from,
})) { })) {
return resolve(); return resolve();
...@@ -9305,7 +9334,7 @@ var serviceContext = (function (vue) { ...@@ -9305,7 +9334,7 @@ var serviceContext = (function (vue) {
.forEach((page) => removePage(page)); .forEach((page) => removePage(page));
setStatusBarStyle(); setStatusBarStyle();
// 前一个页面触发 onShow // 前一个页面触发 onShow
invokeHook('onShow'); invokeHook(ON_SHOW);
}; };
const webview = plus.webview.getWebviewById(currentPage.$page.id + ''); const webview = plus.webview.getWebviewById(currentPage.$page.id + '');
if (!currentPage.__uniapp_webview) { if (!currentPage.__uniapp_webview) {
...@@ -9543,11 +9572,11 @@ var serviceContext = (function (vue) { ...@@ -9543,11 +9572,11 @@ var serviceContext = (function (vue) {
initPageVm(pageVm, __pageInstance); initPageVm(pageVm, __pageInstance);
addCurrentPage(initScope(__pageId, pageVm)); addCurrentPage(initScope(__pageId, pageVm));
vue.onMounted(() => { vue.onMounted(() => {
invokeHook(pageVm, 'onReady'); invokeHook(pageVm, ON_READY);
// TODO preloadSubPackages // TODO preloadSubPackages
}); });
vue.onBeforeUnmount(() => { vue.onBeforeUnmount(() => {
invokeHook(pageVm, 'onUnload'); invokeHook(pageVm, ON_UNLOAD);
}); });
if (oldSetup) { if (oldSetup) {
return oldSetup(__pageQuery, ctx); return oldSetup(__pageQuery, ctx);
...@@ -9690,7 +9719,7 @@ var serviceContext = (function (vue) { ...@@ -9690,7 +9719,7 @@ var serviceContext = (function (vue) {
function _navigateTo({ url, path, query, aniType, aniDuration, }) { function _navigateTo({ url, path, query, aniType, aniDuration, }) {
// TODO eventChannel // TODO eventChannel
// 当前页面触发 onHide // 当前页面触发 onHide
invokeHook('onHide'); invokeHook(ON_HIDE);
return new Promise((resolve) => { return new Promise((resolve) => {
showWebview(registerPage({ url, path, query, openType: 'navigateTo' }), aniType, aniDuration, () => { showWebview(registerPage({ url, path, query, openType: 'navigateTo' }), aniType, aniDuration, () => {
resolve(undefined); resolve(undefined);
...@@ -9869,7 +9898,7 @@ var serviceContext = (function (vue) { ...@@ -9869,7 +9898,7 @@ var serviceContext = (function (vue) {
callOnHide = false; callOnHide = false;
} }
if (currentPage && callOnHide) { if (currentPage && callOnHide) {
invokeHook(currentPage, 'onHide'); invokeHook(currentPage, ON_HIDE);
} }
return new Promise((resolve) => { return new Promise((resolve) => {
if (tabBarPage) { if (tabBarPage) {
...@@ -9877,7 +9906,7 @@ var serviceContext = (function (vue) { ...@@ -9877,7 +9906,7 @@ var serviceContext = (function (vue) {
webview.show('none'); webview.show('none');
// 等visible状态都切换完之后,再触发onShow,否则开发者在onShow里边 getCurrentPages 会不准确 // 等visible状态都切换完之后,再触发onShow,否则开发者在onShow里边 getCurrentPages 会不准确
if (callOnShow && !webview.__preload__) { if (callOnShow && !webview.__preload__) {
invokeHook(tabBarPage, 'onShow'); invokeHook(tabBarPage, ON_SHOW);
} }
resolve(undefined); resolve(undefined);
} }
......
...@@ -260,6 +260,8 @@ ...@@ -260,6 +260,8 @@
const PRIMARY_COLOR = "#007aff"; const PRIMARY_COLOR = "#007aff";
const SCHEME_RE = /^([a-z-]+:)?\/\//i; const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const DATA_RE = /^data:.*,.*/; const DATA_RE = /^data:.*,.*/;
const ON_PAGE_SCROLL = "onPageScroll";
const ON_REACH_BOTTOM = "onReachBottom";
const isObject = (val) => val !== null && typeof val === "object"; const isObject = (val) => val !== null && typeof val === "object";
class BaseFormatter { class BaseFormatter {
constructor() { constructor() {
...@@ -5395,6 +5397,7 @@ ...@@ -5395,6 +5397,7 @@
} }
return res; return res;
} }
[ON_PAGE_SCROLL, ON_REACH_BOTTOM];
const VD_SYNC = "vdSync"; const VD_SYNC = "vdSync";
const ON_WEBVIEW_READY = "onWebviewReady"; const ON_WEBVIEW_READY = "onWebviewReady";
const INVOKE_VIEW_API = "invokeViewApi"; const INVOKE_VIEW_API = "invokeViewApi";
...@@ -15383,12 +15386,12 @@ ...@@ -15383,12 +15386,12 @@
const opts = {}; const opts = {};
if (onPageScroll) { if (onPageScroll) {
opts.onPageScroll = (scrollTop) => { opts.onPageScroll = (scrollTop) => {
UniViewJSBridge.publishHandler("onPageScroll", { scrollTop }); UniViewJSBridge.publishHandler(ON_PAGE_SCROLL, { scrollTop });
}; };
} }
if (onPageReachBottom) { if (onPageReachBottom) {
opts.onReachBottomDistance = onReachBottomDistance; opts.onReachBottomDistance = onReachBottomDistance;
opts.onReachBottom = () => UniViewJSBridge.publishHandler("onReachBottom"); opts.onReachBottom = () => UniViewJSBridge.publishHandler(ON_REACH_BOTTOM);
} }
requestAnimationFrame(() => document.addEventListener("scroll", createScrollListener(opts))); requestAnimationFrame(() => document.addEventListener("scroll", createScrollListener(opts)));
} }
......
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
invokeHook, invokeHook,
} from '@dcloudio/uni-core' } from '@dcloudio/uni-core'
import { useI18n } from '@dcloudio/uni-core' import { useI18n } from '@dcloudio/uni-core'
import { ON_BACK_PRESS, ON_SHOW } from '@dcloudio/uni-shared'
import { ComponentPublicInstance } from 'vue' import { ComponentPublicInstance } from 'vue'
import { ANI_CLOSE, ANI_DURATION } from '../../constants' import { ANI_CLOSE, ANI_DURATION } from '../../constants'
import { removePage } from '../../framework/page/getCurrentPages' import { removePage } from '../../framework/page/getCurrentPages'
...@@ -25,7 +26,7 @@ export const navigateBack = defineAsyncApi<API_TYPE_NAVIGATE_BACK>( ...@@ -25,7 +26,7 @@ export const navigateBack = defineAsyncApi<API_TYPE_NAVIGATE_BACK>(
return reject(`getCurrentPages is empty`) return reject(`getCurrentPages is empty`)
} }
if ( if (
invokeHook(page as ComponentPublicInstance, 'onBackPress', { invokeHook(page as ComponentPublicInstance, ON_BACK_PRESS, {
from: (args as any).from, from: (args as any).from,
}) })
) { ) {
...@@ -105,7 +106,7 @@ function back( ...@@ -105,7 +106,7 @@ function back(
.forEach((page) => removePage(page as ComponentPublicInstance)) .forEach((page) => removePage(page as ComponentPublicInstance))
setStatusBarStyle() setStatusBarStyle()
// 前一个页面触发 onShow // 前一个页面触发 onShow
invokeHook('onShow') invokeHook(ON_SHOW)
} }
const webview = plus.webview.getWebviewById(currentPage.$page.id + '') const webview = plus.webview.getWebviewById(currentPage.$page.id + '')
......
import { parseUrl } from '@dcloudio/uni-shared' import { ON_HIDE, parseUrl } from '@dcloudio/uni-shared'
import { getRouteMeta, invokeHook } from '@dcloudio/uni-core' import { getRouteMeta, invokeHook } from '@dcloudio/uni-core'
import { import {
API_NAVIGATE_TO, API_NAVIGATE_TO,
...@@ -57,7 +57,7 @@ function _navigateTo({ ...@@ -57,7 +57,7 @@ function _navigateTo({
}: NavigateToOptions): Promise<undefined> { }: NavigateToOptions): Promise<undefined> {
// TODO eventChannel // TODO eventChannel
// 当前页面触发 onHide // 当前页面触发 onHide
invokeHook('onHide') invokeHook(ON_HIDE)
return new Promise((resolve) => { return new Promise((resolve) => {
showWebview( showWebview(
registerPage({ url, path, query, openType: 'navigateTo' }), registerPage({ url, path, query, openType: 'navigateTo' }),
......
...@@ -6,7 +6,7 @@ import { ...@@ -6,7 +6,7 @@ import {
SwitchTabProtocol, SwitchTabProtocol,
} from '@dcloudio/uni-api' } from '@dcloudio/uni-api'
import { invokeHook } from '@dcloudio/uni-core' import { invokeHook } from '@dcloudio/uni-core'
import { parseUrl } from '@dcloudio/uni-shared' import { ON_HIDE, ON_SHOW, parseUrl } from '@dcloudio/uni-shared'
import { ComponentPublicInstance } from 'vue' import { ComponentPublicInstance } from 'vue'
import { ANI_CLOSE, ANI_DURATION } from '../../constants' import { ANI_CLOSE, ANI_DURATION } from '../../constants'
import tabBar from '../../framework/app/tabBar' import tabBar from '../../framework/app/tabBar'
...@@ -101,7 +101,7 @@ function _switchTab({ ...@@ -101,7 +101,7 @@ function _switchTab({
callOnHide = false callOnHide = false
} }
if (currentPage && callOnHide) { if (currentPage && callOnHide) {
invokeHook(currentPage, 'onHide') invokeHook(currentPage, ON_HIDE)
} }
return new Promise((resolve) => { return new Promise((resolve) => {
if (tabBarPage) { if (tabBarPage) {
...@@ -109,7 +109,7 @@ function _switchTab({ ...@@ -109,7 +109,7 @@ function _switchTab({
webview.show('none') webview.show('none')
// 等visible状态都切换完之后,再触发onShow,否则开发者在onShow里边 getCurrentPages 会不准确 // 等visible状态都切换完之后,再触发onShow,否则开发者在onShow里边 getCurrentPages 会不准确
if (callOnShow && !(webview as any).__preload__) { if (callOnShow && !(webview as any).__preload__) {
invokeHook(tabBarPage, 'onShow') invokeHook(tabBarPage, ON_SHOW)
} }
resolve(undefined) resolve(undefined)
} else { } else {
......
import { invokeHook } from '@dcloudio/uni-core' import { invokeHook } from '@dcloudio/uni-core'
import { ON_LAUNCH, ON_SHOW } from '@dcloudio/uni-shared'
import { ComponentPublicInstance } from 'vue' import { ComponentPublicInstance } from 'vue'
export function initAppLaunch(appVm: ComponentPublicInstance) { export function initAppLaunch(appVm: ComponentPublicInstance) {
...@@ -7,6 +8,6 @@ export function initAppLaunch(appVm: ComponentPublicInstance) { ...@@ -7,6 +8,6 @@ export function initAppLaunch(appVm: ComponentPublicInstance) {
query: {}, query: {},
scene: 1001, scene: 1001,
} }
invokeHook(appVm, 'onLaunch', args) invokeHook(appVm, ON_LAUNCH, args)
invokeHook(appVm, 'onShow', args) invokeHook(appVm, ON_SHOW, args)
} }
import { formatLog } from '@dcloudio/uni-shared' import {
import { backbuttonListener } from './utils' formatLog,
ON_APP_ENTER_BACKGROUND,
ON_APP_ENTER_FOREGROUND,
ON_THEME_CHANGE,
} from '@dcloudio/uni-shared'
import { EVENT_BACKBUTTON, backbuttonListener } from './utils'
export function initGlobalEvent() { export function initGlobalEvent() {
const plusGlobalEvent = (plus as any).globalEvent const plusGlobalEvent = (plus as any).globalEvent
...@@ -7,19 +12,19 @@ export function initGlobalEvent() { ...@@ -7,19 +12,19 @@ export function initGlobalEvent() {
const emit = UniServiceJSBridge.emit const emit = UniServiceJSBridge.emit
if (weex.config.preload) { if (weex.config.preload) {
plus.key.addEventListener('backbutton', backbuttonListener) plus.key.addEventListener(EVENT_BACKBUTTON, backbuttonListener)
} else { } else {
plusGlobalEvent.addEventListener('splashclosed', () => { plusGlobalEvent.addEventListener('splashclosed', () => {
plus.key.addEventListener('backbutton', backbuttonListener) plus.key.addEventListener(EVENT_BACKBUTTON, backbuttonListener)
}) })
} }
plusGlobalEvent.addEventListener('pause', () => { plusGlobalEvent.addEventListener('pause', () => {
emit('onAppEnterBackground') emit(ON_APP_ENTER_BACKGROUND)
}) })
plusGlobalEvent.addEventListener('resume', () => { plusGlobalEvent.addEventListener('resume', () => {
emit('onAppEnterForeground') emit(ON_APP_ENTER_FOREGROUND)
}) })
weexGlobalEvent.addEventListener( weexGlobalEvent.addEventListener(
...@@ -28,7 +33,7 @@ export function initGlobalEvent() { ...@@ -28,7 +33,7 @@ export function initGlobalEvent() {
const args = { const args = {
theme: event.uistyle, theme: event.uistyle,
} }
emit('onThemeChange', args) emit(ON_THEME_CHANGE, args)
} }
) )
......
import { invokeHook } from '@dcloudio/uni-core' import { invokeHook } from '@dcloudio/uni-core'
import { ON_TAB_ITEM_TAP } from '@dcloudio/uni-shared'
import tabBarInstance from './tabBar' import tabBarInstance from './tabBar'
export function initTabBar() { export function initTabBar() {
...@@ -23,7 +24,7 @@ export function initTabBar() { ...@@ -23,7 +24,7 @@ export function initTabBar() {
openType: 'switchTab', openType: 'switchTab',
from: 'tabBar', from: 'tabBar',
success() { success() {
invokeHook('onTabItemTap', { invokeHook(ON_TAB_ITEM_TAP, {
index, index,
text: item.text, text: item.text,
pagePath: item.pagePath, pagePath: item.pagePath,
......
export const EVENT_BACKBUTTON = 'backbutton'
export function backbuttonListener() { export function backbuttonListener() {
uni.navigateBack({ uni.navigateBack({
from: 'backbutton', from: 'backbutton',
......
import { initPageVm, invokeHook } from '@dcloudio/uni-core' import { initPageVm, invokeHook } from '@dcloudio/uni-core'
import { formatLog } from '@dcloudio/uni-shared' import { formatLog, ON_READY, ON_UNLOAD } from '@dcloudio/uni-shared'
import { import {
ComponentPublicInstance, ComponentPublicInstance,
getCurrentInstance, getCurrentInstance,
...@@ -24,11 +24,11 @@ export function setupPage(component: VuePageComponent) { ...@@ -24,11 +24,11 @@ export function setupPage(component: VuePageComponent) {
initPageVm(pageVm, __pageInstance as Page.PageInstance['$page']) initPageVm(pageVm, __pageInstance as Page.PageInstance['$page'])
addCurrentPage(initScope(__pageId as number, pageVm)) addCurrentPage(initScope(__pageId as number, pageVm))
onMounted(() => { onMounted(() => {
invokeHook(pageVm, 'onReady') invokeHook(pageVm, ON_READY)
// TODO preloadSubPackages // TODO preloadSubPackages
}) })
onBeforeUnmount(() => { onBeforeUnmount(() => {
invokeHook(pageVm, 'onUnload') invokeHook(pageVm, ON_UNLOAD)
}) })
if (oldSetup) { if (oldSetup) {
return oldSetup(__pageQuery as any, ctx) return oldSetup(__pageQuery as any, ctx)
......
import {
ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED,
ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED,
ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED,
ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED,
ON_PULL_DOWN_REFRESH,
} from '@dcloudio/uni-shared'
import { onWebviewClose } from './close' import { onWebviewClose } from './close'
import { onWebviewPopGesture } from './popGesture' import { onWebviewPopGesture } from './popGesture'
import { onWebviewResize } from './resize' import { onWebviewResize } from './resize'
const WEBVIEW_LISTENERS = { const WEBVIEW_LISTENERS = {
pullToRefresh: 'onPullDownRefresh', pullToRefresh: ON_PULL_DOWN_REFRESH,
titleNViewSearchInputChanged: 'onNavigationBarSearchInputChanged', titleNViewSearchInputChanged: ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED,
titleNViewSearchInputConfirmed: 'onNavigationBarSearchInputConfirmed', titleNViewSearchInputConfirmed: ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED,
titleNViewSearchInputClicked: 'onNavigationBarSearchInputClicked', titleNViewSearchInputClicked: ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED,
titleNViewSearchInputFocusChanged: 'onNavigationBarSearchInputFocusChanged', titleNViewSearchInputFocusChanged:
ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED,
} as const } as const
export function initWebviewEvent(webview: PlusWebviewWebviewObject) { export function initWebviewEvent(webview: PlusWebviewWebviewObject) {
......
import { invokeHook } from '@dcloudio/uni-core' import { invokeHook } from '@dcloudio/uni-core'
import { ON_SHOW } from '@dcloudio/uni-shared'
import { import {
lastStatusBarStyle, lastStatusBarStyle,
setStatusBarStyle, setStatusBarStyle,
...@@ -24,7 +25,7 @@ export function onWebviewPopGesture(webview: PlusWebviewWebviewObject) { ...@@ -24,7 +25,7 @@ export function onWebviewPopGesture(webview: PlusWebviewWebviewObject) {
removeCurrentPage() removeCurrentPage()
setStatusBarStyle() setStatusBarStyle()
// 触发前一个页面 onShow // 触发前一个页面 onShow
invokeHook('onShow') invokeHook(ON_SHOW)
} }
}) })
} }
import { debounce } from '@dcloudio/uni-shared' import { debounce, ON_RESIZE } from '@dcloudio/uni-shared'
export function onWebviewResize(webview: PlusWebviewWebviewObject) { export function onWebviewResize(webview: PlusWebviewWebviewObject) {
const { emit } = UniServiceJSBridge
const onResize = function ({ const onResize = function ({
width, width,
height, height,
...@@ -16,8 +17,7 @@ export function onWebviewResize(webview: PlusWebviewWebviewObject) { ...@@ -16,8 +17,7 @@ export function onWebviewResize(webview: PlusWebviewWebviewObject) {
windowHeight: Math.ceil(height), windowHeight: Math.ceil(height),
}, },
} }
UniServiceJSBridge.emit('onViewDidResize', res) // API emit(ON_RESIZE, res, parseInt(webview.id!)) // Page lifecycle
UniServiceJSBridge.emit('onResize', res, parseInt(webview.id!)) // Page lifecycle
} }
webview.addEventListener('resize' as any, debounce(onResize, 50)) webview.addEventListener('resize' as any, debounce(onResize, 50))
} }
import { isArray } from '@vue/shared' import { isArray } from '@vue/shared'
import { BACKGROUND_COLOR } from '@dcloudio/uni-shared' import {
BACKGROUND_COLOR,
ON_NAVIGATION_BAR_BUTTON_TAP,
} from '@dcloudio/uni-shared'
import { isColor } from './utils' import { isColor } from './utils'
import { invokeHook } from '@dcloudio/uni-core' import { invokeHook } from '@dcloudio/uni-core'
export function initTitleNView( export function initTitleNView(
...@@ -59,6 +62,6 @@ function createTitleImageTags(titleImage: string) { ...@@ -59,6 +62,6 @@ function createTitleImageTags(titleImage: string) {
function createTitleNViewBtnClick(index: number) { function createTitleNViewBtnClick(index: number) {
return function onClick(btn: UniApp.PageNavigationBarButton) { return function onClick(btn: UniApp.PageNavigationBarButton) {
;(btn as any).index = index ;(btn as any).index = index
invokeHook('onNavigationBarButtonTap', btn) invokeHook(ON_NAVIGATION_BAR_BUTTON_TAP, btn)
} }
} }
...@@ -4,7 +4,13 @@ import { ...@@ -4,7 +4,13 @@ import {
disableScrollListener, disableScrollListener,
updateCssVar, updateCssVar,
} from '@dcloudio/uni-core' } from '@dcloudio/uni-core'
import { formatLog, PageCreateData, UniNodeJSON } from '@dcloudio/uni-shared' import {
formatLog,
ON_PAGE_SCROLL,
ON_REACH_BOTTOM,
PageCreateData,
UniNodeJSON,
} from '@dcloudio/uni-shared'
import { UniElement } from './elements/UniElement' import { UniElement } from './elements/UniElement'
import { UniNode } from './elements/UniNode' import { UniNode } from './elements/UniNode'
...@@ -149,12 +155,12 @@ function initPageScroll( ...@@ -149,12 +155,12 @@ function initPageScroll(
const opts: CreateScrollListenerOptions = {} const opts: CreateScrollListenerOptions = {}
if (onPageScroll) { if (onPageScroll) {
opts.onPageScroll = (scrollTop) => { opts.onPageScroll = (scrollTop) => {
UniViewJSBridge.publishHandler('onPageScroll', { scrollTop }) UniViewJSBridge.publishHandler(ON_PAGE_SCROLL, { scrollTop })
} }
} }
if (onPageReachBottom) { if (onPageReachBottom) {
opts.onReachBottomDistance = onReachBottomDistance opts.onReachBottomDistance = onReachBottomDistance
opts.onReachBottom = () => UniViewJSBridge.publishHandler('onReachBottom') opts.onReachBottom = () => UniViewJSBridge.publishHandler(ON_REACH_BOTTOM)
} }
// 避免监听太早,直接触发了 scroll // 避免监听太早,直接触发了 scroll
requestAnimationFrame(() => requestAnimationFrame(() =>
......
...@@ -7,7 +7,34 @@ var shared = require('@vue/shared'); ...@@ -7,7 +7,34 @@ var shared = require('@vue/shared');
const sanitise = (val) => (val && JSON.parse(JSON.stringify(val))) || val; const sanitise = (val) => (val && JSON.parse(JSON.stringify(val))) || val;
const UNI_SSR = '__uniSSR'; const UNI_SSR = '__uniSSR';
const UNI_SSR_DATA = 'data'; const UNI_SSR_DATA = 'data';
// lifecycle
// App and Page
const ON_SHOW = 'onShow';
const ON_HIDE = 'onHide';
//App
const ON_LAUNCH = 'onLaunch';
const ON_ERROR = 'onError';
const ON_THEME_CHANGE = 'onThemeChange';
const ON_PAGE_NOT_FOUND = 'onPageNotFound';
const ON_UNHANDLE_REJECTION = 'onUnhandledRejection';
const ON_READY = 'onReady';
const ON_UNLOAD = 'onUnload';
const ON_RESIZE = 'onResize';
const ON_BACK_PRESS = 'onBackPress';
const ON_PAGE_SCROLL = 'onPageScroll';
const ON_TAB_ITEM_TAP = 'onTabItemTap';
const ON_REACH_BOTTOM = 'onReachBottom';
const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh';
const ON_SHARE_TIMELINE = 'onShareTimeline';
const ON_ADD_TO_FAVORITES = 'onAddToFavorites';
const ON_SHARE_APP_MESSAGE = 'onShareAppMessage';
// navigationBar
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed';
const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged';
function assertKey(key, shallow = false) { function assertKey(key, shallow = false) {
if (!key) { if (!key) {
...@@ -81,32 +108,6 @@ function resolveEasycom(component, easycom) { ...@@ -81,32 +108,6 @@ function resolveEasycom(component, easycom) {
} }
// @ts-ignore // @ts-ignore
// App and Page
const ON_SHOW = 'onShow';
const ON_HIDE = 'onHide';
//App
const ON_LAUNCH = 'onLaunch';
const ON_ERROR = 'onError';
const ON_THEME_CHANGE = 'onThemeChange';
const ON_PAGE_NOT_FOUND = 'onPageNotFound';
const ON_UNHANDLE_REJECTION = 'onUnhandledRejection';
const ON_READY = 'onReady';
const ON_UNLOAD = 'onUnload';
const ON_RESIZE = 'onResize';
const ON_BACK_PRESS = 'onBackPress';
const ON_PAGE_SCROLL = 'onPageScroll';
const ON_TAB_ITEM_TAP = 'onTabItemTap';
const ON_REACH_BOTTOM = 'onReachBottom';
const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh';
const ON_SHARE_TIMELINE = 'onShareTimeline';
const ON_ADD_TO_FAVORITES = 'onAddToFavorites';
const ON_SHARE_APP_MESSAGE = 'onShareAppMessage';
// navigationBar
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed';
const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged';
const createHook = (lifecycle) => (hook, target = vue.getCurrentInstance()) => const createHook = (lifecycle) => (hook, target = vue.getCurrentInstance()) =>
// post-create lifecycle registrations are noops during SSR // post-create lifecycle registrations are noops during SSR
!vue.isInSSRComponentSetup && vue.injectHook(lifecycle, hook, target); !vue.isInSSRComponentSetup && vue.injectHook(lifecycle, hook, target);
......
...@@ -4,7 +4,34 @@ import { hasOwn, isString } from '@vue/shared'; ...@@ -4,7 +4,34 @@ import { hasOwn, isString } from '@vue/shared';
const sanitise = (val) => (val && JSON.parse(JSON.stringify(val))) || val; const sanitise = (val) => (val && JSON.parse(JSON.stringify(val))) || val;
const UNI_SSR = '__uniSSR'; const UNI_SSR = '__uniSSR';
const UNI_SSR_DATA = 'data'; const UNI_SSR_DATA = 'data';
const UNI_SSR_GLOBAL_DATA = 'globalData'; const UNI_SSR_GLOBAL_DATA = 'globalData';
// lifecycle
// App and Page
const ON_SHOW = 'onShow';
const ON_HIDE = 'onHide';
//App
const ON_LAUNCH = 'onLaunch';
const ON_ERROR = 'onError';
const ON_THEME_CHANGE = 'onThemeChange';
const ON_PAGE_NOT_FOUND = 'onPageNotFound';
const ON_UNHANDLE_REJECTION = 'onUnhandledRejection';
const ON_READY = 'onReady';
const ON_UNLOAD = 'onUnload';
const ON_RESIZE = 'onResize';
const ON_BACK_PRESS = 'onBackPress';
const ON_PAGE_SCROLL = 'onPageScroll';
const ON_TAB_ITEM_TAP = 'onTabItemTap';
const ON_REACH_BOTTOM = 'onReachBottom';
const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh';
const ON_SHARE_TIMELINE = 'onShareTimeline';
const ON_ADD_TO_FAVORITES = 'onAddToFavorites';
const ON_SHARE_APP_MESSAGE = 'onShareAppMessage';
// navigationBar
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed';
const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged';
function getSSRDataType() { function getSSRDataType() {
return getCurrentInstance() ? UNI_SSR_DATA : UNI_SSR_GLOBAL_DATA; return getCurrentInstance() ? UNI_SSR_DATA : UNI_SSR_GLOBAL_DATA;
...@@ -49,32 +76,6 @@ function resolveEasycom(component, easycom) { ...@@ -49,32 +76,6 @@ function resolveEasycom(component, easycom) {
} }
// @ts-ignore // @ts-ignore
// App and Page
const ON_SHOW = 'onShow';
const ON_HIDE = 'onHide';
//App
const ON_LAUNCH = 'onLaunch';
const ON_ERROR = 'onError';
const ON_THEME_CHANGE = 'onThemeChange';
const ON_PAGE_NOT_FOUND = 'onPageNotFound';
const ON_UNHANDLE_REJECTION = 'onUnhandledRejection';
const ON_READY = 'onReady';
const ON_UNLOAD = 'onUnload';
const ON_RESIZE = 'onResize';
const ON_BACK_PRESS = 'onBackPress';
const ON_PAGE_SCROLL = 'onPageScroll';
const ON_TAB_ITEM_TAP = 'onTabItemTap';
const ON_REACH_BOTTOM = 'onReachBottom';
const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh';
const ON_SHARE_TIMELINE = 'onShareTimeline';
const ON_ADD_TO_FAVORITES = 'onAddToFavorites';
const ON_SHARE_APP_MESSAGE = 'onShareAppMessage';
// navigationBar
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed';
const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged';
const createHook = (lifecycle) => (hook, target = getCurrentInstance()) => const createHook = (lifecycle) => (hook, target = getCurrentInstance()) =>
// post-create lifecycle registrations are noops during SSR // post-create lifecycle registrations are noops during SSR
!isInSSRComponentSetup && injectHook(lifecycle, hook, target); !isInSSRComponentSetup && injectHook(lifecycle, hook, target);
......
import { ComponentInternalInstance } from 'vue' import { ComponentInternalInstance } from 'vue'
// @ts-ignore // @ts-ignore
import { isInSSRComponentSetup, injectHook, getCurrentInstance } from 'vue' import { isInSSRComponentSetup, injectHook, getCurrentInstance } from 'vue'
// App and Page
const ON_SHOW = 'onShow'
const ON_HIDE = 'onHide'
//App
const ON_LAUNCH = 'onLaunch'
const ON_ERROR = 'onError'
const ON_THEME_CHANGE = 'onThemeChange'
const ON_PAGE_NOT_FOUND = 'onPageNotFound'
const ON_UNHANDLE_REJECTION = 'onUnhandledRejection'
//Page
const ON_LOAD = 'onLoad'
const ON_READY = 'onReady'
const ON_UNLOAD = 'onUnload'
const ON_RESIZE = 'onResize' import {
const ON_BACK_PRESS = 'onBackPress' ON_ADD_TO_FAVORITES,
const ON_PAGE_SCROLL = 'onPageScroll' ON_BACK_PRESS,
const ON_TAB_ITEM_TAP = 'onTabItemTap' ON_ERROR,
const ON_REACH_BOTTOM = 'onReachBottom' ON_HIDE,
const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh' ON_LAUNCH,
ON_LOAD,
const ON_SHARE_TIMELINE = 'onShareTimeline' ON_NAVIGATION_BAR_BUTTON_TAP,
const ON_ADD_TO_FAVORITES = 'onAddToFavorites' ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED,
const ON_SHARE_APP_MESSAGE = 'onShareAppMessage' ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED,
// navigationBar ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED,
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap' ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED,
const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = ON_PAGE_NOT_FOUND,
'onNavigationBarSearchInputClicked' ON_PAGE_SCROLL,
const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = ON_PULL_DOWN_REFRESH,
'onNavigationBarSearchInputChanged' ON_REACH_BOTTOM,
const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = ON_READY,
'onNavigationBarSearchInputConfirmed' ON_RESIZE,
const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = ON_SHARE_APP_MESSAGE,
'onNavigationBarSearchInputFocusChanged' ON_SHARE_TIMELINE,
ON_SHOW,
ON_TAB_ITEM_TAP,
ON_THEME_CHANGE,
ON_UNHANDLE_REJECTION,
ON_UNLOAD,
} from '@dcloudio/uni-shared'
type UniLifecycleHooks = type UniLifecycleHooks =
| typeof ON_SHOW | typeof ON_SHOW
......
...@@ -12,7 +12,10 @@ ...@@ -12,7 +12,10 @@
"resolveJsonModule": true, "resolveJsonModule": true,
"esModuleInterop": true, "esModuleInterop": true,
"removeComments": false, "removeComments": false,
"lib": ["ESNext", "DOM"] "lib": ["ESNext", "DOM"],
"paths": {
"@dcloudio/uni-shared": ["../uni-shared/src"]
}
}, },
"include": ["src", "../global.d.ts", "../shims-uni-app.d.ts"] "include": ["src", "../global.d.ts", "../shims-uni-app.d.ts"]
} }
import {
ON_APP_ENTER_BACKGROUND,
ON_APP_ENTER_FOREGROUND,
ON_HIDE,
ON_RESIZE,
ON_SHOW,
} from '@dcloudio/uni-shared'
import { ComponentPublicInstance } from '@vue/runtime-core' import { ComponentPublicInstance } from '@vue/runtime-core'
import { invokeHook } from '../../helpers/hook' import { invokeHook } from '../../helpers/hook'
import { getCurrentPage } from '../../helpers/page' import { getCurrentPage } from '../../helpers/page'
export function initOn() { export function initOn() {
UniServiceJSBridge.on('onAppEnterForeground', onAppEnterForeground) const { on } = UniServiceJSBridge
UniServiceJSBridge.on('onAppEnterBackground', onAppEnterBackground) on(ON_RESIZE, onResize)
on(ON_APP_ENTER_FOREGROUND, onAppEnterForeground)
on(ON_APP_ENTER_BACKGROUND, onAppEnterBackground)
}
function onResize(res: UniApp.WindowResizeResult) {
invokeHook(getCurrentPage() as ComponentPublicInstance, ON_RESIZE, res)
UniServiceJSBridge.invokeOnCallback('onWindowResize', res) // API
} }
function onAppEnterForeground() { function onAppEnterForeground() {
...@@ -17,11 +31,11 @@ function onAppEnterForeground() { ...@@ -17,11 +31,11 @@ function onAppEnterForeground() {
showOptions.path = page.$page.route showOptions.path = page.$page.route
showOptions.query = page.$page.options showOptions.query = page.$page.options
} }
invokeHook(getApp() as ComponentPublicInstance, 'onShow', showOptions) invokeHook(getApp() as ComponentPublicInstance, ON_SHOW, showOptions)
invokeHook(page as ComponentPublicInstance, 'onShow') invokeHook(page as ComponentPublicInstance, ON_SHOW)
} }
function onAppEnterBackground() { function onAppEnterBackground() {
invokeHook(getApp() as ComponentPublicInstance, 'onHide') invokeHook(getApp() as ComponentPublicInstance, ON_HIDE)
invokeHook(getCurrentPage() as ComponentPublicInstance, 'onHide') invokeHook(getCurrentPage() as ComponentPublicInstance, ON_HIDE)
} }
import { ON_PAGE_SCROLL, ON_REACH_BOTTOM } from '@dcloudio/uni-shared'
import { getPageVmById } from '../../helpers/page' import { getPageVmById } from '../../helpers/page'
import { invokeHook } from '../../helpers/hook' import { invokeHook } from '../../helpers/hook'
const SUBSCRIBE_LIFECYCLE_HOOKS = ['onPageScroll', 'onReachBottom'] const SUBSCRIBE_LIFECYCLE_HOOKS = [ON_PAGE_SCROLL, ON_REACH_BOTTOM]
export function initSubscribe() { export function initSubscribe() {
SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) => SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) =>
......
...@@ -6584,7 +6584,7 @@ function errorHandler(err, instance, info) { ...@@ -6584,7 +6584,7 @@ function errorHandler(err, instance, info) {
throw err; throw err;
} }
{ {
invokeHook(app.$vm, "onError", err); invokeHook(app.$vm, uniShared.ON_ERROR, err);
} }
} }
function initApp$1(app) { function initApp$1(app) {
...@@ -7651,7 +7651,7 @@ var index$8 = /* @__PURE__ */ defineBuiltInComponent({ ...@@ -7651,7 +7651,7 @@ var index$8 = /* @__PURE__ */ defineBuiltInComponent({
}; };
} }
}); });
const onWebInvokeAppService = ({ name, arg }, pageId) => { const onWebInvokeAppService = ({ name, arg }) => {
if (name === "postMessage") if (name === "postMessage")
; ;
else { else {
......
import { isFunction, extend, isString, hyphenate, isPlainObject, isArray, hasOwn, isObject, capitalize, toRawType, makeMap as makeMap$1, isPromise, invokeArrayFns as invokeArrayFns$1 } from "@vue/shared"; import { isFunction, extend, isString, hyphenate, isPlainObject, isArray, hasOwn, isObject, capitalize, toRawType, makeMap as makeMap$1, isPromise, invokeArrayFns as invokeArrayFns$1 } from "@vue/shared";
import { once, formatLog, passive, initCustomDataset, invokeArrayFns, normalizeTarget, isBuiltInComponent, SCHEME_RE, DATA_RE, getCustomDataset, callOptions, PRIMARY_COLOR, removeLeadingSlash, getLen, debounce, NAVBAR_HEIGHT, parseQuery, ON_REACH_BOTTOM_DISTANCE, decodedQuery, WEB_INVOKE_APPSERVICE, updateElementStyle, parseUrl, addFont, scrollTo, RESPONSIVE_MIN_WIDTH, formatDateTime } from "@dcloudio/uni-shared"; import { once, formatLog, passive, initCustomDataset, invokeArrayFns, normalizeTarget, isBuiltInComponent, ON_RESIZE, ON_APP_ENTER_FOREGROUND, ON_APP_ENTER_BACKGROUND, ON_SHOW, ON_HIDE, ON_PAGE_SCROLL, ON_REACH_BOTTOM, SCHEME_RE, DATA_RE, getCustomDataset, ON_ERROR, callOptions, PRIMARY_COLOR, removeLeadingSlash, getLen, debounce, NAVBAR_HEIGHT, parseQuery, ON_UNLOAD, ON_REACH_BOTTOM_DISTANCE, decodedQuery, WEB_INVOKE_APPSERVICE, ON_WEB_INVOKE_APP_SERVICE, updateElementStyle, ON_BACK_PRESS, parseUrl, addFont, scrollTo, RESPONSIVE_MIN_WIDTH, formatDateTime, ON_PULL_DOWN_REFRESH } from "@dcloudio/uni-shared";
import { openBlock, createBlock, mergeProps, createVNode, toDisplayString, withModifiers, getCurrentInstance, defineComponent, ref, provide, computed, watch, onUnmounted, inject, onBeforeUnmount, reactive, onActivated, onMounted, nextTick, onBeforeMount, withDirectives, vShow, shallowRef, watchEffect, isVNode, Fragment, markRaw, createTextVNode, injectHook, onBeforeActivate, onBeforeDeactivate, renderList, onDeactivated, createApp, Transition, withCtx, KeepAlive, resolveDynamicComponent, renderSlot } from "vue"; import { openBlock, createBlock, mergeProps, createVNode, toDisplayString, withModifiers, getCurrentInstance, defineComponent, ref, provide, computed, watch, onUnmounted, inject, onBeforeUnmount, reactive, onActivated, onMounted, nextTick, onBeforeMount, withDirectives, vShow, shallowRef, watchEffect, isVNode, Fragment, markRaw, createTextVNode, injectHook, onBeforeActivate, onBeforeDeactivate, renderList, onDeactivated, createApp, Transition, withCtx, KeepAlive, resolveDynamicComponent, renderSlot } from "vue";
import { initVueI18n, LOCALE_EN, LOCALE_ES, LOCALE_FR, LOCALE_ZH_HANS, LOCALE_ZH_HANT } from "@dcloudio/uni-i18n"; import { initVueI18n, LOCALE_EN, LOCALE_ES, LOCALE_FR, LOCALE_ZH_HANS, LOCALE_ZH_HANT } from "@dcloudio/uni-i18n";
import { useRoute, createRouter, createWebHistory, createWebHashHistory, useRouter, isNavigationFailure, RouterView } from "vue-router"; import { useRoute, createRouter, createWebHistory, createWebHashHistory, useRouter, isNavigationFailure, RouterView } from "vue-router";
...@@ -1337,8 +1337,14 @@ const ServiceJSBridge = /* @__PURE__ */ extend(initBridge("view"), { ...@@ -1337,8 +1337,14 @@ const ServiceJSBridge = /* @__PURE__ */ extend(initBridge("view"), {
} }
}); });
function initOn() { function initOn() {
UniServiceJSBridge.on("onAppEnterForeground", onAppEnterForeground); const { on: on2 } = UniServiceJSBridge;
UniServiceJSBridge.on("onAppEnterBackground", onAppEnterBackground); on2(ON_RESIZE, onResize$1);
on2(ON_APP_ENTER_FOREGROUND, onAppEnterForeground);
on2(ON_APP_ENTER_BACKGROUND, onAppEnterBackground);
}
function onResize$1(res) {
invokeHook(getCurrentPage(), ON_RESIZE, res);
UniServiceJSBridge.invokeOnCallback("onWindowResize", res);
} }
function onAppEnterForeground() { function onAppEnterForeground() {
const page = getCurrentPage(); const page = getCurrentPage();
...@@ -1350,14 +1356,14 @@ function onAppEnterForeground() { ...@@ -1350,14 +1356,14 @@ function onAppEnterForeground() {
showOptions.path = page.$page.route; showOptions.path = page.$page.route;
showOptions.query = page.$page.options; showOptions.query = page.$page.options;
} }
invokeHook(getApp(), "onShow", showOptions); invokeHook(getApp(), ON_SHOW, showOptions);
invokeHook(page, "onShow"); invokeHook(page, ON_SHOW);
} }
function onAppEnterBackground() { function onAppEnterBackground() {
invokeHook(getApp(), "onHide"); invokeHook(getApp(), ON_HIDE);
invokeHook(getCurrentPage(), "onHide"); invokeHook(getCurrentPage(), ON_HIDE);
} }
const SUBSCRIBE_LIFECYCLE_HOOKS = ["onPageScroll", "onReachBottom"]; const SUBSCRIBE_LIFECYCLE_HOOKS = [ON_PAGE_SCROLL, ON_REACH_BOTTOM];
function initSubscribe() { function initSubscribe() {
SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) => UniServiceJSBridge.subscribe(name, createPageEvent(name))); SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) => UniServiceJSBridge.subscribe(name, createPageEvent(name)));
} }
...@@ -3729,7 +3735,7 @@ const createCanvasContext = /* @__PURE__ */ defineSyncApi(API_CREATE_CANVAS_CONT ...@@ -3729,7 +3735,7 @@ const createCanvasContext = /* @__PURE__ */ defineSyncApi(API_CREATE_CANVAS_CONT
if (pageId) { if (pageId) {
return new CanvasContext(canvasId, pageId); return new CanvasContext(canvasId, pageId);
} else { } else {
UniServiceJSBridge.emit("onError", "createCanvasContext:fail"); UniServiceJSBridge.emit(ON_ERROR, "createCanvasContext:fail");
} }
}, CreateCanvasContextProtocol); }, CreateCanvasContextProtocol);
const canvasGetImageData = /* @__PURE__ */ defineAsyncApi(API_CANVAS_GET_IMAGE_DATA, ({ canvasId, x, y, width, height }, { resolve, reject }) => { const canvasGetImageData = /* @__PURE__ */ defineAsyncApi(API_CANVAS_GET_IMAGE_DATA, ({ canvasId, x, y, width, height }, { resolve, reject }) => {
...@@ -13080,7 +13086,7 @@ function errorHandler(err, instance2, info) { ...@@ -13080,7 +13086,7 @@ function errorHandler(err, instance2, info) {
throw err; throw err;
} }
{ {
invokeHook(app.$vm, "onError", err); invokeHook(app.$vm, ON_ERROR, err);
} }
} }
function initApp$1(app) { function initApp$1(app) {
...@@ -13263,7 +13269,7 @@ function removeRouteCache(routeKey) { ...@@ -13263,7 +13269,7 @@ function removeRouteCache(routeKey) {
function removePage(routeKey, removeRouteCaches = true) { function removePage(routeKey, removeRouteCaches = true) {
const pageVm = currentPagesMap.get(routeKey); const pageVm = currentPagesMap.get(routeKey);
pageVm.$.__isUnload = true; pageVm.$.__isUnload = true;
invokeHook(pageVm, "onUnload"); invokeHook(pageVm, ON_UNLOAD);
currentPagesMap.delete(routeKey); currentPagesMap.delete(routeKey);
removeRouteCaches && removeRouteCache(routeKey); removeRouteCaches && removeRouteCache(routeKey);
} }
...@@ -13400,7 +13406,7 @@ function initPageScrollListener(instance2, pageMeta) { ...@@ -13400,7 +13406,7 @@ function initPageScrollListener(instance2, pageMeta) {
} }
if (onReachBottom) { if (onReachBottom) {
opts.onReachBottomDistance = pageMeta.onReachBottomDistance || ON_REACH_BOTTOM_DISTANCE; opts.onReachBottomDistance = pageMeta.onReachBottomDistance || ON_REACH_BOTTOM_DISTANCE;
opts.onReachBottom = () => UniViewJSBridge.publishHandler("onReachBottom", {}, pageId); opts.onReachBottom = () => UniViewJSBridge.publishHandler(ON_REACH_BOTTOM, {}, pageId);
} }
curScrollListener = createScrollListener(opts); curScrollListener = createScrollListener(opts);
requestAnimationFrame(() => document.addEventListener("scroll", curScrollListener)); requestAnimationFrame(() => document.addEventListener("scroll", curScrollListener));
...@@ -13408,10 +13414,10 @@ function initPageScrollListener(instance2, pageMeta) { ...@@ -13408,10 +13414,10 @@ function initPageScrollListener(instance2, pageMeta) {
function createOnPageScroll(pageId, onPageScroll, navigationBarTransparent) { function createOnPageScroll(pageId, onPageScroll, navigationBarTransparent) {
return (scrollTop) => { return (scrollTop) => {
if (onPageScroll) { if (onPageScroll) {
UniViewJSBridge.publishHandler("onPageScroll", { scrollTop }, pageId); UniViewJSBridge.publishHandler(ON_PAGE_SCROLL, { scrollTop }, pageId);
} }
if (navigationBarTransparent) { if (navigationBarTransparent) {
UniViewJSBridge.emit(pageId + ".onPageScroll", { UniViewJSBridge.emit(pageId + "." + ON_PAGE_SCROLL, {
scrollTop scrollTop
}); });
} }
...@@ -13558,18 +13564,9 @@ function setupApp(comp) { ...@@ -13558,18 +13564,9 @@ function setupApp(comp) {
onBeforeMount(onLaunch); onBeforeMount(onLaunch);
} }
onMounted(() => { onMounted(() => {
window.addEventListener("message", function(evt) { window.addEventListener("resize", debounce(onResize, 50));
if (isPlainObject(evt.data) && evt.data.type === WEB_INVOKE_APPSERVICE) { window.addEventListener("message", onMessage);
UniServiceJSBridge.emit("onWebInvokeAppService", evt.data.data, evt.data.pageId); document.addEventListener("visibilitychange", onVisibilityChange);
}
});
document.addEventListener("visibilitychange", function() {
if (document.visibilityState === "visible") {
UniServiceJSBridge.emit("onAppEnterForeground");
} else {
UniServiceJSBridge.emit("onAppEnterBackground");
}
});
}); });
return route.query; return route.query;
}, },
...@@ -13581,6 +13578,28 @@ function setupApp(comp) { ...@@ -13581,6 +13578,28 @@ function setupApp(comp) {
} }
}); });
} }
function onResize() {
const { windowWidth, windowHeight, screenWidth, screenHeight } = uni.getSystemInfoSync();
const landscape = Math.abs(Number(window.orientation)) === 90;
const deviceOrientation = landscape ? "landscape" : "portrait";
UniServiceJSBridge.emit(ON_RESIZE, {
deviceOrientation,
size: {
windowWidth,
windowHeight,
screenWidth,
screenHeight
}
});
}
function onMessage(evt) {
if (isPlainObject(evt.data) && evt.data.type === WEB_INVOKE_APPSERVICE) {
UniServiceJSBridge.emit(ON_WEB_INVOKE_APP_SERVICE, evt.data.data, evt.data.pageId);
}
}
function onVisibilityChange() {
UniServiceJSBridge.emit(document.visibilityState === "visible" ? ON_APP_ENTER_FOREGROUND : ON_APP_ENTER_BACKGROUND);
}
function formatTime(val) { function formatTime(val) {
val = val > 0 && val < Infinity ? val : 0; val = val > 0 && val < Infinity ? val : 0;
const h = Math.floor(val / 3600); const h = Math.floor(val / 3600);
...@@ -14431,7 +14450,7 @@ var index$8 = /* @__PURE__ */ defineBuiltInComponent({ ...@@ -14431,7 +14450,7 @@ var index$8 = /* @__PURE__ */ defineBuiltInComponent({
}; };
} }
}); });
const onWebInvokeAppService = ({ name, arg }, pageId) => { const onWebInvokeAppService = ({ name, arg }) => {
if (name === "postMessage") if (name === "postMessage")
; ;
else { else {
...@@ -17271,11 +17290,11 @@ const chooseLocation = /* @__PURE__ */ defineAsyncApi(API_CHOOSE_LOCATION, (args ...@@ -17271,11 +17290,11 @@ const chooseLocation = /* @__PURE__ */ defineAsyncApi(API_CHOOSE_LOCATION, (args
}, ChooseLocationProtocol); }, ChooseLocationProtocol);
const navigateBack = /* @__PURE__ */ defineAsyncApi(API_NAVIGATE_BACK, ({ delta }, { resolve, reject }) => { const navigateBack = /* @__PURE__ */ defineAsyncApi(API_NAVIGATE_BACK, ({ delta }, { resolve, reject }) => {
let canBack = true; let canBack = true;
if (invokeHook("onBackPress") === true) { if (invokeHook(ON_BACK_PRESS) === true) {
canBack = false; canBack = false;
} }
if (!canBack) { if (!canBack) {
return reject("onBackPress"); return reject(ON_BACK_PRESS);
} }
getApp().$router.go(-delta); getApp().$router.go(-delta);
return resolve(); return resolve();
...@@ -17335,7 +17354,7 @@ function removeNonTabBarPages() { ...@@ -17335,7 +17354,7 @@ function removeNonTabBarPages() {
} }
if (curTabBarPageVm.__isTabBar) { if (curTabBarPageVm.__isTabBar) {
curTabBarPageVm.$.__isVisible = false; curTabBarPageVm.$.__isVisible = false;
invokeHook(curTabBarPageVm, "onHide"); invokeHook(curTabBarPageVm, ON_HIDE);
} }
} }
function getTabBarPageId(url) { function getTabBarPageId(url) {
...@@ -18736,30 +18755,9 @@ function createRightWindowTsx(rightWindow, layoutState, windowState) { ...@@ -18736,30 +18755,9 @@ function createRightWindowTsx(rightWindow, layoutState, windowState) {
}, 8, ["data-show", "style"]), [[vShow, layoutState.showRightWindow || layoutState.apiShowRightWindow]]); }, 8, ["data-show", "style"]), [[vShow, layoutState.showRightWindow || layoutState.apiShowRightWindow]]);
} }
} }
var tasks = [];
function onResize() {
tasks.push(setTimeout(() => {
tasks.forEach((task) => clearTimeout(task));
tasks.length = 0;
const { windowWidth, windowHeight, screenWidth, screenHeight } = uni.getSystemInfoSync();
var landscape = Math.abs(Number(window.orientation)) === 90;
var deviceOrientation = landscape ? "landscape" : "portrait";
UniServiceJSBridge.invokeOnCallback(API_ON_WINDOW_RESIZE, {
deviceOrientation,
size: {
windowWidth,
windowHeight,
screenWidth,
screenHeight
}
});
}, 20));
}
const onWindowResize = /* @__PURE__ */ defineOnApi(API_ON_WINDOW_RESIZE, () => { const onWindowResize = /* @__PURE__ */ defineOnApi(API_ON_WINDOW_RESIZE, () => {
window.addEventListener("resize", onResize);
}); });
const offWindowResize = /* @__PURE__ */ defineOffApi(API_OFF_WINDOW_RESIZE, () => { const offWindowResize = /* @__PURE__ */ defineOffApi(API_OFF_WINDOW_RESIZE, () => {
window.removeEventListener("resize", onResize);
}); });
const showTopWindow = /* @__PURE__ */ defineAsyncApi("showTopWindow", (_, { resolve, reject }) => { const showTopWindow = /* @__PURE__ */ defineAsyncApi("showTopWindow", (_, { resolve, reject }) => {
const state2 = getLayoutState(); const state2 = getLayoutState();
...@@ -20963,7 +20961,7 @@ function usePageRefresh(refreshRef) { ...@@ -20963,7 +20961,7 @@ function usePageRefresh(refreshRef) {
} }
refreshControllerElemStyle.transition = "-webkit-transform 0.2s"; refreshControllerElemStyle.transition = "-webkit-transform 0.2s";
refreshControllerElemStyle.transform = "translate3d(-50%, " + height + "px, 0)"; refreshControllerElemStyle.transform = "translate3d(-50%, " + height + "px, 0)";
invokeHook(id2, "onPullDownRefresh"); invokeHook(id2, ON_PULL_DOWN_REFRESH);
} }
function restoring(callback) { function restoring(callback) {
if (!refreshControllerElem) { if (!refreshControllerElem) {
......
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
} from '@dcloudio/uni-api' } from '@dcloudio/uni-api'
import { useSubscribe, withWebEvent } from '@dcloudio/uni-components' import { useSubscribe, withWebEvent } from '@dcloudio/uni-components'
import { usePageMeta } from '../../../setup/provide' import { usePageMeta } from '../../../setup/provide'
import { ON_PULL_DOWN_REFRESH } from '@dcloudio/uni-shared'
function processDeltaY( function processDeltaY(
ev: TouchEvent, ev: TouchEvent,
...@@ -103,7 +104,7 @@ export function usePageRefresh(refreshRef: Ref) { ...@@ -103,7 +104,7 @@ export function usePageRefresh(refreshRef: Ref) {
return return
} }
let rotate = deltaY / range let rotate = deltaY / range!
if (rotate > 1) { if (rotate > 1) {
rotate = 1 rotate = 1
...@@ -111,7 +112,7 @@ export function usePageRefresh(refreshRef: Ref) { ...@@ -111,7 +112,7 @@ export function usePageRefresh(refreshRef: Ref) {
rotate = rotate * rotate * rotate rotate = rotate * rotate * rotate
} }
const y = Math.round(deltaY / (range / height)) || 0 const y = Math.round(deltaY / (range! / height!)) || 0
refreshInnerElemStyle.transform = 'rotate(' + 360 * rotate + 'deg)' refreshInnerElemStyle.transform = 'rotate(' + 360 * rotate + 'deg)'
refreshControllerElemStyle.clip = 'rect(' + (45 - y) + 'px,45px,45px,-5px)' refreshControllerElemStyle.clip = 'rect(' + (45 - y) + 'px,45px,45px,-5px)'
...@@ -162,8 +163,8 @@ export function usePageRefresh(refreshRef: Ref) { ...@@ -162,8 +163,8 @@ export function usePageRefresh(refreshRef: Ref) {
distance = deltaY distance = deltaY
const isReached = deltaY >= range && state !== REACHED const isReached = deltaY >= range! && state !== REACHED
const isPulling = deltaY < range && state !== PULLING const isPulling = deltaY < range! && state !== PULLING
if (isReached || isPulling) { if (isReached || isPulling) {
removeClass() removeClass()
...@@ -231,7 +232,7 @@ export function usePageRefresh(refreshRef: Ref) { ...@@ -231,7 +232,7 @@ export function usePageRefresh(refreshRef: Ref) {
refreshControllerElemStyle.transition = '-webkit-transform 0.2s' refreshControllerElemStyle.transition = '-webkit-transform 0.2s'
refreshControllerElemStyle.transform = refreshControllerElemStyle.transform =
'translate3d(-50%, ' + height + 'px, 0)' 'translate3d(-50%, ' + height + 'px, 0)'
invokeHook(id!, 'onPullDownRefresh') invokeHook(id!, ON_PULL_DOWN_REFRESH)
} }
function restoring(callback: Function) { function restoring(callback: Function) {
......
...@@ -12,11 +12,23 @@ import { ...@@ -12,11 +12,23 @@ import {
onBeforeMount, onBeforeMount,
} from 'vue' } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { decodedQuery, WEB_INVOKE_APPSERVICE } from '@dcloudio/uni-shared' import {
debounce,
decodedQuery,
ON_APP_ENTER_BACKGROUND,
ON_APP_ENTER_FOREGROUND,
ON_RESIZE,
ON_WEB_INVOKE_APP_SERVICE,
WEB_INVOKE_APPSERVICE,
} from '@dcloudio/uni-shared'
import { LayoutComponent } from '../..' import { LayoutComponent } from '../..'
import { initApp } from './app' import { initApp } from './app'
import { initPage, onPageShow, onPageReady } from './page' import { initPage, onPageShow, onPageReady } from './page'
import { usePageMeta, usePageRoute } from './provide' import { usePageMeta, usePageRoute } from './provide'
import {
API_ON_WINDOW_RESIZE,
API_TYPE_ON_WINDOW_RESIZE,
} from '@dcloudio/uni-api'
interface SetupComponentOptions { interface SetupComponentOptions {
init: (vm: ComponentPublicInstance) => void init: (vm: ComponentPublicInstance) => void
...@@ -122,30 +134,9 @@ export function setupApp(comp: any) { ...@@ -122,30 +134,9 @@ export function setupApp(comp: any) {
onBeforeMount(onLaunch) onBeforeMount(onLaunch)
} }
onMounted(() => { onMounted(() => {
window.addEventListener( window.addEventListener('resize', debounce(onResize, 50))
'message', window.addEventListener('message', onMessage)
function (evt: { document.addEventListener('visibilitychange', onVisibilityChange)
data?: { type: string; data: any; pageId: number }
}) {
if (
isPlainObject(evt.data) &&
evt.data.type === WEB_INVOKE_APPSERVICE
) {
UniServiceJSBridge.emit(
'onWebInvokeAppService',
evt.data.data,
evt.data.pageId
)
}
}
)
document.addEventListener('visibilitychange', function () {
if (document.visibilityState === 'visible') {
UniServiceJSBridge.emit('onAppEnterForeground')
} else {
UniServiceJSBridge.emit('onAppEnterBackground')
}
})
}) })
return route.query return route.query
}, },
...@@ -157,3 +148,37 @@ export function setupApp(comp: any) { ...@@ -157,3 +148,37 @@ export function setupApp(comp: any) {
}, },
}) })
} }
function onResize() {
const { windowWidth, windowHeight, screenWidth, screenHeight } =
uni.getSystemInfoSync()
const landscape = Math.abs(Number(window.orientation)) === 90
const deviceOrientation = landscape ? 'landscape' : 'portrait'
UniServiceJSBridge.emit(ON_RESIZE, {
deviceOrientation,
size: {
windowWidth,
windowHeight,
screenWidth,
screenHeight,
},
})
}
function onMessage(evt: {
data?: { type: string; data: any; pageId: number }
}) {
if (isPlainObject(evt.data) && evt.data.type === WEB_INVOKE_APPSERVICE) {
UniServiceJSBridge.emit(
ON_WEB_INVOKE_APP_SERVICE,
evt.data.data,
evt.data.pageId
)
}
}
function onVisibilityChange() {
UniServiceJSBridge.emit(
document.visibilityState === 'visible'
? ON_APP_ENTER_FOREGROUND
: ON_APP_ENTER_BACKGROUND
)
}
...@@ -15,7 +15,12 @@ import { ...@@ -15,7 +15,12 @@ import {
initPageInternalInstance, initPageInternalInstance,
initPageVm, initPageVm,
} from '@dcloudio/uni-core' } from '@dcloudio/uni-core'
import { ON_REACH_BOTTOM_DISTANCE } from '@dcloudio/uni-shared' import {
ON_PAGE_SCROLL,
ON_REACH_BOTTOM,
ON_REACH_BOTTOM_DISTANCE,
ON_UNLOAD,
} from '@dcloudio/uni-shared'
import { usePageMeta } from './provide' import { usePageMeta } from './provide'
import { NavigateType } from '../../service/api/route/utils' import { NavigateType } from '../../service/api/route/utils'
import { updateCurPageCssVar } from '../../helpers/cssVar' import { updateCurPageCssVar } from '../../helpers/cssVar'
...@@ -63,7 +68,7 @@ function removeRouteCache(routeKey: string) { ...@@ -63,7 +68,7 @@ function removeRouteCache(routeKey: string) {
export function removePage(routeKey: string, removeRouteCaches = true) { export function removePage(routeKey: string, removeRouteCaches = true) {
const pageVm = currentPagesMap.get(routeKey) as ComponentPublicInstance const pageVm = currentPagesMap.get(routeKey) as ComponentPublicInstance
pageVm.$.__isUnload = true pageVm.$.__isUnload = true
invokeHook(pageVm, 'onUnload') invokeHook(pageVm, ON_UNLOAD)
currentPagesMap.delete(routeKey) currentPagesMap.delete(routeKey)
removeRouteCaches && removeRouteCache(routeKey) removeRouteCaches && removeRouteCache(routeKey)
} }
...@@ -244,7 +249,7 @@ function initPageScrollListener( ...@@ -244,7 +249,7 @@ function initPageScrollListener(
opts.onReachBottomDistance = opts.onReachBottomDistance =
pageMeta.onReachBottomDistance || ON_REACH_BOTTOM_DISTANCE pageMeta.onReachBottomDistance || ON_REACH_BOTTOM_DISTANCE
opts.onReachBottom = () => opts.onReachBottom = () =>
UniViewJSBridge.publishHandler('onReachBottom', {}, pageId) UniViewJSBridge.publishHandler(ON_REACH_BOTTOM, {}, pageId)
} }
curScrollListener = createScrollListener(opts) curScrollListener = createScrollListener(opts)
// 避免监听太早,直接触发了 scroll // 避免监听太早,直接触发了 scroll
...@@ -260,10 +265,10 @@ function createOnPageScroll( ...@@ -260,10 +265,10 @@ function createOnPageScroll(
) { ) {
return (scrollTop: number) => { return (scrollTop: number) => {
if (onPageScroll) { if (onPageScroll) {
UniViewJSBridge.publishHandler('onPageScroll', { scrollTop }, pageId) UniViewJSBridge.publishHandler(ON_PAGE_SCROLL, { scrollTop }, pageId)
} }
if (navigationBarTransparent) { if (navigationBarTransparent) {
UniViewJSBridge.emit(pageId + '.onPageScroll', { UniViewJSBridge.emit(pageId + '.' + ON_PAGE_SCROLL, {
scrollTop, scrollTop,
}) })
} }
......
...@@ -6,16 +6,17 @@ import { ...@@ -6,16 +6,17 @@ import {
NavigateBackOptions, NavigateBackOptions,
NavigateBackProtocol, NavigateBackProtocol,
} from '@dcloudio/uni-api' } from '@dcloudio/uni-api'
import { ON_BACK_PRESS } from '@dcloudio/uni-shared'
export const navigateBack = defineAsyncApi<API_TYPE_NAVIGATE_BACK>( export const navigateBack = defineAsyncApi<API_TYPE_NAVIGATE_BACK>(
API_NAVIGATE_BACK, API_NAVIGATE_BACK,
({ delta }, { resolve, reject }) => { ({ delta }, { resolve, reject }) => {
let canBack = true let canBack = true
if (invokeHook('onBackPress') === true) { if (invokeHook(ON_BACK_PRESS) === true) {
canBack = false canBack = false
} }
if (!canBack) { if (!canBack) {
return reject('onBackPress') return reject(ON_BACK_PRESS)
} }
getApp().$router.go(-delta!) getApp().$router.go(-delta!)
return resolve() return resolve()
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
import { getCurrentPageVm, invokeHook } from '@dcloudio/uni-core' import { getCurrentPageVm, invokeHook } from '@dcloudio/uni-core'
import { getCurrentPagesMap, removePage } from '../../../framework/setup/page' import { getCurrentPagesMap, removePage } from '../../../framework/setup/page'
import { navigate } from './utils' import { navigate } from './utils'
import { ON_HIDE } from '@dcloudio/uni-shared'
function removeNonTabBarPages() { function removeNonTabBarPages() {
const curTabBarPageVm = getCurrentPageVm() const curTabBarPageVm = getCurrentPageVm()
...@@ -27,7 +28,7 @@ function removeNonTabBarPages() { ...@@ -27,7 +28,7 @@ function removeNonTabBarPages() {
} }
if (curTabBarPageVm.__isTabBar) { if (curTabBarPageVm.__isTabBar) {
curTabBarPageVm.$.__isVisible = false curTabBarPageVm.$.__isVisible = false
invokeHook(curTabBarPageVm, 'onHide') invokeHook(curTabBarPageVm, ON_HIDE)
} }
} }
......
...@@ -12,54 +12,23 @@ import { ...@@ -12,54 +12,23 @@ import {
} from '@dcloudio/uni-api' } from '@dcloudio/uni-api'
import { getLayoutState } from '../../../framework/components/layout' import { getLayoutState } from '../../../framework/components/layout'
var tasks: number[] = []
function onResize() {
tasks.push(
setTimeout(() => {
tasks.forEach((task) => clearTimeout(task))
tasks.length = 0
const { windowWidth, windowHeight, screenWidth, screenHeight } =
uni.getSystemInfoSync()
var landscape = Math.abs(Number(window.orientation)) === 90
var deviceOrientation = landscape ? 'landscape' : 'portrait'
UniServiceJSBridge.invokeOnCallback<API_TYPE_ON_WINDOW_RESIZE>(
API_ON_WINDOW_RESIZE,
{
// @ts-ignore
deviceOrientation,
size: {
windowWidth,
windowHeight,
screenWidth,
screenHeight,
},
}
)
}, 20)
)
}
/** /**
* 监听窗口大小变化 * 监听窗口大小变化
* @param {*} callbackId
*/ */
export const onWindowResize = defineOnApi<API_TYPE_ON_WINDOW_RESIZE>( export const onWindowResize = defineOnApi<API_TYPE_ON_WINDOW_RESIZE>(
API_ON_WINDOW_RESIZE, API_ON_WINDOW_RESIZE,
() => { () => {
window.addEventListener('resize', onResize) // 生命周期包括onResize,框架直接监听resize
// window.addEventListener('resize', onResize)
} }
) )
/** /**
* 取消监听窗口大小变化 * 取消监听窗口大小变化
* @param {*} callbackId
*/ */
export const offWindowResize = defineOffApi<API_TYPE_OFF_WINDOW_RESIZE>( export const offWindowResize = defineOffApi<API_TYPE_OFF_WINDOW_RESIZE>(
API_OFF_WINDOW_RESIZE, API_OFF_WINDOW_RESIZE,
() => { () => {
window.removeEventListener('resize', onResize) // window.removeEventListener('resize', onResize)
} }
) )
......
...@@ -14,10 +14,7 @@ export type WebInvokeAppService = ( ...@@ -14,10 +14,7 @@ export type WebInvokeAppService = (
pageId: number | number[] pageId: number | number[]
) => void ) => void
export const onWebInvokeAppService: WebInvokeAppService = ( export const onWebInvokeAppService: WebInvokeAppService = ({ name, arg }) => {
{ name, arg },
pageId
) => {
if (name === 'postMessage') { if (name === 'postMessage') {
// TODO 小程序后退、组件销毁、分享时通知 // TODO 小程序后退、组件销毁、分享时通知
} else { } else {
......
...@@ -10,7 +10,13 @@ import { ...@@ -10,7 +10,13 @@ import {
initWxsCallMethods, initWxsCallMethods,
} from '@dcloudio/uni-mp-core' } from '@dcloudio/uni-mp-core'
import { stringifyQuery } from '@dcloudio/uni-shared' import {
ON_BACK_PRESS,
ON_LOAD,
ON_READY,
ON_UNLOAD,
stringifyQuery,
} from '@dcloudio/uni-shared'
import { import {
handleRef, handleRef,
...@@ -33,23 +39,23 @@ export function createPage(vueOptions: ComponentOptions) { ...@@ -33,23 +39,23 @@ export function createPage(vueOptions: ComponentOptions) {
// 初始化 vue 实例 // 初始化 vue 实例
this.$vm = createVueComponent('page', this, vueOptions) this.$vm = createVueComponent('page', this, vueOptions)
initSpecialMethods(this) initSpecialMethods(this)
this.$vm.$callHook('onLoad', query) this.$vm.$callHook(ON_LOAD, query)
}, },
onReady() { onReady() {
initChildVues(this) initChildVues(this)
this.$vm.$callHook('mounted') this.$vm.$callHook('mounted')
this.$vm.$callHook('onReady') this.$vm.$callHook(ON_READY)
}, },
onUnload() { onUnload() {
if (this.$vm) { if (this.$vm) {
this.$vm.$callHook('onUnload') this.$vm.$callHook(ON_UNLOAD)
$destroyComponent(this.$vm) $destroyComponent(this.$vm)
} }
}, },
events: { events: {
// 支付宝小程序有些页面事件只能放在events下 // 支付宝小程序有些页面事件只能放在events下
onBack() { onBack() {
this.$vm.$callHook('onBackPress') this.$vm.$callHook(ON_BACK_PRESS)
}, },
}, },
__r: handleRef, __r: handleRef,
......
...@@ -16,6 +16,7 @@ import { ...@@ -16,6 +16,7 @@ import {
import { handleLink as handleBaseLink } from '@dcloudio/uni-mp-weixin' import { handleLink as handleBaseLink } from '@dcloudio/uni-mp-weixin'
import deepEqual from './deepEqual' import deepEqual from './deepEqual'
import { ON_READY } from '@dcloudio/uni-shared'
type MPPageInstance = tinyapp.IPageInstance<Record<string, any>> type MPPageInstance = tinyapp.IPageInstance<Record<string, any>>
export type MPComponentInstance = tinyapp.IComponentInstance< export type MPComponentInstance = tinyapp.IComponentInstance<
...@@ -115,7 +116,7 @@ export function initChildVues( ...@@ -115,7 +116,7 @@ export function initChildVues(
initChildVues(childMPInstance) initChildVues(childMPInstance)
childMPInstance.$vm.$callHook('mounted') childMPInstance.$vm.$callHook('mounted')
childMPInstance.$vm.$callHook('onReady') childMPInstance.$vm.$callHook(ON_READY)
}) })
} }
......
...@@ -2,6 +2,7 @@ import { ...@@ -2,6 +2,7 @@ import {
MiniProgramAppOptions, MiniProgramAppOptions,
MiniProgramAppInstance, MiniProgramAppInstance,
} from '@dcloudio/uni-mp-core' } from '@dcloudio/uni-mp-core'
import { ON_SHOW } from '@dcloudio/uni-shared'
export function parse(appOptions: MiniProgramAppOptions) { export function parse(appOptions: MiniProgramAppOptions) {
// 百度 onShow 竟然会在 onLaunch 之前 // 百度 onShow 竟然会在 onLaunch 之前
...@@ -9,6 +10,6 @@ export function parse(appOptions: MiniProgramAppOptions) { ...@@ -9,6 +10,6 @@ export function parse(appOptions: MiniProgramAppOptions) {
if (!this.$vm) { if (!this.$vm) {
this.onLaunch(args) this.onLaunch(args)
} }
this.$vm!.$callHook('onShow', args) this.$vm!.$callHook(ON_SHOW, args)
} }
} }
import { hasOwn } from '@vue/shared' import { hasOwn } from '@vue/shared'
import { MPComponentInstance, MPComponentOptions } from '@dcloudio/uni-mp-core' import { MPComponentInstance, MPComponentOptions } from '@dcloudio/uni-mp-core'
import { ON_LOAD, ON_SHOW } from '@dcloudio/uni-shared'
export { handleLink, initLifetimes } from '@dcloudio/uni-mp-weixin' export { handleLink, initLifetimes } from '@dcloudio/uni-mp-weixin'
...@@ -35,8 +36,8 @@ export function parse(componentOptions: MPComponentOptions) { ...@@ -35,8 +36,8 @@ export function parse(componentOptions: MPComponentOptions) {
const pageInstance = (this as any).pageinstance const pageInstance = (this as any).pageinstance
pageInstance.$vm = this.$vm pageInstance.$vm = this.$vm
if (hasOwn(pageInstance, '_$args')) { if (hasOwn(pageInstance, '_$args')) {
this.$vm.$callHook('onLoad', pageInstance._$args) this.$vm.$callHook(ON_LOAD, pageInstance._$args)
this.$vm.$callHook('onShow') this.$vm.$callHook(ON_SHOW)
delete pageInstance._$args delete pageInstance._$args
} }
} else { } else {
......
import { MPComponentOptions, MPComponentInstance } from '@dcloudio/uni-mp-core' import { MPComponentOptions, MPComponentInstance } from '@dcloudio/uni-mp-core'
import { ON_LOAD, ON_SHOW } from '@dcloudio/uni-shared'
import { parse as parseComponentOptions } from './parseComponentOptions' import { parse as parseComponentOptions } from './parseComponentOptions'
...@@ -13,7 +14,7 @@ export function parse(pageOptions: MPComponentOptions) { ...@@ -13,7 +14,7 @@ export function parse(pageOptions: MPComponentOptions) {
// 纠正百度小程序生命周期methods:onShow在methods:onLoad之前触发的问题 // 纠正百度小程序生命周期methods:onShow在methods:onLoad之前触发的问题
methods.onShow = function onShow(this: MPComponentInstance) { methods.onShow = function onShow(this: MPComponentInstance) {
if (this.$vm && this._$loaded) { if (this.$vm && this._$loaded) {
this.$vm.$callHook('onShow') this.$vm.$callHook(ON_SHOW)
} }
} }
...@@ -21,8 +22,8 @@ export function parse(pageOptions: MPComponentOptions) { ...@@ -21,8 +22,8 @@ export function parse(pageOptions: MPComponentOptions) {
// 百度 onLoad 在 attached 之前触发,先存储 args, 在 attached 里边触发 onLoad // 百度 onLoad 在 attached 之前触发,先存储 args, 在 attached 里边触发 onLoad
if (this.$vm) { if (this.$vm) {
;(this as any)._$loaded = true ;(this as any)._$loaded = true
this.$vm.$callHook('onLoad', args) this.$vm.$callHook(ON_LOAD, args)
this.$vm.$callHook('onShow') this.$vm.$callHook(ON_SHOW)
} else { } else {
;(this as any).pageinstance._$args = args ;(this as any).pageinstance._$args = args
} }
......
...@@ -5,6 +5,15 @@ import { initBaseInstance } from './componentInstance' ...@@ -5,6 +5,15 @@ import { initBaseInstance } from './componentInstance'
import { initHooks, initUnknownHooks } from './componentHooks' import { initHooks, initUnknownHooks } from './componentHooks'
import App = WechatMiniprogram.App import App = WechatMiniprogram.App
import {
ON_ERROR,
ON_HIDE,
ON_LAUNCH,
ON_PAGE_NOT_FOUND,
ON_SHOW,
ON_THEME_CHANGE,
ON_UNHANDLE_REJECTION,
} from '@dcloudio/uni-shared'
export interface CustomAppInstanceProperty extends Record<string, any> { export interface CustomAppInstanceProperty extends Record<string, any> {
globalData: Record<string, any> globalData: Record<string, any>
$vm?: ComponentPublicInstance $vm?: ComponentPublicInstance
...@@ -14,12 +23,12 @@ export type MiniProgramAppOptions = App.Options<CustomAppInstanceProperty> ...@@ -14,12 +23,12 @@ export type MiniProgramAppOptions = App.Options<CustomAppInstanceProperty>
export type MiniProgramAppInstance = App.Instance<CustomAppInstanceProperty> export type MiniProgramAppInstance = App.Instance<CustomAppInstanceProperty>
const HOOKS = [ const HOOKS = [
'onShow', ON_SHOW,
'onHide', ON_HIDE,
'onError', ON_ERROR,
'onThemeChange', ON_THEME_CHANGE,
'onPageNotFound', ON_PAGE_NOT_FOUND,
'onUnhandledRejection', ON_UNHANDLE_REJECTION,
] ]
export interface ParseAppOptions { export interface ParseAppOptions {
...@@ -48,7 +57,7 @@ function parseApp( ...@@ -48,7 +57,7 @@ function parseApp(
}) })
ctx.globalData = this.globalData ctx.globalData = this.globalData
instance.$callHook('onLaunch', options) instance.$callHook(ON_LAUNCH, options)
}, },
} }
......
import {
ON_ADD_TO_FAVORITES,
ON_HIDE,
ON_LOAD,
ON_PULL_DOWN_REFRESH,
ON_REACH_BOTTOM,
ON_READY,
ON_RESIZE,
ON_SHOW,
ON_TAB_ITEM_TAP,
ON_UNLOAD,
} from '@dcloudio/uni-shared'
import { hasOwn, isFunction } from '@vue/shared' import { hasOwn, isFunction } from '@vue/shared'
import { ComponentOptions } from 'vue' import { ComponentOptions } from 'vue'
...@@ -7,20 +19,18 @@ import { CustomAppInstanceProperty } from './app' ...@@ -7,20 +19,18 @@ import { CustomAppInstanceProperty } from './app'
import { CustomComponentInstanceProperty } from './component' import { CustomComponentInstanceProperty } from './component'
export const PAGE_HOOKS = [ export const PAGE_HOOKS = [
'onLoad', ON_LOAD,
'onShow', ON_SHOW,
ON_HIDE,
ON_UNLOAD,
ON_RESIZE,
ON_TAB_ITEM_TAP,
ON_REACH_BOTTOM,
ON_PULL_DOWN_REFRESH,
ON_ADD_TO_FAVORITES,
// 'onReady', // lifetimes.ready // 'onReady', // lifetimes.ready
'onHide',
'onUnload',
'onResize',
// 'onPageScroll', // 影响性能,开发者手动注册 // 'onPageScroll', // 影响性能,开发者手动注册
'onTabItemTap',
'onReachBottom',
'onPullDownRefresh',
// 'onShareTimeline', // 右上角菜单,开发者手动注册 // 'onShareTimeline', // 右上角菜单,开发者手动注册
'onAddToFavorites',
// 'onShareAppMessage' // 右上角菜单,开发者手动注册 // 'onShareAppMessage' // 右上角菜单,开发者手动注册
] ]
...@@ -65,7 +75,7 @@ function initHook( ...@@ -65,7 +75,7 @@ function initHook(
} }
} }
const EXCLUDE_HOOKS = ['onReady'] const EXCLUDE_HOOKS = [ON_READY]
export function initHooks( export function initHooks(
mpOptions: MiniProgramAppOptions | WechatMiniprogram.Component.MethodOption, mpOptions: MiniProgramAppOptions | WechatMiniprogram.Component.MethodOption,
......
import { ComponentOptions } from 'vue' import { ComponentOptions } from 'vue'
import { stringifyQuery } from '@dcloudio/uni-shared' import { ON_LOAD, stringifyQuery } from '@dcloudio/uni-shared'
import { import {
ParseComponentOptions, ParseComponentOptions,
...@@ -34,7 +34,7 @@ function parsePage( ...@@ -34,7 +34,7 @@ function parsePage(
;(this as any).$page = { ;(this as any).$page = {
fullPath: '/' + (this as any).route + stringifyQuery(query), fullPath: '/' + (this as any).route + stringifyQuery(query),
} }
return this.$vm && this.$vm.$callHook('onLoad', query) return this.$vm && this.$vm.$callHook(ON_LOAD, query)
} }
initHooks(methods, PAGE_HOOKS) initHooks(methods, PAGE_HOOKS)
......
import { ON_LOAD } from '@dcloudio/uni-shared'
import { camelize } from '@vue/shared' import { camelize } from '@vue/shared'
import { MPComponentInstance } from './component' import { MPComponentInstance } from './component'
...@@ -32,7 +33,7 @@ function initHook(name: 'onLoad' | 'created', options: Record<string, any>) { ...@@ -32,7 +33,7 @@ function initHook(name: 'onLoad' | 'created', options: Record<string, any>) {
} }
Page = function (options) { Page = function (options) {
initHook('onLoad', options) initHook(ON_LOAD, options)
return MPPage(options) return MPPage(options)
} }
......
...@@ -9,6 +9,7 @@ import { $destroyComponent } from '@dcloudio/uni-mp-core' ...@@ -9,6 +9,7 @@ import { $destroyComponent } from '@dcloudio/uni-mp-core'
import { initLifetimes as initComponentLifetimes } from './componentLifetimes' import { initLifetimes as initComponentLifetimes } from './componentLifetimes'
import { instances } from './parseComponentOptions' import { instances } from './parseComponentOptions'
import { ON_READY } from '@dcloudio/uni-shared'
export function initLifetimes(lifetimesOptions: CreateLifetimesOptions) { export function initLifetimes(lifetimesOptions: CreateLifetimesOptions) {
return extend(initComponentLifetimes(lifetimesOptions), { return extend(initComponentLifetimes(lifetimesOptions), {
...@@ -19,7 +20,7 @@ export function initLifetimes(lifetimesOptions: CreateLifetimesOptions) { ...@@ -19,7 +20,7 @@ export function initLifetimes(lifetimesOptions: CreateLifetimesOptions) {
} }
this.$vm.$callSyncHook('created') this.$vm.$callSyncHook('created')
this.$vm.$callHook('mounted') this.$vm.$callHook('mounted')
this.$vm.$callHook('onReady') this.$vm.$callHook(ON_READY)
} else { } else {
this.is && console.warn(this.is + ' is not ready') this.is && console.warn(this.is + ' is not ready')
} }
......
...@@ -6,6 +6,7 @@ import { findVmByVueId } from '@dcloudio/uni-mp-core' ...@@ -6,6 +6,7 @@ import { findVmByVueId } from '@dcloudio/uni-mp-core'
import { initInjections, initProvide } from './apiInject' import { initInjections, initProvide } from './apiInject'
import { ParseComponentOptions } from 'packages/uni-mp-core/src/runtime/component' import { ParseComponentOptions } from 'packages/uni-mp-core/src/runtime/component'
import { ON_READY } from '@dcloudio/uni-shared'
export { initLifetimes } from './componentLifetimes' export { initLifetimes } from './componentLifetimes'
...@@ -78,7 +79,7 @@ export function handleLink( ...@@ -78,7 +79,7 @@ export function handleLink(
vm.$callSyncHook('created') vm.$callSyncHook('created')
vm.$callHook('mounted') vm.$callHook('mounted')
vm.$callHook('onReady') vm.$callHook(ON_READY)
} }
export function parse( export function parse(
......
此差异已折叠。
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
$destroyComponent, $destroyComponent,
initComponentInstance, initComponentInstance,
} from '@dcloudio/uni-mp-core' } from '@dcloudio/uni-mp-core'
import { ON_READY } from '@dcloudio/uni-shared'
export function initLifetimes({ export function initLifetimes({
mocks, mocks,
...@@ -59,7 +60,7 @@ export function initLifetimes({ ...@@ -59,7 +60,7 @@ export function initLifetimes({
// https://developers.weixin.qq.com/community/develop/doc/00066ae2844cc0f8eb883e2a557800 // https://developers.weixin.qq.com/community/develop/doc/00066ae2844cc0f8eb883e2a557800
if (this.$vm) { if (this.$vm) {
this.$vm.$callHook('mounted') this.$vm.$callHook('mounted')
this.$vm.$callHook('onReady') this.$vm.$callHook(ON_READY)
} else { } else {
// this.is && console.warn(this.is + ' is not attached') // this.is && console.warn(this.is + ' is not attached')
} }
......
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
initProvide, initProvide,
initInjections, initInjections,
} from '@dcloudio/uni-mp-toutiao' } from '@dcloudio/uni-mp-toutiao'
import { ON_READY } from '@dcloudio/uni-shared'
export { mocks, isPage } from '@dcloudio/uni-mp-baidu' export { mocks, isPage } from '@dcloudio/uni-mp-baidu'
...@@ -68,7 +69,7 @@ export function handleLink( ...@@ -68,7 +69,7 @@ export function handleLink(
delete vm._$childVues delete vm._$childVues
} }
vm.$callHook('mounted') vm.$callHook('mounted')
vm.$callHook('onReady') vm.$callHook(ON_READY)
} }
// 当 parentVm 已经 mounted 时,直接触发,否则延迟 // 当 parentVm 已经 mounted 时,直接触发,否则延迟
if (!parentVm || parentVm.$.isMounted) { if (!parentVm || parentVm.$.isMounted) {
......
...@@ -828,7 +828,40 @@ const UNI_SSR_DATA = 'data'; ...@@ -828,7 +828,40 @@ const UNI_SSR_DATA = 'data';
const UNI_SSR_GLOBAL_DATA = 'globalData'; const UNI_SSR_GLOBAL_DATA = 'globalData';
const SCHEME_RE = /^([a-z-]+:)?\/\//i; const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const DATA_RE = /^data:.*,.*/; const DATA_RE = /^data:.*,.*/;
const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE'; const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE';
// lifecycle
// App and Page
const ON_SHOW = 'onShow';
const ON_HIDE = 'onHide';
//App
const ON_LAUNCH = 'onLaunch';
const ON_ERROR = 'onError';
const ON_THEME_CHANGE = 'onThemeChange';
const ON_PAGE_NOT_FOUND = 'onPageNotFound';
const ON_UNHANDLE_REJECTION = 'onUnhandledRejection';
//Page
const ON_LOAD = 'onLoad';
const ON_READY = 'onReady';
const ON_UNLOAD = 'onUnload';
const ON_RESIZE = 'onResize';
const ON_BACK_PRESS = 'onBackPress';
const ON_PAGE_SCROLL = 'onPageScroll';
const ON_TAB_ITEM_TAP = 'onTabItemTap';
const ON_REACH_BOTTOM = 'onReachBottom';
const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh';
const ON_SHARE_TIMELINE = 'onShareTimeline';
const ON_ADD_TO_FAVORITES = 'onAddToFavorites';
const ON_SHARE_APP_MESSAGE = 'onShareAppMessage';
// navigationBar
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed';
const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged';
// framework
const ON_APP_ENTER_FOREGROUND = 'onAppEnterForeground';
const ON_APP_ENTER_BACKGROUND = 'onAppEnterBackground';
const ON_WEB_INVOKE_APP_SERVICE = 'onWebInvokeAppService';
function getEnvLocale() { function getEnvLocale() {
const { env } = process; const { env } = process;
...@@ -861,7 +894,34 @@ exports.NODE_TYPE_COMMENT = NODE_TYPE_COMMENT; ...@@ -861,7 +894,34 @@ exports.NODE_TYPE_COMMENT = NODE_TYPE_COMMENT;
exports.NODE_TYPE_ELEMENT = NODE_TYPE_ELEMENT; exports.NODE_TYPE_ELEMENT = NODE_TYPE_ELEMENT;
exports.NODE_TYPE_PAGE = NODE_TYPE_PAGE; exports.NODE_TYPE_PAGE = NODE_TYPE_PAGE;
exports.NODE_TYPE_TEXT = NODE_TYPE_TEXT; exports.NODE_TYPE_TEXT = NODE_TYPE_TEXT;
exports.ON_ADD_TO_FAVORITES = ON_ADD_TO_FAVORITES;
exports.ON_APP_ENTER_BACKGROUND = ON_APP_ENTER_BACKGROUND;
exports.ON_APP_ENTER_FOREGROUND = ON_APP_ENTER_FOREGROUND;
exports.ON_BACK_PRESS = ON_BACK_PRESS;
exports.ON_ERROR = ON_ERROR;
exports.ON_HIDE = ON_HIDE;
exports.ON_LAUNCH = ON_LAUNCH;
exports.ON_LOAD = ON_LOAD;
exports.ON_NAVIGATION_BAR_BUTTON_TAP = ON_NAVIGATION_BAR_BUTTON_TAP;
exports.ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED;
exports.ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED;
exports.ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED;
exports.ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED;
exports.ON_PAGE_NOT_FOUND = ON_PAGE_NOT_FOUND;
exports.ON_PAGE_SCROLL = ON_PAGE_SCROLL;
exports.ON_PULL_DOWN_REFRESH = ON_PULL_DOWN_REFRESH;
exports.ON_REACH_BOTTOM = ON_REACH_BOTTOM;
exports.ON_REACH_BOTTOM_DISTANCE = ON_REACH_BOTTOM_DISTANCE; exports.ON_REACH_BOTTOM_DISTANCE = ON_REACH_BOTTOM_DISTANCE;
exports.ON_READY = ON_READY;
exports.ON_RESIZE = ON_RESIZE;
exports.ON_SHARE_APP_MESSAGE = ON_SHARE_APP_MESSAGE;
exports.ON_SHARE_TIMELINE = ON_SHARE_TIMELINE;
exports.ON_SHOW = ON_SHOW;
exports.ON_TAB_ITEM_TAP = ON_TAB_ITEM_TAP;
exports.ON_THEME_CHANGE = ON_THEME_CHANGE;
exports.ON_UNHANDLE_REJECTION = ON_UNHANDLE_REJECTION;
exports.ON_UNLOAD = ON_UNLOAD;
exports.ON_WEB_INVOKE_APP_SERVICE = ON_WEB_INVOKE_APP_SERVICE;
exports.PLUS_RE = PLUS_RE; exports.PLUS_RE = PLUS_RE;
exports.PRIMARY_COLOR = PRIMARY_COLOR; exports.PRIMARY_COLOR = PRIMARY_COLOR;
exports.RESPONSIVE_MIN_WIDTH = RESPONSIVE_MIN_WIDTH; exports.RESPONSIVE_MIN_WIDTH = RESPONSIVE_MIN_WIDTH;
......
...@@ -185,8 +185,62 @@ export declare function normalizeTarget(el: HTMLElement): { ...@@ -185,8 +185,62 @@ export declare function normalizeTarget(el: HTMLElement): {
offsetLeft: number; offsetLeft: number;
}; };
export declare const ON_ADD_TO_FAVORITES = "onAddToFavorites";
export declare const ON_APP_ENTER_BACKGROUND = "onAppEnterBackground";
export declare const ON_APP_ENTER_FOREGROUND = "onAppEnterForeground";
export declare const ON_BACK_PRESS = "onBackPress";
export declare const ON_ERROR = "onError";
export declare const ON_HIDE = "onHide";
export declare const ON_LAUNCH = "onLaunch";
export declare const ON_LOAD = "onLoad";
export declare const ON_NAVIGATION_BAR_BUTTON_TAP = "onNavigationBarButtonTap";
export declare const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = "onNavigationBarSearchInputChanged";
export declare const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = "onNavigationBarSearchInputClicked";
export declare const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = "onNavigationBarSearchInputConfirmed";
export declare const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = "onNavigationBarSearchInputFocusChanged";
export declare const ON_PAGE_NOT_FOUND = "onPageNotFound";
export declare const ON_PAGE_SCROLL = "onPageScroll";
export declare const ON_PULL_DOWN_REFRESH = "onPullDownRefresh";
export declare const ON_REACH_BOTTOM = "onReachBottom";
export declare const ON_REACH_BOTTOM_DISTANCE = 50; export declare const ON_REACH_BOTTOM_DISTANCE = 50;
export declare const ON_READY = "onReady";
export declare const ON_RESIZE = "onResize";
export declare const ON_SHARE_APP_MESSAGE = "onShareAppMessage";
export declare const ON_SHARE_TIMELINE = "onShareTimeline";
export declare const ON_SHOW = "onShow";
export declare const ON_TAB_ITEM_TAP = "onTabItemTap";
export declare const ON_THEME_CHANGE = "onThemeChange";
export declare const ON_UNHANDLE_REJECTION = "onUnhandledRejection";
export declare const ON_UNLOAD = "onUnload";
export declare const ON_WEB_INVOKE_APP_SERVICE = "onWebInvokeAppService";
export declare function once<T extends (...args: any[]) => any>(fn: T, ctx?: unknown): T; export declare function once<T extends (...args: any[]) => any>(fn: T, ctx?: unknown): T;
declare interface Options { declare interface Options {
......
...@@ -824,7 +824,40 @@ const UNI_SSR_DATA = 'data'; ...@@ -824,7 +824,40 @@ const UNI_SSR_DATA = 'data';
const UNI_SSR_GLOBAL_DATA = 'globalData'; const UNI_SSR_GLOBAL_DATA = 'globalData';
const SCHEME_RE = /^([a-z-]+:)?\/\//i; const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const DATA_RE = /^data:.*,.*/; const DATA_RE = /^data:.*,.*/;
const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE'; const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE';
// lifecycle
// App and Page
const ON_SHOW = 'onShow';
const ON_HIDE = 'onHide';
//App
const ON_LAUNCH = 'onLaunch';
const ON_ERROR = 'onError';
const ON_THEME_CHANGE = 'onThemeChange';
const ON_PAGE_NOT_FOUND = 'onPageNotFound';
const ON_UNHANDLE_REJECTION = 'onUnhandledRejection';
//Page
const ON_LOAD = 'onLoad';
const ON_READY = 'onReady';
const ON_UNLOAD = 'onUnload';
const ON_RESIZE = 'onResize';
const ON_BACK_PRESS = 'onBackPress';
const ON_PAGE_SCROLL = 'onPageScroll';
const ON_TAB_ITEM_TAP = 'onTabItemTap';
const ON_REACH_BOTTOM = 'onReachBottom';
const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh';
const ON_SHARE_TIMELINE = 'onShareTimeline';
const ON_ADD_TO_FAVORITES = 'onAddToFavorites';
const ON_SHARE_APP_MESSAGE = 'onShareAppMessage';
// navigationBar
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed';
const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged';
// framework
const ON_APP_ENTER_FOREGROUND = 'onAppEnterForeground';
const ON_APP_ENTER_BACKGROUND = 'onAppEnterBackground';
const ON_WEB_INVOKE_APP_SERVICE = 'onWebInvokeAppService';
function getEnvLocale() { function getEnvLocale() {
const { env } = process; const { env } = process;
...@@ -832,4 +865,4 @@ function getEnvLocale() { ...@@ -832,4 +865,4 @@ function getEnvLocale() {
return (lang && lang.replace(/[.:].*/, '')) || 'en'; return (lang && lang.replace(/[.:].*/, '')) || 'en';
} }
export { ACTION_TYPE_ADD_EVENT, ACTION_TYPE_CREATE, ACTION_TYPE_EVENT, ACTION_TYPE_INSERT, ACTION_TYPE_PAGE_CREATE, ACTION_TYPE_PAGE_CREATED, ACTION_TYPE_REMOVE, ACTION_TYPE_REMOVE_ATTRIBUTE, ACTION_TYPE_REMOVE_EVENT, ACTION_TYPE_SET_ATTRIBUTE, ACTION_TYPE_SET_TEXT, ATTR_CLASS, ATTR_STYLE, BACKGROUND_COLOR, BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, DATA_RE, EventModifierFlags, NAVBAR_HEIGHT, NODE_TYPE_COMMENT, NODE_TYPE_ELEMENT, NODE_TYPE_PAGE, NODE_TYPE_TEXT, ON_REACH_BOTTOM_DISTANCE, PLUS_RE, PRIMARY_COLOR, RESPONSIVE_MIN_WIDTH, SCHEME_RE, SELECTED_COLOR, TABBAR_HEIGHT, TAGS, UNI_SSR, UNI_SSR_DATA, UNI_SSR_GLOBAL_DATA, UNI_SSR_STORE, UNI_SSR_TITLE, UniBaseNode, UniCommentNode, UniElement, UniEvent, UniInputElement, UniNode, UniTextAreaElement, UniTextNode, WEB_INVOKE_APPSERVICE, addFont, cache, cacheStringFunction, callOptions, createRpx2Unit, debounce, decode, decodedQuery, defaultRpx2Unit, formatDateTime, formatLog, getCustomDataset, getEnvLocale, getLen, initCustomDataset, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, isServiceCustomElement, isServiceNativeTag, normalizeDataset, normalizeEventType, normalizeTarget, once, parseEventName, parseQuery, parseUrl, passive, plusReady, removeLeadingSlash, sanitise, scrollTo, stringifyQuery, updateElementStyle }; export { ACTION_TYPE_ADD_EVENT, ACTION_TYPE_CREATE, ACTION_TYPE_EVENT, ACTION_TYPE_INSERT, ACTION_TYPE_PAGE_CREATE, ACTION_TYPE_PAGE_CREATED, ACTION_TYPE_REMOVE, ACTION_TYPE_REMOVE_ATTRIBUTE, ACTION_TYPE_REMOVE_EVENT, ACTION_TYPE_SET_ATTRIBUTE, ACTION_TYPE_SET_TEXT, ATTR_CLASS, ATTR_STYLE, BACKGROUND_COLOR, BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, DATA_RE, EventModifierFlags, NAVBAR_HEIGHT, NODE_TYPE_COMMENT, NODE_TYPE_ELEMENT, NODE_TYPE_PAGE, NODE_TYPE_TEXT, ON_ADD_TO_FAVORITES, ON_APP_ENTER_BACKGROUND, ON_APP_ENTER_FOREGROUND, ON_BACK_PRESS, ON_ERROR, ON_HIDE, ON_LAUNCH, ON_LOAD, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, ON_PAGE_NOT_FOUND, ON_PAGE_SCROLL, ON_PULL_DOWN_REFRESH, ON_REACH_BOTTOM, ON_REACH_BOTTOM_DISTANCE, ON_READY, ON_RESIZE, ON_SHARE_APP_MESSAGE, ON_SHARE_TIMELINE, ON_SHOW, ON_TAB_ITEM_TAP, ON_THEME_CHANGE, ON_UNHANDLE_REJECTION, ON_UNLOAD, ON_WEB_INVOKE_APP_SERVICE, PLUS_RE, PRIMARY_COLOR, RESPONSIVE_MIN_WIDTH, SCHEME_RE, SELECTED_COLOR, TABBAR_HEIGHT, TAGS, UNI_SSR, UNI_SSR_DATA, UNI_SSR_GLOBAL_DATA, UNI_SSR_STORE, UNI_SSR_TITLE, UniBaseNode, UniCommentNode, UniElement, UniEvent, UniInputElement, UniNode, UniTextAreaElement, UniTextNode, WEB_INVOKE_APPSERVICE, addFont, cache, cacheStringFunction, callOptions, createRpx2Unit, debounce, decode, decodedQuery, defaultRpx2Unit, formatDateTime, formatLog, getCustomDataset, getEnvLocale, getLen, initCustomDataset, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, isServiceCustomElement, isServiceNativeTag, normalizeDataset, normalizeEventType, normalizeTarget, once, parseEventName, parseQuery, parseUrl, passive, plusReady, removeLeadingSlash, sanitise, scrollTo, stringifyQuery, updateElementStyle };
...@@ -19,3 +19,46 @@ export const SCHEME_RE = /^([a-z-]+:)?\/\//i ...@@ -19,3 +19,46 @@ export const SCHEME_RE = /^([a-z-]+:)?\/\//i
export const DATA_RE = /^data:.*,.*/ export const DATA_RE = /^data:.*,.*/
export const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE' export const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE'
// lifecycle
// App and Page
export const ON_SHOW = 'onShow'
export const ON_HIDE = 'onHide'
//App
export const ON_LAUNCH = 'onLaunch'
export const ON_ERROR = 'onError'
export const ON_THEME_CHANGE = 'onThemeChange'
export const ON_PAGE_NOT_FOUND = 'onPageNotFound'
export const ON_UNHANDLE_REJECTION = 'onUnhandledRejection'
//Page
export const ON_LOAD = 'onLoad'
export const ON_READY = 'onReady'
export const ON_UNLOAD = 'onUnload'
export const ON_RESIZE = 'onResize'
export const ON_BACK_PRESS = 'onBackPress'
export const ON_PAGE_SCROLL = 'onPageScroll'
export const ON_TAB_ITEM_TAP = 'onTabItemTap'
export const ON_REACH_BOTTOM = 'onReachBottom'
export const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh'
export const ON_SHARE_TIMELINE = 'onShareTimeline'
export const ON_ADD_TO_FAVORITES = 'onAddToFavorites'
export const ON_SHARE_APP_MESSAGE = 'onShareAppMessage'
// navigationBar
export const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap'
export const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED =
'onNavigationBarSearchInputClicked'
export const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED =
'onNavigationBarSearchInputChanged'
export const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED =
'onNavigationBarSearchInputConfirmed'
export const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED =
'onNavigationBarSearchInputFocusChanged'
// framework
export const ON_APP_ENTER_FOREGROUND = 'onAppEnterForeground'
export const ON_APP_ENTER_BACKGROUND = 'onAppEnterBackground'
export const ON_WEB_INVOKE_APP_SERVICE = 'onWebInvokeAppService'
import { invokeHook } from '@dcloudio/uni-core' import { invokeHook } from '@dcloudio/uni-core'
import { ON_ERROR } from '@dcloudio/uni-shared'
import { ComponentPublicInstance } from 'vue' import { ComponentPublicInstance } from 'vue'
export function errorHandler( export function errorHandler(
...@@ -14,8 +15,8 @@ export function errorHandler( ...@@ -14,8 +15,8 @@ export function errorHandler(
throw err throw err
} }
if (__PLATFORM__ !== 'h5' && __PLATFORM__ !== 'app') { if (__PLATFORM__ !== 'h5' && __PLATFORM__ !== 'app') {
app.$vm.$callHook('onError', err, info) app.$vm.$callHook(ON_ERROR, err, info)
} else { } else {
invokeHook(app.$vm, 'onError', err) invokeHook(app.$vm, ON_ERROR, err)
} }
} }
import { invokeHook } from '@dcloudio/uni-core' import { invokeHook } from '@dcloudio/uni-core'
import { ON_LOAD, ON_SHOW } from '@dcloudio/uni-shared'
import { isFunction } from '@vue/shared' import { isFunction } from '@vue/shared'
import { import {
...@@ -27,7 +28,7 @@ export function applyOptions( ...@@ -27,7 +28,7 @@ export function applyOptions(
} }
}) })
if (__PLATFORM__ === 'app' && publicThis.$mpType === 'page') { if (__PLATFORM__ === 'app' && publicThis.$mpType === 'page') {
invokeHook(publicThis, 'onLoad', instance.attrs.__pageQuery) invokeHook(publicThis, ON_LOAD, instance.attrs.__pageQuery)
invokeHook(publicThis, 'onShow') invokeHook(publicThis, ON_SHOW)
} }
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册