Best JavaScript code snippet using playwright-internal
script.js
Source:script.js
...47}48function toXY(e) {49 return [e.screenX, e.screenY];50}51function toModifiers(e) {52 return { alt: e.altKey, ctrl: e.ctrlKey, meta: e.metaKey, shift: e.shiftKey };53}54function isOutside(value, min, max, tolerance) {55 return value + tolerance < 0 || value - tolerance > max;56}57function cloneTransform(obj) {58 return {59 translation: obj.translation.slice(),60 scale: obj.scale.slice(),61 };62}63function clamp(value, min, max) {64 if (value < min) {65 return min;66 }67 if (value > max) {68 return max;69 }70 return value;71}72export default {73 name: 'VtkPiecewiseEditor',74 components: {75 Gaussian,76 },77 props: {78 // points/gaussians79 value: {80 type: Object,81 default() {82 return {83 points: [0, 0, 1, 1],84 gaussians: [],85 };86 },87 },88 // Prevent from over zooming89 maxZoom: {90 type: [String, Number],91 default: 5,92 },93 // side control size94 padding: {95 type: [String, Number],96 default: 20,97 },98 // ui styles99 contentRectangleStyle: {100 type: Object,101 default: () => ({102 stroke: 'black',103 'stroke-width': '1',104 fill: 'white',105 }),106 },107 resultOpacityLineStyle: {108 type: Object,109 default: () => ({110 stroke: '#1565C0',111 'stroke-width': 3,112 fill: 'none',113 }),114 },115 insideZoomStyle: {116 type: Object,117 default: () => ({118 stroke: 'none',119 fill: '#666',120 opacity: 0.1,121 }),122 },123 gaussianOpacityStyle: {124 type: Object,125 default: () => ({126 lineOpacity: 0.1,127 controlSize: 10,128 boundsStyle: {129 stroke: 'none',130 fill: 'white',131 opacity: 0.25,132 },133 widthControlStyle: {134 stroke: 'red',135 'stroke-width': 2,136 fill: 'white',137 },138 heightControlStyle: {139 stroke: 'red',140 'stroke-width': 2,141 fill: 'white',142 },143 biasLineStyle: {144 stroke: '#1565C0',145 'stroke-width': 2,146 opacity: 0.5,147 },148 gaussianStyle: {149 fill: 'none',150 stroke: 'black',151 'stroke-width': 1,152 },153 }),154 },155 activeGaussianOpacityStyle: {156 type: Object,157 default: () => ({158 lineOpacity: 1,159 controlSize: 10,160 boundsStyle: {161 stroke: 'none',162 fill: 'white',163 opacity: 0.25,164 },165 widthControlStyle: {166 stroke: 'red',167 'stroke-width': 2,168 fill: 'white',169 },170 heightControlStyle: {171 stroke: 'red',172 'stroke-width': 2,173 fill: 'white',174 },175 biasLineStyle: {176 stroke: '#1565C0',177 'stroke-width': 2,178 opacity: 0.5,179 },180 gaussianStyle: {181 fill: 'none',182 stroke: '#1565C0',183 'stroke-width': 3,184 },185 }),186 },187 activeLinearOpacityStyle: {188 type: Object,189 default: () => ({190 stroke: '#1565C0',191 opacity: 1,192 'stroke-width': 3,193 fill: 'none',194 }),195 },196 linearOpacityStyle: {197 type: Object,198 default: () => ({199 stroke: 'black',200 opacity: 0.1,201 'stroke-width': 2,202 fill: 'none',203 }),204 },205 linearOpacityControlStyle: {206 type: Object,207 default: () => ({208 stroke: '#1565C0',209 'stroke-width': 2,210 fill: 'white',211 r: 5,212 }),213 },214 activeLinearOpacityControlStyle: {215 type: Object,216 default: () => ({217 stroke: 'red',218 'stroke-width': 2,219 fill: 'white',220 r: 5,221 }),222 },223 zoomControlStyle: {224 type: Object,225 default: () => ({226 stroke: 'black',227 'stroke-width': 1,228 fill: '#BBDEFB',229 }),230 },231 },232 data() {233 return {234 // view setup235 view: {236 begin: [0, 1],237 end: [1, 0],238 size: [200, 100], // width, height239 },240 // zoom transform capturing x/y | translation/scale241 zoomTransform: {242 translation: [0, 0],243 scale: [1, 1],244 },245 // Handle drag action246 dragStart: null,247 dragMousePosition: [0, 0],248 selectedPoints: [],249 hoverPolyline: false,250 activeGaussian: -1,251 };252 },253 watch: {254 padding() {255 this.updateViewSize();256 },257 height() {258 this.updateViewSize();259 },260 value() {261 this.$emit('opacities', this.transferFunction);262 },263 },264 computed: {265 points: {266 get() {267 return this.value?.points;268 },269 set(v) {270 this.$emit('input', {271 gaussians: this.gaussians,272 points: v,273 });274 },275 },276 gaussians: {277 get() {278 return this.value?.gaussians;279 },280 set(v) {281 this.$emit('input', {282 gaussians: v,283 points: this.points,284 });285 },286 },287 windowGaussianPositions() {288 const toViewX = (x) =>289 applyTransform(this.view, this.zoomTransform, x, 0)[0];290 return this.gaussians.map((g, idx) => ({ x: toViewX(g.position), idx }));291 },292 zoomWindow() {293 const [x, y] = this.zoomTransform.translation;294 const width = this.view.size[0] / this.zoomTransform.scale[0];295 const height = this.view.size[1] / this.zoomTransform.scale[1];296 return { x, y, width, height };297 },298 containerStyle() {299 return {300 width: '100%',301 height: '100%',302 boxSizing: 'border-box',303 };304 },305 svgStyle() {306 return {307 width: '100%',308 height: '100%',309 boxSizing: 'border-box',310 };311 },312 viewBox() {313 return `${-this.padding} ${-this.padding} ${314 this.view.size[0] + 2 * this.padding315 } ${this.view.size[1] + 2 * this.padding}`;316 },317 polylinePoints() {318 return this.controlPoints.map(CTRL_POINT_TO_STR).join(' ');319 },320 zoomedPolylinePoints() {321 return this.zoomedControlPoints.map(CTRL_POINT_TO_STR).join(' ');322 },323 controlPoints() {324 const ctrlPoints = [];325 for (let i = 0; i < this.points.length; i += 2) {326 const [x, y] = applyTransform(327 this.view,328 NO_TRANSFORM,329 this.points[i],330 this.points[i + 1]331 );332 ctrlPoints.push({ x, y });333 }334 return ctrlPoints;335 },336 zoomedControlPoints() {337 const ctrlPoints = [];338 for (let i = 0; i < this.points.length; i += 2) {339 const [x, y] = applyTransform(340 this.view,341 this.zoomTransform,342 this.points[i],343 this.points[i + 1]344 );345 ctrlPoints.push({ x, y });346 }347 return ctrlPoints;348 },349 transferFunction() {350 const sampling = 1024;351 const delta = 1 / sampling;352 const result = new Float64Array(sampling + 1);353 // Gather gaussian opacities354 for (let i = 0; i < this.gaussians.length; i++) {355 const g = this.gaussians[i];356 const minX = g.position - g.width;357 const maxX = g.position + g.width;358 const gSampling = Math.floor(1 + (maxX - minX) / delta);359 const gValues = this.gaussianSampling(g, gSampling);360 const offset = Math.floor(gValues[0].x / delta);361 for (let j = 1; j < gValues.length; j++) {362 const { y } = gValues[j];363 if (result[j + offset] < y) {364 result[j + offset] = y;365 }366 }367 }368 // Include linear points369 if (this.points.length) {370 const dx = delta;371 let srcIdx = 0;372 let dy =373 (this.points[srcIdx + 3] - this.points[srcIdx + 1]) /374 (this.points[srcIdx + 2] - this.points[srcIdx]);375 let dstIdx = 0;376 let x = 0;377 let opacity = this.points[srcIdx + 1];378 let nextX = this.points[srcIdx + 2];379 let nextY = this.points[srcIdx + 3];380 while (dstIdx < result.length) {381 if (x > nextX) {382 srcIdx += 2;383 dy =384 (this.points[srcIdx + 3] - this.points[srcIdx + 1]) /385 (this.points[srcIdx + 2] - this.points[srcIdx]);386 if (nextX - x < dx / 2) {387 opacity = nextY;388 } else if (Number.isFinite(dy)) {389 opacity = nextY + (nextX - x) * dy;390 }391 nextX = this.points[srcIdx + 2];392 nextY = this.points[srcIdx + 3];393 }394 if (result[dstIdx] < opacity) {395 result[dstIdx] = opacity;396 }397 dstIdx += 1;398 x += dx;399 opacity += dx * dy;400 }401 }402 return result;403 },404 transferFunctionPoints() {405 const values = this.transferFunction;406 const delta = 1 / (values.length - 1);407 const viewCoordinates = [];408 let x, y;409 for (let i = 0; i < values.length; i++) {410 [x, y] = applyTransform(411 this.view,412 this.zoomTransform,413 i * delta,414 values[i]415 );416 viewCoordinates.push({ x, y });417 }418 return viewCoordinates.map(CTRL_POINT_TO_STR).join(' ');419 },420 },421 created() {422 this.gaussianFinderConnected = false;423 this.documentDragUpdate = null;424 this.onMouseRelease = (e) => {425 this.dragStart = null;426 document.removeEventListener('mousemove', this.documentMouseMove);427 document.removeEventListener('mouseup', this.onMouseRelease);428 if (!this.deselectGaussianIfOutside(e)) {429 this.findToActivateGaussian(e);430 }431 };432 this.onMouseDrag = (e) => {433 this.dragMousePosition = toXY(e);434 this.documentDragUpdate();435 };436 this.findToActivateGaussian = ({ layerX }) => {437 if (this.dragStart) {438 return;439 }440 let minDistance = 100000;441 let activeIdx = -1;442 for (let i = 0; i < this.windowGaussianPositions.length; i++) {443 const { x, idx } = this.windowGaussianPositions[i];444 const distance = Math.abs(x - layerX + this.padding);445 if (distance < minDistance) {446 minDistance = distance;447 activeIdx = idx;448 }449 }450 if (this.activeGaussian !== activeIdx) {451 this.activeGaussian = activeIdx;452 }453 };454 this.$emit('opacities', this.transferFunction);455 },456 mounted() {457 this.updateViewSize();458 },459 methods: {460 attachGaussianFinder() {461 if (this.dragStart || this.gaussianFinderConnected) {462 return;463 }464 this.gaussianFinderConnected = true;465 document.addEventListener('mousemove', this.findToActivateGaussian);466 },467 detachGaussianFinder(e, forceDeselect = false) {468 document.removeEventListener('mousemove', this.findToActivateGaussian);469 this.gaussianFinderConnected = false;470 if (!this.dragStart) {471 this.deselectGaussianIfOutside(e);472 if (forceDeselect) {473 this.activeGaussian = -1;474 }475 }476 },477 deselectGaussianIfOutside({ layerX, layerY }) {478 const { size } = this.view;479 const tolerance = 1;480 if (481 layerX < this.padding + tolerance ||482 layerX > size[0] + this.padding - tolerance ||483 layerY < this.padding + tolerance ||484 layerY > size[1] + this.padding - tolerance485 ) {486 this.activeGaussian = -1;487 return true;488 }489 return false;490 },491 onPolyline(e) {492 this.hoverPolyline = true;493 this.detachGaussianFinder(e, true);494 },495 offPolyline(e) {496 if (this.dragStart) {497 return;498 }499 this.hoverPolyline = false;500 this.attachGaussianFinder(e);501 },502 deleteControlPoint(index) {503 if (index && index < this.points.length / 2 - 1) {504 this.points = this.points.filter(505 (v, idx) => idx !== 2 * index && idx !== 2 * index + 1506 );507 }508 },509 addControlPoint(e) {510 const xy = transformEvent(511 this.$el,512 e,513 this.view,514 this.zoomTransform,515 this.padding516 );517 const newPoints = [];518 let xyPending = true;519 for (let i = 0; i < this.points.length; i += 2) {520 const x = this.points[i];521 if (xyPending && xy[0] < x) {522 newPoints.push(xy[0]);523 newPoints.push(xy[1]);524 xyPending = false;525 }526 newPoints.push(x);527 newPoints.push(this.points[i + 1]);528 }529 this.points = newPoints;530 },531 dblClick(e) {532 // TODO533 // - add gaussian534 // - (alt) delete gaussian535 if (e.altKey && this.activeGaussian !== -1) {536 this.gaussians = this.gaussians.filter(537 (v, i) => i !== this.activeGaussian538 );539 this.activeGaussian = -1;540 } else {541 const xy = transformEvent(542 this.$el,543 e,544 this.view,545 this.zoomTransform,546 this.padding547 );548 this.activeGaussian = this.gaussians.length;549 this.gaussians = this.gaussians.concat({550 position: xy[0],551 xBias: 0,552 yBias: 0,553 height: 1,554 width: 0.1,555 });556 }557 },558 startDrag(updateFn) {559 this.documentDragUpdate = updateFn;560 document.addEventListener('mousemove', this.onMouseDrag);561 document.addEventListener('mouseup', this.onMouseRelease);562 },563 updateViewSize() {564 const { width, height } = this.$el.getBoundingClientRect();565 this.view = {566 ...this.view,567 size: [width - 2 * this.padding, height - 2 * this.padding],568 };569 },570 isControlPointInside(controlPoint) {571 const tolerance = 2;572 const xyMin = 0;573 const [xMax, yMax] = this.view.size;574 return !(575 isOutside(controlPoint.x, xyMin, xMax, tolerance) ||576 isOutside(controlPoint.y, xyMin, yMax, tolerance)577 );578 },579 toggleSelection(index) {580 if (this.selectedPoints.includes(index)) {581 this.selectedPoints = this.selectedPoints.filter(NOT(index));582 } else {583 this.selectedPoints.push(index);584 }585 },586 resetZoomTransform(axis) {587 if (axis > -1 && axis < 2) {588 const newTransform = cloneTransform(this.zoomTransform);589 newTransform.translation[axis] = 0;590 newTransform.scale[axis] = 1;591 this.zoomTransform = newTransform;592 } else {593 // reset all594 this.zoomTransform = {595 translation: [0, 0],596 scale: [1, 1],597 };598 }599 },600 startZoom(axis, mouseEvent, lockZoom = false) {601 this.dragStart = {602 axis,603 lockZoom,604 zoomTransform: cloneTransform(this.zoomTransform),605 mousePosition: toXY(mouseEvent),606 modifiers: toModifiers(mouseEvent),607 };608 this.startDrag(this.updateZoom);609 },610 updateZoom() {611 if (!this.dragStart) {612 return;613 }614 const { axis, zoomTransform, mousePosition, lockZoom } = this.dragStart;615 const { size } = this.view;616 const oppositeAxis = axis ? 0 : 1;617 const direction = axis ? -1 : 1;618 const scale = lockZoom619 ? zoomTransform.scale[axis]620 : clamp(621 (zoomTransform.scale[axis] *622 (size[oppositeAxis] +623 direction *624 (mousePosition[oppositeAxis] -625 this.dragMousePosition[oppositeAxis]))) /626 size[oppositeAxis],627 1,628 Number(this.maxZoom)629 );630 const translation = clamp(631 zoomTransform.translation[axis] +632 (this.dragMousePosition[axis] - mousePosition[axis]),633 0,634 (size[axis] * (scale - 1)) / scale635 );636 const newZoomTransform = cloneTransform(this.zoomTransform);637 newZoomTransform.translation[axis] = translation;638 newZoomTransform.scale[axis] = scale;639 this.zoomTransform = newZoomTransform;640 },641 startControlPointDrag(controlPointIndex, mouseEvent) {642 this.dragStart = {643 cIdx: controlPointIndex,644 startXY: [645 this.points[controlPointIndex * 2],646 this.points[controlPointIndex * 2 + 1],647 ],648 xRange: [649 this.points[controlPointIndex * 2 - 2],650 this.points[controlPointIndex * 2 + 2],651 ],652 mousePosition: toXY(mouseEvent),653 modifiers: toModifiers(mouseEvent),654 };655 this.startDrag(this.updateControlPointDrag);656 },657 updateControlPointDrag() {658 if (!this.dragStart) {659 return;660 }661 const { cIdx, startXY, xRange, mousePosition } = this.dragStart;662 const {663 begin,664 end,665 size: [width, height],666 } = this.view;667 const xScale = (end[0] - begin[0]) / width / this.zoomTransform.scale[0];668 const yScale = (end[1] - begin[1]) / height / this.zoomTransform.scale[1];669 const dx = xScale * (this.dragMousePosition[0] - mousePosition[0]);670 const dy = yScale * (this.dragMousePosition[1] - mousePosition[1]);671 const newPoints = this.points.slice();672 if (xRange[0] !== undefined && xRange[1] !== undefined) {673 // Only update X when not on a side674 if (xRange[0] < startXY[0] + dx && startXY[0] + dx < xRange[1]) {675 newPoints[2 * cIdx] = startXY[0] + dx;676 } else if (startXY[0] + dx < xRange[0]) {677 newPoints[2 * cIdx] = xRange[0];678 } else if (startXY[0] + dx > xRange[1]) {679 newPoints[2 * cIdx] = xRange[1];680 }681 }682 newPoints[2 * cIdx + 1] = clamp(startXY[1] + dy, 0, 1);683 this.points = newPoints;684 // Update selection if need be685 if (this.selectedPoints.length !== 1 || this.selectedPoints[0] !== cIdx) {686 this.selectedPoints = [cIdx];687 }688 },689 isActiveGaussian(gaussian) {690 return this.gaussians.indexOf(gaussian) === this.activeGaussian;691 },692 toGaussianProps(gaussian) {693 return {694 points: this.gaussianPoints(gaussian),695 controls: this.isActiveGaussian(gaussian)696 ? this.gaussianControls(gaussian)697 : false,698 };699 },700 gaussianControls({ position, xBias, yBias, width, height }) {701 const controlSize = this.activeGaussianOpacityStyle.controlSize;702 const [biasCenterX, biasCenterY] = applyTransform(703 this.view,704 this.zoomTransform,705 position,706 0707 );708 const [xBiasPos, yBiasMax] = applyTransform(709 this.view,710 this.zoomTransform,711 position + xBias * width,712 height713 );714 const [minX, minY] = applyTransform(715 this.view,716 this.zoomTransform,717 position - width,718 0719 );720 const [maxX, maxY] = applyTransform(721 this.view,722 this.zoomTransform,723 position + width,724 height725 );726 const yBiasPos =727 biasCenterY -728 2 * this.activeGaussianOpacityStyle.controlSize +729 yBias *730 0.5 *731 (yBiasMax -732 biasCenterY +733 2 * this.activeGaussianOpacityStyle.controlSize);734 return {735 controlSize,736 bounds: {737 x: minX,738 y: maxY,739 width: maxX - minX,740 height: minY - maxY,741 },742 bias: {743 center: [biasCenterX, biasCenterY],744 position: [xBiasPos, yBiasPos],745 },746 height: {747 x: minX,748 y: maxY,749 width: maxX - minX,750 height: controlSize,751 },752 leftWidth: {753 x: minX,754 y: minY,755 width: 0.5 * (maxX - minX),756 height: controlSize,757 },758 rightWidth: {759 x: 0.5 * (minX + maxX),760 y: minY - controlSize,761 width: 0.5 * (maxX - minX),762 height: controlSize,763 },764 };765 },766 gaussianSampling(767 { position, xBias, yBias, width, height },768 sampling = 100769 ) {770 const x1 = new Float32Array(sampling);771 const h = new Float32Array(sampling);772 // x-in773 const xStep = (2 * width) / (sampling - 1);774 if (Math.abs(xBias) === width) {775 for (let i = 0; i < sampling; i++) {776 x1[i] = (i * xStep - width) / width;777 }778 } else {779 const posScale = 1 / (width - xBias);780 const negScale = 1 / (width + xBias);781 for (let i = 0; i < sampling; i++) {782 x1[i] = i * xStep - width;783 if (x1[i] > xBias && posScale !== Number.Infinity) {784 x1[i] -= xBias;785 x1[i] *= posScale;786 } else if (negScale !== Number.Infinity) {787 x1[i] -= xBias;788 x1[i] *= negScale;789 }790 }791 }792 // y-out793 const zero = Math.exp(-4);794 if (yBias < 1) {795 for (let i = 0; i < sampling; i++) {796 const ha = Math.exp(-(4 * x1[i] * x1[i]));797 const hb = 1.0 - x1[i] * x1[i];798 h[i] = yBias * hb + (1 - yBias) * ha;799 h[i] -= zero;800 h[i] *= height;801 }802 } else {803 for (let i = 0; i < sampling; i++) {804 const hb = 1.0 - x1[i] * x1[i];805 h[i] = (2 - yBias) * hb + (yBias - 1);806 h[i] -= zero;807 h[i] *= height;808 }809 }810 const polyline = [];811 for (let i = 0; i < sampling; i++) {812 polyline.push({ x: position - width + i * xStep, y: h[i] });813 }814 polyline.unshift({ x: polyline[0].x, y: 0 });815 polyline.push({ x: polyline[sampling].x, y: 0 });816 return polyline;817 },818 gaussianPoints(gaussian) {819 const values = this.gaussianSampling(gaussian, 100);820 const viewCoordinates = [];821 let x, y;822 for (let i = 0; i < values.length; i++) {823 [x, y] = applyTransform(824 this.view,825 this.zoomTransform,826 values[i].x,827 values[i].y828 );829 viewCoordinates.push({ x, y });830 }831 return viewCoordinates.map(CTRL_POINT_TO_STR).join(' ');832 },833 startGaussianPositionDrag(index, mouseEvent) {834 this.dragStart = {835 gaussian: index,836 position: this.gaussians[index].position,837 mousePosition: toXY(mouseEvent),838 modifiers: toModifiers(mouseEvent),839 };840 this.startDrag(this.updateGaussianPosition);841 },842 updateGaussianPosition() {843 if (!this.dragStart) {844 return;845 }846 const { gaussian, position, mousePosition } = this.dragStart;847 const { begin, end, size } = this.view;848 const xScale =849 (end[0] - begin[0]) / size[0] / this.zoomTransform.scale[0];850 const dx = xScale * (this.dragMousePosition[0] - mousePosition[0]);851 const newGaussians = this.gaussians.slice();852 newGaussians[gaussian].position = clamp(position + dx, 0, 1);853 this.gaussians = newGaussians;854 },855 startGaussianBiasDrag(index, mouseEvent) {856 this.dragStart = {857 gaussian: index,858 xBias: this.gaussians[index].xBias,859 yBias: this.gaussians[index].yBias,860 mousePosition: toXY(mouseEvent),861 modifiers: toModifiers(mouseEvent),862 };863 this.startDrag(this.updateGaussianBias);864 },865 updateGaussianBias() {866 if (!this.dragStart) {867 return;868 }869 const { gaussian, xBias, yBias, mousePosition } = this.dragStart;870 const { begin, end, size } = this.view;871 const { width, height } = this.gaussians[gaussian];872 const xScale =873 (end[0] - begin[0]) / width / size[0] / this.zoomTransform.scale[0];874 const yScale =875 -2 /876 height /877 (size[1] - 2 * this.activeGaussianOpacityStyle.controlSize) /878 this.zoomTransform.scale[1];879 const dx = xScale * (this.dragMousePosition[0] - mousePosition[0]);880 const dy = yScale * (this.dragMousePosition[1] - mousePosition[1]);881 const newGaussians = this.gaussians.slice();882 newGaussians[gaussian].xBias = clamp(xBias + dx, -1, 1);883 newGaussians[gaussian].yBias = clamp(yBias + dy, 0, 2);884 this.gaussians = newGaussians;885 },886 resetGaussianBias(index) {887 const newGaussians = this.gaussians.slice();888 newGaussians[index].xBias = 0;889 newGaussians[index].yBias = 0;890 if (newGaussians[index].height < 0.001) {891 newGaussians[index].height = 1;892 }893 this.gaussians = newGaussians;894 },895 startGaussianHeightDrag(index, mouseEvent) {896 this.dragStart = {897 gaussian: index,898 height: this.gaussians[index].height,899 mousePosition: toXY(mouseEvent),900 modifiers: toModifiers(mouseEvent),901 };902 this.startDrag(this.updateGaussianHeight);903 },904 updateGaussianHeight() {905 if (!this.dragStart) {906 return;907 }908 const { gaussian, height, mousePosition } = this.dragStart;909 const { size } = this.view;910 const yScale =911 1 /912 (2 * this.activeGaussianOpacityStyle.controlSize - size[1]) /913 this.zoomTransform.scale[1];914 const dy = yScale * (this.dragMousePosition[1] - mousePosition[1]);915 const newGaussians = this.gaussians.slice();916 // Prevent the height control to collapse over width controls917 const minValue =918 (2 * this.activeGaussianOpacityStyle.controlSize) / size[1];919 newGaussians[gaussian].height = clamp(height + dy, minValue, 1);920 this.gaussians = newGaussians;921 },922 startGaussianWidthDrag(index, mouseEvent, direction = 1) {923 this.dragStart = {924 gaussian: index,925 direction,926 width: this.gaussians[index].width,927 mousePosition: toXY(mouseEvent),928 modifiers: toModifiers(mouseEvent),929 };930 this.startDrag(this.updateGaussianWidth);931 },932 updateGaussianWidth() {933 if (!this.dragStart) {934 return;935 }936 const { gaussian, width, direction, mousePosition } = this.dragStart;937 const { begin, end, size } = this.view;938 const xScale =939 (end[0] - begin[0]) / size[0] / this.zoomTransform.scale[0];940 const dx = xScale * (this.dragMousePosition[0] - mousePosition[0]);941 const newGaussians = this.gaussians.slice();942 newGaussians[gaussian].width = clamp(width + direction * dx, 0.01, 1);...
karabiner.js
Source:karabiner.js
1#!/usr/bin/env node2function fromTo(from, to) {3 return [4 {5 from: {6 key_code: from,7 },8 to: {9 key_code: to,10 },11 },12 ];13}14function genericModifierFN(mod, from, to) {15 const modVar = `${mod}_mod`;16 return [17 {18 from: {19 modifiers: {20 optional: ['any'],21 },22 simultaneous: [23 {24 key_code: mod,25 },26 {27 key_code: from,28 },29 ],30 simultaneous_options: {31 key_down_order: 'strict',32 key_up_order: 'strict_inverse',33 to_after_key_up: [34 {35 set_variable: {36 name: modVar,37 value: 0,38 },39 },40 ],41 },42 },43 parameters: {44 'basic.simultaneous_threshold_milliseconds': 3000 /* Default: 1000 */,45 },46 to: [47 {48 set_variable: {49 name: modVar,50 value: 1,51 },52 },53 ...to,54 ],55 type: 'basic',56 },57 {58 conditions: [59 {60 name: modVar,61 type: 'variable_if',62 value: 1,63 },64 ],65 from: {66 key_code: from,67 modifiers: {68 optional: ['any'],69 },70 },71 to,72 type: 'basic',73 },74 ];75}76function modifierFN(mod, from, to, toMods) {77 const toModifiers = toMods78 ? { modifiers: Array.isArray(toMods) ? toMods : [toMods] }79 : {};80 return genericModifierFN(mod, from, [{ key_code: to, ...toModifiers }]);81}82function repeatModifierFN(mod, from, to, toMods, repeatCount) {83 const toModifiers = toMods84 ? { modifiers: Array.isArray(toMods) ? toMods : [toMods] }85 : {};86 const toArray = [];87 for (let i = 0; i < repeatCount; i++) {88 toArray.push({ key_code: to, ...toModifiers });89 }90 return genericModifierFN(mod, from, toArray);91}92function spaceFN(from, to, toMods) {93 return modifierFN('spacebar', from, to, toMods);94}95function swap(a, b) {96 return [...fromTo(a, b), ...fromTo(b, a)];97}98const PARAMETER_DEFAULTS = {99 'basic.simultaneous_threshold_milliseconds': 50,100 'basic.to_delayed_action_delay_milliseconds': 500,101 'basic.to_if_alone_timeout_milliseconds': 1000,102 'basic.to_if_held_down_threshold_milliseconds': 500,103};104const VANILLA_PROFILE = {105 complex_modifications: {106 parameters: PARAMETER_DEFAULTS,107 rules: [],108 },109 name: 'Vanilla',110 selected: false,111 simple_modifications: [],112};113const DEFAULT_PROFILE = {114 ...VANILLA_PROFILE,115 simple_modifications: [116 {117 from: {118 key_code: 'caps_lock',119 },120 to: [121 {122 key_code: 'left_control',123 },124 ],125 },126 {127 from: {128 key_code: 'non_us_backslash',129 },130 to: [131 {132 key_code: 'grave_accent_and_tilde',133 },134 ],135 },136 {137 from: {138 key_code: 'backslash',139 },140 to: [141 {142 key_code: 'return_or_enter',143 },144 ],145 },146 ],147 complex_modifications: {148 parameters: {149 ...PARAMETER_DEFAULTS,150 'basic.to_if_alone_timeout_milliseconds': 500 /* Default: 1000 */,151 },152 rules: [153 {154 description: 'Numeric qwerty row',155 manipulators: [156 ...spaceFN('q', '1'),157 ...spaceFN('w', '2'),158 ...spaceFN('e', '3'),159 ...spaceFN('r', '4'),160 ...spaceFN('t', '5'),161 ...spaceFN('y', '6'),162 ...spaceFN('u', '7'),163 ...spaceFN('i', '8'),164 ...spaceFN('o', '9'),165 ...spaceFN('p', '0'),166 ],167 },168 {169 description: 'Brackets and special characters',170 manipulators: [171 ...spaceFN('a', '1', 'left_shift'),172 ...spaceFN('s', '2', 'left_shift'),173 ...spaceFN('d', 'open_bracket'),174 ...spaceFN('x', 'close_bracket'),175 ...spaceFN('f', 'open_bracket', 'left_shift'),176 ...spaceFN('c', 'close_bracket', 'left_shift'),177 ...spaceFN('g', '9', 'left_shift'),178 ...spaceFN('v', '0', 'left_shift'),179 ...spaceFN('h', 'equal_sign', 'left_shift'),180 ...spaceFN('n', 'hyphen'),181 ...spaceFN('j', 'equal_sign'),182 ...spaceFN('k', '8', 'left_shift'),183 ...spaceFN('l', '7', 'left_shift'),184 ...spaceFN('semicolon', 'backslash', 'left_shift'),185 ...spaceFN('m', 'hyphen', 'left_shift'),186 ...spaceFN('slash', 'backslash'),187 ...spaceFN('z', '6', 'left_shift'),188 ...spaceFN('b', '4', 'left_shift'),189 ...spaceFN('comma', '3', 'left_shift'),190 ...spaceFN('period', '5', 'left_shift'),191 ...spaceFN('quote', 'grave_accent_and_tilde'),192 ...spaceFN(193 'open_bracket',194 'grave_accent_and_tilde',195 'left_shift'196 ),197 ],198 },199 {200 description: 'Sloveninan caron character bindings',201 manipulators: [202 ...modifierFN('m', 's', 's', ['option']),203 ...modifierFN('m', 'z', 'z', ['option']),204 ...modifierFN('m', 'c', 'c', ['option']),205 ...modifierFN('n', 's', 's', ['option', 'left_shift']),206 ...modifierFN('n', 'z', 'z', ['option', 'left_shift']),207 ...modifierFN('n', 'c', 'c', ['option', 'left_shift']),208 ],209 },210 {211 description: 'Basic movememnt bindings',212 manipulators: [213 // movement by one line character214 ...modifierFN('d', 'j', 'left_arrow'),215 ...modifierFN('d', 'l', 'right_arrow'),216 ...modifierFN('f', 'i', 'up_arrow'),217 ...modifierFN('f', 'k', 'down_arrow'),218 ...modifierFN('d', 'i', 'up_arrow'),219 ...modifierFN('d', 'k', 'down_arrow'),220 ...modifierFN('g', 'i', 'up_arrow'),221 ...modifierFN('g', 'k', 'down_arrow'),222 // left, right movements by word223 ...modifierFN('g', 'j', 'left_arrow', 'option'),224 ...modifierFN('g', 'l', 'right_arrow', 'option'),225 ...modifierFN('f', 'j', 'left_arrow'),226 ...modifierFN('f', 'l', 'right_arrow'),227 // left, right movements by 3 words228 ...repeatModifierFN('s', 'j', 'left_arrow', 'option', 3),229 ...repeatModifierFN('s', 'l', 'right_arrow', 'option', 3),230 // page up, down movements231 ...repeatModifierFN('s', 'i', 'page_up', [], 20),232 ...repeatModifierFN('s', 'k', 'page_down', [], 20),233 // move to beginning, end of line234 ...modifierFN('a', 'j', 'left_arrow', 'left_command'),235 ...modifierFN('a', 'l', 'right_arrow', 'left_command'),236 // move to start, end of document237 ...modifierFN('a', 'i', 'up_arrow', 'left_command'),238 ...modifierFN('a', 'k', 'down_arrow', 'left_command'),239 ],240 },241 {242 description: 'UI bindings',243 manipulators: [244 // move to left document tab245 ...modifierFN('t', 'j', 'open_bracket', [246 'left_shift',247 'left_command',248 ]),249 // move to right document tab250 ...modifierFN('t', 'l', 'close_bracket', [251 'left_shift',252 'left_command',253 ]),254 // cycle trough windows in the application255 ...modifierFN('w', 'i', 'grave_accent_and_tilde', [256 'left_command',257 ]),258 // cycle trough windows in the application259 ...modifierFN('w', 'k', 'grave_accent_and_tilde', [260 'left_command',261 'left_shift',262 ]),263 // cycle trough applications forwards264 ...modifierFN('w', 'l', 'tab', ['left_command']),265 // cycle trough applications backwards266 ...modifierFN('w', 'j', 'tab', ['left_command', 'left_shift']),267 ],268 },269 {270 description: 'Basic selection bindings',271 manipulators: [272 // select word left273 ...modifierFN('e', 'j', 'left_arrow', ['option', 'right_shift']),274 // select word right275 ...modifierFN('e', 'l', 'right_arrow', [276 'option',277 'right_shift',278 ]),279 // select character left280 ...modifierFN('r', 'j', 'left_arrow', ['right_shift']),281 // select character right282 ...modifierFN('r', 'l', 'right_arrow', ['right_shift']),283 // select line up284 ...modifierFN('e', 'i', 'up_arrow', ['right_shift']),285 // select line down286 ...modifierFN('e', 'k', 'down_arrow', ['right_shift']),287 // select and copy current line288 ...genericModifierFN('f', 'y', [289 {290 key_code: 'left_arrow',291 modifiers: ['left_command'],292 },293 {294 key_code: 'left_arrow',295 modifiers: ['left_command'],296 },297 {298 key_code: 'down_arrow',299 modifiers: ['left_shift'],300 },301 {302 key_code: 'c',303 modifiers: ['right_command'],304 },305 ]),306 // select line for downward selection movement307 ...genericModifierFN('r', 'k', [308 {309 key_code: 'left_arrow',310 modifiers: ['left_command'],311 },312 {313 key_code: 'left_arrow',314 modifiers: ['left_command'],315 },316 {317 key_code: 'down_arrow',318 modifiers: ['left_shift'],319 },320 ]),321 // select line for upward selection movement322 ...genericModifierFN('r', 'i', [323 {324 key_code: 'down_arrow',325 modifiers: [],326 },327 {328 key_code: 'left_arrow',329 modifiers: ['left_command'],330 },331 {332 key_code: 'left_arrow',333 modifiers: ['left_command'],334 },335 {336 key_code: 'up_arrow',337 modifiers: ['left_shift'],338 },339 ]),340 ],341 },342 {343 description: 'Basic deletion and line insetion bindings', // to do here344 manipulators: [345 // delete character backwards, forwards346 ...modifierFN('c', 'j', 'delete_or_backspace'),347 ...modifierFN('c', 'l', 'delete_or_backspace', ['fn']),348 // insert empty line below349 ...genericModifierFN('v', 'k', [350 {351 key_code: 'right_arrow',352 modifiers: ['left_command'],353 },354 {355 key_code: 'return_or_enter',356 modifiers: [],357 },358 ]),359 // insert empty line above360 ...genericModifierFN('v', 'i', [361 {362 key_code: 'up_arrow',363 modifiers: [],364 },365 {366 key_code: 'right_arrow',367 modifiers: ['left_command'],368 },369 {370 key_code: 'return_or_enter',371 modifiers: [],372 },373 ]),374 // delete word left, right375 ...modifierFN('v', 'j', 'delete_or_backspace', ['option']),376 ...modifierFN('b', 'j', 'delete_or_backspace', ['option']),377 ...modifierFN('v', 'l', 'delete_or_backspace', ['option', 'fn']),378 ...modifierFN('b', 'l', 'delete_or_backspace', ['option', 'fn']),379 // delete to beginning of line380 ...modifierFN('x', 'j', 'delete_or_backspace', ['left_command']),381 // delete to end of line382 ...genericModifierFN('x', 'l', [383 {384 key_code: 'right_arrow',385 modifiers: ['left_command', 'right_shift'],386 },387 {388 key_code: 'delete_or_backspace',389 modifiers: [],390 },391 ]),392 // delete line and move down393 ...genericModifierFN('x', 'k', [394 {395 key_code: 'left_arrow',396 modifiers: ['left_command'],397 },398 {399 key_code: 'left_arrow',400 modifiers: ['left_command'],401 },402 {403 key_code: 'down_arrow',404 modifiers: ['left_shift'],405 },406 {407 key_code: 'x',408 modifiers: ['right_command'],409 },410 ]),411 // delete line and move up412 ...genericModifierFN('x', 'i', [413 {414 key_code: 'left_arrow',415 modifiers: ['left_command'],416 },417 {418 key_code: 'left_arrow',419 modifiers: ['left_command'],420 },421 {422 key_code: 'down_arrow',423 modifiers: ['left_shift'],424 },425 {426 key_code: 'x',427 modifiers: ['right_command'],428 },429 {430 key_code: 'up_arrow',431 modifiers: [],432 },433 ]),434 // select and cut (to clipboard) current line435 ...genericModifierFN('d', 'y', [436 {437 key_code: 'left_arrow',438 modifiers: ['left_command'],439 },440 {441 key_code: 'left_arrow',442 modifiers: ['left_command'],443 },444 {445 key_code: 'down_arrow',446 modifiers: ['left_shift'],447 },448 {449 key_code: 'x',450 modifiers: ['right_command'],451 },452 ]),453 // duplicate current line454 ...genericModifierFN('f', 'u', [455 {456 key_code: 'left_arrow',457 modifiers: ['left_command'],458 },459 {460 key_code: 'left_arrow',461 modifiers: ['left_command'],462 },463 {464 key_code: 'down_arrow',465 modifiers: ['left_shift'],466 },467 {468 key_code: 'c',469 modifiers: ['right_command'],470 },471 {472 key_code: 'left_arrow',473 modifiers: ['left_command'],474 },475 {476 key_code: 'v',477 modifiers: ['left_command'],478 },479 ]),480 ],481 },482 {483 description: 'Toggle CAPS_LOCK with LEFT_SHIFT + RIGHT_SHIFT',484 manipulators: [485 {486 from: {487 key_code: 'left_shift',488 modifiers: {489 mandatory: ['right_shift'],490 optional: ['caps_lock'],491 },492 },493 to: [494 {495 key_code: 'caps_lock',496 },497 ],498 to_if_alone: [499 {500 key_code: 'left_shift',501 },502 ],503 type: 'basic',504 },505 {506 from: {507 key_code: 'right_shift',508 modifiers: {509 mandatory: ['left_shift'],510 optional: ['caps_lock'],511 },512 },513 to: [514 {515 key_code: 'caps_lock',516 },517 ],518 to_if_alone: [519 {520 key_code: 'right_shift',521 },522 ],523 type: 'basic',524 },525 ],526 },527 {528 description: 'Post Esc if Caps is tapped, Control if held.',529 manipulators: [530 {531 type: 'basic',532 from: {533 key_code: 'left_control',534 modifiers: {535 optional: ['any'],536 },537 },538 to: [539 {540 key_code: 'left_control',541 lazy: true,542 },543 ],544 to_if_alone: [545 {546 key_code: 'escape',547 },548 ],549 },550 ],551 },552 {553 description:554 'Change return to control if pressed with other keys, to return if pressed alone',555 manipulators: [556 {557 from: {558 key_code: 'return_or_enter',559 modifiers: {560 optional: ['any'],561 },562 },563 to: [564 {565 key_code: 'right_control',566 },567 ],568 to_if_alone: [569 {570 key_code: 'return_or_enter',571 },572 ],573 type: 'basic',574 },575 ],576 },577 {578 description: 'Testing',579 manipulators: [580 {581 from: {582 key_code: 'g',583 modifiers: {584 mandatory: ['left_control'],585 },586 },587 to: [588 {589 shell_command:590 '/Users/matej/Projects/tselect/bin/tselect',591 },592 ],593 type: 'basic',594 },595 {596 from: {597 key_code: 'g',598 modifiers: {599 mandatory: ['right_control'],600 },601 },602 to: [603 {604 shell_command:605 '/Users/matej/Projects/tselect/bin/tselect',606 },607 ],608 type: 'basic',609 },610 ],611 },612 {613 description: 'Xcode specific',614 manipulators: [615 {616 from: {617 key_code: 't',618 modifiers: {619 mandatory: ['right_control'],620 },621 },622 to: [623 {624 key_code: 't',625 },626 {627 key_code: 'r',628 },629 {630 key_code: 'u',631 },632 {633 key_code: 'e',634 },635 ],636 type: 'basic',637 },638 {639 from: {640 key_code: 'f',641 modifiers: {642 mandatory: ['right_control'],643 },644 },645 to: [646 {647 key_code: 'f',648 },649 {650 key_code: 'a',651 },652 {653 key_code: 'l',654 },655 {656 key_code: 's',657 },658 {659 key_code: 'e',660 },661 ],662 type: 'basic',663 },664 {665 from: {666 key_code: 's',667 modifiers: {668 mandatory: ['right_control'],669 },670 },671 to: [672 {673 key_code: 's',674 },675 {676 key_code: 'e',677 },678 {679 key_code: 'l',680 },681 {682 key_code: 'f',683 },684 {685 key_code: 'period',686 },687 ],688 type: 'basic',689 },690 {691 from: {692 key_code: 'l',693 modifiers: {694 mandatory: ['left_control'],695 },696 },697 to: [698 {699 key_code: 'l',700 },701 {702 key_code: 'e',703 },704 {705 key_code: 't',706 },707 {708 key_code: 'spacebar',709 },710 ],711 type: 'basic',712 },713 {714 from: {715 key_code: 'v',716 modifiers: {717 mandatory: ['right_control'],718 },719 },720 to: [721 {722 key_code: 'v',723 },724 {725 key_code: 'a',726 },727 {728 key_code: 'r',729 },730 {731 key_code: 'spacebar',732 },733 ],734 type: 'basic',735 },736 {737 from: {738 key_code: 'c',739 modifiers: {740 mandatory: ['right_control'],741 },742 },743 to: [744 {745 key_code: 'c',746 },747 {748 key_code: 'o',749 },750 {751 key_code: 'n',752 },753 {754 key_code: 's',755 },756 {757 key_code: 't',758 },759 {760 key_code: 'spacebar',761 },762 ],763 type: 'basic',764 },765 {766 from: {767 key_code: 'w',768 modifiers: {769 mandatory: ['right_control'],770 },771 },772 to: [773 {774 key_code: 's',775 },776 {777 key_code: 'w',778 },779 {780 key_code: 'i',781 },782 {783 key_code: 't',784 },785 {786 key_code: 'c',787 },788 {789 key_code: 'h',790 },791 {792 key_code: 'spacebar',793 },794 ],795 type: 'basic',796 },797 ],798 },799 ],800 },801 name: 'Default',802 selected: true,803};804process.stdout.write(805 JSON.stringify(806 {807 global: {808 check_for_updates_on_startup: true,809 show_in_menu_bar: true,810 show_profile_name_in_menu_bar: false,811 },812 profiles: [DEFAULT_PROFILE, VANILLA_PROFILE],813 },814 null,815 2816 ) + '\n'...
index.js
Source:index.js
1import { isEqual } from 'lodash';2function getTables(tables) {3 return Object.keys(tables).map((tableName) => tables[tableName]);4}5function getTypes(types) {6 return Object.keys(types).map((typeName) => types[typeName]);7}8function getColumns(table) {9 return Object.keys(table.columns).map((columnName) => table.columns[columnName]);10}11function getModifiersSql(column) {12 const modifiers = [];13 if (column.modifiers.default) {14 modifiers.push(`DEFAULT ${column.modifiers.default}`);15 }16 if (column.modifiers.notNull) {17 modifiers.push(`NOT NULL`);18 }19 return modifiers.join(` `);20}21function getColumnSql(table, column) {22 let query = `${column.name} ${column.dataType}`;23 if (Object.keys(column.modifiers).length > 0) {24 query += ` ${getModifiersSql(column)}`;25 }26 // Find applicable indexes.27 table.indexes.forEach((index) => {28 if (index.columns.length === 1 && index.columns[0] === column.name) {29 if (index.type === `primaryKey`) {30 query += ` PRIMARY KEY`;31 }32 else if (index.type === `foreignKey`) {33 query += ` REFERENCES ${index.tableName} (${index.referenceColumns.join(`, `)})`;34 }35 else if (index.type === `unique`) {36 query += ` UNIQUE`;37 }38 else if (index.type === `check`) {39 query += ` CHECK (${index.expression})`;40 }41 }42 });43 return query;44}45function isEqualColumn(fromColumn, toColumn) {46 if (!fromColumn || !toColumn || fromColumn.dataType !== toColumn.dataType) {47 return false;48 }49 const fromModifiers = fromColumn.modifiers;50 const toModifiers = toColumn.modifiers;51 return (52 (!fromModifiers.notNull && !toModifiers.notNull ||53 fromModifiers.notNull && toModifiers.notNull) &&54 (!fromModifiers.primaryKey && !toModifiers.primaryKey ||55 fromModifiers.primaryKey && toModifiers.primaryKey) &&56 (!fromModifiers.default && !toModifiers.default ||57 fromModifiers.default === toModifiers.default)58 );59}60function isEqualTable(fromTable, toTable) {61 return Object.keys(fromTable.columns).length === Object.keys(toTable.columns).length &&62 getColumns(fromTable).every((fromColumn) => isEqualColumn(fromColumn, toTable.columns[fromColumn.name]));63}64export default function createSql(from, to) {65 const queries = [];66 getTables(to.tables).forEach((toTable) => {67 const fromTable = from.tables[toTable.name];68 if (!fromTable) {69 const tables = getTables(from.tables).filter((fromTable) => isEqualTable(fromTable, toTable));70 if (tables.length === 1) {71 const table = tables[0];72 const query = `ALTER TABLE ${table.name} RENAME TO ${toTable.name}`;73 from.simulateQuery(query);74 queries.push(query);75 }76 else {77 const query = `CREATE TABLE ${toTable.name} (\n${Object.keys(toTable.columns).map((columnName) => toTable.columns[columnName]).map((column) => `\t${getColumnSql(toTable, column)}`).join(`,\n`)}\n)`;78 from.simulateQuery(query);79 queries.push(query);80 }81 }82 else {83 getColumns(toTable).forEach((toColumn) => {84 const fromColumn = fromTable.columns[toColumn.name];85 if (!fromColumn) {86 const columns = getColumns(fromTable).filter((fromColumn) => isEqualColumn(fromColumn, toColumn));87 const column = columns[0];88 if (columns.length === 1 && !toTable.columns[column.name]) {89 const query = `ALTER TABLE ${toTable.name} RENAME COLUMN ${column.name} TO ${toColumn.name}`;90 from.simulateQuery(query);91 queries.push(query);92 }93 else {94 let query = `ALTER TABLE ${toTable.name} ADD COLUMN ${getColumnSql(toTable, toColumn)}`;95 from.simulateQuery(query);96 queries.push(query);97 }98 }99 else {100 // TODO: Create one alter table query if there are multiple changes.101 if (fromColumn.dataType !== toColumn.dataType) {102 const query = `ALTER TABLE ${toTable.name} ALTER COLUMN ${toColumn.name} SET DATA TYPE ${toColumn.dataType}`;103 from.simulateQuery(query);104 queries.push(query);105 }106 if (fromColumn.modifiers.notNull && !toColumn.modifiers.notNull) {107 const query = `ALTER TABLE ${toTable.name} ALTER COLUMN ${toColumn.name} DROP NOT NULL`;108 from.simulateQuery(query);109 queries.push(query);110 }111 else if (!fromColumn.modifiers.notNull && toColumn.modifiers.notNull) {112 const query = `ALTER TABLE ${toTable.name} ALTER COLUMN ${toColumn.name} SET NOT NULL`;113 from.simulateQuery(query);114 queries.push(query);115 }116 if (fromColumn.modifiers.default && !toColumn.modifiers.default) {117 const query = `ALTER TABLE ${toTable.name} ALTER COLUMN ${toColumn.name} DROP DEFAULT`;118 from.simulateQuery(query);119 queries.push(query);120 }121 else if (!fromColumn.modifiers.default && toColumn.modifiers.default) {122 const query = `ALTER TABLE ${toTable.name} ALTER COLUMN ${toColumn.name} SET DEFAULT ${toColumn.modifiers.default}`;123 from.simulateQuery(query);124 queries.push(query);125 }126 }127 });128 getColumns(fromTable).forEach((fromColumn) => {129 const toColumn = toTable.columns[fromColumn.name];130 if (!toColumn) {131 // TODO: Check if this was a rename.132 const query = `ALTER TABLE ${toTable.name} DROP COLUMN ${fromColumn.name}`;133 from.simulateQuery(query);134 queries.push(query);135 }136 });137 fromTable.indexes.forEach((fromIndex) => {138 const toIndex = toTable.indexes.find((toIndex) => isEqual(toIndex, fromIndex));139 if (!toIndex) {140 const query = `ALTER TABLE ${toTable.name} DROP CONSTRAINT ${fromIndex.name}`;141 from.simulateQuery(query);142 queries.push(query);143 }144 });145 toTable.indexes.forEach((toIndex) => {146 const fromIndex = fromTable.indexes.find((fromIndex) => isEqual(fromIndex, toIndex));147 if (!fromIndex) {148 if (toIndex.type === `primaryKey`) {149 const query = `ALTER TABLE ${toTable.name} ADD CONSTRAINT ${toIndex.name} PRIMARY KEY (${toIndex.columns.join(`, `)})`;150 from.simulateQuery(query);151 queries.push(query);152 }153 else if (toIndex.type === `unique`) {154 const query = `ALTER TABLE ${toTable.name} ADD CONSTRAINT ${toIndex.name} UNIQUE (${toIndex.columns.join(`, `)})`;155 from.simulateQuery(query);156 queries.push(query);157 }158 else if (toIndex.type === `foreignKey`) {159 const query = `ALTER TABLE ${toTable.name} ADD CONSTRAINT ${toIndex.name} FOREIGN KEY (${toIndex.columns.join(`, `)}) REFERENCES ${toIndex.tableName}${toIndex.referenceColumns.length > 0 ? ` (${toIndex.referenceColumns.join(`, `)})` : ``}`;160 from.simulateQuery(query);161 queries.push(query);162 }163 else if (toIndex.type === `check`) {164 const query = `ALTER TABLE ${toTable.name} ADD CONSTRAINT ${toIndex.name} CHECK (${toIndex.expression})`;165 from.simulateQuery(query);166 queries.push(query);167 }168 else {169 // Unknown index type.170 }171 }172 });173 }174 });175 getTables(from.tables).forEach((fromTable) => {176 const toTable = to.tables[fromTable.name];177 if (!toTable) {178 const query = `DROP TABLE ${fromTable.name}`;179 from.simulateQuery(query);180 queries.push(query);181 }182 });183 getTypes(to.types).forEach((toType) => {184 const fromType = from.types[toType.name];185 if (!fromType) {186 const query = `CREATE TYPE ${toType.name} AS ENUM (${toType.labels.map((label) => `'${label}'`).join(`, `)})`;187 from.simulateQuery(query);188 queries.push(query);189 }190 else {191 const previousLabels = fromType.labels.reduce((labels, label, index) => {192 labels[label] = index;193 return labels;194 }, {});195 toType.labels.forEach((label, index) => {196 const exists = previousLabels[label] >= 0;197 if (!exists) {198 if (index === 0) {199 const query = `ALTER TYPE ${toType.name} ADD VALUE '${label}' BEFORE '${fromType.labels[0]}'`;200 from.simulateQuery(query);201 queries.push(query);202 }203 else {204 const query = `ALTER TYPE ${toType.name} ADD VALUE '${label}' AFTER '${fromType.labels[index - 1]}'`;205 from.simulateQuery(query);206 queries.push(query);207 }208 }209 });210 }211 });212 getTypes(from.types).forEach((fromType) => {213 const toType = to.types[fromType.name];214 if (!toType) {215 const query = `DROP TYPE ${fromType.name}`;216 from.simulateQuery(query);217 queries.push(query);218 }219 });220 return queries;...
bemify-test.js
Source:bemify-test.js
...224});225// Utilities226test('converting to modifiers', (t) => {227 const expected = ['--one', '--three', '--two']; // sorted228 t.isEquivalent(toModifiers('one two three'), expected);229 t.isEquivalent(toModifiers(['one', 'two', 'three']), expected);230 t.isEquivalent(toModifiers({231 'one': true,232 'two': true,233 'three': true,234 'four': false,235 }), expected);236 t.isEquivalent(toModifiers('one', ['two'], { 'three': true }), expected);237 t.end();...
config.js
Source:config.js
1const { getPermutation } = require('./permutation')2const arrowKeys = [3 ['w', 'up_arrow'],4 ['s', 'down_arrow'],5 ['a', 'left_arrow'],6 ['d', 'right_arrow'],7]8const cursorKeys = [9 ['l', 'home'],10 ['comma', 'end'],11]12const functionKeys = [13 ['1', 'f1'],14 ['2', 'f2'],15 ['3', 'f3'],16 ['4', 'f4'],17 ['5', 'f5'],18 ['6', 'f6'],19 ['7', 'f7'],20 ['8', 'f8'],21 ['9', 'f9'],22 ['0', 'f10'],23 ['-', 'f11'],24 ['=', 'f12'],25]26const inputKeys = [['escape', 'grave_accent_and_tilde']]27const editKeys = [['delete_or_backspace', 'delete_forward']]28function bindModifier(keyMap, modifier) {29 if (!Array.isArray(modifier)) {30 modifier = [modifier]31 }32 return keyMap.map((combo) => [combo[0], [combo[1]], modifier])33}34function bindTargetModifier(keyMap, fromModifier, toModifier) {35 if (!Array.isArray(toModifier)) {36 toModifier = [toModifier]37 }38 return keyMap.map((combo) => [39 combo[0],40 [combo[1], ...toModifier],41 [fromModifier, ...toModifier],42 ])43}44function bindPermutationModifier(keyMap, fromModifier, toModifiers) {45 // get permutations of modifiers46 const permutationMap = getPermutation(toModifiers.length)47 return permutationMap48 .map((map) => {49 return map.map((idx) => {50 return toModifiers[idx]51 })52 })53 .map((modifiers) => {54 return bindTargetModifier(keyMap, fromModifier, modifiers)55 })56 .flat()57}58const complexModification = [59 // arrow keys60 ...bindModifier(arrowKeys, 'fn'),61 ...bindPermutationModifier(arrowKeys, 'fn', [62 'right_shift',63 'left_shift',64 'left_option',65 'left_control',66 'left_command',67 ]),68 // cursor keys69 ...bindModifier(cursorKeys, 'fn'),70 ...bindTargetModifier(cursorKeys, 'fn', 'right_shift'),71 ...bindTargetModifier(cursorKeys, 'fn', 'left_shift'),72 // Edit keys73 ...bindModifier(editKeys, 'fn'),74 // function keys75 ...bindModifier(functionKeys, 'fn'),76 // input keys77 ...bindModifier(inputKeys, 'fn'),78 ...bindPermutationModifier(inputKeys, 'fn', ['right_shift', 'left_shift']),79]80const fn = {81 apple_vendor_top_case_key_code: 'keyboard_fn',82}83const leftOption = { key_code: 'left_option' }84const leftControl = { key_code: 'left_control' }85const rightCommand = { key_code: 'right_command' }86const capsLock = {87 key_code: 'caps_lock',88}89const simpleModifications = [90 [leftControl, fn],91 [leftOption, leftControl],92 [rightCommand, fn],93 [capsLock, leftOption],94].map(getRule)95function getRule([from, to]) {96 return {97 from,98 to: [to],99 }100}...
utils.js
Source:utils.js
1import { isObject, } from 'lodash';2import type { GeekCapsConfig } from '../../typeDefinition';3export function generateGroup(globalConfigs: GeekCapsConfig, description, manipulators) {4 return {5 description,6 manipulators,7 };8}9export function generateManipulator(fromInput, toInput, type = 'basic') {10 const fromConfig = extractKeyConfig(fromInput),11 targetConfig = extractKeyConfig(toInput),12 from = {13 key_code: fromConfig.key,14 modifiers: {15 mandatory: [16 ...fromConfig.modifiers,17 ...essentialModifiers,18 'right_shift',19 ],20 },21 },22 to = { key_code: targetConfig.key };23 if (targetConfig.modifiers.length > 0) {24 to.modifiers = targetConfig.modifiers;25 }26 return { from, to, type };27}28export function generateManipulators(fromKey, toKey, variations = [[]], type = 'basic') {29 return variations.map(([fromModifiers, toModifiers]) => {30 const from = {31 key_code: fromKey,32 modifiers: {33 mandatory: [34 ...essentialModifiers,35 'right_shift',36 ],37 }38 },39 to = { key_code: toKey };40 if (fromModifiers && fromModifiers.length > 0) {41 from.modifiers.mandatory = fromModifiers.map(i => i.key).concat(from.modifiers.mandatory);42 }43 if (toModifiers && toModifiers.length > 0) {44 to.modifiers = toModifiers.map(i => i.key);45 }46 return { from, to, type, };47 });48}49function extractKeyConfig(option) {50 if (isObject(option)) {51 if (!option.key) throw new Error({ message: 'key is required!', payload: option });52 if (!option.modifiers) option.modifiers = [];53 return option;54 }55 return { key: option, modifiers: [] };56}57export const essentialModifiers = [58 'right_command',59 'right_control',60 'right_option',61];62export const Modifiers = {63 shift: {64 key: 'left_shift',65 },66 command: {67 key: 'left_command',68 },69 option: {70 key: 'left_option',71 },72 ctrl: {73 key: 'left_control',74 },75 fn: {76 key: 'fn',77 },...
ClassNames.js
Source:ClassNames.js
...13 modifiers?: string | string[] | {[string]: boolean}14) {15 return {16 element,17 modifiers: Array.isArray(modifiers) ? toModifiers(modifiers) : modifiers18 };...
Media.js
Source:Media.js
1import PropTypes from 'prop-types'2import bp from '../breakpoints'3const toModifiers = (base, media) =>4 Object.entries(media).map(5 ([breakpoint, size]) => `${base}--${size}@${breakpoint}`,6 )7const propTypeFor = propType =>8 PropTypes.shape({9 [bp.phoneOnly]: propType,10 [bp.tabletLandscape]: propType,11 [bp.tabletPortrait]: propType,12 [bp.phoneOnly]: propType,13 })14export default {15 toModifiers,16 propTypeFor,...
Using AI Code Generation
1const { toModifiers } = require('playwright/lib/server/keyboard');2const modifiers = toModifiers('Shift+Control+Alt+Meta');3console.log(modifiers);4const { toModifiers } = require('playwright/lib/server/keyboard');5const modifiers = toModifiers('Shift+Control+Alt+Meta+Shift');6console.log(modifiers);7const { toModifiers } = require('playwright/lib/server/keyboard');8const modifiers = toModifiers('Shift+Control+Alt+Meta+Shift+Control+Alt+Meta');9console.log(modifiers);10const { toModifiers } = require('playwright/lib/server/keyboard');11const modifiers = toModifiers('Shift+Control+Alt+Meta+Shift+Control+Alt+Meta+Shift');12console.log(modifiers);13const { toModifiers } = require('playwright/lib/server/keyboard');14const modifiers = toModifiers('Shift+Control+Alt+Meta+Shift+Control+Alt+Meta+Shift+Control');15console.log(modifiers);16const { toModifiers } = require('playwright/lib/server/keyboard');17const modifiers = toModifiers('Shift+Control+Alt+Meta+Shift+Control+Alt+Meta+Shift+Control+Alt');18console.log(modifiers);19const { toModifiers } = require('playwright/lib/server/keyboard');20const modifiers = toModifiers('Shift+Control+Alt+Meta+Shift+Control+Alt+Meta+Shift+Control+Alt+Meta');21console.log(modifiers
Using AI Code Generation
1const { toModifiers } = require('@playwright/test/lib/utils/utils');2console.log(toModifiers('Control+Shift+KeyT'));3const { toModifiers } = require('@playwright/test/lib/utils/utils');4console.log(toModifiers('Control+Shift+KeyT'));5const { toModifiers } = require('@playwright/test/lib/utils/utils');6console.log(toModifiers('Control+Shift+KeyT'));7const { toModifiers } = require('@playwright/test/lib/utils/utils');8console.log(toModifiers('Control+Shift+KeyT'));9const { toModifiers } = require('@playwright/test/lib/utils/utils');10console.log(toModifiers('Control+Shift+KeyT'));11const { toModifiers } = require('@playwright/test/lib/utils/utils');12console.log(toModifiers('Control+Shift+KeyT'));13const { toModifiers } = require('@playwright/test/lib/utils/utils');14console.log(toModifiers('Control+Shift+KeyT'));15const { toModifiers } = require('@playwright/test/lib/utils/utils');16console.log(toModifiers('Control+Shift+KeyT'));17const { toModifiers } = require('@playwright/test/lib/utils/utils');18console.log(toModifiers('Control+Shift+KeyT'));19const { toModifiers } = require('@playwright/test/lib/utils/utils');20console.log(toModifiers('Control+Shift+KeyT'));21const { toModifiers } = require('@playwright/test/lib/utils/utils');22console.log(toModifiers('Control+Shift+KeyT'));23const { toModifiers } = require('@playwright/test/lib/utils/utils');24console.log(toModifiers('Control+Shift+KeyT'));25const { toModifiers } = require('@playwright/test/lib/utils/utils');
Using AI Code Generation
1const { toModifiers } = require('playwright/lib/server/keyboard.js');2console.log(toModifiers(['Meta', 'Shift', 'Control']));3const { toModifiers } = require('playwright/lib/server/keyboard.js');4console.log(toModifiers(['Meta', 'Shift', 'Control']));5const { toModifiers } = require('playwright/lib/server/keyboard.js');6console.log(toModifiers(['Meta', 'Shift', 'Control']));7const { toModifiers } = require('playwright/lib/server/keyboard.js');8console.log(toModifiers(['Meta', 'Shift', 'Control']));9const { toModifiers } = require('playwright/lib/server/keyboard.js');10console.log(toModifiers(['Meta', 'Shift', 'Control']));11const { toModifiers } = require('playwright/lib/server/keyboard.js');12console.log(toModifiers(['Meta', 'Shift', 'Control']));13const { toModifiers } = require('playwright/lib/server/keyboard.js');14console.log(toModifiers(['Meta', 'Shift', 'Control']));15const { toModifiers } = require('playwright/lib/server/keyboard.js');16console.log(toModifiers(['Meta', 'Shift', 'Control']));17const { toModifiers } = require('playwright/lib/server/keyboard.js');18console.log(toModifiers(['Meta', 'Shift', 'Control']));19const { toModifiers } = require('playwright/lib/server/keyboard.js');20console.log(toModifiers(['Meta', 'Shift', 'Control']));21const { toModifiers } = require('playwright/lib/server/keyboard.js');22console.log(toModifiers(['Meta', 'Shift', 'Control']));23const { toModifiers } = require('playwright/lib/server/keyboard.js');24console.log(toModifiers(['Meta', '
Using AI Code Generation
1const { toModifiers } = require('playwright/lib/utils/utils');2console.log(toModifiers('ctrl+shift+alt+meta'));3console.log(toModifiers('control+shift+alt+meta'));4console.log(toModifiers('ctrl+shift+alt'));5console.log(toModifiers('ctrl+shift'));6console.log(toModifiers('ctrl'));7console.log(toModifiers('shift'));8console.log(toModifiers('alt'));9console.log(toModifiers('meta'));10const { toModifiers } = require('playwright/lib/utils/utils');11console.log(toModifiers('ctrl+shift+alt+meta'));12console.log(toModifiers('control+shift+alt+meta'));13console.log(toModifiers('ctrl+shift+alt'));14console.log(toModifiers('ctrl+shift'));15console.log(toModifiers('ctrl'));16console.log(toModifiers('shift'));17console.log(toModifiers('alt'));18console.log(toModifiers('meta'));19const { toModifiers } = require('playwright/lib/utils/utils');20console.log(toModifiers('ctrl+shift+alt+meta'));21console.log(toModifiers('control+shift+alt+meta'));22console.log(toModifiers('ctrl+shift+alt'));23console.log(toModifiers('ctrl+shift'));24console.log(toModifiers('ctrl'));25console.log(toModifiers('shift'));
Using AI Code Generation
1const modifiers = require('@playwright/test/lib/utils').toModifiers;2console.log(modifiers);3const modifiers = require('@playwright/test/lib/utils').toModifiers();4console.log(modifiers);5const modifiers = require('@playwright/test/lib/utils').toModifiers('Shift');6console.log(modifiers);7const modifiers = require('@playwright/test/lib/utils').toModifiers('Shift', 'Control');8console.log(modifiers);9const modifiers = require('@playwright/test/lib/utils').toModifiers('Shift', 'Control', 'Alt');10console.log(modifiers);11const modifiers = require('@playwright/test/lib/utils').toModifiers('Shift', 'Control', 'Alt', 'Meta');12console.log(modifiers);13const modifiers = require('@playwright/test/lib/utils').toModifiers('Shift', 'Control', 'Alt', 'Meta', 'Custom');14console.log(modifiers);15const modifiers = require('@playwright/test/lib/utils').toModifiers('Shift', 'Control', 'Alt', 'Meta', 'Custom', 'Shift');16console.log(modifiers);17const modifiers = require('@playwright/test/lib/utils').toModifiers('Shift', 'Control', 'Alt', 'Meta', 'Custom', 'Shift', 'Control');18console.log(modifiers);19const modifiers = require('@playwright/test/lib
Using AI Code Generation
1const internal = require('playwright/lib/internal');2const modifiers = internal.toModifiers('Shift+Control+Alt+Meta+KeyA');3console.log(modifiers)4const internal = require('playwright/lib/internal');5const modifiers = internal.toModifiers('Shift+Control+Alt+Meta+KeyA');6console.log(modifiers)7const internal = require('playwright/lib/internal');8const modifiers = internal.toModifiers('Shift+Control+Alt+Meta+KeyA');9console.log(modifiers)10const internal = require('playwright/lib/internal');11const modifiers = internal.toModifiers('Shift+Control+Alt+Meta+KeyA');12console.log(modifiers)13const internal = require('playwright/lib/internal');14const modifiers = internal.toModifiers('Shift+Control+Alt+Meta+KeyA');15console.log(modifiers)16const internal = require('playwright/lib/internal');17const modifiers = internal.toModifiers('Shift+Control+Alt+Meta+KeyA');18console.log(modifiers)19const internal = require('playwright/lib/internal');20const modifiers = internal.toModifiers('Shift+Control+Alt+Meta+KeyA');21console.log(modifiers)22const internal = require('playwright/lib/internal');
Using AI Code Generation
1import { toModifiers } from 'playwright/lib/server/keyboard.js';2const modifiers = toModifiers(['Shift', 'Control']);3console.log(modifiers);4import { toModifiers } from 'playwright/lib/server/keyboard.js';5const modifiers = toModifiers(['Shift', 'Control']);6console.log(modifiers);
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.
Get 100 minutes of automation test minutes FREE!!