How to use baseWarn method in Playwright Internal

Best JavaScript code snippet using playwright-internal

attrHandler.js

Source:attrHandler.js Github

copy

Full Screen

...48export function vForMap(ast) {49 // 强制赋予了wx:for-index 如果有iterator1则用iterator1,否则程序指定为遍历的索引50 let forRes = ` ${ATTR_MAP['v-for']}="{{${ast.for}}}" wx:for-item="${ast.alias}" wx:for-index="${ast.forKey}"`51 if (ast.iterator2 !== undefined) {52 baseWarn(`wx:for 不支持对象的索引${ast.iterator2}遍历,已被忽略`, ast.originLine)53 }54 // 添加wx:key 避免warning55 // if (ast.attrsMap[':key'] === undefined && ast.attrsMap['v-bind:key'] === undefined) {56 // forRes += ` wx:key="${ast.forKey}"`57 // }58 if(ast.key){59 let xcxKey = ast.key.replace( ast.alias + '.' ,'')60 xcxKey = xcxKey.replace(/"|'/g, "")61 forRes += ` wx:key="${xcxKey}"`62 }else if(ast.attrsMap[':wx-key'] || ast.attrsMap['v-bind:wx-key']){63 let xcxKey = ast.attrsMap[':wx-key'] || ast.attrsMap['v-bind:wx-key']64 xcxKey = xcxKey.replace( ast.alias + '.' ,'').replace(/"|'/g, "")65 forRes += ` wx:key="${xcxKey}"`66 }67 return forRes68}69function handleStyleValue(item, isDynamic = true) {70 let res = splitObj(item, isDynamic)71 // 处理css单位转化72 let styleValue = rem2rpx(px2rpx(res.value))73 // 处理css,驼峰转中划线74 let styleKey = kebabize(res.key)75 return {76 styleValue,77 styleKey78 }79}80/**81 * 检查根据','的若拆解是否有错误82 * eg: transform:'scale(1,'+slideScaleY+')'会被拆成["transform:'scale(1,'", "'+slideScaleY+')'"]导致错误83 * @param {*} arr 84 */85function checkObjSplit(arr){86 let res = []87 arr && arr.map((item)=>{88 if(item.indexOf(':') !== -1){89 res.push(item)90 }else if(item){91 res[res.length-1] = res[res.length-1] + ',' +item92 }93 })94 return res95}96function transObjStyle(str){97 let res = ''98 // todo: 改为babel分析生成ast99 str = str.replace(/\{|\}/g,'')100 let styleArr = str.split(',')101 styleArr = checkObjSplit(styleArr)102 styleArr.map((item)=>{103 if(!item){104 return 105 }106 107 let styleRes = handleStyleValue(item, true)108 let styleKey = styleRes.styleKey109 let styleValue = styleRes.styleValue110 res += `${styleKey}: {{${styleValue}}};`111 })112 return res113}114export function getObjItem(str){115 let res = ''116 let objContent = str.trim().slice(1, str.length-1)117 let keyValueArr = objContent.split(',')118 keyValueArr.forEach((item, index) => {119 let keyValue = item.split(':')120 let key = keyValue[0].trim().replace(/'|"/g,'')121 let value= keyValue[1].trim()122 if(index>0){123 res += ','124 }125 res += `${value}?'${key}': ''`126 })127 return res128}129function transObjClass(str){130 let res = '{{['131 res += getObjItem(str)132 res += ']}}'133 return res134}135function transArrClass(str){136 let res = '{{['137 let objContent = str.trim().slice(1, str.length-1)138 let keyValueArr = objContent.split(',')139 keyValueArr.forEach((item, index) => {140 if(index>0){141 res += ','142 }143 if( item.startsWith('{') && item.endsWith('}') ){144 res += getObjItem(item)145 }else{146 res += item147 }148 })149 res += ']}}'150 return res151}152/**153 * 处理v-bind:class和v-bind:style154 * v-bind:class不支持对象。简单变量/数组可以支持;但是变量如果是对象,将无法被小程序解析155 * @param {*} ast 156 * :style="{height: 7.5*(banner._img.scale) + 'rem', color: '#fff'}"157 * style="height: 2rem"158 * 159 * isRoot: true. 需要在原class和style上拼接__vx_class和__vx_style,以支持组件上传递的样式160 */161export function handleClassAndStyle(ast, isRoot) {162 let specAttrRes = ''163 let specAttrBinding = {164 class: 'classBinding'165 , style: 'styleBinding'166 }167 Object.keys(specAttrBinding).map((attr) => {168 let res = ''169 let attrBinding = specAttrBinding[attr]170 // 静态数据171 // style="width: 400px; height: 500px;"172 if (ast.attrsMap[attr]) {173 if(attr === 'class'){174 res += ` ${attr}="${ast.attrsMap[attr]}`175 }else{176 try {177 let staticStyleArr = ast.attrsMap[attr].split(';')178 staticStyleArr.map((item)=>{179 if(!item){180 return181 }182 let styleRes = handleStyleValue(item, false)183 let styleKey = styleRes.styleKey184 let styleValue = styleRes.styleValue185 if (res) {186 res += ` ${styleKey}: ${styleValue};`187 } else {188 res += ` ${attr}="${styleKey}: ${styleValue};`189 }190 })191 }catch(err){192 err && console.error(err.stack)193 }194 }195 }196 //动态数据197 if (ast[attrBinding]) {198 if (ast[attrBinding][0] === '{') {199 // v-bind:class="{ active: isActive, 'text-danger': hasError }"200 if(attr === 'class'){201 if (res) {202 res += ` ${transObjClass(ast[attrBinding])}`203 }else{204 res += ` ${attr}="${transObjClass(ast[attrBinding])}`205 }206 // baseWarn(`:${attr}="${ast[attrBinding]}"无法转化至WXML,已被忽略`, ast.originLine)207 }else{208 // :style="{height: 7.5*(banner._img.scale) + 'rem', color: '#fff'}" -> 209 // style="height: {{7.5*(banner._img.scale) + 'rpx'}}; color: '#fff';"210 try {211 if(res){212 res += ` ${transObjStyle(ast[attrBinding])}`213 }else{214 res += ` ${attr}="${transObjStyle(ast[attrBinding])}`215 }216 } catch (err) {217 baseError(`:${attr}="${ast[attrBinding]}"语法错误,=后不是合法对象`, ast.originLine)218 }219 }220 221 } else if (ast[attrBinding][0] === '[') {222 if(attr === 'class'){223 if (res) {224 res += ` ${transArrClass(ast[attrBinding])}`225 }else{226 res += ` ${attr}="${transArrClass(ast[attrBinding])}`227 }228 }else{229 try {230 let str = ast[attrBinding].slice(1, ast[attrBinding].length-1)231 if(res){232 res += ` ${transObjStyle(str)}`233 }else{234 res += ` ${attr}="${transObjStyle(str)}`235 }236 } catch (err) {237 baseError(`:${attr}="${ast[attrBinding]}"语法错误,=后不是合法对象`, ast.originLine)238 }239 }240 241 } else {242 // <div v-bind:class="variable"> (如果variable是对象、数组变量,则无法被小程序解析)243 let attrValue = ast[attrBinding].trim()244 if(attr === 'style'){245 attrValue = rem2rpx(px2rpx(ast[attrBinding].trim()))246 }247 if (res) {248 res += ` {{${attrValue}}}`249 } else {250 res += ` ${attr}="{{${attrValue}}}`251 }252 }253 }254 // 非组件且含有曝光打点255 if(attr === 'class' ){256 res = handleVlog(ast, res)257 }258 if(isRoot){259 res += res? ` {{__vx_${attr}}}`: ` ${attr}="{{__vx_${attr}}}`260 }261 res += res? '"': ''262 263 specAttrRes += res264 })265 return specAttrRes266}267/**268 * class="favor_goods_image" :class="varClass"269 * => class: "favor_goods_image " + varClass ,270 * @param {*} ast 271 * 272 * isRoot: 需要添加外部传入的class:COMPGETCLASS273 */274export function handleCompClass(ast, isRoot){275 let res = ''276 if(ast['classBinding']){277 res += `"${COMPGETCLASS}":${ast['classBinding']}`278 }279 if(ast.attrsMap['class']) {280 if(res){281 res += `+" ${ast.attrsMap['class']}"`282 }else{283 res += `"${COMPGETCLASS}":"${ast.attrsMap['class']}"`284 } 285 }286 if(isRoot){287 res += res ? ` + ${COMPGETCLASS}`: `"${COMPGETCLASS}": ${COMPGETCLASS}`288 }289 if(res){290 res +=','291 }292 return res293}294/** 295style="height:100px; width:100px" :style="variable"296=>297"style": "height:100px; width:100px;" + variable298style="height:100px; width:100px" :style="{'marginTop': '10px', 'marginBottom': bot + 'rem'}"299=>300"style": { 'height':'100px'; 'width':'100px', 'marginTop': '10rem', 'marginBottom': this.bot + 'rem' }301改成字符串拼接302"style": "height:100px; width:100px; marginTop: 10rem; marginBottom: " + this.bot + "rem"303* isRoot: 需要添加外部传入的style:COMPGETSTYLE304*/305export function handleCompStyle(ast, isRoot){306 let staticObj = {}307 let dynamicObj = {}308 let dynamicVar = null309 let res = ''310 // 静态数据311 // style="width: 400px; height: 500px;"312 if (ast.attrsMap['style']) {313 try {314 let staticStyleArr = ast.attrsMap['style'].split(';')315 staticStyleArr.map((item)=>{316 if(!item){317 return318 }319 let styleRes = handleStyleValue(item, false)320 let styleKey = styleRes.styleKey321 let styleValue = styleRes.styleValue322 staticObj[styleKey] = styleValue323 })324 }catch(err){325 err && console.error(err.stack)326 }327 }328 //动态数据329 if (ast['styleBinding']) {330 if (ast['styleBinding'][0] === '{') {331 332 // :style="{height: 7.5*(banner._img.scale) + 'rem', color: '#fff'}" -> 333 // style="height: {{7.5*(banner._img.scale) + 'rpx'}}; color: '#fff';"334 try {335 let value = ast['styleBinding']336 value = value.replace(/\{|\}/g,'')337 let styleArr = value.split(',')338 styleArr.map((item)=>{339 if(!item){340 return341 }342 let styleRes = handleStyleValue(item, true)343 let styleKey = styleRes.styleKey344 let styleValue = styleRes.styleValue345 dynamicObj[styleKey] = styleValue346 })347 } catch (err) {348 baseError(`style="${ast['styleBinding']}"语法错误,=后不是合法对象`, ast.originLine)349 }350 351 352 } else if (ast['styleBinding'][0] === '[') {353 baseWarn(`:style="${ast['styleBinding']}"无法转化至WXML,已被忽略`, ast.originLine)354 } else {355 // <div v-bind:style="variable"> (如果variable是对象、数组变量,则无法被小程序解析)356 dynamicVar = ast['styleBinding'].trim()357 }358 }359 360 // 1) static + dynamicObj; 2) static + dynamicVar 3) dynamicObj 4)dynamicVar 5)static361 if(Object.keys(staticObj).length && Object.keys(dynamicObj).length){362 if(!res){363 res += `"${COMPGETSTYLE}":`364 }365 res += '"'366 Object.keys(staticObj).map((key) => {367 res += `${key}:${staticObj[key]};`368 })369 Object.keys(dynamicObj).map((key) => {370 res += `${key}:" + ${dynamicObj[key]} + ";`371 })372 res += '"'373 374 }else if(Object.keys(staticObj).length && dynamicVar){375 if(!res){376 res += `"${COMPGETSTYLE}":`377 }378 res += '"'379 Object.keys(staticObj).map((key) => {380 res += `${key}:${staticObj[key]};`381 })382 res += `"+${dynamicVar}`383 }else if(Object.keys(dynamicObj).length){384 if(!res){385 res += `"${COMPGETSTYLE}":`386 }387 res += '"'388 Object.keys(dynamicObj).map((key) => {389 res += `${key}:" + ${dynamicObj[key]} + ";`390 })391 res += '"'392 }else if(dynamicVar){393 if(!res){394 res += `"${COMPGETSTYLE}":`395 }396 res += `${dynamicVar}`397 }else if(Object.keys(staticObj).length){398 if(!res){399 res += `"${COMPGETSTYLE}":`400 }401 res += '"'402 Object.keys(staticObj).map((key) => {403 res += `${key}:${staticObj[key]};`404 })405 res += '"'406 }407 if(isRoot){408 res += res ? ` + ${COMPGETSTYLE}`: `"${COMPGETSTYLE}": ${COMPGETSTYLE}`409 }410 if(res){411 res +=','412 }413 return res414}415/**416 * 事件处理,返回事件的key-value对417 * @param {*string} direcKey:418 * ["v-on:click.once", ":click.once", "click", ".once", index: 0, input: "v-on:click.once"]419 * ["v-on:click", ":click", "click", undefined, index: 0, input: "v-on:click"]420 * ["@click.once", "click", ".once", index: 0, input: ":@click.once"]421 * ["v-on", undefined, undefined, undefined, index: 0, input: "v-on"]422 * @param {*string} value: @click = value423 * @return {*object}424 */425function getEventKeyValue(direcKey, value, isComp, line, ast){426 let res = {}427 function checkEvent(event, handle, modifer){428 let obj = {}429 let isVXtag = VX_TAG.indexOf(ast.tag)===-1? false: true430 431 if(isComp){432 // 组件上433 // if(mapEvent){434 // // 不支持原生事件435 // baseWarn(`不支持在组件上直接绑定内置事件,${event}=${value}转化时已被忽略`, line)436 // }else{437 // 支持外部传给组件内部的事件回调函数438 obj[event] = handle439 // }440 }else{441 // 非组件元素442 let resEvent443 let VXtagEvent = COMPONENT_MAP[ast.tag] && COMPONENT_MAP[ast.tag].event && COMPONENT_MAP[ast.tag].event[event]444 // 是组件上的非标准事件。使用映射事件或原样保留445 if(isVXtag && COMPONENT_MAP[ast.tag] && !EVENT_MAP[event]){446 // 内置组件的内置事件447 resEvent = VXtagEvent || event448 }else{449 // 普通元素 || 普通事件450 let mapEvent = EVENT_MAP[event] 451 if(mapEvent){452 resEvent = 'bind' + mapEvent453 if(modifer){454 if(modifer === '.stop'){455 resEvent = 'catch' + mapEvent456 }else if(modifer.indexOf('.stop') !== -1){457 resEvent = 'catch' + mapEvent458 baseWarn(`不支持除了.stop之外的事件的modifiers`, line)459 }else{460 baseWarn(`小程序不支持事件的modifiers,${event}${modifer}已被替换为${event}`, line)461 }462 }463 }464 }465 if(resEvent){466 obj[resEvent] = handle467 }else{468 baseWarn(`小程序不支持${event}事件,转化时已被忽略`, line)469 }470 }471 return obj;472 }473 if (direcKey[2] && direcKey[2][0] !== '.') {474 res = checkEvent(direcKey[2], value, direcKey[3])475 } else if (direcKey[1] && direcKey[1][0] !== ':') {476 res = checkEvent(direcKey[1], value, direcKey[2])477 } else if (direcKey[0] === 'v-on') {478 if(value && value[0] !== '{'){479 if(isComp){480 res = `...${value}`481 }else{482 baseWarn(`${direcKey[0]}="${value}"语法错误,v-on的值只允许为对象,转化时已被忽略`, line)483 }484 }else{485 try {486 value = value.replace(/\{|\}/g,'')487 var attrsArr = value.split(',')488 attrsArr.map((item)=>{489 let itemRes = splitObj(item)490 res = Object.assign(res,checkEvent(itemRes.key, itemRes.value))491 })492 } catch (err) {493 baseError(`${direcKey[0]}="${value}"语法错误,v-on=后应该跟随对象`, line)494 }495 }496 }497 return res498 // let finalRes = {}499 // if(isComp && typeof res === 'object'){500 // // 中划线转驼峰。props内容传递给子组件js501 // for (let key in res){502 // finalRes[camelize(key)] = res[key]503 // }504 // }else{505 // finalRes = res506 // }507 508 // return finalRes509}510/**511 * 事件处理,返回处理后的字符串供template拼接512 * @param {*string} direcKey:513 * ["v-on:click.once", ":click.once", "click", ".once", index: 0, input: "v-on:click.once"]514 * ["v-on:click", ":click", "click", undefined, index: 0, input: "v-on:click"]515 * ["@click.once", "click", ".once", index: 0, input: ":@click.once"]516 * ["v-on", undefined, undefined, undefined, index: 0, input: "v-on"]517 * @param {*string} value: @click = value518 * @return {*string}519 */520export function handleEvent(event, handler, line, ast) {521 let res = ''522 let resObj = getEventKeyValue(event, handler, false, line, ast)523 resObj && Object.keys(resObj).map((key) => {524 if(key === 'bindinput'){525 res += ` ${key}="vx_inputHandle" data-input-event="${resObj[key]}" data-vx-scope="{{$scope}}" `526 }else if( (key === 'bindtap' || key === 'catchtap') && ast._vxClickNotJumpLog){527 res += ` ${key}="vx_clickLogHandle" data-click-event="${resObj[key]}"`528 }else{529 res += ` ${key}="{{$scope}}.${resObj[key]}"`530 }531 })532 return res533}534/**535 * v-bind处理,获得处理后的键值对536 * @param {*string} direcKey : ["v-bind:text-content.prop", ":text-content.prop", "text-content", ".prop", index: 0, input: "v-bind:text-content.prop"]537 * ["v-bind:src", ":src", "src", undefined, index: 0, input: "v-bind:src"]538 * [":src.prop", "src", ".prop", index: 0, input: ":src.prop"]539 * ["v-bind", undefined, undefined, undefined, index: 0, input: "v-bind"]540 * @param {*string} value: v-bind:key=value 541 * @param {*boolen}isComp542 * @return {*object} object为key-value543 */544function getVbindKeyValue(direcKey, value, isComp, line, ast){545 let res = {}546 let resName = '';547 // 过滤value的filter548 let originValue = value549 if( value && value.indexOf('|')!==-1 && value[value.indexOf('|')+1] !== '|'){ //排除`||`的语句550 // 处理filter551 value = value.split('|')[0] 552 baseWarn(`小程序不支持filter,${originValue}已被转为${value}`, line)553 }554 if (direcKey[2] && direcKey[2][0] !== '.') {555 // :key -> wx:key的处理556 resName = ATTR_MAP[direcKey[2]] || (COMPONENT_MAP[ast.tag] && COMPONENT_MAP[ast.tag].attr && COMPONENT_MAP[ast.tag].attr[direcKey[2]]) || direcKey[2]557 // :is的特殊处理558 if(resName === 'is'){559 // res = ` ${resName}="${value}"`560 !isComp && baseWarn(`不支持is方式的组件引入,转化时已被忽略`, line)561 }else if(direcKey[2]==='key'){562 // baseWarn(`不支持在组件中使用循环和key,转化时已被忽略`, line)563 }else{564 res = {565 [resName]: value566 }567 }568 if (direcKey[3]) {569 baseWarn(`小程序不支持vue对应v-bind的modifiers,${direcKey[2]}${direcKey[3]}已被替换为${direcKey[2]}`, line)570 }571 } else if (direcKey[1] && direcKey[1][0] !== ':') {572 resName = ATTR_MAP[direcKey[1]] || (COMPONENT_MAP[ast.tag] && COMPONENT_MAP[ast.tag].attr && COMPONENT_MAP[ast.tag].attr[direcKey[1]]) || direcKey[1]573 // :is的特殊处理574 if(resName === 'is'){575 // res = ` ${resName}="${value}"`576 baseWarn(`不支持is方式的组件引入,转化时已被忽略`, line)577 }else{578 res = {579 [resName]: value580 }581 }582 if (direcKey[2]) {583 baseWarn(`小程序不支持vue对应v-bind的modifiers,${direcKey[1]}${direcKey[2]}已被替换为${direcKey[1]}`, line)584 }585 } else if (direcKey[0] === 'v-bind') {586 if(value && value[0] !== '{'){587 if(isComp){588 // 值为对象的变量589 res = `...${value}`590 }else{591 baseWarn(`${direcKey[0]}="${value}"语法错误,v-bind的值只允许为对象,转化时已被忽略`, line)592 } 593 }else{594 try {595 value = value.replace(/\{|\}/g,'')596 var attrsArr = value.split(',')597 attrsArr.map((item)=>{598 let itemRes = splitObj(item)599 let bindValue = itemRes.value600 res[itemRes.key] = ATTR_MAP[bindValue] || (COMPONENT_MAP[ast.tag] && COMPONENT_MAP[ast.tag].attr && COMPONENT_MAP[ast.tag].attr[bindValue]) || bindValue601 })602 } catch (err) {603 baseError(`${direcKey[0]}="${value}"语法错误,v-bind=后应该跟随对象`, line)604 }605 }606 }607 // return res608 let finalRes = {}609 if(isComp && typeof res === 'object'){610 // 中划线转驼峰。props内容传递给子组件js611 for (let key in res){612 finalRes[camelize(key)] = res[key]613 }614 }else{615 finalRes = res616 }617 return finalRes618}619/**620 * v-bind处理,获得处理后的字符串,以追加在模板上621 * @param {*string} bindKey : ["v-bind:text-content.prop", ":text-content.prop", "text-content", ".prop", index: 0, input: "v-bind:text-content.prop"]622 * ["v-bind:src", ":src", "src", undefined, index: 0, input: "v-bind:src"]623 * [":src.prop", "src", ".prop", index: 0, input: ":src.prop"]624 * ["v-bind", undefined, undefined, undefined, index: 0, input: "v-bind"]625 * @param {*string} value: v-bind:key=value 626 * @return {*string} 追加到template的字符串627 */628export function handleVbind(bindKey, value, line, ast) {629 let res = ''630 let resObj = getVbindKeyValue(bindKey, value, false, line, ast)631 resObj && Object.keys(resObj).map((key) => {632 if(!isNoUseAtrr(key, ast.tag)){633 res += ` ${key}="{{${resObj[key]}}}"`634 }635 })636 return res637}638// function handleFilter(value, line){639// let originValue = value640// let filterReg = /.*?[^|](|.*?}})/g //不对641// if( value && value.indexOf('|')!==-1 && value[value.indexOf('|')+1] !== '|'){ //排除`||`的语句642// // 处理filter643// value = value.split('|')[0] 644// baseWarn(`小程序不支持filter,${originValue}已被转为${value}`, line)645// }646// return value647// }648export function recordForKey(forKeyArr, key){649 forKeyArr.push(key)650 return forKeyArr651}652function transquota(ast){653 if(ast.classBinding){654 ast.classBinding = ast.classBinding.replace(/"/g, "'")655 }656 if(ast.styleBinding){657 ast.styleBinding = ast.styleBinding.replace(/"/g, "'")658 }659 return ast660}661/**662 * 663 * @param {*} target 664 * @param {*} template 665 * @param {*} isRoot 666 * @param {*} specInfo 特殊节点需要的信息,譬如MIX_LOG_FLAG会带有mixLogIdx,667 * { mixLogIdx: "'1'_key1_key2", mixLogIdxStatic: false}668 */669export function generateAstAttr(target, template, isRoot, specInfo){670 // 处理attr671 let insertMap = {672 attr: null673 , value: null674 , type: 'text'675 }; //处理v-text和v-html676 let hasEventKey = false677 target = transquota(target)678 let attrs = target.attrsMap;679 attrs && Object.keys(attrs).map((key) => {680 // a的target不支持681 if(target.tag === 'a' && key === 'target'){682 return683 }684 if (WARN_MSG[key]) {685 baseWarn(WARN_MSG[key], target.originLine)686 }687 let value = attrs[key]688 if(typeof value === 'string'){689 value = value.trim()690 value = value.replace(/"/g, "'")691 attrs[key] = value692 }693 checkConfigUse(value, target.originLine)694 let eventKey = key.match(EVENT_REG.ON) || key.match(EVENT_REG.SHORT)695 let vbindKey = key.match(VBIND_REG.BIND) || key.match(VBIND_REG.SHORT)696 let mapKey = ATTR_MAP[key] || (COMPONENT_MAP[target.tag] && COMPONENT_MAP[target.tag].attr && COMPONENT_MAP[target.tag].attr[key])697 let resKey = mapKey !== undefined ? mapKey : key698 if (resKey === REPLACECONTENT) {699 // v-text和v-html处理700 insertMap.attr = key701 insertMap.value = value702 if(key === 'v-html'){703 insertMap.type = 'html'704 }705 } else if(resKey === DEPRECATED){706 // 不支持的标签不做处理707 } else if (key === 'v-for') {708 template += vForMap(target)709 } else if(target.for && (key === 'key'|| key === ":key" || key === "v-bind:key" || key ===':wx-key' || key === 'v-bind:wx-key')){710 // key在vForMap里有单独的处理711 } else if (SPEC_ATTR.indexOf(key) !== -1) {712 // class 和 style的特殊处理713 } else if (vbindKey) {714 template += handleVbind(vbindKey, value, target.originLine, target)715 } else if (eventKey) {716 // 事件的处理717 template += handleEvent(eventKey, value, target.originLine, target)718 hasEventKey = true719 } else if (DIRECTIVES.indexOf(key) !== -1) {720 if(resKey === 'wx:else'){721 template += ` ${resKey}`722 }else{723 template += ` ${resKey}="{{${value}}}"` 724 }725 } else {726 if(value === ""){727 template += ` ${resKey}`728 }else{729 if(!isNoUseAtrr(resKey, target.tag)){730 // 是否是打点标志,打点的属性需要平铺731 if(key === LOG_FLAG){732 template += handleLog(value, specInfo.mixLogIdx, specInfo.mixLogIdxStatic)733 }else if(key === MIX_LOG_FLAG){734 template += handleMixLog(target, specInfo.mixLogIdx, specInfo.mixLogIdxStatic)735 }else{736 template += ` ${resKey}="${value}"`737 }738 }739 }740 }741 })742 if(target._vxClickNotJumpLog && !hasEventKey){743 template += ` capture-bind:tap="vx_clickLogHandle"`744 }745 // handle class and style746 template += handleClassAndStyle(target, isRoot)747 return {748 template,749 insertMap750 }751}752export function generateCompAstAttr(ast, template, isRoot, props, event ){753 // 处理attr754 ast = transquota(ast)755 let attrs = ast.attrsMap;756 attrs && Object.keys(attrs).map((key) => {757 if (WARN_MSG[key]) {758 baseWarn(WARN_MSG[key], ast.originLine)759 }760 let value = attrs[key]761 if(typeof value === 'string'){762 value = value.trim()763 value = value.replace(/"/g, "'")764 attrs[key] = value765 }766 let eventKey = key.match(EVENT_REG.ON) || key.match(EVENT_REG.SHORT)767 let vbindKey = key.match(VBIND_REG.BIND) || key.match(VBIND_REG.SHORT)768 let mapKey = ATTR_MAP[key] || (COMPONENT_MAP[ast.tag] && COMPONENT_MAP[ast.tag].attr && COMPONENT_MAP[ast.tag].attr[key])769 let resKey = mapKey !== undefined ? mapKey : key770 if (resKey === REPLACECONTENT) {771 // v-text和v-html处理772 baseWarn(`组件${ast.tag}不支持使用${key}`, ast.originLine)773 } else if(resKey === DEPRECATED){774 // 不支持的标签不做处理, baseWarn(WARN_MSG[key])已抛出775 } else if (SPEC_ATTR.indexOf(key) !== -1) {776 // style的特殊处理777 } else if (key === 'v-for') {778 // template += vForMap(ast)779 } else if(ast.for && (key === 'key'|| key === ":key" || key === "v-bind:key")){780 // key在vForMap里有单独的处理781 } else if (vbindKey) {782 let propsRes = getVbindKeyValue(vbindKey, value, true, ast.originLine, ast)783 if(typeof propsRes === 'string'){784 // ...value的处理785 props += `${propsRes},`786 }else{787 for (let key in propsRes){788 props += `"${key}": ${propsRes[key]},`789 }790 }791 792 } else if (eventKey) {793 // 事件的处理794 let eventRes = getEventKeyValue(eventKey, value, true, ast.originLine, ast)795 if(typeof eventRes === 'string'){796 // ...value的处理797 event += `${eventRes},`798 }else{799 for (let eventKey in eventRes){800 event += `"${eventKey}": ${eventRes[eventKey]},`801 }802 }803 } else if (DIRECTIVES.indexOf(key) !== -1) {804 // 'v-if', 'v-else', 'v-else-if', 'v-show'805 if(SURPORT_COMPONENT_DIRECTIVES){806 if(resKey === 'wx:else'){807 template += ` ${resKey}`808 }else{809 template += ` ${resKey}="{{${value}}}"` 810 }811 }else{812 baseWarn(`不支持在组件${ast.tag}上使用${key},转化时已被忽略`, ast.originLine)813 }814 } else {815 if(VX_DIRECTIVE.indexOf(resKey) !== -1){816 props += `"${resKey}": ${value},`817 }else{818 if(key === LOG_FLAG || key === MIX_LOG_FLAG){819 baseError(`不支持在组件${ast.tag}上使用${key},转化时已被忽略,请在组件外或者内部包裹一层元素打点`, ast.originLine)820 }else{821 resKey = camelize(resKey)822 props += `"${resKey}": "${value}",`823 }824 }825 }826 })...

Full Screen

Full Screen

observerPatch.spec.jsx

Source:observerPatch.spec.jsx Github

copy

Full Screen

1import { Component, render } from 'inferno';2import * as mobx from 'mobx';3import { inject, observer, observerPatch } from 'inferno-mobx';4import { createClass } from 'inferno-create-class';5import { warning } from 'inferno-shared';6const getDNode = (obj, prop) => obj.$mobx.values[prop];7describe('Mobx Observer Patch', () => {8 let container;9 beforeEach(function () {10 container = document.createElement('div');11 document.body.appendChild(container);12 });13 afterEach(function () {14 render(null, container);15 container.innerHTML = '';16 document.body.removeChild(container);17 });18 it('nestedRendering', () => {19 const store = mobx.observable({20 todos: [21 {22 title: 'a',23 completed: false24 }25 ]26 });27 let todoItemRenderings = 0;28 class TodoItem extends Component {29 render({ todo }) {30 todoItemRenderings++;31 return <li>|{todo.title}</li>;32 }33 shouldComponentUpdate({ todo: { title } }) {34 return title !== this.props.todo.title;35 }36 }37 observerPatch(TodoItem);38 let todoListRenderings = 0;39 let todoListWillReactCount = 0;40 const TodoList = createClass({41 componentWillReact() {42 todoListWillReactCount++;43 },44 render() {45 todoListRenderings++;46 const todos = store.todos;47 return (48 <div>49 <hi>{todos.length}</hi>50 {todos.map((todo, idx) => (51 <TodoItem key={idx} todo={todo} />52 ))}53 </div>54 );55 }56 });57 observerPatch(TodoList);58 render(<TodoList />, container);59 expect(todoListRenderings).toEqual(1); //, 'should have rendered list once');60 expect(todoListWillReactCount).toEqual(0); //, 'should never call componentWillReact')61 expect(container.querySelectorAll('li').length).toEqual(1);62 expect(container.querySelector('li').textContent).toEqual('|a');63 expect(todoItemRenderings).toEqual(1); // 'item1 should render once'64 expect(getDNode(store, 'todos').observers.length).toBe(1);65 expect(getDNode(store.todos[0], 'title').observers.length).toBe(1);66 store.todos[0].title += 'a';67 expect(todoListRenderings).toEqual(1); //, 'should have rendered list once');68 expect(todoListWillReactCount).toEqual(0); //, 'should never call componentWillReact')69 expect(todoItemRenderings).toEqual(2); //, 'item1 should have rendered twice');70 expect(getDNode(store, 'todos').observers.length).toBe(1); //, 'observers count shouldn\'t change');71 expect(getDNode(store.todos[0], 'title').observers.length).toBe(1); //, 'title observers should not have increased');72 store.todos.push({73 title: 'b',74 completed: true75 });76 expect(container.querySelectorAll('li').length).toBe(2); //, 'list should two items in in the list');77 const expectedOutput = [];78 const nodes = container.querySelectorAll('li');79 for (let i = 0; i < nodes.length; i++) {80 expectedOutput.push(nodes[i].textContent);81 }82 expect(expectedOutput).toEqual(['|aa', '|b']);83 expect(todoListRenderings).toBe(2); //'should have rendered list twice');84 expect(todoListWillReactCount).toBe(0); //, 'should never call componentWillReact')85 expect(todoItemRenderings).toBe(3); //, 'item2 should have rendered as well');86 expect(getDNode(store.todos[1], 'title').observers.length).toBe(1); //, 'title observers should have increased');87 expect(getDNode(store.todos[1], 'completed').observers.length).toBe(0); //, 'completed observers should not have increased');88 const oldTodo = store.todos.pop();89 expect(todoListRenderings).toBe(3); //, 'should have rendered list another time');90 expect(todoListWillReactCount).toBe(0); //, 'should never call componentWillReact')91 expect(todoItemRenderings).toBe(3); //, 'item1 should not have rerendered');92 expect(container.querySelectorAll('li').length).toBe(1); //, 'list should have only on item in list now');93 expect(getDNode(oldTodo, 'title').observers.length).toBe(0); //, 'title observers should have decreased');94 expect(getDNode(oldTodo, 'completed').observers.length).toBe(0); //, 'completed observers should not have decreased');95 });96 it('keep views alive', () => {97 let yCalcCount = 0;98 const data = mobx.observable({99 x: 3,100 get y() {101 yCalcCount++;102 return this.x * 2;103 },104 z: 'hi'105 });106 class TestComponent extends Component {107 render() {108 return (109 <div>110 {data.z}111 {data.y}112 </div>113 );114 }115 }116 observerPatch(TestComponent);117 render(<TestComponent />, container);118 expect(yCalcCount).toBe(1);119 expect(container.textContent).toBe('hi6');120 data.z = 'hello';121 // test: rerender should not need a recomputation of data.y because the subscription is kept alive122 expect(yCalcCount).toBe(1);123 expect(container.textContent).toBe('hello6');124 expect(yCalcCount).toBe(1);125 expect(getDNode(data, 'y').observers.length).toBe(1);126 render(<div />, container);127 expect(getDNode(data, 'y').observers.length).toBe(0);128 });129 it('patched render is run first', (done) => {130 let origRenderMethod;131 const Comp = createClass({132 render() {133 // ugly check, but proofs that observer.willmount has run134 // We cannot use function.prototype.name here like in react-redux tests because it is not supported in Edge/IE135 expect(this.render).not.toBe(origRenderMethod);136 return null;137 }138 });139 origRenderMethod = Comp.prototype.render;140 observerPatch(Comp);141 render(<Comp />, container);142 done();143 });144 it('issue 12', function () {145 const data = mobx.observable({146 selected: 'coffee',147 items: [148 {149 name: 'coffee'150 },151 {152 name: 'tea'153 }154 ]155 });156 /** Row Class */157 class Row extends Component {158 constructor(props) {159 super(props);160 }161 render() {162 return (163 <span>164 {this.props.item.name}165 {data.selected === this.props.item.name ? '!' : ''}166 </span>167 );168 }169 }170 /** table stateles component */171 class Table extends Component {172 render() {173 return (174 <div>175 {data.items.map((item) => (176 <Row key={item.name} item={item} />177 ))}178 </div>179 );180 }181 }182 observerPatch(Table);183 render(<Table />, container);184 expect(container.querySelector('div').textContent).toBe('coffee!tea');185 mobx.runInAction(() => {186 data.items[1].name = 'boe';187 data.items.splice(0, 2, { name: 'soup' });188 data.selected = 'tea';189 });190 expect(container.querySelector('div').textContent).toBe('soup');191 });192 it('component should not be inject', function (done) {193 const msg = [];194 const baseWarn = console.error;195 console.error = (m) => msg.push(m);196 const Foo = inject('foo')(197 createClass({198 render() {199 return (200 <div>201 context:202 {this.props.foo}203 </div>204 );205 }206 })207 );208 observerPatch(Foo);209 expect(msg.length).toBe(1);210 console.error = baseWarn;211 done();212 });213 it('component should not be observer', function (done) {214 const msg = [];215 const baseWarn = console.error;216 console.error = (m) => msg.push(m);217 const Foo = observer(218 createClass({219 render() {220 return (221 <div>222 context:223 {this.props.foo}224 </div>225 );226 }227 })228 );229 observerPatch(Foo);230 expect(msg.length).toBe(1);231 console.error = baseWarn;232 done();233 });234 it('component should not be already be patched', function (done) {235 const msg = [];236 const baseWarn = console.error;237 console.error = (m) => msg.push(m);238 const Foo = createClass({239 render() {240 return (241 <div>242 context:243 {this.props.foo}244 </div>245 );246 }247 });248 observerPatch(Foo);249 observerPatch(Foo);250 expect(msg.length).toBe(1);251 console.error = baseWarn;252 done();253 });254 it('observer component can be injected', (done) => {255 const msg = [];256 const baseWarn = console.error;257 console.error = (m) => msg.push(m);258 const fooA = createClass({259 render: () => null260 });261 observerPatch(fooA);262 inject('foo')(fooA);263 // N.B, the injected component will be observer since mobx-react 4.0!264 const fooB = createClass({265 render: () => null266 });267 observerPatch(fooB);268 inject(() => {})(fooB);269 expect(msg.length).toBe(0);270 console.error = baseWarn;271 done();272 });273 it('should do warn when a patching a class extended from a patched class', (done) => {274 const msg = [];275 const baseWarn = console.error;276 console.error = (m) => msg.push(m);277 class fooA extends Component {278 render() {279 return <p>Foo A</p>;280 }281 }282 observerPatch(fooA);283 class fooB extends fooA {284 render() {285 return <p>Foo B</p>;286 }287 }288 observerPatch(fooB);289 expect(msg.length).toBe(1);290 console.error = baseWarn;291 done();292 });293 it('should render component even if setState called with exactly the same props', function (done) {294 let renderCount = 0;295 const Component = createClass({296 onClick() {297 this.setState({});298 },299 render() {300 renderCount++;301 return <div onClick={this.onClick} id="clickableDiv" />;302 }303 });304 observerPatch(Component);305 render(<Component />, container);306 expect(renderCount).toBe(1); //'renderCount === 1');307 container.querySelector('#clickableDiv').click();308 expect(renderCount).toBe(2); // 'renderCount === 2');309 container.querySelector('#clickableDiv').click();310 expect(renderCount).toBe(3); //'renderCount === 3');311 done();312 });313 it('observerPatch should keep MobX from eating exceptions', () => {314 const exception = new Error('dummy error');315 class Faulty extends Component {316 render() {317 throw exception;318 }319 }320 observerPatch(Faulty);321 expect(() => {322 render(<Faulty />, container);323 }).toThrow(exception);324 });325 // it('it rerenders correctly if some props are non-observables - 1', done => {326 // let renderCount = 0;327 // let odata = observable({ x: 1 })328 // let data = { y : 1 }329 //330 // @observer class Com extends Component {331 // @computed get computed () {332 // // n.b: data.y would not rerender! shallowly new equal props are not stored333 // return this.props.odata.x;334 // }335 // render() {336 // renderCount++;337 // return <span onClick={stuff} >{this.props.odata.x}-{this.props.data.y}-{this.computed}</span>338 // }339 // }340 //341 // const Parent = observer(createClass({342 // render() {343 // // this.props.odata.x;344 // return <Com data={this.props.data} odata={this.props.odata} />345 // }346 // }))347 //348 // function stuff() {349 // data.y++;350 // odata.x++;351 // }352 //353 // render(<Parent odata={odata} data={data} />, container);354 //355 // expect(renderCount).toBe(1) // 'renderCount === 1');356 // expect(container.querySelector("span").textContent).toBe("1-1-1");357 //358 // container.querySelector("span").click();359 // setTimeout(() => {360 // expect(renderCount).toBe(2) // 'renderCount === 2');361 // expect(container.querySelector("span").textContent).toBe("2-2-2");362 //363 // container.querySelector("span").click();364 // setTimeout(() => {365 // expect(renderCount).toBe(3) // 'renderCount === 3');366 // expect(container.querySelector("span").textContent).toBe("3-3-3");367 //368 // done();369 // }, 10);370 // }, 20);371 // });372 // it('it rerenders correctly if some props are non-observables - 2', done => {373 // let renderCount = 0;374 // let odata = observable({ x: 1 })375 //376 // @observer class Com extends Component {377 // @computed get computed () {378 // return this.props.data.y; // should recompute, since props.data is changed379 // }380 //381 // render() {382 // renderCount++;383 // return <span onClick={stuff}>{this.props.data.y}-{this.computed}</span>384 // }385 // }386 //387 // const Parent = observer(createClass({388 // render() {389 // let data = { y : this.props.odata.x }390 // return <Com data={data} odata={this.props.odata} />391 // }392 // }))393 //394 // function stuff() {395 // odata.x++;396 // }397 //398 // render(<Parent odata={odata} />, container);399 // expect(renderCount).toBe(1) // 'renderCount === 1');400 // expect(container.querySelector("span").textContent).toBe("1-1");401 //402 // container.querySelector("span").click();403 // setTimeout(() => {404 // expect(renderCount).toBe(2) // 'renderCount === 2');405 // expect(container.querySelector("span").textContent).toBe("2-2");406 //407 // container.querySelector("span").click();408 // setTimeout(() => {409 // expect(renderCount).toBe(3) // 'renderCount === 3');410 // expect(container.querySelector("span").textContent).toBe("3-3");411 //412 // done();413 // }, 10);414 // }, 20);415 // })...

Full Screen

Full Screen

theme.js

Source:theme.js Github

copy

Full Screen

1import Color from 'color';2/* eslint-disable max-len */3/* eslint-disable prettier/prettier */4// Base colors5const basePrimary = 'rgb(157, 32, 82)';6const baseSecondary = '#C23B47';7const baseSuccess = '#5bde4e';8const baseWarn = '#ffb741';9const baseError = '#ea4444';10// Greyscale11export const white = '#fff';12export const black = '#222';13export const greyLightest = '#f9f7f8';14export const greyLighter = '#f2f2f2';15export const greyLight = '#eee';16export const grey = '#ddd';17export const greyDark = '#ccc';18export const greyDarker = '#888';19export const greyDarkest = '#444';20// Main variations21export const primary = Color(basePrimary).hsl().string();22export const primaryLight = Color(basePrimary).lighten(0.1).hsl().string();23export const primaryLighter = Color(basePrimary).lighten(0.2).hsl().string();24export const primaryLightest = Color(basePrimary).lighten(0.3).hsl().string();25export const primaryDark = Color(basePrimary).darken(0.2).hsl().string();26export const primaryDarker = Color(basePrimary).darken(0.4).hsl().string();27export const primaryDarkest = Color(basePrimary).darken(0.6).hsl().string();28export const secondary = Color(baseSecondary).hsl().string();29export const secondaryLight = Color(baseSecondary).lighten(0.1).hsl().string();30export const secondaryLighter = Color(baseSecondary)31 .lighten(0.2)32 .hsl()33 .string();34export const secondaryLightest = Color(baseSecondary)35 .lighten(0.3)36 .hsl()37 .string();38export const secondaryDark = Color(baseSecondary).darken(0.2).hsl().string();39export const secondaryDarker = Color(baseSecondary).darken(0.4).hsl().string();40export const secondaryDarkest = Color(baseSecondary).darken(0.6).hsl().string();41export const error = Color(baseError).hsl().string();42export const errorLight = Color(baseError).lighten(0.2).hsl().string();43export const errorLighter = Color(baseError).lighten(0.4).hsl().string();44export const errorLightest = Color(baseError).lighten(0.6).hsl().string();45export const errorDark = Color(baseError).darken(0.2).hsl().string();46export const errorDarker = Color(baseError).darken(0.4).hsl().string();47export const errorDarkest = Color(baseError).darken(0.6).hsl().string();48export const success = Color(baseSuccess).hsl().string();49export const successLight = Color(baseSuccess).lighten(0.2).hsl().string();50export const successLighter = Color(baseSuccess).lighten(0.4).hsl().string();51export const successLightest = Color(baseSuccess).lighten(0.6).hsl().string();52export const successDark = Color(baseSuccess).darken(0.2).hsl().string();53export const successDarker = Color(baseSuccess).darken(0.4).hsl().string();54export const successDarkest = Color(baseSuccess).darken(0.6).hsl().string();55export const warn = Color(baseWarn).hsl().string();56export const warnLight = Color(baseWarn).lighten(0.2).hsl().string();57export const warnLighter = Color(baseWarn).lighten(0.4).hsl().string();58export const warnLightest = Color(baseWarn).lighten(0.6).hsl().string();59export const warnDark = Color(baseWarn).darken(0.2).hsl().string();60export const warnDarker = Color(baseWarn).darken(0.4).hsl().string();61export const warnDarkest = Color(baseWarn).darken(0.6).hsl().string();62// Backgrounds63export const background = '#222223';64export const backgroundSeparator = '#404144';65export const backgroundGradientFrom = primary;66export const backgroundGradientTo = secondary;67export const backgroundGradientSeparator = '#D5395E';68// AttendeeAvatars69export const circlePrimaryBg = primary;70export const circleSecondaryBg = white;71export const textPrimary = white;72export const textSecondary = primary;73// LoadingBalls74export const ballPrimary = primary;75export const ballSecondary = white;76// ToggleButton77export const primaryBgOff = greyDark;78export const primaryBallOff = white;79export const primaryBallOn = white;80export const primaryBorder = white;81export const primaryBgOn = primary;82export const secondaryBgOff = white;83export const secondaryBallOff = greyDark;84export const secondaryBallOn = primary;85export const secondaryBorder = primary;86export const secondaryBgOn = white;87// Buttons88export const btnPrimary = '#D5395E';89export const btnPrimaryGradient = secondary;90export const btnPrimaryText = white;91export const btnSecondary = 'transparent';92export const btnSecondaryGradient = greyLightest;93export const btnSecondaryText = white;94// Inputs95export const inputBorder = primary;96// Text97export const text = white;98export const textShadow = greyDarkest;99export const textInverse = black;100export const textTitle = greyLightest;101export const textTitleShadow = greyDarkest;102export const textTitleInverse = greyDarkest;103export const textTitleInverseShadow = greyLightest;104// Header105export const headerText = white;106export const headerBackground = '#1C1C1F';107export const headerBottomLine = '#464646';108// Logo109export const logoPrimaryText = 'white';110export const logoSecondaryText = 'black';111export const logoPrimarySmallText = 'indianred';112export const logoSecondarySmallText = 'indianred';113// Export theme object also for easier consumation for eg. ThemeProvider114export const theme = {115 /* eslint-disable */116 fontImportUrl:117 typeof fontImportUrl !== 'undefined' && fontImportUrl118 ? fontImportUrl119 : false,120 /* eslint-enable */121 primaryBgOff,122 primaryBallOff,123 primaryBallOn,124 primaryBorder,125 primaryBgOn,126 secondaryBgOff,127 secondaryBallOff,128 secondaryBallOn,129 secondaryBorder,130 secondaryBgOn,131 ballPrimary,132 ballSecondary,133 circlePrimaryBg,134 circleSecondaryBg,135 textPrimary,136 textSecondary,137 primary,138 primaryLight,139 primaryLighter,140 primaryLightest,141 primaryDark,142 primaryDarker,143 primaryDarkest,144 secondary,145 secondaryLight,146 secondaryLighter,147 secondaryLightest,148 secondaryDark,149 secondaryDarker,150 secondaryDarkest,151 error,152 errorLight,153 errorLighter,154 errorLightest,155 errorDark,156 errorDarker,157 errorDarkest,158 success,159 successLight,160 successLighter,161 successLightest,162 successDark,163 successDarker,164 successDarkest,165 warn,166 warnLight,167 warnLighter,168 warnLightest,169 warnDark,170 warnDarker,171 warnDarkest,172 grey,173 greyLightest,174 greyLighter,175 greyLight,176 greyDark,177 greyDarker,178 greyDarkest,179 white,180 black,181 background,182 backgroundSeparator,183 btnPrimary,184 btnPrimaryGradient,185 btnPrimaryText,186 btnSecondary,187 btnSecondaryGradient,188 btnSecondaryText,189 inputBorder,190 text,191 textShadow,192 textInverse,193 textTitle,194 textTitleShadow,195 textTitleInverse,196 textTitleInverseShadow,197 headerText,198 headerBackground,199 headerBottomLine,200 logoPrimaryText,201 logoSecondaryText,202 logoPrimarySmallText,203 logoSecondarySmallText,204};...

Full Screen

Full Screen

context.test.js

Source:context.test.js Github

copy

Full Screen

1/* eslint no-console: 0 */2import { h, render} from 'preact';3import { createClass } from 'preact-compat';4import { observable} from 'mobx';5import { observer, inject, Provider } from '../';6import { createTestRoot } from './test-util';7let testRoot;8beforeEach(() => {9 testRoot = createTestRoot();10});11describe('observer based context', () => {12 test('basic context', () => {13 const C = inject('foo')(observer(14 createClass({15 render() {16 return <div>context:{this.props.foo}</div>;17 },18 })19 ));20 const B = () => <C />;21 const A = () => (22 <Provider foo="bar">23 <B />24 </Provider>25 );26 render(<A />, testRoot);27 expect(testRoot.querySelector('div').textContent).toBe('context:bar');28 });29 test('props override context', () => {30 const C = inject('foo')(observer(31 createClass({32 render() {33 return <div>context:{this.props.foo}</div>;34 },35 })36 ));37 const B = () => <C foo={42} />;38 const A = () => (39 <Provider foo="bar">40 <B />41 </Provider>42 );43 render(<A />, testRoot);44 expect(testRoot.querySelector('div').textContent).toBe('context:42');45 });46 test('overriding stores is supported', () => {47 const C = observer(48 inject('foo','bar')(49 createClass({50 render() {51 return (52 <div>53 context:{this.props.foo}54 {this.props.bar}55 </div>56 );57 },58 }))59 );60 const B = () => <C />;61 const A = () => (62 <Provider foo="bar" bar={1337}>63 <div>64 <span>65 <B />66 </span>67 <section>68 <Provider foo={42}>69 <B />70 </Provider>71 </section>72 </div>73 </Provider>74 );75 render(<A />, testRoot);76 expect(testRoot.querySelector('span').textContent).toBe('context:bar1337');77 expect(testRoot.querySelector('section').textContent).toBe('context:421337');78 });79 test('store is not required if prop is available', () => {80 const C = inject('foo')(observer(81 createClass({82 render() {83 return <div>context:{this.props.foo}</div>;84 },85 })86 ));87 const B = () => <C foo="bar" />;88 render(<B />, testRoot);89 expect(testRoot.querySelector('div').textContent).toBe('context:bar');90 });91 test('warning is printed when changing stores', () => {92 let msg = null;93 const baseWarn = console.warn;94 console.warn = m => (msg = m);95 const a = observable(3);96 const C = inject('foo')(observer(97 createClass({98 render() {99 return <div>context:{this.props.foo}</div>;100 },101 })102 ));103 const B = observer(104 createClass({105 render: () => <C />,106 })107 );108 const A = observer(109 createClass({110 render: () => (111 <section>112 <span>{a.get()}</span>,113 <Provider foo={a.get()}>114 <B />115 </Provider>116 </section>117 ),118 })119 );120 render(<A />, testRoot);121 expect(testRoot.querySelector('span').textContent).toBe('3');122 expect(testRoot.querySelector('div').textContent).toBe('context:3');123 a.set(42);124 expect(testRoot.querySelector('span').textContent).toBe('42');125 expect(testRoot.querySelector('div').textContent).toBe('context:3');126 expect(msg).toBe(127 'MobX Provider: Provided store \'foo\' has changed. Please avoid replacing stores as the change might not propagate to all children'128 );129 console.warn = baseWarn;130 });131 test('warning is not printed when changing stores, but suppressed explicitly', () => {132 let msg = null;133 const baseWarn = console.warn;134 console.warn = m => (msg = m);135 const a = observable(3);136 const C = inject('foo')(observer(137 createClass({138 render() {139 return <div>context:{this.props.foo}</div>;140 },141 })142 ));143 const B = observer(144 createClass({145 render: () => <C />,146 })147 );148 const A = observer(149 createClass({150 render: () => (151 <section>152 <span>{a.get()}</span>,153 <Provider foo={a.get()} suppressChangedStoreWarning>154 <B />155 </Provider>156 </section>157 ),158 })159 );160 render(<A />, testRoot);161 expect(testRoot.querySelector('span').textContent).toBe('3');162 expect(testRoot.querySelector('div').textContent).toBe('context:3');163 a.set(42);164 expect(testRoot.querySelector('span').textContent).toBe('42');165 expect(testRoot.querySelector('div').textContent).toBe('context:3');166 expect(msg).toBe(null);167 console.warn = baseWarn;168 });...

Full Screen

Full Screen

edit_folder.js

Source:edit_folder.js Github

copy

Full Screen

1function tagSplit(str) {2 var delim = RegExp.escape(mt.screen.tag_delim);3 var delim_scan = new RegExp('^((([\'"])(.*?)\\3[^' + delim + ']*?|.*?)(' + delim + '\\s*|$))', '');4 str = str.replace(/(^\s+|\s+$)/g, '');5 var tags = [];6 while (str.length && str.match(delim_scan)) {7 str = str.substr(RegExp.$1.length);8 var tag = RegExp.$4 ? RegExp.$4 : RegExp.$2;9 tag = tag.replace(/(^\s+|\s+$)/g, '');10 tag = tag.replace(/\s+/g, ' ');11 if (tag != '') tags.push(tag);12 }13 return tags;14}15var autoTag;16var tagPos = 0;17function initTags() {18 /* browsers don't want to cache the tags field, so we use a hidden input field to cache them */19 var t = getByID('tags-cache');20 if ( t ) {21 log('tag cache:'+t.value);22 var v = getByID('tags');23 if ( t.value )24 v.value = t.value;25 DOM.addEventListener( v, "change", function() { log('caching tags'); t.value = v.value; } );26 }27 if (!mt.screen.tag_list || mt.screen.tag_list.length == 0) return;28 autoTag = new TC.TagComplete("tags", mt.screen.tag_list);29 autoTag.delimiter = mt.screen.tag_delim;30}31function validate(form) { 32 if (form.label.value.match(/\S/,''))33 return true;34 alert(mt.screen.trans.ENTER_FOLDER_LABEL);35 form.label.focus();36 return false;37}38 39function toggleFile() {40 var fld = getByID("basename");41 if (fld) {42 fld.disabled = false;43 fld.focus();44 var baseman = getByID("basename_manual");45 if (baseman) baseman.value = "1";46 var basewarn = getByID("basename-warning");47 if (basewarn) basewarn.style.display = "block";48 }49 var img = getByID("basename-lock");50 if (img)51 img.style.display = 'none';52 return false;53}54var tableSelect;55jQuery(document).ready( function($) {56 // setup57 tableSelect = new TC.TableSelect( "selector" );58 tableSelect.rowSelect = true;59 initTags();...

Full Screen

Full Screen

edit_category.js

Source:edit_category.js Github

copy

Full Screen

1function tagSplit(str) {2 var delim = RegExp.escape(mt.screen.tag_delim);3 var delim_scan = new RegExp('^((([\'"])(.*?)\\3[^' + delim + ']*?|.*?)(' + delim + '\\s*|$))', '');4 str = str.replace(/(^\s+|\s+$)/g, '');5 var tags = [];6 while (str.length && str.match(delim_scan)) {7 str = str.substr(RegExp.$1.length);8 var tag = RegExp.$4 ? RegExp.$4 : RegExp.$2;9 tag = tag.replace(/(^\s+|\s+$)/g, '');10 tag = tag.replace(/\s+/g, ' ');11 if (tag != '') tags.push(tag);12 }13 return tags;14}15var autoTag;16var tagPos = 0;17function initTags() {18 /* browsers don't want to cache the tags field, so we use a hidden input field to cache them */19 var t = getByID('tags-cache');20 if ( t ) {21 log('tag cache:'+t.value);22 var v = getByID('tags');23 if ( t.value )24 v.value = t.value;25 DOM.addEventListener( v, "change", function() { log('caching tags'); t.value = v.value; } );26 }27 if (!mt.screen.tag_list || tagList.length == 0) return;28 autoTag = new TC.TagComplete("tags", tagList);29 autoTag.delimiter = tag_delim;30}31function validate(form) { 32 if (form.label.value.match(/\S/,''))33 return true;34 alert(mt.screen.trans.SPECIFY_CATEGORY);35 form.label.focus();36 return false;37}38function toggleFile() {39 var fld = getByID("basename");40 if (fld) {41 fld.disabled = false;42 fld.focus();43 var baseman = getByID("basename_manual");44 if (baseman) baseman.value = "1";45 var basewarn = getByID("basename-warning");46 if (basewarn) basewarn.style.display = "block";47 }48 var img = getByID("basename-lock");49 if (img)50 img.style.display = 'none';51 return false;52}53var tableSelect;54jQuery(document).ready(function($) {55 // setup56 tableSelect = new TC.TableSelect( mt.screen.asset_type + "-listing-table" );57 tableSelect.rowSelect = true;58 initTags();...

Full Screen

Full Screen

style.js

Source:style.js Github

copy

Full Screen

1/* @flow */2import { parseText } from 'compiler/parser/text-parser'3import { parseStyleText } from 'web/util/style'4import {5 getAndRemoveAttr,6 getBindingAttr,7 baseWarn8} from 'compiler/helpers'9function transformNode (el: ASTElement, options: CompilerOptions) {10 const warn = options.warn || baseWarn11 const staticStyle = getAndRemoveAttr(el, 'style')12 if (staticStyle) {13 /* istanbul ignore if */14 if (process.env.NODE_ENV !== 'production') {15 const res = parseText(staticStyle, options.delimiters)16 if (res) {17 warn(18 `style="${staticStyle}": ` +19 'Interpolation inside attributes has been removed. ' +20 'Use v-bind or the colon shorthand instead. For example, ' +21 'instead of <div style="{{ val }}">, use <div :style="val">.'22 )23 }24 }25 el.staticStyle = JSON.stringify(parseStyleText(staticStyle))26 }27 const styleBinding = getBindingAttr(el, 'style', false /* getStatic */)28 if (styleBinding) {29 el.styleBinding = styleBinding30 }31}32function genData (el: ASTElement): string {33 let data = ''34 if (el.staticStyle) {35 data += `staticStyle:${el.staticStyle},`36 }37 if (el.styleBinding) {38 data += `style:(${el.styleBinding}),`39 }40 return data41}42export default {43 staticKeys: ['staticStyle'],44 transformNode,45 genData...

Full Screen

Full Screen

class.js

Source:class.js Github

copy

Full Screen

1/* @flow */2import { parseText } from 'compiler/parser/text-parser'3import {4 getAndRemoveAttr,5 getBindingAttr,6 baseWarn7} from 'compiler/helpers'8function transformNode (el: ASTElement, options: CompilerOptions) {9 const warn = options.warn || baseWarn10 const staticClass = getAndRemoveAttr(el, 'class')11 if (process.env.NODE_ENV !== 'production' && staticClass) {12 const res = parseText(staticClass, options.delimiters)13 if (res) {14 warn(15 `class="${staticClass}": ` +16 'Interpolation inside attributes has been removed. ' +17 'Use v-bind or the colon shorthand instead. For example, ' +18 'instead of <div class="{{ val }}">, use <div :class="val">.'19 )20 }21 }22 if (staticClass) {23 el.staticClass = JSON.stringify(staticClass)24 }25 const classBinding = getBindingAttr(el, 'class', false /* getStatic */)26 if (classBinding) {27 el.classBinding = classBinding28 }29}30function genData (el: ASTElement): string {31 let data = ''32 if (el.staticClass) {33 data += `staticClass:${el.staticClass},`34 }35 if (el.classBinding) {36 data += `class:${el.classBinding},`37 }38 return data39}40export default {41 staticKeys: ['staticClass'],42 transformNode,43 genData...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const {baseWarn,baseError,baseInfo} = require('@playwright/test/lib/reporters/base');2baseWarn('This is a warning');3baseError('This is an error');4baseInfo('This is an info');5const {baseTestResult} = require('@playwright/test/lib/reporters/base');6baseTestResult({title: 'test', fullTitle: 'test', duration: 0, error: undefined, status: 'passed'});7const {baseSuiteResult} = require('@playwright/test/lib/reporters/base');8baseSuiteResult({title: 'suite', fullTitle: 'suite', file: 'file', duration: 0, error: undefined, status: '

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PlaywrightError } = require('@playwright/test');2const { InternalError } = require('@playwright/test/lib/utils/errors');3const { baseWarn } = require('@playwright/test/lib/utils/stackTrace');4const internalError = new InternalError('test');5const error = new PlaywrightError('test', internalError);6baseWarn(error);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2const { baseWarn } = Playwright.InternalError;3baseWarn('test');4const { Playwright } = require('playwright');5const { baseWarn } = Playwright.InternalError;6baseWarn('test');7 at Object.baseWarn (C:\Users\username\AppData\Roaming\npm-cache\_npx\28964\node_modules\playwright\lib\server\utils\utils.js:22:15)8 at Object.<anonymous> (C:\Users\username\playwright-test\test.js:3:20)9 at Module._compile (node:internal/modules/cjs/loader:1108:14)10 at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)11 at Module.load (node:internal/modules/cjs/loader:973:32)12 at Function.Module._load (node:internal/modules/cjs/loader:813:14)13 at Module.require (node:internal/modules/cjs/loader:996:19)14 at require (node:internal/modules/cjs/helpers:92:18)15 at Object.<anonymous> (C:\Users\username\playwright-test\test.js:1:1)16const { Playwright } = require('playwright');17const { baseWarn } = Playwright.InternalError;18console.warn('test');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { baseWarn } = require('@playwright/test/lib/utils/stackTrace');2baseWarn('test');3 at Object.<anonymous> (test.js:3:1)4 at Module._compile (internal/modules/cjs/loader.js:999:30)5 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)6 at Module.load (internal/modules/cjs/loader.js:863:32)7 at Function.Module._load (internal/modules/cjs/loader.js:708:14)8 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('@playwright/test');2Playwright.baseWarn('Test warning');3const { Playwright } = require('@playwright/test');4const playwright = new Playwright();5const { Playwright } = require('@playwright/test');6const playwright = new Playwright();7playwright.baseWarn('Test warning');8const { Playwright } = require('@playwright/test');9const playwright = new Playwright();10playwright.baseLog('Test Log');11const { Playwright } = require('@playwright/test');12const playwright = new Playwright();13playwright.baseError('Test Error');14const { Playwright } = require('@playwright/test');15const playwright = new Playwright();16playwright.baseInfo('Test Info');17const { Playwright } = require('@playwright/test');18const playwright = new Playwright();19playwright.baseDebug('Test Debug');

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