How to use test_svg method in wpt

Best JavaScript code snippet using wpt

combined.js

Source:combined.js Github

copy

Full Screen

1// ==================== Unit Testing ====================2const enable_tests = false3var test_count = 0, test_passes = 04function test(f){5 if(enable_tests){6 return f()7 }8}9function getErrorObject(){10 try { throw Error('') } catch(err) { return err; }11}12function check(a, b, f, name, stack_depth = 2){13 var err = getErrorObject()14 var caller_line = err.stack.split("\n")[stack_depth]15 var index = caller_line.indexOf(".js")16 var clean = caller_line.slice(index+4, caller_line.length)17 var result = f(a, b)18 test_count++19 if (result) {test_passes++}20 console.assert(result,21 "Values not " + name + " on line " + clean,22 a,23 b)24}25function checker(f, name){26 return ((a, b) => check(a, b, f, name, 3))27}28var check_equal = checker(_.isEqual, "equal")29var check_lt = checker(_.lt, "<")30var check_gt = checker(_.gt, ">")31test(() => console.log("Testing enabled!"))32test(() =>33 {window.onload =34 (() =>35 {console.log(`Passed ${test_passes}/${test_count} checks.`)})})36function map_keys(hash, f){37 return _.map(_.keys(hash), f)38}39function map_key_values(hash, f){40 return map_keys(hash,41 (k) => {return f(k, hash[k])})42}43function remove_duplicates(l){44 return _.uniqWith(l, _.isEqual)45}46test(() => {47 var l1 = [1, 2, 3]48 check_equal(remove_duplicates(l1),49 l1)50 var l2 = [1, 1, 2, 3]51 check_equal(remove_duplicates(l2),52 l1)53 var l3 = [1, 2, 3, 2, 1]54 check_equal(remove_duplicates(l3),55 l1)56 var l4 = [{"a": 1, "b": 2}, {"a": 1, "b": 3}]57 check_equal(remove_duplicates(l4),58 l4)59 var l5 = [{"a": 1, "b": 2}, {"a": 1, "b": 3}, {"a": 1, "b": 3}]60 check_equal(remove_duplicates(l5),61 l4)62})63function add_between(l, v){64 const make_v = ((typeof v == "function") ? v : (() => v))65 var result = []66 for(const el of l){67 result.push(el)68 result.push(make_v())69 }70 if (result.length > 0) {71 result.pop() // remove the last one72 }73 return result74}75test(() => {76 var l1 = [1, 2, 3]77 check_equal(add_between(l1, ","), [1, ",", 2, ",", 3])78 check_equal(add_between([], ","), [])79})80class StringMap {81 string_map = null82 constructor(mappings = []){83 this.string_map = new Map()84 for(const [k, v] of mappings){85 this.set_in_place(k, v)86 }87 }88 copy(){89 var copied = new StringMap()90 for(const [str, [k, v]] of this.string_map) {91 copied.string_map.set(str, [k, v])92 }93 return copied94 }95 repr(key){96 function replacer(key, value){97 if (value instanceof Map){98 return Array.from(value.entries())99 } else if (value instanceof StringMap){100 return Array.from(value.string_map.entries())101 } else{102 return value103 }104 }105 // if (key instanceof Map){106 // return JSON.stringify(Array.from(key.entries()));107 // } else if (key instanceof StringMap){108 // return JSON.stringify(Array.from(key.string_map.entries()));109 // } else{110 // return JSON.stringify(key)111 // }112 return JSON.stringify(key, replacer)113 }114 ref(key){115 const str = this.repr(key)116 var [_, v] = this.string_map.get(str)117 return v118 }119 set_in_place(key, value){120 const str = this.repr(key)121 this.string_map.set(str, [key, value])122 }123 set(key, value){124 var updated = this.copy()125 updated.set_in_place(key, value)126 return updated127 }128 keys(){129 var res = []130 for(const [_1, [k, _2]] of this.string_map) {131 res.push(k)132 }133 return res134 }135 values(){136 var res = []137 for(const [_1, [_2, v]] of this.string_map) {138 res.push(v)139 }140 return res141 }142 has_key(key){143 const str = this.repr(key)144 return this.string_map.has(str)145 }146}147test(() => {148 const a = {a: 1, b: 2},149 c = {c: 1, d: 2},150 d = {d: 1, e: 2}151 const m = new StringMap([[a, "a"], [c, "c"]])152 check_equal(m.ref(a), "a")153 check_equal(m.ref(c), "c")154 check_equal(m.keys(), [a, c])155 check_equal(m.values(), ["a", "c"])156 const m2 = m.set(d, "d")157 check_equal(m.has_key(d), false)158 check_equal(m2.has_key(d), true)159 check_equal(m2.ref(a), "a")160 check_equal(m2.ref(c), "c")161 check_equal(m2.ref(d), "d")162 check_equal(m2.keys(), [a, c, d])163 const mm = new StringMap([[m, m2], ["a", "b"]])164 check_equal(mm.has_key(m), true)165 check_equal(mm.has_key(m2), false)166 check_equal(mm.ref(m), m2)167})168// ==================== SVG Wrappers ====================169class Bounds {170 left = null;171 top = null;172 width = null;173 height = null;174 bottom = null;175 right = null;176 constructor(left, top, width, height){177 this.left = left178 this.top = top179 this.width = width180 this.height = height181 this.bottom = top + height182 this.right = left + width183 }184}185class SVGInfo {186 raw = null;187 bounds = null;188 base = null;189 bounds_adjuster = null;190 current_x_offset = 0;191 current_y_offset = 0;192 constructor(raw, base, bounds, bounds_adjuster = null){193 this.raw = raw194 this.base = base195 this.bounds = bounds196 this.bounds_adjuster = bounds_adjuster197 }198 // -> Bounds199 get current_bounds(){200 return new Bounds(this.bounds.left + this.current_x_offset,201 this.bounds.top + this.current_y_offset,202 this.bounds.width, this.bounds.height)203 }204 // real real -> void205 translate(x_offset, y_offset){206 this.current_x_offset += x_offset207 this.current_y_offset += y_offset208 this.raw.attr("transform",209 `translate(${this.current_x_offset}, ${this.current_y_offset})`)210 }211 set_bounds(new_bounds){212 if (!_.isNull(this.bounds_adjuster)){213 this.bounds_adjuster(this.raw, new_bounds)214 this.bounds = new_bounds215 }216 }217}218var test_svg = test(() => d3.select("#test").append("svg"))219test(() => {220 var raw = test_svg.append("rect")221 .attr("x", 0)222 .attr("y", 30)223 .attr("width", 10)224 .attr("height", 20)225 .attr("fill", "cyan")226 .style("stroke", "rgb(255, 255, 255)")227 .style("stroke-width", 2)228 var info = new SVGInfo(raw, test_svg, new Bounds(0, 30, 10, 20))229 check_equal(info.current_bounds, new Bounds(0, 30, 10, 20))230 info.translate(0, -30)231 check_equal(info.current_bounds, new Bounds(0, 0, 10, 20))232 info.translate(100, 100)233 check_equal(info.current_bounds, new Bounds(100, 100, 10, 20))234})235function rectangle(base,236 width, height,237 fill,238 stroke, stroke_width,239 pos = {x: 0, y: 0}){240 var _base = base instanceof SVGInfo ? base.raw : base241 var raw = _base.append("rect")242 .attr("x", 0)243 .attr("y", 0)244 .attr("width", width)245 .attr("height", height)246 .attr("fill", fill)247 .style("stroke", stroke)248 .style("stroke-width", stroke_width)249 var info = new SVGInfo(raw, _base, new Bounds(0, 0, width, height))250 info.translate(pos.x, pos.y)251 return info252}253test(() => {254 var r1 = rectangle(test_svg, 20, 30, "blue", "black", 2)255 check_equal(r1.current_bounds, new Bounds(0, 0, 20, 30))256 var r2 = rectangle(test_svg, 20, 30, "blue", "black", 2, {x: 0, y: 50})257 check_equal(r2.current_bounds, new Bounds(0, 50, 20, 30))258})259function label(base, str, pos = {x: 0, y: 0}){260 var _base = base instanceof SVGInfo ? base.raw : base261 var raw = _base.append("text")262 .text(str)263 .attr("x", 0)264 .attr("y", 0)265 var bbox = raw.node().getBBox()266 var bounds = new Bounds(0, 0,267 bbox.width, bbox.height)268 var info = new SVGInfo(raw, _base,269 bounds)270 // Somehow text is aligned by bottom left corner271 info.translate(pos.x, pos.y + bbox.height)272 return info273}274function label_maker(str, pos = {x: 0, y: 0}){275 return function(base){return label(base, str, pos)}276}277function container(base, width, height, type = "svg"){278 var _base = base instanceof SVGInfo ? base.raw : base279 var raw = _base.append(type)280 .attr("width", width)281 .attr("height", height)282 function adjust_bounds(raw, new_bounds){283 raw.attr("width", new_bounds.width)284 .attr("height", new_bounds.height)285 }286 var info = new SVGInfo(raw, _base, new Bounds(0, 0, width, height),287 adjust_bounds)288 return info289}290function blank(base, width, height){291 var rect = rectangle(base, width, height, "white", "white", 0)292 rect.raw.attr("visibility", "hidden")293 rect.raw.attr("id", "blank")294 return rect295}296function move_to(base, svgs){297 var _base = base instanceof SVGInfo ? base.raw : base298 for(var svg of svgs){299 var svgNode = svg.raw.node()300 var removed = svgNode.parentNode.removeChild(svgNode)301 _base.node().appendChild(removed)302 }303}304function group(base, svgs, bounds){305 var _base = base instanceof SVGInfo ? base.raw : base306 var group_container = container(base, bounds.width, bounds.height)307 move_to(group_container, svgs)308 return group_container309}310// ==================== Pict-like utilities ====================311function align_horizontal_left(svg1, svg2){312 svg2.translate(svg1.current_bounds.left - svg2.current_bounds.left, 0)313}314test(() => {315 var w = 20, w2 = 50, h = 30316 var y = 50317 var r1 = rectangle(test_svg, w, h, "blue", "black", 2)318 var r2 = rectangle(test_svg, w2, h, "blue", "black", 2, {x: 100, y: y})319 var r1_orig_bounds = r1.current_bounds320 align_horizontal_left(r1, r2)321 check_equal(r1.current_bounds, r1_orig_bounds)322 check_equal(r2.current_bounds, new Bounds(0, y, w2, h))323})324function align_vertical_top(svg1, svg2){325 svg2.translate(0, svg1.current_bounds.top - svg2.current_bounds.top)326}327test(() => {328 var w = 20, w2 = 50, h = 30329 var x = 100, y = 50330 var r1 = rectangle(test_svg, w, h, "blue", "black", 2)331 var r2 = rectangle(test_svg, w2, h, "blue", "black", 2, {x: x, y: y})332 var r1_orig_bounds = r1.current_bounds333 align_vertical_top(r1, r2)334 check_equal(r1.current_bounds, r1_orig_bounds)335 check_equal(r2.current_bounds, new Bounds(x, r1_orig_bounds.top, w2, h))336})337function bounds_center(b){338 return {x: b.left + b.width/2,339 y: b.top + b.height/2}340}341function center(svg){342 return bounds_center(svg.current_bounds)343}344function align_horizontal_center(svg1, svg2){345 align_horizontal_left(svg1, svg2)346 svg2.translate((svg1.bounds.width - svg2.bounds.width)/2, 0)347}348test(() => {349 var w = 20, w2 = 50, h = 30350 var y = 50351 var r1 = rectangle(test_svg, w, h, "blue", "black", 2)352 var r2 = rectangle(test_svg, w2, h, "blue", "black", 2, {x: 100, y: y})353 var r1_orig_bounds = r1.current_bounds354 align_horizontal_center(r1, r2)355 // r1 unchanged356 check_equal(r1.current_bounds, r1_orig_bounds)357 // r2 moved to line up with r1 horizontally358 check_equal(center(r1).x, center(r2).x)359 // r2 unchanged vertically360 check_equal(r2.current_bounds.top, y)361})362function align_vertical_center(svg1, svg2){363 align_vertical_top(svg1, svg2)364 svg2.translate(0, (svg1.bounds.height - svg2.bounds.height)/2)365}366test(() => {367 var w = 20, w2 = 50, h = 30, h2 = 50368 var x = 100, y = 50369 var r1 = rectangle(test_svg, w, h, "blue", "black", 2)370 var r2 = rectangle(test_svg, w2, h2, "blue", "black", 2, {x: x, y: y})371 var r1_orig_bounds = r1.current_bounds372 align_vertical_center(r1, r2)373 // r1 unchanged374 check_equal(r1.current_bounds, r1_orig_bounds)375 // r2 moved to line up with r1 vertically376 check_equal(center(r1).y, center(r2).y)377 // r2 unchanged horizontally378 check_equal(r2.current_bounds.left, x)379})380function _align(svgs, init_acc, f){381 var root = svgs[0]382 var root_bounds = root.current_bounds383 var top_most = root_bounds.top384 var left_most = root_bounds.left385 var right_most = root_bounds.right386 var bottom_most = root_bounds.bottom387 var acc = init_acc(root)388 for(var svg of svgs.slice(1)){389 acc = f(root, svg, acc)390 var bounds = svg.current_bounds391 var top = bounds.top392 var left = bounds.left393 var right = bounds.left + bounds.width394 var bottom = bounds.bottom395 top_most = (top < top_most) ? top : top_most396 left_most = (left < left_most) ? left : left_most397 right_most = (right > right_most) ? right : right_most398 bottom_most = (bottom > bottom_most) ? bottom : bottom_most399 }400 var width = right_most - left_most401 var height = bottom_most - top_most402 return new Bounds(left_most, top_most, width, height)403}404function v_appender(align_horizontal){405 return function (...svgs){406 return _align(svgs,407 (root) => {408 return root.current_bounds.bottom409 },410 (root, svg, bottom_so_far) => {411 align_horizontal(root, svg)412 svg.translate(0, bottom_so_far - svg.current_bounds.top)413 return svg.current_bounds.bottom414 })415 }416}417var vc_append = v_appender(align_horizontal_center)418var vl_append = v_appender(align_horizontal_left)419var vr_append = v_appender((svg1, svg2) => {420 align_horizontal_left(svg1, svg2)421 svg2.translate(svg1.current_bounds.width, 0)422})423test(() => {424 var w = 20, w2 = 50, h = 30, h2 = 50, y_pos = 50425 var r1 = rectangle(test_svg, w, h, "blue", "black", 2)426 var r2 = rectangle(test_svg, w2, h, "blue", "black", 2, {x: 100, y: y_pos})427 var r3 = rectangle(test_svg, w2, h2, "blue", "black", 2, {x: 10, y: y_pos+20})428 var r1_orig_bounds = r1.current_bounds429 var total_bounds = vc_append(r1, r2, r3)430 check_equal(r1.current_bounds, r1_orig_bounds)431 check_equal(center(r1).x, center(r2).x)432 check_equal(center(r2).x, center(r3).x)433 check_equal(r1.current_bounds.bottom, r2.current_bounds.top)434 check_equal(r2.current_bounds.bottom, r3.current_bounds.top)435 check_equal(total_bounds,436 new Bounds(r1_orig_bounds.left - (w2 - w)/2,437 r1_orig_bounds.top,438 w2,439 h*2+h2))440})441function cc_align(...svgs){442 return _align(svgs,443 (_) => {},444 (root, svg, _) => {445 align_horizontal_center(root, svg)446 align_vertical_center(root, svg)447 })448}449test(() => {450 var w = 20, w2 = 50, h = 30, h2 = 50, y_pos = 50451 var r1 = rectangle(test_svg, w, h, "blue", "black", 2)452 var r2 = rectangle(test_svg, w2, h, "blue", "black", 2, {x: 100, y: y_pos})453 var r3 = rectangle(test_svg, w2, h2, "blue", "black", 2, {x: 10, y: y_pos+20})454 var r1_orig_bounds = r1.current_bounds455 var total_bounds = cc_align(r1, r2, r3)456 check_equal(r1.current_bounds, r1_orig_bounds)457 check_equal(center(r1), center(r2))458 check_equal(center(r2), center(r3))459 check_equal(total_bounds,460 new Bounds(r1_orig_bounds.left - (w2 - w)/2,461 r1_orig_bounds.top - (h2 - h)/2,462 w2,463 h2))464})465function h_appender(align_vertical){466 return function (...svgs){467 return _align(svgs,468 (root) => {return root.current_bounds.right},469 (root, svg, right_most) => {470 align_vertical(root, svg)471 align_horizontal_left(root, svg)472 svg.translate(right_most, 0)473 return svg.current_bounds.right474 })475 }476}477var hc_append = h_appender(align_vertical_center)478var ht_append = h_appender(align_vertical_top)479var hb_append = h_appender((svg1, svg2) => {480 align_vertical_top(svg1, svg2)481 svg2.translate(0, svg1.current_bounds.height)482})483test(() => {484 var w = 20, w2 = 50, h = 30, h2 = 50, y_pos = 50485 var r1 = rectangle(test_svg, w, h, "blue", "black", 2)486 var r2 = rectangle(test_svg, w2, h, "blue", "black", 2, {x: 100, y: y_pos})487 var r3 = rectangle(test_svg, w2, h2, "blue", "black", 2, {x: 10, y: y_pos+20})488 var r1_orig_bounds = r1.current_bounds489 var total_bounds = hc_append(r1, r2, r3)490 check_equal(r1.current_bounds, r1_orig_bounds)491 check_equal(center(r1).y, center(r2).y)492 check_equal(center(r2).y, center(r3).y)493 check_equal(r1.current_bounds.right, r2.current_bounds.left)494 check_equal(r2.current_bounds.right, r3.current_bounds.left)495 check_equal(total_bounds,496 new Bounds(r1_orig_bounds.left,497 r1_orig_bounds.top - (h2 - h)/2,498 w+2*w2,499 h2))500})501function ghost(base, bounds){502 var g = blank(base, bounds.width, bounds.height)503 g.raw.attr("id", "ghost")504 g.translate(bounds.left, bounds.top)505 return g506}507// ===== Simple and dumb lattice interaction implementation =====508function config(primes_level, sift_level, sieve_level){509 return new StringMap([510 ["primes", primes_level],511 ["sift", sift_level],512 ["sieve", sieve_level]513 ])514}515// The lattice is an opaque image, so this hack is the easiest way to align516// things.517//518// A more robust alternative would be to read the SVG as XML and determine the519// locations and bounding information using the color information in520// `../figure-gen/colors.rkt` as the key to link the config SVGs (as color521// triples) to their representation as mappings from component to contract522// level.523// No time for that, though! ¯\_(ツ)_/¯524const y0 = "92.5%",525 y1 = "78%",526 y2 = "63.65%",527 y3 = "49.3%",528 y4 = "35%",529 y5 = "20.8%",530 y6 = "6.5%"531const config_positions = new StringMap([532 [config("none", "none", "none"), {x: "45%", y: y0}],533 [config("primes-types", "none", "none"), {x: "32%", y: y1}],534 [config("none", "sift-types", "none"), {x: "45%", y: y1}],535 [config("none", "none", "sieve-types"), {x: "58.1%", y: y1}],536 [config("primes-types", "sift-types", "none"), {x: "12.5%", y: y2}],537 [config("none", "sift-max", "none"), {x: "25.55%", y: y2}],538 [config("none", "sift-types", "sieve-types"), {x: "38.5%", y: y2}],539 [config("primes-types", "none", "sieve-types"), {x: "51.5%", y: y2}],540 [config("none", "none", "sieve-max"), {x: "64.3%", y: y2}],541 [config("primes-max", "none", "none"), {x: "77.5%", y: y2}],542 [config("primes-types", "sift-types", "sieve-types"), {x: "6%", y: y3}],543 [config("none", "sift-max", "sieve-types"), {x: "19%", y: y3}],544 [config("none", "sift-types", "sieve-max"), {x: "32%", y: y3}],545 [config("primes-types", "sift-max", "none"), {x: "45%", y: y3}],546 [config("primes-max", "sift-types", "none"), {x: "58%", y: y3}],547 [config("primes-max", "none", "sieve-types"), {x: "71%", y: y3}],548 [config("primes-types", "none", "sieve-max"), {x: "84%", y: y3}],549 [config("primes-max", "sift-max", "none"), {x: "12.5%", y: y4}],550 [config("primes-max", "sift-types", "sieve-types"), {x: "25.5%", y: y4}],551 [config("primes-types", "sift-types", "sieve-max"), {x: "38.5%", y: y4}],552 [config("none", "sift-max", "sieve-max"), {x: "51.5%", y: y4}],553 [config("primes-types", "sift-max", "sieve-types"), {x: "64.5%", y: y4}],554 [config("primes-max", "none", "sieve-max"), {x: "77.4%", y: y4}],555 [config("primes-max", "sift-types", "sieve-max"), {x: "32.1%", y: y5}],556 [config("primes-max", "sift-max", "sieve-types"), {x: "45%", y: y5}],557 [config("primes-types", "sift-max", "sieve-max"), {x: "58%", y: y5}],558 [config("primes-max", "sift-max", "sieve-max"), {x: "45%", y: y6}],559])560const config_height = 38561function config_size(config){562 return {width: 50, height: config_height}563 // ===== Dead code for sizing with textual configs =====564 // if (config.ref("primes").endsWith("types")) {565 // return {width: 70, height: config_height}566 // } else if ( config.ref("primes").endsWith("max")567 // || config.ref("sieve") .endsWith("types")) {568 // return {width: 67, height: config_height}569 // } else if (config.ref("sieve").endsWith("max")) {570 // return {width: 63, height: config_height}571 // } else if (config.ref("sift").endsWith("types")) {572 // return {width: 61, height: config_height}573 // } else if (config.ref("sift").endsWith("max")) {574 // return {width: 58, height: config_height}575 // } else {576 // return {width: 50, height: config_height}577 // }578}579var current_highlight = null580function highlight_config_in_lattice(base, config,581 replace = true,582 color = "red"){583 if (replace && current_highlight !== null) {584 remove_config_highlight(current_highlight)585 }586 const size = config_size(config)587 const pos = config_positions.ref(config)588 let rect = rectangle(base,589 size.width, size.height,590 "none",591 color,592 2)593 rect.raw.attr("x", pos.x)594 .attr("y", pos.y)595 if (replace) {596 current_highlight = rect597 }598 return rect599}600function remove_config_highlight(h){601 h.raw.remove()602}603function config_to_string(config){604 c = {}605 for(const id of ["primes", "sift", "sieve"]){606 c[id] = config.ref(id)607 }608 return JSON.stringify(c, null, 4)609}610var lattice_svg = d3.select("#lattice svg")611var current_selection = []612function select_config(config){613 for(let circle of current_selection){614 circle.attr("fill", "white")615 }616 current_selection = []617 for(const id of config.keys()){618 var id_circle = d3.select("#" + id).select("#" + config.ref(id))619 .select("circle")620 id_circle.attr("fill", "red")621 current_selection.push(id_circle)622 }623 show_run_result(config)624 console.log("selected:", config_to_string(config))625 extend_current_trail(config)626 // Highlight current config last in case it's a repeat of one in the trail627 // (so the red shows over the orange)628 highlight_config_in_lattice(lattice_svg, config)629}630var current_config = config("none", "none", "none")631function select_level(id, level){632 current_config = current_config.set(id, level)633 select_config(current_config)634}635function get_current_config(){636 return current_config637}638var result_div = d3.select("#run-result")639var blame_primes = {elt: d3.select("#run-result").select("#blame-primes"), id: "primes"}640blame_primes.elt.remove()641var blame_sift = {elt: d3.select("#run-result").select("#blame-sift"), id: "sift"}642blame_sift.elt.remove()643var blame_sieve = {elt: d3.select("#run-result").select("#blame-sieve"), id: "sieve"}644blame_sieve.elt.remove()645const config_blames = new StringMap([646 [config("none", "none", "none"), blame_primes],647 [config("primes-types", "none", "none"), blame_primes],648 [config("none", "sift-types", "none"), blame_primes],649 [config("none", "none", "sieve-types"), blame_primes],650 [config("primes-max", "none", "none"), blame_sieve],651 [config("primes-types", "sift-types", "none"), blame_primes],652 [config("primes-types", "none", "sieve-types"), blame_primes],653 [config("none", "sift-max", "none"), blame_sift],654 [config("none", "sift-types", "sieve-types"), blame_primes],655 [config("none", "none", "sieve-max"), blame_sift],656 [config("primes-types", "sift-max", "none"), blame_sift],657 [config("none", "sift-max", "sieve-types"), blame_sift],658 [config("primes-types", "none", "sieve-max"), blame_sift],659 [config("none", "sift-types", "sieve-max"), blame_sift],660 [config("primes-types", "sift-types", "sieve-types"), blame_primes],661 [config("primes-max", "sift-types", "none"), blame_sieve],662 [config("primes-max", "none", "sieve-types"), blame_sieve],663 [config("primes-max", "none", "sieve-max"), blame_sift],664 [config("primes-types", "sift-types", "sieve-max"), blame_sift],665 [config("primes-max", "sift-max", "none"), blame_sift],666 [config("primes-max", "sift-types", "sieve-types"), blame_sieve],667 [config("primes-types", "sift-max", "sieve-types"), blame_sift],668 [config("none", "sift-max", "sieve-max"), blame_sift],669 [config("primes-max", "sift-max", "sieve-types"), blame_sift],670 [config("primes-types", "sift-max", "sieve-max"), blame_sift],671 [config("primes-max", "sift-types", "sieve-max"), blame_sift],672 [config("primes-max", "sift-max", "sieve-max"), blame_sift],673])674var current_blame = blame_primes675function show_run_result(config){676 current_blame.elt.remove()677 var new_blame = config_blames.ref(config)678 var new_blame_node = new_blame.elt.node()679 result_div.node().appendChild(new_blame_node)680 current_blame = new_blame681}682var current_trail = []683function extend_current_trail(config){684 if (current_trail.length === 0685 || !_.isEqual(current_trail[current_trail.length - 1], config)){686 current_trail.push(config)687 show_current_trail_stats()688 highlight_trail_history(current_trail)689 }690}691function reset_trail_tracking(){692 current_trail = []693 show_current_trail_stats()694 remove_current_trail_history_highlighting()695}696var stats_div = d3.select("#lattice").select("#trail-stats")697function show_current_trail_stats(){698 stats_div.html("")699 const is_valid = is_valid_trail(current_trail)700 const current_config = get_current_config()701 const blamed = config_blames.ref(current_config)702 const satisfies_blame_trail = ((blamed.id === blame_sift.id)703 && current_config.ref("sift") === "sift-max")704 var c = container(stats_div, 250, 70)705 var l1 = label(c, `Trail length: ${current_trail.length}`)706 var l2 = label(c, `Valid trail: ${is_valid}`)707 l2.raw.attr("style", `fill:${is_valid ? "green" : "red"}`)708 var l3 = label(c, `Satisfies Blame Trail: ${satisfies_blame_trail}`)709 l3.raw.attr("style", `fill:${satisfies_blame_trail ? "green" : "red"}`)710 vl_append(l1, l2, l3)711}712function is_valid_trail(config_list){713 if (config_list.length < 2){714 return true715 } else {716 const current_config = config_list[0]717 const next_config = config_list[1]718 function ctc_level_changed(id){719 return (current_config.ref(id) !== next_config.ref(id))720 }721 function ctc_level_incremented(id){722 const current_level = current_config.ref(id)723 const next_level = next_config.ref(id)724 if (current_level.endsWith("none")){725 return next_level.endsWith("types")726 } else if (current_level.endsWith("types")){727 return next_level.endsWith("max")728 } else {729 return false730 }731 }732 const blamed_id = config_blames.ref(current_config).id733 const not_blamed_ids = _.filter(["primes", "sift", "sieve"],734 (id) => (id !== blamed_id))735 if (!ctc_level_changed(blamed_id) || !ctc_level_incremented(blamed_id)){736 console.log(`blamed_id ${blamed_id} didn't change (to the right) level!`)737 return false738 }739 for(const other_id of not_blamed_ids){740 if (ctc_level_changed(other_id)){741 console.log(`other_id ${other_id} changed level!`)742 return false743 }744 }745 const remaining_configs = config_list.slice(1)746 return is_valid_trail(remaining_configs)747 }748}749var current_trail_highlights = []750function highlight_trail_history(trail){751 if (trail.length < 2) {752 return753 }754 remove_current_trail_history_highlighting()755 for(const config of trail.slice(0, -1)){756 const highlight = highlight_config_in_lattice(lattice_svg,757 config,758 false,759 "orange")760 current_trail_highlights.push(highlight)761 }762}763function remove_current_trail_history_highlighting(){764 for(let highlight of current_trail_highlights){765 remove_config_highlight(highlight)766 }767 current_trail_highlights = []768}769// var h1 = highlight_config_in_lattice(lattice_svg, config("primes-max", "sift-max", "sieve-max"))770// remove_config_highlight(h1)771// var h2 = highlight_config_in_lattice(lattice_svg, config("none", "sift-max", "sieve-max"))772// var s = d3.select("#sift").select("#none").select("circle")773// console.log(s)774// s.attr("fill", "red")775reset_trail_tracking()776select_config(current_config)777// select_config(config("none", "sift-max", "sieve-types"))778// const scale = 22779// var hello_svg = d3.select("#hello-world svg")780// hello_svg.append("circle")781// .attr("cx", 20)782// .attr("cy", 50)783// .attr("r", 10)784// .attr("fill", "black")785// hello_svg.append("circle")786// .attr("cx", 50)787// .attr("cy", 20)788// .attr("r", 10)789// .attr("fill", "black")790// hello_svg.append("line")791// .attr("x1", function(d){return 20})792// .attr("y1", function(d){return 50})793// .attr("x2", function(d){return 50})794// .attr("y2", function(d){return 20})795// // .attr("style", "stroke:rgb(255,0,0);stroke-width:2");796// .style("stroke", "rgb(255,0,0)")797// .style("stroke-width", 2)798// var text = hello_svg.append("text")799// .text("Hello world!")800// .attr("x", 100)801// .attr("y", 100)802// .on("click", onClick)803// // .call(d3.click().on('click', onClick))804// function onClick(){805// console.log("Clicked!")806// text.attr("x", +text.attr("x") + 20)807// }808// var lattice_svg = d3.select("#lattice svg")809// lattice_svg.append("image")810// .attr("href", "./lattice.svg")811// .attr("x", 0)812// .attr("y", 0)813// .attr("width", "100%")814// .attr("height", "100%")815// var l1 = label_maker("foo")(hello_svg)816// console.log(l1.current_bounds)817// console.log("---")818// l1.translate(100, 0)819// console.log(l1.current_bounds)820// var l2 = label_maker("bar")(hello_svg)821// l2.translate(0, 20)822// var l3 = label_maker("bamboozle!")(hello_svg)823// l3.translate(0, 40)824// l3.translate(200, 0)825// console.log(l1.current_bounds)826// console.log(l2.current_bounds)827// console.log(l3.current_bounds)828// vc_align(l1, l2, l3)829// console.log(l1.current_bounds)830// console.log(l2.current_bounds)831// console.log(l3.current_bounds)832// var texts = vc_append(hello_svg, [label_maker("foo"),833// label_maker("bar"),834// label_maker("bamboozle!")])835// var some_g = hello_svg.append("g")836// var config_1 = configuration_svg(hello_svg, {"a": "max", "b": "types", "c": "none"})837// config_1.translate(100, 20)838// var config_2 = configuration_svg(hello_svg, {"a": "max", "b": "max", "c": "none"})839// var config_3 = configuration_svg(hello_svg, {"a": "max", "b": "max", "c": "none"})840// // config_2.translate(300, 20)841// // config_3.translate(200, 200)842// var bounds = hc_append(config_1, blank(hello_svg, -150, 1), config_2)843// vc_append(ghost(hello_svg, bounds), blank(hello_svg, 1, 50), config_3)844// // lltodo: have an hc_align, and an hc_append845// // hc_align does what append does now: just translates the images846// // hc_append translates the images then moves them onto a new sub-svg847// configuration_link_svg(hello_svg, config_3.current_bounds, config_2.current_bounds)848// configuration_link_svg(hello_svg, config_3.current_bounds, config_1.current_bounds)849// move_to(some_g, [config_1])850// some_g.attr("transform", "translate(0, 200)")851// var v1 = hello_svg.append("circle").attr("r", 5).attr("fill", "red").attr("cx", 5).attr("cy", 5)852// var make_v2 = function(base) {return base.append("circle").attr("r", 2.5).attr("fill", "green").attr("cx", 0).attr("cy", 0)}853// cc_superimpose(hello_svg, v1, make_v2)854/*855var margin = {top: 20, right: 20, bottom: 20, left: 20},856 width = +400- margin.left - margin.right,857 height = +400 - margin.top - margin.bottom858var svg = d3.select("svg")859 .append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");860// add your code here861var dataset = [[5, 20], [480, 90], [250, 50], [100, 33], [330, 95], [410, 12], [475, 44], [25, 67], [85, 21], [220, 88]];862var scale = d3.scaleLinear()863 .domain([100, 500])864 .range([10, 350]);865function make_accessor(index){866 return function(pair){return pair[index];}867}868var first = make_accessor(0);869var second = make_accessor(1);870var x_max = d3.max(dataset, first);871var y_max = d3.max(dataset, second);872var x_min = d3.min(dataset, first);873var y_min = d3.min(dataset, second);874var scale_offset = 5;875// Determine the ratio of each dimension (x and y) against the larger of the two876var scales_multiplier = (x_max > y_max) ? [1, y_max/x_max] : [x_max/y_max, 1];877var x_ratio = scales_multiplier[0]878var y_ratio = scales_multiplier[1]879var xScale = d3.scaleLinear()880 .domain([0, x_max])881 .range([0, 400*x_ratio]); // Use the ratio of x to the larger dimension to scale x within 400882var yScale = d3.scaleLinear()883 .domain([0, y_max])884 .range([400*y_ratio, 0]); // Use the ratio of y to the larger dimension to scale y within 400885var position_x = function(d) { return xScale(d[0]); }886var position_y = function(d) { return yScale(d[1]); }887svg.selectAll("circle")888 .data(dataset)889 .enter().append("circle")890 .attr("cx", position_x)891 .attr("cy", position_y)892 .attr("r", 5);893var xAxis = d3.axisBottom().scale(xScale);894svg.append("g").call(xAxis)895 .attr("transform", "translate(0," + (y_max) + ")");896var yAxis = d3.axisLeft().scale(yScale);897svg.append("g").call(yAxis)898 .attr("transform", "translate(0,"+ scale_offset + ")");899// reset everything to color=black, radius=3900circles = svg.selectAll("circle")901 .data(dataset)902 .attr("fill","black")903 .attr("r",3);904// transition to magenta with a radius of 6 over 1 seconds905transition1 = circles.transition()906 .duration(1000)907 .attr("fill","magenta")908 .attr("r", 6)909 .attr("cx", function(){return position_x([Math.random()*x_max, 0])})910 .attr("cy", function(){return position_y([0, Math.random()*y_max])});911// transition to black with a radius of 3 after a delay of 1 seconds912transition2 = transition1.transition()913 .delay(1000)914 .duration(3000) // last step takes 3s915 .attr("fill", "black")916 .attr("r", 3);...

Full Screen

Full Screen

svgo.test.js

Source:svgo.test.js Github

copy

Full Screen

1'use strict';2const svgo = require('svgo');3const svgoTransform = require('../../../lib/svg-sprite/transform/svgo.js');4const TEST_SVG = '<svg></svg>';5jest.mock('svgo');6describe('testing transforms.svgo', () => {7 let noop;8 beforeEach(() => {9 noop = jest.fn();10 });11 it('should set default config with expected params if not provided 1', () => {12 expect.hasAssertions();13 const spriter = {14 config: {15 svg: {16 xmlDeclaration: false,17 doctypeDeclaration: false18 }19 },20 error: jest.fn()21 };22 const shape = {23 setSVG: jest.fn(),24 getSVG: jest.fn().mockReturnValue(TEST_SVG)25 };26 const TEST_RESULT = 'test result';27 jest.spyOn(svgo, 'optimize').mockReturnValueOnce(TEST_RESULT);28 svgoTransform(shape, {}, spriter, noop);29 expect(svgo.optimize).toHaveBeenCalledWith(TEST_SVG, { plugins: ['preset-default', {30 active: true,31 name: 'removeXMLProcInst'32 }, {33 active: true,34 name: 'removeDoctype'35 }] });36 });37 it('should set default config with expected params if not provided 2', () => {38 expect.hasAssertions();39 const spriter = {40 config: {41 svg: {42 xmlDeclaration: true,43 doctypeDeclaration: true44 }45 },46 error: jest.fn()47 };48 const shape = {49 setSVG: jest.fn(),50 getSVG: jest.fn().mockReturnValue(TEST_SVG)51 };52 const TEST_RESULT = 'test result';53 jest.spyOn(svgo, 'optimize').mockReturnValueOnce(TEST_RESULT);54 svgoTransform(shape, {}, spriter, noop);55 expect(svgo.optimize).toHaveBeenCalledWith(TEST_SVG, { plugins: ['preset-default', {56 active: false,57 name: 'removeXMLProcInst'58 }, {59 active: false,60 name: 'removeDoctype'61 }] });62 });63 it('should add provided config', () => {64 expect.hasAssertions();65 const TEST_PLUGINS = [{66 name: 'preset-default',67 params: {68 overrides: {69 removeTitle: false,70 removeDesc: false71 }72 }73 }];74 const spriter = {75 config: {76 svg: {77 xmlDeclaration: true,78 doctypeDeclaration: true79 }80 },81 error: jest.fn()82 };83 const shape = {84 setSVG: jest.fn(),85 getSVG: jest.fn().mockReturnValue(TEST_SVG)86 };87 const TEST_RESULT = 'test result';88 jest.spyOn(svgo, 'optimize').mockReturnValueOnce(TEST_RESULT);89 svgoTransform(shape, { plugins: TEST_PLUGINS }, spriter, noop);90 expect(svgo.optimize).toHaveBeenCalledWith(TEST_SVG, { plugins: expect.arrayContaining(TEST_PLUGINS) });91 });92 it('should log about optimizations', () => {93 expect.hasAssertions();94 const MOCKED_ORIGINAL_SVG = 'svgsvg';95 const MOCKED_OPTIMIZED_SVG = 'svg';96 const spriter = {97 config: {98 svg: {},99 log: {100 transports: [{101 level: 'debug'102 }, {103 level: 'debug'104 }]105 }106 },107 error: jest.fn(),108 debug: jest.fn()109 };110 const shape = {111 name: 'name',112 setSVG: jest.fn(),113 getSVG: jest.fn().mockReturnValueOnce(MOCKED_ORIGINAL_SVG).mockReturnValueOnce(MOCKED_OPTIMIZED_SVG)114 };115 jest.spyOn(svgo, 'optimize').mockReturnValueOnce({});116 svgoTransform(shape, {}, spriter, noop);117 expect(spriter.debug).toHaveBeenCalledTimes(2);118 expect(spriter.debug).toHaveBeenCalledWith('Optimized "%s" with SVGO (saved %s / %s%%)', 'name', '3 Bytes', 50);119 });120 it('should not log about optimizations', () => {121 expect.hasAssertions();122 const spriter = {123 config: {124 svg: {},125 log: {126 transports: [{127 level: 'info'128 }]129 }130 },131 error: jest.fn(),132 debug: jest.fn()133 };134 const shape = {135 name: 'name',136 setSVG: jest.fn(),137 getSVG: jest.fn().mockReturnValue(TEST_SVG)138 };139 jest.spyOn(svgo, 'optimize').mockReturnValueOnce({});140 svgoTransform(shape, {}, spriter, noop);141 expect(spriter.debug).not.toHaveBeenCalled();142 });143 it('should call callback', () => {144 expect.hasAssertions();145 const spriter = {146 config: {147 svg: {},148 log: {149 transports: []150 }151 },152 error: jest.fn(),153 debug: jest.fn()154 };155 const shape = {156 name: 'name',157 setSVG: jest.fn(),158 getSVG: jest.fn().mockReturnValue(TEST_SVG)159 };160 jest.spyOn(svgo, 'optimize').mockReturnValueOnce({});161 svgoTransform(shape, {}, spriter, noop);162 expect(noop).toHaveBeenCalledWith(null);163 });164 it('should call callback with error and call spriter.error if error raised', () => {165 expect.hasAssertions();166 const TEST_ERROR = new Error('test');167 const spriter = {168 config: {169 svg: {}170 },171 error: jest.fn(),172 debug: jest.fn()173 };174 const shape = {175 name: 'name',176 setSVG: jest.fn(),177 getSVG: jest.fn().mockReturnValue(TEST_SVG)178 };179 jest.spyOn(svgo, 'optimize').mockImplementationOnce(() => {180 throw TEST_ERROR;181 });182 svgoTransform(shape, {}, spriter, noop);183 expect(noop).toHaveBeenCalledWith(TEST_ERROR);184 expect(spriter.error).toHaveBeenCalledWith('Optimizing "%s" with SVGO failed with error "%s"', 'name', TEST_ERROR);185 });...

Full Screen

Full Screen

spriter.test.js

Source:spriter.test.js Github

copy

Full Screen

1'use strict';2/* eslint-disable max-nested-callbacks, jest/prefer-expect-assertions */3const fs = require('fs');4const path = require('path');5const { Buffer } = require('buffer');6const File = require('vinyl');7const SVGSpriter = require('../lib/svg-sprite.js');8const TEST_SVG = 'fixture/svg/single/weather-clear.svg';9const TEST_EMPTY_SVG = '<svg></svg>';10describe('testing SVGSpriter', () => {11 let spriter;12 beforeEach(() => {13 spriter = new SVGSpriter({14 shape: {15 dest: 'svg'16 }17 });18 });19 describe('testing add()', () => {20 describe('testing adding vinyl file', () => {21 it('should transform file.base of Vinyl file with path.resolve and add to _queue as vinyl file', () => {22 const TEST_FILE = new File({23 base: path.dirname(TEST_SVG),24 path: TEST_SVG,25 contents: fs.readFileSync(path.join(__dirname, TEST_SVG))26 });27 spriter._queue = {28 add: jest.fn()29 };30 spriter.add(TEST_FILE);31 expect(TEST_FILE.base).toStrictEqual(path.resolve(TEST_FILE.base));32 expect(spriter._queue.add).toHaveBeenCalledWith(TEST_FILE);33 });34 });35 describe('testing adding non-vinyl file', () => {36 it('should raise an error when passing name with an absolute path', () => {37 expect(() => {38 spriter.add(TEST_SVG, path.resolve(TEST_SVG), TEST_EMPTY_SVG);39 }).toThrow(Error);40 });41 it('should raise an error when passing less than 3 arguments', () => {42 expect(() => {43 spriter.add(TEST_SVG);44 }).toThrow(Error);45 expect(() => {46 spriter.add(TEST_SVG, null);47 }).toThrow(Error);48 });49 it('should throw an error if passed file arg is empty', () => {50 expect(() => {51 spriter.add('', null, TEST_EMPTY_SVG);52 }).toThrow(Error);53 });54 it('should throw an error if passed name arg is empty and file path is not valid', () => {55 expect(() => {56 spriter.add(' ', '../', TEST_EMPTY_SVG);57 }).toThrow(Error);58 });59 it('should throw an error if passed svg arg is empty', () => {60 expect(() => {61 spriter.add(TEST_SVG, null, '');62 }).toThrow(Error);63 expect(() => {64 spriter.add(TEST_SVG, null, ' ');65 }).toThrow(Error);66 });67 it('should throw an error if passed name differs from the ending of passed file path', () => {68 expect(() => {69 spriter.add(TEST_SVG, 'absolutely-random-string', TEST_EMPTY_SVG);70 }).toThrow(Error);71 });72 it('should create vinyl file from passed relative file and add it to _queue', () => {73 spriter._queue = {74 add: jest.fn()75 };76 spriter.add(TEST_SVG, 'weather-clear.svg', TEST_EMPTY_SVG);77 expect(spriter._queue.add).toHaveBeenCalledWith(new File({78 base: path.dirname(path.resolve(TEST_SVG)),79 path: path.resolve(TEST_SVG),80 contents: Buffer.from(TEST_EMPTY_SVG)81 }));82 });83 it('should create vinyl file from passed absolute file and add it to _queue', () => {84 spriter._queue = {85 add: jest.fn()86 };87 spriter.add(path.resolve(TEST_SVG), 'weather-clear.svg', TEST_EMPTY_SVG);88 expect(spriter._queue.add).toHaveBeenCalledWith(new File({89 base: path.dirname(path.resolve(TEST_SVG)),90 path: path.resolve(TEST_SVG),91 contents: Buffer.from(TEST_EMPTY_SVG)92 }));93 });94 });95 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var client = wpt('www.webpagetest.org');3 if (err) return console.error(err);4 console.log(data);5});6var wpt = require('webpagetest');7var client = wpt('www.webpagetest.org');8 if (err) return console.error(err);9 console.log(data);10});11var wpt = require('webpagetest');12var client = wpt('www.webpagetest.org');13 if (err) return console.error(err);14 console.log(data);15});16var wpt = require('webpagetest');17var client = wpt('www.webpagetest.org');18 if (err) return console.error(err);19 console.log(data);20});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3 if(err) return console.log(err);4 console.log(data);5});6wpt.test(url, options, callback)7wpt.test_run(url, options, callback)8wpt.test_status(testId, callback)9wpt.test_results(testId, callback)10wpt.get_locations(callback)11wpt.get_location(location, callback)12wpt.get_testers(location, callback)13wpt.test_svg(url, options, callback)14wpt.get_history(url, callback)15wpt.get_page_speed(url, callback)16wpt.get_browsertime(url, callback)17wpt.get_video(testId, callback)18wpt.get_request(testId, callback)19wpt.get_requests(testId, callback)20wpt.get_pagespeed(testId, callback)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2 if (err) {3 console.log(err);4 } else {5 console.log(response);6 }7});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt 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