提交 17cf413c 编写于 作者: fxy060608's avatar fxy060608

wip(app): uni-app-plus

上级 b2709b64
......@@ -86,7 +86,7 @@
"semver": "^7.3.4",
"ts-jest": "^27.0.3",
"typescript": "~4.1.3",
"vite": "^2.4.0-beta.3",
"vite": "^2.4.0",
"vue": "^3.1.2",
"yorkie": "^2.0.0"
},
......
......@@ -31,6 +31,6 @@
"compression": "^1.7.4",
"cypress": "^7.3.0",
"serve-static": "^1.14.1",
"vite": "^2.4.0-beta.3"
"vite": "^2.4.0"
}
}
......@@ -800,9 +800,9 @@ ee-first@1.1.1:
integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=
electron-to-chromium@^1.3.723:
version "1.3.766"
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.766.tgz#2fd14a4e54f77665872f4e23fcf4968e83638220"
integrity sha512-u2quJ862q9reRKh/je3GXis3w38+RoXH1J9N3XjtsS6NzmUAosNsyZgUVFZPN/ZlJ3v6T0rTyZR3q/J5c6Sy5w==
version "1.3.768"
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.768.tgz#bbe47394f0073c947168589b7d19388518a7a9a9"
integrity sha512-I4UMZHhVSK2pwt8jOIxTi3GIuc41NkddtKT/hpuxp9GO5UWJgDKTBa4TACppbVAuKtKbMK6BhQZvT5tFF1bcNA==
emoji-regex@^8.0.0:
version "8.0.0"
......@@ -2243,10 +2243,10 @@ verror@1.10.0:
core-util-is "1.0.2"
extsprintf "^1.2.0"
vite@^2.4.0-beta.3:
version "2.4.0-beta.3"
resolved "https://registry.yarnpkg.com/vite/-/vite-2.4.0-beta.3.tgz#81da5e6cbfb4cb710610e5757567cbe58b667c44"
integrity sha512-sSUbH0mPMbqqOVZ1/LD/Wiu347yvn4BXjS/94mn5Q7E/zd50hxEnKU1NC4x59TBKq5OeboPhyXwibyCEpyAQKQ==
vite@^2.4.0:
version "2.4.0"
resolved "https://registry.yarnpkg.com/vite/-/vite-2.4.0.tgz#a591e4f2c996ae9a044093f629b418069629ca16"
integrity sha512-FR+1hCyGt8i+ijMe9z4tIfUQ7BQThxGevp3IlmdXDBSJEPjbeDznbuJa/QVzXw2Mpxh7KCmveVI082h8nzcCNw==
dependencies:
esbuild "^0.12.8"
postcss "^8.3.5"
......
import { inspect } from 'util'
import { decodeActions } from '../../../src/service/framework/dom/decodeActions'
describe('decode', () => {
test('actions', () => {
console.log(
inspect(
decodeActions([
[3, 1, 4],
[3, 2, 4],
[4, 1, 0, -1, { a: {}, t: '' }],
[4, 2, 0, -1, { a: {}, t: '' }],
[3, 3, 1],
[4, 3, 0, 2, { a: { '.c': 'content' }, t: '123' }],
[3, 4, 1],
[4, 4, 0, 2, { a: { '.c': 'title' }, t: '456' }],
[2],
]),
{ colors: true, depth: null }
)
)
})
})
......@@ -16,6 +16,7 @@ import {
describe('dom', () => {
const pageId = 1
const root = createPageNode(pageId, {
css: true,
route: 'pages/index/index',
version: 1,
locale: 'zh_CN',
......@@ -37,7 +38,7 @@ describe('dom', () => {
expect(addElementAction[0]).toBe(ACTION_TYPE_INSERT)
expect(addElementAction[1]).toBe(1) // nodeId
expect(addElementAction[2]).toBe(0) // parentNodeId
expect(addElementAction[3]).toBe(0) // index
expect(addElementAction[3]).toBe(-1) // index
const elementJson = addElementAction[4] as UniNodeJSON
expect(elementJson.a.id).toBe('view')
......@@ -72,7 +73,6 @@ describe('dom', () => {
} = root
expect(removeChildAction[0]).toBe(ACTION_TYPE_REMOVE)
expect(removeChildAction[1]).toBe(1)
expect(removeChildAction[2]).toBe(0)
root.updateActions.length = 0
const textNode = createTextNode('hello')
......@@ -83,7 +83,7 @@ describe('dom', () => {
expect(addTextNodeAction[0]).toBe(ACTION_TYPE_INSERT)
expect(addTextNodeAction[1]).toBe(2)
expect(addTextNodeAction[2]).toBe(0)
expect(addTextNodeAction[3]).toBe(0)
expect(addTextNodeAction[3]).toBe(-1)
const textNodeJson = addTextNodeAction[4] as UniNodeJSON
expect(textNodeJson.t).toBe('hello')
......
......@@ -11,6 +11,7 @@ import {
import { createPageNode } from '../../src/service/framework/dom/Page'
const defaultPageNodeOptions = {
css: true,
route: 'pages/index/index',
version: 1,
locale: 'zh_CN',
......
......@@ -663,6 +663,9 @@ var serviceContext = (function (vue) {
dispatchEvent(evt) {
const listeners = this._listeners[evt.type];
if (!listeners) {
if ((process.env.NODE_ENV !== 'production')) {
console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found');
}
return false;
}
const len = listeners.length;
......@@ -695,7 +698,7 @@ var serviceContext = (function (vue) {
listeners.splice(index, 1);
}
}
}
}
const COMPONENT_MAP = {
VIEW: 1,
IMAGE: 2,
......@@ -839,20 +842,18 @@ var serviceContext = (function (vue) {
newChild.parentNode = this;
checkNodeId(newChild);
const { childNodes } = this;
let index;
if (refChild) {
index = childNodes.indexOf(refChild);
const index = childNodes.indexOf(refChild);
if (index === -1) {
throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`);
}
childNodes.splice(index, 0, newChild);
}
else {
index = childNodes.length;
childNodes.push(newChild);
}
return this.pageNode
? this.pageNode.onInsertBefore(this, newChild, index)
? this.pageNode.onInsertBefore(this, newChild, refChild)
: newChild;
}
removeChild(oldChild) {
......@@ -863,9 +864,7 @@ var serviceContext = (function (vue) {
}
oldChild.parentNode = null;
childNodes.splice(index, 1);
return this.pageNode
? this.pageNode.onRemoveChild(this, oldChild)
: oldChild;
return this.pageNode ? this.pageNode.onRemoveChild(oldChild) : oldChild;
}
}
......@@ -1233,6 +1232,26 @@ var serviceContext = (function (vue) {
return res;
}, {});
}
const initI18nAppMsgsOnce = /*#__PURE__*/ once(() => {
const name = 'uni.app.';
{
useI18n().add(LOCALE_EN, normalizeMessages(name, { quit: 'Press back button again to exit' }));
}
{
useI18n().add(LOCALE_ES, normalizeMessages(name, { quit: 'Pulse otra vez para salir' }));
}
{
useI18n().add(LOCALE_FR, normalizeMessages(name, {
quit: "Appuyez à nouveau pour quitter l'application",
}));
}
{
useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, { quit: '再按一次退出应用' }));
}
{
useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, { quit: '再按一次退出應用' }));
}
});
const initI18nShowActionSheetMsgsOnce = /*#__PURE__*/ once(() => {
const name = 'uni.showActionSheet.';
{
......@@ -2337,6 +2356,7 @@ var serviceContext = (function (vue) {
const API_NAVIGATE_TO = 'navigateTo';
const API_REDIRECT_TO = 'redirectTo';
const API_SWITCH_TAB = 'switchTab';
const API_NAVIGATE_BACK = 'navigateBack';
const API_PRELOAD_PAGE = 'preloadPage';
const API_UN_PRELOAD_PAGE = 'unPreloadPage';
const NavigateToProtocol =
......@@ -5780,6 +5800,39 @@ var serviceContext = (function (vue) {
const VD_SYNC = 'vdSync';
const ON_WEBVIEW_READY = 'onWebviewReady';
const ACTION_TYPE_PAGE_CREATE = 1;
const ACTION_TYPE_PAGE_CREATED = 2;
const ACTION_TYPE_CREATE = 3;
const ACTION_TYPE_INSERT = 4;
const ACTION_TYPE_REMOVE = 5;
const ACTION_TYPE_SET_ATTRIBUTE = 6;
const ACTION_TYPE_REMOVE_ATTRIBUTE = 7;
const ACTION_TYPE_SET_TEXT = 8;
const ACTION_TYPE_EVENT = 20;
function onNodeEvent(nodeId, evt, pageNode) {
pageNode.fireEvent(nodeId, evt);
}
function onVdSync(actions, pageId) {
const page = getPageById(parseInt(pageId));
if (!page) {
if ((process.env.NODE_ENV !== 'production')) {
console.error(formatLog('onVdSync', 'page', pageId, 'not found'));
}
return;
}
const pageNode = page.$.appContext.app
._container;
actions.forEach((action) => {
switch (action[0]) {
case ACTION_TYPE_EVENT:
onNodeEvent(action[1], action[2], pageNode);
break;
}
});
}
function initNVue(webviewStyle, routeMeta, path) {
if (path && routeMeta.isNVue) {
webviewStyle.uniNView = {
......@@ -6095,6 +6148,7 @@ var serviceContext = (function (vue) {
if (__uniConfig.renderer !== 'native') {
// 非纯原生
subscribe(ON_WEBVIEW_READY, subscribeWebviewReady);
subscribe(VD_SYNC, onVdSync);
}
}
......@@ -6654,19 +6708,11 @@ var serviceContext = (function (vue) {
}, delay);
}
const ACTION_TYPE_PAGE_CREATE = 1;
const ACTION_TYPE_PAGE_CREATED = 2;
const ACTION_TYPE_CREATE = 3;
const ACTION_TYPE_INSERT = 4;
const ACTION_TYPE_REMOVE = 5;
const ACTION_TYPE_SET_ATTRIBUTE = 6;
const ACTION_TYPE_REMOVE_ATTRIBUTE = 7;
const ACTION_TYPE_SET_TEXT = 8;
class UniPageNode extends UniNode {
constructor(pageId, options, setup = false) {
super(NODE_TYPE_PAGE, '#page', null);
this._id = 1;
this._created = false;
this.updateActions = [];
this.nodeId = 0;
this.pageId = pageId;
......@@ -6680,12 +6726,12 @@ var serviceContext = (function (vue) {
pushCreateAction(this, thisNode.nodeId, nodeName);
return thisNode;
}
onInsertBefore(thisNode, newChild, index) {
pushInsertAction(this, newChild, thisNode.nodeId, index);
onInsertBefore(thisNode, newChild, refChild) {
pushInsertAction(this, newChild, thisNode.nodeId, (refChild && refChild.nodeId) || -1);
return newChild;
}
onRemoveChild(thisNode, oldChild) {
pushRemoveAction(this, oldChild.nodeId, thisNode.nodeId);
onRemoveChild(oldChild) {
pushRemoveAction(this, oldChild.nodeId);
return oldChild;
}
onSetAttribute(thisNode, qualifiedName, value) {
......@@ -6736,6 +6782,11 @@ var serviceContext = (function (vue) {
if ((process.env.NODE_ENV !== 'production')) {
console.log(formatLog('PageNode', 'update', updateActions.length));
}
// 首次
if (!this._created) {
this._created = true;
updateActions.push(this.createdAction);
}
if (updateActions.length) {
this.send(updateActions);
updateActions.length = 0;
......@@ -6744,21 +6795,43 @@ var serviceContext = (function (vue) {
send(action) {
UniServiceJSBridge.publishHandler(VD_SYNC, action, this.pageId);
}
fireEvent(id, evt) {
const node = findNodeById(id, this);
if (node) {
node.dispatchEvent(evt);
}
else if ((process.env.NODE_ENV !== 'production')) {
console.error(formatLog('PageNode', 'fireEvent', id, 'not found', evt));
}
}
}
function findNodeById(id, uniNode) {
if (uniNode.nodeId === id) {
return uniNode;
}
const { childNodes } = uniNode;
for (let i = 0; i < childNodes.length; i++) {
const uniNode = findNodeById(id, childNodes[i]);
if (uniNode) {
return uniNode;
}
}
return null;
}
function pushCreateAction(pageNode, nodeId, nodeName) {
pageNode.push([ACTION_TYPE_CREATE, nodeId, nodeName]);
}
function pushInsertAction(pageNode, newChild, parentNodeId, index) {
function pushInsertAction(pageNode, newChild, parentNodeId, refChildId) {
pageNode.push([
ACTION_TYPE_INSERT,
newChild.nodeId,
parentNodeId,
index,
refChildId,
newChild.toJSON({ attr: true }),
]);
}
function pushRemoveAction(pageNode, nodeId, parentNodeId) {
pageNode.push([ACTION_TYPE_REMOVE, nodeId, parentNodeId]);
function pushRemoveAction(pageNode, nodeId) {
pageNode.push([ACTION_TYPE_REMOVE, nodeId]);
}
function pushSetAttributeAction(pageNode, nodeId, name, value) {
pageNode.push([ACTION_TYPE_SET_ATTRIBUTE, nodeId, name, value]);
......@@ -6902,6 +6975,7 @@ var serviceContext = (function (vue) {
function initPageOptions({ meta }) {
const statusbarHeight = getStatusbarHeight();
return {
css: true,
route: meta.route,
version: 1,
locale: '',
......@@ -6956,6 +7030,31 @@ var serviceContext = (function (vue) {
];
}
const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, (args, { resolve, reject }) => {
const page = getCurrentPage();
if (!page) {
return;
}
if (page.$page.meta.isQuit) {
quit();
}
return resolve();
});
let firstBackTime = 0;
function quit() {
initI18nAppMsgsOnce();
if (!firstBackTime) {
firstBackTime = Date.now();
plus.nativeUI.toast(useI18n().t('uni.app.quit'));
setTimeout(() => {
firstBackTime = 0;
}, 2000);
}
else if (Date.now() - firstBackTime < 2000) {
plus.runtime.quit();
}
}
var uni$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
setStorageSync: setStorageSync,
......@@ -7060,7 +7159,8 @@ var serviceContext = (function (vue) {
createFullScreenVideoAd: createFullScreenVideoAd,
createInterstitialAd: createInterstitialAd,
createInteractiveAd: createInteractiveAd,
navigateTo: navigateTo
navigateTo: navigateTo,
navigateBack: navigateBack
});
const UniServiceJSBridge$1 = /*#__PURE__*/ extend(ServiceJSBridge, {
......
......@@ -821,6 +821,31 @@
function formatLog(module, ...args) {
return `[${Date.now()}][${module}]\uFF1A${args.map((arg) => JSON.stringify(arg)).join(" ")}`;
}
function getCustomDataset(el) {
return extend({}, el.dataset, el.__uniDataset);
}
function normalizeTarget(el) {
const { id, offsetTop, offsetLeft } = el;
return {
id,
dataset: getCustomDataset(el),
offsetTop,
offsetLeft
};
}
const optionsModifierRE$1 = /(?:Once|Passive|Capture)$/;
function parseEventName(name) {
let options;
if (optionsModifierRE$1.test(name)) {
options = {};
let m;
while (m = name.match(optionsModifierRE$1)) {
name = name.slice(0, name.length - m[0].length);
options[m[0].toLowerCase()] = true;
}
}
return [hyphenate(name.slice(2)), options];
}
const ATTR_MAP = {
class: ".c",
style: ".s",
......@@ -840,51 +865,6 @@
onAnimationend: ".ed",
onTouchforcechange: ".ee"
};
const COMPONENT_MAP = {
VIEW: 1,
IMAGE: 2,
TEXT: 3,
"#text": 4,
"#comment": 5,
NAVIGATOR: 6,
FORM: 7,
BUTTON: 8,
INPUT: 9,
LABEL: 10,
RADIO: 11,
CHECKBOX: 12,
"CHECKBOX-GROUP": 13,
AD: 14,
AUDIO: 15,
CAMERA: 16,
CANVAS: 17,
"COVER-IMAGE": 18,
"COVER-VIEW": 19,
EDITOR: 20,
"FUNCTIONAL-PAGE-NAVIGATOR": 21,
ICON: 22,
"RADIO-GROUP": 23,
"LIVE-PLAYER": 24,
"LIVE-PUSHER": 25,
MAP: 26,
"MOVABLE-AREA": 27,
"MOVABLE-VIEW": 28,
"OFFICIAL-ACCOUNT": 29,
"OPEN-DATA": 30,
PICKER: 31,
"PICKER-VIEW": 32,
"PICKER-VIEW-COLUMN": 33,
PROGRESS: 34,
"RICH-TEXT": 35,
"SCROLL-VIEW": 36,
SLIDER: 37,
SWIPER: 38,
"SWIPER-ITEM": 39,
SWITCH: 40,
TEXTAREA: 41,
VIDEO: 42,
"WEB-VIEW": 43
};
const DECODED_ATTR_MAP = /* @__PURE__ */ Object.keys(ATTR_MAP).reduce((map, name) => {
map[ATTR_MAP[name]] = name;
return map;
......@@ -892,13 +872,6 @@
function decodeAttr(name) {
return DECODED_ATTR_MAP[name] || name;
}
const DECODED_COMPONENT_ARR = /* @__PURE__ */ Object.keys(COMPONENT_MAP).reduce((arr, name) => {
arr.push(name.toLowerCase());
return arr;
}, [""]);
function decodeTag(tag) {
return DECODED_COMPONENT_ARR[tag] || tag;
}
const E = function() {
};
E.prototype = {
......@@ -2166,6 +2139,205 @@
return key in el;
}
extend({ patchProp, forcePatchProp }, nodeOps);
var attrs = ["top", "left", "right", "bottom"];
var inited;
var elementComputedStyle = {};
var support;
function getSupport() {
if (!("CSS" in window) || typeof CSS.supports != "function") {
support = "";
} else if (CSS.supports("top: env(safe-area-inset-top)")) {
support = "env";
} else if (CSS.supports("top: constant(safe-area-inset-top)")) {
support = "constant";
} else {
support = "";
}
return support;
}
function init() {
support = typeof support === "string" ? support : getSupport();
if (!support) {
attrs.forEach(function(attr) {
elementComputedStyle[attr] = 0;
});
return;
}
function setStyle2(el, style) {
var elStyle = el.style;
Object.keys(style).forEach(function(key) {
var val = style[key];
elStyle[key] = val;
});
}
var cbs = [];
function parentReady(callback) {
if (callback) {
cbs.push(callback);
} else {
cbs.forEach(function(cb) {
cb();
});
}
}
var passiveEvents = false;
try {
var opts = Object.defineProperty({}, "passive", {
get: function() {
passiveEvents = { passive: true };
}
});
window.addEventListener("test", null, opts);
} catch (e) {
}
function addChild(parent, attr) {
var a1 = document.createElement("div");
var a2 = document.createElement("div");
var a1Children = document.createElement("div");
var a2Children = document.createElement("div");
var W = 100;
var MAX = 1e4;
var aStyle = {
position: "absolute",
width: W + "px",
height: "200px",
boxSizing: "border-box",
overflow: "hidden",
paddingBottom: support + "(safe-area-inset-" + attr + ")"
};
setStyle2(a1, aStyle);
setStyle2(a2, aStyle);
setStyle2(a1Children, {
transition: "0s",
animation: "none",
width: "400px",
height: "400px"
});
setStyle2(a2Children, {
transition: "0s",
animation: "none",
width: "250%",
height: "250%"
});
a1.appendChild(a1Children);
a2.appendChild(a2Children);
parent.appendChild(a1);
parent.appendChild(a2);
parentReady(function() {
a1.scrollTop = a2.scrollTop = MAX;
var a1LastScrollTop = a1.scrollTop;
var a2LastScrollTop = a2.scrollTop;
function onScroll() {
if (this.scrollTop === (this === a1 ? a1LastScrollTop : a2LastScrollTop)) {
return;
}
a1.scrollTop = a2.scrollTop = MAX;
a1LastScrollTop = a1.scrollTop;
a2LastScrollTop = a2.scrollTop;
attrChange(attr);
}
a1.addEventListener("scroll", onScroll, passiveEvents);
a2.addEventListener("scroll", onScroll, passiveEvents);
});
var computedStyle = getComputedStyle(a1);
Object.defineProperty(elementComputedStyle, attr, {
configurable: true,
get: function() {
return parseFloat(computedStyle.paddingBottom);
}
});
}
var parentDiv = document.createElement("div");
setStyle2(parentDiv, {
position: "absolute",
left: "0",
top: "0",
width: "0",
height: "0",
zIndex: "-1",
overflow: "hidden",
visibility: "hidden"
});
attrs.forEach(function(key) {
addChild(parentDiv, key);
});
document.body.appendChild(parentDiv);
parentReady();
inited = true;
}
function getAttr(attr) {
if (!inited) {
init();
}
return elementComputedStyle[attr];
}
var changeAttrs = [];
function attrChange(attr) {
if (!changeAttrs.length) {
setTimeout(function() {
var style = {};
changeAttrs.forEach(function(attr2) {
style[attr2] = elementComputedStyle[attr2];
});
changeAttrs.length = 0;
callbacks.forEach(function(callback) {
callback(style);
});
}, 0);
}
changeAttrs.push(attr);
}
var callbacks = [];
function onChange(callback) {
if (!getSupport()) {
return;
}
if (!inited) {
init();
}
if (typeof callback === "function") {
callbacks.push(callback);
}
}
function offChange(callback) {
var index = callbacks.indexOf(callback);
if (index >= 0) {
callbacks.splice(index, 1);
}
}
var safeAreaInsets = {
get support() {
return (typeof support === "string" ? support : getSupport()).length != 0;
},
get top() {
return getAttr("top");
},
get left() {
return getAttr("left");
},
get right() {
return getAttr("right");
},
get bottom() {
return getAttr("bottom");
},
onChange,
offChange
};
var out = safeAreaInsets;
function getWindowOffset() {
const style = document.documentElement.style;
const top = parseInt(style.getPropertyValue("--window-top"));
const bottom = parseInt(style.getPropertyValue("--window-bottom"));
const left = parseInt(style.getPropertyValue("--window-left"));
const right = parseInt(style.getPropertyValue("--window-right"));
return {
top: top ? top + out.top : 0,
bottom: bottom ? bottom + out.bottom : 0,
left: left ? left + out.left : 0,
right: right ? right + out.right : 0
};
}
function updateCssVar(cssVars) {
const style = document.documentElement.style;
Object.keys(cssVars).forEach((name) => {
......@@ -2230,6 +2402,100 @@
ticking = true;
};
}
const isClickEvent = (val) => val.type === "click";
const isMouseEvent = (val) => val.type.indexOf("mouse") === 0;
function $nne(evt) {
const { currentTarget } = evt;
if (!(evt instanceof Event) || !(currentTarget instanceof HTMLElement)) {
return evt;
}
if (currentTarget.tagName.indexOf("UNI-") !== 0) {
return evt;
}
const res = createNativeEvent(evt);
if (isClickEvent(evt)) {
normalizeClickEvent(res, evt);
} else if (isMouseEvent(evt)) {
normalizeMouseEvent(res, evt);
} else if (evt instanceof TouchEvent) {
const { top } = getWindowOffset();
res.touches = normalizeTouchEvent(evt.touches, top);
res.changedTouches = normalizeTouchEvent(evt.changedTouches, top);
}
return res;
}
function findUniTarget(target) {
while (target && target.tagName.indexOf("UNI-") !== 0) {
target = target.parentElement;
}
return target;
}
function createNativeEvent(evt) {
const { type, timeStamp, target, currentTarget } = evt;
const event = {
type,
timeStamp,
target: normalizeTarget(findUniTarget(target)),
detail: {},
currentTarget: normalizeTarget(currentTarget)
};
if (evt._stopped) {
event._stopped = true;
}
if (evt.type.startsWith("touch")) {
event.touches = evt.touches;
event.changedTouches = evt.changedTouches;
}
{
extend(event, {
preventDefault() {
return evt.preventDefault();
},
stopPropagation() {
return evt.stopPropagation();
}
});
}
return event;
}
function normalizeClickEvent(evt, mouseEvt) {
const { x, y } = mouseEvt;
const { top } = getWindowOffset();
evt.detail = { x, y: y - top };
evt.touches = evt.changedTouches = [createTouchEvent(mouseEvt)];
}
function normalizeMouseEvent(evt, mouseEvt) {
const { top } = getWindowOffset();
evt.pageX = mouseEvt.pageX;
evt.pageY = mouseEvt.pageY - top;
evt.clientX = mouseEvt.clientX;
evt.clientY = mouseEvt.clientY - top;
}
function createTouchEvent(evt) {
return {
force: 1,
identifier: 0,
clientX: evt.clientX,
clientY: evt.clientY,
pageX: evt.pageX,
pageY: evt.pageY
};
}
function normalizeTouchEvent(touches, top) {
const res = [];
for (let i = 0; i < touches.length; i++) {
const { identifier, pageX, pageY, clientX, clientY, force } = touches[i];
res.push({
identifier,
pageX,
pageY: pageY - top,
clientX,
clientY: clientY - top,
force: force || 0
});
}
return res;
}
const APP_SERVICE_ID = "__uniapp__service";
const UniViewJSBridge$1 = /* @__PURE__ */ extend(ViewJSBridge, {
publishHandler
......@@ -2259,44 +2525,128 @@
const ACTION_TYPE_SET_ATTRIBUTE = 6;
const ACTION_TYPE_REMOVE_ATTRIBUTE = 7;
const ACTION_TYPE_SET_TEXT = 8;
const elements = new Map();
function $(id) {
return elements.get(id);
}
function createElement(id, tag) {
const element = document.createElement(decodeTag(tag));
elements.set(id, element);
return element;
}
function setElementAttr(element, name, value) {
element.setAttribute(decodeAttr(name), value);
}
function onNodeCreate(id, tag) {
return createElement(id, decodeTag(tag));
const ACTION_TYPE_EVENT = 20;
class UniNode {
constructor(id, tag) {
this.id = id;
this.tag = tag;
}
init(nodeJson) {
if (hasOwn(nodeJson, "t")) {
this.$.textContent = nodeJson.t || "";
}
}
setText(text) {
this.$.textContent = text;
}
insert(parentNodeId, refNodeId, nodeJson) {
this.init(nodeJson);
const node = this.$;
const parentNode = $(parentNodeId).$;
if (refNodeId === -1) {
parentNode.appendChild(node);
} else {
parentNode.insertBefore(node, $(refNodeId).$);
}
}
remove() {
const { $: $2 } = this;
$2.parentNode.removeChild($2);
}
}
function onNodeInsert(nodeId, parentNodeId, refNodeId, nodeJson) {
const element = $(nodeId);
$(parentNodeId).insertBefore(initElement(element, nodeJson), $(refNodeId));
class UniElement extends UniNode {
constructor(id, tag) {
super(id, tag);
this._listeners = {};
this.$ = document.createElement(tag);
}
init(nodeJson) {
super.init(nodeJson);
if (hasOwn(nodeJson, "a")) {
this.setAttrs(nodeJson.a);
}
}
setAttrs(attrs2) {
Object.keys(attrs2).forEach((name) => {
this.setAttr(name, attrs2[name]);
});
}
setAttr(name, value) {
if (name === ".c") {
this.$.className = value;
} else if (name.indexOf(".e") === 0) {
this.addEvent(name);
} else {
this.$.setAttribute(decodeAttr(name), value);
}
}
removeAttr(name) {
if (name === ".c") {
this.$.className = "";
} else if (name.indexOf(".e") === 0) {
this.removeEvent(name);
} else {
this.$.removeAttribute(decodeAttr(name));
}
}
addEvent(name) {
const [type] = parseEventName(decodeAttr(name));
if (this._listeners[type]) {
{
console.error(formatLog(`tag`, this.tag, this.id, "event[" + type + "] already registered"));
}
return;
}
this._listeners[type] = (evt) => {
UniViewJSBridge.publishHandler(VD_SYNC, [
[ACTION_TYPE_EVENT, this.id, $nne(evt)]
]);
};
this.$.addEventListener(type, this._listeners[type]);
}
removeEvent(name) {
const [type] = parseEventName(decodeAttr(name));
const listener = this._listeners[type];
if (listener) {
this.$.removeEventListener(type, listener);
} else {
console.error(formatLog(`tag`, this.tag, this.id, "event[" + type + "] not found"));
}
}
}
function initElement(element, { a, s }) {
initAttribute(element, a);
return element;
class UniText extends UniNode {
constructor(id) {
super(id, "#text");
this.$ = document.createTextNode("");
}
}
function initAttribute(element, attr) {
if (!attr) {
return;
class UniViewElement extends UniElement {
constructor(id) {
super(id, "uni-view");
}
Object.keys(attr).forEach((name) => setElementAttr(element, name, attr[name]));
}
function onNodeRemove(nodeId, parentNodeId) {
const elements = new Map();
const UniBuiltInComponents = [, UniViewElement, , , UniText];
function createUniComponent(type, id) {
return new UniBuiltInComponents[type](id);
}
function onNodeRemoveAttr(nodeId, name) {
function $(id) {
return elements.get(id);
}
function onNodeSetAttr(nodeId, name, value) {
function createElement(id, tag) {
let element;
if (isString(tag)) {
element = new UniElement(id, tag);
} else {
element = createUniComponent(tag, id);
}
elements.set(id, element);
return element;
}
function onNodeSetText(nodeId, text) {
function onPageCreated() {
}
function onPageCreate({
css,
route,
disableScroll,
onPageScroll,
......@@ -2306,6 +2656,10 @@
windowTop,
windowBottom
}) {
initPageElement();
if (css) {
initPageCss(route);
}
const pageId2 = plus.webview.currentWebview().id;
window.__id__ = pageId2;
document.title = `${route}[${pageId2}]`;
......@@ -2316,6 +2670,16 @@
initPageScroll(onPageScroll, onPageReachBottom, onReachBottomDistance);
}
}
function initPageElement() {
createElement(0, "div").$ = document.getElementById("app");
}
function initPageCss(route) {
const element = document.createElement("link");
element.type = "text/css";
element.rel = "stylesheet";
element.href = route + ".css";
document.head.appendChild(element);
}
function initCssVar(statusbarHeight, windowTop, windowBottom) {
const cssVars = {
"--window-left": "0px",
......@@ -2342,8 +2706,6 @@
}
requestAnimationFrame(() => document.addEventListener("scroll", createScrollListener(opts)));
}
function onPageCreated() {
}
function onVdSync(actions) {
actions.forEach((action) => {
switch (action[0]) {
......@@ -2352,17 +2714,17 @@
case ACTION_TYPE_PAGE_CREATED:
return onPageCreated();
case ACTION_TYPE_CREATE:
return onNodeCreate(action[1], action[2]);
return createElement(action[1], action[2]);
case ACTION_TYPE_INSERT:
return onNodeInsert(action[1], action[2], action[3], action[4]);
return $(action[1]).insert(action[2], action[3], action[4]);
case ACTION_TYPE_REMOVE:
return onNodeRemove(action[1], action[2]);
return $(action[1]).remove();
case ACTION_TYPE_SET_ATTRIBUTE:
return onNodeSetAttr(action[1], action[2], action[3]);
return $(action[1]).setAttr(action[2], action[3]);
case ACTION_TYPE_REMOVE_ATTRIBUTE:
return onNodeRemoveAttr(action[1], action[2]);
return $(action[1]).removeAttr(action[2]);
case ACTION_TYPE_SET_TEXT:
return onNodeSetText(action[1], action[2]);
return $(action[1]).setText(action[2]);
}
});
}
......
import { onNodeCreate } from './view/framework/subscriber/vdom/onNodeCreate'
import { onNodeInsert } from './view/framework/subscriber/vdom/onNodeInsert'
import { onNodeRemove } from './view/framework/subscriber/vdom/onNodeRemove'
import { onNodeRemoveAttr } from './view/framework/subscriber/vdom/onNodeRemoveAttr'
import { onNodeSetAttr } from './view/framework/subscriber/vdom/onNodeSetAttr'
import { onNodeSetText } from './view/framework/subscriber/vdom/onNodeSetText'
import { onNodeEvent } from './service/framework/dom/onNodeEvent'
import { createElement } from './view/framework/dom/elements'
import { UniElement } from './view/framework/dom/elements/UniElement'
export const ACTION_TYPE_PAGE_CREATE = 1
export const ACTION_TYPE_PAGE_CREATED = 2
......@@ -14,7 +11,10 @@ export const ACTION_TYPE_SET_ATTRIBUTE = 6
export const ACTION_TYPE_REMOVE_ATTRIBUTE = 7
export const ACTION_TYPE_SET_TEXT = 8
export const ACTION_TYPE_EVENT = 20
export interface PageNodeOptions {
css: boolean
route: string
version: number
locale: string
......@@ -32,34 +32,42 @@ export interface PageCreateData extends PageNodeOptions {}
export type PageCreateAction = [typeof ACTION_TYPE_PAGE_CREATE, PageCreateData]
export type PageCreatedAction = [typeof ACTION_TYPE_PAGE_CREATED]
export type EventAction = [
typeof ACTION_TYPE_EVENT,
Parameters<typeof onNodeEvent>[0],
Parameters<typeof onNodeEvent>[1]
]
export type CreateAction = [
typeof ACTION_TYPE_CREATE,
...Parameters<typeof onNodeCreate>
...Parameters<typeof createElement>
]
type NodeAction<T extends Parameters<any>> = [/* nodeId */ number, ...T]
export type InsertAction = [
typeof ACTION_TYPE_INSERT,
...Parameters<typeof onNodeInsert>
...NodeAction<Parameters<UniElement['insert']>>
]
export type RemoveAction = [
typeof ACTION_TYPE_REMOVE,
...Parameters<typeof onNodeRemove>
...NodeAction<Parameters<UniElement['remove']>>
]
export type SetAttributeAction = [
typeof ACTION_TYPE_SET_ATTRIBUTE,
...Parameters<typeof onNodeSetAttr>
...NodeAction<Parameters<UniElement['setAttr']>>
]
export type RemoveAttributeAction = [
typeof ACTION_TYPE_REMOVE_ATTRIBUTE,
...Parameters<typeof onNodeRemoveAttr>
...NodeAction<Parameters<UniElement['removeAttr']>>
]
export type SetTextAction = [
typeof ACTION_TYPE_SET_TEXT,
...Parameters<typeof onNodeSetText>
...NodeAction<Parameters<UniElement['setText']>>
]
export type PageUpdateAction =
......
......@@ -50,3 +50,4 @@ export * from './ad/interstitialAd'
export * from './ad/interactiveAd'
export * from './route/navigateTo'
export * from './route/navigateBack'
import {
API_NAVIGATE_BACK,
API_TYPE_NAVIGATE_BACK,
defineAsyncApi,
} from '@dcloudio/uni-api'
import { getCurrentPage, initI18nAppMsgsOnce } from '@dcloudio/uni-core'
import { useI18n } from '@dcloudio/uni-core'
export const navigateBack = defineAsyncApi<API_TYPE_NAVIGATE_BACK>(
API_NAVIGATE_BACK,
(args, { resolve, reject }) => {
const page = getCurrentPage()
if (!page) {
return
}
if (page.$page.meta.isQuit) {
quit()
}
return resolve()
}
)
let firstBackTime = 0
function quit() {
initI18nAppMsgsOnce()
if (!firstBackTime) {
firstBackTime = Date.now()
plus.nativeUI.toast(useI18n().t('uni.app.quit'))
setTimeout(() => {
firstBackTime = 0
}, 2000)
} else if (Date.now() - firstBackTime < 2000) {
plus.runtime.quit()
}
}
import { ON_WEBVIEW_READY } from '../../../../constants'
import { ON_WEBVIEW_READY, VD_SYNC } from '../../../../constants'
import { onVdSync } from '../../dom'
import { onPlusMessage } from '../initGlobalEvent'
import { subscribeWebviewReady } from './webviewReady'
......@@ -15,5 +16,6 @@ export function initSubscribeHandlers() {
if (__uniConfig.renderer !== 'native') {
// 非纯原生
subscribe(ON_WEBVIEW_READY, subscribeWebviewReady)
subscribe(VD_SYNC, onVdSync)
}
}
......@@ -5,6 +5,7 @@ import {
UniBaseNode,
IUniPageNode,
formatLog,
UniEvent,
} from '@dcloudio/uni-shared'
import {
PageCreateAction,
......@@ -25,6 +26,7 @@ import { VD_SYNC } from '../../../constants'
export default class UniPageNode extends UniNode implements IUniPageNode {
pageId: number
private _id: number = 1
private _created: boolean = false
private createAction: PageCreateAction
private createdAction: PageCreatedAction
public updateActions: PageAction[] = []
......@@ -52,12 +54,21 @@ export default class UniPageNode extends UniNode implements IUniPageNode {
pushCreateAction(this, thisNode.nodeId!, nodeName)
return thisNode
}
onInsertBefore(thisNode: UniNode, newChild: UniNode, index: number) {
pushInsertAction(this, newChild as UniBaseNode, thisNode.nodeId!, index)
onInsertBefore(
thisNode: UniNode,
newChild: UniNode,
refChild: UniNode | null
) {
pushInsertAction(
this,
newChild as UniBaseNode,
thisNode.nodeId!,
(refChild && refChild.nodeId!) || -1
)
return newChild
}
onRemoveChild(thisNode: UniNode, oldChild: UniNode) {
pushRemoveAction(this, oldChild.nodeId!, thisNode.nodeId!)
onRemoveChild(oldChild: UniNode) {
pushRemoveAction(this, oldChild.nodeId!)
return oldChild
}
onSetAttribute(thisNode: UniNode, qualifiedName: string, value: unknown) {
......@@ -108,6 +119,11 @@ export default class UniPageNode extends UniNode implements IUniPageNode {
if (__DEV__) {
console.log(formatLog('PageNode', 'update', updateActions.length))
}
// 首次
if (!this._created) {
this._created = true
updateActions.push(this.createdAction)
}
if (updateActions.length) {
this.send(updateActions)
updateActions.length = 0
......@@ -116,6 +132,28 @@ export default class UniPageNode extends UniNode implements IUniPageNode {
send(action: PageAction[]) {
UniServiceJSBridge.publishHandler(VD_SYNC, action, this.pageId)
}
fireEvent(id: number, evt: UniEvent) {
const node = findNodeById(id, this)
if (node) {
node.dispatchEvent(evt)
} else if (__DEV__) {
console.error(formatLog('PageNode', 'fireEvent', id, 'not found', evt))
}
}
}
function findNodeById(id: number, uniNode: UniNode): UniNode | null {
if (uniNode.nodeId === id) {
return uniNode
}
const { childNodes } = uniNode
for (let i = 0; i < childNodes.length; i++) {
const uniNode = findNodeById(id, childNodes[i])
if (uniNode) {
return uniNode
}
}
return null
}
function pushCreateAction(
......@@ -130,23 +168,19 @@ function pushInsertAction(
pageNode: UniPageNode,
newChild: UniBaseNode,
parentNodeId: number,
index: number
refChildId: number
) {
pageNode.push([
ACTION_TYPE_INSERT,
newChild.nodeId!,
parentNodeId,
index,
refChildId,
newChild.toJSON({ attr: true }),
])
}
function pushRemoveAction(
pageNode: UniPageNode,
nodeId: number,
parentNodeId: number
) {
pageNode.push([ACTION_TYPE_REMOVE, nodeId, parentNodeId])
function pushRemoveAction(pageNode: UniPageNode, nodeId: number) {
pageNode.push([ACTION_TYPE_REMOVE, nodeId])
}
function pushSetAttributeAction(
......
......@@ -13,7 +13,19 @@ import {
ACTION_TYPE_REMOVE_ATTRIBUTE,
ACTION_TYPE_SET_TEXT,
PageAction,
} from './Page'
PageCreateAction,
PageCreatedAction,
ACTION_TYPE_PAGE_CREATE,
ACTION_TYPE_PAGE_CREATED,
} from '../../../PageAction'
function decodePageCreateAction([, pageCreateData]: PageCreateAction) {
return ['pageCreate', pageCreateData]
}
function decodePageCreatedAction([]: PageCreatedAction) {
return ['pageCreated']
}
function decodeCreateAction([, nodeId, nodeName]: CreateAction) {
return ['create', nodeId, decodeTag(nodeName)]
......@@ -42,6 +54,10 @@ function decodeSetTextAction([, ...action]: SetTextAction) {
export function decodeActions(actions: PageAction[]) {
return actions.map((action) => {
switch (action[0]) {
case ACTION_TYPE_PAGE_CREATE:
return decodePageCreateAction(action)
case ACTION_TYPE_PAGE_CREATED:
return decodePageCreatedAction(action)
case ACTION_TYPE_CREATE:
return decodeCreateAction(action)
case ACTION_TYPE_INSERT:
......
import { getPageById } from '@dcloudio/uni-core'
import { formatLog } from '@dcloudio/uni-shared'
import { ComponentPublicInstance } from 'vue'
import { ACTION_TYPE_EVENT, EventAction } from '../../../PageAction'
import { onNodeEvent } from './onNodeEvent'
import UniPageNode from './Page'
export function onVdSync(actions: EventAction[], pageId: string) {
const page = getPageById(parseInt(pageId))
if (!page) {
if (__DEV__) {
console.error(formatLog('onVdSync', 'page', pageId, 'not found'))
}
return
}
const pageNode = (page as ComponentPublicInstance).$.appContext.app
._container as UniPageNode
actions.forEach((action) => {
switch (action[0]) {
case ACTION_TYPE_EVENT:
onNodeEvent(action[1], action[2], pageNode)
break
}
})
}
import { UniEvent } from '@dcloudio/uni-shared'
import UniPageNode from './Page'
export function onNodeEvent(
nodeId: number,
evt: UniEvent,
pageNode: UniPageNode
) {
pageNode.fireEvent(nodeId, evt)
}
......@@ -93,6 +93,7 @@ export function registerPage({
function initPageOptions({ meta }: UniApp.UniRoute): PageNodeOptions {
const statusbarHeight = getStatusbarHeight()
return {
css: true,
route: meta.route,
version: 1,
locale: '',
......
import { hasOwn } from '@vue/shared'
import { normalizeNativeEvent } from '@dcloudio/uni-core'
import {
decodeAttr,
formatLog,
parseEventName,
UniNodeJSON,
} from '@dcloudio/uni-shared'
import { VD_SYNC } from '../../../../constants'
import { ACTION_TYPE_EVENT } from '../../../../PageAction'
import { UniNode } from './UniNode'
export class UniElement extends UniNode {
$: Element
private _listeners: Record<string, (evt: Event) => void> = {}
constructor(id: number, tag: string) {
super(id, tag)
this.$ = document.createElement(tag)
}
init(nodeJson: Partial<UniNodeJSON>) {
super.init(nodeJson)
if (hasOwn(nodeJson, 'a')) {
this.setAttrs(nodeJson.a!)
}
}
setAttrs(attrs: Record<string, any>) {
Object.keys(attrs).forEach((name) => {
this.setAttr(name, attrs[name])
})
}
setAttr(name: string, value: unknown) {
if (name === '.c') {
this.$.className = value as string
} else if (name.indexOf('.e') === 0) {
this.addEvent(name)
} else {
this.$.setAttribute(decodeAttr(name), value as string)
}
}
removeAttr(name: string) {
if (name === '.c') {
this.$.className = ''
} else if (name.indexOf('.e') === 0) {
this.removeEvent(name)
} else {
this.$.removeAttribute(decodeAttr(name))
}
}
addEvent(name: string) {
const [type] = parseEventName(decodeAttr(name))
if (this._listeners[type]) {
if (__DEV__) {
console.error(
formatLog(
`tag`,
this.tag,
this.id,
'event[' + type + '] already registered'
)
)
}
return
}
this._listeners[type] = (evt: Event) => {
UniViewJSBridge.publishHandler(VD_SYNC, [
[ACTION_TYPE_EVENT, this.id, normalizeNativeEvent(evt)],
])
}
this.$.addEventListener(type, this._listeners[type])
}
removeEvent(name: string) {
const [type] = parseEventName(decodeAttr(name))
const listener = this._listeners[type]
if (listener) {
this.$.removeEventListener(type, listener)
} else if (__DEV__) {
console.error(
formatLog(`tag`, this.tag, this.id, 'event[' + type + '] not found')
)
}
}
}
import { hasOwn } from '@vue/shared'
import { UniNodeJSON } from '@dcloudio/uni-shared'
import { $ } from './utils'
export class UniNode {
id: number
tag: string
$!: Element | Text
constructor(id: number, tag: string) {
this.id = id
this.tag = tag
}
init(nodeJson: Partial<UniNodeJSON>) {
if (hasOwn(nodeJson, 't')) {
this.$.textContent = nodeJson.t || ''
}
}
setText(text: string) {
this.$.textContent = text
}
insert(
parentNodeId: number,
refNodeId: number,
nodeJson: Partial<UniNodeJSON>
) {
this.init(nodeJson)
const node = this.$
const parentNode = $(parentNodeId).$
if (refNodeId === -1) {
parentNode.appendChild(node)
} else {
parentNode.insertBefore(node, $(refNodeId).$)
}
}
remove() {
const { $ } = this
$.parentNode!.removeChild($)
}
}
import { UniNode } from './UniNode'
export class UniText extends UniNode {
constructor(id: number) {
super(id, '#text')
this.$ = document.createTextNode('')
}
}
import { UniElement } from './UniElement'
export class UniViewElement extends UniElement {
constructor(id: number) {
super(id, 'uni-view')
}
}
import { isString } from '@vue/shared'
import { UniElement } from './UniElement'
import { UniText } from './UniText'
import { UniViewElement } from './UniViewElement'
const elements = new Map<number, UniElement | UniText>()
const UniBuiltInComponents = [, UniViewElement, , , UniText]
function createUniComponent(type: number, id: number) {
return new UniBuiltInComponents[type]!(id)
}
export function $(id: number) {
return elements.get(id) as UniElement
}
export function createElement(id: number, tag: string | number) {
let element: UniElement | UniText
if (isString(tag)) {
element = new UniElement(id, tag)
} else {
element = createUniComponent(tag, id)
}
elements.set(id, element)
return element
}
......@@ -8,15 +8,9 @@ import {
ACTION_TYPE_SET_ATTRIBUTE,
ACTION_TYPE_SET_TEXT,
PageAction,
} from '../../../../PageAction'
import { onNodeCreate } from './onNodeCreate'
import { onNodeInsert } from './onNodeInsert'
import { onNodeRemove } from './onNodeRemove'
import { onNodeRemoveAttr } from './onNodeRemoveAttr'
import { onNodeSetAttr } from './onNodeSetAttr'
import { onNodeSetText } from './onNodeSetText'
import { onPageCreate } from './onPageCreate'
import { onPageCreated } from './onPageCreated'
} from '../../../PageAction'
import { $, createElement } from './elements'
import { onPageCreate, onPageCreated } from './page'
export function onVdSync(actions: PageAction[]) {
actions.forEach((action) => {
......@@ -26,17 +20,17 @@ export function onVdSync(actions: PageAction[]) {
case ACTION_TYPE_PAGE_CREATED:
return onPageCreated()
case ACTION_TYPE_CREATE:
return onNodeCreate(action[1], action[2])
return createElement(action[1], action[2])
case ACTION_TYPE_INSERT:
return onNodeInsert(action[1], action[2], action[3], action[4])
return $(action[1]).insert(action[2], action[3], action[4])
case ACTION_TYPE_REMOVE:
return onNodeRemove(action[1], action[2])
return $(action[1]).remove()
case ACTION_TYPE_SET_ATTRIBUTE:
return onNodeSetAttr(action[1], action[2], action[3])
return $(action[1]).setAttr(action[2], action[3])
case ACTION_TYPE_REMOVE_ATTRIBUTE:
return onNodeRemoveAttr(action[1], action[2])
return $(action[1]).removeAttr(action[2])
case ACTION_TYPE_SET_TEXT:
return onNodeSetText(action[1], action[2])
return $(action[1]).setText(action[2])
}
})
}
......@@ -5,9 +5,13 @@ import {
updateCssVar,
} from '@dcloudio/uni-core'
import { formatLog } from '@dcloudio/uni-shared'
import { PageCreateData } from '../../../../PageAction'
import { PageCreateData } from '../../../PageAction'
import { createElement } from './elements'
export function onPageCreated() {}
export function onPageCreate({
css,
route,
disableScroll,
onPageScroll,
......@@ -17,6 +21,13 @@ export function onPageCreate({
windowTop,
windowBottom,
}: PageCreateData) {
// 初始化页面容器元素
initPageElement()
if (css) {
initPageCss(route)
}
const pageId = plus.webview.currentWebview().id!
;(window as any).__id__ = pageId
document.title = `${route}[${pageId}]`
......@@ -30,6 +41,18 @@ export function onPageCreate({
}
}
function initPageElement() {
createElement(0, 'div').$ = document.getElementById('app')!
}
function initPageCss(route: string) {
const element = document.createElement('link')
element.type = 'text/css'
element.rel = 'stylesheet'
element.href = route + '.css'
document.head.appendChild(element)
}
function initCssVar(
statusbarHeight: number,
windowTop: number,
......
import { VD_SYNC } from '../../../constants'
import { onVdSync } from './vdom'
import { onVdSync } from '../dom'
export function initSubscribeHandlers() {
const { subscribe } = UniViewJSBridge
......
import { decodeTag } from '@dcloudio/uni-shared'
import { createElement } from './utils'
export function onNodeCreate(id: number, tag: string | number) {
return createElement(id, decodeTag(tag))
}
import { UniNodeJSON } from '@dcloudio/uni-shared'
import { $, setElementAttr } from './utils'
export function onNodeInsert(
nodeId: number,
parentNodeId: number,
refNodeId: number,
nodeJson: Partial<UniNodeJSON>
) {
const element = $(nodeId)
$(parentNodeId).insertBefore(initElement(element, nodeJson), $(refNodeId))
}
function initElement(element: Element, { a, s }: Partial<UniNodeJSON>) {
initAttribute(element, a)
// TODO style
return element
}
function initAttribute(element: Element, attr?: Record<string, unknown>) {
if (!attr) {
return
}
Object.keys(attr).forEach((name) => setElementAttr(element, name, attr[name]))
}
export function onNodeRemove(nodeId: number, parentNodeId: number) {}
export function onNodeRemoveAttr(nodeId: number, name: string) {}
export function onNodeSetAttr(nodeId: number, name: string, value: unknown) {}
export function onNodeSetText(nodeId: number, text: string) {}
import { decodeAttr, decodeTag } from '@dcloudio/uni-shared'
const elements = new Map<number, Element>()
export function $(id: number) {
return elements.get(id)!
}
export function createElement(id: number, tag: string) {
const element = document.createElement(decodeTag(tag))
elements.set(id, element)
return element
}
export function setElementAttr(element: Element, name: string, value: unknown) {
// TODO
element.setAttribute(decodeAttr(name), value as string)
}
......@@ -86,6 +86,16 @@ export default function vueFactory(exports) {
return str.charAt(0).toUpperCase() + str.slice(1);
});
function formatLog(module) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key2 = 1; _key2 < _len; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
return "[".concat(Date.now(), "][").concat(module, "]\uFF1A").concat(args.map(function (arg) {
return JSON.stringify(arg);
}).join(' '));
}
var DOMException = /*#__PURE__*/function (_Error) {
_inherits(DOMException, _Error);
......@@ -121,6 +131,10 @@ export default function vueFactory(exports) {
var listeners = this._listeners[evt.type];
if (!listeners) {
if (process.env.NODE_ENV !== 'production') {
console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found');
}
return false;
}
......@@ -489,10 +503,9 @@ export default function vueFactory(exports) {
newChild.parentNode = this;
checkNodeId(newChild);
var childNodes = this.childNodes;
var index;
if (refChild) {
index = childNodes.indexOf(refChild);
var index = childNodes.indexOf(refChild);
if (index === -1) {
throw new DOMException("Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.");
......@@ -500,11 +513,10 @@ export default function vueFactory(exports) {
childNodes.splice(index, 0, newChild);
} else {
index = childNodes.length;
childNodes.push(newChild);
}
return this.pageNode ? this.pageNode.onInsertBefore(this, newChild, index) : newChild;
return this.pageNode ? this.pageNode.onInsertBefore(this, newChild, refChild) : newChild;
}
}, {
key: "removeChild",
......@@ -518,7 +530,7 @@ export default function vueFactory(exports) {
oldChild.parentNode = null;
childNodes.splice(index, 1);
return this.pageNode ? this.pageNode.onRemoveChild(this, oldChild) : oldChild;
return this.pageNode ? this.pageNode.onRemoveChild(oldChild) : oldChild;
}
}]);
......@@ -1258,8 +1270,8 @@ export default function vueFactory(exports) {
} // we run the method using the original args first (which may be reactive)
for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
args[_key2] = arguments[_key2];
for (var _len2 = arguments.length, args = new Array(_len2), _key3 = 0; _key3 < _len2; _key3++) {
args[_key3] = arguments[_key3];
}
var res = method.apply(arr, args);
......@@ -1278,8 +1290,8 @@ export default function vueFactory(exports) {
instrumentations[key] = function () {
pauseTracking();
for (var _len2 = arguments.length, args = new Array(_len2), _key3 = 0; _key3 < _len2; _key3++) {
args[_key3] = arguments[_key3];
for (var _len3 = arguments.length, args = new Array(_len3), _key4 = 0; _key4 < _len3; _key4++) {
args[_key4] = arguments[_key4];
}
var res = method.apply(this, args);
......@@ -2265,8 +2277,8 @@ export default function vueFactory(exports) {
var appWarnHandler = instance && instance.appContext.config.warnHandler;
var trace = getComponentTrace();
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key4 = 1; _key4 < _len3; _key4++) {
args[_key4 - 1] = arguments[_key4];
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key5 = 1; _key5 < _len4; _key5++) {
args[_key5 - 1] = arguments[_key5];
}
if (appWarnHandler) {
......@@ -3030,8 +3042,8 @@ export default function vueFactory(exports) {
function emit(instance, event) {
var props = instance.vnode.props || EMPTY_OBJ;
for (var _len4 = arguments.length, rawArgs = new Array(_len4 > 2 ? _len4 - 2 : 0), _key5 = 2; _key5 < _len4; _key5++) {
rawArgs[_key5 - 2] = arguments[_key5];
for (var _len5 = arguments.length, rawArgs = new Array(_len5 > 2 ? _len5 - 2 : 0), _key6 = 2; _key6 < _len5; _key6++) {
rawArgs[_key6 - 2] = arguments[_key6];
}
if (process.env.NODE_ENV !== 'production') {
......@@ -5481,8 +5493,8 @@ export default function vueFactory(exports) {
setCurrentInstance(target);
for (var _len5 = arguments.length, args = new Array(_len5), _key6 = 0; _key6 < _len5; _key6++) {
args[_key6] = arguments[_key6];
for (var _len6 = arguments.length, args = new Array(_len6), _key7 = 0; _key7 < _len6; _key7++) {
args[_key7] = arguments[_key7];
}
var res = callWithAsyncErrorHandling(hook, target, type, args);
......@@ -5638,30 +5650,30 @@ export default function vueFactory(exports) {
}
if (methods) {
for (var _key7 in methods) {
var methodHandler = methods[_key7];
for (var _key8 in methods) {
var methodHandler = methods[_key8];
if (isFunction(methodHandler)) {
// In dev mode, we use the `createRenderContext` function to define methods to the proxy target,
// and those are read-only but reconfigurable, so it needs to be redefined here
if (process.env.NODE_ENV !== 'production') {
Object.defineProperty(ctx, _key7, {
Object.defineProperty(ctx, _key8, {
value: methodHandler.bind(publicThis),
configurable: true,
enumerable: true,
writable: true
});
} else {
ctx[_key7] = methodHandler.bind(publicThis);
ctx[_key8] = methodHandler.bind(publicThis);
}
if (process.env.NODE_ENV !== 'production') {
checkDuplicateProperties('Methods'
/* METHODS */
, _key7);
, _key8);
}
} else if (process.env.NODE_ENV !== 'production') {
warn("Method \"".concat(_key7, "\" has type \"").concat(typeof methodHandler, "\" in the component definition. ") + "Did you reference the function correctly?");
warn("Method \"".concat(_key8, "\" has type \"").concat(typeof methodHandler, "\" in the component definition. ") + "Did you reference the function correctly?");
}
}
}
......@@ -5684,25 +5696,25 @@ export default function vueFactory(exports) {
instance.data = reactive(data);
if (process.env.NODE_ENV !== 'production') {
var _loop = function _loop(_key8) {
var _loop = function _loop(_key9) {
checkDuplicateProperties('Data'
/* DATA */
, _key8); // expose data on ctx during dev
, _key9); // expose data on ctx during dev
if (_key8[0] !== '$' && _key8[0] !== '_') {
Object.defineProperty(ctx, _key8, {
if (_key9[0] !== '$' && _key9[0] !== '_') {
Object.defineProperty(ctx, _key9, {
configurable: true,
enumerable: true,
get: function get() {
return data[_key8];
return data[_key9];
},
set: NOOP
});
}
};
for (var _key8 in data) {
_loop(_key8);
for (var _key9 in data) {
_loop(_key9);
}
}
}
......@@ -5713,22 +5725,22 @@ export default function vueFactory(exports) {
shouldCacheAccess = true;
if (computedOptions) {
var _loop2 = function _loop2(_key9) {
var opt = computedOptions[_key9];
var _loop2 = function _loop2(_key10) {
var opt = computedOptions[_key10];
var get = isFunction(opt) ? opt.bind(publicThis, publicThis) : isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP;
if (process.env.NODE_ENV !== 'production' && get === NOOP) {
warn("Computed property \"".concat(_key9, "\" has no getter."));
warn("Computed property \"".concat(_key10, "\" has no getter."));
}
var set = !isFunction(opt) && isFunction(opt.set) ? opt.set.bind(publicThis) : process.env.NODE_ENV !== 'production' ? function () {
warn("Write operation failed: computed property \"".concat(_key9, "\" is readonly."));
warn("Write operation failed: computed property \"".concat(_key10, "\" is readonly."));
} : NOOP;
var c = computed$1({
get,
set
});
Object.defineProperty(ctx, _key9, {
Object.defineProperty(ctx, _key10, {
enumerable: true,
configurable: true,
get: function get() {
......@@ -5742,18 +5754,18 @@ export default function vueFactory(exports) {
if (process.env.NODE_ENV !== 'production') {
checkDuplicateProperties('Computed'
/* COMPUTED */
, _key9);
, _key10);
}
};
for (var _key9 in computedOptions) {
_loop2(_key9);
for (var _key10 in computedOptions) {
_loop2(_key10);
}
}
if (watchOptions) {
for (var _key10 in watchOptions) {
createWatcher(watchOptions[_key10], ctx, publicThis, _key10);
for (var _key11 in watchOptions) {
createWatcher(watchOptions[_key11], ctx, publicThis, _key11);
}
}
......@@ -6138,21 +6150,21 @@ export default function vueFactory(exports) {
var kebabKey;
for (var _key11 in rawCurrentProps) {
for (var _key12 in rawCurrentProps) {
if (!rawProps || // for camelCase
!hasOwn(rawProps, _key11) && ( // it's possible the original props was passed in as kebab-case
!hasOwn(rawProps, _key12) && ( // it's possible the original props was passed in as kebab-case
// and converted to camelCase (#955)
(kebabKey = hyphenate(_key11)) === _key11 || !hasOwn(rawProps, kebabKey))) {
(kebabKey = hyphenate(_key12)) === _key12 || !hasOwn(rawProps, kebabKey))) {
if (options) {
if (rawPrevProps && ( // for camelCase
rawPrevProps[_key11] !== undefined || // for kebab-case
rawPrevProps[_key12] !== undefined || // for kebab-case
rawPrevProps[kebabKey] !== undefined)) {
props[_key11] = resolvePropValue(options, rawCurrentProps, _key11, undefined, instance, true
props[_key12] = resolvePropValue(options, rawCurrentProps, _key12, undefined, instance, true
/* isAbsent */
);
}
} else {
delete props[_key11];
delete props[_key12];
}
}
} // in the case of functional component w/o props declaration, props and
......@@ -6160,9 +6172,9 @@ export default function vueFactory(exports) {
if (attrs !== rawCurrentProps) {
for (var _key12 in attrs) {
if (!rawProps || !hasOwn(rawProps, _key12)) {
delete attrs[_key12];
for (var _key13 in attrs) {
if (!rawProps || !hasOwn(rawProps, _key13)) {
delete attrs[_key13];
hasAttrsChanged = true;
}
}
......@@ -6221,8 +6233,8 @@ export default function vueFactory(exports) {
var castValues = rawCastValues || EMPTY_OBJ;
for (var i = 0; i < needCastKeys.length; i++) {
var _key13 = needCastKeys[i];
props[_key13] = resolvePropValue(options, rawCurrentProps, _key13, castValues[_key13], instance, !hasOwn(castValues, _key13));
var _key14 = needCastKeys[i];
props[_key14] = resolvePropValue(options, rawCurrentProps, _key14, castValues[_key14], instance, !hasOwn(castValues, _key14));
}
}
......@@ -6543,8 +6555,8 @@ export default function vueFactory(exports) {
function isBoolean() {
for (var _len6 = arguments.length, args = new Array(_len6), _key14 = 0; _key14 < _len6; _key14++) {
args[_key14] = arguments[_key14];
for (var _len7 = arguments.length, args = new Array(_len7), _key15 = 0; _key15 < _len7; _key15++) {
args[_key15] = arguments[_key15];
}
return args.some(function (elem) {
......@@ -6841,8 +6853,8 @@ export default function vueFactory(exports) {
},
use(plugin) {
for (var _len7 = arguments.length, options = new Array(_len7 > 1 ? _len7 - 1 : 0), _key15 = 1; _key15 < _len7; _key15++) {
options[_key15 - 1] = arguments[_key15];
for (var _len8 = arguments.length, options = new Array(_len8 > 1 ? _len8 - 1 : 0), _key16 = 1; _key16 < _len8; _key16++) {
options[_key16 - 1] = arguments[_key16];
}
if (installedPlugins.has(plugin)) {
......@@ -8041,9 +8053,9 @@ export default function vueFactory(exports) {
}
if (oldProps !== EMPTY_OBJ) {
for (var _key16 in oldProps) {
if (!isReservedProp(_key16) && !(_key16 in newProps)) {
hostPatchProp(el, _key16, oldProps[_key16], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
for (var _key17 in oldProps) {
if (!isReservedProp(_key17) && !(_key17 in newProps)) {
hostPatchProp(el, _key17, oldProps[_key17], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
}
}
}
......@@ -9626,8 +9638,8 @@ export default function vueFactory(exports) {
}
var createVNodeWithArgsTransform = function createVNodeWithArgsTransform() {
for (var _len8 = arguments.length, args = new Array(_len8), _key17 = 0; _key17 < _len8; _key17++) {
args[_key17] = arguments[_key17];
for (var _len9 = arguments.length, args = new Array(_len9), _key18 = 0; _key18 < _len9; _key18++) {
args[_key18] = arguments[_key18];
}
return _createVNode.apply(void 0, _toConsumableArray(vnodeArgsTransformer ? vnodeArgsTransformer(args, currentRenderingInstance) : args));
......@@ -10850,8 +10862,8 @@ export default function vueFactory(exports) {
get emit() {
return function (event) {
for (var _len9 = arguments.length, args = new Array(_len9 > 1 ? _len9 - 1 : 0), _key18 = 1; _key18 < _len9; _key18++) {
args[_key18 - 1] = arguments[_key18];
for (var _len10 = arguments.length, args = new Array(_len10 > 1 ? _len10 - 1 : 0), _key19 = 1; _key19 < _len10; _key19++) {
args[_key19 - 1] = arguments[_key19];
}
return instance.emit.apply(instance, [event].concat(args));
......@@ -11456,8 +11468,8 @@ export default function vueFactory(exports) {
}
}
for (var _key19 in next) {
batchedStyles[_key19] = next[_key19];
for (var _key20 in next) {
batchedStyles[_key20] = next[_key20];
}
el.setAttribute('style', batchedStyles);
......@@ -12265,8 +12277,8 @@ export default function vueFactory(exports) {
if (guard && guard(event, modifiers)) return;
}
for (var _len10 = arguments.length, args = new Array(_len10 > 1 ? _len10 - 1 : 0), _key20 = 1; _key20 < _len10; _key20++) {
args[_key20 - 1] = arguments[_key20];
for (var _len11 = arguments.length, args = new Array(_len11 > 1 ? _len11 - 1 : 0), _key21 = 1; _key21 < _len11; _key21++) {
args[_key21 - 1] = arguments[_key21];
}
return fn.apply(void 0, [event].concat(args));
......
export { ViewJSBridge } from './bridge'
export { initView } from './init'
export { initViewPlugin } from './plugin'
export { createNativeEvent } from './plugin/componentInstance'
export {
createNativeEvent,
$nne as normalizeNativeEvent,
} from './plugin/componentInstance'
import { ComponentPublicInstance } from 'vue'
import { extend } from '@vue/shared'
import { normalizeTarget } from '@dcloudio/uni-shared'
import { getWindowOffset } from '../../helpers'
......@@ -7,7 +6,7 @@ const isClickEvent = (val: Event): val is MouseEvent => val.type === 'click'
const isMouseEvent = (val: Event): val is MouseEvent =>
val.type.indexOf('mouse') === 0
// normalizeNativeEvent
export function $nne(this: ComponentPublicInstance, evt: Event) {
export function $nne(evt: Event) {
// 目前内置组件底层实现,当需要访问原始event时,请使用withWebEvent包裹
// 用法参考:uni-h5/src/framework/components/page/page-refresh/index.ts
const { currentTarget } = evt
......
......@@ -43,8 +43,11 @@ function createHandleHotUpdate() {
path_1.default.resolve(inputDir, 'pages.json.js'),
path_1.default.resolve(inputDir, 'manifest.json.js'),
require.resolve('@dcloudio/uni-h5/dist/uni-h5.es.js'),
require.resolve('vite/dist/client/env.js'),
];
try {
invalidateFiles.push(require.resolve('vite/dist/client/env.mjs'));
}
catch (e) { }
}
// TODO 目前简单处理,当pages.json,manifest.json发生变化,就直接刷新,理想情况下,应该区分变化的内容,仅必要时做整页面刷新
const isPagesJson = file.endsWith('pages.json');
......
......@@ -32,8 +32,10 @@ export function createHandleHotUpdate(): Plugin['handleHotUpdate'] {
path.resolve(inputDir, 'pages.json.js'),
path.resolve(inputDir, 'manifest.json.js'),
require.resolve('@dcloudio/uni-h5/dist/uni-h5.es.js'),
require.resolve('vite/dist/client/env.js'),
]
try {
invalidateFiles.push(require.resolve('vite/dist/client/env.mjs'))
} catch (e) {}
}
// TODO 目前简单处理,当pages.json,manifest.json发生变化,就直接刷新,理想情况下,应该区分变化的内容,仅必要时做整页面刷新
const isPagesJson = file.endsWith('pages.json')
......
......@@ -355,6 +355,9 @@ class UniEventTarget {
dispatchEvent(evt) {
const listeners = this._listeners[evt.type];
if (!listeners) {
if ((process.env.NODE_ENV !== 'production')) {
console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found');
}
return false;
}
const len = listeners.length;
......@@ -387,6 +390,19 @@ class UniEventTarget {
listeners.splice(index, 1);
}
}
}
const optionsModifierRE = /(?:Once|Passive|Capture)$/;
function parseEventName(name) {
let options;
if (optionsModifierRE.test(name)) {
options = {};
let m;
while ((m = name.match(optionsModifierRE))) {
name = name.slice(0, name.length - m[0].length);
options[m[0].toLowerCase()] = true;
}
}
return [shared.hyphenate(name.slice(2)), options];
}
class UniCSSStyleDeclaration {
......@@ -634,20 +650,18 @@ class UniNode extends UniEventTarget {
newChild.parentNode = this;
checkNodeId(newChild);
const { childNodes } = this;
let index;
if (refChild) {
index = childNodes.indexOf(refChild);
const index = childNodes.indexOf(refChild);
if (index === -1) {
throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`);
}
childNodes.splice(index, 0, newChild);
}
else {
index = childNodes.length;
childNodes.push(newChild);
}
return this.pageNode
? this.pageNode.onInsertBefore(this, newChild, index)
? this.pageNode.onInsertBefore(this, newChild, refChild)
: newChild;
}
removeChild(oldChild) {
......@@ -658,9 +672,7 @@ class UniNode extends UniEventTarget {
}
oldChild.parentNode = null;
childNodes.splice(index, 1);
return this.pageNode
? this.pageNode.onRemoveChild(this, oldChild)
: oldChild;
return this.pageNode ? this.pageNode.onRemoveChild(oldChild) : oldChild;
}
}
class UniBaseNode extends UniNode {
......@@ -963,6 +975,7 @@ exports.isServiceNativeTag = isServiceNativeTag;
exports.normalizeDataset = normalizeDataset;
exports.normalizeTarget = normalizeTarget;
exports.once = once;
exports.parseEventName = parseEventName;
exports.parseQuery = parseQuery;
exports.parseUrl = parseUrl;
exports.passive = passive;
......
......@@ -94,8 +94,8 @@ export declare interface IUniPageNode {
genId: () => number;
push: (...args: any[]) => void;
onCreate: (thisNode: UniNode, nodeName: string | number) => UniNode;
onInsertBefore: (thisNode: UniNode, newChild: UniNode, index: number) => UniNode;
onRemoveChild: (thisNode: UniNode, oldChild: UniNode) => UniNode;
onInsertBefore: (thisNode: UniNode, newChild: UniNode, refChild: UniNode | null) => UniNode;
onRemoveChild: (oldChild: UniNode) => UniNode;
onSetAttribute: (thisNode: UniNode, qualifiedName: string, value: unknown) => void;
onRemoveAttribute: (thisNode: UniNode, qualifiedName: string) => void;
onTextContent: (thisNode: UniNode, text: string) => void;
......@@ -131,6 +131,8 @@ declare interface Options {
complete?: (res: any) => void;
}
export declare function parseEventName(name: string): [string, EventListenerOptions | undefined];
/**
* https://github.com/vuejs/vue-router-next/blob/master/src/query.ts
* @internal
......
import { camelize, extend, isString, isPlainObject, isArray, isHTMLTag, isSVGTag, capitalize } from '@vue/shared';
import { camelize, extend, isString, isPlainObject, isArray, isHTMLTag, isSVGTag, hyphenate, capitalize } from '@vue/shared';
function formatLog(module, ...args) {
return `[${Date.now()}][${module}]:${args
......@@ -351,6 +351,9 @@ class UniEventTarget {
dispatchEvent(evt) {
const listeners = this._listeners[evt.type];
if (!listeners) {
if ((process.env.NODE_ENV !== 'production')) {
console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found');
}
return false;
}
const len = listeners.length;
......@@ -383,6 +386,19 @@ class UniEventTarget {
listeners.splice(index, 1);
}
}
}
const optionsModifierRE = /(?:Once|Passive|Capture)$/;
function parseEventName(name) {
let options;
if (optionsModifierRE.test(name)) {
options = {};
let m;
while ((m = name.match(optionsModifierRE))) {
name = name.slice(0, name.length - m[0].length);
options[m[0].toLowerCase()] = true;
}
}
return [hyphenate(name.slice(2)), options];
}
class UniCSSStyleDeclaration {
......@@ -630,20 +646,18 @@ class UniNode extends UniEventTarget {
newChild.parentNode = this;
checkNodeId(newChild);
const { childNodes } = this;
let index;
if (refChild) {
index = childNodes.indexOf(refChild);
const index = childNodes.indexOf(refChild);
if (index === -1) {
throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`);
}
childNodes.splice(index, 0, newChild);
}
else {
index = childNodes.length;
childNodes.push(newChild);
}
return this.pageNode
? this.pageNode.onInsertBefore(this, newChild, index)
? this.pageNode.onInsertBefore(this, newChild, refChild)
: newChild;
}
removeChild(oldChild) {
......@@ -654,9 +668,7 @@ class UniNode extends UniEventTarget {
}
oldChild.parentNode = null;
childNodes.splice(index, 1);
return this.pageNode
? this.pageNode.onRemoveChild(this, oldChild)
: oldChild;
return this.pageNode ? this.pageNode.onRemoveChild(oldChild) : oldChild;
}
}
class UniBaseNode extends UniNode {
......@@ -898,4 +910,4 @@ function getEnvLocale() {
return (lang && lang.replace(/[.:].*/, '')) || 'en';
}
export { BACKGROUND_COLOR, BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, DATA_RE, 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, decodeAttr, decodeTag, decodedQuery, defaultRpx2Unit, encodeAttr, encodeTag, formatDateTime, formatLog, getCustomDataset, getEnvLocale, getLen, initCustomDataset, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, isServiceCustomElement, isServiceNativeTag, normalizeDataset, normalizeTarget, once, parseQuery, parseUrl, passive, plusReady, removeLeadingSlash, sanitise, scrollTo, stringifyQuery, updateElementStyle };
export { BACKGROUND_COLOR, BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, DATA_RE, 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, decodeAttr, decodeTag, decodedQuery, defaultRpx2Unit, encodeAttr, encodeTag, formatDateTime, formatLog, getCustomDataset, getEnvLocale, getLen, initCustomDataset, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, isServiceCustomElement, isServiceNativeTag, normalizeDataset, normalizeTarget, once, parseEventName, parseQuery, parseUrl, passive, plusReady, removeLeadingSlash, sanitise, scrollTo, stringifyQuery, updateElementStyle };
import { extend, capitalize, camelize } from '@vue/shared'
import { extend, capitalize, camelize, hyphenate } from '@vue/shared'
import { formatLog } from '../log'
import { UniElement } from './Element'
import { UniNode } from './Node'
export function normalizeEventType(type: string) {
return `on${capitalize(camelize(type))}`
......@@ -50,6 +52,13 @@ export class UniEventTarget {
dispatchEvent(evt: UniEvent): boolean {
const listeners = this._listeners[evt.type]
if (!listeners) {
if (__DEV__) {
console.error(
formatLog('dispatchEvent', (this as unknown as UniNode).nodeId),
evt.type,
'not found'
)
}
return false
}
const len = listeners.length
......@@ -97,3 +106,21 @@ export class UniEventTarget {
}
}
}
const optionsModifierRE = /(?:Once|Passive|Capture)$/
export function parseEventName(
name: string
): [string, EventListenerOptions | undefined] {
let options: EventListenerOptions | undefined
if (optionsModifierRE.test(name)) {
options = {}
let m
while ((m = name.match(optionsModifierRE))) {
name = name.slice(0, name.length - m[0].length)
;(options as any)[m[0].toLowerCase()] = true
options
}
}
return [hyphenate(name.slice(2)), options]
}
......@@ -52,9 +52,9 @@ export interface IUniPageNode {
onInsertBefore: (
thisNode: UniNode,
newChild: UniNode,
index: number
refChild: UniNode | null
) => UniNode
onRemoveChild: (thisNode: UniNode, oldChild: UniNode) => UniNode
onRemoveChild: (oldChild: UniNode) => UniNode
onSetAttribute: (
thisNode: UniNode,
qualifiedName: string,
......@@ -165,9 +165,8 @@ export class UniNode extends UniEventTarget {
newChild.parentNode = this
checkNodeId(newChild)
const { childNodes } = this
let index: number
if (refChild) {
index = childNodes.indexOf(refChild)
const index = childNodes.indexOf(refChild)
if (index === -1) {
throw new DOMException(
`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`
......@@ -175,11 +174,10 @@ export class UniNode extends UniEventTarget {
}
childNodes.splice(index, 0, newChild)
} else {
index = childNodes.length
childNodes.push(newChild)
}
return this.pageNode
? this.pageNode.onInsertBefore(this, newChild, index)
? this.pageNode.onInsertBefore(this, newChild, refChild)
: newChild
}
......@@ -193,9 +191,7 @@ export class UniNode extends UniEventTarget {
}
oldChild.parentNode = null
childNodes.splice(index, 1)
return this.pageNode
? this.pageNode.onRemoveChild(this, oldChild)
: oldChild
return this.pageNode ? this.pageNode.onRemoveChild(oldChild) : oldChild
}
}
......
export { UniCommentNode } from './Comment'
export { UniElement, UniInputElement, UniTextAreaElement } from './Element'
export { UniEvent, UniEventListener } from './Event'
export { UniEvent, UniEventListener, parseEventName } from './Event'
export {
NODE_TYPE_PAGE,
NODE_TYPE_ELEMENT,
......
......@@ -16,5 +16,5 @@
"removeComments": false,
"lib": ["ESNext", "DOM"]
},
"include": ["src"]
"include": ["src", "../global.d.ts", "../shims-uni-app.d.ts"]
}
......@@ -2492,47 +2492,47 @@
"@types/yargs-parser" "*"
"@typescript-eslint/parser@^4.12.0":
version "4.28.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.28.1.tgz#5181b81658414f47291452c15bf6cd44a32f85bd"
integrity sha512-UjrMsgnhQIIK82hXGaD+MCN8IfORS1CbMdu7VlZbYa8LCZtbZjJA26De4IPQB7XYZbL8gJ99KWNj0l6WD0guJg==
version "4.28.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.28.2.tgz#6aff11bf4b91eb67ca7517962eede951e9e2a15d"
integrity sha512-Q0gSCN51eikAgFGY+gnd5p9bhhCUAl0ERMiDKrTzpSoMYRubdB8MJrTTR/BBii8z+iFwz8oihxd0RAdP4l8w8w==
dependencies:
"@typescript-eslint/scope-manager" "4.28.1"
"@typescript-eslint/types" "4.28.1"
"@typescript-eslint/typescript-estree" "4.28.1"
"@typescript-eslint/scope-manager" "4.28.2"
"@typescript-eslint/types" "4.28.2"
"@typescript-eslint/typescript-estree" "4.28.2"
debug "^4.3.1"
"@typescript-eslint/scope-manager@4.28.1":
version "4.28.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.28.1.tgz#fd3c20627cdc12933f6d98b386940d8d0ce8a991"
integrity sha512-o95bvGKfss6705x7jFGDyS7trAORTy57lwJ+VsYwil/lOUxKQ9tA7Suuq+ciMhJc/1qPwB3XE2DKh9wubW8YYA==
"@typescript-eslint/scope-manager@4.28.2":
version "4.28.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.28.2.tgz#451dce90303a3ce283750111495d34c9c204e510"
integrity sha512-MqbypNjIkJFEFuOwPWNDjq0nqXAKZvDNNs9yNseoGBB1wYfz1G0WHC2AVOy4XD7di3KCcW3+nhZyN6zruqmp2A==
dependencies:
"@typescript-eslint/types" "4.28.1"
"@typescript-eslint/visitor-keys" "4.28.1"
"@typescript-eslint/types" "4.28.2"
"@typescript-eslint/visitor-keys" "4.28.2"
"@typescript-eslint/types@4.28.1":
version "4.28.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.28.1.tgz#d0f2ecbef3684634db357b9bbfc97b94b828f83f"
integrity sha512-4z+knEihcyX7blAGi7O3Fm3O6YRCP+r56NJFMNGsmtdw+NCdpG5SgNz427LS9nQkRVTswZLhz484hakQwB8RRg==
"@typescript-eslint/types@4.28.2":
version "4.28.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.28.2.tgz#e6b9e234e0e9a66c4d25bab881661e91478223b5"
integrity sha512-Gr15fuQVd93uD9zzxbApz3wf7ua3yk4ZujABZlZhaxxKY8ojo448u7XTm/+ETpy0V0dlMtj6t4VdDvdc0JmUhA==
"@typescript-eslint/typescript-estree@4.28.1":
version "4.28.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.28.1.tgz#af882ae41740d1f268e38b4d0fad21e7e8d86a81"
integrity sha512-GhKxmC4sHXxHGJv8e8egAZeTZ6HI4mLU6S7FUzvFOtsk7ZIDN1ksA9r9DyOgNqowA9yAtZXV0Uiap61bIO81FQ==
"@typescript-eslint/typescript-estree@4.28.2":
version "4.28.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.28.2.tgz#680129b2a285289a15e7c6108c84739adf3a798c"
integrity sha512-86lLstLvK6QjNZjMoYUBMMsULFw0hPHJlk1fzhAVoNjDBuPVxiwvGuPQq3fsBMCxuDJwmX87tM/AXoadhHRljg==
dependencies:
"@typescript-eslint/types" "4.28.1"
"@typescript-eslint/visitor-keys" "4.28.1"
"@typescript-eslint/types" "4.28.2"
"@typescript-eslint/visitor-keys" "4.28.2"
debug "^4.3.1"
globby "^11.0.3"
is-glob "^4.0.1"
semver "^7.3.5"
tsutils "^3.21.0"
"@typescript-eslint/visitor-keys@4.28.1":
version "4.28.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.28.1.tgz#162a515ee255f18a6068edc26df793cdc1ec9157"
integrity sha512-K4HMrdFqr9PFquPu178SaSb92CaWe2yErXyPumc8cYWxFmhgJsNY9eSePmO05j0JhBvf2Cdhptd6E6Yv9HVHcg==
"@typescript-eslint/visitor-keys@4.28.2":
version "4.28.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.28.2.tgz#bf56a400857bb68b59b311e6d0a5fbef5c3b5130"
integrity sha512-aT2B4PLyyRDUVUafXzpZFoc0C9t0za4BJAKP5sgWIhG+jHECQZUEjuQSCIwZdiJJ4w4cgu5r3Kh20SOdtEBl0w==
dependencies:
"@typescript-eslint/types" "4.28.1"
"@typescript-eslint/types" "4.28.2"
eslint-visitor-keys "^2.0.0"
"@vitejs/plugin-legacy@^1.4.3":
......@@ -4071,9 +4071,9 @@ ee-first@1.1.1:
integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=
electron-to-chromium@^1.3.723:
version "1.3.766"
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.766.tgz#2fd14a4e54f77665872f4e23fcf4968e83638220"
integrity sha512-u2quJ862q9reRKh/je3GXis3w38+RoXH1J9N3XjtsS6NzmUAosNsyZgUVFZPN/ZlJ3v6T0rTyZR3q/J5c6Sy5w==
version "1.3.768"
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.768.tgz#bbe47394f0073c947168589b7d19388518a7a9a9"
integrity sha512-I4UMZHhVSK2pwt8jOIxTi3GIuc41NkddtKT/hpuxp9GO5UWJgDKTBa4TACppbVAuKtKbMK6BhQZvT5tFF1bcNA==
elliptic@^6.5.3:
version "6.5.4"
......@@ -9362,10 +9362,10 @@ verror@1.10.0:
core-util-is "1.0.2"
extsprintf "^1.2.0"
vite@^2.4.0-beta.3:
version "2.4.0-beta.3"
resolved "https://registry.yarnpkg.com/vite/-/vite-2.4.0-beta.3.tgz#81da5e6cbfb4cb710610e5757567cbe58b667c44"
integrity sha512-sSUbH0mPMbqqOVZ1/LD/Wiu347yvn4BXjS/94mn5Q7E/zd50hxEnKU1NC4x59TBKq5OeboPhyXwibyCEpyAQKQ==
vite@^2.4.0:
version "2.4.0"
resolved "https://registry.yarnpkg.com/vite/-/vite-2.4.0.tgz#a591e4f2c996ae9a044093f629b418069629ca16"
integrity sha512-FR+1hCyGt8i+ijMe9z4tIfUQ7BQThxGevp3IlmdXDBSJEPjbeDznbuJa/QVzXw2Mpxh7KCmveVI082h8nzcCNw==
dependencies:
esbuild "^0.12.8"
postcss "^8.3.5"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册