How to use _wrapCode 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.

omPreDialog.js

Source: omPreDialog.js Github

copy
1/**
2 * Dialog for preformat code insertation
3 * @author Roman Ozana <ozana@omdesign.cz>
4 */
5
6var omPreDialog = (function ($) {
7
8	var _modal = _decDictionary = _options = {};
9	var _editor, _encRegex, _node;
10
11	var _tags = {
12		precode: { open: '<pre><code>', close: '</code></pre>' },
13		pre: { open: '<pre>', close: '</pre>'},
14		code: { open: '<code>', close: '</code>' }
15	};
16
17	var _encoding = { '<': 'lt', '>': 'gt', '"': 'quot', '&': 'amp' };
18
19	/**
20	 * Wrap code with tags
21	 * @param string code
22	 * @param wrapper
23	 * @return {*}
24	 * @private
25	 */
26	var _wrapCode = function _wrapCode(code, wrapper) {
27		return _tags[wrapper].open + code + _tags[wrapper].close;
28	}
29
30	/**
31	 * Encode common HTML elements
32	 * @param text
33	 * @return {*|void}
34	 * @private
35	 */
36	var _processCode = function _processCode(content, spaces) {
37		content = content.replace(_encRegex, function (char) {
38			return '&' + _encoding[char] + ';';
39		});
40
41		// replace tab with spaces
42		if (spaces) content = content.replace(/\t/g, ' ');
43
44		return content;
45	}
46
47	return {
48		getModalBody: function () {
49			var style = 'float:left;margin-right:8px;';
50
51			return [
52				{
53					type: 'textbox',
54					name: 'omCode',
55					label: '',
56					value: this.getContent(),
57					multiline: true,
58					autofocus: true,
59					minWidth: 820,
60					minHeight: 420
61				},
62				{
63					type: 'container',
64					style: "height:32px",
65					items: [
66						{
67							type: 'listbox',
68							name: 'omCodeWrapper',
69							style: style,
70							value: this.getCodeWrapper(),
71							values: [
72								{text: '<pre><code>', value: 'precode'},
73								{text: '<pre>', value: 'pre'},
74								{text: '<code>', value: 'code'}
75							]
76						},
77						{name: 'omSpaces', type: 'checkbox', checked: true, text: 'nahradit taby mezerama', style: style + 'margin-top: 6px'}
78					]
79				}
80			]
81		},
82
83		init: function () {
84
85			// Dinamically init the decoding dictionary and the encoding regex
86			var char_list = '';
87			for (var ch in _encoding) {
88				char_list += ch;
89				_decDictionary[ _encoding[ch] ] = ch
90			}
91			_encRegex = new RegExp('[' + char_list + ']', 'g');
92		},
93
94		open: function (editor, url) {
95			_editor = editor;
96			_node = editor.selection.getNode(); // current node
97
98			_modal = editor.windowManager.open({
99						id: 'omPreDialog_wrapper',
100						title: 'Vložit preformátovaný kód',
101						pading: 0,
102						dialogClass: 'wp-dialog',
103						zIndex: 99999,
104						body: this.getModalBody(),
105						onsubmit: function (e) {
106
107							if (e.data.omCode) {
108								console.log(e.data);
109								omPreDialog.updateContent(
110										e.data.omCode,
111										e.data.omCodeWrapper,
112										e.data.omSpaces
113								)
114							} else {
115								e.preventDefault();
116							}
117						}
118					}
119			);
120		},
121
122		getCodeWrapper: function () {
123			if (_editor.selection.getContent() || _node.nodeName == 'CODE') return 'code';
124			if (_node.nodeName == 'PRE') return 'pre';
125			if (_node.nodeName == 'CODE' && _node.parentNode.nodeName == 'PRE') return 'precode';
126		},
127
128		getContent: function () {
129			if (_node.nodeName == 'PRE' || _node.nodeName == 'CODE') {
130				return _editor.selection.getNode().innerText;
131			}
132			if (_editor.selection.getContent()) return _editor.selection.getContent();
133		},
134
135		updateContent: function (code, wrapper, spaces) {
136			var code = _wrapCode(_processCode(code, spaces), wrapper); // handle code
137			// have some tags? select them
138			if (_node.nodeName == 'PRE' || _node.nodeName == 'CODE') {
139				if (_node.nodeName == 'CODE' && _node.parentNode.nodeName == 'PRE') {
140					_editor.selection.select(_node.parentNode);
141				} else {
142					_editor.selection.select(_node);
143				}
144			}
145
146			// split paragraph to two new when
147			if (_node.nodeName == 'CODE' && _node.parentNode.nodeName == 'P' && wrapper != 'code') _node.remove();
148
149			if (_editor.selection.getContent()) {
150				return _editor.selection.setContent(code);
151			}
152
153			// just insert new one
154			return _editor.execCommand('mceInsertContent', false, code);
155		}
156	};
157})(jQuery);
158
Full Screen

babel.js

Source: babel.js Github

copy
1const babel = require('@babel/core')
2const log = require('@ui5/logger').getLogger('ui5-task-babel')
3
4const _wrapCode = code => `(function() {\n'use strict';\n\n${code}\n})()`
5
6/**
7 * Custom UI5 task for transpiling code using babel.
8 *
9 * @param {Object} parameters Parameters
10 * @param {DuplexCollection} parameters.workspace DuplexCollection to read and write files
11 * @param {AbstractReader} parameters.dependencies Reader or Collection to read dependency files
12 * @param {Object} parameters.options Options
13 * @param {string} parameters.options.projectName Project name
14 * @param {string} [parameters.options.configuration] Task configuration if given in ui5.yaml
15 * @returns {Promise<undefined>} Promise resolving with undefined once data has been written
16 */
17module.exports = async ({ workspace, options }) => {
18  // get options / defaults
19  const { configuration = {} } = options
20  const { enabled = true, debug = false, wrap = true, files = ['**/*.js'] } = configuration
21  // skip task
22  if (!enabled) {
23    return
24  }
25  // match resources
26  const resources = await workspace.byGlob(files)
27  // transform resources concurrently
28  await Promise.all(resources.map(async resource => {
29    if (debug) {
30      log.info(`Transforming file: ${resource.getPath()}`)
31    }
32    const code = await resource.getString()
33    const result = await babel.transformAsync(code)
34    const transformed = wrap ? _wrapCode(result.code) : result.code
35    resource.setString(transformed)
36    await workspace.write(resource)
37  }))
38}
39
Full Screen

xmlDocumentation.js

Source: xmlDocumentation.js Github

copy
1/**
2 * Copyright (c) Microsoft Corporation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// @ts-check
18const Documentation = require('./documentation');
19const { visitAll } = require('../markdown');
20/**
21 * @param {Documentation.MarkdownNode[]} nodes
22 * @param {number} maxColumns
23 */
24function renderXmlDoc(nodes, maxColumns = 80, prefix = '/// ') {
25  if (!nodes)
26    return [];
27
28  const renderResult = _innerRenderNodes(nodes, maxColumns);
29
30  const doc = [];
31  _wrapInNode('summary', renderResult.summary, doc);
32  _wrapInNode('remarks', renderResult.remarks, doc);
33  return doc.map(x => `${prefix}${x}`);
34}
35
36function _innerRenderNodes(nodes, maxColumns = 80, wrapParagraphs = true) {
37  const summary = [];
38  const remarks = [];
39  const handleListItem = (lastNode, node) => {
40    if (node && node.type === 'li' && (!lastNode || lastNode.type !== 'li'))
41      summary.push(`<list type="${node.liType}">`);
42    else if (lastNode && lastNode.type === 'li' && (!node || node.type !== 'li'))
43      summary.push('</list>');
44
45  };
46
47  let lastNode;
48  visitAll(nodes, node => {
49    // handle special cases first
50    if (_nodeShouldBeIgnored(node))
51      return;
52    if (node.text && node.text.startsWith('extends: ')) {
53      remarks.push('Inherits from ' + node.text.replace('extends: ', ''));
54      return;
55    }
56    handleListItem(lastNode, node);
57    if (node.type === 'text') {
58      if (wrapParagraphs)
59        _wrapInNode('para', _wrapAndEscape(node, maxColumns), summary);
60      else
61        summary.push(..._wrapAndEscape(node, maxColumns));
62    } else if (node.type === 'code' && node.codeLang === 'csharp') {
63      _wrapInNode('code', _wrapCode(node.lines), summary);
64    } else if (node.type === 'li') {
65      _wrapInNode('item><description', _wrapAndEscape(node, maxColumns), summary, '/description></item');
66    } else if (node.type === 'note') {
67      _wrapInNode('para', _wrapAndEscape(node, maxColumns), remarks);
68    }
69    lastNode = node;
70  });
71  handleListItem(lastNode, null);
72
73  return { summary, remarks };
74}
75
76function _wrapCode(lines) {
77  let i = 0;
78  let out = [];
79  for (let line of lines) {
80    line = line.replace(/[&]/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
81    if (i < lines.length - 1)
82      line = line + "<br/>";
83    out.push(line);
84    i++;
85  }
86  return out;
87}
88
89function _wrapInNode(tag, nodes, target, closingTag = null) {
90  if (nodes.length === 0)
91    return;
92
93  if (!closingTag)
94    closingTag = `/${tag}`;
95
96  if (nodes.length === 1) {
97    target.push(`<${tag}>${nodes[0]}<${closingTag}>`);
98    return;
99  }
100
101  target.push(`<${tag}>`);
102  target.push(...nodes);
103  target.push(`<${closingTag}>`);
104}
105
106/**
107 *
108 * @param {Documentation.MarkdownNode} node
109 */
110function _wrapAndEscape(node, maxColumns = 0) {
111  const lines = [];
112  const pushLine = text => {
113    if (text === '')
114      return;
115    text = text.trim();
116    lines.push(text);
117  };
118
119
120  let text = node.text;
121  text = text.replace(/\[([^\]]*)\]\((.*?)\)/g, (match, linkName, linkUrl) => {
122    return `<a href="${linkUrl}">${linkName}</a>`;
123  });
124  text = text.replace(/(?<!`)\[(.*?)\]/g, (match, link) => `<see cref="${link}"/>`);
125  text = text.replace(/`([^`]*)`/g, (match, code) => `<c>${code.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</c>`);
126  text = text.replace(/ITimeoutError/, 'TimeoutException');
127  text = text.replace(/Promise/, 'Task');
128
129  const words = text.split(' ');
130  let line = '';
131  for (let i = 0; i < words.length; i++) {
132    line = line + ' ' + words[i];
133    if (line.length >= maxColumns) {
134      pushLine(line);
135      line = '';
136    }
137  }
138
139  pushLine(line);
140  return lines;
141}
142
143/**
144 *
145 * @param {Documentation.MarkdownNode} node
146 */
147function _nodeShouldBeIgnored(node) {
148  if (!node
149    || (node.text === 'extends: [EventEmitter]'))
150    return true;
151
152  return false;
153}
154
155/**
156 * @param {Documentation.MarkdownNode[]} nodes
157 */
158function renderTextOnly(nodes, maxColumns = 80) {
159  const result = _innerRenderNodes(nodes, maxColumns, false);
160  return result.summary;
161}
162
163module.exports = { renderXmlDoc, renderTextOnly }
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)