How to use boxAbove method in Playwright Internal

Best JavaScript code snippet using playwright-internal

graph.serie.box.js

Source:graph.serie.box.js Github

copy

Full Screen

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}...

Full Screen

Full Screen

Home.js

Source:Home.js Github

copy

Full Screen

1import React, { Component } from 'react';2import { connect } from 'react-redux'3import { BarChart, AreaChart, Area, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend,4 Bar, ComposedChart, PieChart, Pie, Sector, Cell } from 'recharts';5import { Col, Row, Table, Icon, Popover, Select , Button } from 'antd'6import { Modal, ButtonToolbar } from 'react-bootstrap';7import Cookies from 'js-cookie'8import TotalRev from '../visualizeComponent/TotalRev'9import BoxAbove from '../visualizeComponent/BoxAbove'10import TourRevRanking from '../visualizeComponent/TourRevRanking'11import PopularNation from '../visualizeComponent/PopularNation'12import TotalRevModal from '../visualizeComponent/Modal/TotalRevModal'13import TourRevRankingModal from '../visualizeComponent/Modal/TourRevRankingModal'14import PopNationModal from '../visualizeComponent/Modal/PopNationModal'15import TotalParticipant from '../visualizeComponent/TotalParticipant'16import TotalParticipantModal from '../visualizeComponent/Modal/TotalParticipantModal'17import TourCustomerRanking from '../visualizeComponent/TourCustomerRanking'18import TourCustomerRankingModal from '../visualizeComponent/Modal/TourCustomerRankingModal'19import TotalCostFromGuide from '../visualizeComponent/TotalCostFromGuide'20import AgencyParticipantsRanking from '../visualizeComponent/AgencyParticipantsRanking'21import ParticipantsFromAgencyModal from '../visualizeComponent/Modal/ParticipantsFromAgencyModal'22import CostFromGuideModal from '../visualizeComponent/Modal/CostFromGuideModal'23import { changeYearDashBoard } from '../../actions/action-changeYearDashBoard'24function throwOptionYearObject(){25 let today = new Date();26 let curYear = today.getFullYear();27 let startYear = 200028 let temp = []29 for (let i = startYear; i <= curYear; i++) {30 temp.push(<Option key= {i}>{i}</Option>);31 }32 return temp33}34const Option = Select.Option;35let today = new Date();36let curYear = today.getFullYear();37class Home extends Component {38 constructor(props){39 super(props)40 this.state = {41 showMoreTourRevRanking: false,42 showMoreNationsSummary: false,43 showMoreTotalRevenue:false,44 showMoreParticipantSummary:false,45 selectedYear:curYear,46 showMoreTourCustomerRankingSummary:false,47 showMoreTotalAgency:false,48 showMoreTotalCostFromGuide:false49 }50 }51 handleClickShowMoreTourRevRanking(){52 this.setState({showMoreTourRevRanking: true})53 }54 handleClickShowMoreNationsSummary(){55 this.setState({showMoreNationsSummary: true})56 }57 handleClickshowMoreTotalRevenue(){58 this.setState({showMoreTotalRevenue: true})59 }60 handleClickShowMoreTourCustomerRanking(){61 this.setState({showMoreTourCustomerRankingSummary: true})62 }63 handleClickShowTotalAgency(){64 this.setState({showMoreTotalAgency: true})65 }66 handleYearSelect(value,option){67 this.setState({selectedYear: value})68 this.props.dispatch(changeYearDashBoard('CHANGE_YEAR',value))69 }70 handleClickShowTotalParticipant(value,option){71 this.setState({showMoreParticipantSummary: true})72 }73 handleClickShowTotalCostFromGuide(){74 this.setState({showMoreTotalCostFromGuide:true})75 }76 // setYearRev(){77 // // Cookies.set('selectedYearInDashBoard',this.state.selectedYear)78 // // this.getRevData(this.state.selectedYear)79 //80 // }81 render() {82 let closeShowMoreTourRevRanking = () => { this.setState({showMoreTourRevRanking: false}) }83 let closeShowMoreNationsSummary = () => { this.setState({showMoreNationsSummary: false}) }84 let closeShowMoreTotalRevenue = () => { this.setState({showMoreTotalRevenue:false}) }85 let closeShowMoreParticipantSummary = () => { this.setState({showMoreParticipantSummary:false}) }86 let closeShowMoreTourCustomerRankingSummary = () => { this.setState({showMoreTourCustomerRankingSummary: false}) }87 let closeShowMoreTotalAgency = () => { this.setState({showMoreTotalAgency:false}) }88 let closeShowMoreTotalCostFromGuide = () => { this.setState({showMoreTotalCostFromGuide:false}) }89 return (90 <div className="home-dashboard">91 <div className="modal-container">92 <Modal93 show={this.state.showMoreTotalAgency}94 onHide={closeShowMoreTotalAgency}95 container={this}96 responsive={true}97 aria-labelledby="contained-modal-title"98 >99 <Modal.Header closeButton>100 <Modal.Title id="contained-modal-title">Participants From Agency</Modal.Title>101 </Modal.Header>102 <Modal.Body>103 <ParticipantsFromAgencyModal dispatch = {this.props.dispatch} />104 </Modal.Body>105 </Modal>106 </div>107 <div className="modal-container">108 <Modal109 show={this.state.showMoreTotalCostFromGuide}110 onHide={closeShowMoreTotalCostFromGuide}111 container={this}112 responsive={true}113 aria-labelledby="contained-modal-title"114 >115 <Modal.Header closeButton>116 <Modal.Title id="contained-modal-title">Cost From Guide</Modal.Title>117 </Modal.Header>118 <Modal.Body>119 <CostFromGuideModal dispatch={this.props.dispatch}/>120 </Modal.Body>121 </Modal>122 </div>123 <div className="modal-container">124 <Modal125 bsSize="large"126 show={this.state.showMoreTotalRevenue}127 onHide={closeShowMoreTotalRevenue}128 responsive={true}129 container={this}130 aria-labelledby="contained-modal-title"131 >132 <Modal.Header closeButton>133 <Modal.Title id="contained-modal-title">Total Revenue Summary</Modal.Title>134 </Modal.Header>135 <Modal.Body>136 <TotalRevModal dispatch = {this.props.dispatch} />137 </Modal.Body>138 </Modal>139 </div>140 <div className="modal-container">141 <Modal142 show={this.state.showMoreTourRevRanking}143 onHide={closeShowMoreTourRevRanking}144 container={this}145 responsive={true}146 aria-labelledby="contained-modal-title"147 >148 <Modal.Header closeButton>149 <Modal.Title id="contained-modal-title">Tour Total Revenue Summary</Modal.Title>150 </Modal.Header>151 <Modal.Body>152 <TourRevRankingModal dispatch = {this.props.dispatch} />153 </Modal.Body>154 </Modal>155 </div>156 <div className="modal-container">157 <Modal158 show={this.state.showMoreNationsSummary}159 onHide={closeShowMoreNationsSummary}160 container={this}161 responsive={true}162 aria-labelledby="contained-modal-title"163 >164 <Modal.Header closeButton>165 <Modal.Title id="contained-modal-title">Popular Nation Summary</Modal.Title>166 </Modal.Header>167 <Modal.Body>168 <PopNationModal dispatch = {this.props.dispatch} />169 </Modal.Body>170 </Modal>171 </div>172 <div className="modal-container">173 <Modal174 bsSize="lg"175 show={this.state.showMoreParticipantSummary}176 onHide={closeShowMoreParticipantSummary}177 container={this}178 responsive={true}179 aria-labelledby="contained-modal-title"180 >181 <Modal.Header closeButton>182 <Modal.Title id="contained-modal-title">Total Participant Summary</Modal.Title>183 </Modal.Header>184 <Modal.Body>185 <TotalParticipantModal dispatch = {this.props.dispatch} />186 </Modal.Body>187 </Modal>188 </div>189 <div className="modal-container">190 <Modal191 show={this.state.showMoreTourCustomerRankingSummary}192 onHide={closeShowMoreTourCustomerRankingSummary}193 container={this}194 responsive={true}195 aria-labelledby="contained-modal-title"196 >197 <Modal.Header closeButton>198 <Modal.Title id="contained-modal-title">Tour Customer Summary</Modal.Title>199 </Modal.Header>200 <Modal.Body>201 <TourCustomerRankingModal dispatch ={this.props.dispatch}/>202 </Modal.Body>203 </Modal>204 </div>205 <div className = "year-selection">206 <Row>207 <Col span={6}>208 <div className ="year-title">209 <h2>{this.state.selectedYear}</h2>210 </div>211 </Col>212 <Col xs={{ span: 6, offset: 2 }} lg={{ span: 6, offset: 12 }} className="year-go">213 <Icon type="calendar" style={{fontSize:'2rem'}} />214 <Select215 showSearch216 style={{width: 150}}217 defaultValue= {this.state.selectedYear}218 placeholder="Year"219 optionFilterProp="children"220 onSelect={this.handleYearSelect.bind(this)}221 filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}222 >223 {throwOptionYearObject()}224 </Select>225 </Col>226 </Row>227 </div>228 <div className="gutter-example" >229 <BoxAbove dispatch = {this.props.dispatch}/>230 </div>231 <Row gutter={16}>232 <Col xs={24} lg={16}>233 <div className = "visualize-box">234 <div className = "visualize-label">235 <Row>236 <Col span = {14} className="label-box">237 <h4>Total Revenue Summary</h4>238 </Col>239 <Col span = {1} offset = {8}>240 <Popover placement="top" title={"See more!"}>241 <Icon className = "read-more-button" type="ellipsis"242 onClick = {()=> this.handleClickshowMoreTotalRevenue()}/>243 </Popover>244 </Col>245 </Row>246 </div>247 <TotalRev dispatch = {this.props.dispatch}/>248 </div>249 <div className = "visualize-box">250 <div className = "visualize-label">251 <Row>252 <Col span = {14} className="label-box">253 <h4>Total Customer Summary</h4>254 </Col>255 <Col span = {1} offset = {8}>256 <Popover placement="top" title={"See more!"}>257 <Icon className = "read-more-button" type="ellipsis"258 onClick = {()=> this.handleClickShowTotalParticipant()}/>259 </Popover>260 </Col>261 </Row>262 </div>263 <TotalParticipant dispatch = {this.props.dispatch} />264 </div>265 <div className = "visualize-box">266 <div className = "visualize-label">267 <Row>268 <Col span = {14} className="label-box">269 <h4>Total Cost From Guide</h4>270 </Col>271 <Col span = {1} offset = {8}>272 <Popover placement="top" title={"See more!"}>273 <Icon className = "read-more-button" type="ellipsis"274 onClick = {()=> this.handleClickShowTotalCostFromGuide()}/>275 </Popover>276 </Col>277 </Row>278 </div>279 <TotalCostFromGuide dispatch={this.props.dispatch}/>280 </div>281 <div className = "visualize-box">282 <div className = "visualize-label">283 <Row>284 <Col span = {14} className="label-box">285 <h4>Participants From Agency Ranking</h4>286 </Col>287 <Col span = {1} offset = {8}>288 <Popover placement="top" title={"See more!"}>289 <Icon className = "read-more-button" type="ellipsis"290 onClick = {()=> this.handleClickShowTotalAgency()}/>291 </Popover>292 </Col>293 </Row>294 </div>295 <AgencyParticipantsRanking dispatch={this.props.dispatch} />296 </div>297 </Col>298 <Col xs={24} lg={8}>299 <div className = "visualize-box">300 <div className = "visualize-label">301 <Row>302 <Col span = {17} className="label-box">303 <h4>Tour Revenue Ranking</h4>304 </Col>305 <Col span = {1} offset = {4}>306 <Popover placement="top" title={"See more!"}>307 <Icon className = "read-more-button" type="ellipsis"308 onClick = {()=> this.handleClickShowMoreTourRevRanking()}/>309 </Popover>310 </Col>311 </Row>312 </div>313 <TourRevRanking dispatch = {this.props.dispatch}/>314 </div>315 <div className = "visualize-box">316 <div className = "visualize-label">317 <Row>318 <Col span = {17} className="label-box">319 <h4>Tour Customer Ranking</h4>320 </Col>321 <Col span = {1} offset = {4}>322 <Popover placement="top" title={"See more!"}>323 <Icon className = "read-more-button" type="ellipsis"324 onClick = {()=> this.handleClickShowMoreTourCustomerRanking()}/>325 </Popover>326 </Col>327 </Row>328 </div>329 <TourCustomerRanking dispatch = {this.props.dispatch}/>330 </div>331 <div className = "visualize-box-pop-nation">332 <div className = "visualize-label">333 <Row>334 <Col span = {17} className="label-box">335 <h4>Popular Nation</h4>336 </Col>337 <Col span = {1} offset = {4}>338 <Popover placement="top" title={"See more!"}>339 <Icon className = "read-more-button" type="ellipsis"340 onClick = {()=> this.handleClickShowMoreNationsSummary()}/>341 </Popover>342 </Col>343 </Row>344 </div>345 <PopularNation dispatch = {this.props.dispatch}/>346 </div>347 </Col>348 { /*</Row>349 <Col span={8}>350 <div className = "fav-nation">351 </div>352 </Col>353 <Col span={8}>354 <div className = "guide-rev">355 </div>356 </Col>357 <Col span={8}>358 <div className = "guide-rev-graph">359 </div>360 </Col>361 <Row>362 */}363 </Row>364 </div>365 );366 }367}368function mapStateToProps(state){369 return{370 }371}...

Full Screen

Full Screen

perlin_grid.js

Source:perlin_grid.js Github

copy

Full Screen

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};...

Full Screen

Full Screen

playerblockcollision.js

Source:playerblockcollision.js Github

copy

Full Screen

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 // }...

Full Screen

Full Screen

BoxAbove.js

Source:BoxAbove.js Github

copy

Full Screen

1import React, { Component } from 'react';2import { connect } from 'react-redux'3import { Col, Row } from 'antd'4import apiAccess from '../../Helpers/apiAccess'5let today = new Date();6let curYear = today.getFullYear();7class BoxAbove extends Component {8 constructor(props){9 super(props)10 this.state = {11 selectedyear: curYear,12 netCustomers:[],13 individualCustomers:[],14 agencyCustomer:[],15 publicCustomers:[],16 privateCustomers:[],17 mostYearlyPopularTour:''18 }19 }20 getYearlyTotalCustomer(year){21 apiAccess({22 url: 'bookedtours/total-participants/'+year,23 method: 'GET',24 payload: null,25 attemptAction: () => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_CUSTOMER_ATTEMPT' }),26 successAction: (json) => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_CUSTOMER_SUCCESS', json }),27 failureAction: () => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_CUSTOMER_FAILURE' })28 })29 }30 getYearlyBookingTypeCustomer(year){31 apiAccess({32 url: 'bookedtours/total-participants/bookingmethod-type/'+year,33 method: 'GET',34 payload: null,35 attemptAction: () => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_BOOKINGTYPE_CUSTOMER_ATTEMPT' }),36 successAction: (json) => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_BOOKINGTYPE_CUSTOMER_SUCCESS', json }),37 failureAction: () => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_BOOKINGTYPE_CUSTOMER_FAILURE' })38 })39 }40 getYearlyTourTypeCustomer(year){41 apiAccess({42 url: 'bookedtours/total-participants/tour-type/'+year,43 method: 'GET',44 payload: null,45 attemptAction: () => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_TOURTYPE_CUSTOMER_ATTEMPT' }),46 successAction: (json) => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_TOURTYPE_CUSTOMER_SUCCESS', json }),47 failureAction: () => this.props.dispatch({ type: 'GET_YEARLY_TOTAL_TOURTYPE_CUSTOMER_FAILURE' })48 })49 }50 getMostPopularTour(year){51 apiAccess({52 url: 'bookedtours/most-popular-tour/participants/'+year,53 method: 'GET',54 payload: null,55 attemptAction: () => this.props.dispatch({ type: 'GET_ALL_TOUR_CUSTOMERS_RANKING_ATTEMPT' }),56 successAction: (json) => this.props.dispatch({ type: 'GET_ALL_TOUR_CUSTOMERS_RANKING_SUCCESS', json }),57 failureAction: () => this.props.dispatch({ type: 'GET_ALL_TOUR_CUSTOMERS_RANKING_FAILURE' })58 })59 }60 checkBookingTypeCustomer(data){61 for(let i=0;i<data.length;i++){62 if(data[i].booking_method == "Individual"){63 this.setState({individualCustomers:data[i].participants})64 }else if(data[i].booking_method == "Agency"){65 this.setState({agencyCustomer:data[i].participants})66 }67 }68 }69 getYearlyTheMostPopularTour(data){70 let tourname = 'N/A'71 let amt_customer = 072 if(typeof data[0] !== 'undefined' && typeof data[0].tour_name){73 tourname = data[0].tour_name74 }75 if(typeof data[0] !== 'undefined' && typeof data[0].participants){76 amt_customer = data[0].participants77 }78 let result = tourname+ ': '+amt_customer+ ' customers'79 this.setState({mostYearlyPopularTour:result})80 }81 checkTourTypeCustomer(data){82 for(let i=0;i<data.length;i++){83 if(data[i].tour_type == "Public"){84 this.setState({publicCustomers:data[i].participants})85 }else if(data[i].tour_type == "Private"){86 this.setState({privateCustomers:data[i].participants})87 }88 }89 }90 componentWillMount(){91 this.getYearlyBookingTypeCustomer(this.state.selectedyear)92 this.getYearlyTotalCustomer(this.state.selectedyear)93 this.getYearlyTourTypeCustomer(this.state.selectedyear)94 this.getMostPopularTour(this.state.selectedyear)95 }96 componentWillReceiveProps(nextProps){97 if(this.props.selectedYear !== nextProps.selectedYear){98 if(nextProps.selectedYear){99 this.setState({selectedYear:nextProps.selectedYear})100 this.getMostPopularTour(nextProps.selectedYear)101 this.getYearlyTourTypeCustomer(nextProps.selectedYear)102 this.getYearlyBookingTypeCustomer(nextProps.selectedYear)103 this.getYearlyTotalCustomer(nextProps.selectedYear)104 }105 }106 if(this.props.totalYearlyCustomer !== nextProps.totalYearlyCustomer){107 if(nextProps.totalYearlyCustomer){108 if(typeof nextProps.totalYearlyCustomer[0] !=='undefined'109 && typeof nextProps.totalYearlyCustomer[0].participants ){110 let totalCustomers = nextProps.totalYearlyCustomer[0].participants111 this.setState({netCustomers: totalCustomers})112 }113 }114 }115 if(this.props.totalYearlyBookingTypeCustomer !== nextProps.totalYearlyBookingTypeCustomer){116 if(nextProps.totalYearlyBookingTypeCustomer){117 this.checkBookingTypeCustomer(nextProps.totalYearlyBookingTypeCustomer)118 }119 }120 if(this.props.totalYearlyTourTypeCustomer !== nextProps.totalYearlyTourTypeCustomer){121 if(nextProps.totalYearlyTourTypeCustomer){122 this.checkTourTypeCustomer(nextProps.totalYearlyTourTypeCustomer)123 }124 }125 if(this.state.totalCustomerTourRanking !== nextProps.totalCustomerTourRanking){126 if(nextProps.totalCustomerTourRanking){127 this.getYearlyTheMostPopularTour(nextProps.totalCustomerTourRanking)128 }129 }130 }131 render() {132 return (133 <div className="customer-box-above" style={{backgroundColor:'#9B2F10'}}>134 <Row gutter={8}>135 <Col xs={24} lg={4} >136 <div className="total-customer" >137 <h3>Total customers</h3>138 <p>{this.state.netCustomers}</p>139 </div>140 </Col>141 <Col xs={12} lg={5}>142 <div className="individual-customer" >143 <h4>Direct Customer</h4>144 <p>{this.state.individualCustomers}</p>145 </div>146 <div className="agency-customer">147 <h4>Agency</h4>148 <p>{this.state.agencyCustomer}</p>149 </div>150 </Col>151 <Col xs={12} lg={5}>152 <div className="public-tour" >153 <h4>Public Tour</h4>154 <p>{this.state.publicCustomers}</p>155 </div>156 <div className="private-tour">157 <h4>Private Tour</h4>158 <p>{this.state.privateCustomers}</p>159 </div>160 </Col>161 <Col xs={24} lg={10}>162 <div className="popular-tour" >163 <h3>Most Popular Tour</h3>164 <p>{this.state.mostYearlyPopularTour}</p>165 </div>166 </Col>167 </Row>168 </div>169 );170 }171}172function mapStateToProps(state){173 return{174 selectedYear: state.updateYearDashBoard.selectedYear,175 totalYearlyCustomer: state.getYearlyTotalCustomer.totalYearlyCustomer,176 totalYearlyBookingTypeCustomer: state.getYearlyBookingTypeCustomer.totalYearlyBookingTypeCustomer,177 totalYearlyTourTypeCustomer: state.getYearlyTourTypeCustomer.totalYearlyTourTypeCustomer,178 totalCustomerTourRanking: state.getTourCustomerRanking.totalCustomerTourRanking179 }180}...

Full Screen

Full Screen

RightArea.js

Source:RightArea.js Github

copy

Full Screen

1/* eslint react/prop-types: 0 */2import { Mark } from 'prosemirror-model';3import React, { useContext, useState, useMemo, useCallback } from 'react';4import useDeepCompareEffect from 'use-deep-compare-effect';5import { each, uniqBy, sortBy } from 'lodash';6import { WaxContext } from 'wax-prosemirror-core';7import { DocumentHelpers } from 'wax-prosemirror-utilities';8import BoxList from './BoxList';9export default ({ area }) => {10 const {11 pmViews,12 pmViews: { main },13 app,14 activeView,15 } = useContext(WaxContext);16 const commentPlugin = app.PmPlugins.get('commentPlugin');17 const trakChangePlugin = app.PmPlugins.get('trackChangePlugin');18 const [marksNodes, setMarksNodes] = useState([]);19 const [position, setPosition] = useState();20 const [isFirstRun, setFirstRun] = useState(true);21 const setTops = useCallback(() => {22 const result = [];23 let markNodeEl = null;24 let annotationTop = 0;25 let boxHeight = 0;26 let top = 0;27 let WaxSurface = {};28 const allCommentsTop = [];29 let panelWrapper = {};30 let panelWrapperHeight = {};31 if (main) {32 WaxSurface = main.dom.getBoundingClientRect();33 }34 each(marksNodes[area], (markNode, pos) => {35 const id =36 markNode instanceof Mark ? markNode.attrs.id : markNode.node.attrs.id;37 const activeComment = commentPlugin.getState(activeView.state).comment;38 const activeTrackChange = trakChangePlugin.getState(activeView.state)39 .trackChange;40 let isActive = false;41 if (42 (activeComment && id === activeComment.attrs.id) ||43 (activeTrackChange && id === activeTrackChange.attrs.id)44 )45 isActive = true;46 // annotation top47 if (area === 'main') {48 markNodeEl = document.querySelector(`[data-id="${id}"]`);49 if (markNodeEl)50 annotationTop =51 markNodeEl.getBoundingClientRect().top - WaxSurface.top;52 } else {53 // Notes54 panelWrapper = document.getElementsByClassName('panelWrapper');55 panelWrapperHeight = panelWrapper[0].getBoundingClientRect().height;56 markNodeEl = document57 .querySelector('#notes-container')58 .querySelector(`[data-id="${id}"]`);59 if (markNodeEl) {60 const WaxContainerTop = document61 .querySelector('#wax-container')62 .getBoundingClientRect().top;63 annotationTop =64 markNodeEl.getBoundingClientRect().top -65 panelWrapperHeight -66 WaxContainerTop -67 50;68 }69 }70 let boxEl = null;71 // get height of this markNode box72 if (markNodeEl) {73 boxEl = document.querySelector(`div[data-box="${id}"]`);74 }75 if (boxEl) {76 boxHeight = parseInt(boxEl.offsetHeight, 10);77 // where the box should move to78 top = annotationTop;79 }80 // if the above comment box has already taken up the height, move down81 if (pos > 0) {82 const previousBox = marksNodes[area][pos - 1];83 const previousEndHeight = previousBox.endHeight;84 if (annotationTop < previousEndHeight) {85 top = previousEndHeight + 2;86 }87 }88 // store where the box ends to be aware of overlaps in the next box89 markNode.endHeight = top + boxHeight + 4;90 result[pos] = top;91 allCommentsTop.push({ [id]: result[pos] });92 // if active, move as many boxes above as needed to bring it to the annotation's height93 if (isActive) {94 markNode.endHeight = annotationTop + boxHeight + 3;95 result[pos] = annotationTop;96 allCommentsTop[pos][id] = result[pos];97 let b = true;98 let i = pos;99 // first one active, none above100 if (i === 0) b = false;101 while (b) {102 const boxAbove = marksNodes[area][i - 1];103 const boxAboveEnds = boxAbove.endHeight;104 const currentTop = result[i];105 const doesOverlap = boxAboveEnds > currentTop;106 if (doesOverlap) {107 const overlap = boxAboveEnds - currentTop;108 result[i - 1] -= overlap;109 const previousMarkNode =110 marksNodes[area][i - 1] instanceof Mark111 ? marksNodes[area][i - 1].attrs.id112 : marksNodes[area][i - 1].node.attrs.id;113 allCommentsTop[i - 1][previousMarkNode] = result[i - 1];114 }115 if (!doesOverlap) b = false;116 if (i <= 1) b = false;117 i -= 1;118 }119 }120 });121 return allCommentsTop;122 });123 const recalculateTops = () => {124 setTimeout(() => {125 setPosition(setTops());126 });127 };128 useDeepCompareEffect(() => {129 setMarksNodes(updateMarks(pmViews));130 if (isFirstRun) {131 setTimeout(() => {132 setPosition(setTops());133 setFirstRun(false);134 }, 400);135 } else {136 setPosition(setTops());137 }138 }, [updateMarks(pmViews), setTops()]);139 const CommentTrackComponent = useMemo(140 () => (141 <BoxList142 area={area}143 commentsTracks={marksNodes[area] || []}144 position={position}145 recalculateTops={recalculateTops}146 view={main}147 />148 ),149 [marksNodes[area] || [], position],150 );151 return <>{CommentTrackComponent}</>;152};153const updateMarks = views => {154 if (views.main) {155 const allInlineNodes = [];156 Object.keys(views).forEach(eachView => {157 allInlineNodes.push(158 ...DocumentHelpers.findInlineNodes(views[eachView].state.doc),159 );160 });161 const allBlockNodes = DocumentHelpers.findBlockNodes(views.main.state.doc);162 const finalMarks = [];163 const finalNodes = [];164 allInlineNodes.map(node => {165 if (node.node.marks.length > 0) {166 node.node.marks.filter(mark => {167 if (168 mark.type.name === 'comment' ||169 mark.type.name === 'insertion' ||170 mark.type.name === 'deletion' ||171 mark.type.name === 'format_change'172 ) {173 mark.pos = node.pos;174 finalMarks.push(mark);175 }176 });177 }178 });179 allBlockNodes.map(node => {180 if (node.node.attrs.track && node.node.attrs.track.length > 0) {181 finalNodes.push(node);182 }183 });184 const nodesAndMarks = [...uniqBy(finalMarks, 'attrs.id'), ...finalNodes];185 const groupedMarkNodes = {};186 nodesAndMarks.forEach(markNode => {187 const markNodeAttrs = markNode.attrs188 ? markNode.attrs189 : markNode.node.attrs;190 if (!groupedMarkNodes[markNodeAttrs.group]) {191 groupedMarkNodes[markNodeAttrs.group] = [markNode];192 } else {193 groupedMarkNodes[markNodeAttrs.group].push(markNode);194 }195 });196 return {197 main: sortBy(groupedMarkNodes.main, ['pos']),198 notes: groupedMarkNodes.notes,199 };200 }201 return [];...

Full Screen

Full Screen

use-position-reorder.js

Source:use-position-reorder.js Github

copy

Full Screen

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);...

Full Screen

Full Screen

spiral.js

Source:spiral.js Github

copy

Full Screen

1import React, { useEffect, useRef, useState, useCallback } from 'react';2import styled from 'styled-components';3import { LoremIpsum } from "lorem-ipsum";4const Container = styled.div`5 position: relative;6 width: 100%;7 flex-grow: 1;8 flex-shrink: 1;9 overflow: hidden;10`11const BlockContainer = styled.div`12 position: absolute;13 width: 0;14 height: 0;15`16const BlockView = styled.div`17 font-size: 10pt;18 width: 200px;19 padding: 10px 0;20 transform: translate(-50%, -50%);21`22const Hint = styled.div`23 color: blue;24 position: absolute;25 left: 20px;26 bottom: 20px;27`28const lorem = new LoremIpsum({29 sentencesPerParagraph: { max: 6, min: 4 },30 wordsPerSentence: { max: 8, min: 4 }31});32const ipsum = [...new Array(100)].map(() => lorem.generateParagraphs(1));33const Block = ({ content, transform, reportSize }) => {34 const domRef = useRef(null);35 useEffect(() => {36 if (domRef.current) {37 reportSize(domRef.current.getBoundingClientRect());38 }39 }, []);40 return <BlockContainer style={{ transform }}>41 <BlockView ref={domRef}>{content}</BlockView>42 </BlockContainer>43}44const Spiral = () => {45 const [sizes, setSizes] = useState(new Array(ipsum.length));46 const [offset, setOffset] = useState(0);47 const [shape, setShape] = useState(null);48 const containerRef = useRef(null);49 const calculateSize = useCallback(() => {50 const { width, height } = containerRef.current.getBoundingClientRect()51 setShape({52 centreX: width / 2,53 centreY: height / 2,54 radius: (Math.min(width, height) / 2) - 10055 });56 });57 useEffect(() => {58 document.addEventListener('wheel', e => {59 setOffset(v => v - e.deltaY);60 });61 window.addEventListener('resize', calculateSize);62 calculateSize();63 }, []);64 function trackSizes(i, size) {65 sizes[i] = size;66 setSizes([...sizes]);67 }68 function calculateTop(i) {69 // Super inefficient - should precalculate and store70 if (i == 0) return offset;71 const box = sizes[i];72 const boxAbove = sizes[i - 1];73 if (!box || !boxAbove) return 0;74 return (box.height / 2) + (boxAbove.height / 2) + calculateTop(i - 1);75 }76 function buildTransform(i) {77 const { centreX, centreY, radius } = shape;78 const up = calculateTop(i);79 let left, top;80 let angle = 0;81 let scale = 1;82 if (up > 0) {83 // sliding84 left = centreX + radius;85 top = centreY + up;86 } else {87 // turning88 // https://mathworld.wolfram.com/LogarithmicSpiral.html89 angle = up / - 300;90 const r = Math.exp(up / (radius * 8)) * radius;91 scale = Math.exp(up / (radius * 8));92 left = centreX + (Math.cos(angle) * r);93 top = centreY - (Math.sin(angle) * r);94 }95 return `translate(${left}px, ${top}px) rotate(-${angle}rad) scale(${scale})`;96 }97 return <Container ref={containerRef}>98 <Hint>(Scroll the text up)</Hint>99 {shape && ipsum.map((p, i) => <Block100 key={i}101 transform={buildTransform(i)}102 content={p}103 reportSize={size => trackSizes(i, size)}104 />)}105 </Container>;106};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { boxAbove } = require('playwright/lib/internal/frames');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 await page.click('#docs');8 const box = await boxAbove(page, '#docs');9 console.log(box);10 await browser.close();11})();12{ x: 0, y: 0, width: 1280, height: 0 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const boxAbove = require('playwright/lib/internal/frames').boxAbove;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 logo = await page.$('#hplogo');8 const logoBox = await logo.boundingBox();9 const aboveBox = await boxAbove(page, logoBox);10 await page.mouse.click(aboveBox.x + aboveBox.width / 2, aboveBox.y + aboveBox.height / 2);11 await browser.close();12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { boxAbove } = require('playwright/lib/internal/boxModel');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 const elementHandle = await page.$('text=Documentation');8 const box = await boxAbove(elementHandle);9 console.log(box);10 await browser.close();11})();12const { boxModel } = require('playwright/lib/internal/boxModel');13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch({ headless: false });16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.goto('

Full Screen

Using AI Code Generation

copy

Full Screen

1const { boxAbove } = require('playwright/lib/internal/boxModel');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 handle = await page.$('input#searchInput');8 const box = await handle.boundingBox();9 const aboveBox = await boxAbove(box, 10);10 console.log(aboveBox);11 await browser.close();12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1await page.boxAbove(selector, boxAboveOptions);2await page.boxBelow(selector, boxBelowOptions);3await page.boxLeft(selector, boxLeftOptions);4await page.boxRight(selector, boxRightOptions);5await page.boxAround(selector, boxAroundOptions);6await page.boxInside(selector, boxInsideOptions);7await page.boxOutside(selector, boxOutsideOptions);8await page.boxCenter(selector, boxCenterOptions);9await page.boxEnd(selector, boxEndOptions);10await page.boxStart(selector, boxStartOptions);11await page.boxTop(selector, boxTopOptions);12await page.boxBottom(selector, boxBottomOptions);13await page.boxLeftOf(selector, boxLeftOfOptions);14await page.boxRightOf(selector, boxRightOfOptions);15await page.boxAboveOf(selector, boxAboveOfOptions);16await page.boxBelowOf(selector, boxBelowOfOptions);17await page.boxInsideOf(selector, boxInsideOfOptions);18await page.boxOutsideOf(selector, boxOutsideOfOptions);19await page.boxCenterOf(selector, boxCenterOfOptions);20await page.boxEndOf(selector, boxEndOfOptions);21await page.boxStartOf(selector, boxStartOfOptions);

Full Screen

Using AI Code Generation

copy

Full Screen

1const boxAbove = require('playwright/lib/internal/boxAbove.js');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 await page.click('text=Get started');8 await page.click('text=Docs');9 await page.click('text=API');10 const element = await page.$('text=boxAbove');11 const box = await boxAbove(element);12 console.log(box);13 await browser.close();14})();15{ x: 0, y: 0, width: 0, height: 0 }16const boxAbove = require('playwright/lib/internal/boxAbove.js');17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.click('text=Get started');23 await page.click('text=Docs');24 await page.click('text=API');25 const element = await page.$('text=boxAbove');26 const box = await page.evaluate(element => boxAbove(element), element);27 console.log(box);28 await browser.close();29})();30{ x: 0, y: 0, width: 0, height: 0 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');2const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');3const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');4const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');5const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');6const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');7const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');8const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');9const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');10const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');11const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');12const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');13const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');14const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');15const { boxAbove } = require('playwright-core/lib/server/trace/recorder/dom.js');16const {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { boxAbove } = require('@playwright/test');2const box = boxAbove({x: 100, y: 100}, 10, 10);3console.log(box);4const { boxBelow } = require('@playwright/test');5const box = boxBelow({x: 100, y: 100}, 10, 10);6console.log(box);7const { boxLeft } = require('@playwright/test');8const box = boxLeft({x: 100, y: 100}, 10, 10);9console.log(box);10const { boxRight } = require('@playwright/test');11const box = boxRight({x: 100, y: 100}, 10, 10);12console.log(box);13const { boxAround } = require('@playwright/test');14const box = boxAround({x: 100, y: 100}, 10, 10);15console.log(box);16const { boxCenter } = require('@playwright/test');17const box = boxCenter({x: 100, y: 100}, 10, 10);18console.log(box);19const { boxTransform } = require('@playwright/test');20const box = boxTransform({x: 100, y: 100}, 10, 10);21console.log(box);22const { boxScale } = require('@playwright/test');23const box = boxScale({x: 100, y: 100}, 10, 10);24console.log(box);25const { boxShift } = require('@playwright/test');26const box = boxShift({x: 100, y: 100}, 10, 10);27console.log(box);28const { boxFrom } = require('@playwright/test');29const box = boxFrom({x: 100, y: 100}, 10, 10);30console.log(box);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { boxAbove } from '@playwright/test';2const element = await boxAbove('text=Hello world');3await element.click();4await element.dblclick();5await element.hover();6await element.selectText();7await element.fill('Hello world');8await element.press('Enter');9await element.check();10await element.uncheck();11await element.selectOption('value=2');12await element.setInputFiles('/tmp/myfile.pdf');13await element.type('Hello world');14await element.selectText();15await element.type('Hello world');16await element.setInputFiles('/tmp/myfile.pdf');17await element.selectOption('value=2');18await element.check();19await element.uncheck();20await element.click();21await element.dblclick();22await element.hover();23await element.selectText();24await element.fill('Hello world');25await element.press('Enter');26await element.type('Hello world');27await element.setInputFiles('/tmp/myfile.pdf');28await element.selectOption('value=2');29await element.check();30await element.uncheck();31await element.click();32await element.dblclick();33await element.hover();34await element.selectText();35await element.fill('Hello world');36await element.press('Enter');37await element.type('Hello world');38await element.setInputFiles('/tmp/myfile.pdf');39await element.selectOption('value=2');40await element.check();41await element.uncheck();42await element.click();43await element.dblclick();44await element.hover();45await element.selectText();46await element.fill('Hello world');47await element.press('Enter');48await element.type('Hello world');49await element.setInputFiles('/tmp/myfile.pdf');50await element.selectOption('value=2');51await element.check();52await element.uncheck();53await element.click();54await element.dblclick();55await element.hover();56await element.selectText();57await element.fill('Hello world');58await element.press('Enter');59await element.type('Hello world');60await element.setInputFiles('/tmp/myfile.pdf');61await element.selectOption('value=2');62await element.check();63await element.uncheck();64await element.click();65await element.dblclick();66await element.hover();67await element.selectText();68await element.fill('Hello world');69await element.press('Enter');70await element.type('Hello world');71await element.setInputFiles('/tmp/myfile.pdf');72await element.selectOption('value=2');73await element.check();74await element.uncheck();75await element.click();76await element.dblclick();77await element.hover();78await element.selectText();79await element.fill('Hello world');80await element.press('Enter');

Full Screen

Using AI Code Generation

copy

Full Screen

1async boxAbove(): Promise<Rect> {2 const { x, y, width, height } = await this._mainFrame._utilityWorld().evaluate((injected, node) => {3 const { x, y, width, height } = node.getBoundingClientRect();4 const element = document.elementFromPoint(x + width / 2, y + height / 2);5 const box = element && element.getBoundingClientRect();6 return box ? { x: box.x, y: box.y, width: box.width, height: box.height } : null;7 }, this);8 return { x, y, width, height };9}10async boxBelow(): Promise<Rect> {11 const { x, y, width, height } = await this._mainFrame._utilityWorld().evaluate((injected, node) => {12 const { x, y, width, height } = node.getBoundingClientRect();13 const element = document.elementFromPoint(x + width / 2, y - 1);14 const box = element && element.getBoundingClientRect();15 return box ? { x: box.x, y: box.y, width: box.width, height: box.height } : null;16 }, this);17 return { x, y, width, height };18}

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful