Best JavaScript code snippet using playwright-internal
graph.serie.box.js
Source:graph.serie.box.js
1import {2 extend,3 guid,4 throwError,5 emptyDom6}7from '../graph.util.js';8import Serie from './graph.serie.js';9const defaultOptions = {10 orientation: 'y',11 maxBoxWidth: 20,12 defaultStyle: {13 meanLineColor: 'rgb( 100, 0, 0 )',14 meanLineWidth: 2,15 boxAboveLineWidth: 1,16 boxAboveLineColor: 'rgb( 0, 0, 0 )',17 boxAboveFillColor: 'transparent',18 boxAboveFillOpacity: 1,19 boxBelowLineWidth: 1,20 boxBelowLineColor: 'rgb( 0, 0, 0 )',21 boxBelowFillColor: 'transparent',22 boxBelowFillOpacity: 1,23 barAboveLineColor: 'rgba( 0, 0, 0, 1 )',24 barAboveLineWidth: 1,25 barBelowLineColor: 'rgba( 0, 0, 0, 1 )',26 barBelowLineWidth: 1,27 outlierLineWidth: 1,28 outlierLineColor: 'rgb( 255, 255, 255 )',29 outlierFillColor: 'rgb( 0, 0, 0 )',30 outlierFillOpacity: 131 }32};33/**34 * @static35 * @extends Serie36 * @example graph.newSerie( name, options, "scatter" );37 * @see Graph#newSerie38 */39class SerieBox extends Serie {40 constructor( graph, name, options, defaultInherited = {} ) {41 super( graph, name, options, extend( true, {}, defaultOptions, defaultInherited ) );42 this.pathDom = document.createElementNS( this.graph.ns, 'path' );43 this.groupMain.appendChild( this.pathDom );44 // Creates an empty style variable45 this.styles = {};46 // Unselected style47 this.styles.unselected = this.options.defaultStyle;48 }49 /**50 * Sets the data of the bar serie51 * @param {Object} data52 * @example serie.setData( [ { x: 'cat', Q2: valMean, Q1: valBoxMin, Q3: valBoxMax, whiskers: [ val1, val2 ], outliers: [ ...yList ] } ] );53 * @return {SerieBar} The current serie instance54 */55 setData( data, noRescale ) {56 this.data = data;57 if ( !Array.isArray( data ) ) {58 return;59 }60 let axisref, axisval, methodref, methodval, blnX;61 if ( this.options.orientation == 'y' ) {62 axisref = this.getXAxis();63 axisval = this.getYAxis();64 methodref = this._checkX.bind( this );65 methodval = this._checkY.bind( this );66 blnX = true;67 this.minY = data[ 0 ].Q2;68 this.maxY = data[ 0 ].Q2;69 this.maxX = data[ 0 ].x;70 this.minX = data[ 0 ].x;71 } else {72 axisref = this.getYAxis();73 axisval = this.getXAxis();74 methodref = this._checkY.bind( this );75 methodval = this._checkX.bind( this );76 blnX = false;77 this.minX = data[ 0 ].Q2;78 this.maxX = data[ 0 ].Q2;79 this.maxY = data[ 0 ].y;80 this.minY = data[ 0 ].y;81 }82 if ( noRescale ) {83 methodref = function() {};84 methodval = function() {};85 }86 if ( !axisref || !axisval ) {87 throwError( 'Error in setting data of the box serie. The X and Y axes must be set beforehand' );88 }89 for ( var i in this.data ) {90 if ( blnX ) {91 methodref( this.data[ i ].x );92 this.data[ i ].pos = this.data[ i ].x;93 } else {94 methodref( this.data[ i ].y );95 this.data[ i ].pos = this.data[ i ].y;96 }97 if ( this.data[ i ].Q3 ) {98 methodval( this.data[ i ].Q3 );99 }100 if ( this.data[ i ].Q1 ) {101 methodval( this.data[ i ].Q1 );102 }103 if ( this.data[ i ].whiskers ) {104 if ( Array.isArray( this.data[ i ].whiskers ) ) {105 if ( this.data[ i ].whiskers.length > 0 ) {106 methodval( this.data[ i ].whiskers[ 0 ] );107 }108 if ( this.data[ i ].whiskers.length > 1 ) {109 methodval( this.data[ i ].whiskers[ 1 ] );110 }111 } else {112 methodval( this.data[ i ].whiskers );113 this.data[ i ].whiskers = [ this.data[ i ].whiskers ];114 }115 } else {116 this.data[ i ].whiskers = [];117 }118 if ( Array.isArray( this.data[ i ].outliers ) ) {119 this.data[ i ].outliers.map( ( val ) => methodval( val ) );120 } else {121 this.data[ i ].outliers = [];122 }123 }124 this.dataHasChanged();125 this.graph.updateDataMinMaxAxes();126 return this;127 }128 _style( type, styleValue, selectionType = 'unselected', applyToSelected = false ) {129 this.styles[ selectionType ] = this.styles[ selectionType ] || {};130 this.styles[ selectionType ][ type ] = styleValue;131 if ( applyToSelected ) {132 this._set( type, styleValue, 'selected' );133 }134 this.styleHasChanged( selectionType );135 return this;136 }137 _gstyle( type, selectionType ) {138 return this.getStyle( selectionType )[ type ];139 }140 /**141 * Retrives a selection object142 * @param {String} [ selectionType = "unselected" ] - The selection type143 * @returns {Object} The selection object144 */145 getStyle( selectionType = 'unselected' ) {146 return this.styles[ selectionType ] || {};147 }148 /**149 * Sets the mean line color150 * @param {String} color - The mean line color151 * @returns {SerieBox} The current serie instance152 */153 setMeanLineColor() {154 return this._style( 'meanLineColor', ...arguments );155 }156 /**157 * Returns the mean line color158 * @return {String} The mean line color159 */160 getMeanLineColor() {161 return this._gstyle( 'meanLineColor', ...arguments );162 }163 setStyle( style, selectionType = 'unselected' ) {164 this.styles[ selectionType ] = extend( {}, this.default().defaultStyle, this.styles.unselected, style );165 this.styleHasChanged( selectionType );166 }167 /**168 * Sets the mean line width169 * @param {Number} width - The line width170 * @returns {SerieBox} The current serie instance171 */172 setMeanLineWidth() {173 return this._style( 'meanLineWidth', ...arguments );174 }175 /**176 * Returns the mean line width177 * @return {Number} The mean line width178 */179 getMeanLineWidth() {180 return this._gstyle( 'meanLineWidth', ...arguments );181 }182 /**183 * Sets the box line color184 * @param {Number} color - The color of the box above the median185 * @returns {SerieBox} The current serie instance186 */187 setBoxAboveLineColor() {188 return this._style( 'boxAboveLineColor', ...arguments );189 }190 /**191 * Returns the box line color192 * @return {String} The line color of the box above the median193 */194 getBoxAboveLineColor() {195 return this._gstyle( 'boxAboveLineColor', ...arguments );196 }197 /**198 * Sets the fill color199 * @param {Number} color - The color of the box below the median200 * @returns {SerieBox} The current serie instance201 */202 setBoxBelowLineColor() {203 return this._style( 'boxBelowLineColor', ...arguments );204 }205 /**206 * Returns the fill color207 * @return {String} The line color of the box below the median208 */209 getBoxBelowLineColor() {210 return this._gstyle( 'boxBelowLineColor', ...arguments );211 }212 /**213 * Sets the fill color214 * @param {Number} width - The contour width of the box above the median215 * @returns {SerieBox} The current serie instance216 */217 setBoxAboveLineWidth() {218 return this._style( 'boxAboveLineWidth', ...arguments );219 }220 /**221 * Returns the line width of the box above the median222 * @return {Number} The line width of the box above the median223 */224 getBoxAboveLineWidth() {225 return this._gstyle( 'boxAboveLineWidth', ...arguments );226 }227 /**228 * Sets the fill color229 * @param {Number} width - The contour width of the box below the median230 * @returns {SerieBox} The current serie instance231 */232 setBoxBelowLineWidth() {233 return this._style( 'boxBelowLineWidth', ...arguments );234 }235 /**236 * Returns the line width of the box below the median237 * @return {Number} The line width of the box below the median238 */239 getBoxBelowLineWidth() {240 return this._gstyle( 'boxBelowLineWidth', ...arguments );241 }242 /**243 * Sets the fill color244 * @param {String} color - The fill color of the box above the median245 * @returns {SerieBox} The current serie instance246 */247 setBoxAboveFillColor() {248 return this._style( 'boxAboveFillColor', ...arguments );249 }250 /**251 * Returns the fill color of the box above the median252 * @return {String} The fill color of the box above the median253 */254 getBoxAboveFillColor() {255 return this._gstyle( 'boxAboveFillColor', ...arguments );256 }257 /**258 * Sets the fill color259 * @param {String} color - The fill color of the box below the median260 * @returns {SerieBox} The current serie instance261 */262 setBoxBelowFillColor() {263 return this._style( 'boxBelowFillColor', ...arguments );264 }265 /**266 * Returns the fill color of the box below the median267 * @return {String} The fill color of the box below the median268 */269 getBoxBelowFillColor() {270 return this._gstyle( 'boxBelowFillColor', ...arguments );271 }272 /**273 * Sets the fill color274 * @param {Number} opacity - The fill opacity of the box above the median275 * @returns {SerieBox} The current serie instance276 */277 setBoxAboveFillOpacity() {278 return this._style( 'boxAboveFillOpacity', ...arguments );279 }280 /**281 * Returns the fill opacity of the box above the median282 * @return {Number} The fill opacity of the box above the median283 */284 getBoxAboveFillOpacity() {285 return this._gstyle( 'boxAboveFillOpacity', ...arguments );286 }287 /**288 * Sets the fill color289 * @param {Number} opacity - The fill opacity of the box below the median290 * @returns {SerieBox} The current serie instance291 */292 setBoxBelowFillOpacity() {293 return this._style( 'boxBelowFillOpacity', ...arguments );294 }295 /**296 * Returns the fill opacity of the box below the median297 * @return {Number} The fill opacity of the box below the median298 */299 getBoxBelowFillOpacity() {300 return this._gstyle( 'boxBelowFillOpacity', ...arguments );301 }302 /**303 * Sets the whisker color304 * @param {String} color - The line color of the whisker above the median305 * @returns {SerieBox} The current serie instance306 */307 setBarAboveLineColor() {308 return this._style( 'barAboveLineColor', ...arguments );309 }310 /**311 * Returns the line color of the whisker above the median312 * @return {String} The line color of the whisker above the median313 */314 getBarAboveLineColor() {315 return this._gstyle( 'barAboveLineColor', ...arguments );316 }317 /**318 * Sets the fill color319 * @param {String} color - The line color of the whisker below the median320 * @returns {SerieBox} The current serie instance321 */322 setBarBelowLineColor() {323 return this._style( 'barBelowLineColor', ...arguments );324 }325 /**326 * Returns the line color of the whisker below the median327 * @return {String} The line color of the whisker below the median328 */329 getBarBelowLineColor() {330 return this._gstyle( 'barBelowLineColor', ...arguments );331 }332 /**333 * Sets the fill color334 * @param {Number} width - The line width of the whisker above the median335 * @returns {SerieBox} The current serie instance336 */337 setBarAboveLineWidth() {338 return this._style( 'barAboveLineWidth', ...arguments );339 }340 /**341 * Returns the line width of the whisker above the median342 * @return {Number} The line width of the whisker above the median343 */344 getBarAboveLineWidth() {345 return this._gstyle( 'barAboveLineWidth', ...arguments );346 }347 /**348 * Sets the fill color349 * @param {Number} width - The line width of the whisker below the median350 * @returns {SerieBox} The current serie instance351 */352 setBarBelowLineWidth() {353 return this._style( 'barBelowLineWidth', ...arguments );354 }355 /**356 * Returns the line width of the whisker below the median357 * @return {Number} The line width of the whisker below the median358 */359 getBarBelowLineWidth() {360 return this._gstyle( 'barBelowLineWidth', ...arguments );361 }362 /**363 * Sets the fill color364 * @param {String} color - The outlier stroke color365 * @returns {SerieBox} The current serie instance366 */367 setOutlierLineColor() {368 return this._style( 'outlierLineColor', ...arguments );369 }370 /**371 * Returns the line color of the outliers372 * @return {String} The line color of the outliers373 */374 getOutlierLineColor() {375 return this._gstyle( 'outlierLineColor', ...arguments );376 }377 /**378 * Sets the stroke width379 * @param {Number} width - The outlier stroke width380 * @returns {SerieBox} The current serie instance381 */382 setOutlierLineWidth() {383 return this._style( 'outlierLineWidth', ...arguments );384 }385 /**386 * Returns the line width of the outliers387 * @return {Number} The line width of the outliers388 */389 getOutlierLineWidth() {390 return this._gstyle( 'outlierLineWidth', ...arguments );391 }392 /**393 * Sets the fill color394 * @param {String} color - The outlier fill color395 * @returns {SerieBox} The current serie instance396 */397 setOutlierFillColor() {398 return this._style( 'outlierFillColor', ...arguments );399 }400 /**401 * Returns the fill color of the outliers402 * @return {String} The fill color of the outliers403 */404 getOutlierFillColor() {405 return this._gstyle( 'outlierFillColor', ...arguments );406 }407 /**408 * Sets the outlier fill opacity409 * @param {Number} opacity - The outlier fill opacity410 * @returns {SerieBox} The current serie instance411 */412 setOutlierFillOpacity() {413 return this._style( 'outlierFillOpacity', ...arguments );414 }415 /**416 * Returns the fill opacity of the outliers417 * @return {Number} The fill opacity of the outliers418 */419 getOutlierFillOpacity() {420 return this._gstyle( 'outlierFillOpacity', ...arguments );421 }422 /**423 * Reapply the current style to the serie lines elements. Mostly used internally424 * @returns {SerieBox} The current serie instance425 */426 applyLineStyles() {427 this.applyLineStyle( this.pathDom );428 }429 /**430 * Applies the current style to a line element. Mostly used internally431 * @memberof SerieBar432 */433 applyLineStyle( line ) {434 line.setAttribute( 'stroke', this.getLineColor() );435 line.setAttribute( 'stroke-width', this.getLineWidth() );436 line.removeAttribute( 'stroke-dasharray' );437 line.setAttribute( 'fill', this.getFillColor() );438 line.setAttribute( 'fill-opacity', this.getFillOpacity() || 1 );439 }440 draw() {441 if ( !this.data ) {442 return;443 }444 let position;445 let axis = this.options.orientation == 'y' ? this.getYAxis() : this.getXAxis();446 let axis2 = this.options.orientation == 'y' ? this.getXAxis() : this.getYAxis();447 let boxOtherDimension; // width or height of the box448 let useCategories = false;449 let mean, boxAbove, boxBelow, barAbove, barBelow, outliers, posAbove, posBelow;450 let categoryNumber;451 emptyDom( this.groupMain );452 if ( axis2.getType() == 'category' ) {453 boxOtherDimension = axis2.getRelPx( 0.8 / ( this.nbCategories ) );454 useCategories = true;455 } else {456 // Get all the spacing and determine the smallest one457 boxOtherDimension = this.options.maxBoxWidth;458 for ( var i = 0, l = this.data.length; i < l - 1; i++ ) {459 boxOtherDimension = Math.max( 5, Math.min( boxOtherDimension, Math.abs( axis2.getPx( this.data[ i + 1 ].x ) - axis2.getPx( this.data[ i ].x ) ) ) );460 }461 }462 for ( var i = 0, l = this.data.length; i < l; i++ ) {463 if ( axis2.getType() == 'category' ) {464 let cat = this.options.orientation == 'y' ? this.data[ i ].x : this.data[ i ].y;465 if ( !this.categoryIndices.hasOwnProperty( cat ) ) {466 if ( Array.isArray( this._linkedToScatterSeries ) ) {467 for ( let scatter_serie of this._linkedToScatterSeries ) {468 if ( scatter_serie.categoryIndices.hasOwnProperty( cat ) ) {469 position = [ axis2.getPos( scatter_serie.categoryIndices[ cat ] ) + 1.2 * boxOtherDimension / 2 ];470 if ( this.options.orientation == 'y' ) {471 axis = scatter_serie.getYAxis();472 } else {473 axis = scatter_serie.getXAxis();474 }475 break;476 }477 }478 }479 } else {480 position = [ axis2.getPos( this.categoryIndices[ cat ] ) + 1.2 * boxOtherDimension / 2 ];481 }482 } else {483 position = [ axis2.getPos( this.options.orientation == 'y' ? this.data[ i ].x : this.data[ i ].y ), boxOtherDimension ];484 }485 mean = axis.getPos( this.data[ i ].Q2 );486 boxAbove = axis.getPos( this.data[ i ].Q3 );487 boxBelow = axis.getPos( this.data[ i ].Q1 );488 this.data[ i ].whiskers.map( ( val ) => {489 if ( val < this.data[ i ].Q1 ) {490 barBelow = axis.getPos( val );491 } else {492 barAbove = axis.getPos( val );493 }494 } );495 outliers = this.data[ i ].outliers.map( ( val ) => axis.getPos( val ) );496 var lineMean = document.createElementNS( this.graph.ns, 'line' );497 this.applyMeanStyle( lineMean );498 var rectAbove = document.createElementNS( this.graph.ns, 'rect' );499 var rectBelow = document.createElementNS( this.graph.ns, 'rect' );500 if ( this.options.orientation == 'y' ) {501 rectAbove.setAttribute( 'width', boxOtherDimension );502 rectAbove.setAttribute( 'x', position[ 0 ] - boxOtherDimension / 2 );503 rectBelow.setAttribute( 'width', boxOtherDimension );504 rectBelow.setAttribute( 'x', position[ 0 ] - boxOtherDimension / 2 );505 lineMean.setAttribute( 'x1', position[ 0 ] - boxOtherDimension / 2 );506 lineMean.setAttribute( 'x2', position[ 0 ] + boxOtherDimension / 2 );507 lineMean.setAttribute( 'y1', mean );508 lineMean.setAttribute( 'y2', mean );509 } else {510 rectAbove.setAttribute( 'height', boxOtherDimension );511 rectAbove.setAttribute( 'y', position[ 0 ] - boxOtherDimension / 2 );512 rectBelow.setAttribute( 'height', boxOtherDimension );513 rectBelow.setAttribute( 'y', position[ 0 ] - boxOtherDimension / 2 );514 lineMean.setAttribute( 'y1', position[ 0 ] - boxOtherDimension / 2 );515 lineMean.setAttribute( 'y2', position[ 0 ] + boxOtherDimension / 2 );516 lineMean.setAttribute( 'x1', mean );517 lineMean.setAttribute( 'x2', mean );518 }519 this.boxPos( rectAbove, mean, boxAbove, this.options.orientation == 'x' );520 this.boxPos( rectBelow, mean, boxBelow, this.options.orientation == 'x' );521 this.applyBoxStyle( rectAbove, rectBelow );522 var whiskerAbove = document.createElementNS( this.graph.ns, 'line' );523 var whiskerBelow = document.createElementNS( this.graph.ns, 'line' );524 if ( this.options.orientation == 'y' ) {525 if ( barAbove !== undefined ) {526 whiskerAbove.setAttribute( 'y1', boxAbove );527 whiskerAbove.setAttribute( 'y2', barAbove );528 whiskerAbove.setAttribute( 'x1', position[ 0 ] );529 whiskerAbove.setAttribute( 'x2', position[ 0 ] );530 }531 if ( barBelow !== undefined ) {532 whiskerBelow.setAttribute( 'y1', boxBelow );533 whiskerBelow.setAttribute( 'y2', barBelow );534 whiskerBelow.setAttribute( 'x1', position[ 0 ] );535 whiskerBelow.setAttribute( 'x2', position[ 0 ] );536 }537 } else {538 if ( barAbove !== undefined ) {539 whiskerAbove.setAttribute( 'x1', boxAbove );540 whiskerAbove.setAttribute( 'x2', barAbove );541 whiskerAbove.setAttribute( 'y1', position[ 0 ] );542 whiskerAbove.setAttribute( 'y2', position[ 0 ] );543 }544 if ( barBelow !== undefined ) {545 whiskerBelow.setAttribute( 'x1', boxBelow );546 whiskerBelow.setAttribute( 'x2', barBelow );547 whiskerBelow.setAttribute( 'y1', position[ 0 ] );548 whiskerBelow.setAttribute( 'y2', position[ 0 ] );549 }550 }551 outliers.map( ( outliervalue ) => {552 let outlier = document.createElementNS( this.graph.ns, 'circle' );553 outlier.setAttribute( 'r', 2 );554 if ( this.options.orientation == 'y' ) {555 outlier.setAttribute( 'cx', position[ 0 ] );556 outlier.setAttribute( 'cy', outliervalue );557 } else {558 outlier.setAttribute( 'cy', position[ 0 ] );559 outlier.setAttribute( 'cx', outliervalue );560 }561 this.setOutlierStyle( outlier );562 this.groupMain.appendChild( outlier );563 } );564 if ( barAbove !== undefined ) {565 this.groupMain.appendChild( whiskerAbove );566 }567 if ( barBelow !== undefined ) {568 this.groupMain.appendChild( whiskerBelow );569 }570 if ( boxAbove !== undefined ) {571 this.groupMain.appendChild( rectAbove );572 }573 if ( boxBelow !== undefined ) {574 this.groupMain.appendChild( rectBelow );575 }576 this.groupMain.appendChild( lineMean );577 this.applyWhiskerStyle( whiskerAbove, whiskerBelow );578 }579 }580 applyBoxStyle( above, below ) {581 above.setAttribute( 'stroke', this.getBoxAboveLineColor() );582 above.setAttribute( 'stroke-width', this.getBoxAboveLineWidth() );583 if ( this.getBoxAboveFillColor() !== undefined ) {584 above.setAttribute( 'fill', this.getBoxAboveFillColor() );585 }586 if ( this.getBoxAboveFillOpacity() !== undefined ) {587 above.setAttribute( 'fill-opacity', this.getBoxAboveFillOpacity() );588 }589 below.setAttribute( 'stroke', this.getBoxBelowLineColor() );590 below.setAttribute( 'stroke-width', this.getBoxBelowLineWidth() );591 if ( this.getBoxBelowFillColor() !== undefined ) {592 below.setAttribute( 'fill', this.getBoxBelowFillColor() );593 }594 if ( this.getBoxAboveFillOpacity() !== undefined ) {595 below.setAttribute( 'fill-opacity', this.getBoxBelowFillOpacity() );596 }597 }598 applyWhiskerStyle( above, below ) {599 above.setAttribute( 'stroke', this.getBarAboveLineColor() );600 above.setAttribute( 'stroke-width', this.getBarAboveLineWidth() );601 below.setAttribute( 'stroke', this.getBarBelowLineColor() );602 below.setAttribute( 'stroke-width', this.getBarBelowLineWidth() );603 }604 applyMeanStyle( line ) {605 line.setAttribute( 'stroke', this.getMeanLineColor() );606 line.setAttribute( 'stroke-width', this.getMeanLineWidth() );607 }608 setOutlierStyle( outlier ) {609 outlier.setAttribute( 'stroke', this.getOutlierLineColor() );610 outlier.setAttribute( 'stroke-width', this.getOutlierLineWidth() );611 if ( this.getBoxBelowFillColor() !== undefined ) {612 outlier.setAttribute( 'fill', this.getOutlierFillColor() );613 }614 if ( this.getBoxAboveFillOpacity() !== undefined ) {615 outlier.setAttribute( 'fill-opacity', this.getOutlierFillOpacity() );616 }617 }618 /**619 * Returns the index of a category based on its name620 * @param {String} name - The name of the category621 */622 getCategoryIndex( name ) {623 if ( !this.categories ) {624 throw new Error( 'No categories were defined. Probably axis.setSeries was not called' );625 }626 for ( var i = 0; i < this.categories.length; i++ ) {627 if ( this.categories[ i ].name == name ) {628 return i;629 }630 }631 return false;632 }633 // Markers now allowed634 setMarkers() {}635 boxPos( box, mean, extremity, blnX ) {636 if ( mean > extremity ) {637 box.setAttribute( blnX ? 'x' : 'y', extremity );638 box.setAttribute( blnX ? 'width' : 'height', mean - extremity );639 } else {640 box.setAttribute( blnX ? 'x' : 'y', mean );641 box.setAttribute( blnX ? 'width' : 'height', extremity - mean );642 }643 }644 getUsedCategories() {645 let xymode = this.options.orientation == 'y' ? 'x' : 'y';646 let categories = this.data.map( ( d ) => d[ xymode ] );647 if ( Array.isArray( this._linkedToScatterSeries ) ) {648 this._linkedToScatterSeries.map( ( scatter_serie ) => {649 scatter_serie.getUsedCategories().map( ( scatter_serie_cat ) => {650 let index;651 if ( ( index = categories.indexOf( scatter_serie_cat ) ) > -1 ) {652 categories.splice( index, 1 );653 }654 } );655 } );656 }657 return categories;658 }659 linkToScatterSerie( ...series ) {660 this._linkedToScatterSeries = series;661 }662}...
perlin_grid.js
Source:perlin_grid.js
1var vertexShader = `varying vec2 vUv;2void main()3{4 vUv = uv;5 vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );6 gl_Position = projectionMatrix * mvPosition;7}`;8var fragmentShader = `9uniform float r;10uniform float g;11uniform float b;12uniform float distance;13uniform float pulse;14uniform float rows;15uniform float cols;16varying vec2 vUv;17float checkerRows = 1.5;18float checkerCols = 2.0;19void main( void ) {20 vec2 position = abs(-1.0 + 2.0 * vUv);21 float edging = abs((pow(position.y, 5.0) + pow(position.x, 5.0)) / 1.0);22 float perc = 0.25 + distance * edging * 0.75;23 vec2 checkPosition = vUv;24 25 float checkerX = mod(checkPosition.x, 1.0 / rows) * rows; // loop of 0 to 1 per row: /|/|/|//26 checkerX = abs(checkerX - 0.5) * 2.0; // make up and down: /\/\/\ 27 checkerX = pow(checkerX, 3.0); // power to sharpen edges: \__/\__/28 float checkerY = mod(checkPosition.y, 1.0 / cols) * cols;29 checkerY = abs(checkerY - 0.5) * 2.0;30 checkerY = pow(checkerY, 3.0);31 float checkerMod = 0.0;32 if (rows > 1.0 && floor(checkPosition.x * rows) == checkerMod) {33 perc = 2.0;34 }35 if (cols > 1.0 && floor(checkPosition.y * cols) == checkerMod) {36 perc = 2.0;37 }38 // float checker = (checkerX * checkerY) * 2.0;39 float checker = (checkerX + checkerY) * 0.5;40 float r1 = r * checker + 0.1;41 float g1 = g * checker + 0.05;42 float b1 = b * checker + 0.2;43 float red = r1 * perc + pulse;44 float green = g1 * perc + pulse;45 float blue = b1 * perc + pulse + 0.05;46 // float red = r;47 // float green = g;48 // float blue = b;49 gl_FragColor = vec4(red, green, blue, 1.0);50}`;51var perlin_grid = function(noise) {52 var stage = document.createElement("div");53 var camera, scene, renderer;54 var mouse = {x: 0, y: 0};55 var camPos = {x: 0, y: 0, z: 10};56 var sw = window.innerWidth, sh = window.innerHeight;57 var size = {58 width: 300,59 height: 100,60 depth: 300,61 }62 var edgeSize = 50;63 var gridUnits = 7;64 var gridAbove = [];65 var gridBelow = [];66 var seed = Math.random();67 var holderAbove, holderBelow;68 function num(min, max) { return Math.random() * (max - min) + min; }69 function createMaterial(rows, cols, colourRand, distance) {70 var colourBase = {r: 0.7, g: 0.3, b: 0.6};71 var colour = {72 r: colourBase.r + colourRand.r,73 g: colourBase.g + colourRand.g,74 b: colourBase.b + colourRand.b75 }76 var uniforms = {77 r: { type: "f", value: colour.r},78 g: { type: "f", value: colour.g},79 b: { type: "f", value: colour.b},80 // distanceX: { type: "f", value: 1.0},81 distance: { type: "f", value: distance},82 pulse: { type: "f", value: 0},83 rows: { type: "f", value: rows},84 cols: { type: "f", value: cols},85 };86 var material = new THREE.ShaderMaterial( {87 uniforms: uniforms,88 vertexShader: vertexShader,89 fragmentShader: fragmentShader90 });91 return material;92 }93 function cube(options) {94 var width = options.dimensions.width;95 var height = options.dimensions.height;96 var depth = options.dimensions.depth;97 var colour = options.colour;98 var checker = options.checker;99 var distance = options.distance;100 // these coloured vars are just for debugging101 var shaderRed = createMaterial(checker[0][0], checker[0][1], colour, distance);102 var shaderYellow = createMaterial(checker[1][0], checker[1][1], colour, distance);103 var shaderGreen = createMaterial(checker[2][0], checker[2][1], colour, distance);104 var shaderBlue = createMaterial(checker[3][0], checker[3][1], colour, distance);105 var shaderCyan = createMaterial(checker[4][0], checker[4][1], colour, distance);106 var shaderMagenta = createMaterial(checker[5][0], checker[5][1], colour, distance);107 // const material = new THREE.MeshPhongMaterial({108 // color: props.colour,109 // emissive: 0x803000,110 // });111 var geometry = new THREE.BoxGeometry(width, height, depth);112 var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial([113 shaderRed,114 shaderYellow,115 shaderGreen,116 shaderBlue,117 shaderCyan, 118 shaderMagenta119 ]));120 // mesh.colours = colours;121 return mesh;122 }123 const draw = (x, z, distanceFromCentre) => {124 var colourRand = {125 r: num(0, 0.5),126 g: num(0, 0.5),127 b: num(0, 0.5)128 }129 var vertProps = {130 width: edgeSize, 131 height: size.height, 132 depth: edgeSize,133 }134 var distance = size.width / 2 - edgeSize; // only because size.width == size.depth135 var holder = new THREE.Group();136 var verticalEdgeBL = cube({ // back left137 dimensions: vertProps,138 checker: [[1,2],[1,2],[1,1],[1,1],[1,2],[1,2]],139 colour: colourRand, 140 distance: distanceFromCentre141 });142 verticalEdgeBL.position.set(-distance, 0, -distance)143 holder.add(verticalEdgeBL);144 var verticalEdgeBR = cube({145 dimensions: vertProps,146 checker: [[1,2],[1,2],[1,1],[1,1],[1,2],[1,2]],147 colour: colourRand, 148 distance: distanceFromCentre149 });150 verticalEdgeBR.position.set(distance, 0, -distance)151 holder.add(verticalEdgeBR);152 var verticalEdgeFL = cube({153 dimensions: vertProps,154 checker: [[1,2],[1,2],[1,1],[1,1],[1,2],[1,2]],155 colour: colourRand, 156 distance: distanceFromCentre157 });158 verticalEdgeFL.position.set(-distance, 0, distance)159 holder.add(verticalEdgeFL);160 var verticalEdgeFR = cube({161 dimensions: vertProps,162 checker: [[1,2],[1,2],[1,1],[1,1],[1,2],[1,2]],163 colour: colourRand, 164 distance: distanceFromCentre165 });166 verticalEdgeFR.position.set(distance, 0, distance)167 holder.add(verticalEdgeFR); // front right168 var horizProps = {169 width: size.width - edgeSize, 170 height: edgeSize,171 depth: edgeSize,172 }173 var horizontalEdgeF = cube({174 dimensions: horizProps,175 checker: [[1,1],[1,1],[5,1],[5,1],[5,1],[5,1]],176 colour: colourRand, 177 distance: distanceFromCentre178 });179 horizontalEdgeF.position.set(0, (size.height + edgeSize) / 2, -distance)180 holder.add(horizontalEdgeF);181 var horizontalEdgeB = cube({182 dimensions: horizProps,183 checker: [[1,1],[1,1],[5,1],[5,1],[5,1],[5,1]],184 colour: colourRand, 185 distance: distanceFromCentre186 });187 horizontalEdgeB.position.set(0, (size.height + edgeSize) / 2, distance)188 holder.add(horizontalEdgeB);189 return holder;190 }191 function init() {192 return;193 scene = new THREE.Scene();194 camera = new THREE.PerspectiveCamera( 90, sw / sh, 1, 10000 );195 camera.position.set( 0, 100, 500 );196 scene.add( camera );197 var light = new THREE.DirectionalLight( 0xffffff, 2 );198 light.position.set( 1, 1, 1 ).normalize();199 scene.add( light );200 var light = new THREE.DirectionalLight( 0xff00ff, 2 );201 light.position.set( -1, 0, 0 ).normalize();202 scene.add( light );203 renderer = new THREE.WebGLRenderer({antialias: true});204 // renderer.sortObjects = false;205 renderer.setSize( sw, sh );206 holderAbove = new THREE.Group();207 scene.add(holderAbove);208 holderBelow = new THREE.Group();209 scene.add(holderBelow);210 for (var x = 0; x < gridUnits; x++) {211 for (var z = 0; z < gridUnits; z++) {212 var px = (x - gridUnits / 2 + 0.5) * size.width;213 var py = 0;214 var pz = (z - gridUnits / 2 + 0.5) * size.depth;215 var distanceFromCentre = 1 - Math.sqrt(px * px + pz * pz) / 1200;216 // con.log("distanceFromCentre", distanceFromCentre)217 var boxAbove = draw(x, z, distanceFromCentre);218 boxAbove.position.set(px, py, pz);219 holderAbove.add(boxAbove);220 gridAbove.push(boxAbove);221 222 var boxBelow = draw(x, z, distanceFromCentre);223 boxBelow.position.set(px, py, pz);224 boxBelow.rotation.set(Math.PI, Math.PI / 2, 0);225 holderBelow.add(boxBelow);226 gridBelow.push(boxBelow);227 }228 }229 // var boxAbove = draw(0, 0, 1);230 // scene.add(boxAbove);231 stage.appendChild(renderer.domElement);232 animate(0);233 }234 function listen(eventNames, callback) {235 for (var i = 0; i < eventNames.length; i++) {236 window.addEventListener(eventNames[i], callback);237 }238 }239 listen(["resize"], function(e){240 sw = window.innerWidth;241 sh = window.innerHeight242 camera.aspect = sw / sh;243 camera.updateProjectionMatrix();244 renderer.setSize(sw, sh);245 });246 listen(["mousedown", "touchstart"], function(e) {247 e.preventDefault();248 isMouseDown = true;249 });250 listen(["mousemove", "touchmove"], function(e) {251 e.preventDefault();252 if (e.changedTouches && e.changedTouches[0]) e = e.changedTouches[0];253 mouse.x = (e.clientX / sw) * 2 - 1;254 mouse.y = -(e.clientY / sh) * 2 + 1;255 });256 listen(["mouseup", "touchend"], function(e) {257 e.preventDefault();258 isMouseDown = false;259 });260 function render(time) {261 var breathDistance = 1 + (1 + Math.sin(time * 0.004)) * 2;262 263 function renderBox(holder, value, x, z, above) {264 value = value * value * value * value; // power the fuck265 var scale = 1 + value * 50;266 var px = (x - gridUnits / 2 + 0.5) * size.width * breathDistance;267 var py = scale * size.height / 2 * above;268 var pz = (z - gridUnits / 2 + 0.5) * size.depth * breathDistance;269 holder.position.set(px, py, pz);270 // con.log('holder', scale , size.height / 2 * above)271 // con.log('holder', scale)272 // con.log("holder", holder)273 // for (var m = 0; m < holder.children.length; m++) {274 // var mesh = holder.children[m];275 // for (var n = 0; n < mesh.material.materials.length; n++) {276 // var material = mesh.material.materials[n];277 // if (Math.random() > 0.99) {278 // material.uniforms.pulse.value = 1;279 // }280 // material.uniforms.pulse.value -= material.uniforms.pulse.value * 0.1 / (1 + 1);281 // }282 // }283 }284 for (var z = 0; z < gridUnits; z++) { // using double high grid, first half is top, 2nd half is bottom285 for (var x = 0; x < gridUnits; x++) {286 var gridIndex = (x + z * gridUnits);287 var valueAbove = (noise.perlin3(x / gridUnits, z / gridUnits, seed) + 1) / 2;288 var valueBelow = (noise.perlin3(x / gridUnits, z + gridUnits * gridUnits / gridUnits, seed) + 1) / 2;289 var holderAbove = gridAbove[gridIndex];290 var holderBelow = gridBelow[gridIndex];291 renderBox(holderAbove, valueAbove, x, z, 1);292 renderBox(holderBelow, valueBelow, x, z, -1);293 }294 }295 296 seed += 0.01;297 var camDistance = 400;298 camPos.x -= (camPos.x - mouse.x * 1) * 0.02;299 camPos.y -= (camPos.y - mouse.y * 1000) * 0.05;300 // var rotY = time * 0.001 + camPos.x;301 var rotY = camPos.x * 4;302 camera.position.set(Math.sin(rotY) * camDistance, camPos.y, Math.cos(rotY) * camDistance);303 camera.lookAt( scene.position );304 renderer.render( scene, camera );305 }306 function animate(time) {307 requestAnimationFrame( animate );308 if (Math.random() > 0.99) {309 var holder = Math.random() > 0.5 ? holderAbove : holderBelow;310 TweenMax.to(holder.rotation, 0.75, {311 y: Math.PI / 2 * Math.round(num(-2, 2)),312 eade: Quad.easeInOut313 })314 }315 render(time);316 }317 return {318 init,319 stage320 };321};...
playerblockcollision.js
Source:playerblockcollision.js
1var raycaster = new THREE.Raycaster();2//bottom looking, left and right3var intBL, intBR;4//left looking top and bottom5var intLT, intLB;6//right looking top and bottom7var intRT, intRB;8var oldRays = [];9function arrEqual(arr1, arr2){10 if(arr1.length!= arr2.length){return false;}11 for(var i = 0; i < arr1.length;i++){12 if(arr1[i] != arr2[i]){13 return false;14 }15 }16 return true;17}18//left = [1,0,0];19//right = [-1,0,0];20//below = [0,1,0];21function lookDirection(direction){22 // var pVec;23 // creates a vector from the player to some point way below24 for(var i = 0; i < stage.players.length; i++){25 var farAwayPoint = new THREE.Vector3();26 var intersects =[];27 //will be bottom left then bottom right,28 //right bottom, right top,29 //left bottom, left top30 var pVec1 = new THREE.Vector3();31 var pVec2 = new THREE.Vector3();32 var intersects1 = [];33 var intersects2 = [];34 //left35 if(arrEqual(direction, [1,0,0])){36 //far left37 farAwayPoint.x = -1;38 farAwayPoint.y = 0;39 farAwayPoint.z = 0;40 pVec1.x = stage.players[i].x-(2*stage.players[i].width)/5;41 pVec1.y = stage.players[i].y-(2*stage.players[i].height)/5;42 pVec1.z = stage.players[i].z;43 raycaster.set(pVec1, farAwayPoint.normalize());44 intersects1 = raycaster.intersectObjects(stage.blockAMeshes);45 pVec2.x = stage.players[i].x-(2*stage.players[i].width)/5;46 pVec2.y = stage.players[i].y+(2*stage.players[i].height)/5;47 pVec2.z = stage.players[i].z;48 raycaster.set(pVec2, farAwayPoint.normalize());49 intersects2 = raycaster.intersectObjects(stage.blockAMeshes);50 var pointA = pVec1;51 var pointB = new THREE.Vector3();52 pointB.addVectors ( pointA, farAwayPoint.normalize().multiplyScalar( 20 ) );53 drawRay(pointA, pointB, 0xff0000);54 var pointA = pVec2;55 var pointB = new THREE.Vector3();56 pointB.addVectors ( pointA, farAwayPoint.normalize().multiplyScalar( 20 ) );57 drawRay(pointA, pointB, 0xff0000);58 }59 //right60 else if(arrEqual(direction, [-1,0,0])){61 //far right62 farAwayPoint.x = 1;63 farAwayPoint.y = 0;64 farAwayPoint.z = 0;65 //current right below66 pVec1.x = stage.players[i].x+(2*stage.players[i].width)/5;67 pVec1.y = stage.players[i].y-(2*stage.players[i].height)/5;68 pVec1.z = stage.players[i].z;69 raycaster.set(pVec1, farAwayPoint.normalize());70 intersects1 = raycaster.intersectObjects(stage.blockAMeshes);71 //current right top72 pVec2.x = stage.players[i].x+(2*stage.players[i].width)/5;73 pVec2.y = stage.players[i].y+(2*stage.players[i].height)/5;74 pVec2.z = stage.players[i].z;75 raycaster.set(pVec2, farAwayPoint.normalize());76 intersects2 = raycaster.intersectObjects(stage.blockAMeshes);77 //draw right below78 var pointA = pVec1;79 var pointB = new THREE.Vector3();80 pointB.addVectors ( pointA, farAwayPoint.normalize().multiplyScalar( 20 ) );81 drawRay(pointA, pointB, 0x00ff00);82 //draw right top83 var pointA = pVec2;84 var pointB = new THREE.Vector3();85 pointB.addVectors ( pointA, farAwayPoint.normalize().multiplyScalar( 20 ) );86 drawRay(pointA, pointB, 0x00ff00);87 }88 //below89 else if(arrEqual(direction, [0,1,0])){90 farAwayPoint.x = 0;91 farAwayPoint.y = -1;92 farAwayPoint.z = 0;93 pVec1.x = stage.players[i].x-(2*stage.players[i].width)/5;94 pVec1.y = stage.players[i].y-(2*stage.players[i].height)/5;95 pVec1.z = stage.players[i].z;96 raycaster.set(pVec1, farAwayPoint.normalize());97 intersects1 = raycaster.intersectObjects(stage.blockAMeshes);98 pVec2.x = stage.players[i].x+(2*stage.players[i].width)/5;99 pVec2.y = stage.players[i].y-(2*stage.players[i].height)/5;100 pVec2.z = stage.players[i].z;101 raycaster.set(pVec2, farAwayPoint.normalize());102 intersects2 = raycaster.intersectObjects(stage.blockAMeshes);103 var pointA = pVec1;104 var pointB = new THREE.Vector3();105 pointB.addVectors ( pointA, farAwayPoint.normalize().multiplyScalar( 20 ) );106 drawRay(pointA, pointB, 0x0000ff);107 var pointA = pVec2;108 var pointB = new THREE.Vector3();109 pointB.addVectors ( pointA, farAwayPoint.normalize().multiplyScalar( 20 ) );110 drawRay(pointA, pointB, 0x0000ff);111 }112 //above113 else if(arrEqual(direction, [0,-1,0])){114 farAwayPoint.x = 0;115 farAwayPoint.y = 1;116 farAwayPoint.z = 0;117 pVec1.x = stage.players[i].x-(2*stage.players[i].width)/5;118 pVec1.y = stage.players[i].y+(2*stage.players[i].height)/5;119 pVec1.z = stage.players[i].z;120 raycaster.set(pVec1, farAwayPoint.normalize());121 intersects1 = raycaster.intersectObjects(stage.blockAMeshes);122 pVec2.x = stage.players[i].x+(2*stage.players[i].width)/5;123 pVec2.y = stage.players[i].y+(2*stage.players[i].height)/5;124 pVec2.z = stage.players[i].z;125 raycaster.set(pVec2, farAwayPoint.normalize());126 intersects2 = raycaster.intersectObjects(stage.blockAMeshes);127 var pointA = pVec1;128 var pointB = new THREE.Vector3();129 pointB.addVectors ( pointA, farAwayPoint.normalize().multiplyScalar( 20 ) );130 drawRay(pointA, pointB, 0xff00ff);131 var pointA = pVec2;132 var pointB = new THREE.Vector3();133 pointB.addVectors ( pointA, farAwayPoint.normalize().multiplyScalar( 20 ) );134 drawRay(pointA, pointB, 0xff00ff);135 }136 intersects = determineClosest(intersects1, intersects2);137 if ( intersects != undefined) {138 if(intersects.length > 0){139 //players[i].boxBelow = intersects[0].object;140 if(direction[1] == 1){141 stage.players[i].boxBelow = intersects[0].object;142 }143 //stage.players[i].boxLeft = intersects[0].object;144 if(direction[0] == 1){145 stage.players[i].boxLeft = intersects[0].object;146 }147 //players[i].boxRight = intersects[0].object;148 if(direction[0] == -1){149 stage.players[i].boxRight = intersects[0].object;150 }151 if(direction[1] == -1){152 if(intersects[0].object.userData.type != "platform"){153 stage.players[i].boxAbove = intersects[0].object;154 }155 else{156 stage.players[i].boxAbove = undefined;157 }158 }159 }160 else{161 //players[i].boxBelow = undefined;162 if(direction[1] == 1){163 stage.players[i].boxBelow = undefined;164 }165 //players[i].boxLeft = undefined;166 if(direction[0] == 1){167 stage.players[i].boxLeft = undefined;168 }169 if(direction[0] == -1){170 stage.players[i].boxRight = undefined;171 }172 if(direction[1] == -1){173 stage.players[i].boxAbove = undefined;174 }175 }176 } else {177 //players[i].boxBelow = undefined;178 if(direction[1] == 1){179 stage.players[i].boxBelow = undefined;180 }181 //players[i].boxLeft = undefined;182 if(direction[0] == 1){183 stage.players[i].boxLeft = undefined;184 }185 if(direction[0] == -1){186 stage.players[i].boxRight = undefined;187 }188 if(direction[1] == -1){189 stage.players[i].boxAbove = undefined;190 }191 }192 }193}194function determineClosest(arr1, arr2){195 if(arr1.length > 0 && arr2.length > 0){196 if(arr1[0].distance < arr2[0].distance){197 return arr1;198 }199 else{200 return arr2;201 }202 console.log("Both exist but neither is closer");203 return arr1;204 }205 else if(!(arr1.length > 0) && arr2.length > 0){206 return arr2;207 }208 else if(!(arr2.length > 0) && arr1.length > 0){209 return arr1;210 }211 else if(!(arr1.length > 0) && !(arr2.length > 0)){212 return undefined;213 }214 console.log("none of these three cases exist");215 return arr1;216}217function drawRay(pointA, pointB, color){218 // if(drawRays){219 // var geometry = new THREE.Geometry();220 // geometry.vertices.push( pointA );221 // geometry.vertices.push( pointB );222 // var material = new THREE.LineBasicMaterial( { color : color } );223 // var intLT = new THREE.Line(geometry, material);224 // stage.scene.add(intLT);225 // setTimeout(function(){stage.scene.remove(intLT)}, 25);226 // setTimeout(function(){intLT.geometry.dispose();}, 25);227 // }...
oldcollision.js
Source:oldcollision.js
1var raycaster = new THREE.Raycaster();2var INTERSECTED,INTERSECTEDLEFT,INTERSECTEDRIGHT;3var boxes = [boxBelow, boxLeft, boxRight];4//left = [1,0,0];5//right = [-1,0,0];6//below = [0,1,0];7function lookDirection(direction){8 // creates a vector from the player to some point way below9 var positionBelow = new THREE.Vector3();10 positionBelow.x = player1.x-1000*direction[0];11 positionBelow.y = player1.y-1000*direction[1];12 positionBelow.z = player1.z-1000*direction[2];13 //casts a ray from player to point below14 raycaster.set(player1, positionBelow.normalize());15 // calculate objects intersecting the picking ray16 var intersects = raycaster.intersectObjects(blockMeshes);17 if ( intersects.length > 0 ) {18 if ( INTERSECTED != intersects[ 0 ].object ) {19 if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );20 INTERSECTED = intersects[ 0 ].object;21 INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();22 INTERSECTED.material.emissive.setHex( 0xff0000 );23 //boxBelow = intersects[0].object;24 if(direction[1] == 1){25 boxes[0] = intersects[0].object;26 }27 //boxLeft = intersects[0].object;28 if(direction[0] == 1){29 boxes[1] = intersects[0].object;30 }31 //boxRight = intersects[0].object;32 if(direction[0] == -1){33 boxes[2] = intersects[0].object;34 }35 }36 } else {37 if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );38 INTERSECTED = null;39 //boxBelow = undefined;40 if(direction[1] == 1){41 boxes[0] = undefined;42 }43 //boxLeft = undefined;44 if(direction[0] == 1){45 boxes[1] = undefined;46 }47 if(direction[0] == -1){48 boxes[2] = undefined;49 }50 }51 belowBox = boxes[0];52 boxLeft = boxes[1];53 boxRight = boxes[2];54}55/////////////////56function lookBelow(){57 // creates a vector from the player to some point way below58 var positionBelow = new THREE.Vector3();59 positionBelow.x = player1.x;60 positionBelow.y = player1.y-1000;61 positionBelow.z = player1.z;62 //casts a ray from player to point below63 raycaster.set(player1, positionBelow.normalize());64 // calculate objects intersecting the picking ray65 var intersects = raycaster.intersectObjects(blockMeshes);66 // finds the intersections and colors them for testing, adds to the below box67 if ( intersects.length > 0 ) {68 if ( INTERSECTED != intersects[ 0 ].object ) {69 if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );70 INTERSECTED = intersects[ 0 ].object;71 INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();72 INTERSECTED.material.emissive.setHex( 0xff0000 );73 boxBelow = intersects[0].object;74 }75 } else {76 if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );77 INTERSECTED = null;78 boxBelow = undefined;79 }80}81function lookRight(){82 // creates a vector from the player to some point way below83 var positionBelow = new THREE.Vector3();84 positionBelow.x = player1.x+1000;85 positionBelow.y = player1.y;86 positionBelow.z = player1.z;87 //casts a ray from player to point below88 raycaster.set(player1, positionBelow.normalize());89 // calculate objects intersecting the picking ray90 var intersects = raycaster.intersectObjects(blockMeshes);91 // finds the intersections and colors them for testing, adds to the below box92 if ( intersects.length > 0 ) {93 if ( INTERSECTEDRIGHT != intersects[ 0 ].object ) {94 if ( INTERSECTEDRIGHT ) INTERSECTEDRIGHT.material.emissive.setHex( INTERSECTEDRIGHT.currentHex );95 INTERSECTEDRIGHT = intersects[ 0 ].object;96 INTERSECTEDRIGHT.currentHex = INTERSECTEDRIGHT.material.emissive.getHex();97 INTERSECTEDRIGHT.material.emissive.setHex( 0xff0000 );98 boxRight = intersects[0].object;99 }100 } else {101 if ( INTERSECTEDRIGHT ) INTERSECTEDRIGHT.material.emissive.setHex( INTERSECTEDRIGHT.currentHex );102 INTERSECTEDRIGHT = null;103 boxRight = undefined;104 }105}106function lookLeft(){107 // creates a vector from the player to some point way below108 var positionBelow = new THREE.Vector3();109 positionBelow.x = player1.x-1000;110 positionBelow.y = player1.y;111 positionBelow.z = player1.z;112 //casts a ray from player to point below113 raycaster.set(player1, positionBelow.normalize());114 // calculate objects intersecting the picking ray115 var intersects = raycaster.intersectObjects(blockMeshes);116 // finds the intersections and colors them for testing, adds to the below box117 if ( intersects.length > 0 ) {118 if ( INTERSECTEDLEFT != intersects[ 0 ].object ) {119 if ( INTERSECTEDLEFT ) INTERSECTEDLEFT.material.emissive.setHex( INTERSECTEDLEFT.currentHex );120 INTERSECTEDLEFT = intersects[ 0 ].object;121 INTERSECTEDLEFT.currentHex = INTERSECTEDLEFT.material.emissive.getHex();122 INTERSECTEDLEFT.material.emissive.setHex( 0xff0000 );123 boxLeft = intersects[0].object;124 }125 } else {126 if ( INTERSECTEDLEFT ) INTERSECTEDLEFT.material.emissive.setHex( INTERSECTEDLEFT.currentHex );127 INTERSECTEDLEFT = null;128 boxLeft = undefined;129 }...
puzzle.js
Source:puzzle.js
1"use strict";2var x = [3 [0, 0, 0],4 [0, 0, 0],5 [0, 0, 0]6];7var solved = [8 [1, 2, 3],9 [4, 5, 6],10 [7, 8, 9]11];12function allowDrop(ev) {13 ev.preventDefault();14}15function drag(ev) {16 ev.dataTransfer.setData("text", ev.target.id);17}18function drop(ev) {19 ev.preventDefault();20 21 var sourceBoxId = ev.dataTransfer.getData("text");22 var sourceBox = document.getElementById(sourceBoxId);23 var targetBox = document.getElementById(ev.target.id);24 25 swap(sourceBox, targetBox);26 copyTextContentsIntoArray();27 if(isPuzzleSolved()) {28 messages.textContent = "Puzzle solved!!!";29 }30 addRemoveEventListenersToSquares();31}32function swap(source, target) {33 swapBackgrounds(source, target);34 swapTextContent(source, target);35}36function swapTextContent(source, target) {37 var targetTextContent = target.textContent;38 target.textContent = source.textContent;39 source.textContent = targetTextContent;40}41function swapBackgrounds(source, target) {42 var sourceBoxBackground = window.getComputedStyle(source, null).getPropertyValue("background");43 target.style.background = sourceBoxBackground;44 source.style.background = "black";45}46function copyTextContentsIntoArray() {47 var squares = document.getElementsByClassName("square");48 for(var i = 0; i < x.length; i++) {49 for(var j = 0; j < x.length; j++) {50 x[i][j] = Number(squares[i * x.length + j].textContent);51 }52 }53}54function isBox9ToTheRight(box) {55 var boxNumber = box.id.replace("box", "");56 var modulus = Number(boxNumber) % x.length;57 if(modulus == 0) {58 return false;59 }60 var boxToTheRight = document.getElementById("box".concat(Number(boxNumber) + 1));61 var boxToTheRightTextContent = boxToTheRight.textContent;62 63 if(boxToTheRightTextContent == 9) {64 return true;65 }66 return false;67}68function isBox9ToTheLeft(box) {69 var boxNumber = box.id.replace("box", "");70 var modulus = Number(boxNumber) % x.length;71 if(modulus == 1) {72 return false;73 }74 var boxToTheLeft = document.getElementById("box".concat(Number(boxNumber) - 1));75 var boxToTheLeftTextContent = boxToTheLeft.textContent;76 77 if(boxToTheLeftTextContent == 9) {78 return true;79 }80 return false;81}82function isBox9OnTop(box) {83 var boxNumber = box.id.replace("box", "");84 if(Number(boxNumber) <= x.length) {85 return false;86 }87 var boxOnTop = document.getElementById("box".concat(Number(boxNumber) - x.length));88 var boxOnTopTextContent = boxOnTop.textContent;89 90 if(boxOnTopTextContent == 9) {91 return true;92 }93 return false;94}95function isBox9Below(box) {96 var boxNumber = box.id.replace("box", "");97 if(boxNumber > x.length * (x.length - 1)) {98 return false;99 }100 var boxBelow = document.getElementById("box".concat(Number(boxNumber) + x.length));101 var boxBelowTextContent = boxBelow.textContent;102 103 if(boxBelowTextContent == 9) {104 return true;105 }106 return false;107}108function addRemoveEventListenersToSquares() {109 var squares = document.getElementsByClassName("square");110 111 for(var i = 0; i < squares.length; i++) {112 squares[i].removeEventListener("drop", drop);113 squares[i].removeEventListener("dragover", allowDrop);114 squares[i].removeEventListener("dragstart", drag);115 116 squares[i]["draggable"] = false;117 }118 for(var i = 0; i < x.length; i++) {119 for(var j = 0; j < x.length; j++) {120 var currentBox = squares[i * x.length + j];121 if(currentBox.textContent == 9) {122 currentBox.addEventListener("drop", drop, false);123 currentBox.addEventListener("dragover", allowDrop, false);124 }125 else {126 if(isBox9Below(currentBox) ||127 isBox9OnTop(currentBox) ||128 isBox9ToTheLeft(currentBox) ||129 isBox9ToTheRight(currentBox)) {130 currentBox.addEventListener("dragstart", drag, false);131 currentBox["draggable"] = true;132 }133 }134 }135 }136}137function isPuzzleSolved() {138 for(var i = 0; i < x.length; i++) {139 for(var j = 0; j < x.length; j++) {140 if(x[i][j] != solved[i][j]) {141 return false;142 }143 } 144 }145 return true;146}147function scramblePuzzlePieces() {148 // TODO:149 swap(getBox(6), getBox(9));150 swap(getBox(3), getBox(6));151 swap(getBox(2), getBox(3));152 swap(getBox(1), getBox(2));153 swap(getBox(4), getBox(1));154 swap(getBox(7), getBox(4));155 swap(getBox(8), getBox(7));156 swap(getBox(5), getBox(8));157}158function getBox(id) {159 return document.getElementById("box" + id);160}161document.getElementById("newGameButton").addEventListener("click", function() {162 location.reload();163}, false);164scramblePuzzlePieces();165copyTextContentsIntoArray();...
use-position-reorder.js
Source:use-position-reorder.js
1import { useState, useRef } from "react";2import { clamp } from "popmotion";3import move from "array-move";4export const usePositionReorder = (initialState) => {5 const [order, setOrder] = useState(initialState);6 // We need to collect an array of width and position data for all of this component's7 // `Item` children, so we can later us that in calculations to decide when a dragging8 // `Item` should swap places with its siblings.9 const positions = useRef([]).current;10 const updatePosition = (i, offset) => (positions[i] = offset);11 // Find the ideal index for a dragging item based on its position in the array, and its12 // current drag offset. If it's different to its current index, we swap this item with that13 // sibling.14 const updateOrder = (i, viewportBox) => {15 const targetIndex = findIndex(i, viewportBox, positions);16 if (targetIndex !== i) setOrder(move(order, i, targetIndex));17 };18 return [order, updatePosition, updateOrder];19};20// This margin needs to match space between cells exactly.21// TODO: Optimize for safer handling22const margin = 20;23export const findIndex = (i, currentBox, positions) => {24 let target = i;25 const { left, width, top, height } = positions[i];26 const bottom = top + height;27 currentBox.x.center = (currentBox.x.min + currentBox.x.max) / 2;28 currentBox.y.center = (currentBox.y.min + currentBox.y.max) / 2;29 // If current within same row30 if (31 currentBox.y.center > top - margin &&32 currentBox.y.center < bottom + margin33 ) {34 // Moving right35 if (currentBox.x.center > left + width / 2) {36 const nextItem = positions[i + 1];37 if (nextItem === undefined || nextItem.top !== top) return i; // If end of array or not in same row38 if (currentBox.x.center > nextItem.left + nextItem.width / 2) {39 target = i + 1;40 }41 // Moving left42 } else if (currentBox.x.center < left + width / 2) {43 const prevItem = positions[i - 1];44 if (prevItem === undefined || prevItem.top !== top) return i; // If beginning of array or not in same row45 if (currentBox.x.center < prevItem.left + prevItem.width / 2) {46 target = i - 1;47 }48 }49 return target;50 }51 // If current going to row above52 if (currentBox.y.center < top - margin) {53 // Add index to positions array54 const indexedPositions = positions.map((el, i) => {55 return { ...el, i };56 });57 // Get box directly above58 const boxesAbove = indexedPositions.filter(59 (el) => el.left === left && el.top < top60 );61 const boxAbove = boxesAbove[boxesAbove.length - 1];62 if (boxAbove === undefined) return target;63 // Return box to right if slightly right of center, else return box above64 if (boxAbove.left + boxAbove.width / 2 < currentBox.x.center) {65 return boxAbove.i + 1;66 } else if (boxAbove.left + boxAbove.width / 2 >= currentBox.x.center) {67 return boxAbove.i;68 }69 return target;70 }71 // If current going to row below72 if (currentBox.y.center > bottom + margin) {73 // Add index to positions array74 const indexedPositions = positions.map((el, i) => {75 return { ...el, i };76 });77 // Get box directly above78 const boxesBelow = indexedPositions.filter(79 (el) => el.left === left && el.top > top80 );81 const boxBelow = boxesBelow[0];82 if (boxBelow === undefined) return target;83 // Return box to left if slightly left of center, else return box below84 if (boxBelow.left + boxBelow.width / 2 <= currentBox.x.center) {85 return boxBelow.i;86 } else if (boxBelow.left + boxBelow.width / 2 > currentBox.x.center) {87 return boxBelow.i - 1;88 }89 return target;90 }91 return clamp(0, positions.length, target);...
styles.js
Source:styles.js
1import {StyleSheet} from 'react-native';2export default StyleSheet.create({3 container: {4 flex: 1,5 backgroundColor: '#F9FAFB',6 },7 createRoomView: {8 margin: 16,9 position: 'absolute',10 bottom: 0,11 right: 0,12 },13 boxBelow: {14 margin: 16,15 position: 'absolute',16 bottom: 0,17 right: 0,18 },19 buttonStyleView: {20 backgroundColor: '#DBE0FE',21 borderRadius: 30,22 paddingHorizontal: 10,23 },24 titleStyleView: {25 color: '#3a82f6',26 fontSize: 15,27 marginHorizontal: 2,28 },29 roomListView: {30 backgroundColor: '#e8e8e8',31 margin: 10,32 borderRadius: 20,33 },34 roomBoxView: {35 padding: 5,36 flexDirection: 'column',37 },38 roomAvatarView: {39 flexDirection: 'row',40 alignItems: 'center',41 },42 roomAvatarContainer: {43 backgroundColor: '#68a0cf',44 borderRadius: 30,45 justifyContent: 'center',46 alignItems: 'center',47 textAlign: 'center',48 margin: 5,49 },50 dotView: {51 marginTop: 8,52 marginHorizontal: 10,53 height: 10,54 width: 10,55 backgroundColor: '#ff7c4d',56 borderRadius: 10,57 shadowColor: '#000',58 shadowOffset: {59 width: 0,60 height: 2,61 },62 shadowOpacity: 0.25,63 shadowRadius: 3.84,64 elevation: 5,65 },66 container: {67 flex: 1,68 backgroundColor: '#F9FAFB',69 },70 formContent: {71 flexDirection: 'row',72 marginVertical: 5,73 },74 inputContainer: {75 backgroundColor: '#E5E7EB',76 borderRadius: 20,77 flexDirection: 'row',78 alignItems: 'center',79 flex: 1,80 margin: 10,81 marginBottom: 0,82 },83 inputs: {84 height: 45,85 borderBottomColor: '#FFFFFF',86 flex: 1,87 },88 createRoomView: {89 margin: 16,90 position: 'absolute',91 bottom: 0,92 right: 0,93 },...
BoxAnime.js
Source:BoxAnime.js
1import React, {useState} from "react";2import {3 ImageBackground,4 FlatList,5 Text,6 View,7 Image,8 StyleSheet,9 TouchableOpacity,10 Button,11 ScrollView,12} from "react-native";13import Icon from "react-native-vector-icons/FontAwesome";14const BoxAnime = ({cover, img, name, text}) => {15 return (16 <View style={{margin: 10}}>17 <Image18 source={{uri: img}}19 resizeMode="cover"20 style={styles.BoxImageAbove}21 />22 <View style={styles.boxBelow}>23 <View>24 <Image25 source={{uri: cover}}26 resizeMode="cover"27 style={styles.BoxPortAnime}28 />29 </View>30 <View style={styles.boxText}>31 <Text style={styles.boxTextTitle}>{name}</Text>32 <View>33 <Text style={styles.boxTextSubTitle}>SERIES</Text>34 </View>35 </View>36 </View>37 </View>38 );39};40const styles = StyleSheet.create({41 BoxImageAbove: {42 width: "100%",43 height: 200,44 },45 boxBelow: {46 backgroundColor: "#213945",47 height: 200,48 flexDirection: "row",49 },50 BoxPortAnime: {51 width: 140,52 height: 250,53 position: "relative",54 left: 10,55 bottom: 60,56 },57 boxText: {58 justifyContent: "space-around",59 position: "relative",60 left: 20,61 },62 boxTextTitle: {63 color: "white",64 },65 boxTextSubTitle: {66 color: "#00FFEE",67 },68});...
Using AI Code Generation
1const boxBelow = require('@playwright/test').boxBelow;2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const searchBox = await page.$('input[name="q"]');8 const box = await boxBelow(searchBox);9 await page.click(box);10 await page.fill(box, 'playwright');11 await page.press(box, 'Enter');12 await page.screenshot({ path: 'example.png' });13 await browser.close();14})();
Using AI Code Generation
1const boxBelow = require('playwright/lib/internal/boxModel').boxBelow;2const boxAbove = require('playwright/lib/internal/boxModel').boxAbove;3const boxRight = require('playwright/lib/internal/boxModel').boxRight;4const boxLeft = require('playwright/lib/internal/boxModel').boxLeft;5const boxCenter = require('playwright/lib/internal/boxModel').boxCenter;6const boxWithText = require('playwright/lib/internal/boxModel').boxWithText;7const boxWithText = require('playwright/lib/internal/boxModel').boxWithText;8const boxInside = require('playwright/lib/internal/boxModel').boxInside;9const boxOutside = require('playwright/lib/internal/boxModel').boxOutside;10const boxIntersects = require('playwright/lib/internal/boxModel').boxIntersects;11const boxContains = require('playwright/lib/internal/boxModel').boxContains;12const boxEquals = require('playwright/lib/internal/boxModel').boxEquals;13const boxToString = require('playwright/lib/internal/boxModel').boxToString;14const boxFromRect = require('playwright/lib/internal/boxModel').boxFromRect;15const boxFromPoint = require('playwright/lib/internal/boxModel').boxFromPoint;16const boxFromSize = require('playwright/lib/internal/boxModel').boxFromSize;
Using AI Code Generation
1const { boxBelow } = require('@playwright/test/lib/autowaiting');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 await page.click('text=Get Started');5 await page.click('text=Docs');6 await page.click('text=API');7 const element = await page.locator('text=class Locator').first();8 const box = await boxBelow(element);9 console.log(box);10});11const { test } = require('@playwright/test');12test('test', async ({ page }) => {13 await page.click('text=Get Started');14 await page.click('text=Docs');15 await page.click('text=API');16 const element = await page.locator('text=class Locator').first();17 const box = await element.boundingBox();18 const belowBox = await element.elementHandle().evaluate((el) => {19 const belowEl = el.nextElementSibling;20 return belowEl.getBoundingClientRect();21 });22 console.log(box);23 console.log(belowBox);24});
Using AI Code Generation
1const { boxBelow } = require("@playwright/test");2const { test, expect } = require("@playwright/test");3test("Test", async ({ page }) => {4 const box = await boxBelow(page.locator("text=Docs"));5 await expect(box).toMatchSnapshot("boxBelow");6});7test("Test", async ({ page }) => {8 const box = await boxBelow(page.locator("text=Docs"), { threshold: 0.5 });9 await expect(box).toMatchSnapshot("boxBelow");10});11test("Test", async ({ page }) => {12 const box = await boxBelow(page.locator("text=Docs"), { threshold: 0.5, maxMatches: 1 });13 await expect(box).toMatchSnapshot("boxBelow");14});15test("Test", async ({ page }) => {16 const box = await boxBelow(page.locator("text=Docs"), { threshold: 0.5, maxMatches: 1, selector: "text=API" });17 await expect(box).toMatchSnapshot("boxBelow");18});19test("Test", async ({ page }) => {20 const box = await boxBelow(page.locator("text=Docs"), { threshold: 0.5, maxMatches: 1, selector: "text=API", root: page.locator("text=Docs") });21 await expect(box).toMatchSnapshot("boxBelow");22});23test("Test", async ({ page }) => {24 const box = await boxBelow(page.locator("text=Docs"), { threshold: 0.5, maxMatches: 1, selector: "text=API", root: page.locator("text=Docs"), usePageCoordinates: true });25 await expect(box).toMatchSnapshot("boxBelow");26});27test("Test", async ({ page }) => {28 const box = await boxBelow(page.locator("text=Docs"), { threshold: 0.5, maxMatches: 1, selector: "text=API", root: page.locator("text=Docs"), usePageCoordinates: true, waitFor: "visible
Using AI Code Generation
1const { boxBelow } = require('./playwright/lib/helper');2const { chromium } = require('./playwright');3const path = require('path');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const searchBox = await page.$('input[name="q"]');9 const box = await boxBelow(searchBox);10 console.log(box);11 await browser.close();12})();13const { helper } = require('./helper');14const { getBoundingBox } = require('./dom');15module.exports = {16};17async function boxBelow(element) {18 const box = await getBoundingBox(element);19 return {20 };21}22const { helper } = require('./helper');23module.exports = {24};25async function getBoundingBox(element) {26 const result = await element.evaluate(element => {27 const rect = element.getBoundingClientRect();28 return {29 };30 });31 return helper.evaluationResultToObject(result);32}33module.exports = {34};35const helper = {36};37function evaluationResultToObject(result) {38 if (result && result.__previewValue) {39 const preview = result.__previewValue;40 if (preview.type === 'object') {41 const value = {};42 for (const { name, value } of preview.properties) {43 value[name] = evaluationResultToObject(value);44 }45 return value;46 }47 if (preview.type === 'array') {48 return preview.properties.map(evaluationResultToObject);49 }50 if (preview.type === 'function') {51 return evaluationResultToObject(preview.description);52 }53 if (preview.type === 'undefined') {54 return undefined;55 }56 if (preview.type === 'null') {57 return null;58 }59 if (preview.type === 'bigint') {60 return BigInt(preview.description);61 }62 if (preview.type === 'nan') {63 return NaN;64 }
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const elementHandle = await page.$('text="API"');7 const box = await elementHandle.boxModel();8 console.log(box);9 await browser.close();10})();11{ content: [ { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 } ],12 padding: [ { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 } ],13 border: [ { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 } ],14 margin: [ { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 } ],15 height: 0 }
Using AI Code Generation
1const box = await page.evaluate(() => window.boxBelow());2console.log(box);3import { PlaywrightTestConfig } from '@playwright/test';4const config: PlaywrightTestConfig = {5 {6 use: {7 },8 },9 use: {10 viewport: { width: 1280, height: 720 },11 },12};13export default config;14const { PlaywrightTestConfig } = require('@playwright/test');15const config = new PlaywrightTestConfig();16config.use = {17 viewport: { width: 1280, height: 720 },18};19config.testDir = 'src';20config.testMatch = '**/*.spec.ts';21config.timeout = 30000;22config.workers = 1;23module.exports = config;24module.exports = {25 testEnvironmentOptions: {26 'jest-playwright': {27 launchOptions: {28 },29 },30 },31};32const { setDefaultOptions } = require('expect-puppeteer');33setDefaultOptions({ timeout: 30000 });34{35 "scripts": {36 },
Using AI Code Generation
1import { boxBelow } from "@playwright/test";2const box = boxBelow(100, 100, 200, 200);3console.log(box);4import { boxAbove } from "@playwright/test";5const box = boxAbove(100, 100, 200, 200);6console.log(box);7import { boxLeft } from "@playwright/test";8const box = boxLeft(100, 100, 200, 200);9console.log(box);10import { boxRight } from "@playwright/test";11const box = boxRight(100, 100, 200, 200);12console.log(box);13import { boxInside } from "@playwright/test";14const box = boxInside(100, 100, 200, 200);15console.log(box);16import { boxOutside } from "@playwright/test";17const box = boxOutside(100, 100, 200, 200);18console.log(box);19import { boxAround } from "@playwright/test";20const box = boxAround(100, 100, 200, 200);21console.log(box);22import { boxCenter } from "@playwright/test";23const box = boxCenter(100, 100, 200, 200);24console.log(box);25import { boxIntersect } from "@playwright/test";26const box = boxIntersect(100, 100, 200, 200, 100, 100, 200, 200);27console.log(box);28import { boxEquals } from "@playwright/test";29const box = boxEquals(100, 100, 200, 200, 100, 100, 200, 200);30console.log(box);31import { boxContains } from "@playwright/test";32const box = boxContains(100,
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!!