Skip to content

Commit

Permalink
fix: 优化构建方式
Browse files Browse the repository at this point in the history
  • Loading branch information
1977474741 committed Jul 27, 2023
1 parent 236b8b9 commit 21a7608
Show file tree
Hide file tree
Showing 16 changed files with 330 additions and 323 deletions.
8 changes: 0 additions & 8 deletions .babelrc

This file was deleted.

3 changes: 0 additions & 3 deletions .browserslistrc

This file was deleted.

1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -17,6 +17,7 @@ pnpm-debug.log*
# Editor directories and files
.idea
.vscode
.history
*.suo
*.ntvs*
*.njsproj
Expand Down
1 change: 1 addition & 0 deletions .releaserc
Expand Up @@ -22,6 +22,7 @@
{
"assets": [
"lib/spa-custom-hooks.js",
"lib/spa-custom-hooks.mjs",
"package.json",
"CHANGELOG.md"
],
Expand Down
2 changes: 1 addition & 1 deletion lib/spa-custom-hooks.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions lib/spa-custom-hooks.mjs
@@ -0,0 +1 @@
function t(t,e){var o=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),o.push.apply(o,n)}return o}function e(e){for(var o=1;o<arguments.length;o++){var n=null!=arguments[o]?arguments[o]:{};o%2?t(Object(n),!0).forEach((function(t){c(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,l(n.key),n)}}function i(t,e,o){return e&&r(t.prototype,e),o&&r(t,o),Object.defineProperty(t,"prototype",{writable:!1}),t}function c(t,e,o){return(e=l(e))in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}function a(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var o=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=o){var n,r,i,c,a=[],u=!0,s=!1;try{if(i=(o=o.call(t)).next,0===e){if(Object(o)!==o)return;u=!1}else for(;!(u=(n=i.call(o)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(t){s=!0,r=t}finally{try{if(!u&&null!=o.return&&(c=o.return(),Object(c)!==c))return}finally{if(s)throw r}}return a}}(t,e)||s(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t){return function(t){if(Array.isArray(t))return h(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||s(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(t,e){if(t){if("string"==typeof t)return h(t,e);var o=Object.prototype.toString.call(t).slice(8,-1);return"Object"===o&&t.constructor&&(o=t.constructor.name),"Map"===o||"Set"===o?Array.from(t):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?h(t,e):void 0}}function h(t,e){(null==e||e>t.length)&&(e=t.length);for(var o=0,n=new Array(e);o<e;o++)n[o]=t[o];return n}function l(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var o=t[Symbol.toPrimitive];if(void 0!==o){var n=o.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}var f,y=function(t,e,o){try{if(e){for(var n=e.split("."),r=o?n.length-1:n.length,i=0;i<r;i++)t=t[n[i]];return o?{key:n[r],obj:t}:t}return t}catch(t){return}},p=function(t){return f&&f.state?f:t&&t.$store||{}},m=function(){function t(e){var o=e.customhook,r=e.name,i=e.destroy,c=e.hit,a=void 0!==c&&c,u=e.watchKey,s=e.onUpdate;n(this,t),this.name=r,this.destroy=i,this.hit=a,this.need=!1,this.initFlag=!1,u&&(this.watchKey=u.replace("$store.state.","")),this.onUpdate=s,this.__customhook=o}return i(t,[{key:"init",value:function(){var t=this;this.initFlag||(this.watchKey&&this.watchAttr((function(e){t[e?"cycleStart":"cycleEnd"]()})),this.initFlag=!0)}},{key:"cycleStart",value:function(){this.hit||(this.hit=!0,this.__customhook&&this.__customhook.triggerHook(this.name))}},{key:"cycleEnd",value:function(){this.hit&&(this.hit=!1,this.__customhook&&this.__customhook.resetExecute(this.name))}},{key:"watchAttr",value:function(t){try{var e=this;p(this.__customhook.pageInstance).watch((function(t){return y(t,e.watchKey)}),(function(o,n){t(e.onUpdate?e.onUpdate(o,n):o)}),{watchKey:e.watchKey})}catch(t){}}}]),t}(),k={},d=["onLaunch","created","beforeMount","mounted","activated","deactivated","beforeDestroy","destroyed","onLoad","attached","detached","onShow","onHide","onReady","onUnload"],b=function(t){return e({Launch:new m({customhook:t,name:"onLaunch",destroy:"onUnload",hit:!0}),Created:new m({customhook:t,name:"created",destroy:"destroyed",hit:"created"==j.initHook}),Load:new m({customhook:t,name:"onLoad",destroy:"onUnload",hit:"onLoad"==j.initHook}),Attached:new m({customhook:t,name:"attached",destroy:"detached"}),Show:new m({customhook:t,name:"onShow",destroy:"onHide"}),Mounted:new m({customhook:t,name:"mounted",destroy:"destroyed"}),Ready:new m({customhook:t,name:"onReady",destroy:"onUnload"})},Object.keys(k).reduce((function(e,o){var n=k[o];return n.customhook=t,(e[o]=new m(n))&&e}),{}))},v=function(){return Object.keys(k)},g=d.map((function(t){return H(t)})),w=function(){function t(e,o,r){n(this,t),this.pageInstance=e,this.customHooks={},this.customHookArr=[],this.hook={},this.options=o||{},this.pageHooks=r,this.init()}return i(t,[{key:"init",value:function(){var t=this,e=b(this);this.hook=e;var o=this.pageHooks,n=o.hasOwnProperty("beforeCreate")||o.hasOwnProperty("onReady"),r=this.filterHooks(n?o:o.__proto__),i=r.customHookArr,c=r.hookInscape;this.customHookArr=i,i.forEach((function(n){t.customHooks[n]={callback:o[n].bind(t.pageInstance),inscape:c[n],execute:!1},c[n].forEach((function(t){return e[t].need=!0}))})),i.length&&Object.keys(e).forEach((function(t){return e[t].need&&e[t].init()}))}},{key:"filterHooks",value:function(t){var e=this,o={};return{customHookArr:Object.keys(t).filter((function(t){var n=e.getHookArr(t);return!!n.length&&(o[t]=n.filter((function(o){return!!e.hook[o]||(console.warn('[custom-hook 错误声明警告] "'.concat(o,'"钩子未注册,意味着"').concat(t,'"可能永远不会执行,请先注册此钩子再使用,文档:https://github.com/1977474741/spa-custom-hooks#-diyhooks对象说明')),!1)})),t=="on"+n.join("")&&o[t].length==n.length)})),hookInscape:o}}},{key:"triggerHook",value:function(t){var e=this;this.customHookArr.forEach((function(t){var o=e.customHooks[t];o.inscape.every((function(t){return e.hook[t].need&&e.checkHookHit(e.hook[t])}))&&!o.execute&&(o.execute=!0,e.customHooks[t].callback(e.options))}))}},{key:"resetExecute",value:function(t){var e=this;t=H(t),this.customHookArr.forEach((function(o){var n=e.customHooks[o];-1!=n.inscape.indexOf(t)&&(n.execute=!1)}))}},{key:"splitHook",value:function(t){t=t.replace("on","").split(/(?=[A-Z])/);for(var e=u(new Set(g.concat(v()))).sort((function(t,e){return e.length-t.length})),o=[],n="",r=0;r<t.length;r++){n+=t[r],-1!=e.indexOf(n)&&(o.push(n),n="")}return o}},{key:"checkHookHit",value:function(t){if(t.watchKey){var e=y(p(t.__customhook.pageInstance).state,t.watchKey);return t.onUpdate?t.onUpdate(e):e}return t.hit}},{key:"getHookArr",value:function(t){if(-1==t.indexOf("on"))return[];var e=this.splitHook(t),o=v();return e.length>1||-1!=o.indexOf(e[0])?e:[]}}]),t}();function H(t){return t=(t=t.replace("on","")).substring(0,1).toUpperCase()+t.substring(1)}var O={"vue-h5":{hooksKey:"$options",initHook:"beforeCreate",supportComponent:!0,isPage:function(t){return t._compiled&&this.supportComponent}},"vue-miniprogram":{hooksKey:"$options",initHook:"beforeCreate",supportComponent:!0,isPage:function(){return this.supportComponent}},miniprogram:{hooksKey:"",initHook:"onLoad",initHookApp:"onLaunch",supportComponent:!0,isPage:function(){return this.supportComponent}}},j=O["vue-miniprogram"],A=function(t,n,r,i){var a;function u(t){var e=y(this,j.hooksKey);j.isPage(e)&&(null!=r&&r.state||!i||(r.state=this[i]||i),this.customHook=new w(this,t,e))}t.mpvueVersion?j.initHook="onLoad":t.userAgentKey&&(j=O[t.userAgentKey]),f=r,k=n,t.mixin(e(e({},d.reduce((function(t,e){return(t[e]=function(t){if(("object"==o(this.customHook)||null==o(this.customHook))&&this.customHook.customHookArr.length){t&&Object.keys(t).length>0&&(this.customHook.options=t);var n=this.customHook.hook;for(var r in n){var i=n[r];i.name==e?i.cycleStart():i.destroy==e&&i.cycleEnd()}}})&&t}),{})),{},(c(a={},j.initHook,(function(t){u.call(this,t)})),c(a,j.initHookApp,(function(t){u.call(this,t)})),a)))},S=Object.freeze({__proto__:null,get BASE(){return j},install:A}),P={mixin:function(t){var e=this,o=Page,n=App;Page=function(n){e.mergeHook(t,n),o(n)},App=function(o){e.mergeHook(t,o),n(o)}},mergeHook:function(t,e){for(var o=function(){var t=a(r[n],2),o=t[0],i=t[1],c=e[o];e[o]=function(){for(var t=arguments.length,e=new Array(t),o=0;o<t;o++)e[o]=arguments[o];return i.call.apply(i,[this].concat(e)),c&&c.call.apply(c,[this].concat(e))}},n=0,r=Object.entries(t);n<r.length;n++)o()},userAgentKey:"miniprogram"},_={},E={watch:function(t,e,n){var r=p().state,i=n.watchKey,c=y(r,i,!0);_[i]?_[i].push(e):_[i]=[e],function t(n,r){var u=n[r];Object.defineProperty(n,r,{configurable:!0,enumerable:!0,set:function(t){u=t,_[i].map((function(t){return t(c.obj[c.key])}))},get:function(){return u}}),Array.isArray(n[r])&&(s=n[r],h=function(){e(c.obj[c.key])},l=Object.create(s),["push","pop","shift","unshift","splice","sort","reverse"].forEach((function(t){var e=l[t];!function(t,e,o,n){Object.defineProperty(t,e,{value:o,enumerable:!!n,writable:!0,configurable:!0})}(s,t,(function(){return e.apply(this,arguments),h.apply(this,arguments)}))})));var s,h,l;if("object"===o(n[r])&&null!=n[r])for(var f=0,y=Object.entries(n[r]);f<y.length;f++){var p=a(y[f],2),m=p[0];p[1],t(n[r],m)}}(c.obj,c.key)}};var K={install:function(){arguments.length<3?A(P,arguments[0],E,arguments[1]||"globalData"):A.apply(S,arguments)},setHit:function(t,e){b()[t][e?"cycleStart":"cycleEnd"]()}};export{K as default};
70 changes: 36 additions & 34 deletions lib/spa-custom-hooks/custom-hook.js
@@ -1,18 +1,18 @@
import { Hooks,getDiyHooks,nativeHooks } from './hooks.js';
import { getVal,getStore } from './utils.js';
import { Hooks, getDiyHooks, nativeHooks } from './hooks.js';
import { getVal, getStore } from './utils.js';
//所有原生钩子数组
let nativeHooksName = nativeHooks.map(e=>toHookName(e));
let nativeHooksName = nativeHooks.map((e) => toHookName(e));
/**
* @Author 鹅鹅鹅
* @DateTime 2020-06-24T19:24:40+0800
* @description 自定义钩子
* @param page {Object component} 当前组件实例
* @param options {Object object} 当前组件接收到的参数
* @param pageHooks {Object object} 当前组件钩子对象
* return customHook {Object customHook}
* return customHook {Object customHook}
*/
export default class customHook {
constructor(page,options,pageHooks) {
constructor(page, options, pageHooks) {
// 页面实例、原生钩子对象
this.pageInstance = page;
// 页面内需要处理的所有钩子构成和函数执行状态
Expand All @@ -36,7 +36,7 @@ export default class customHook {
// 钩子对象在自身还是原型链
let oneself = pageHooks.hasOwnProperty('beforeCreate') || pageHooks.hasOwnProperty('onReady');
// 过滤钩子对象、分析钩子构成
let {customHookArr,hookInscape} = this.filterHooks(oneself ? pageHooks : pageHooks['__proto__']);
let { customHookArr, hookInscape } = this.filterHooks(oneself ? pageHooks : pageHooks['__proto__']);
this.customHookArr = customHookArr;
// 单独处理每个钩子
customHookArr.forEach((e) => {
Expand All @@ -46,13 +46,13 @@ export default class customHook {
// 此钩子构成
inscape: hookInscape[e],
// 此钩子是否已执行
execute: false
execute: false,
};
//启用需要的钩子
hookInscape[e].forEach(hookStr => hook[hookStr].need = true);
hookInscape[e].forEach((hookStr) => (hook[hookStr].need = true));
});
// await Promise.resolve();
customHookArr.length && Object.keys(hook).forEach(e => hook[e].need && hook[e].init());
customHookArr.length && Object.keys(hook).forEach((e) => hook[e].need && hook[e].init());
}
/**
* 过滤出钩子对象
Expand All @@ -62,30 +62,32 @@ export default class customHook {
* hookInscape {Object array} 自定义钩子构成
* }
*/
filterHooks(option){
filterHooks(option) {
// 各钩子和包含的所有已注册单独钩子构成
let hookInscape = {};
// 筛选出自定义钩子
return {
customHookArr: Object.keys(option).filter(e => {
customHookArr: Object.keys(option).filter((e) => {
// 不符合规则的钩子不予处理
let hookArr = this.getHookArr(e);
if(hookArr.length){
if (hookArr.length) {
//过滤掉未注册的钩子
hookInscape[e] = hookArr.filter((h)=>{
if(this.hook[h]){
hookInscape[e] = hookArr.filter((h) => {
if (this.hook[h]) {
return true;
}
console.warn(`[custom-hook 错误声明警告] "${h}"钩子未注册,意味着"${e}"可能永远不会执行,请先注册此钩子再使用,文档:https://github.com/1977474741/spa-custom-hooks#-diyhooks对象说明`);
console.warn(
`[custom-hook 错误声明警告] "${h}"钩子未注册,意味着"${e}"可能永远不会执行,请先注册此钩子再使用,文档:https://github.com/1977474741/spa-custom-hooks#-diyhooks对象说明`
);
return false;
});
//格式 + 是否注册的效验
return e == 'on' + hookArr.join('') && hookInscape[e].length == hookArr.length;
}
return false;
}),
hookInscape
}
hookInscape,
};
}
/**
* 检测是否有需要触发的钩子
Expand All @@ -94,7 +96,7 @@ export default class customHook {
triggerHook(hitKey) {
this.customHookArr.forEach((name) => {
let customHook = this.customHooks[name];
let meet = customHook.inscape.every(e => this.hook[e].need && this.checkHookHit(this.hook[e]))
let meet = customHook.inscape.every((e) => this.hook[e].need && this.checkHookHit(this.hook[e]));
if (meet && !customHook.execute) {
customHook.execute = true;
this.customHooks[name]['callback'](this.options);
Expand All @@ -112,23 +114,23 @@ export default class customHook {
if (customHook.inscape.indexOf(name) != -1) {
customHook.execute = false;
}
})
});
}
/**
* 分析钩子构成
* @param name {String} 钩子名称
* return hookArr {Array string} 钩子构成数组
*/
splitHook(name){
//分割算法待优化、目前只支持单名大写开头的钩子、比如beforeCreate暂不支持
splitHook(name) {
//分割算法待优化、目前只支持单名大写开头的钩子、比如beforeCreate暂不支持
name = name.replace('on', '').split(/(?=[A-Z])/);
const hooksAll = [...new Set(nativeHooksName.concat(getDiyHooks()))].sort((a,b)=>b.length - a.length);
const hooksAll = [...new Set(nativeHooksName.concat(getDiyHooks()))].sort((a, b) => b.length - a.length);
const hookArr = [];
let hookName = '';
for (var i = 0; i < name.length; i++) {
const str = name[i];
hookName += str;
if(hooksAll.indexOf(hookName) != -1){
if (hooksAll.indexOf(hookName) != -1) {
hookArr.push(hookName);
hookName = '';
}
Expand All @@ -140,12 +142,12 @@ export default class customHook {
* @param hookEntity {Object hookEntity} hookEntity实例
* return {Boolean} 是否满足
*/
checkHookHit(hookEntity){
if(hookEntity.watchKey){
checkHookHit(hookEntity) {
if (hookEntity.watchKey) {
//注意:pageInstance对象必须从传进来的实体里拿,不能this.pageInstance
let val = getVal(getStore(hookEntity.__customhook.pageInstance).state,hookEntity.watchKey);
return (hookEntity.onUpdate ? hookEntity.onUpdate(val) : val);
}else{
let val = getVal(getStore(hookEntity.__customhook.pageInstance).state, hookEntity.watchKey);
return hookEntity.onUpdate ? hookEntity.onUpdate(val) : val;
} else {
return hookEntity.hit;
}
}
Expand All @@ -154,10 +156,10 @@ export default class customHook {
* @param name {String} 钩子名称
* return hookArr {Array string} 钩子构成
*/
getHookArr(name){
if(name.indexOf("on") == -1) return [];
getHookArr(name) {
if (name.indexOf('on') == -1) return [];
const hookArr = this.splitHook(name),
diyHooks = getDiyHooks();
diyHooks = getDiyHooks();
//组合钩子或者单个自定义钩子都视为有效钩子
return hookArr.length > 1 || diyHooks.indexOf(hookArr[0]) != -1 ? hookArr : [];
}
Expand All @@ -167,8 +169,8 @@ export default class customHook {
* @param name {String} 钩子名
* return name {String} 转换后的钩子key
*/
function toHookName(name){
function toHookName(name) {
name = name.replace('on', '');
name = name.substring(0,1).toUpperCase() + name.substring(1);
name = name.substring(0, 1).toUpperCase() + name.substring(1);
return name;
}
}

0 comments on commit 21a7608

Please sign in to comment.