How to use initMethods method in Playwright Internal

Best JavaScript code snippet using playwright-internal

pagination.component.js

Source:pagination.component.js Github

copy

Full Screen

1import { __decorate } from "tslib";2import { VoyoComponent, } from "../commonComponent";3import { VoyoDor, VoyoInput, VoyoTemplate } from "../BaseComponent";4import { SETTING_IOC_NAME } from "../../setting";5import { IOCAutowired } from "../../ioc";6import { CircleLoader } from "../utils/circle-loader";7import { ClassManage } from "../../utils";8import { finalize } from "rxjs/operators";9let PaginationComponent = class PaginationComponent extends VoyoComponent {10 constructor() {11 super(...arguments);12 this.circleLoader = new CircleLoader();13 this.currentPage = 1;14 this.initMethods = {15 initComplete: false,16 initExists: false,17 initDisplay: () => {18 this.initMethods.initExists = this.initLoaderEl.show = true;19 this.initMethods.initComplete = false;20 this.refresher.disabledScroll = true;21 const params = {22 currentPage: this.currentPage = 1,23 behavior: "init",24 };25 this.paginationFn(params)26 .pipe(finalize(() => {27 this.initMethods.initRemove();28 }))29 .subscribe(result => {30 const r = this.handlePaginationResult(params, result);31 if (r == "empty") {32 this.initMethods.errorRemove();33 }34 else if (r == "error") {35 this.initMethods.emptyRemove();36 }37 else {38 this.initMethods.errorRemove();39 this.initMethods.emptyRemove();40 this.initMethods.initComplete = true;41 this.refresher.disabledScroll = false;42 }43 }, error => {44 this.handlePaginationError("init");45 });46 },47 initRemove: () => {48 this.initMethods.initExists = this.initLoaderEl.show = false;49 },50 emptyExists: false,51 emptyDisplay: () => {52 if (this.initMethods.emptyExists)53 return;54 this.emptyTemplate.insert(this.emptyEl);55 this.initMethods.emptyExists = true;56 },57 emptyRemove: () => {58 if (!this.initMethods.emptyExists)59 return;60 this.emptyTemplate.remove();61 this.initMethods.emptyExists = false;62 },63 errorExists: false,64 errorDisplay: () => {65 if (this.initMethods.errorExists)66 return;67 this.errorTemplate.insert(this.errorEl);68 this.initMethods.errorExists = true;69 },70 errorRemove: () => {71 if (!this.initMethods.errorExists)72 return;73 this.errorTemplate.remove();74 this.initMethods.errorExists = false;75 },76 };77 this.refreshing = false;78 this.pullDownMethods = {79 hasError: false,80 hasEnd: false,81 loading: false,82 trigger: false,83 reset: () => {84 if (this.pullDownMethods.hasError) {85 this.downErrorTemplate.remove();86 this.pullDownMethods.hasError = false;87 }88 if (this.pullDownMethods.hasEnd) {89 this.downNoMoreTemplate.remove();90 this.pullDownMethods.hasEnd = false;91 }92 },93 load: () => {94 if (this.isRunning || this.pullDownMethods.hasEnd)95 return;96 this.pullDownMethods.loading = true;97 if (this.pullDownMethods.hasError) {98 this.downErrorTemplate.remove();99 this.pullDownMethods.hasError = false;100 }101 this.bottomLoaderEl.show = true;102 const params = {103 currentPage: this.currentPage + 1,104 behavior: "down",105 };106 this.paginationFn(params)107 .pipe(finalize(() => (this.pullDownMethods.loading = false)))108 .subscribe((result) => {109 this.handlePaginationResult(params, result);110 }, err => this.handlePaginationError("down"));111 },112 loadSuccess: () => {113 this.pullDownMethods.loading = this.bottomLoaderEl.show = false;114 this.currentPage++;115 },116 loadError: () => {117 this.pullDownMethods.loading = this.bottomLoaderEl.show = false;118 this.pullDownMethods.hasError = false;119 this.downErrorTemplate.insert(this.bottomAreaEl);120 },121 loadEnd: () => {122 this.pullDownMethods.loading = this.bottomLoaderEl.show = false;123 this.pullDownMethods.hasEnd = true;124 this.downNoMoreTemplate.insert(this.bottomAreaEl);125 },126 };127 }128 set setScrollContainer(v) {129 this.classManage.toggleClass("__scroll", v);130 }131 created() {132 this.pgEl = this.shadowRoot.querySelector(".voyo-pagination");133 this.classManage = new ClassManage(this.pgEl);134 this.refresher = this.shadowRoot.querySelector("#refresher");135 this.refresher.defaultEffects = false;136 this.refresher.disabledScroll = true;137 this.refresher.addEventListener("refresherRefresh", (e) => {138 this.toRefresh(e.detail);139 });140 this.refresher.executeAfterConnected.execute(() => {141 this.scrollContainer = this.refresher.scrollContainer;142 this.handleScrollDown(this.refresher.listenScroll, this.scrollContainer);143 });144 }145 handleScrollDown(listenScrcoll, scrollContainer) {146 let containerHeight = scrollContainer.offsetHeight;147 let thresholdDistance;148 listenScrcoll.subscribe(({ e, v }) => {149 if (this.initMethods.initExists || !this.initMethods.initComplete)150 return;151 thresholdDistance = scrollContainer.scrollHeight - containerHeight - v;152 if (thresholdDistance <= this.lowerThreshold &&153 !this.pullDownMethods.trigger) {154 this.pullDownMethods.trigger = true;155 this.toPullDown();156 }157 else if (thresholdDistance > this.lowerThreshold &&158 this.pullDownMethods.trigger) {159 this.pullDownMethods.trigger = false;160 }161 });162 }163 get isRunning() {164 return (this.initMethods.initExists ||165 this.refreshing ||166 this.pullDownMethods.loading);167 }168 initRefresh() {169 this.pullDownMethods.reset();170 this.initMethods.initDisplay();171 }172 toRefresh(refreshRestore) {173 if (this.isRunning)174 return refreshRestore();175 this.refreshing = true;176 this.pullDownMethods.reset();177 const params = {178 currentPage: 1,179 behavior: "refresh",180 };181 this.paginationFn(params)182 .pipe(finalize(() => {183 refreshRestore();184 this.refreshing = false;185 }))186 .subscribe((result) => {187 if (this.handlePaginationResult(params, result)) {188 this.currentPage = 1;189 }190 }, err => this.handlePaginationError("refresh"));191 }192 handlePaginationResult(params, result) {193 const setting = this.setting.pgSetting;194 if (setting.isEmpty(params, result)) {195 this.initMethods.emptyDisplay();196 return "empty";197 }198 else if (setting.isEnd(params, result)) {199 //clean200 this.pullDownMethods.loadEnd();201 return "end";202 }203 else if (setting.isError(params, result)) {204 this.initMethods.emptyRemove();205 this.handlePaginationError(params.behavior);206 return "error";207 }208 else {209 if (params.behavior === "down")210 this.pullDownMethods.loadSuccess();211 return "true";212 }213 }214 handlePaginationError(type) {215 if (type === "init") {216 this.initMethods.errorDisplay();217 }218 else if (type === "down") {219 this.pullDownMethods.loadError();220 }221 else if (type === "refresh") {222 console.debug("pagination refresh error");223 }224 }225 toPullDown() {226 this.pullDownMethods.load();227 }228 handlerResource() {229 const pgSetting = this.setting.pgSetting;230 this._errorImg = this.errorImg || pgSetting.errorImg;231 this._errorText = this.errorText || pgSetting.errorText;232 this._emptyImg = this.emptyImg || pgSetting.emptyImg;233 this._emptyText = this.emptyText || pgSetting.emptyText;234 this._downNoMoreText = this.downNoMoreText || pgSetting.downNoMoreText;235 this._downErrorText = this.downErrorText || pgSetting.downErrorText;236 }237 entryStart() {238 this.initMethods.initDisplay();239 }240 mounted() {241 this.bottomLoaderEl = this.shadowRoot.querySelector("#bottom-loader");242 this.bottomAreaEl = this.shadowRoot.querySelector(".voyo-pagination-bottom-area");243 this.emptyEl = this.shadowRoot.querySelector(".voyo-pagination-empty");244 this.errorEl = this.shadowRoot.querySelector(".voyo-pagination-error");245 this.initLoaderEl = this.shadowRoot.querySelector("#init-loader");246 this.initLoaderEl.absCenter = true;247 this.initLoaderEl.size = "mini";248 this.bottomLoaderEl.size = "mini";249 this.handlerResource();250 this.handleRefreshSvg();251 this.bottomAreaEl.addEventListener("click", () => {252 if (this.pullDownMethods.hasError) {253 this.toPullDown();254 }255 });256 this.entryStart();257 }258 handleRefreshSvg() {259 const svgContainer = this.shadowRoot.querySelector(".voyo-svg-container");260 this.circleLoader.render();261 const svgEl = this.circleLoader.getSvg();262 const svgLoaderEl = this.circleLoader.getSvgLoader();263 svgContainer.appendChild(svgEl);264 const run = () => {265 this.refresher.refreshAnimation.percentEvent.subscribe(({ triggerDistancePercent }) => {266 this.circleLoader.drawSrcByPercent(triggerDistancePercent);267 });268 this.refresher.refreshTriggerSubject.subscribe(isTrigger => {269 if (isTrigger) {270 svgEl.parentElement && svgEl.parentElement.removeChild(svgEl);271 svgContainer.appendChild(svgLoaderEl);272 }273 else {274 svgLoaderEl.parentElement &&275 svgLoaderEl.parentElement.removeChild(svgLoaderEl);276 svgContainer.appendChild(svgEl);277 }278 });279 };280 if (this.refresher.voyoConnectCompleted) {281 run();282 }283 else {284 this.refresher.voyoConnected.subscribe(() => run());285 }286 }287};288__decorate([289 VoyoInput({ name: "scrollContainer" })290], PaginationComponent.prototype, "setScrollContainer", null);291__decorate([292 VoyoInput({})293], PaginationComponent.prototype, "errorImg", void 0);294__decorate([295 VoyoInput({})296], PaginationComponent.prototype, "emptyImg", void 0);297__decorate([298 VoyoInput({})299], PaginationComponent.prototype, "errorText", void 0);300__decorate([301 VoyoInput({})302], PaginationComponent.prototype, "emptyText", void 0);303__decorate([304 VoyoInput({})305], PaginationComponent.prototype, "downNoMoreText", void 0);306__decorate([307 VoyoInput({})308], PaginationComponent.prototype, "downErrorText", void 0);309__decorate([310 VoyoInput({ name: "useRefresh", defaultValue: false })311], PaginationComponent.prototype, "useRefresh", void 0);312__decorate([313 VoyoInput({ defaultValue: 100 })314], PaginationComponent.prototype, "lowerThreshold", void 0);315__decorate([316 IOCAutowired({ name: SETTING_IOC_NAME })317], PaginationComponent.prototype, "setting", void 0);318__decorate([319 VoyoInput({ name: "paginationFn" })320], PaginationComponent.prototype, "paginationFn", void 0);321__decorate([322 VoyoTemplate({323 render() {324 return `<span>${this._downNoMoreText}</span>`;325 },326 tag: "div",327 className: "voyo-pagination-text-des",328 })329], PaginationComponent.prototype, "downNoMoreTemplate", void 0);330__decorate([331 VoyoTemplate({332 render() {333 return `<span>${this._downErrorText}</span>`;334 },335 tag: "div",336 className: "voyo-pagination-text-des",337 })338], PaginationComponent.prototype, "downErrorTemplate", void 0);339__decorate([340 VoyoTemplate({341 render() {342 return `343 <img src="${this._errorImg}" class="_image"/>344 <view class="_title">345 ${this._errorText}346 </view>347 `;348 },349 tag: "div",350 className: "voyo-figure",351 renderCallback(el) {352 el.querySelector("._image").addEventListener("click", () => {353 this.initMethods.initDisplay();354 });355 },356 })357], PaginationComponent.prototype, "errorTemplate", void 0);358__decorate([359 VoyoTemplate({360 render() {361 return `362 <img src="${this._emptyImg}" class="_image"/>363 <view class="_title">364 ${this._emptyText}365 </view>366 `;367 },368 tag: "div",369 className: "voyo-figure",370 renderCallback(el) {371 el.querySelector("._image").addEventListener("click", () => {372 this.initMethods.initDisplay();373 });374 },375 })376], PaginationComponent.prototype, "emptyTemplate", void 0);377PaginationComponent = __decorate([378 VoyoDor({379 template: `380<div class="voyo-pagination">381 <voyoc-loader id="init-loader"></voyoc-loader>382 <voyoc-refresh id="refresher" effects="0">383 <div slot="refresher">384 <div class="voyo-svg-container"></div>385 </div>386 <slot></slot>387 <div class="voyo-pagination-bottom-area">388 <voyoc-loader id="bottom-loader"></voyoc-loader>389 </div>390 </voyoc-refresh>391 <div class="voyo-pagination-empty">392 393 </div>394 <div class="voyo-pagination-error">395 396 </div>397</div>398 `,399 styles: '.voyo-figure{display:flex;justify-content:center;flex-flow:column;padding:2.2rem 1rem 2rem}.voyo-figure ._image{width:8em;height:8em;margin:0 auto}.voyo-figure ._title{font-size:var(--size-small);color:var(--color-font-content)}.voyo-figure ._content,.voyo-figure ._title{padding:1rem;text-align:center}.voyo-pagination{z-index:1}.voyo-pagination.__scroll{position:absolute;top:0;left:0;width:100%;height:100%;overflow-x:hidden}.voyo-svg-container svg{width:50px}.voyo-pagination-bottom-area{width:100%;display:none;height:50px;display:flex;justify-content:center;align-items:center}.voyo-pagination-text-des{font-size:var(--size-mini)!important;color:var(--color-font-des)}',400 })401], PaginationComponent);...

Full Screen

Full Screen

FastVue.js

Source:FastVue.js Github

copy

Full Screen

1/**2 * FastVue 3 * version 1.3.44 * 5 * 6 * author: Wangwenwei (970073804@qq.com)7 * 8 */9class FastVue {10 constructor({ appName, templatePathRoot, config, plugins }) {11 this.appName = appName;12 this.templatePathRoot = templatePathRoot;13 this.config = config;14 this.plugins = plugins;15 this.$VM = {};16 this.idNameList = [];17 this.templateList = {};18 this.isDebug = true;19 }20 /**21 * 安装配置22 */23 initConfig() {24 this.log('安装配置');25 }26 /**27 * 日志输出28 * @param {*} obj 29 */30 log(obj) {31 this.isDebug && console.log(obj)32 }33 /**34 * 安装插件,即 Vue.use()35 * @param {*} plugin 36 */37 initPlugin(plugin) {38 this.log('安装插件');39 if (!Vue) {40 this.throwError('FastVue initPlugin:找不到 Vue');41 }42 if (!plugin) {43 this.throwError('FastVue initPlugin:你不能使用一个不存在的插件');44 }45 Vue.use(plugin);46 }47 /**48 * 注册组件49 */50 async regComponent(componentId, initdata = {}, initMethods = {}, loadCss = false) {51 if (!componentId) {52 this.throwError('你使用了注册组件功能,但该组件没有指定参数!')53 }54 //根据id初始化组件55 let res = await this.makeComponent(componentId, 1, initdata, initMethods, loadCss)56 return res;57 }58 /**59 * 包裹组件60 * 61 * @param {*} container 被包裹的div的id62 * @param {*} componentId 组件库中用什么组件包裹63 * @param {*} initdata 包裹组件的传值64 * @param {*} initMethods 包裹组件的方法65 */66 async wrapComponent(container, wrapComponentId, initdata = {}, initMethods = {}) {67 if (!wrapComponentId) {68 this.throwError('你使用了包裹组件功能,但该组件没有指定参数!')69 }70 if (!container || typeof container != 'string') {71 this.throwError('container 参数不正确,应该是字符串')72 }73 let _cont = document.querySelector(container);74 if (!_cont) {75 this.throwError('你给的 container 参数没法获取到具体DOM对象');76 }77 //取出 container 里作为嵌套组件模板内容78 let innerHtml = _cont.innerHTML;79 //初始化 container 组件80 Vue.component(container.replace("#", ""), {81 props: ['componentkey', 'propsdata'],82 template: innerHtml,83 methods: initMethods84 });85 //清除 container 里的内容86 _cont.innerHTML = "";87 //初始化绑定对象88 return await this.makeComponent(wrapComponentId, container, initdata)89 }90 /**91 * 异常抛出92 * @param {*} msg 93 */94 throwError(msg) {95 throw new Error(`FastVue Error: ${msg}`)96 }97 /**98 * 99 * 获取VM对象100 * @param {*} container 101 * @param {*} componentId 102 * @returns 103 */104 async getVM(container, componentId) {105 let _vm = await this.pushComponent(container, componentId);106 return _vm;107 }108 /**109 * 容器中放置组件110 * 111 * @param {*} container 112 * @param {*} componentId 113 * @param {*} initdata 114 * @param {*} initMethods 115 * @returns 116 */117 async pushComponent(container, componentId, initdata = {}, initMethods = {}, loadCss = false) {118 this.log('放置一个组件');119 if (!container || typeof container != 'string') {120 this.throwError('container 参数不正确,应该是字符串')121 }122 let _cont = document.querySelector(container);123 if (!_cont) {124 this.throwError('你给的 container 参数没法获取到具体DOM对象');125 }126 // 放置容器127 this.pushDiv(_cont, componentId);128 if (!this.$VM[`${container}`]) {129 this.$VM[`${container}`] = {};130 }131 let _VM = await this.makeComponent(componentId, 0, initdata, initMethods, loadCss)132 this.$VM[`${container}`][`${componentId}`] = _VM;133 return _VM;134 }135 /**136 * 创造Vue组件137 * @param { 组件id } componentId 138 * @param { 创造类型 } type 默认为0,即创建VM对象,1为注册Vue组件139 * @param { 初始化数据 } initdata 140 * @param { 初始化方法 } initMethods 141 * @returns VM对象142 */143 async makeComponent(144 componentId,145 type = 0,146 initdata = {},147 initMethods = {},148 loadCss = false149 ) {150 // 加载组件151 let _tpl = await this.loadTemplate(componentId);152 if (!_tpl) {153 this.throwError(`组件 ${componentId}找不到`);154 }155 // 加载组件脚本156 let _script = await this.getComponentScript(componentId);157 if (loadCss) {158 await this.loadCss(componentId);159 }160 this.log('组件脚本数据信息为', _script);161 // 如果type为字符串,说明是包裹组件162 if (typeof type == 'string') {163 let _cont = document.querySelector(type);164 if (!_cont) {165 this.throwError(' makeComponent 传进了字符串类型的type,但DOM中无法寻得该元素');166 }167 // 赋予嵌套组件id168 let _data = this.initComponentData(initdata, _script.data);169 _data['contentComponent'] = type.replace("#", "");170 const vm = new Vue({171 el: type,172 template: _tpl.template,173 data: _data,174 computed: _script.computed,175 created: _script.created,176 methods: this.initComponentData(initMethods, _script.methods)177 });178 console.log(vm);179 return vm;180 }181 switch (type) {182 case 1://注册组件183 const that = this;184 return Vue.component(componentId, {185 props: ['componentkey', 'propsdata'],186 template: _tpl.template,187 data: function () {188 return that.initComponentData(initdata, _script.data);189 },190 computed: _script.computed,191 created: _script.created,192 methods: that.initComponentData(initMethods, _script.methods)193 });194 break;195 case 0://实例化VM对象196 default:197 return new Vue({198 el: `#${componentId}`,199 template: _tpl.template,200 data: this.initComponentData(initdata, _script.data),201 computed: _script.computed,202 created: _script.created,203 methods: this.initComponentData(initMethods, _script.methods)204 });205 break;206 }207 }208 /**209 * 解析组件数据210 * @param {*} initdata 211 * @param {*} defaultData 212 * @returns 213 */214 initComponentData(initdata, defaultData) {215 let _data = {};216 for (const key in defaultData) {217 if (Object.hasOwnProperty.call(defaultData, key)) {218 const element = defaultData[key];219 if (initdata[key] != undefined) {220 _data[key] = initdata[key]221 } else {222 _data[key] = element;223 }224 }225 }226 return _data;227 }228 /**229 * 模板解析230 * @param {*} componentId 231 * @returns 232 */233 async loadTemplate(componentId) {234 if (!this.templateList[`${componentId}`]) {235 let _tpl = await this.getTemplateFiles(`${this.templatePathRoot}${componentId}/${componentId}.html`);236 this.templateList[`${componentId}`] = _tpl;237 }238 return this.templateList[`${componentId}`];239 }240 async loadCss(componentId) {241 if (!$) {242 this.throwError('请先加载JQ库');243 }244 let url = `${this.templatePathRoot}${componentId}/${componentId}.css`;245 return new Promise(async (resolve, reject) => {246 let file_exist = await this.IsExistsFile(url)247 if (file_exist) {248 console.log('css 存在');249 var head = document.getElementsByTagName('head')[0];250 var link = document.createElement('link');251 link.type = 'text/css';252 link.rel = 'stylesheet';253 link.href = url;254 head.appendChild(link);255 resolve({256 cssObj: url257 })258 } else {259 console.log('css 不存在');260 resolve({261 cssObj: null262 })263 }264 })265 }266 async IsExistsFile(filepath) {267 return new Promise((resolve, reject) => {268 try {269 var xmlhttp = null;270 if (window.XMLHttpRequest) {271 xmlhttp = new XMLHttpRequest();272 } else if (window.ActiveXObject) {273 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");274 }275 xmlhttp.open("GET", filepath, false);276 xmlhttp.send();277 if (xmlhttp.readyState == 4) {278 if (xmlhttp.status == 200) resolve(true); //url存在 279 else if (xmlhttp.status == 404) resolve(false); //url不存在 280 else resolve(false);//其他状态 281 }282 } catch (error) {283 resolve(false)284 }285 })286 }287 /**288 * 组件脚本部分解析289 * @param {*} componentId 290 * @returns 291 */292 async getComponentScript(componentId) {293 return new Promise((resolve, reject) => {294 $.getScript(295 `${this.templatePathRoot}${componentId}/${componentId}.js`296 , function (res) {297 //解析data298 let _data = returnData();299 returnData = null;300 //解析created301 let _created = returnCreated();302 returnCreated = null;303 let _computed = {};304 try {305 //解析computed306 _computed = returnComputed();307 returnComputed = null;308 } catch (e) {309 // console.log(e.message);//sojson is undefined310 }311 //解析methods312 let _methods = returnMethods();313 returnMethods = null;314 resolve({315 data: _data,316 computed: _computed,317 created: _created,318 methods: _methods319 });320 });321 })322 }323 /**324 * 获取模板文件325 * @param {*} filePath 326 * @returns 327 */328 async getTemplateFiles(filePath) {329 if (!$) {330 this.throwError('请先加载JQ库');331 }332 return new Promise((resolve, reject) => {333 $.get(filePath).then(function (res) {334 resolve({335 template: res336 })337 });338 })339 }340 /**341 * 容器放置操作 342 * @param {*} container 343 * @param {*} idName 344 */345 pushDiv(container, idName = new Date().getTime()) {346 let _div = document.createElement('div');347 _div.id = idName;348 container.appendChild(_div)349 }350 /**351 * 批量放置组件到容器中352 * @param {*} compntListArray 353 * @returns 354 */355 async batchPushCompnt(compntListArray) {356 if (!Array.isArray(compntListArray)) {357 this.throwError('batchPushCompnt 第一个参数必须是数组');358 }359 const that = this;360 return new Promise.all(compntListArray.map(async (item) => {361 return new Promise((resolve) => {362 resolve(that.pushComponent(item))363 })364 }))365 }...

Full Screen

Full Screen

FastVue_test.js

Source:FastVue_test.js Github

copy

Full Screen

1/**2 * FastVue 3 * version 1.3.34 * 5 * 6 * author: Wangwenwei (970073804@qq.com)7 * 8 */9class FastVue {10 constructor({ appName, templatePathRoot, config, plugins }) {11 this.appName = appName;12 this.templatePathRoot = templatePathRoot;13 this.config = config;14 this.plugins = plugins;15 this.$VM = {};16 this.idNameList = [];17 this.templateList = {};18 this.isDebug = true;19 }20 /**21 * 安装配置22 */23 initConfig() {24 this.log('安装配置');25 }26 /**27 * 日志输出28 * @param {*} obj 29 */30 log(obj) {31 this.isDebug && console.log(obj)32 }33 /**34 * 安装插件,即 Vue.use()35 * @param {*} plugin 36 */37 initPlugin(plugin) {38 this.log('安装插件');39 if (!Vue) {40 this.throwError('FastVue initPlugin:找不到 Vue');41 }42 if (!plugin) {43 this.throwError('FastVue initPlugin:你不能使用一个不存在的插件');44 }45 Vue.use(plugin);46 }47 /**48 * 注册组件49 */50 async regComponent(componentId, initdata = {}, initMethods = {}) {51 if (!componentId) {52 this.throwError('你使用了注册组件功能,但该组件没有指定参数!')53 }54 //根据id初始化组件55 let res = await this.makeComponent(componentId, 1, initdata, initMethods)56 return res;57 }58 /**59 * 包裹组件60 * 61 * @param {*} container 被包裹的div的id62 * @param {*} componentId 组件库中用什么组件包裹63 * @param {*} initdata 包裹组件的传值64 * @param {*} initMethods 包裹组件的方法65 */66 async wrapComponent(container, wrapComponentId, initdata = {}, initMethods = {}) {67 if (!wrapComponentId) {68 this.throwError('你使用了包裹组件功能,但该组件没有指定参数!')69 }70 if (!container || typeof container != 'string') {71 this.throwError('container 参数不正确,应该是字符串')72 }73 let _cont = document.querySelector(container);74 if (!_cont) {75 this.throwError('你给的 container 参数没法获取到具体DOM对象');76 }77 //取出 container 里作为嵌套组件模板内容78 let innerHtml = _cont.innerHTML;79 //初始化 container 组件80 Vue.component(container.replace("#", ""), {81 props: ['componentkey', 'propsdata'],82 template: innerHtml,83 methods: initMethods84 });85 //清除 container 里的内容86 _cont.innerHTML = "";87 //初始化绑定对象88 return await this.makeComponent(wrapComponentId, container, initdata)89 }90 /**91 * 异常抛出92 * @param {*} msg 93 */94 throwError(msg) {95 throw new Error(`FastVue Error: ${msg}`)96 }97 /**98 * 99 * 获取VM对象100 * @param {*} container 101 * @param {*} componentId 102 * @returns 103 */104 async getVM(container, componentId) {105 let _vm = await this.pushComponent(container, componentId);106 return _vm;107 }108 /**109 * 容器中放置组件110 * 111 * @param {*} container 112 * @param {*} componentId 113 * @param {*} initdata 114 * @param {*} initMethods 115 * @returns 116 */117 async pushComponent(container, componentId, initdata = {}, initMethods = {}, loadCss = false) {118 this.log('放置一个组件');119 if (!container || typeof container != 'string') {120 this.throwError('container 参数不正确,应该是字符串')121 }122 let _cont = document.querySelector(container);123 if (!_cont) {124 this.throwError('你给的 container 参数没法获取到具体DOM对象');125 }126 // 放置容器127 this.pushDiv(_cont, componentId);128 if (!this.$VM[`${container}`]) {129 this.$VM[`${container}`] = {};130 }131 let _VM = await this.makeComponent(componentId, 0, initdata, initMethods, loadCss)132 this.$VM[`${container}`][`${componentId}`] = _VM;133 return _VM;134 }135 /**136 * 创造Vue组件137 * @param { 组件id } componentId 138 * @param { 创造类型 } type 默认为0,即创建VM对象,1为注册Vue组件139 * @param { 初始化数据 } initdata 140 * @param { 初始化方法 } initMethods 141 * @returns VM对象142 */143 async makeComponent(144 componentId,145 type = 0,146 initdata = {},147 initMethods = {},148 loadCss = false149 ) {150 // 加载组件151 let _tpl = await this.loadTemplate(componentId);152 if (!_tpl) {153 this.throwError(`组件 ${componentId}找不到`);154 }155 // 加载组件脚本156 let _script = await this.getComponentScript(componentId);157 if (loadCss) {158 await this.loadCss(componentId);159 }160 this.log('组件脚本数据信息为', _script);161 // 如果type为字符串,说明是包裹组件162 if (typeof type == 'string') {163 let _cont = document.querySelector(type);164 if (!_cont) {165 this.throwError(' makeComponent 传进了字符串类型的type,但DOM中无法寻得该元素');166 }167 // 赋予嵌套组件id168 let _data = this.initComponentData(initdata, _script.data);169 _data['contentComponent'] = type.replace("#", "");170 const vm = new Vue({171 el: type,172 template: _tpl.template,173 data: _data,174 computed: _script.computed,175 created: _script.created,176 methods: this.initComponentData(initMethods, _script.methods)177 });178 console.log(vm);179 return vm;180 }181 switch (type) {182 case 1://注册组件183 const that = this;184 return Vue.component(componentId, {185 props: ['componentkey', 'propsdata'],186 template: _tpl.template,187 data: function () {188 return that.initComponentData(initdata, _script.data);189 },190 computed: _script.computed,191 created: _script.created,192 methods: that.initComponentData(initMethods, _script.methods)193 });194 break;195 case 0://实例化VM对象196 default:197 return new Vue({198 el: `#${componentId}`,199 template: _tpl.template,200 data: this.initComponentData(initdata, _script.data),201 computed: _script.computed,202 created: _script.created,203 methods: this.initComponentData(initMethods, _script.methods)204 });205 break;206 }207 }208 /**209 * 解析组件数据210 * @param {*} initdata 211 * @param {*} defaultData 212 * @returns 213 */214 initComponentData(initdata, defaultData) {215 let _data = {};216 for (const key in defaultData) {217 if (Object.hasOwnProperty.call(defaultData, key)) {218 const element = defaultData[key];219 if (initdata[key] != undefined) {220 _data[key] = initdata[key]221 } else {222 _data[key] = element;223 }224 }225 }226 return _data;227 }228 /**229 * 模板解析230 * @param {*} componentId 231 * @returns 232 */233 async loadTemplate(componentId) {234 if (!this.templateList[`${componentId}`]) {235 let _tpl = await this.getTemplateFiles(`${this.templatePathRoot}${componentId}/${componentId}.html`);236 this.templateList[`${componentId}`] = _tpl;237 }238 return this.templateList[`${componentId}`];239 }240 async loadCss(componentId) {241 if (!$) {242 this.throwError('请先加载JQ库');243 }244 let url = `${this.templatePathRoot}${componentId}/${componentId}.css`;245 return new Promise(async (resolve, reject) => {246 let file_exist = await this.IsExistsFile(url)247 if (file_exist) {248 console.log('css 存在');249 var head = document.getElementsByTagName('head')[0];250 var link = document.createElement('link');251 link.type = 'text/css';252 link.rel = 'stylesheet';253 link.href = url;254 head.appendChild(link);255 resolve({256 cssObj: res257 })258 } else {259 console.log('css 不存在');260 resolve({261 cssObj: null262 })263 }264 })265 }266 async IsExistsFile(filepath) {267 return new Promise((resolve, reject) => {268 try {269 var xmlhttp = null;270 if (window.XMLHttpRequest) {271 xmlhttp = new XMLHttpRequest();272 } else if (window.ActiveXObject) {273 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");274 }275 xmlhttp.open("GET", filepath, false);276 xmlhttp.send();277 if (xmlhttp.readyState == 4) {278 if (xmlhttp.status == 200) resolve(true); //url存在 279 else if (xmlhttp.status == 404) resolve(false); //url不存在 280 else resolve(false);//其他状态 281 }282 } catch (error) {283 resolve(false)284 }285 })286 }287 /**288 * 组件脚本部分解析289 * @param {*} componentId 290 * @returns 291 */292 async getComponentScript(componentId) {293 return new Promise((resolve, reject) => {294 $.getScript(295 `${this.templatePathRoot}${componentId}/${componentId}.js`296 , function (res) {297 //解析data298 let _data = returnData();299 returnData = null;300 //解析created301 let _created = returnCreated();302 returnCreated = null;303 let _computed = {};304 try {305 //解析computed306 _computed = returnComputed();307 returnComputed = null;308 } catch (e) {309 // console.log(e.message);//sojson is undefined310 }311 //解析methods312 let _methods = returnMethods();313 returnMethods = null;314 resolve({315 data: _data,316 computed: _computed,317 created: _created,318 methods: _methods319 });320 });321 })322 }323 /**324 * 获取模板文件325 * @param {*} filePath 326 * @returns 327 */328 async getTemplateFiles(filePath) {329 if (!$) {330 this.throwError('请先加载JQ库');331 }332 return new Promise((resolve, reject) => {333 $.get(filePath).then(function (res) {334 resolve({335 template: res336 })337 });338 })339 }340 /**341 * 容器放置操作 342 * @param {*} container 343 * @param {*} idName 344 */345 pushDiv(container, idName = new Date().getTime()) {346 let _div = document.createElement('div');347 _div.id = idName;348 container.appendChild(_div)349 }350 /**351 * 批量放置组件到容器中352 * @param {*} compntListArray 353 * @returns 354 */355 async batchPushCompnt(compntListArray) {356 if (!Array.isArray(compntListArray)) {357 this.throwError('batchPushCompnt 第一个参数必须是数组');358 }359 const that = this;360 return new Promise.all(compntListArray.map(async (item) => {361 return new Promise((resolve) => {362 resolve(that.pushComponent(item))363 })364 }))365 }...

Full Screen

Full Screen

app.js

Source:app.js Github

copy

Full Screen

1/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */2/* The Whistle technology trial app. C.Veness 2017-2018 */3/* */4/* App comprises following (composed) sub-apps: */5/* - report. (public incident reporting pages) */6/* - admin. (pages for interactively managing data) */7/* - publish. (publicly available aggregated metreics) */8/* - sms. (sms incident reporting) */9/* - twilio. (RESTful API for Twilio webhooks) */10/* */11/* © 2017-2018 Cambridge University / The Whistle | MIT licence */12/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */13/* eslint no-shadow:off *//* app is already declared in the upper scope */14import Koa from 'koa'; // Koa framework15import body from 'koa-body'; // body parser16import compose from 'koa-compose'; // middleware composer17import compress from 'koa-compress'; // HTTP compression18import session from 'koa-session'; // session for flash messages19import dateFormat from 'dateformat'; // Steven Levithan's dateFormat()20import dotenv from 'dotenv'; // load environment variables from a .env file into process.env21dotenv.config();22import FormGenerator from './lib/form-generator.js';23// models are imported to invoke their init() methods24import FormSpecification from './models/form-specification.js';25import Notification from './models/notification.js';26import Report from './models/report.js';27import Resource from './models/resource.js';28import Submission from './models/submission.js';29import Update from './models/update.js';30import User from './models/user.js';31import Group from './models/group.js';32import ReportSession from './models/report-session.js';33const app = new Koa();34// for user-agents reporting35app.proxy = true;36global.start = new Date(); // to report counts since given timestamp37global.userAgents = [];38/* set up middleware which will be applied to each request - - - - - - - - - - - - - - - - - - - */39// return response time in X-Response-Time header40app.use(async function responseTime(ctx, next) {41 const t1 = Date.now();42 await next();43 const t2 = Date.now();44 ctx.response.set('X-Response-Time', Math.ceil(t2-t1)+'ms');45});46// HTTP compression47app.use(compress({}));48// only search-index report subdomain49app.use(async function robots(ctx, next) {50 await next();51 if (ctx.request.hostname.slice(0, 6) != 'report') ctx.response.set('X-Robots-Tag', 'noindex, nofollow');52});53// parse request body into ctx.request.body54// - multipart allows parsing of enctype=multipart/form-data55app.use(body({ multipart: true }));56// set signed cookie keys for JWT cookie & session cookie; keys are rotated monthly with 3-month57// lifetime, stem is taken from environment variable to protect against source code leak; note keys58// are set on app startup (which on Heroku happens at least daily), not per request59const date = { y: new Date().getFullYear(), m: new Date().getMonth(), d: 1 };60app.keys = [ 0, 1, 2 ].map(x => process.env.COOKIE_KEY + dateFormat(new Date(date.y, date.m-x, date.d), '-yyyy-mm'));61// ctx.session uses signed session cookies, with no server storage; it is used for holding submitted62// report details in the report sub-app, and for flash messages across all apps63app.use(session({ maxAge: 1000*60*60*24*7 }, app));64// invoke model init() methods to ensure current validation is applied to all databases (in65// development or staging environments, all databases ending with '-test'; in production environment,66// all databases not ending in '-test'; 'user' database is initialised in all cases)67async function initModels() {68 if (global.it) return 0; // don't bother reinitialising within mocha tests69 const t1 = Date.now();70 const databases = Object.keys(process.env)71 .filter(env => env.slice(0, 3)=='DB_' && env!='DB_USERS')72 .map(db => db.slice(3).toLowerCase().replace(/_/g, '-'))73 .filter(db => app.env=='production' ? !/-test$/.test(db) : /-test$/.test(db));74 // set up array of init methods...75 const initMethods = [];76 for (const db of databases) {77 initMethods.push(FormSpecification.init(db));78 initMethods.push(Notification.init(db));79 initMethods.push(Report.init(db));80 initMethods.push(Resource.init(db));81 initMethods.push(Submission.init(db));82 initMethods.push(Update.init(db));83 initMethods.push(Group.init(db));84 initMethods.push(ReportSession.init(db));85 }86 initMethods.push(User.init());87 // ... so that we can run all init methods in parallel88 try {89 await Promise.all(initMethods);90 } catch (e) {91 throw new Error(`Model initialisation failed: ${e.message}`);92 }93 return Date.now() - t1;94}95// model initialisation runs asynchronously and won't complete until after app startup, but that's96// fine: we've no reason to wait on model init's before responding to requests97initModels()98 .then(t => console.info(t?`${app.env=='production'?'live':'test'} database collections re-initialised (${t}ms)`:''))99 .catch(err => console.error(err));100async function buildForms() {101 const t1 = Date.now();102 await FormGenerator.buildAll();103 return Date.now() - t1;104}105// form building runs asynchronously and won't complete until after app startup, but that's fine:106// we've no reason to wait on form builds before responding to requests (a request will initiate a107// form build, and await on completion)108buildForms()109 .then(t => console.info(`All forms built (${t}ms)`))110 .catch(err => console.error('ERR (buildForms):', err.message));111// select sub-app (admin/api) according to host subdomain (could also be by analysing request.url);112// separate sub-apps can be used for modularisation of a large system, for different login/access113// rights for public/protected elements, and also for different functionality between api & web114// pages (content negotiation, error handling, handlebars templating, etc).115app.use(async function subApp(ctx, next) {116 // use subdomain to determine which app to serve: report. as default, or admin. or api117 ctx.state.subapp = ctx.request.hostname.split('.')[0]; // subdomain = part before first '.' of hostname118 // note: could use root part of path instead of sub-domains e.g. ctx.request.url.split('/')[1]119 await next();120});121import appAdmin from './app-admin/app-admin.js';122import appReport from './app-report/app-report.js';123import appSms from './app-sms/app-sms.js';124import appTextit from './app-textit/app-textit.js';125import appPublish from './app-publish/app-publish.js';126app.use(async function composeSubapp(ctx) { // note no 'next' after composed subapp127 switch (ctx.state.subapp) {128 case 'admin': await compose(appAdmin.middleware)(ctx); break;129 case 'report': await compose(appReport.middleware)(ctx); break;130 case 'sms': await compose(appSms.middleware)(ctx); break;131 case 'textit': await compose(appTextit.middleware)(ctx); break;132 case 'publish': await compose(appPublish.middleware)(ctx); break;133 default: // no recognised subdomain134 if (process.env.SUBAPP) {135 // eg for Heroku review apps where subdomain cannot be supplied, take subapp from env136 const subapp = await import(`./app-${process.env.SUBAPP}/app-${process.env.SUBAPP}.js`);137 await compose(subapp.default.middleware)(ctx); break;138 }139 if (ctx.state.subapp == 'localhost') { ctx.response.status = 403; break; } // avoid redirect loop140 // otherwise redirect to www static site (which should not be this app)141 ctx.response.redirect(ctx.request.protocol+'://'+'www.'+ctx.request.host+ctx.request.path);142 break;143 }144});145/* create server - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */146app.listen(process.env.PORT || 3000);147console.info(`${process.version} listening on port ${process.env.PORT || 3000} (${app.env})`);148/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */...

Full Screen

Full Screen

gradient.js

Source:gradient.js Github

copy

Full Screen

1// GRID2var gradient = (function () {3 // object update methods4 var objUpdaters = {5 objDefaults: function (grid, obj, secs) {6 obj.cps = 1;7 obj.heading += Math.PI / 180 * 5 * secs;8 obj.heading %= Math.PI * 2;9 }10 };11 // init methods12 var initMethods = {13 objDefaults: function (obj, grad, i) {14 obj.x = 0;15 obj.y = 0;16 obj.i = i;17 obj.radius = 5;18 obj.power = [1, 1, 1, 1];19 obj.cps = 0;20 obj.heading = 1;21 obj.radiusDir = 1;22 obj.updaterList = grad.updaters;23 }24 };25 // The Grid constructor26 var Grid = function (opt) {27 opt = opt || {};28 var grad = this;29 grad.ver = '0.1.1';30 grad.gridWidth = opt.gridWidth || 7;31 grad.gridHeight = opt.gridHeight || 6;32 grad.cellWidth = opt.cellWidth || 7;33 grad.cellHeight = opt.cellHeight || 6;34 grad.MIN_CPS = opt.MIN_CPS || 0.25;35 grad.MAX_CPS = opt.MAX_CPS || 1.5;36 grad.MIN_RADIUS = opt.MIN_RADIUS || 3;37 grad.MAX_RADIUS = opt.MAX_RADIUS || 5;38 grad.cells = [];39 grad.resetCells();40 grad.lt = new Date();41 // init methods42 grad.init = opt.init || ['objDefaults'];43 grad.initMethods = initMethods;44 // updaters45 grad.updaters = opt.updaters === undefined ? ['objDefaults'] : opt.updaters;46 grad.objUpdaters = objUpdaters;47 // setup objects48 grad.objs = [];49 var i = opt.objCount || 5,50 rand,51 r,52 g,53 b;54 // create objects With init method(s)55 while (i--) {56 var obj = {};57 // ensure calling defaults at least once58 initMethods.objDefaults(obj, grad, i);59 if (opt.init) {60 if (typeof opt.init === 'string') {61 initMethods[opt.init](obj, grad, i);62 }63 if (typeof opt.init === 'object') {64 opt.init.forEach(function (initMethodKey) {65 initMethods[initMethodKey](obj, grad, i);66 });67 }68 }69 grad.objs.push(obj);70 }71 // update for the first time72 grad.update();73 };74 // setup reset cells75 Grid.prototype.resetCells = function () {76 this.cells = [];77 var ci = 0,78 cellObj,79 cLen = this.gridWidth * this.gridHeight;80 while (ci < cLen) {81 cellObj = {82 i: ci,83 y: Math.floor(ci / this.gridWidth),84 x: ci % this.gridWidth,85 color: [0, 0, 0, 0]86 };87 this.cells.push(cellObj);88 ci += 1;89 }90 };91 Grid.prototype.capCellColors = function () {92 this.cells.forEach(function (cell) {93 var c = cell.color;94 c[0] = Math.floor(c[0] > 255 ? 255 : c[0]);95 c[1] = Math.floor(c[1] > 255 ? 255 : c[1]);96 c[2] = Math.floor(c[2] > 255 ? 255 : c[2]);97 c[3] = c[3] > 1 ? 1 : c[3];98 });99 };100 var upCellColor = function (grid, cell, obj, x, y) {101 d = u.distance(cell.x, cell.y, x, y);102 if (d <= obj.radius) {103 var per = 1 - d / obj.radius;104 var c = cell.color;105 c[0] += Math.floor(255 * per * obj.power[0]);106 c[1] += Math.floor(255 * per * obj.power[1]);107 c[2] += Math.floor(255 * per * obj.power[2]);108 c[3] += per * obj.power[3];109 }110 };111 var applyUpdaterList = function (grid, obj, secs) {112 obj.updaterList.forEach(function (updaterKey) {113 objUpdaters[updaterKey](grid, obj, secs);114 });115 };116 // Main Grid update method117 Grid.prototype.update = function () {118 var grid = this,119 now = new Date(),120 t = now - grid.lt,121 secs = t / 1000;122 // reset123 grid.resetCells();124 // increase color channel values for objects125 grid.objs.forEach(function (obj) {126 // apply updater list for the object127 applyUpdaterList(grid, obj, secs);128 // move object129 obj.x += Math.cos(obj.heading) * obj.cps * secs;130 obj.y += Math.sin(obj.heading) * obj.cps * secs;131 obj.x = u.mod(obj.x, grid.gridWidth);132 obj.y = u.mod(obj.y, grid.gridHeight);133 // update cells134 grid.cells.forEach(function (cell) {135 upCellColor(grid, cell, obj, obj.x - grid.gridWidth, obj.y);136 upCellColor(grid, cell, obj, obj.x + grid.gridWidth, obj.y);137 upCellColor(grid, cell, obj, obj.x, obj.y - grid.gridHeight);138 upCellColor(grid, cell, obj, obj.x, obj.y + grid.gridHeight);139 upCellColor(grid, cell, obj, obj.x - grid.gridWidth, obj.y - grid.gridHeight);140 upCellColor(grid, cell, obj, obj.x + grid.gridWidth, obj.y + grid.gridHeight);141 upCellColor(grid, cell, obj, obj.x - grid.gridWidth, obj.y + grid.gridHeight);142 upCellColor(grid, cell, obj, obj.x + grid.gridWidth, obj.y - grid.gridHeight);143 upCellColor(grid, cell, obj, obj.x, obj.y);144 });145 });146 // cap colors and set lt to now147 grid.capCellColors();148 grid.lt = now;149 };150 return {151 Grid: Grid,152 load: function (plug) {153 // load any init methods154 for (var key in plug.initMethods) {155 initMethods[key] = plug.initMethods[key];156 }157 // load any update methods158 for (var key in plug.objUpdaters) {159 objUpdaters[key] = plug.objUpdaters[key];160 }161 }162 };163}...

Full Screen

Full Screen

winFocus.js

Source:winFocus.js Github

copy

Full Screen

1/* winFocus() */2;(function() {3 var callBacks = { blur: [], focus: [], blurFocus: [] },4 hidden = "hidden"5 6 function winFocus() {7 var args = Array.prototype.slice.call(arguments, 0)8 init = true, initMethods = [], methods = []9 10 for (var x in args) {11 switch (typeof args[x]) {12 case 'boolean':13 init: args[x];14 break;15 case 'function':16 methods.push(args[x]);17 break;18 case 'object':19 if (args[x].hasOwnProperty('init')) init = args[x]["init"];20 if (args[x]["blur"]) {21 callBacks.blur.push(args[x]["blur"]);22 if (init) initMethods.push(args[x]["blur"]);23 }24 if (args[x]["focus"]) {25 callBacks.focus.push(args[x]["focus"]);26 if (init) initMethods.push(args[x]["focus"]);27 }28 if (args[x]["blurFocus"]) {29 callBacks.blurFocus.push(args[x]["blurFocus"]);30 if (init) initMethods.push(args[x]["blurFocus"]);31 }32 break;33 }34 }35 36 if (methods && methods.length) {37 if (init) initMethods.concat(methods);38 switch (methods.length) {39 case 1:40 callBacks.blurFocus.push(methods[0]);41 break;42 case 2:43 callBacks.blur.push(methods[0]);44 callBacks.focus.push(methods[1]);45 break;46 default:47 for (var x in methods) {48 switch (x%3) {49 case 0:50 callBacks.blur.push(methods[x]);51 break;52 case 1:53 callBacks.focus.push(methods[x]);54 break;55 case 2:56 callBacks.blurFocus.push(methods[x]);57 break;58 }59 }60 }61 }62 63 if (init && initMethods.length) for (var x in initMethods) initMethods[x].apply(window, [{ hidden: document[hidden] }]);64 }65 66 function onChange(e) {67 var eMap = { focus: false, focusin: false, pageshow: false, blur: true, focusout: true, pagehide: true };68 e = e || window.event;69 if (e) {70 e.hidden = e.type in eMap ? eMap[e.type] : document[hidden];71 window.visible = !e.hidden;72 exeCB(e);73 }74 else {75 try { onChange.call(document, new Event('visibilitychange')); }76 catch(err) { }77 }78 }79 80 function exeCB(e) {81 if (e.hidden && callBacks.blur.length) for (var x in callBacks.blur) callBacks.blur[x].apply(window, [e]);82 if (!e.hidden && callBacks.focus.length) for (var x in callBacks.focus) callBacks.focus[x].apply(window, [e]);83 if (callBacks.blurFocus.length) for (var x in callBacks.blurFocus) callBacks.blurFocus[x].apply(window, [e, !e.hidden]);84 }85 86 function initWinFocus() {87 if (console && console['log']) console.log('Initializing winFocus()');88 // Standard initialization89 if (hidden in document) // IE10 | FF20+90 document.addEventListener("visibilitychange", onChange);91 else if ((hidden = "mozHidden") in document) // Older FF Versions (?)92 document.addEventListener("mozvisibilitychange", onChange);93 else if ((hidden = "webkitHidden") in document) // Chrome94 document.addEventListener("webkitvisibilitychange", onChange);95 else if ((hidden = "msHidden") in document) // IE 4-696 document.addEventListener("msvisibilitychange", onChange);97 else if ((hidden = "onfocusin") in document) // IE7-998 document.onfocusin = document.onfocusout = onChange;99 else // All others:100 window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onChange;101 }102 103 winFocus.clear = function(what) {104 if (what && callBacks[what]) callBacks[what] = [];105 else if (void 0 == what || what == 'all') for (var x in callBacks) callBacks[x] = [];106 return callBacks;107 }108 109 winFocus.getCallBacks = function(what) {110 if (what && callBacks[what]) return callBacks[what];111 return callBacks;112 }113 114 if (document.readyState == "complete") initWinFocus();115 window.onload = initWinFocus;116 117 // add as window variable118 window.hasOwnProperty("winFocus")||(window.winFocus=winFocus);119 120 121 // add as a jQuery extension122 try {123 if (window.hasOwnProperty('jQuery') && jQuery) {124 jQuery.winFocus || (jQuery.extend({125 winFocus: function() {126 var args = Array.prototype.slice.call(arguments, 0);127 128 if (args[0] && /^clear/i.test(args[0])) return winFocus.clear.apply(jQuery);129 if (args[0] && /^callbacks$/i.test(args[0])) {130 args = Array.prototype.slice.call(arguments, 1);131 return winFocus.getCallBacks.apply(window, args);132 }133 134 return winFocus.apply(window, args);135 }136 }))137 }138 }139 catch (err) {}...

Full Screen

Full Screen

init_rand.js

Source:init_rand.js Github

copy

Full Screen

1gradient.load({2 initMethods: {3 randomPos: function (obj, grad) {4 obj.x = grad.gridWidth * Math.random();5 obj.y = grad.gridHeight * Math.random();6 },7 randomColor: function (obj, grad, i) {8 var r = Math.random(),9 g = Math.random(),10 b = Math.random(),11 a = Math.random();12 obj.power = [r, g, b, a];13 },14 randomHeading: function (obj, grad, i) {15 var r = Math.PI * 2 * Math.random();16 obj.heading = r;17 },18 randomSpeed: function (obj, grad, i) {19 obj.cps = grad.MIN_CPS + (Math.random() * (grad.MAX_CPS - grad.MIN_CPS));20 },21 randomRadius: function (obj, grad, i) {22 obj.radius = grad.MIN_RADIUS + (Math.random() * (grad.MAX_RADIUS - grad.MIN_RADIUS));23 },24 // random25 random: function (obj, grad, i) {26 grad.initMethods.randomPos(obj, grad, i);27 grad.initMethods.randomColor(obj, grad, i);28 grad.initMethods.randomHeading(obj, grad, i);29 grad.initMethods.randomSpeed(obj, grad, i);30 grad.initMethods.randomRadius(obj, grad, i);31 }32 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...15 const opts = vm.$options16 // 如果存在props17 if (opts.props) initProps(vm, opts.props)18 // 有方法methods的时候19 // if (opts.methods) initMethods(vm, opts.methods)20 // // 有data的时候21 // if (opts.data) {22 // initData(vm)23 // } else {24 // // observe(vm._data={}, true)25 // }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { initMethods } = require('playwright/lib/server/chromium/crBrowser');2const { Browser } = require('playwright/lib/server/chromium/crBrowser');3const { BrowserContext } = require('playwright/lib/server/chromium/crBrowser');4const { Page } = require('playwright/lib/server/chromium/crPage');5const { Frame } = require('playwright/lib/server/chromium/crFrame');6initMethods(Browser, BrowserContext, Page, Frame);7const { initMethods } = require('playwright/lib/server/chromium/crBrowser');8const { Browser } = require('playwright/lib/server/chromium/crBrowser');9const { BrowserContext } = require('playwright/lib/server/chromium/crBrowser');10const { Page } = require('playwright/lib/server/chromium/crPage');11const { Frame } = require('playwright/lib/server/chromium/crFrame');12initMethods(Browser, BrowserContext, Page, Frame);13const { initMethods } = require('playwright/lib/server/chromium/crBrowser');14const { Browser } = require('playwright/lib/server/chromium/crBrowser');15const { BrowserContext } = require('playwright/lib/server/chromium/crBrowser');16const { Page } = require('playwright/lib/server/chromium/crPage');17const { Frame } = require('playwright/lib/server/chromium/crFrame');18initMethods(Browser, BrowserContext, Page, Frame);19const { initMethods } = require('playwright/lib/server/chromium/crBrowser');20const { Browser } = require('playwright/lib/server/chromium/crBrowser');21const { BrowserContext } = require('playwright/lib/server/chromium/crBrowser');22const { Page } = require('playwright/lib/server/chromium/crPage');23const { Frame } = require('playwright/lib/server/chromium/crFrame');24initMethods(Browser, BrowserContext, Page, Frame);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { initMethods } = require('playwright/lib/client/initializer');2const { Page } = require('playwright/lib/client/page');3const { Browser } = require('playwright/lib/client/browser');4const { BrowserContext } = require('playwright/lib/client/browserContext');5const { CDPSession } = require('playwright/lib/client/cdpsession');6const { Frame } = require('playwright/lib/client/frame');7const { Worker } = require('playwright/lib/client/worker');8const { JSHandle } = require('playwright/lib/client/jsHandle');9const { ElementHandle } = require('playwright/lib/client/elementHandle');10const { Keyboard } = require('playwright/lib/client/keyboard');11const { Mouse } = require('playwright/lib/client/mouse');12const { TimeoutError } = require('playwright/lib/client/errors');13const { ConsoleMessage } = require('playwright/lib/client/consoleMessage');14const { Dialog } = require('playwright/lib/client/dialog');15const { Route } = require('playwright/lib/client/route');16const { Selectors } = require('playwright/lib/client/selectors');17const { Request } = require('playwright/lib/client/request');18const { Response } = require('playwright/lib/client/response');19const { Stream } = require('playwright/lib/client/stream');20const { FileChooser } = require('playwright/lib/client/fileChooser');21const { Video } = require('playwright/lib/client/video');22const { BrowserServer } = require('playwright/lib/client/browserServer');23const { BrowserType } = require('playwright/lib/client/browserType');24const { Android } = require('playwright/lib/client/android');25const { AndroidDevice } = require('playwright/lib/client/androidDevice');26const { AndroidSocket } = require('playwright/lib/client/androidSocket');27const { AndroidProcess } = require('playwright/lib/client/androidProcess');28const { ConsoleMessageChannel } = require('playwright/lib/client/consoleMessageChannel');29const { DialogChannel } = require('playwright/lib/client/dialogChannel');30const { ElementHandleChannel } = require('playwright/lib/client/elementHandleChannel');31const { FileChooserChannel } = require('playwright/lib/client/fileChooserChannel');32const { FrameChannel } = require('playwright/lib/client/frameChannel');33const { InputChannel } = require('playwright/lib/client/inputChannel');34const { JSHandleChannel } = require('playwright/lib/client/js

Full Screen

Using AI Code Generation

copy

Full Screen

1const { initMethods } = require('playwright/lib/server/frames');2const { Page } = require('playwright/lib/server/page');3const { Frame } = require('playwright/lib/server/frame');4const { FrameManager } = require('playwright/lib/server/frames');5const { BrowserContext } = require('playwright/lib/server/browserContext');6const { Browser } = require('playwright/lib/server/browser');7const { helper } = require('playwright/lib/helper');8const { BrowserType } = require('playwright/lib/server/browserType');9const { Connection } = require('playwright/lib/server/connection');10const { BrowserServer } = require('playwright/lib/server/browserServer');11const { Events } = require('playwright/lib/server/events');12const { Progress } = require('playwright/lib/server/progress');13const { BrowserContextDispatcher } = require('playwright/lib/server/browserContextDispatcher');14const { PageDispatcher } = require('playwright/lib/server/pageDispatcher');15const { FrameDispatcher } = require('playwright/lib/server/frameDispatcher');16const { JSHandleDispatcher } = require('playwright/lib/server/jsHandleDispatcher');17const { ConsoleMessageDispatcher } = require('playwright/lib/server/consoleMessageDispatcher');18const { WorkerDispatcher } = require('playwright/lib/server/workerDispatcher');19const { DownloadDispatcher } = require('playwright/lib/server/downloadDispatcher');20const { BrowserContextChannel } = require('playwright/lib/server/browserContextChannel');21const { PageChannel } = require('playwright/lib/server/pageChannel');22const { FrameChannel } = require('playwright/lib/server/frameChannel');23const { JSHandleChannel } = require('playwright/lib/server/jsHandleChannel');24const { ConsoleMessageChannel } = require('playwright/lib/server/consoleMessageChannel');25const { WorkerChannel } = require('playwright/lib/server/workerChannel');26const { DownloadChannel } = require('playwright/lib/server/downloadChannel');27const { BrowserDispatcher } = require('playwright/lib/server/browserDispatcher');28const { BrowserTypeDispatcher } = require('playwright/lib/server/browserTypeDispatcher');29const { BrowserServerDispatcher } = require('playwright/lib/server/browserServerDispatcher');30const { BrowserServerChannel } = require('playwright/lib/server/browserServerChannel');31const { BrowserTypeChannel } = require('playwright/lib/server/browserTypeChannel');32const { BrowserChannel } = require('playwright/lib/server/browserChannel');33const { BrowserContextBase } = require('

Full Screen

Using AI Code Generation

copy

Full Screen

1const { initMethods } = require("playwright/lib/server/browserType");2initMethods();3const { initMethods } = require("playwright/lib/server/browserType");4initMethods();5const { initMethods } = require("playwright/lib/server/browserType");6initMethods();7const { initMethods } = require("playwright/lib/server/browserType");8initMethods();9const { initMethods } = require("playwright/lib/server/browserType");10initMethods();11const { initMethods } = require("playwright/lib/server/browserType");12initMethods();13const { initMethods } = require("playwright/lib/server/browserType");14initMethods();15const { initMethods } = require("playwright/lib/server/browserType");16initMethods();17const { initMethods } = require("playwright/lib/server/browserType");18initMethods();19const { initMethods } = require("playwright/lib/server/browserType");20initMethods();21const { initMethods } = require("playwright/lib/server/browserType");22initMethods();23const { initMethods } = require("playwright/lib/server/browserType");24initMethods();25const { initMethods } = require("playwright/lib/server/browserType");26initMethods();27const { initMethods } = require("playwright/lib/server/browserType");

Full Screen

Using AI Code Generation

copy

Full Screen

1const { initMethods } = require('playwright/lib/client/initializer');2const playwright = require('playwright');3const { chromium } = playwright;4(async () => {5 const browser = await chromium.launch();6 const page = await browser.newPage();7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();10const { initMethods } = require('playwright/lib/client/initializer');11const playwright = require('playwright');12const { chromium } = playwright;13(async () => {14 const browser = await chromium.launch();15 const page = await browser.newPage();16 await page.screenshot({ path: 'example.png' });17 await browser.close();18 await initMethods();19})();20const { initMethods } = require('playwright/lib/client/initializer');21const playwright = require('playwright');22const { chromium } = playwright;23(async () => {24 await initMethods();25 const browser = await chromium.launch();26 const page = await browser.newPage();27 await page.screenshot({ path: 'example.png' });28 await browser.close();29})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const {initMethods} = require('playwright/lib/utils/initMethods');2const {chromium} = require('playwright-chromium');3const browser = await chromium.launch();4const page = await browser.newPage();5await initMethods(page, ['emulateMedia']);6await page.emulateMedia({media: 'screen', colorScheme: 'dark'});7await page.screenshot({path: 'google.png'});8await browser.close();9const {initMethods} = require('playwright/lib/utils/initMethods');10const {chromium} = require('playwright-chromium');11const browser = await chromium.launch();12const page = await browser.newPage();13await initMethods(page, ['emulateMedia']);14await page.emulateMedia({media: 'screen', colorScheme: 'dark'});15await page.screenshot({path: 'google.png'});16await browser.close();17const {initMethods} = require('playwright/lib/utils/initMethods');18const {chromium} = require('playwright-chromium');19const browser = await chromium.launch();20const page = await browser.newPage();21await initMethods(page, ['emulateMedia']);22await page.emulateMedia({media: 'screen', colorScheme: 'dark'});23await page.screenshot({path: 'google.png'});24await browser.close();25const {initMethods} = require('playwright/lib/utils/initMethods');26const {chromium} = require('playwright-chromium');27const browser = await chromium.launch();28const page = await browser.newPage();29await initMethods(page, ['emulateMedia']);30await page.emulateMedia({media: 'screen', colorScheme: 'dark'});31await page.screenshot({path: 'google.png'});32await browser.close();33const {initMethods} = require('playwright/lib/utils/initMethods');34const {chromium} = require('playwright-chromium');35const browser = await chromium.launch();

Full Screen

Using AI Code Generation

copy

Full Screen

1const {initMethods} = require('playwright-core/lib/server/chromium/crBrowser');2const {BrowserType} = require('playwright-core/lib/server/browserType');3const {BrowserServer} = require('playwright-core/lib/server/browserServer');4const {BrowserContext} = require('playwright-core/lib/server/browserContext');5const {Page} = require('playwright-core/lib/server/page');6const browserType = new BrowserType();7const browserServer = new BrowserServer(browserType, process.pid, {}, () => {});8const browserContext = new BrowserContext(browserType, browserServer, {}, () => {});9const page = new Page(browserContext, {}, {}, {});10const methods = initMethods(page);11console.log(methods);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { initMethods } = require('playwright/lib/server/initializer');2const { Playwright } = require('playwright/lib/server/playwright');3const { initMethods } = require('puppeteer/lib/Connection');4const { Puppeteer } = require('puppeteer/lib/Puppeteer');5const { initMethods } = require('webdriverio/build/utils');6const { RemoteWebDriver } = require('webdriverio/build/remote');7const { initMethods } = require('testcafe/lib/test-run/commands/utils');8const { TestRun } = require('testcafe/lib/test-run');9const { initMethods } = require('cypress/lib/server/commands');10const { Cypress } = require('cypress/lib/cypress');11const { initMethods } = require('selenium-webdriver/lib/webdriver');12const { WebDriver } = require('selenium-webdriver/lib/webdriver');13const { initMethods } = require('nightwatch/lib/runner/run');14const { Runner } = require('nightwatch/lib/runner');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { initMethods } = require('playwright/lib/internal/initMethods');2const { chromium } = require('playwright');3const { expect } = require('chai');4const { test } = require('@playwright/test');5test('test', async ({page}) => {6 const { initMethods } = require('playwright/lib/internal/initMethods');7 const { chromium } = require('playwright');8 const { expect } = require('chai');9 const { test } = require('@playwright/test');10 test('test', async ({page}) => {11 const { initMethods } = require('playwright/lib/internal/initMethods');12 const { chromium } = require('playwright');13 const { expect } = require('chai');14 const { test } = require('@playwright/test');15 test('test', async ({page}) => {16 const { initMethods } = require('playwright/lib/internal/initMethods');17 const { chromium } = require('playwright');18 const { expect } = require('chai');19 const { test } = require('@playwright/test');20 test('test', async ({page}) => {21 const { initMethods } = require('playwright/lib/internal/initMethods');22 const { chromium } = require('playwright');23 const { expect } = require('chai');24 const { test } = require('@playwright/test');25 test('test', async ({page}) => {26 const { initMethods } = require('playwright/lib/internal/initMethods');27 const { chromium } = require('playwright');28 const { expect } = require('chai');29 const { test } = require('@playwright/test');30 test('test', async ({page}) => {31 const { initMethods } = require('playwright/lib/internal/initMethods');32 const { chromium } = require('playwright');33 const { expect } = require('chai');34 const { test } = require('@playwright/test');35 test('test', async ({page}) => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { initMethods } from '@playwright/test/lib/runner/initMethods';2import { TestType } from '@playwright/test/lib/types';3initMethods().then(() => {4 console.log(TestType);5});6{ TestType: { Unit: 'unit', Integration: 'integration' } }

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful