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

braces.js

Source: braces.js Github

copy
1/*
2
3Write a function that takes a string of braces, and determines if the order of the braces is valid.
4It should return true if the string is valid, and false if it's invalid.
5
6This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}.
7
8All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.
9What is considered Valid?
10
11A string of braces is considered valid if all braces are matched with the correct brace.
12
13*/
14
15console.log(validBraces("(){}[]")); // true
16console.log(validBraces("([{}])")); // true
17console.log(validBraces("[(])")); // false
18console.log(validBraces("[({})](]")); // false
19
20console.log(validBraces("(({{[[]]}}))")); // true
21console.log(validBraces("({})[({})]")); // true
22
23function validBraces(str) {
24  let matchingBracket = {};
25  matchingBracket["["] = "]";
26  matchingBracket["{"] = "}";
27  matchingBracket["("] = ")";
28
29  //   console.log(str);
30  let characters = str.split("");
31
32  // a valid string will always have even number of symbols
33  if (characters.length % 2 !== 0) return false;
34
35  // a valid string will always start with an opening bracket
36  if (!matchingBracket[characters[0]]) return false;
37
38  if (characters.length === 2) {
39    const openingBracket = characters.shift();
40    const closingBracket = characters.pop();
41    return matchingBracket[openingBracket] && closingBracket === matchingBracket[openingBracket];
42  }
43
44  const openingBracket = characters[0];
45  let closingBracketIndex = characters.lastIndexOf(matchingBracket[openingBracket]);
46
47  // there is a matching closing symbol at the end of the string
48  if (closingBracketIndex === str.length - 1) {
49    characters.shift();
50    characters.pop();
51    return validBraces(characters.join(""));
52    // otherwise find the first matching closing symbol we can possibly find,
53    // split the string in two and validate each section recursively
54  } else {
55    closingBracketIndex = characters.indexOf(matchingBracket[openingBracket]);
56    if (!closingBracketIndex) return false; // no closing symbol exists for this opener
57    const left = str.substring(0, closingBracketIndex + 1);
58    const right = str.substring(closingBracketIndex + 1, characters.length);
59    return validBraces(left) && validBraces(right);
60  }
61}
62
Full Screen

main.js

Source: main.js Github

copy
1/**
2* Brackets extension to select the block inside matching brackets by double clicking a bracket.
3*
4* Hugo Pessotti <hpessotti@gmail.com>
5**/
6define(function (require, exports, module) {
7
8	"use strict";
9
10	var AppInit = brackets.getModule("utils/AppInit"),
11		EditorManager = brackets.getModule("editor/EditorManager");
12
13	var checkMatching = function(editor, event) {
14		if (editor.doc.getSelection().match(/^[\s\[\]{}()]+$/)) {
15			var matchingBracket = editor.findMatchingBracket(editor.doc.getCursor());
16
17			if (matchingBracket && matchingBracket.match) {
18				matchingBracket.from.ch += 1;
19				editor.doc.setSelection(matchingBracket.from, matchingBracket.to);
20			}
21		}
22	}
23
24	var activeEditorChangeHandler = function ($event, focusedEditor, lostEditor) {
25        if (lostEditor) {
26            lostEditor._codeMirror.off("dblclick", checkMatching);
27        }
28        if (focusedEditor) {
29            focusedEditor._codeMirror.on("dblclick", checkMatching);
30        }
31    };
32
33	AppInit.appReady(function() {
34		$(EditorManager).on("activeEditorChange", activeEditorChangeHandler);
35	});
36});
37
Full Screen

editor.js

Source: editor.js Github

copy
1import {saveState, states, temp_file} from "./state_handler";
2
3import {open} from "./layout";
4import {make, request_reset, request_update} from "./event_handler";
5import {terminable_command} from "./canceller";
6import {registerEditor, removeEditor, notify_changed} from "./test_results";
7import {doTailViz, javastyle} from "./settings";
8
9export {register};
10
11function register(layout) {
12    layout.registerComponent('editor', function (container, componentState) {
13        let decoded = $.parseJSON(start_data);
14        let testable = componentState.id < decoded["files"].length;
15        let test_case = states[componentState.id].file_name.startsWith(temp_file);
16
17        container.getElement().html(`
18        <div class="content">
19            <div class="header">        
20                ${(!test_case) ?
21            `<button type="button" class="btn-light save-btn" aria-label="Save">
22                    <span class="text"> Save </span>
23                </button>` : ``}
24
25
26                <button type="button" data-toggle="tooltip"
27                            title="Open a console and run the program locally."
28                            class="btn-success toolbar-btn run-btn">Run</button>
29                ${testable ?
30            `<button type="button" data-toggle="tooltip"
31                            title="Run all ok.py tests locally."
32                            class="btn-danger toolbar-btn test-btn">Test</button>` : ``}
33                <button type="button" data-toggle="tooltip"
34                            title="Step through the program's execution."
35                            class="btn-primary toolbar-btn sub-btn">Debug</button>          
36                <button type="button" data-toggle="tooltip"
37                            title="View environment diagram."
38                            class="btn-info toolbar-btn env-btn">Environments</button>          
39                <button type="button" data-toggle="tooltip"
40                            title="Reformat code and fix (some) minor mistakes."
41                            class="btn-secondary toolbar-btn reformat-btn">Reformat</button>          
42            </div>
43            <div class="editor-wrapper">
44                <div class="editor"></div>
45            </div>
46        </div>
47    `);
48
49        make(container, "editor", componentState.id);
50
51        let editorDiv;
52        let editor;
53
54        let changed = false;
55        let saveTimer;
56
57        let name;
58
59        container.on("open", function () {
60            editorDiv = container.getElement().find(".editor").get(0);
61            editor = ace.edit(editorDiv);
62            ace.config.set("packaged", true);
63            editor.session.setMode("ace/mode/scheme");
64            editor.setOption("fontSize", 14);
65            editor.setOption("enableBasicAutocompletion", true);
66            editor.setOption("enableLiveAutocompletion", true);
67            editor.setAutoScrollEditorIntoView(true);
68            editor.getSession().setUseSoftTabs(true);
69            editor.container.style.background = "white";
70            editor.focus();
71
72            saveTimer = setInterval(() => save(), 5000);
73
74            states[componentState.id].editor_open = true;
75
76            container.on("resize", function () {
77                editor.resize();
78            });
79
80            if (testable) {
81                states[componentState.id].file_name = decoded["files"][componentState.id];
82            }
83
84            name = states[componentState.id].file_name;
85
86            if (test_case) {
87                editor.setValue(states[componentState.id].file_content);
88                registerEditor(name, editor);
89            } else {
90                $.post("/read_file", {
91                    filename: states[componentState.id].file_name,
92                }).done(function (data) {
93                    data = $.parseJSON(data);
94                    editor.setValue(data);
95                });
96            }
97
98            editor.getSession().on("change", function () {
99                container.getElement().find(".save-btn > .text").text("Save");
100                changed = true;
101            });
102
103            let selectMarker;
104
105            function getMatchingBracket() {
106                let cursor = editor.getCursorPosition();
107                let index = editor.getSession().getDocument().positionToIndex(cursor);
108                let nextVal = editor.getValue()[index];
109                let prevVal = editor.getValue()[index - 1];
110
111                if (prevVal === ")" || prevVal === "]") {
112                    return editor.getSession().findMatchingBracket(cursor, prevVal);
113                } else if (nextVal === "(" || nextVal === "[") {
114                    cursor.column += 1;
115                    let out = editor.getSession().findMatchingBracket(cursor, nextVal);
116                    if (out !== null) {
117                        out.column += 1;
118                    }
119                    return out;
120                }
121                return null;
122            }
123
124            editor.getSelection().on("changeCursor", function () {
125                let matchingBracket = getMatchingBracket();
126                if (selectMarker !== undefined) {
127                    editor.getSession().removeMarker(selectMarker);
128                }
129                if (matchingBracket !== null) {
130                    let currentPos = editor.getCursorPosition();
131
132                    if (currentPos.row > matchingBracket.row ||
133                        currentPos.row === matchingBracket.row && currentPos.column > matchingBracket.column) {
134                        let temp = currentPos;
135                        currentPos = matchingBracket;
136                        matchingBracket = temp;
137                    }
138
139                    let range = new ace.Range(currentPos.row, currentPos.column, matchingBracket.row, matchingBracket.column);
140                    selectMarker = editor.getSession().addMarker(range, "ace_selection match_parens", editor.getSelectionStyle());
141                }
142            });
143        });
144
145        layout.eventHub.on("update", () => {
146            if (states[componentState.id].environments.length === 0) {
147                // program has never been run
148                container.getElement().find(".env-btn")//.prop("disabled", true)
149                    .attr('data-original-title', "To use the environment diagram, press Run first.");
150                container.getElement().find(".sub-btn")//.prop("disabled", true)
151                    .attr('data-original-title', "To use the debugger, press Run first.");
152            } else {
153                container.getElement().find(".env-btn")//.prop("disabled", false)
154                    .attr('data-original-title', "View environment diagram.");
155                container.getElement().find(".sub-btn")//.prop("disabled", false)
156                    .attr('data-original-title', "Step through the program's execution.");
157            }
158        });
159
160        container.on("destroy", function () {
161            removeEditor(name, editor);
162            clearInterval(saveTimer);
163        });
164
165
166        container.getElement().keydown(function (event) {
167            if ((event.ctrlKey || event.metaKey) && event.keyCode === 13) {
168                event.preventDefault();
169                // noinspection JSIgnoredPromiseFromCall
170                run();
171            }
172            if ((event.ctrlKey || event.metaKey) && event.keyCode === 83) {
173                event.preventDefault();
174                // noinspection JSIgnoredPromiseFromCall
175                save();
176            }
177        });
178
179        container.getElement().find(".run-btn").on("click", () => run());
180
181        container.getElement().find(".save-btn").on("click", () => save());
182
183        container.getElement().find(".reformat-btn").on("click", reformat);
184
185        container.getElement().find(".sub-btn").on("click", async function () {
186            await save();
187            await run(true);
188            open("substitution_tree", componentState.id);
189        });
190
191        container.getElement().find(".env-btn").on("click", async function () {
192            await save();
193            await run(true);
194            open("env_diagram", componentState.id);
195        });
196
197        container.getElement().find(".test-btn").on("click", run_tests);
198
199        async function save(running) {
200            if (!running && !changed) {
201                return;
202            }
203
204            if (test_case) {
205                states[componentState.id].file_content = editor.getValue();
206            }
207
208            container.getElement().find(".save-btn > .text").text("Saving...");
209
210            let code = [editor.getValue()];
211            await $.post("./save", {
212                code: code,
213                filename: name,
214                do_save: !test_case,
215            }).done(function (data) {
216                data = $.parseJSON(data);
217                if (data["result"] === "success") {
218                    container.getElement().find(".save-btn > .text").text("Saved");
219                    changed = false;
220                    if (running) {
221                        states[componentState.id].active_code = data["stripped"];
222                        states[componentState.id].up_to_date = true;
223                        return;
224                    }
225                    if (states[componentState.id].active_code === data["stripped"]) {
226                        if (!states[componentState.id].up_to_date) {
227                            states[componentState.id].up_to_date = true;
228                            request_update();
229                        }
230                        states[componentState.id].up_to_date = true;
231                    } else {
232                        states[componentState.id].up_to_date = false;
233                    }
234                } else {
235                    alert("Save error - try copying code from editor to a file manually");
236                }
237            })
238        }
239
240        async function run(noOutput) {
241            let code = [editor.getValue()];
242
243            async function run_done(data) {
244                data = $.parseJSON(data);
245                if (data.success) {
246                    states[componentState.id].states = data.states;
247                    states[componentState.id].environments = [];
248                    for (let key of data.active_frames) {
249                        states[componentState.id].environments.push(data.frame_lookup[key]);
250                    }
251                    states[componentState.id].moves = data.graphics;
252                    states[componentState.id].out = data.out[0];
253                    states[componentState.id].start = data.states[0][0];
254                    states[componentState.id].end = data.states[0][1];
255                    states[componentState.id].index = data.states[0][0];
256                    states[componentState.id].expr_i = 0;
257                    states[componentState.id].roots = data.roots;
258                    states[componentState.id].globalFrameID = data.globalFrameID;
259                    states[componentState.id].heap = data.heap;
260                    states[componentState.id].frameUpdates = data.frameUpdates;
261                } else {
262                    states[componentState.id].out = data.out[0];
263                    states[componentState.id].globalFrameID = -1;
264                }
265
266                await save(true);
267
268                if (!noOutput) {
269                    open("output", componentState.id);
270                    if (data.graphics_open) {
271                        open("turtle_graphics", componentState.id);
272                    }
273                }
274                // noinspection JSIgnoredPromiseFromCall
275                saveState(true);
276                request_reset();
277                request_update();
278            }
279
280            let aj = $.post("./process2", {
281                code: code,
282                globalFrameID: -1,
283                curr_i: 0,
284                curr_f: 0,
285                tailViz: doTailViz()
286            });
287            terminable_command("executing code", aj, run_done);
288        }
289
290        function reformat() {
291            let code = [editor.getValue()];
292            $.post("./reformat", {
293                code: code,
294                javastyle: javastyle(),
295            }).done(function (data) {
296                if (data) {
297                    data = $.parseJSON(data);
298                    editor.setValue(data["formatted"] + "\n");
299                } else {
300                    $("#formatFailModal").modal("show");
301                }
302            });
303        }
304
305        async function run_tests() {
306            if (editor.getValue().trim() === "") {
307                return;
308            }
309            await save();
310            let ajax = $.post("./test");
311
312            async function done_fn(data) {
313                data = $.parseJSON(data);
314                states[0].test_results = data;
315                await save();
316                notify_changed();
317                open("test_results", 0);
318            }
319
320            terminable_command("test cases", ajax, done_fn);
321        }
322    });
323}
324
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)