How to use isKeyOfType method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

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

InlineEditor.js

Source: InlineEditor.js Github

copy
1// @flow
2
3import React, { PureComponent } from 'react'
4import isEqual from 'lodash.isequal'
5import ClickOutside from 'react-click-outside'
6
7import Button from './Button'
8
9const cmz = require('cmz')
10
11const cx = {
12  editor: cmz(`
13    width: 100%
14  `),
15
16  link: cmz(`
17    & {
18      text-decoration: none
19      color: inherit
20    }
21
22    &:hover {
23      text-decoration: underline
24    }
25  `),
26
27  button: cmz(`
28    margin-top: 10px
29    margin-right: 10px
30  `),
31
32  warningMessage: cmz(`
33    padding: 10px 0
34  `)
35}
36
37const KEY_CODES = {
38  ENTER: 13,
39  ESCAPE: 27
40}
41
42const isKeyOfType = (keyCode: number, type: number) => keyCode === type
43
44export type EditorProps = {
45  value: any,
46  onValueChange(data: any): any
47}
48
49export type PresenterProps = {
50  value: any,
51  isEditable: boolean,
52  isHover: boolean,
53  activateEditingMode(): any
54}
55
56type Props = {
57  /** Component's value */
58  value: any,
59  /** To control whether the component can be editable or not */
60  isEditable: boolean,
61  /** To control whether the component begins in presenter mode or edit mode */
62  initialMode: 'present' | 'edit',
63  /** To control whether the component can be saved or not */
64  isValid: boolean,
65  /** To control whether the component will save changes on Enter or not, the Shift+Enter combination works always */
66  shouldSaveOnEnter: boolean,
67  /** Editing mode render function */
68  editor(props: EditorProps): any,
69  /** Presentation mode render function */
70  presenter(props: PresenterProps): any,
71  /** On save changes callback */
72  onSave(data: any): any,
73  /** On cancel changes callback */
74  onCancel?: () => void,
75}
76
77type State = {
78  editValue: any,
79  isInEditMode: boolean,
80  isHover: boolean
81}
82
83/**
84 * A generic component that provides inline editing functionality to any component.
85 */
86class InlineEditor extends PureComponent<Props, State> {
87  static defaultProps = {
88    isEditable: true,
89    initialMode: 'present',
90    isValid: true,
91    shouldSaveOnEnter: true
92  }
93
94  state = {
95    isInEditMode: this.props.initialMode === 'edit',
96    isHover: false,
97    editValue: this.props.value
98  }
99
100  componentWillReceiveProps (nextProps: Props) {
101    const { value } = nextProps
102    if (this.props.value !== value && this.state.editValue !== value) {
103      this.setState({ editValue: value })
104    }
105  }
106
107  renderControls = () => {
108    const { editValue } = this.state
109    const { value, isValid } = this.props
110
111    return (
112      <div>
113        <Button
114          className={cx.button}
115          type='button'
116          size='small'
117          rounded
118          onClick={this.handleSaveClick}
119          disabled={isEqual(editValue, value) || !isValid}
120        >
121          Save
122        </Button>
123        <Button
124          className={cx.button}
125          type='button'
126          size='small'
127          rounded
128          color='silver'
129          onClick={this.handleCancelClick}
130        >
131          Cancel
132        </Button>
133      </div>
134    )
135  }
136
137  setEditing = (isInEditMode: boolean) => {
138    let update = { isInEditMode }
139    if (!isInEditMode) {
140      update = {
141        ...update,
142        isHover: false
143      }
144    }
145    this.setState(update)
146  }
147
148  handleContainerClick = () => {
149    if (this.state.isInEditMode) {
150      this.abortChanges()
151    }
152  }
153
154  handleComponentClick = (event: Object) => {
155    if (this.state.isInEditMode) {
156      event.stopPropagation()
157    }
158  }
159
160  handleKeyDown = (event: Object) => {
161    const { keyCode } = event
162    const { shouldSaveOnEnter } = this.props
163    const { ENTER, ESCAPE } = KEY_CODES
164
165    const saveChanges = shouldSaveOnEnter
166      ? isKeyOfType(keyCode, ENTER)
167      : event.shiftKey && isKeyOfType(keyCode, ENTER)
168
169    if (saveChanges) {
170      this.saveChanges()
171    } else if (isKeyOfType(keyCode, ESCAPE)) {
172      this.abortChanges()
173    }
174  }
175
176  handleSaveClick = (event: Object) => {
177    event.stopPropagation()
178    this.saveChanges()
179  }
180
181  saveChanges = () => {
182    const { editValue } = this.state
183    const { onSave, isValid } = this.props
184
185    if (isValid) {
186      this.setEditing(false)
187
188      if (onSave) {
189        onSave(editValue)
190      }
191    }
192  }
193
194  abortChanges = () => {
195    const { value, onCancel } = this.props
196
197    this.setState({
198      editValue: value,
199      isInEditMode: false,
200      isHover: false
201    })
202
203    if (onCancel) {
204      onCancel()
205    }
206  }
207
208  handleCancelClick = (event: Object) => {
209    event.stopPropagation()
210    this.abortChanges()
211  }
212
213  handleClickOutside = () => {
214    this.abortChanges()
215  }
216
217  handleValueChange = (value: any) => {
218    this.setState({ editValue: value })
219  }
220
221  handleActivateEditingMode = () => {
222    if (this.props.isEditable) {
223      this.setEditing(true)
224    }
225  }
226
227  handleMouseEnter = () => {
228    this.setState({ isHover: true })
229  }
230
231  handleMouseLeave = () => {
232    this.setState({ isHover: false })
233  }
234
235  renderContent = () => {
236    const { editValue, isHover, isInEditMode } = this.state
237    const { editor, presenter, isEditable } = this.props
238    const mainComponentRenderer = isInEditMode ? editor : presenter
239    const props = {
240      value: editValue,
241      onValueChange: this.handleValueChange,
242      activateEditingMode: this.handleActivateEditingMode,
243      isEditable,
244      isHover
245    }
246
247    return (
248      <div
249        onClick={this.handleContainerClick}
250        onKeyDown={this.handleKeyDown}
251        onMouseEnter={this.handleMouseEnter}
252        onMouseLeave={this.handleMouseLeave}
253      >
254        <div onClick={this.handleComponentClick}>
255          {mainComponentRenderer && mainComponentRenderer(props)}
256        </div>
257        {isInEditMode && this.renderControls()}
258      </div>
259    )
260  }
261
262  render () {
263    return this.state.isInEditMode
264      ? (
265        <div className={cx.editor}>
266          <ClickOutside onClickOutside={this.handleClickOutside}>
267            {this.renderContent()}
268          </ClickOutside>
269        </div>
270      ) : this.renderContent()
271  }
272}
273
274export default InlineEditor
275
Full Screen

KeyofType.js

Source: KeyofType.js Github

copy
1const UnionType = require("./UnionType"); 
2const LiteralType = require("./LiteralType"); 
3const Type = require("./Type.js");
4const Utils = require("../core/Utils");
5class KeyofType extends UnionType{
6    constructor(target, referenceType){
7        super([],target);
8        this.isKeyofType = true;
9        this.referenceType = referenceType;
10        this.hasGenericType = !!referenceType.isGenericType;
11        this.elements = this.getTypeKeys(referenceType)
12    }
13    clone(inference){
14        if( !inference || !this.hasGenericType ){
15            return this;
16        }
17        const type = Utils.inferTypeValue( this.referenceType.type(), inference );
18        if( type !== this.referenceType ){
19            return new KeyofType(this.target, type );
20        }
21        return this;
22    }
23
24    getTypeKeys( type ){
25        type = type || this.referenceType;
26        if( type.isGenericType ){
27            return [];
28        }
29        const properties = new Set();
30        if( type ){
31            const push=(name,type)=>{
32                properties.add( new LiteralType( this.target.getGlobalTypeById(type), this.target, name) );
33            }
34            switch(true){
35                case type.isLiteralObjectType :
36                case type.isEnumType :
37                    type.attributes.forEach( (value,key)=>{
38                        push(key, 'string');
39                    });
40                break;
41                case type.isLiteralArrayType :
42                case type.isTupleUnion :
43                    type.elements.forEach( (value,key)=>{
44                        push(key, 'number');
45                    });
46                break;
47                case type.isIntersectionType : 
48                case type.isModule :
49                case type.isInstanceofType :
50                    type.getTypeKeys().forEach( key=>{
51                        push(key, 'string');
52                    });
53                break
54            }
55        }
56        return Array.from( properties.values() );
57    }
58    is(type, context){
59        if( !type || !(type instanceof Type) )return false;
60        if( !this.isNeedCheckType(type) )return true;
61        if( type.isAliasType ){
62            const inherit = type.inherit;
63            if( inherit && inherit.isUnionType ){
64                type = inherit;
65            }
66        }
67        const infer = type=>{
68            if( context && context.inference ){
69                return context.inference(type);
70            }
71            return type;
72        };
73        const elements = this.getTypeKeys( infer( this.referenceType ) );
74        if( !elements.length )return false; 
75        if( type.isUnionType ){
76            return type.elements.every( item=>{
77                const base = item.type();
78                return elements.some( child=>{
79                    const childType = child.type();
80                    if( base.isLiteralType ){
81                        return childType.isLiteralType ? base.value === childType.value : false;
82                    }
83                    return base.is(child.type(), context);
84                });
85            });
86        }
87       
88        return elements.some( base=>base.type().is(type, context) );
89    }
90    toString(context={}){
91        const refType = this.referenceType.type();
92        if( refType.hasGenericType ){
93            if( refType.isGenericType && refType.hasConstraint && !refType.inherit.hasGenericType ){
94                return `keyof ${refType.inherit.toString(context)}`;
95            }
96            return `keyof ${refType.toString(context)}`;
97        }
98        let elements = this.getTypeKeys( refType );
99        if( !elements.length ){
100            return 'never';
101        }
102        return elements.map( item=>item.type().toString(context) ).join(' | ');
103    }
104}
105module.exports = KeyofType;
Full Screen

TupleType.js

Source: TupleType.js Github

copy
1const Utils = require("../core/Utils");
2const Namespace = require("../core/Namespace");
3const Type = require("./Type");
4class TupleType extends Type{
5    constructor(inherit, elements , target, rest = false , isTupleUnion=false){
6        super("$TupleType",inherit);
7        this.elements = [].concat(elements);
8        const len = this.elements.length;
9        this.rest = rest;
10        this.requireCount = rest && len > 1 ? len-1 : len;
11        this.isTupleType = true;
12        this.prefix = !!(target && target.prefix);
13        this.isTupleUnion = isTupleUnion ? true : !!(target && target.isTypeTupleUnionDefinition);
14        this.target = target;
15    }
16
17    get hasGenericType(){
18        return this.elements.some( type=>{
19            type = type.type();
20            return type && type.hasGenericType;
21        });
22    }
23
24    attribute(index){
25        if( !(this.prefix || this.isTupleUnion) ){
26            return this.elements[ index ] || null;
27        }
28        return null;
29    }
30
31    dynamicAttribute( type ){
32        const arrClass = Namespace.globals.get('Array');
33        return arrClass && arrClass.dynamicProperties.get( Utils.getOriginType( type ) );
34    }
35
36    clone(inference){
37        if( !inference || !this.hasGenericType ){
38            return this;
39        }
40        const elements = this.elements.map( item=>{
41            return Utils.inferTypeValue(item.type(), inference);
42        });
43        return new TupleType(this.inherit,elements,this.target,this.rest, this.isTupleUnion);
44    }
45    checkItems(items, errorItems=[], context={} ){
46        const infer = type =>Utils.inferTypeValue(type, context.inference);
47        const errorHandler = context.errorHandler || ( result=>result );
48        const checkItem = (base, item, flag=true)=>{
49            const baseType = infer( base.type() );
50            const type = infer( item.type() );
51            if( ( base.isThisType || (base.target && base.target.isThisType) ) && !type.isInstanceofType ){
52                errorItems.push( item );
53                return flag ? errorHandler(false, baseType, item) : false;
54            }
55            if( baseType && !baseType.is( type, context ) ){
56                errorItems.push( item );
57                return flag ? errorHandler(false, baseType, item) : false;
58            }
59            return true;
60        }
61        if(this.prefix || this.rest || this.isTupleUnion){
62            return items.every( (item)=>{
63                return errorHandler(this.elements.some( base=>{
64                    return checkItem(base, item, false);
65                }), this.elements[0].type(), item);
66            });
67        }
68        const len = this.elements.length;
69        const rest = len > 0 ? this.elements[ len-1 ] : null;
70        const hasRest = rest && rest.type().rest;
71        const requireCount = hasRest ? this.requireCount-1 : this.requireCount;
72        if( (hasRest && items.length < requireCount) ){
73            return false;
74        }else if( !hasRest && items.length !== requireCount ){
75            return false;
76        }
77        return items.every( (item,index)=>{
78            let base = this.elements[index];
79            if( base && !(hasRest && base === rest) ){
80                return checkItem(base,item);
81            }else{
82                if( hasRest && rest ){
83                    return checkItem(rest,item);
84                }else{
85                    return errorHandler(this.elements.some( (base)=>{
86                        return checkItem(base,item,false);
87                    }), this.elements[0].type(), item );
88                }
89            }
90        });
91    }
92    is( type, context ){
93        if( !type || !(type instanceof Type) )return false;
94        if( !this.isNeedCheckType(type) )return true;
95        if( type.isAliasType ){
96            const inherit = type.inherit;
97            if( inherit && inherit.isTupleType ){
98                type = inherit;
99            }
100        }
101        if( this.isTupleUnion && !this.inherit.is(type.inherit, context) ){
102            return false;
103        }
104        let items = [];
105        if( type.isTupleType || type.isLiteralArrayType){
106            items =type.elements;
107        }else if( type.isClassGenericType && type.inherit === this.inherit ){
108            items = type.types;
109        }else if( !this.rest ){
110            return this.inherit.is(type, context);
111        }
112        return this.checkItems( items , [], context);
113    }
114    toString(context){
115        const isTupleUnion = this.isTupleUnion || this.elements.some( item=>{
116            let type = item.type();
117            if( type.isComputeType && !type.object.isThisType ){
118                type = type.property.type();
119            }
120            return !!type.isUnionType;
121        });
122        context = {parent:context,type:this,isTupleUnion};
123        const elements = this.elements.map( (item)=>{
124            return item.type().toString(context);
125        });
126        const rest = this.rest && this.target && !this.target.isRestElement ? '...' : '';
127        if( isTupleUnion ){
128            if( elements.length > 1 || ( (this.elements[0].isUnionType || this.elements[0].isKeyofType) && this.elements[0].elements.length > 1) ){
129                return `(${elements.join(" | ")})[]`;
130            }else{
131                return `${elements[0]}[]`;
132            }
133        }
134        if( elements.length === 1 && (this.prefix||this.rest) ){
135            return `${rest}${elements[0]}[]`;
136        }
137        return `${rest}[${elements.join(',')}]`;
138    }
139}
140module.exports = TupleType;
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)