code
stringlengths
2
1.05M
// JavaScript Document var datable_result; var _url_path = baseurl+'enrolment/new_enrolment/'; var _url_edit = baseurl+'enrolment/new_enrolment/'; var _url_del = baseurl+'enrolment/delete/'; $(document).ready(function() { datable_result = $('#datable_score_student').DataTable( { // fixedColumns : true, "filter" : true, "info" : true, "paging" : true, "ordering" : true, "processing" : true, "serverSide" : true , dom : "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>tp", buttons: [ {extend: 'copy',className: 'btn-sm'}, {extend: 'csv',title: 'ExampleFile', className: 'btn-sm'}, {extend: 'pdf', title: 'ExampleFile', className: 'btn-sm'}, {extend: 'print',className: 'btn-sm'} ], "ajax" : { "url" : baseurl+'staff/get_employee_data', "type" : 'POST', "destroy" : true }, language: { processing: "<img src='"+baseurl+"assets/images/reload.gif'>", loadingRecords: "<img src='"+baseurl+"assets/images/reload.gif'>", "url": baseurl+"assets/langs/kh.json" }, "columns" : [ { "data" : "emp_code"}, { "data" : "latin_last_name" }, { "data" : "gender_id" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" }, { "data" : "position_level" } ], "order": [[0, 'desc']] }); } ); function edit_enrolment_data(url){ $.ajax({ type: "POST", url: url, //dataType:"JSON", //data: $("#frmNewEnrolment").serialize(), // serializes the form's elements. success: function(data){ //alert(data); $('#modal_ajax').modal('hide'); $('#document_render').html(data); } }); } // function on_delete_data(url){ delete_data(url,remove_row); } // function remove_row(url){ $.ajax({ type: "POST", url: url, success: function(data){ datable_result.draw(); } }); }
(function(root, factory) { if (typeof define === 'function' && define.amd) { define('three.SoftwareRenderer', ['three'], factory); } else if ('undefined' !== typeof exports && 'undefined' !== typeof module) { module.exports = factory(require('three')); } else { factory(root.THREE); } }(this, function(THREE) { /** * @author mrdoob / http://mrdoob.com/ * @author ryg / http://farbrausch.de/~fg * @author mraleph / http://mrale.ph/ * @author daoshengmu / http://dsmu.me/ */ THREE.SoftwareRenderer = function ( parameters ) { console.log( 'THREE.SoftwareRenderer', THREE.REVISION ); parameters = parameters || {}; var canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ); var context = canvas.getContext( '2d', { alpha: parameters.alpha === true } ); var alpha = parameters.alpha; var shaders = {}; var textures = {}; var canvasWidth, canvasHeight; var canvasWBlocks, canvasHBlocks; var viewportXScale, viewportYScale, viewportZScale; var viewportXOffs, viewportYOffs, viewportZOffs; var clearColor = new THREE.Color( 0x000000 ); var imagedata, data, zbuffer; var numBlocks, blockMaxZ, blockFlags; var BLOCK_ISCLEAR = ( 1 << 0 ); var BLOCK_NEEDCLEAR = ( 1 << 1 ); var subpixelBits = 4; var subpixelBias = ( 1 << subpixelBits ) - 1; var blockShift = 3; var blockSize = 1 << blockShift; var maxZVal = ( 1 << 24 ); // Note: You want to size this so you don't get overflows. var lineMode = false; var lookVector = new THREE.Vector3( 0, 0, 1 ); var crossVector = new THREE.Vector3(); var rectx1 = Infinity, recty1 = Infinity; var rectx2 = 0, recty2 = 0; var prevrectx1 = Infinity, prevrecty1 = Infinity; var prevrectx2 = 0, prevrecty2 = 0; var projector = new THREE.Projector(); var spriteV1 = new THREE.Vector4(); var spriteV2 = new THREE.Vector4(); var spriteV3 = new THREE.Vector4(); var spriteUV1 = new THREE.Vector2(); var spriteUV2 = new THREE.Vector2(); var spriteUV3 = new THREE.Vector2(); var mpVPool = []; var mpVPoolCount = 0; var mpNPool = []; var mpNPoolCount = 0; var mpUVPool = []; var mpUVPoolCount = 0; this.domElement = canvas; this.autoClear = true; // WebGLRenderer compatibility this.supportsVertexTextures = function () {}; this.setFaceCulling = function () {}; this.setClearColor = function ( color, alpha ) { clearColor.set( color ); clearColorBuffer( clearColor ); }; this.setPixelRatio = function () {}; this.setSize = function ( width, height ) { canvasWBlocks = Math.floor( width / blockSize ); canvasHBlocks = Math.floor( height / blockSize ); canvasWidth = canvasWBlocks * blockSize; canvasHeight = canvasHBlocks * blockSize; var fixScale = 1 << subpixelBits; viewportXScale = fixScale * canvasWidth / 2; viewportYScale = - fixScale * canvasHeight / 2; viewportZScale = maxZVal / 2; viewportXOffs = fixScale * canvasWidth / 2 + 0.5; viewportYOffs = fixScale * canvasHeight / 2 + 0.5; viewportZOffs = maxZVal / 2 + 0.5; canvas.width = canvasWidth; canvas.height = canvasHeight; context.fillStyle = alpha ? "rgba(0, 0, 0, 0)" : clearColor.getStyle(); context.fillRect( 0, 0, canvasWidth, canvasHeight ); imagedata = context.getImageData( 0, 0, canvasWidth, canvasHeight ); data = imagedata.data; zbuffer = new Int32Array( data.length / 4 ); numBlocks = canvasWBlocks * canvasHBlocks; blockMaxZ = new Int32Array( numBlocks ); blockFlags = new Uint8Array( numBlocks ); for ( var i = 0, l = zbuffer.length; i < l; i ++ ) { zbuffer[ i ] = maxZVal; } for ( var i = 0; i < numBlocks; i ++ ) { blockFlags[ i ] = BLOCK_ISCLEAR; } clearColorBuffer( clearColor ); }; this.setSize( canvas.width, canvas.height ); this.clear = function () { rectx1 = Infinity; recty1 = Infinity; rectx2 = 0; recty2 = 0; mpVPoolCount = 0; mpNPoolCount = 0; mpUVPoolCount = 0; for ( var i = 0; i < numBlocks; i ++ ) { blockMaxZ[ i ] = maxZVal; blockFlags[ i ] = ( blockFlags[ i ] & BLOCK_ISCLEAR ) ? BLOCK_ISCLEAR : BLOCK_NEEDCLEAR; } }; this.render = function ( scene, camera ) { // TODO: Check why autoClear can't be false. this.clear(); var background = scene.background; if ( background && background.isColor ) { clearColorBuffer( background ); } var renderData = projector.projectScene( scene, camera, false, false ); var elements = renderData.elements; for ( var e = 0, el = elements.length; e < el; e ++ ) { var element = elements[ e ]; var material = element.material; var shader = getMaterialShader( material ); if ( !shader ) continue; if ( element instanceof THREE.RenderableFace ) { if ( ! element.uvs ) { drawTriangle( element.v1.positionScreen, element.v2.positionScreen, element.v3.positionScreen, null, null, null, shader, element, material ); } else { drawTriangle( element.v1.positionScreen, element.v2.positionScreen, element.v3.positionScreen, element.uvs[ 0 ], element.uvs[ 1 ], element.uvs[ 2 ], shader, element, material ); } } else if ( element instanceof THREE.RenderableSprite ) { var scaleX = element.scale.x * 0.5; var scaleY = element.scale.y * 0.5; spriteV1.copy( element ); spriteV1.x -= scaleX; spriteV1.y += scaleY; spriteV2.copy( element ); spriteV2.x -= scaleX; spriteV2.y -= scaleY; spriteV3.copy( element ); spriteV3.x += scaleX; spriteV3.y += scaleY; if ( material.map ) { spriteUV1.set( 0, 1 ); spriteUV2.set( 0, 0 ); spriteUV3.set( 1, 1 ); drawTriangle( spriteV1, spriteV2, spriteV3, spriteUV1, spriteUV2, spriteUV3, shader, element, material ); } else { drawTriangle( spriteV1, spriteV2, spriteV3, null, null, null, shader, element, material ); } spriteV1.copy( element ); spriteV1.x += scaleX; spriteV1.y += scaleY; spriteV2.copy( element ); spriteV2.x -= scaleX; spriteV2.y -= scaleY; spriteV3.copy( element ); spriteV3.x += scaleX; spriteV3.y -= scaleY; if ( material.map ) { spriteUV1.set( 1, 1 ); spriteUV2.set( 0, 0 ); spriteUV3.set( 1, 0 ); drawTriangle( spriteV1, spriteV2, spriteV3, spriteUV1, spriteUV2, spriteUV3, shader, element, material ); } else { drawTriangle( spriteV1, spriteV2, spriteV3, null, null, null, shader, element, material ); } } else if ( element instanceof THREE.RenderableLine ) { var shader = getMaterialShader( material ); drawLine( element.v1.positionScreen, element.v2.positionScreen, element.vertexColors[0], element.vertexColors[1], shader, material ); } } finishClear(); var x = Math.min( rectx1, prevrectx1 ); var y = Math.min( recty1, prevrecty1 ); var width = Math.max( rectx2, prevrectx2 ) - x; var height = Math.max( recty2, prevrecty2 ) - y; /* // debug; draw zbuffer for ( var i = 0, l = zbuffer.length; i < l; i++ ) { var o = i * 4; var v = (65535 - zbuffer[ i ]) >> 3; data[ o + 0 ] = v; data[ o + 1 ] = v; data[ o + 2 ] = v; data[ o + 3 ] = 255; } */ if ( x !== Infinity ) { context.putImageData( imagedata, 0, 0, x, y, width, height ); } prevrectx1 = rectx1; prevrecty1 = recty1; prevrectx2 = rectx2; prevrecty2 = recty2; }; function setSize( width, height ) { canvasWBlocks = Math.floor( width / blockSize ); canvasHBlocks = Math.floor( height / blockSize ); canvasWidth = canvasWBlocks * blockSize; canvasHeight = canvasHBlocks * blockSize; var fixScale = 1 << subpixelBits; viewportXScale = fixScale * canvasWidth / 2; viewportYScale = -fixScale * canvasHeight / 2; viewportZScale = maxZVal / 2; viewportXOffs = fixScale * canvasWidth / 2 + 0.5; viewportYOffs = fixScale * canvasHeight / 2 + 0.5; viewportZOffs = maxZVal / 2 + 0.5; canvas.width = canvasWidth; canvas.height = canvasHeight; context.fillStyle = alpha ? "rgba(0, 0, 0, 0)" : clearColor.getStyle(); context.fillRect( 0, 0, canvasWidth, canvasHeight ); imagedata = context.getImageData( 0, 0, canvasWidth, canvasHeight ); data = imagedata.data; zbuffer = new Int32Array( data.length / 4 ); numBlocks = canvasWBlocks * canvasHBlocks; blockMaxZ = new Int32Array( numBlocks ); blockFlags = new Uint8Array( numBlocks ); for ( var i = 0, l = zbuffer.length; i < l; i ++ ) { zbuffer[ i ] = maxZVal; } for ( var i = 0; i < numBlocks; i ++ ) { blockFlags[ i ] = BLOCK_ISCLEAR; } clearColorBuffer( clearColor ); } function clearColorBuffer( color ) { var size = canvasWidth * canvasHeight * 4; for ( var i = 0; i < size; i += 4 ) { data[ i ] = color.r * 255 | 0; data[ i + 1 ] = color.g * 255 | 0; data[ i + 2 ] = color.b * 255 | 0; data[ i + 3 ] = alpha ? 0 : 255; } context.fillStyle = alpha ? "rgba(0, 0, 0, 0)" : color.getStyle(); context.fillRect( 0, 0, canvasWidth, canvasHeight ); } function getPalette( material, bSimulateSpecular ) { var i = 0, j = 0; var diffuseR = material.color.r * 255; var diffuseG = material.color.g * 255; var diffuseB = material.color.b * 255; var palette = new Uint8Array( 256 * 3 ); if ( bSimulateSpecular ) { while ( i < 204 ) { palette[ j ++ ] = Math.min( i * diffuseR / 204, 255 ); palette[ j ++ ] = Math.min( i * diffuseG / 204, 255 ); palette[ j ++ ] = Math.min( i * diffuseB / 204, 255 ); ++ i; } while ( i < 256 ) { // plus specular highlight palette[ j ++ ] = Math.min( diffuseR + ( i - 204 ) * ( 255 - diffuseR ) / 82, 255 ); palette[ j ++ ] = Math.min( diffuseG + ( i - 204 ) * ( 255 - diffuseG ) / 82, 255 ); palette[ j ++ ] = Math.min( diffuseB + ( i - 204 ) * ( 255 - diffuseB ) / 82, 255 ); ++ i; } } else { while ( i < 256 ) { palette[ j ++ ] = Math.min( i * diffuseR / 255, 255 ); palette[ j ++ ] = Math.min( i * diffuseG / 255, 255 ); palette[ j ++ ] = Math.min( i * diffuseB / 255, 255 ); ++ i; } } return palette; } function basicMaterialShader( buffer, depthBuf, offset, depth, u, v, n, face, material ) { var colorOffset = offset * 4; var texture = textures[ material.map.id ]; if ( ! texture.data ) return; var tdim = texture.width; var isTransparent = material.transparent; var tbound = tdim - 1; var tdata = texture.data; var tIndex = ( ( ( v * tdim ) & tbound ) * tdim + ( ( u * tdim ) & tbound ) ) * 4; if ( ! isTransparent ) { buffer[ colorOffset ] = tdata[ tIndex ]; buffer[ colorOffset + 1 ] = tdata[ tIndex + 1 ]; buffer[ colorOffset + 2 ] = tdata[ tIndex + 2 ]; buffer[ colorOffset + 3 ] = ( material.opacity << 8 ) - 1; depthBuf[ offset ] = depth; } else { var srcR = tdata[ tIndex ]; var srcG = tdata[ tIndex + 1 ]; var srcB = tdata[ tIndex + 2 ]; var opaci = tdata[ tIndex + 3 ] * material.opacity / 255; var destR = buffer[ colorOffset ]; var destG = buffer[ colorOffset + 1 ]; var destB = buffer[ colorOffset + 2 ]; buffer[ colorOffset ] = ( srcR * opaci + destR * ( 1 - opaci ) ); buffer[ colorOffset + 1 ] = ( srcG * opaci + destG * ( 1 - opaci ) ); buffer[ colorOffset + 2 ] = ( srcB * opaci + destB * ( 1 - opaci ) ); buffer[ colorOffset + 3 ] = ( material.opacity << 8 ) - 1; if ( buffer[ colorOffset + 3 ] == 255 ) // Only opaue pixls write to the depth buffer depthBuf[ offset ] = depth; } } function lightingMaterialShader( buffer, depthBuf, offset, depth, u, v, n, face, material ) { var colorOffset = offset * 4; var texture = textures[ material.map.id ]; if ( ! texture.data ) return; var tdim = texture.width; var isTransparent = material.transparent; var cIndex = ( n > 0 ? ( ~~ n ) : 0 ) * 3; var tbound = tdim - 1; var tdata = texture.data; var tIndex = ( ( ( v * tdim ) & tbound ) * tdim + ( ( u * tdim ) & tbound ) ) * 4; if ( ! isTransparent ) { buffer[ colorOffset ] = ( material.palette[ cIndex ] * tdata[ tIndex ] ) >> 8; buffer[ colorOffset + 1 ] = ( material.palette[ cIndex + 1 ] * tdata[ tIndex + 1 ] ) >> 8; buffer[ colorOffset + 2 ] = ( material.palette[ cIndex + 2 ] * tdata[ tIndex + 2 ] ) >> 8; buffer[ colorOffset + 3 ] = ( material.opacity << 8 ) - 1; depthBuf[ offset ] = depth; } else { var foreColorR = material.palette[ cIndex ] * tdata[ tIndex ]; var foreColorG = material.palette[ cIndex + 1 ] * tdata[ tIndex + 1 ]; var foreColorB = material.palette[ cIndex + 2 ] * tdata[ tIndex + 2 ]; var opaci = tdata[ tIndex + 3 ] * material.opacity / 256; var destR = buffer[ colorOffset ]; var destG = buffer[ colorOffset + 1 ]; var destB = buffer[ colorOffset + 2 ]; buffer[ colorOffset ] = foreColorR * opaci + destR * ( 1 - opaci ); buffer[ colorOffset + 1 ] = foreColorG * opaci + destG * ( 1 - opaci ); buffer[ colorOffset + 2 ] = foreColorB * opaci + destB * ( 1 - opaci ); buffer[ colorOffset + 3 ] = ( material.opacity << 8 ) - 1; if ( buffer[ colorOffset + 3 ] == 255 ) // Only opaue pixls write to the depth buffer depthBuf[ offset ] = depth; } } function onMaterialUpdate ( event ) { var material = event.target; material.removeEventListener( 'update', onMaterialUpdate ); delete shaders[ material.id ]; } function getMaterialShader( material ) { var id = material.id; var shader = shaders[ id ]; if ( shader && material.map && !textures[ material.map.id ] ) delete shaders[ id ]; if ( shaders[ id ] === undefined ) { material.addEventListener( 'update', onMaterialUpdate ); if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial || material instanceof THREE.SpriteMaterial ) { if ( material instanceof THREE.MeshLambertMaterial ) { // Generate color palette if ( ! material.palette ) { material.palette = getPalette( material, false ); } } else if ( material instanceof THREE.MeshPhongMaterial ) { // Generate color palette if ( ! material.palette ) { material.palette = getPalette( material, true ); } } var string; if ( material.map ) { var texture = new THREE.SoftwareRenderer.Texture(); texture.fromImage( material.map.image ); if ( !texture.data ) return; textures[ material.map.id ] = texture; if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.SpriteMaterial ) { shader = basicMaterialShader; } else { shader = lightingMaterialShader; } } else { if ( material.vertexColors === THREE.FaceColors ) { string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = face.color.r * 255;', 'buffer[ colorOffset + 1 ] = face.color.g * 255;', 'buffer[ colorOffset + 2 ] = face.color.b * 255;', 'buffer[ colorOffset + 3 ] = material.opacity * 255;', 'depthBuf[ offset ] = depth;' ].join( '\n' ); } else { string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = material.color.r * 255;', 'buffer[ colorOffset + 1 ] = material.color.g * 255;', 'buffer[ colorOffset + 2 ] = material.color.b * 255;', 'buffer[ colorOffset + 3 ] = material.opacity * 255;', 'depthBuf[ offset ] = depth;' ].join( '\n' ); } shader = new Function( 'buffer, depthBuf, offset, depth, u, v, n, face, material', string ); } } else if ( material instanceof THREE.LineBasicMaterial ) { var string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = material.color.r * (color1.r+color2.r) * 0.5 * 255;', 'buffer[ colorOffset + 1 ] = material.color.g * (color1.g+color2.g) * 0.5 * 255;', 'buffer[ colorOffset + 2 ] = material.color.b * (color1.b+color2.b) * 0.5 * 255;', 'buffer[ colorOffset + 3 ] = 255;', 'depthBuf[ offset ] = depth;' ].join('\n'); shader = new Function( 'buffer, depthBuf, offset, depth, color1, color2, material', string ); } else { var string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = u * 255;', 'buffer[ colorOffset + 1 ] = v * 255;', 'buffer[ colorOffset + 2 ] = 0;', 'buffer[ colorOffset + 3 ] = 255;', 'depthBuf[ offset ] = depth;' ].join( '\n' ); shader = new Function( 'buffer, depthBuf, offset, depth, u, v, n, face, material', string ); } shaders[ id ] = shader; } return shader; } function clearRectangle( x1, y1, x2, y2 ) { var xmin = Math.max( Math.min( x1, x2 ), 0 ); var xmax = Math.min( Math.max( x1, x2 ), canvasWidth ); var ymin = Math.max( Math.min( y1, y2 ), 0 ); var ymax = Math.min( Math.max( y1, y2 ), canvasHeight ); var offset = ( xmin + ymin * canvasWidth ) * 4 + 3; var linestep = ( canvasWidth - ( xmax - xmin ) ) * 4; for ( var y = ymin; y < ymax; y ++ ) { for ( var x = xmin; x < xmax; x ++ ) { data[ offset += 4 ] = 0; } offset += linestep; } } function drawTriangle( v1, v2, v3, uv1, uv2, uv3, shader, face, material ) { // TODO: Implement per-pixel z-clipping if ( v1.z < - 1 || v1.z > 1 || v2.z < - 1 || v2.z > 1 || v3.z < - 1 || v3.z > 1 ) return; // https://gist.github.com/2486101 // explanation: http://pouet.net/topic.php?which=8760&page=1 var fixscale = ( 1 << subpixelBits ); // 28.4 fixed-point coordinates var x1 = ( v1.x * viewportXScale + viewportXOffs ) | 0; var x2 = ( v2.x * viewportXScale + viewportXOffs ) | 0; var x3 = ( v3.x * viewportXScale + viewportXOffs ) | 0; var y1 = ( v1.y * viewportYScale + viewportYOffs ) | 0; var y2 = ( v2.y * viewportYScale + viewportYOffs ) | 0; var y3 = ( v3.y * viewportYScale + viewportYOffs ) | 0; var bHasNormal = face.vertexNormalsModel && face.vertexNormalsModel.length; var bHasUV = uv1 && uv2 && uv3; var longestSide = Math.max( Math.sqrt( (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) ), Math.sqrt( (x2 - x3)*(x2 - x3) + (y2 - y3)*(y2 - y3) ), Math.sqrt( (x3 - x1)*(x3 - x1) + (y3 - y1)*(y3 - y1) ) ); if( !(face instanceof THREE.RenderableSprite) && (longestSide > 100 * fixscale) ) { // 1 // |\ // |a\ // |__\ // |\c|\ // |b\|d\ // |__\__\ // 2 3 var tempFace = { vertexNormalsModel : [], color : face.color }; var mpUV12, mpUV23, mpUV31; if ( bHasUV ) { if ( mpUVPoolCount === mpUVPool.length ) { mpUV12 = new THREE.Vector2(); mpUVPool.push( mpUV12 ); ++mpUVPoolCount; mpUV23 = new THREE.Vector2(); mpUVPool.push( mpUV23 ); ++mpUVPoolCount; mpUV31 = new THREE.Vector2(); mpUVPool.push( mpUV31 ); ++mpUVPoolCount; } else { mpUV12 = mpUVPool[ mpUVPoolCount ]; ++mpUVPoolCount; mpUV23 = mpUVPool[ mpUVPoolCount ]; ++mpUVPoolCount; mpUV31 = mpUVPool[ mpUVPoolCount ]; ++mpUVPoolCount; } var weight; weight = (1 + v2.z) * (v2.w / v1.w) / (1 + v1.z); mpUV12.copy( uv1 ).multiplyScalar( weight ).add( uv2 ).multiplyScalar( 1 / (weight + 1) ); weight = (1 + v3.z) * (v3.w / v2.w) / (1 + v2.z); mpUV23.copy( uv2 ).multiplyScalar( weight ).add( uv3 ).multiplyScalar( 1 / (weight + 1) ); weight = (1 + v1.z) * (v1.w / v3.w) / (1 + v3.z); mpUV31.copy( uv3 ).multiplyScalar( weight ).add( uv1 ).multiplyScalar( 1 / (weight + 1) ); } var mpV12, mpV23, mpV31; if ( mpVPoolCount === mpVPool.length ) { mpV12 = new THREE.Vector4(); mpVPool.push( mpV12 ); ++mpVPoolCount; mpV23 = new THREE.Vector4(); mpVPool.push( mpV23 ); ++mpVPoolCount; mpV31 = new THREE.Vector4(); mpVPool.push( mpV31 ); ++mpVPoolCount; } else { mpV12 = mpVPool[ mpVPoolCount ]; ++mpVPoolCount; mpV23 = mpVPool[ mpVPoolCount ]; ++mpVPoolCount; mpV31 = mpVPool[ mpVPoolCount ]; ++mpVPoolCount; } mpV12.copy( v1 ).add( v2 ).multiplyScalar( 0.5 ); mpV23.copy( v2 ).add( v3 ).multiplyScalar( 0.5 ); mpV31.copy( v3 ).add( v1 ).multiplyScalar( 0.5 ); var mpN12, mpN23, mpN31; if( bHasNormal ) { if ( mpNPoolCount === mpNPool.length ) { mpN12 = new THREE.Vector3(); mpNPool.push( mpN12 ); ++mpNPoolCount; mpN23 = new THREE.Vector3(); mpNPool.push( mpN23 ); ++mpNPoolCount; mpN31 = new THREE.Vector3(); mpNPool.push( mpN31 ); ++mpNPoolCount; } else { mpN12 = mpNPool[ mpNPoolCount ]; ++mpNPoolCount; mpN23 = mpNPool[ mpNPoolCount ]; ++mpNPoolCount; mpN31 = mpNPool[ mpNPoolCount ]; ++mpNPoolCount; } mpN12.copy( face.vertexNormalsModel[ 0 ] ).add( face.vertexNormalsModel[ 1 ] ).normalize(); mpN23.copy( face.vertexNormalsModel[ 1 ] ).add( face.vertexNormalsModel[ 2 ] ).normalize(); mpN31.copy( face.vertexNormalsModel[ 2 ] ).add( face.vertexNormalsModel[ 0 ] ).normalize(); } // a if( bHasNormal ) { tempFace.vertexNormalsModel[ 0 ] = face.vertexNormalsModel[ 0 ]; tempFace.vertexNormalsModel[ 1 ] = mpN12; tempFace.vertexNormalsModel[ 2 ] = mpN31; } drawTriangle( v1, mpV12, mpV31, uv1, mpUV12, mpUV31, shader, tempFace, material ); // b if( bHasNormal ) { tempFace.vertexNormalsModel[ 0 ] = face.vertexNormalsModel[ 1 ]; tempFace.vertexNormalsModel[ 1 ] = mpN23; tempFace.vertexNormalsModel[ 2 ] = mpN12; } drawTriangle( v2, mpV23, mpV12, uv2, mpUV23, mpUV12, shader, tempFace, material ); // c if( bHasNormal ) { tempFace.vertexNormalsModel[ 0 ] = mpN12; tempFace.vertexNormalsModel[ 1 ] = mpN23; tempFace.vertexNormalsModel[ 2 ] = mpN31; } drawTriangle( mpV12, mpV23, mpV31, mpUV12, mpUV23, mpUV31, shader, tempFace, material ); // d if( bHasNormal ) { tempFace.vertexNormalsModel[ 0 ] = face.vertexNormalsModel[ 2 ]; tempFace.vertexNormalsModel[ 1 ] = mpN31; tempFace.vertexNormalsModel[ 2 ] = mpN23; } drawTriangle( v3, mpV31, mpV23, uv3, mpUV31, mpUV23, shader, tempFace, material ); return; } // Z values (.28 fixed-point) var z1 = ( v1.z * viewportZScale + viewportZOffs ) | 0; var z2 = ( v2.z * viewportZScale + viewportZOffs ) | 0; var z3 = ( v3.z * viewportZScale + viewportZOffs ) | 0; // UV values var bHasUV = false; var tu1, tv1, tu2, tv2, tu3, tv3; if ( uv1 && uv2 && uv3 ) { bHasUV = true; tu1 = uv1.x; tv1 = 1 - uv1.y; tu2 = uv2.x; tv2 = 1 - uv2.y; tu3 = uv3.x; tv3 = 1 - uv3.y; } // Normal values var n1, n2, n3, nz1, nz2, nz3; if ( bHasNormal ) { n1 = face.vertexNormalsModel[ 0 ]; n2 = face.vertexNormalsModel[ 1 ]; n3 = face.vertexNormalsModel[ 2 ]; nz1 = n1.z * 255; nz2 = n2.z * 255; nz3 = n3.z * 255; } // Deltas var dx12 = x1 - x2, dy12 = y2 - y1; var dx23 = x2 - x3, dy23 = y3 - y2; var dx31 = x3 - x1, dy31 = y1 - y3; // Bounding rectangle var minx = Math.max( ( Math.min( x1, x2, x3 ) + subpixelBias ) >> subpixelBits, 0 ); var maxx = Math.min( ( Math.max( x1, x2, x3 ) + subpixelBias ) >> subpixelBits, canvasWidth ); var miny = Math.max( ( Math.min( y1, y2, y3 ) + subpixelBias ) >> subpixelBits, 0 ); var maxy = Math.min( ( Math.max( y1, y2, y3 ) + subpixelBias ) >> subpixelBits, canvasHeight ); rectx1 = Math.min( minx, rectx1 ); rectx2 = Math.max( maxx, rectx2 ); recty1 = Math.min( miny, recty1 ); recty2 = Math.max( maxy, recty2 ); // Block size, standard 8x8 (must be power of two) var q = blockSize; // Start in corner of 8x8 block minx &= ~ ( q - 1 ); miny &= ~ ( q - 1 ); // Constant part of half-edge functions var minXfixscale = ( minx << subpixelBits ); var minYfixscale = ( miny << subpixelBits ); var c1 = dy12 * ( ( minXfixscale ) - x1 ) + dx12 * ( ( minYfixscale ) - y1 ); var c2 = dy23 * ( ( minXfixscale ) - x2 ) + dx23 * ( ( minYfixscale ) - y2 ); var c3 = dy31 * ( ( minXfixscale ) - x3 ) + dx31 * ( ( minYfixscale ) - y3 ); // Correct for fill convention if ( dy12 > 0 || ( dy12 == 0 && dx12 > 0 ) ) c1 ++; if ( dy23 > 0 || ( dy23 == 0 && dx23 > 0 ) ) c2 ++; if ( dy31 > 0 || ( dy31 == 0 && dx31 > 0 ) ) c3 ++; // Note this doesn't kill subpixel precision, but only because we test for >=0 (not >0). // It's a bit subtle. :) c1 = ( c1 - 1 ) >> subpixelBits; c2 = ( c2 - 1 ) >> subpixelBits; c3 = ( c3 - 1 ) >> subpixelBits; // Z interpolation setup var dz12 = z1 - z2, dz31 = z3 - z1; var invDet = 1.0 / ( dx12 * dy31 - dx31 * dy12 ); var dzdx = ( invDet * ( dz12 * dy31 - dz31 * dy12 ) ); // dz per one subpixel step in x var dzdy = ( invDet * ( dz12 * dx31 - dx12 * dz31 ) ); // dz per one subpixel step in y // Z at top/left corner of rast area var cz = ( z1 + ( ( minXfixscale ) - x1 ) * dzdx + ( ( minYfixscale ) - y1 ) * dzdy ) | 0; // Z pixel steps dzdx = ( dzdx * fixscale ) | 0; dzdy = ( dzdy * fixscale ) | 0; var dtvdx, dtvdy, cbtu, cbtv; if ( bHasUV ) { // UV interpolation setup var dtu12 = tu1 - tu2, dtu31 = tu3 - tu1; var dtudx = ( invDet * ( dtu12 * dy31 - dtu31 * dy12 ) ); // dtu per one subpixel step in x var dtudy = ( invDet * ( dtu12 * dx31 - dx12 * dtu31 ) ); // dtu per one subpixel step in y var dtv12 = tv1 - tv2, dtv31 = tv3 - tv1; dtvdx = ( invDet * ( dtv12 * dy31 - dtv31 * dy12 ) ); // dtv per one subpixel step in x dtvdy = ( invDet * ( dtv12 * dx31 - dx12 * dtv31 ) ); // dtv per one subpixel step in y // UV at top/left corner of rast area cbtu = ( tu1 + ( minXfixscale - x1 ) * dtudx + ( minYfixscale - y1 ) * dtudy ); cbtv = ( tv1 + ( minXfixscale - x1 ) * dtvdx + ( minYfixscale - y1 ) * dtvdy ); // UV pixel steps dtudx = dtudx * fixscale; dtudy = dtudy * fixscale; dtvdx = dtvdx * fixscale; dtvdy = dtvdy * fixscale; } var dnxdx, dnzdy, cbnz; if ( bHasNormal ) { // Normal interpolation setup var dnz12 = nz1 - nz2, dnz31 = nz3 - nz1; var dnzdx = ( invDet * ( dnz12 * dy31 - dnz31 * dy12 ) ); // dnz per one subpixel step in x var dnzdy = ( invDet * ( dnz12 * dx31 - dx12 * dnz31 ) ); // dnz per one subpixel step in y // Normal at top/left corner of rast area cbnz = ( nz1 + ( minXfixscale - x1 ) * dnzdx + ( minYfixscale - y1 ) * dnzdy ); // Normal pixel steps dnzdx = ( dnzdx * fixscale ); dnzdy = ( dnzdy * fixscale ); } // Set up min/max corners var qm1 = q - 1; // for convenience var nmin1 = 0, nmax1 = 0; var nmin2 = 0, nmax2 = 0; var nmin3 = 0, nmax3 = 0; var nminz = 0, nmaxz = 0; if ( dx12 >= 0 ) nmax1 -= qm1 * dx12; else nmin1 -= qm1 * dx12; if ( dy12 >= 0 ) nmax1 -= qm1 * dy12; else nmin1 -= qm1 * dy12; if ( dx23 >= 0 ) nmax2 -= qm1 * dx23; else nmin2 -= qm1 * dx23; if ( dy23 >= 0 ) nmax2 -= qm1 * dy23; else nmin2 -= qm1 * dy23; if ( dx31 >= 0 ) nmax3 -= qm1 * dx31; else nmin3 -= qm1 * dx31; if ( dy31 >= 0 ) nmax3 -= qm1 * dy31; else nmin3 -= qm1 * dy31; if ( dzdx >= 0 ) nmaxz += qm1 * dzdx; else nminz += qm1 * dzdx; if ( dzdy >= 0 ) nmaxz += qm1 * dzdy; else nminz += qm1 * dzdy; // Loop through blocks var linestep = canvasWidth - q; var cb1 = c1; var cb2 = c2; var cb3 = c3; var cbz = cz; var qstep = - q; var e1x = qstep * dy12; var e2x = qstep * dy23; var e3x = qstep * dy31; var ezx = qstep * dzdx; var etux, etvx; if ( bHasUV ) { etux = qstep * dtudx; etvx = qstep * dtvdx; } var enzx; if ( bHasNormal ) { enzx = qstep * dnzdx; } var x0 = minx; for ( var y0 = miny; y0 < maxy; y0 += q ) { // New block line - keep hunting for tri outer edge in old block line dir while ( x0 >= minx && x0 < maxx && cb1 >= nmax1 && cb2 >= nmax2 && cb3 >= nmax3 ) { x0 += qstep; cb1 += e1x; cb2 += e2x; cb3 += e3x; cbz += ezx; if ( bHasUV ) { cbtu += etux; cbtv += etvx; } if ( bHasNormal ) { cbnz += enzx; } } // Okay, we're now in a block we know is outside. Reverse direction and go into main loop. qstep = - qstep; e1x = - e1x; e2x = - e2x; e3x = - e3x; ezx = - ezx; if ( bHasUV ) { etux = - etux; etvx = - etvx; } if ( bHasNormal ) { enzx = - enzx; } while ( 1 ) { // Step everything x0 += qstep; cb1 += e1x; cb2 += e2x; cb3 += e3x; cbz += ezx; if ( bHasUV ) { cbtu += etux; cbtv += etvx; } if ( bHasNormal ) { cbnz += enzx; } // We're done with this block line when at least one edge completely out // If an edge function is too small and decreasing in the current traversal // dir, we're done with this line. if ( x0 < minx || x0 >= maxx ) break; if ( cb1 < nmax1 ) if ( e1x < 0 ) break; else continue; if ( cb2 < nmax2 ) if ( e2x < 0 ) break; else continue; if ( cb3 < nmax3 ) if ( e3x < 0 ) break; else continue; // We can skip this block if it's already fully covered var blockX = x0 >> blockShift; var blockY = y0 >> blockShift; var blockId = blockX + blockY * canvasWBlocks; var minz = cbz + nminz; // farthest point in block closer than closest point in our tri? if ( blockMaxZ[ blockId ] < minz ) continue; // Need to do a deferred clear? var bflags = blockFlags[ blockId ]; if ( bflags & BLOCK_NEEDCLEAR ) clearBlock( blockX, blockY ); blockFlags[ blockId ] = bflags & ~ ( BLOCK_ISCLEAR | BLOCK_NEEDCLEAR ); // Offset at top-left corner var offset = x0 + y0 * canvasWidth; // Accept whole block when fully covered if ( cb1 >= nmin1 && cb2 >= nmin2 && cb3 >= nmin3 ) { var maxz = cbz + nmaxz; blockMaxZ[ blockId ] = Math.min( blockMaxZ[ blockId ], maxz ); var cy1 = cb1; var cy2 = cb2; var cyz = cbz; var cytu, cytv; if ( bHasUV ) { cytu = cbtu; cytv = cbtv; } var cynz; if ( bHasNormal ) { cynz = cbnz; } for ( var iy = 0; iy < q; iy ++ ) { var cx1 = cy1; var cx2 = cy2; var cxz = cyz; var cxtu; var cxtv; if ( bHasUV ) { cxtu = cytu; cxtv = cytv; } var cxnz; if ( bHasNormal ) { cxnz = cynz; } for ( var ix = 0; ix < q; ix ++ ) { var z = cxz; if ( z < zbuffer[ offset ] ) { shader( data, zbuffer, offset, z, cxtu, cxtv, cxnz, face, material ); } cx1 += dy12; cx2 += dy23; cxz += dzdx; if ( bHasUV ) { cxtu += dtudx; cxtv += dtvdx; } if ( bHasNormal ) { cxnz += dnzdx; } offset ++; } cy1 += dx12; cy2 += dx23; cyz += dzdy; if ( bHasUV ) { cytu += dtudy; cytv += dtvdy; } if ( bHasNormal ) { cynz += dnzdy; } offset += linestep; } } else { // Partially covered block var cy1 = cb1; var cy2 = cb2; var cy3 = cb3; var cyz = cbz; var cytu, cytv; if ( bHasUV ) { cytu = cbtu; cytv = cbtv; } var cynz; if ( bHasNormal ) { cynz = cbnz; } for ( var iy = 0; iy < q; iy ++ ) { var cx1 = cy1; var cx2 = cy2; var cx3 = cy3; var cxz = cyz; var cxtu; var cxtv; if ( bHasUV ) { cxtu = cytu; cxtv = cytv; } var cxnz; if ( bHasNormal ) { cxnz = cynz; } for ( var ix = 0; ix < q; ix ++ ) { if ( ( cx1 | cx2 | cx3 ) >= 0 ) { var z = cxz; if ( z < zbuffer[ offset ] ) { shader( data, zbuffer, offset, z, cxtu, cxtv, cxnz, face, material ); } } cx1 += dy12; cx2 += dy23; cx3 += dy31; cxz += dzdx; if ( bHasUV ) { cxtu += dtudx; cxtv += dtvdx; } if ( bHasNormal ) { cxnz += dnzdx; } offset ++; } cy1 += dx12; cy2 += dx23; cy3 += dx31; cyz += dzdy; if ( bHasUV ) { cytu += dtudy; cytv += dtvdy; } if ( bHasNormal ) { cynz += dnzdy; } offset += linestep; } } } // Advance to next row of blocks cb1 += q * dx12; cb2 += q * dx23; cb3 += q * dx31; cbz += q * dzdy; if ( bHasUV ) { cbtu += q * dtudy; cbtv += q * dtvdy; } if ( bHasNormal ) { cbnz += q * dnzdy; } } } // When drawing line, the blockShiftShift has to be zero. In order to clean pixel // Using color1 and color2 to interpolation pixel color // LineWidth is according to material.linewidth function drawLine( v1, v2, color1, color2, shader, material ) { // While the line mode is enable, blockSize has to be changed to 0. if ( !lineMode ) { lineMode = true; blockShift = 0; blockSize = 1 << blockShift; setSize( canvas.width, canvas.height ); } // TODO: Implement per-pixel z-clipping if ( v1.z < -1 || v1.z > 1 || v2.z < -1 || v2.z > 1 ) return; var halfLineWidth = Math.floor( ( material.linewidth - 1 ) * 0.5 ); // https://gist.github.com/2486101 // explanation: http://pouet.net/topic.php?which=8760&page=1 // 28.4 fixed-point coordinates var x1 = ( v1.x * viewportXScale + viewportXOffs ) | 0; var x2 = ( v2.x * viewportXScale + viewportXOffs ) | 0; var y1 = ( v1.y * viewportYScale + viewportYOffs ) | 0; var y2 = ( v2.y * viewportYScale + viewportYOffs ) | 0; var z1 = ( v1.z * viewportZScale + viewportZOffs ) | 0; var z2 = ( v2.z * viewportZScale + viewportZOffs ) | 0; // Deltas var dx12 = x1 - x2, dy12 = y1 - y2, dz12 = z1 - z2; // Bounding rectangle var minx = Math.max( ( Math.min( x1, x2 ) + subpixelBias ) >> subpixelBits, 0 ); var maxx = Math.min( ( Math.max( x1, x2 ) + subpixelBias ) >> subpixelBits, canvasWidth ); var miny = Math.max( ( Math.min( y1, y2 ) + subpixelBias ) >> subpixelBits, 0 ); var maxy = Math.min( ( Math.max( y1, y2 ) + subpixelBias ) >> subpixelBits, canvasHeight ); var minz = Math.max( ( Math.min( z1, z2 ) + subpixelBias ) >> subpixelBits, 0 ); var maxz = ( Math.max( z1, z2 ) + subpixelBias ) >> subpixelBits; rectx1 = Math.min( minx, rectx1 ); rectx2 = Math.max( maxx, rectx2 ); recty1 = Math.min( miny, recty1 ); recty2 = Math.max( maxy, recty2 ); // Get the line's unit vector and cross vector var length = Math.sqrt( ( dy12 * dy12 ) + ( dx12 * dx12 ) ); var unitX = ( dx12 / length ); var unitY = ( dy12 / length ); var unitZ = ( dz12 / length ); var pixelX, pixelY, pixelZ; var pX, pY, pZ; crossVector.set( unitX, unitY, unitZ ); crossVector.cross( lookVector ); crossVector.normalize(); while (length > 0) { // Get this pixel. pixelX = x2 + length * unitX; pixelY = y2 + length * unitY; pixelZ = z2 + length * unitZ; pixelX = ( pixelX + subpixelBias ) >> subpixelBits; pixelY = ( pixelY + subpixelBias ) >> subpixelBits; pZ = ( pixelZ + subpixelBias ) >> subpixelBits; // Draw line with line width for ( var i = -halfLineWidth; i <= halfLineWidth; ++i ) { // Compute the line pixels. // Get the pixels on the vector that crosses to the line vector pX = Math.floor( ( pixelX + crossVector.x * i ) ); pY = Math.floor( ( pixelY + crossVector.y * i ) ); // if pixel is over the rect. Continue if ( rectx1 >= pX || rectx2 <= pX || recty1 >= pY || recty2 <= pY ) continue; // Find this pixel at which block var blockX = pX >> blockShift; var blockY = pY >> blockShift; var blockId = blockX + blockY * canvasWBlocks; // Compare the pixel depth width z block. if ( blockMaxZ[ blockId ] < minz ) continue; blockMaxZ[ blockId ] = Math.min( blockMaxZ[ blockId ], maxz ); var bflags = blockFlags[ blockId ]; if ( bflags & BLOCK_NEEDCLEAR ) clearBlock( blockX, blockY ); blockFlags[ blockId ] = bflags & ~( BLOCK_ISCLEAR | BLOCK_NEEDCLEAR ); // draw pixel var offset = pX + pY * canvasWidth; if ( pZ < zbuffer[ offset ] ) { shader( data, zbuffer, offset, pZ, color1, color2, material ); } } --length; } } function clearBlock( blockX, blockY ) { var zoffset = blockX * blockSize + blockY * blockSize * canvasWidth; var poffset = zoffset * 4; var zlinestep = canvasWidth - blockSize; var plinestep = zlinestep * 4; for ( var y = 0; y < blockSize; y ++ ) { for ( var x = 0; x < blockSize; x ++ ) { zbuffer[ zoffset ++ ] = maxZVal; data[ poffset ++ ] = clearColor.r * 255 | 0; data[ poffset ++ ] = clearColor.g * 255 | 0; data[ poffset ++ ] = clearColor.b * 255 | 0; data[ poffset ++ ] = alpha ? 0 : 255; } zoffset += zlinestep; poffset += plinestep; } } function finishClear( ) { var block = 0; for ( var y = 0; y < canvasHBlocks; y ++ ) { for ( var x = 0; x < canvasWBlocks; x ++ ) { if ( blockFlags[ block ] & BLOCK_NEEDCLEAR ) { clearBlock( x, y ); blockFlags[ block ] = BLOCK_ISCLEAR; } block ++; } } } }; THREE.SoftwareRenderer.Texture = function() { var canvas; this.fromImage = function( image ) { if ( ! image || image.width <= 0 || image.height <= 0 ) return; if ( canvas === undefined ) { canvas = document.createElement( 'canvas' ); } var size = image.width > image.height ? image.width : image.height; size = THREE.Math.nextPowerOfTwo( size ); if ( canvas.width != size || canvas.height != size ) { canvas.width = size; canvas.height = size; } var ctx = canvas.getContext( '2d' ); ctx.clearRect( 0, 0, size, size ); ctx.drawImage( image, 0, 0, size, size ); var imgData = ctx.getImageData( 0, 0, size, size ); this.data = imgData.data; this.width = size; this.height = size; this.srcUrl = image.src; }; }; }));
import React from 'react'; import { shallow } from 'enzyme'; import FormElementControl from '../FormElementControl'; describe('<FormElementControl />', () => { let mounted = null; const child = <div className="foo" />; beforeEach(() => { mounted = shallow(<FormElementControl>{child}</FormElementControl>); }); it('renders the correct markup', () => { expect(mounted.find('.slds-form-element__control').contains(child)).toBeTruthy(); }); it('renders left icon', () => { mounted.setProps({ hasIconLeft: true }); expect(mounted.hasClass('slds-input-has-icon_right')).toBeFalsy(); expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon')).toBeTruthy(); expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon_left')).toBeTruthy(); }); it('renders right icon', () => { mounted.setProps({ hasIconRight: true }); expect(mounted.hasClass('slds-input-has-icon_left')).toBeFalsy(); expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon')).toBeTruthy(); expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon_right')).toBeTruthy(); }); it('renders left and right icon together', () => { mounted.setProps({ hasIconLeft: true, hasIconRight: true }); expect(mounted.hasClass('slds-input-has-icon_right')).toBeFalsy(); expect(mounted.hasClass('slds-input-has-icon_left')).toBeFalsy(); expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon')).toBeTruthy(); expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon_left-right')).toBeTruthy(); }); it('applies className and rest-properties', () => { mounted.setProps({ className: 'foo', 'data-test': 'bar' }); expect(mounted.find('.slds-form-element__control').hasClass('foo')).toBeTruthy(); expect(mounted.find('.slds-form-element__control').prop('data-test')).toEqual('bar'); }); });
function init_types_categories() { var init = function () { init_edit_modal(); }; load_modal_on_click('#create-type', { target: '#modal-sm', controller: 'admin', action: 'type' }, { todo: init }); load_modal_on_click('#create-category', { target: '#modal-sm', controller: 'admin', action: 'category' }, { todo: init }); init_bind_edit_remove(); } function init_bind_edit_remove() { var init_edit = function () { init_edit_modal(); }; load_modal_on_click('.edit-type', { target: '#modal-sm', controller: 'admin', action: 'type' }, { todo: init_edit }); load_modal_on_click('.edit-category', { target: '#modal-sm', controller: 'admin', action: 'category' }, { todo: init_edit }); var init_delete = function () { init_bind_edit_remove(); }; bind_delete('.remove-type', '#type-list', init_delete); bind_delete('.remove-category', '#category-list', init_delete); } function init_edit_modal() { var url = $('#modal-sm #send-infos-url').val(); var todo = function () { init_bind_edit_remove(); }; var success_message = 'Vos modifications ont été prises en compte'; $('#modal-sm #send-type-modal-new').click(function() { var name = $('#modal-sm #type_name').val(); send_infos(url, { name: name }, '#type-list', { todo: todo, success_message: success_message }); }); $('#modal-sm #send-type-modal-edit').click(function() { var id = $('#modal-sm #type_id').val(); var name = $('#modal-sm #type_name').val(); send_infos(url, { id: id, name: name }, '.editable-type-' + id, { todo: todo, success_message: success_message }); }); $('#modal-sm #send-category-modal-new').click(function() { var name = $('#modal-sm #category_name').val(); var type = $('#modal-sm #category_type').val(); send_infos(url, { name: name, type: type }, '#category-list', { todo: todo, success_message: success_message }); }); $('#modal-sm #send-category-modal-edit').click(function() { var id = $('#modal-sm #category_id').val(); var name = $('#modal-sm #category_name').val(); var type = $('#modal-sm #category_type').val(); send_infos(url, { id: id, name: name, type: type }, '.editable-category-' + id, { todo: todo, success_message: success_message }); }); }
module.exports = { verbose: true, testURL: "http://localhost", transform: { ".+\\.tsx?$": "ts-jest" }, transformIgnorePatterns: ["/node_modules/", "/dist/"], testRegex: "/__tests__/.*\\.spec\\.tsx?$", moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"] };
import config from '../config'; import path from 'path'; import gulp from 'gulp'; import {Server} from 'karma'; gulp.task('unit', ['blogViews'], function(cb) { new Server({ configFile: path.resolve(__dirname, '../..', config.test.karma), singleRun: true }, cb).start(); });
/** * Vehicle payload * * LIGNA scenario: step 15 * * Display description: - A chart of the vehicle payload for the current day * * Input variables: - machine[mid].technical_data.vehicle_payload * * @@source_header * * -- * * This file is part of the focus-app-demonstrator package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ 'use strict'; (function() { angular.module('focusApp.vehiclePayload', [ 'focusApp.dataService', 'focusApp.navigationService' ]) .controller('VehiclePayloadController', [ '$location', 'DataService', 'NavigationService', function($location, DataService, NavigationService) { var _self = this; /** * Reference to DataService */ _self.dataSvc = DataService; /** * Get the id of the currently accessed machine */ var parts = $location.path().split(/\//); _self.currentMachineId = parts[2] || 0; /** * Reference to the current data sample being rendered */ _self.dataSvc = DataService; _self.data = DataService.data; _self.dataMachine = DataService.data.machine[_self.currentMachineId]; /** * Set the title of the page */ NavigationService.currentTitle = 'Vehicle payload - ' + _self.dataMachine.name; /** * Table with latest values */ _self.last_values = []; /** * Initialize everything. */ var _init = function() { // infer max value for yAxis var max_value = 10000 * 1.3; angular .forEach( DataService.dataSet.timedependent['<TIME:machine[' + _self.currentMachineId + '].technical_data.vehicle_payload>'], function(v) { if (v > max_value) { max_value = v * 1.3; } }); // init data array _self.chartData = [ { label : ' Payload: ' + _self.dataMachine.name, color: '#4444ff', data : [ [ DataService.startDateTime.getTime(), 0 ] ] }, { label : ' Overload threshold', color: '#ff0000', data : [ [ DataService.startDateTime.getTime(), 10000 ] ] }]; // init chart options _self.chartOptions = { series : { lines : { show : true }, points : { show : false }, }, xaxis : { show : true, mode : "time", timezone : "browser", ticks: 6 }, yaxis : { min : 0, max : max_value }, legend: { position: 'nw', margin: [12, 6] }, grid: { labelMargin: 12 } }; }; _init(); /** * Update the drawing of the map */ _self.drawDynamicData = function() { // we store the new data in a tmp array, otherwise flot/angularjs will try to update the view on every data change // and that's very CPU demanding var new_data = [[],[]]; var TOTAL_SPAN_IN_INCREMENTS = 30 * 60 / 2; // we want to always display a 30min timeline, so let's fill // empty values if necessary var num_empty = Math.max(TOTAL_SPAN_IN_INCREMENTS - DataService.currentTimeIncrement, 0); for (var i = num_empty; i > 0; --i) { var cur = DataService.startDateTime.getTime() - 2 * i * 1000; new_data[0].push([ cur, null ]); new_data[1].push([ cur, 10000 ]); } for (var i = 0; i < DataService.currentTimeIncrement; ++i) { var cur = DataService.startDateTime.getTime() + 2 * i * 1000; var val = DataService.dataSet.timedependent['<TIME:machine[' + _self.currentMachineId + '].technical_data.vehicle_payload>'][i]; new_data[0].push([ cur, val ]); new_data[1].push([ cur, 10000 ]); } // do fill the new 'last values' var last_elem = new_data[0].length - 1; _self.last_values = []; for (var i = 0; i < 10; ++i) { _self.last_values.push({ date: new_data[0][last_elem - i*30][0], value: new_data[0][last_elem - i*30][1] }); } angular.copy(new_data[0], _self.chartData[0].data); angular.copy(new_data[1], _self.chartData[1].data); }; _self.drawDynamicData(); /** * Register refresh callback */ DataService.registerRefreshCallback(_self.drawDynamicData); } ]); }());
Chartled.registerChartleEditor( Chartled.ChartChartle, { initialize: function( definition ) { this.configuringChartle = false; this._chartEditorDialog= new Chartled.ChartleEditDialog({ title: "Edit Chart" }); this._metricEditors=[]; } , dispose: function() { this._disposeMetricEditors(); this._chartEditorDialog.dispose(); this._chartEditorDialog = null; } , addRefreshListener: function( refresher ) { this.refresh= refresher; } , configureChartle : function() { var that= this; if( that.configuringChartle ) return; else that.configuringChartle= true; // Take a copy of the current metrics, prior to edit. var metricGroups=2; that.editableGroups= []; for(var i=0;i<metricGroups;i++) { that.editableGroups.push({ metrics: [], interpolation: "linear", renderer: "line" }); } for(var i=0;i<that.editableGroups.length;i++ ) { for(var m in that.groups[i].metrics) { that.editableGroups[i].metrics.push( that.groups[i].metrics[m] ); } if(typeof(that.groups[i].interpolation) != 'undefined') that.editableGroups[i].interpolation = that.groups[i].interpolation; if(typeof(that.groups[i].renderer) != 'undefined') that.editableGroups[i].renderer = that.groups[i].renderer; } var html = ""; html += " <ul class='nav nav-tabs'>"; html += " <li class='active'><a href='#details' data-toggle='tab'>Details</a></li>"; html += " <li><a href='#metrics' data-toggle='tab'>Metrics</a></li>"; html += " <li><a href='#axes' data-toggle='tab'>Axes</a></li>"; html += " <li><a href='#clock' data-toggle='tab'>Clock</a></li>"; html += " </ul>"; html += " <div class='tab-content'>"; html += " <div class='tab-pane active' id='details'>"; html += " <form class='form-horizontal'>"; html += " <div class='form-group'><label class='col-sm-3 control-label'>Title</label><div class='col-sm-9'><input class='form-control title' type='text'/></div></div>"; html += " </form>"; html += " </div>"; html += " <div class='tab-pane' id='metrics'>"; var selected= ""; function buildSelectOptions(options, selectedValue){ var result= ""; for(var i=0;i<options.length;i++) { result += "<option value='"+ options[i][0] + "'" + (options[i][0]==selectedValue?" selected ": "") +">"+ options[i][1] +"</option>"; } return result; } for(var i=0;i<that.editableGroups.length;i++) { html += " <fieldset class='metricEditor"+ i +"'><legend>Metric group " + (i+1) + "</legend>"; html += " <form class='form-horizontal'>"; html += " <div class='metricValueEditorContainer'/>"; html += " <div class='form-group col-sm-12'>"; html += " <label class='col-sm-2 control-label'>Style</label><div class='col-sm-3'>" html += " <select class='form-control selectpicker renderer'>"; html += buildSelectOptions([["line","Line"],["area", "Area"],["bar", "Bar"]], that.editableGroups[i].renderer); html += " </select>"; html += " </div>"; html += " <label class='col-sm-2 control-label'>Interpolation</label><div class='col-sm-3'>" html += " <select class='form-control selectpicker interpolation'>"; html += buildSelectOptions([["basis","B-Spline"],["cardinal", "Cardinal"],["linear", "Linear"], ["step-after", "Step After"], ["step-before", "Step Before"],["monotone", "Cubic"] ], that.editableGroups[i].interpolation); html += " </select>"; html += " </div>"; html += " </div>"; html += " <div class='form-group col-sm-12'>"; html += " <label class='col-sm-2 control-label'>Axis</label><div class='col-sm-3'>" html += " <select disabled class='form-control selectpicker'>"; html += buildSelectOptions([["0","Left"],["1", "Right"]], "0"); html += " </select>"; html += " </div>"; html += " </div>"; html += " </form>"; html += " </fieldset>"; } html += " </div>" html += " <div class='tab-pane' id='axes'>" html += " <form class='form-horizontal'>"; html += " <fieldset><legend>Horizontal</legend>" html += " <div class='form-group'><div class='controls col-sm-offset-3 col-sm-9'><div class='checkbox'><label><input type='checkbox' class='horizontalAxis'/>Visible</label></div></div></div>"; html += " <div class='form-group'><div class='controls col-sm-offset-3 col-sm-9'><div class='checkbox'><label><input type='checkbox' class='autoSampleData'/>Auto-Sample Data</label></div></div></div>"; html += " </fieldset>" html += " <fieldset><legend>Vertical</legend>" html += " <fieldset><legend>Left</legend>" html += " </fieldset>" html += " <fieldset><legend>Right</legend>" html += " </fieldset>" html += " </fieldset>" html += " </form>"; html += " </div>" html += " <div class='tab-pane' id='clock'/>" html += " </div>"; var $dialog= this._chartEditorDialog.show( html, function($dialog) { that.configuringChartle= false; // The metric editors will have (potentially) directly updated the 'editableGroups' references with the new metric values, but // this code still needs to manually update them with the selected drop-down values. for(var i=0;i<that.editableGroups.length;i++) { var metricEditor= $dialog.find(".metricEditor"+ i); that.editableGroups[i].interpolation= metricEditor.find(".interpolation").val(); that.editableGroups[i].renderer= metricEditor.find(".renderer").val(); } // Bleurghhh this is nasty, avoiding shared mutable states?? that.groups= that.editableGroups; that.chart.config.groups= that.groups; that.editableGroups= null; that.set_title($dialog.find(".title").val()) that.set_horizontalAxisVisible($dialog.find(".horizontalAxis").prop('checked')); that.set_autoSampleData($dialog.find(".autoSampleData").prop('checked')); that.refresh(); }, function() { that.configuringChartle= false; } ); this._disposeMetricEditors(); this._metricEditors= []; for(var i=0;i<that.editableGroups.length;i++) { this._metricEditors.push( new Chartled.MetricEditor( $dialog, $dialog.find(".metricEditor" + i +" .metricValueEditorContainer" ), that.editableGroups[i].metrics, {allowAdd: true, allowRemove: true} )); } $dialog.find(".title").val(that._title); $dialog.find(".horizontalAxis").prop('checked', that._horizontalAxisVisible); $dialog.find(".autoSampleData").prop('checked', that._autoSampleData); } , metricChartTypes : [ {name:"Area", type: "area"}, {name:"Bar", type: "bar"}, {name:"Line", type: "line"}, {name:"Scatter Plot", type: "scatterplot"} ] , _disposeMetricEditors: function() { for(var k in this._metricEditors) { this._metricEditors[k].dispose(); } this._metricEditors= null; } });
import cp from 'child_process'; import fs from 'fs'; import path from 'path'; import test from 'ava'; import helpers from 'yeoman-test'; const files = [ 'lib/config.js', 'lib/persister.js', 'lib/logger.js', 'lib/sub.js', 'sub/commands.js', 'sub/completions.js', 'sub/example.js', 'sub/help.js', 'sub/init.js', 'sub/version.js', 'sub/update.js', 'tests/lib/config.spec.js', 'tests/lib/persister.spec.js', 'tests/lib/sub.spec.js', 'tests/sub/commands.spec.js', 'tests/sub/example.spec.js', 'tests/sub/version.spec.js', 'tests/fixtures/mockPersister.js', 'tests/fixtures/spyLogger.js', '.eslintignore', '.eslintrc', '.gitignore', 'README.md', 'package.json', 'index.js', 'cli.js' ]; const testCases = [{ updateInterval: 7, updater : 'git', repo : 'http://github.com/doug-wade/example-sub', argParser : 'minimist', name : 'minimist-and-git' }, { updateInterval: 7, updater : 'npm', repo : 'http://github.com/doug-wade/example-sub', argParser : 'yargs', name : 'yargs-and-npm' }]; testCases.forEach(testCase => { test(`generator-sub:app ${testCase.name} creates files`, async t => { let testDir; await helpers.run(path.join(__dirname, '../generators/app')) .inTmpDir(dir => { testDir = dir; }) .withPrompts(testCase) .toPromise(); t.plan(files.length); files.forEach(file => { t.true(exists(file, testDir)); }); }); // These don't terminate on ci and take forever locally, so only run them when // publishing if (!process.env.CONTINUOUS_INTEGRATION) { test(`generator-sub:app ${testCase.name} passes the test target`, async t => { let testDir; await helpers.run(path.join(__dirname, '../generators/app')) .inTmpDir(dir => { testDir = dir; }) .withPrompts({name: 'foo', dockerCfg: false}) .toPromise(); await installDeps(testDir); t.true(await runsSuccessfully('npm test', testDir)); }); } }); function exists(filename, dir) { filename = path.join(dir, filename); try { fs.accessSync(filename, fs.F_OK); return true; } catch (error) { return false; } } function runsSuccessfully(command, dir) { return new Promise((resolve, reject) => { cp.exec(command, { cwd: dir }, error => { if (error) { reject(error); } else { resolve(true); } }); }); } function installDeps(dir) { return new Promise((resolve, reject) => { cp.exec('npm install', { cwd: dir }, error => { if (error) { reject(error); } else { resolve(); } }); }); }
export default class { constructor(jsonInputData = {}, storyInputData = {}) { this.jsonInputData = jsonInputData; this.storyInputData = storyInputData; } get input() { let {jsonInputData = {}, storyInputData = {}} = this; let {radioButtons = []} = jsonInputData; let {options = []} = storyInputData; let newRadioButtons = options.map(option => { let {display, value} = option; let radio = hasRadio(option, radioButtons); if (radio) { let newRadio = Object.assign({}, radio); return newRadio; } else { return { value, label: display } } }); let newInputData = Object.assign({}, jsonInputData, { radioButtons: newRadioButtons, type: "radio" }) return newInputData; function hasRadio(option, radioButtons = []) { return radioButtons.find(radioButton => { return radioButton.value === option.value; }) } } }
// @flow import * as React from 'react'; import Benchmark, { type BenchmarkRef } from '../Benchmark'; import BenchmarkType from '../BenchmarkType'; import { act, render, waitFor } from '@testing-library/react'; import type { Sample } from '../types'; type Props = {| testID: number |}; function Test({ testID }: Props) { return <div id={testID}>hello</div>; } describe('new', () => { beforeEach(() => { jest.useRealTimers(); }); test('renders nothing if not running', () => { const { getByTestId } = render(<Benchmark component={Test} onComplete={jest.fn()} samples={2} />); expect(() => getByTestId('test')).toThrow('Unable to find an element'); }); test.each([[BenchmarkType.MOUNT], [BenchmarkType.UPDATE], [BenchmarkType.UNMOUNT]])( 'samples for %s', async (type: $Values<typeof BenchmarkType>) => { const ref = React.createRef<BenchmarkRef | void>(); const handleComplete = jest.fn(); render(<Benchmark ref={ref} component={Test} onComplete={handleComplete} samples={10} type={type} />); act(() => { ref.current && ref.current.start(); }); await waitFor(() => expect(handleComplete).toHaveBeenCalledWith( expect.objectContaining({ sampleCount: 10, }) ) ); } ); describe('results', () => { let results; beforeAll(async () => { const ref = React.createRef<BenchmarkRef | void>(); const handleComplete = jest.fn(); render(<Benchmark ref={ref} component={Test} onComplete={handleComplete} samples={2} />); act(() => { ref.current && ref.current.start(); }); await waitFor(() => expect(handleComplete).toHaveBeenCalled()); results = handleComplete.mock.calls[0][0]; }); test.each([ ['startTime', 'number'], ['endTime', 'number'], ['runTime', 'number'], ['sampleCount', 'number'], ['max', 'number'], ['min', 'number'], ['median', 'number'], ['mean', 'number'], ['stdDev', 'number'], ['p70', 'number'], ['p95', 'number'], ['p99', 'number'], ])('include a key %s that is a %s', (key: string, type: string) => { expect(results).toHaveProperty(key); expect(typeof results[key]).toEqual(type); }); test('includes an array for samples', () => { expect(results).toHaveProperty('samples'); expect(Array.isArray(results.samples)).toBe(true); results.samples.forEach((sample: Sample) => { expect(sample).toHaveProperty('start'); expect(sample).toHaveProperty('end'); expect(sample).toHaveProperty('elapsed'); expect(sample).toHaveProperty('layout'); }); }); }); });
Cufon.replace('h1', {fontFamily: 'Comfortaa'}); Cufon.replace('p.c_soon strong', {fontFamily: 'Comfortaa'});
import React from 'react'; class AboutPage extends React.Component { render() { return ( <div> <h1>About </h1> </div> ) } } export default AboutPage;
/* Function: buttonPress Params: - onclick - Function to call when button is clicked. Returns: Nothing. Operation: Adds consistent onmouse* events to a button. */ Element.prototype.buttonPress = function(onclick) { this.onmouseover = function() { this.style.borderColor = DEFAULT_COLOR; }; this.onmouseout = function() { this.style.borderColor = BACKGROUND_COLOR; }; this.onmousedown = function() { this.style.backgroundColor = DEFAULT_COLOR_TRANSLUCENT; }; this.onmouseup = function() { this.style.backgroundColor = BACKGROUND_COLOR; }; this.onclick = onclick; }; /* Function: createShareButton Params: - service - ShareService object to create the button for. Returns: HTML "td" element for the button for the service. Operation: Creates a button cell for the specified service. The cell contains the service's title and icon and, when clicked, sends a share message to the service's extension. */ function createShareButton(service) { var cell = document.createElement("td"); cell.setAttribute("class", "service-button"); cell.setAttribute("id", service.extensionId + " " + service.id); var image = document.createElement("img"); image.setAttribute("class", "service-icon"); image.setAttribute("src", service.icon); image.setAttribute("alt", service.name); var text = document.createElement("div"); text.setAttribute("class", "service-name"); text.innerText = service.name; cell.appendChild(image); cell.appendChild(document.createElement("br")); cell.appendChild(text); cell.buttonPress(function() { service.sendShareMessageFromTab(displayResponseMessage); }); return cell; }; /* Function: addCell Params: - cell - the cell to be added. Returns: Nothing. Operation: Adds a new cell to the table of buttons. Buttons are added in rows of four, so this function creates new rows in the table to maintain rows of four buttons. */ function addCell(cell) { var table = document.getElementById("button-table") var row; if (table.rows.length == 0) { row = table.insertRow(); } else if (table.rows[table.rows.length - 1].cells.length == 4) { row = table.insertRow(-1); } else { row = table.rows[table.rows.length - 1]; }; row.appendChild(cell); }; /* Function: refreshButtons Params: None. Returns: Nothing. Operation: Clears any present buttons, then gets the active ShareServices from storage and displays buttons for them all. */ function refreshButtons() { var table = document.getElementById("button-table"); while (table.rows.length > 0) { table.deleteRow(0); }; getShareServiceFromStorage(null, function(services) { for (var key in services) { var button = createShareButton(services[key]); addCell(button); }; }); }; /* Function: displayResponseMessage Params: - response - object containing the response. Returns: Nothing. Operation: Takes a response from the ShareService extension and displays it in a temporary box in the popup. */ function displayResponseMessage(response) { if (response) { console.log("Displaying response message", response); var message_display = document.createElement("div"); message_display.setAttribute("id", "message"); message_display.innerText = response.message; document.body.appendChild(message_display); setTimeout(function() { message_display.parentNode.removeChild(message_display)}, RESPONSE_MESSAGE_TIMEOUT); }; }; document.addEventListener("DOMContentLoaded", function() { // Add listeners for refresh and options buttons document.getElementById("refresh").buttonPress(function() { console.log("Refresh button clicked"); pingAllServices(); }); document.getElementById("options").buttonPress(function() { console.log("Options button clicked"); chrome.tabs.create( {url: "/options/options.html"}, function(tab) {chrome.windows.update(tab.windowId,{"focused": true});} ); }); // Add listener to update buttons if services in storage changes. chrome.storage.onChanged.addListener(function(changes) { if (changes.services) { refreshButtons(); }; }); refreshButtons(); });
(function (window, document) { var layout = document.getElementById('layout'), menu = document.getElementById('menu'), menuLink = document.getElementById('menuLink'); function toggleClass(element, className) { var classes = element.className.split(/\s+/), length = classes.length, i = 0; for(; i < length; i++) { if (classes[i] === className) { classes.splice(i, 1); break; } } // The className is not found if (length === classes.length) { classes.push(className); } element.className = classes.join(' '); } menuLink.onclick = function (e) { var active = 'active'; e.preventDefault(); toggleClass(layout, active); toggleClass(menu, active); toggleClass(menuLink, active); }; $("pre").addClass("prettyprint").addClass("linenums"); if(typeof(prettyPrint)=='function'){ prettyPrint(); } }(this, this.document));
'use strict'; /* Controllers */ angular.module('restBrowser.controllers', []) .controller('MyCtrl1', ['$scope', 'Restangular', function($scope, Restangular) { $scope.itemSelected = function(item) { console.log(item.attr('id')); var listing = Restangular.all(item.attr('id')).getList(); return listing; }; }]);
/** * Created by marciso on 10/02/2017. */ $('#nota').click(function(){ console.log('funcionou'); if($('#nota').is(":checked")){ $("#notaFiscal").prop('disabled',false); $("#notaFiscal").val(''); }else{ $("#notaFiscal").prop('disabled',true); $("#notaFiscal").val("S/N"); } }); $('#course').change(function(){ $.ajax({ url: '../../index.php/Cliente/buscaCliente', type: 'POST', data:{ nome: $('#course').val() }, beforeSend : function() { $.blockUI({ message: 'Procurando informações do cliente', baseZ: 2000 }); }, complete: function () { $.unblockUI(); }, success : function (data) { var array = JSON.parse("[" + data + "]"); $('#cliente').val(array[0][0]['id_clients']); $('#telefone').val(array[0][0]['telefone']); }, error: function(data){ $.unblockUI(); } }); }); $("#salvarVolume").click(function(){//cadastrar deposito var controller; if($("#tipoVolume").val()==1) { controller='cadastrarVolume'; }else{//Editando controller='editarVolume'; } var dados = { id_mercadoria : $('#id_mercadoria_editar').val(), cliente: $('#cliente').val(), telefone: $('#telefone').val(), notafiscal: $('#notaFiscal').val(), desc: $('#desc').val(), dt_deposito: $('#dt_deposito').val(), tipoVolume: $('input:radio[name=tipoVolume]:checked').val(), tamanhoVolume: $('input:radio[name=tamanhoVolume]:checked').val() }; $.ajax({ url: controller, type: 'POST', data: dados, beforeSend : function() { $.blockUI({ message: 'Salvando...', baseZ: 2000 }); }, complete: function () { $.unblockUI(); }, success: function (data) { limpaVolumeModel(); $("#volumeSucesso").show(); setTimeout(function () { $('#inserirModal-modal').modal('toggle'); $("#volumeSucesso").hide(); }, 800); window.location.reload(); }, error: function (data) { $("#volumeErro").show(); $.unblockUI(); } }); }); $('#salvarEnvio').click(function(){ if($("#tipoVolume").val()==1) { var dados ={ id_mercadoria : $('#id_mercadoria').val(), veiculo : $('#onibus_envio').val(), dt_envio : $('#dt_envio').val(), destino : $("[name=destino]").val(), origem : $("[name=origem]").val() }; $.ajax({ url: 'cadastrarEnvio', type: 'POST', data: dados, beforeSend : function() { $.blockUI({ message: 'Enviando...', baseZ: 2000 }); }, complete: function () { $.unblockUI(); }, success : function(data){ limparEnvioModel(); $('#envioSucesso').show(); setTimeout(function(){ $('#despacharModal-modal').modal('toggle'); $("#envioSucesso").hide(); },800); window.location.reload(); }, error: function(data){ $('#envioErro').show(); $.unblockUI(); } }); }else{//Editando } }); $("#salvarRecebido").click(function(){ if($("#tipoRecebido").val()==1) { var dados = { id_mercadoria : $("#id_mercadoria_recebido").val(), dt_recebido : $("#dt_recebido").val() }; $.ajax({ url: "cadastrarRecebido", type:"POST", data:dados, beforeSend : function() { $.blockUI({ message: 'Recebendo...', baseZ: 2000 }); }, complete: function () { $.unblockUI(); }, success: function(data){ limparRecebidoModel(); $('#recebidoSucesso').show(); setTimeout(function(){ $('#receberModal-modal').modal('toggle'); $("#recebidoSucesso").hide(); },800); // window.location.reload(); }, error: function(data){ $('#recebidoErro').show(); $.unblockUI(); } }); }else{//editando } }); $("#salvarEntregue").click(function(){ if($("#tipoEntregue").val()==1){ var dados = { id_mercadoria : $("#id_mercadoria_entregue").val(), dt_entregue : $("#dt_entregue").val() }; $.ajax({ url :"cadastrarEntregue", type: "POST", data: dados, beforeSend : function() { $.blockUI({ message: 'Entregando...', baseZ: 2000 }); }, complete: function () { $.unblockUI(); }, success: function(data){ limparEntregueModel(); $('#entregueSucesso').show(); setTimeout(function(){ $('#entregarModal-modal').modal('toggle'); $("#entregueSucesso").hide(); },800); window.location.reload(); }, error: function(data){ $("#entregueErro").show(); $.unblockUI(); } }); }else{//editando } }); $("#cancelarVolume").click(function(){ limpaVolumeModel(); }); $("#cancelarEnvio").click(function(){ limparEnvioModel(); }); $("#cancelarRecebido").click(function(){ limparRecebidoModel(); }); $("#cancelarEntregue").click(function(){ limparEntregueModel(); }); $("#excluir").click(function(){ var controller; if($("#tipoExclusao").val()==1){//Deposito controller = 'cancelarVolume'; }else if($("#tipoExclusao").val()==2){//Envio controller = 'cancelarEnvio'; }else if($("#tipoExclusao").val()==3){//Recebido controller = 'cancelarRecebido'; }else if($("#tipoExclusao").val()==4){//Entregue controller = 'cancelarEntregue'; } var dados = { id_mercadoria : $('#id_mercadoria_excluir').val() }; $.ajax({ url: controller, type: 'POST', data: dados, beforeSend:function (){ $.blockUI({ message: 'Excluindo...', baseZ: 2000 }); }, complete: function () { $.unblockUI(); }, success: function(data){ limparExcluirModel(); $('#excluidoSucesso').show(); setTimeout(function(){ $('#excluirModal-modal').modal('toggle'); $("#excluidoSucesso").hide(); },800); window.location.reload(); }, error: function(data){ $("#excluidoErro").show(); $.unblockUI(); } }); }); function editarVolume(id){ var dados = { id_mercadoria : id }; console.log(dados); limpaVolumeModel(); $.ajax({ url:'buscaEditarVolume', type: 'POST', data: dados, beforeSend: function(){ $.blockUI({ message: "Carregando...", baseZ: 2000 }); }, complete:function(data){ var array = JSON.parse(data.responseText); if(array[0].nr_nota_fiscal != "S/N") { $('#nota').prop('checked', true); $("#notaFiscal").prop('disabled',false); }else{ $('#nota').prop('checked', false); $("#notaFiscal").prop('disabled',true); } $('#cliente').val(array[0].id_cliente); $('#course').val(array[0].nome); $('#telefone').val(array[0].telefone); $('#notaFiscal').val(array[0].nr_nota_fiscal); $('#desc').val(array[0].descricao); $('#dt_deposito').val(array[0].dt_deposito); $('#tipoVolume'+array[0].tp_volume).prop('checked',true); $('#tamanhoVolume'+array[0].tm_volume).prop('checked',true); $.unblockUI(); } }); } function limpaVolumeModel(){ $('#cliente').val(''); $('#course').val(''); $('#telefone').val(''); $('#notaFiscal').val('S/N'); $('#desc').val(''); $('#dt_deposito').val(''); $('#id_mercadoria_editar').val(''); $('#tipoVolume1').prop('checked',true); $('#tamanhoVolume1').prop('checked',true); $("#volumeSucesso").hide(); $("#volumeErro").hide(); } function limparBuscaModel(){ $('#cliente_busca').val(''); $('#data_busca').val(''); $('#onibus_busca').val(''); $('#origem_busca').val(''); $('#destino_busca').val(''); $('#tp_volume1_busca').prop('checked',false); $('#tp_volume2_busca').prop('checked',false); $('#tp_volume3_busca').prop('checked',false); $('#tp_volume4_busca').prop('checked',false); $('#tm_volume1_busca').prop('checked',false); $('#tm_volume2_busca').prop('checked',false); $('#tm_volume3_busca').prop('checked',false); } function limparEnvioModel(){ $('#onibus_envio').val(''); $('#dt_envio').val(''); $('#cliente_despacho').val(''); $('#nota_fiscal_despacho').val(''); $('#dt_entrada_despacho').val(''); $('#descricao_despacho').val(''); $('#tp_volume_despacho').val(''); $('#tm_volume_despacho').val(''); $("#envioSucesso").hide(); $("#envioErro").hide(); } function limparRecebidoModel(){ $('#dt_recebido').val(''); } function limparEntregueModel(){ $("#dt_entregue").val(''); } function limparExcluirModel(){ $('#id_mercadoria_excluir').val(''); }
/* OrderPortal Meta documents indexed by id. Value: title. */ function(doc) { if (doc.orderportal_doctype !== 'meta') return; emit(doc._id, null); }
(function () { "use strict"; angular.module("mailCRMApp", ["ngRoute", "MailCRM.services", "MailCRM.controllers"]) .config(function ($routeProvider, $locationProvider) { $routeProvider.when("/login", { controller: "loginCtrl", templateUrl: "../../templates/view-MailCRM-Login.html" }) .when("/lookup", { controller: "lookupCtrl", templateUrl: "../../templates/view-MailCRM-Create.html" }) .when("/detail", { controller: "crmCtrl", templateUrl: "../../templates/view-MailCRM-Detail.html" }) .when("/contacts", { controller: "crmCtrl", templateUrl: "../../templates/view-MailCRM-Contacts.html" }) .when("/invoices", { controller: "crmCtrl", templateUrl: "../../templates/view-MailCRM-Invoices.html" }) .when("/location", { controller: "geoCtrl", templateUrl: "../../templates/view-MailCRM-Location.html" }) .when("/notes", { controller: "crmCtrl", templateUrl: "../../templates/view-MailCRM-Notes.html" }) .when("/attachments", { controller: "crmCtrl", templateUrl: "../../templates/view-MailCRM-Attachments.html" }) .otherwise({ redirectTo: "/login" }); }) .directive("sideNav", ["$rootScope", "$location", "stateSvc", function ($rootScope, $location, stateSvc) { return { restrict: "E", templateUrl: "../../templates/directive-MailCRM-SideNav.html", scope: { ngModel: "=" }, link: function (scope, element, attrs) { scope.user = stateSvc.idToken.user; scope.activeNavIndex = stateSvc.activeNavIndex; scope.nav = function (path, index) { stateSvc.activeNavIndex = index; $location.path(path); }; } }; }]) .directive("spinner", function () { return { restrict: "E", templateUrl: "../../templates/directive-MailCRM-Spinner.html" }; }); })();
Meteor.startup(function() { /** * Sets Mideor.MIDI to the Web MIDI API object if there is a MIDI device * detected otherwise false. * * Handles API change in Chrome 29. */ navigator.requestMIDIAccess() .then(function (m) { // Web MIDI API changed in Chrome 29 here's a catchall. // Chrome < 29: if (typeof m.inputs === 'function') { Mideor.MIDI = m.inputs()[0]; } else { // Chrome > 29: Mideor.MIDI = m.inputs.values().next().value; } if (Mideor.MIDI) { Mideor.log(Mideor.MIDI); Mideor.MIDI.onmidimessage = Mideor.playNote; } else { Mideor.log('no midi device.'); } }, function(err) { Mideor.log("MIDI Access Failure. Error code: " + err.code ); }); });
// All symbols in the Kangxi Radicals block as per Unicode v6.1.0: [ '\u2F00', '\u2F01', '\u2F02', '\u2F03', '\u2F04', '\u2F05', '\u2F06', '\u2F07', '\u2F08', '\u2F09', '\u2F0A', '\u2F0B', '\u2F0C', '\u2F0D', '\u2F0E', '\u2F0F', '\u2F10', '\u2F11', '\u2F12', '\u2F13', '\u2F14', '\u2F15', '\u2F16', '\u2F17', '\u2F18', '\u2F19', '\u2F1A', '\u2F1B', '\u2F1C', '\u2F1D', '\u2F1E', '\u2F1F', '\u2F20', '\u2F21', '\u2F22', '\u2F23', '\u2F24', '\u2F25', '\u2F26', '\u2F27', '\u2F28', '\u2F29', '\u2F2A', '\u2F2B', '\u2F2C', '\u2F2D', '\u2F2E', '\u2F2F', '\u2F30', '\u2F31', '\u2F32', '\u2F33', '\u2F34', '\u2F35', '\u2F36', '\u2F37', '\u2F38', '\u2F39', '\u2F3A', '\u2F3B', '\u2F3C', '\u2F3D', '\u2F3E', '\u2F3F', '\u2F40', '\u2F41', '\u2F42', '\u2F43', '\u2F44', '\u2F45', '\u2F46', '\u2F47', '\u2F48', '\u2F49', '\u2F4A', '\u2F4B', '\u2F4C', '\u2F4D', '\u2F4E', '\u2F4F', '\u2F50', '\u2F51', '\u2F52', '\u2F53', '\u2F54', '\u2F55', '\u2F56', '\u2F57', '\u2F58', '\u2F59', '\u2F5A', '\u2F5B', '\u2F5C', '\u2F5D', '\u2F5E', '\u2F5F', '\u2F60', '\u2F61', '\u2F62', '\u2F63', '\u2F64', '\u2F65', '\u2F66', '\u2F67', '\u2F68', '\u2F69', '\u2F6A', '\u2F6B', '\u2F6C', '\u2F6D', '\u2F6E', '\u2F6F', '\u2F70', '\u2F71', '\u2F72', '\u2F73', '\u2F74', '\u2F75', '\u2F76', '\u2F77', '\u2F78', '\u2F79', '\u2F7A', '\u2F7B', '\u2F7C', '\u2F7D', '\u2F7E', '\u2F7F', '\u2F80', '\u2F81', '\u2F82', '\u2F83', '\u2F84', '\u2F85', '\u2F86', '\u2F87', '\u2F88', '\u2F89', '\u2F8A', '\u2F8B', '\u2F8C', '\u2F8D', '\u2F8E', '\u2F8F', '\u2F90', '\u2F91', '\u2F92', '\u2F93', '\u2F94', '\u2F95', '\u2F96', '\u2F97', '\u2F98', '\u2F99', '\u2F9A', '\u2F9B', '\u2F9C', '\u2F9D', '\u2F9E', '\u2F9F', '\u2FA0', '\u2FA1', '\u2FA2', '\u2FA3', '\u2FA4', '\u2FA5', '\u2FA6', '\u2FA7', '\u2FA8', '\u2FA9', '\u2FAA', '\u2FAB', '\u2FAC', '\u2FAD', '\u2FAE', '\u2FAF', '\u2FB0', '\u2FB1', '\u2FB2', '\u2FB3', '\u2FB4', '\u2FB5', '\u2FB6', '\u2FB7', '\u2FB8', '\u2FB9', '\u2FBA', '\u2FBB', '\u2FBC', '\u2FBD', '\u2FBE', '\u2FBF', '\u2FC0', '\u2FC1', '\u2FC2', '\u2FC3', '\u2FC4', '\u2FC5', '\u2FC6', '\u2FC7', '\u2FC8', '\u2FC9', '\u2FCA', '\u2FCB', '\u2FCC', '\u2FCD', '\u2FCE', '\u2FCF', '\u2FD0', '\u2FD1', '\u2FD2', '\u2FD3', '\u2FD4', '\u2FD5', '\u2FD6', '\u2FD7', '\u2FD8', '\u2FD9', '\u2FDA', '\u2FDB', '\u2FDC', '\u2FDD', '\u2FDE', '\u2FDF' ];
import { Base } from './base'; export class Asset extends Base { setStage(stage) { this.stage = stage; } set(params) {} }
import Utils from './Utils'; import TestIDs from '../playground/src/testIDs'; const { elementById } = Utils; describe.e2e('Lazy Registration', () => { beforeEach(async () => { await device.relaunchApp(); await elementById(TestIDs.STACK_BTN).tap(); }); it('push and pop lazily registered screen', async () => { await elementById(TestIDs.PUSH_LAZY_BTN).tap(); await expect(elementById(TestIDs.LAZILY_REGISTERED_SCREEN_HEADER)).toBeVisible(); await expect(elementById(TestIDs.LAZY_TOP_PAR)).toBeVisible(); await elementById(TestIDs.POP_BTN).tap(); await expect(elementById(TestIDs.STACK_SCREEN_HEADER)).toBeVisible(); }); });
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Physics Manager is responsible for looking after all of the running physics systems. * Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. * * Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. * * For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the * faster (due to being much simpler) Arcade Physics system. * * @class Phaser.Physics * @constructor * @param {Phaser.Game} game - A reference to the currently running game. * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. */ Phaser.Physics = function (game, config) { config = config || {}; /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; /** * @property {object} config - The physics configuration object as passed to the game on creation. */ this.config = config; /** * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. */ this.arcade = null; /** * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. */ this.p2 = null; /** * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. */ this.ninja = null; /** * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. */ this.box2d = null; /** * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). */ this.chipmunk = null; /** * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). */ this.matter = null; this.parseConfig(); }; /** * @const * @type {number} */ Phaser.Physics.ARCADE = 0; /** * @const * @type {number} */ Phaser.Physics.P2JS = 1; /** * @const * @type {number} */ Phaser.Physics.NINJA = 2; /** * @const * @type {number} */ Phaser.Physics.BOX2D = 3; /** * @const * @type {number} */ Phaser.Physics.CHIPMUNK = 4; /** * @const * @type {number} */ Phaser.Physics.MATTERJS = 5; Phaser.Physics.prototype = { /** * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. * * @method Phaser.Physics#parseConfig */ parseConfig: function () { if ((!this.config.hasOwnProperty('arcade') || this.config.arcade === true) && Phaser.Physics.hasOwnProperty('Arcade')) { // If Arcade isn't specified, we create it automatically if we can this.arcade = new Phaser.Physics.Arcade(this.game); } if (this.config.hasOwnProperty('ninja') && this.config.ninja === true && Phaser.Physics.hasOwnProperty('Ninja')) { this.ninja = new Phaser.Physics.Ninja(this.game); } if (this.config.hasOwnProperty('p2') && this.config.p2 === true && Phaser.Physics.hasOwnProperty('P2')) { this.p2 = new Phaser.Physics.P2(this.game, this.config); } if (this.config.hasOwnProperty('box2d') && this.config.box2d === true && Phaser.Physics.hasOwnProperty('BOX2D')) { this.box2d = new Phaser.Physics.Box2D(this.game, this.config); } if (this.config.hasOwnProperty('matter') && this.config.matter === true && Phaser.Physics.hasOwnProperty('Matter')) { this.matter = new Phaser.Physics.Matter(this.game, this.config); } }, /** * This will create an instance of the requested physics simulation. * Phaser.Physics.Arcade is running by default, but all others need activating directly. * * You can start the following physics systems: * * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) * * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. * They are not bundled into the core Phaser library. * * If the physics world has already been created (i.e. in another state in your game) then * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. * * @method Phaser.Physics#startSystem * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. */ startSystem: function (system) { if (system === Phaser.Physics.ARCADE) { this.arcade = new Phaser.Physics.Arcade(this.game); } else if (system === Phaser.Physics.P2JS) { if (this.p2 === null) { this.p2 = new Phaser.Physics.P2(this.game, this.config); } else { this.p2.reset(); } } else if (system === Phaser.Physics.NINJA) { this.ninja = new Phaser.Physics.Ninja(this.game); } else if (system === Phaser.Physics.BOX2D) { if (this.box2d === null) { this.box2d = new Phaser.Physics.Box2D(this.game, this.config); } else { this.box2d.reset(); } } else if (system === Phaser.Physics.MATTERJS) { if (this.matter === null) { this.matter = new Phaser.Physics.Matter(this.game, this.config); } else { this.matter.reset(); } } }, /** * This will create a default physics body on the given game object or array of objects. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. * It can be for any of the physics systems that have been started: * * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) * Phaser.Physics.CHIPMUNK is still in development. * * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the * individual physics systems `enable` methods instead of using this generic one. * * @method Phaser.Physics#enable * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. */ enable: function (object, system, debug) { if (system === undefined) { system = Phaser.Physics.ARCADE; } if (debug === undefined) { debug = false; } if (system === Phaser.Physics.ARCADE) { this.arcade.enable(object); } else if (system === Phaser.Physics.P2JS && this.p2) { this.p2.enable(object, debug); } else if (system === Phaser.Physics.NINJA && this.ninja) { this.ninja.enableAABB(object); } else if (system === Phaser.Physics.BOX2D && this.box2d) { this.box2d.enable(object); } else if (system === Phaser.Physics.MATTERJS && this.matter) { this.matter.enable(object); } else { console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); } }, /** * preUpdate checks. * * @method Phaser.Physics#preUpdate * @protected */ preUpdate: function () { // ArcadePhysics / Ninja don't have a core to preUpdate if (this.p2) { this.p2.preUpdate(); } if (this.box2d) { this.box2d.preUpdate(); } if (this.matter) { this.matter.preUpdate(); } }, /** * Updates all running physics systems. * * @method Phaser.Physics#update * @protected */ update: function () { // ArcadePhysics / Ninja don't have a core to update if (this.p2) { this.p2.update(); } if (this.box2d) { this.box2d.update(); } if (this.matter) { this.matter.update(); } }, /** * Updates the physics bounds to match the world dimensions. * * @method Phaser.Physics#setBoundsToWorld * @protected */ setBoundsToWorld: function () { if (this.arcade) { this.arcade.setBoundsToWorld(); } if (this.ninja) { this.ninja.setBoundsToWorld(); } if (this.p2) { this.p2.setBoundsToWorld(); } if (this.box2d) { this.box2d.setBoundsToWorld(); } if (this.matter) { this.matter.setBoundsToWorld(); } }, /** * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. * * @method Phaser.Physics#clear * @protected */ clear: function () { if (this.p2) { this.p2.clear(); } if (this.box2d) { this.box2d.clear(); } if (this.matter) { this.matter.clear(); } }, /** * Resets the active physics system. Called automatically on a Phaser.State swap. * * @method Phaser.Physics#reset * @protected */ reset: function () { if (this.p2) { this.p2.reset(); } if (this.box2d) { this.box2d.reset(); } if (this.matter) { this.matter.reset(); } }, /** * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. * * @method Phaser.Physics#destroy */ destroy: function () { if (this.p2) { this.p2.destroy(); } if (this.box2d) { this.box2d.destroy(); } if (this.matter) { this.matter.destroy(); } this.arcade = null; this.ninja = null; this.p2 = null; this.box2d = null; this.matter = null; } }; Phaser.Physics.prototype.constructor = Phaser.Physics;
class x509enrollment_cx500distinguishedname { constructor() { // string EncodedName (EncodingType) {get} this.Parameterized = undefined; // string Name () {get} this.Name = undefined; } // void Decode (string, EncodingType, X500NameFlags) Decode(string, EncodingType, X500NameFlags) { } // void Encode (string, X500NameFlags) Encode(string, X500NameFlags) { } } module.exports = x509enrollment_cx500distinguishedname;
/* * @flow * @lint-ignore-every LINE_WRAP1 */ import {suite, test} from '../../tsrc/test/Tester'; export default suite(({addFile, addFiles, addCode}) => [ test('@jsx pragma without expression is disallowed', [ addCode('// @jsx') .newErrors( ` test.js:3 3: // @jsx ^^^^ Invalid @jsx declaration. Should have form \`@jsx LeftHandSideExpression\` with no spaces. `, ), ]), test('@jsx pragma with a non-left-hand-side expression is disallowed', [ addCode('// @jsx (x)=>x') .newErrors( ` test.js:3 3: // @jsx (x)=>x ^^^^^^ Invalid @jsx declaration. Should have form \`@jsx LeftHandSideExpression\` with no spaces. Parse error: Unexpected token => `, ), ]), test('@jsx pragma with a newline should have the right error location', [ addCode(` /* @jsx (x)=>x */ `) .newErrors( ` test.js:5 5: (x)=>x ^^^^^^ Invalid @jsx declaration. Should have form \`@jsx LeftHandSideExpression\` with no spaces. Parse error: Unexpected token => `, ), ]), test('Line comment complex @jsx with unknown identifier points to pragma', [ addCode(` // @jsx Foo['Bar'] var Bar = 123; <Bar />; `) .newErrors( ` test.js:4 4: // @jsx Foo['Bar'] ^^^ identifier \`Foo\`. Could not resolve name `, ), ]), test('Block comment complex @jsx with unknown identifier points to pragma', [ addCode(` /* * @jsx Foo['Bar'] */ var Bar = 123; <Bar />; `) .newErrors( ` test.js:5 5: * @jsx Foo['Bar'] ^^^ identifier \`Foo\`. Could not resolve name `, ), ]), test('Simple identifier @jsx with unknown identifier has better location', [ addCode(` // @jsx Foo var Bar = 123; <Bar />; `) .newErrors( ` test.js:6 6: <Bar />; ^^^^^^^ JSX desugared to \`Foo(...)\`. identifier Foo. Could not resolve name `, ), ]), test('Simple member @jsx with unknown identifier has better location', [ addCode(` // @jsx Foo.baz var Bar = 123; <Bar />; `) .newErrors( ` test.js:6 6: <Bar />; ^^^^^^^ JSX desugared to \`Foo.baz(...)\`. identifier Foo. Could not resolve name `, ), ]), test('Should respect local scope', [ addCode(` // @jsx Foo const Bar = 123; function Foo(x: string) {} <Bar />; { const Foo = (y: boolean) => {}; <Bar />; } `) .newErrors( ` test.js:8 8: <Bar />; ^^^^^^^ JSX desugared to \`Foo(...)\` 5: const Bar = 123; ^^^ number. This type is incompatible with the expected param type of 6: function Foo(x: string) {} ^^^^^^ string test.js:12 12: <Bar />; ^^^^^^^ JSX desugared to \`Foo(...)\` 5: const Bar = 123; ^^^ number. This type is incompatible with the expected param type of 11: const Foo = (y: boolean) => {}; ^^^^^^^ boolean `, ), ]), test('Second arg to jsx function should be props', [ addCode(` // @jsx Foo function Foo(elem: number, props: { x: string }) {} const Bar = 123; <Bar x={123} />; `).newErrors( ` test.js:8 8: <Bar x={123} />; ^^^^^^^^^^^^^^^ props of JSX element \`Bar\`. This type is incompatible with the expected param type of 5: function Foo(elem: number, props: { x: string }) {} ^^^^^^^^^^^^^ object type Property \`x\` is incompatible: 8: <Bar x={123} />; ^^^ number. This type is incompatible with 5: function Foo(elem: number, props: { x: string }) {} ^^^^^^ string `, ), ]), test('Second arg to jsx function is null when there are no attributes', [ addCode(` // @jsx Foo function Foo(elem: number, props: { x: string }) {} const Bar = 123; <Bar />; `).newErrors( ` test.js:8 8: <Bar />; ^^^^^^^ JSX desugared to \`Foo(...)\` 8: <Bar />; ^^^^^^^ null. This type is incompatible with the expected param type of 5: function Foo(elem: number, props: { x: string }) {} ^^^^^^^^^^^^^ object type `, ), ]), test('Children are passed after the element and props', [ addCode(` // @jsx Foo function Foo(elem: number, props: null, child1: number, child2: string) {} const Bar = 123; <Bar>{true}{/regex/}</Bar> `).newErrors( ` test.js:8 8: <Bar>{true}{/regex/}</Bar> ^^^^^ JSX desugared to \`Foo(...)\` 8: <Bar>{true}{/regex/}</Bar> ^^^^ boolean. This type is incompatible with the expected param type of 5: function Foo(elem: number, props: null, child1: number, child2: string) {} ^^^^^^ number test.js:8 8: <Bar>{true}{/regex/}</Bar> ^^^^^ JSX desugared to \`Foo(...)\` 8: <Bar>{true}{/regex/}</Bar> ^^^^^^^ RegExp. This type is incompatible with the expected param type of 5: function Foo(elem: number, props: null, child1: number, child2: string) {} ^^^^^^ string `, ), ]).flowConfig("_flowconfig_with_flowlib"), test('React ignores certain props, but @jsx shouldnt', [ addCode(` // @jsx Foo function Foo(elem: number, props: {key: boolean, ref: number}) {} const Bar = 123; <Bar key="hi" ref="bye" />; `) .newErrors( ` test.js:7 7: <Bar key="hi" ref="bye" />; ^^^^^^^^^^^^^^^^^^^^^^^^^^ props of JSX element \`Bar\`. This type is incompatible with the expected param type of 5: function Foo(elem: number, props: {key: boolean, ref: number}) {} ^^^^^^^^^^^^^^^^^^^^^^^^^^^ object type Property \`key\` is incompatible: 7: <Bar key="hi" ref="bye" />; ^^^^ string. This type is incompatible with 5: function Foo(elem: number, props: {key: boolean, ref: number}) {} ^^^^^^^ boolean test.js:7 7: <Bar key="hi" ref="bye" />; ^^^^^^^^^^^^^^^^^^^^^^^^^^ props of JSX element \`Bar\`. This type is incompatible with the expected param type of 5: function Foo(elem: number, props: {key: boolean, ref: number}) {} ^^^^^^^^^^^^^^^^^^^^^^^^^^^ object type Property \`ref\` is incompatible: 7: <Bar key="hi" ref="bye" />; ^^^^^ string. This type is incompatible with 5: function Foo(elem: number, props: {key: boolean, ref: number}) {} ^^^^^^ number `, ), ]), test('jsx intrinsics should pass through a string', [ addCode(` // @jsx Foo function Foo(elem: "bar") {} <baz />; `) .newErrors( ` test.js:7 7: <baz />; ^^^^^^^ JSX desugared to \`Foo(...)\` 7: <baz />; ^^^^^^^ JSX Intrinsic: \`baz\`. Expected string literal \`bar\`, got \`baz\` instead 5: function Foo(elem: "bar") {} ^^^^^ string literal \`bar\` `, ), ]).flowConfig("_flowconfig_with_flowlib"), test('JSX element missing property should error', [ addCode(` // @jsx Foo function Foo(elem: number, props: {x: string}) {} const Bar = 123; <Bar y="hi" />; `) .newErrors( ` test.js:8 8: <Bar y="hi" />; ^^^^^^^^^^^^^^ JSX desugared to \`Foo(...)\` 8: <Bar y="hi" />; ^^^^^^^^^^^^^^ props of JSX element \`Bar\`. This type is incompatible with the expected param type of 5: function Foo(elem: number, props: {x: string}) {} ^^^^^^^^^^^ object type Property \`x\` is incompatible: 5: function Foo(elem: number, props: {x: string}) {} ^^^^^^^^^^^ property \`x\`. Property not found in 8: <Bar y="hi" />; ^^^^^^^^^^^^^^ props of JSX element \`Bar\` `, ), ]), test('Missing JSX element', [ addCode(` // @jsx Foo function Foo(elem: number) {} <Bar y="hi" />; `) .newErrors( ` test.js:7 7: <Bar y="hi" />; ^^^^^^^^^^^^^^ identifier \`Bar\`. Could not resolve name `, ), ]), test('Exact prop type without spread should work', [ addCode(` // @jsx Foo function Foo(elem: number, props: {| x: string |}) {} const Bar = 123; <Bar x="hi" />; `).noNewErrors(), ]), test('Exact prop type with spread still doesnt work', [ addCode(` // @jsx Foo function Foo(elem: number, props: {| x: string |}) {} const Bar = 123; const props = {x: "hi"}; <Bar {...props} />; `).newErrors( ` test.js:9 9: <Bar {...props} />; ^^^^^^^^^^^^^^^^^^ JSX desugared to \`Foo(...)\` 9: <Bar {...props} />; ^^^^^^^^^^^^^^^^^^ props of JSX element \`Bar\`. Inexact type is incompatible with exact type 5: function Foo(elem: number, props: {| x: string |}) {} ^^^^^^^^^^^^^^^ exact type: object type `, ), ]), test('Whitespace trimming', [ addCode(` // @jsx Foo function Foo( elem: number, props: null, child1: 'hello', child2: boolean, child3: 'bye', ...rest: Array<void> ) {} const Bar = 123; <Bar> hi {true} bye there </Bar>; `).newErrors( ` test.js:14 14: <Bar> ^^^^^ JSX desugared to \`Foo(...)\` 16: hi ^^ JSX text. Expected string literal \`hello\`, got \`hi\` instead 8: child1: 'hello', ^^^^^^^ string literal \`hello\` test.js:14 14: <Bar> ^^^^^ JSX desugared to \`Foo(...)\` 18: bye ^ JSX text. Expected string literal \`bye\`, got \`bye there\` instead 10: child3: 'bye', ^^^^^ string literal \`bye\` `, ), ]), test('Empty JSXText children are stripped out', [ addCode(` // @jsx Foo function Foo( elem: number, props: null, child1: "should be single space", child2: "should be true", child3: "should be empty string", child4: "should be single space", ...rest: Array<void> ) {} const Bar = 123; <Bar> {true} {''} </Bar>; `) .newErrors( ` test.js:16 16: <Bar> {true} ^^^^^ JSX desugared to \`Foo(...)\` 16: <Bar> {true} ^ JSX text. Expected string literal \`should be single space\`, got \` \` instead 8: child1: "should be single space", ^^^^^^^^^^^^^^^^^^^^^^^^ string literal \`should be single space\` test.js:16 16: <Bar> {true} ^^^^^ JSX desugared to \`Foo(...)\` 16: <Bar> {true} ^^^^ boolean. This type is incompatible with the expected param type of 9: child2: "should be true", ^^^^^^^^^^^^^^^^ string literal \`should be true\` test.js:16 16: <Bar> {true} ^^^^^ JSX desugared to \`Foo(...)\` 17: {''} </Bar>; ^^ string. Expected string literal \`should be empty string\`, got \`\` instead 10: child3: "should be empty string", ^^^^^^^^^^^^^^^^^^^^^^^^ string literal \`should be empty string\` test.js:16 16: <Bar> {true} ^^^^^ JSX desugared to \`Foo(...)\` 17: {''} </Bar>; ^ JSX text. Expected string literal \`should be single space\`, got \` \` instead 11: child4: "should be single space", ^^^^^^^^^^^^^^^^^^^^^^^^ string literal \`should be single space\` `, ) .because('JSXText children with only whitespace or newlines are ignored'), ]), test('JSXText trimming', [ addCode("// @jsx Foo"), addCode("const Bar = 123;"), addCode(` let Foo = (elem: any, props: any, c1: "First Middle Last") => {}; (<Bar> First${" "} Middle${" "} Last </Bar>); `) .newErrors( ` test.js:9 9: (<Bar> First ^^^^^ JSX desugared to \`Foo(...)\` 9: (<Bar> First ^ JSX text. Expected string literal \`First Middle Last\`, got \` First Middle Last \` instead 8: let Foo = (elem: any, props: any, c1: "First Middle Last") => {}; ^^^^^^^^^^^^^^^^^^^ string literal \`First Middle Last\` `, ) .because( "Leading whitespace on the first line and trailing whiteline on the "+ "last line is not trimmed", ), addCode(` (<Bar>First Middle Last</Bar>); `) .noNewErrors() .because('Empty lines are filtered out'), addCode("(<Bar>First\tMiddle\tLast</Bar>);") .noNewErrors() .because("Tabs are turned into spaces"), addCode("(<Bar>First Middle\t \t Last</Bar>)") .newErrors( ` test.js:24 24: (<Bar>First Middle Last</Bar>) ^^^^^ JSX desugared to \`Foo(...)\` 24: (<Bar>First Middle Last</Bar>) ^^^^^^^^^^^^^^^^^^^^^^^ JSX text. Expected string literal \`First Middle Last\`, got \`First Middle Last\` instead 8: let Foo = (elem: any, props: any, c1: "First Middle Last") => {}; ^^^^^^^^^^^^^^^^^^^ string literal \`First Middle Last\` `, ) .because("Multiple spaces midline stay as multiple spaces"), ]), ]);
/** * Talisman tokenizers/ngrams tests * ================================= * */ import assert from 'assert'; import ngrams, { bigrams, trigrams, quadrigrams } from '../../src/tokenizers/ngrams'; describe('ngrams', function() { it('should throw if n is < 1.', function() { assert.throws(function() { ngrams(-1, [1, 2, 3]); }, Error); }); it('should properly compute ngrams.', function() { const solutions = { 1: [['h'], ['e'], ['l'], ['l'], ['o']], 2: [['h', 'e'], ['e', 'l'], ['l', 'l'], ['l', 'o']], 3: [['h', 'e', 'l'], ['e', 'l', 'l'], ['l', 'l', 'o']], 4: [['h', 'e', 'l', 'l'], ['e', 'l', 'l', 'o']] }; Object.keys(solutions).forEach(n => { assert.deepEqual(ngrams(n, 'hello'.split('')), solutions[n], `n = ${n}`); assert.deepEqual(ngrams(n, 'hello'), solutions[n].map(s => s.join('')), `n = ${n}`); }); }); it('popular aliases should also work.', function() { assert.deepEqual(bigrams('hello'), ngrams(2, 'hello')); assert.deepEqual(trigrams('hello'), ngrams(3, 'hello')); assert.deepEqual(quadrigrams('hello'), ngrams(4, 'hello')); }); });
// This file has been generated by the SAPUI5 'AllInOne' Builder jQuery.sap.declare('sap.uxap.library-all'); if ( !jQuery.sap.isDeclared('sap.uxap.BlockBaseMetadata') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides class sap.uxap.BlockBaseMetadata jQuery.sap.declare('sap.uxap.BlockBaseMetadata'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.ElementMetadata'); // unlisted dependency retained sap.ui.define("sap/uxap/BlockBaseMetadata",["jquery.sap.global", "sap/ui/core/ElementMetadata"], function (jQuery, ElementMetadata) { "use strict"; /** * Creates a new metadata object for a BlockBase subclass. * * @param {string} sClassName fully qualified name of the class that is described by this metadata object * @param {object} oClassInfo static info to construct the metadata from * * @class * @author SAP SE * @version 1.36.6 * @since 1.26 * @alias sap.uxap.BlockBaseMetadata */ var BlockBaseMetadata = function (sClassName, oClassInfo) { // call super constructor ElementMetadata.apply(this, arguments); this._mViews = oClassInfo.metadata.views || {}; }; //chain the prototypes BlockBaseMetadata.prototype = jQuery.sap.newObject(ElementMetadata.prototype); BlockBaseMetadata.prototype.applySettings = function (oClassInfo) { var vRenderer = oClassInfo.hasOwnProperty("renderer") ? (oClassInfo.renderer || "") : undefined; ElementMetadata.prototype.applySettings.call(this, oClassInfo); if (vRenderer == null) { // If a renderer has been defined on the block then use it, otherwise use the BlockBaseRenderer this._sRendererName = null; } }; /** * Determines the class name of the renderer for the described control class. * @returns {string} renderer name */ BlockBaseMetadata.prototype.getRendererName = function () { //if we have not resolved the renderer yet if (!this._sBlockRenderer) { this._sBlockRenderer = this._resolveRendererName(); jQuery.sap.log.debug("BlockBaseMetadata :: " + this.getName() + " is renderer with " + this._sBlockRenderer); } return this._sBlockRenderer; }; BlockBaseMetadata.prototype._resolveRendererName = function () { var sCandidateRenderer = ElementMetadata.prototype.getRendererName.call(this); //we test if a specific render has been provided, in this case we keep it if (sCandidateRenderer == null) { var oParent = this.getParent(); if (oParent) { sCandidateRenderer = BlockBaseMetadata.prototype._resolveRendererName.apply(oParent); } else { throw new Error("BlockBaseMetadata :: no renderer found for " + this.getName()); } } return sCandidateRenderer; }; /** * return a view from its name * @param {*} sViewName * @returns {*} view */ BlockBaseMetadata.prototype.getView = function (sViewName) { return this._mViews[sViewName]; }; /** * return the view definition object * @returns {*} view */ BlockBaseMetadata.prototype.getViews = function () { return this._mViews; }; /** * setter for the view * @param {*} sViewName the name of the view * @param {*} oViewParameters view parameters * @returns {*} this */ BlockBaseMetadata.prototype.setView = function (sViewName, oViewParameters) { this._mViews[sViewName] = oViewParameters; return this; }; /** * checks whether some view are defined * @returns {*} has views */ BlockBaseMetadata.prototype.hasViews = function () { return !jQuery.isEmptyObject(this._mViews); }; return BlockBaseMetadata; }, /* bExport= */ true); }; // end of sap/uxap/BlockBaseMetadata.js if ( !jQuery.sap.isDeclared('sap.uxap.BlockBaseRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.BlockBaseRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder sap.ui.define("sap/uxap/BlockBaseRenderer",function () { "use strict"; var BlockBaseRenderer = {}; BlockBaseRenderer.render = function (oRm, oControl) { if (!oControl.getVisible()) { return; } oRm.write("<div"); oRm.writeControlData(oControl); if (oControl._getSelectedViewContent()) { oRm.addClass('sapUxAPBlockBase'); oRm.addClass("sapUxAPBlockBase" + oControl.getMode()); } else { var sClassShortName = oControl.getMetadata().getName().split(".").pop(); oRm.addClass('sapUxAPBlockBaseDefaultSize'); oRm.addClass('sapUxAPBlockBaseDefaultSize' + sClassShortName + oControl.getMode()); } oRm.writeClasses(); oRm.write(">"); if (oControl._getSelectedViewContent()) { oRm.renderControl(oControl._getSelectedViewContent()); } oRm.write("</div>"); }; return BlockBaseRenderer; }, /* bExport= */ true); }; // end of sap/uxap/BlockBaseRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.BreadCrumbsRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.BreadCrumbsRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder sap.ui.define("sap/uxap/BreadCrumbsRenderer",function () { "use strict"; /** * @class BreadCrumbs renderer. * @static */ var BreadCrumbsRenderer = {}; BreadCrumbsRenderer.render = function (oRm, oControl) { oRm.write("<div"); oRm.writeControlData(oControl); oRm.addClass("sapUxAPBreadCrumbs"); oRm.writeClasses(); oRm.writeAttribute("role", "navigation"); oRm.writeAttributeEscaped("aria-labelledby", oControl._getAriaLabelledBy().getId()); oRm.write(">"); this._renderOverflowSelect(oRm, oControl); if (!oControl._bOnPhone) { this._renderBreadcrumbTrail(oRm, oControl); } oRm.write("</div>"); }; BreadCrumbsRenderer._renderBreadcrumbTrail = function (oRm, oControl) { var aLinks = oControl.getLinks(), oCurrentLocation = oControl.getCurrentLocation(), oTubeIcon = oControl._getTubeIcon(), bShowCurrentLocation = oControl.getShowCurrentLocation(); oRm.write("<ul id='" + oControl.getId() + "-breadcrumbs'"); oRm.write(">"); aLinks.forEach(function (oLink) { oRm.write("<li>"); oRm.renderControl(oLink); oRm.renderControl(oTubeIcon); oRm.write("</li>"); }); if (bShowCurrentLocation) { oRm.write("<li>"); oRm.renderControl(oCurrentLocation); oRm.write("</li>"); } oRm.write("</ul>"); }; BreadCrumbsRenderer._renderOverflowSelect = function (oRm, oControl) { var oTubeIcon = oControl._getTubeIcon(); oRm.write("<div id='" + oControl.getId() + "-select'"); oRm.addClass("sapUiHidden"); oRm.writeClasses(); oRm.write(">"); oRm.write('<span class="sapUxAPBreadCrumbsDots">...</span>'); oRm.renderControl(oTubeIcon); oRm.renderControl(oControl._getOverflowSelect()); oRm.write("</div>"); }; return BreadCrumbsRenderer; }, /* bExport= */ true); }; // end of sap/uxap/BreadCrumbsRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.HierarchicalSelectRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.HierarchicalSelectRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.m.SelectRenderer'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Renderer'); // unlisted dependency retained sap.ui.define("sap/uxap/HierarchicalSelectRenderer",["sap/m/SelectRenderer", "sap/ui/core/Renderer" ], function (SelectRenderer, Renderer) { "use strict"; /** * @class ObjectPageRenderer renderer. * @static */ var HierarchicalSelectRenderer = Renderer.extend(SelectRenderer); HierarchicalSelectRenderer.addClass = function (oRm) { oRm.addClass("sapUxAPHierarchicalSelect"); }; return HierarchicalSelectRenderer; }, /* bExport= */ true); }; // end of sap/uxap/HierarchicalSelectRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageHeaderActionButtonRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.ObjectPageHeaderActionButtonRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.m.ButtonRenderer'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Renderer'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageHeaderActionButtonRenderer",["sap/m/ButtonRenderer", "sap/ui/core/Renderer"], function (ButtonRenderer, Renderer) { "use strict"; /** * @class ObjectPageRenderer renderer. * @static */ var ObjectPageHeaderActionButtonRenderer = Renderer.extend(ButtonRenderer); return ObjectPageHeaderActionButtonRenderer; }, /* bExport= */ true); }; // end of sap/uxap/ObjectPageHeaderActionButtonRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageLayout.designtime') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides the Design Time Metadata for the sap.uxap.ObjectPageLayout control jQuery.sap.declare('sap.uxap.ObjectPageLayout.designtime'); // unresolved dependency added by SAPUI5 'AllInOne' Builder sap.ui.define("sap/uxap/ObjectPageLayout.designtime",[], function() { "use strict"; return { aggregations : { sections : { domRef : ":sap-domref > .sapUxAPObjectPageWrapper" } }, cloneDomRef : ":sap-domref > header" }; }, /* bExport= */ false); }; // end of sap/uxap/ObjectPageLayout.designtime.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageSectionRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.ObjectPageSectionRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder sap.ui.define("sap/uxap/ObjectPageSectionRenderer",function () { "use strict"; /** * @class Section renderer. * @static */ var ObjectPageSectionRenderer = {}; ObjectPageSectionRenderer.render = function (oRm, oControl) { if (!oControl.getVisible() || !oControl._getInternalVisible()) { return; } var sTitle = oControl._getInternalTitle() ? oControl._getInternalTitle() : oControl.getTitle(); oRm.write("<section "); oRm.addClass("sapUxAPObjectPageSection"); oRm.writeClasses(); oRm.writeAttribute("role", "region"); oRm.writeAttributeEscaped("aria-labelledby", oControl.getAggregation("ariaLabelledBy").getId()); oRm.writeControlData(oControl); oRm.write(">"); if (oControl.getShowTitle() && oControl._getInternalTitleVisible()) { oRm.write("<div"); oRm.writeAttribute("role", "heading"); oRm.writeAttributeEscaped("id", oControl.getId() + "-header"); oRm.addClass("sapUxAPObjectPageSectionHeader"); oRm.writeClasses(); oRm.write(">"); oRm.write("<div"); oRm.writeAttributeEscaped("id", oControl.getId() + "-title"); oRm.addClass("sapUxAPObjectPageSectionTitle"); if (oControl.getTitleUppercase()) { oRm.addClass("sapUxAPObjectPageSectionTitleUppercase"); } oRm.writeClasses(); oRm.write(">"); oRm.writeEscaped(sTitle); oRm.write("</div>"); oRm.renderControl(oControl._getShowHideAllButton()); oRm.renderControl(oControl._getShowHideButton()); oRm.write("</div>"); } oRm.write("<div"); oRm.addClass("sapUxAPObjectPageSectionContainer"); oRm.writeClasses(); if (oControl._isHidden){ oRm.addStyle("display", "none"); } oRm.writeStyles(); oRm.write(">"); oControl.getSubSections().forEach(oRm.renderControl); oRm.write("</div>"); oRm.write("</section>"); }; return ObjectPageSectionRenderer; }, /* bExport= */ true); }; // end of sap/uxap/ObjectPageSectionRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageSubSectionRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.ObjectPageSubSectionRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder sap.ui.define("sap/uxap/ObjectPageSubSectionRenderer",function () { "use strict"; /** * @class Section renderer. * @static */ var ObjectPageSubSectionRenderer = {}; ObjectPageSubSectionRenderer.render = function (oRm, oControl) { var aActions, bHasTitle, bHasTitleLine, bHasActions, bUseTitleOnTheLeft; if (!oControl.getVisible() || !oControl._getInternalVisible()) { return; } aActions = oControl.getActions() || []; bHasActions = aActions.length > 0; bHasTitle = (oControl._getInternalTitleVisible() && (oControl.getTitle().trim() !== "")); bHasTitleLine = bHasTitle || bHasActions; oRm.write("<div "); oRm.writeAttribute("role", "region"); oRm.writeControlData(oControl); oRm.addClass("sapUxAPObjectPageSubSection"); oRm.writeClasses(oControl); oRm.writeClasses(); oRm.write(">"); if (bHasTitleLine) { oRm.write("<div"); oRm.addClass("sapUxAPObjectPageSubSectionHeader"); bUseTitleOnTheLeft = oControl._getUseTitleOnTheLeft(); if (bUseTitleOnTheLeft && oControl._onDesktopMediaRange()) { oRm.addClass("titleOnLeftLayout"); } oRm.writeAttributeEscaped("id", oControl.getId() + "-header"); oRm.writeClasses(); oRm.write(">"); oRm.write("<div"); if (bHasTitle) { oRm.writeAttribute("role", "heading"); } oRm.addClass('sapUxAPObjectPageSubSectionHeaderTitle'); if (oControl.getTitleUppercase()) { oRm.addClass("sapUxAPObjectPageSubSectionHeaderTitleUppercase"); } oRm.writeAttributeEscaped("id", oControl.getId() + "-headerTitle"); oRm.writeClasses(); oRm.writeAttribute("data-sap-ui-customfastnavgroup", true); if (bHasTitle) { oRm.writeAttribute("tabindex", 0); } oRm.write(">"); if (bHasTitle) { oRm.writeEscaped(oControl.getTitle()); } oRm.write("</div>"); if (bHasActions) { oRm.write("<div"); oRm.addClass('sapUxAPObjectPageSubSectionHeaderActions'); oRm.writeClasses(); oRm.writeAttribute("data-sap-ui-customfastnavgroup", true); oRm.write(">"); aActions.forEach(oRm.renderControl); oRm.write("</div>"); } oRm.write("</div>"); } oRm.write("<div"); oRm.addClass("ui-helper-clearfix"); oRm.addClass("sapUxAPBlockContainer"); oRm.addClass("sapUiResponsiveMargin"); oRm.writeClasses(); if (oControl._isHidden){ oRm.addStyle("display", "none"); } oRm.writeStyles(); oRm.write(">"); oRm.renderControl(oControl._getGrid()); oRm.write("<div"); oRm.addClass("sapUxAPSubSectionSeeMoreContainer"); oRm.writeClasses(); oRm.write(">"); oRm.renderControl(oControl._getSeeMoreButton()); oRm.write("</div>"); oRm.write("</div>"); oRm.write("</div>"); }; return ObjectPageSubSectionRenderer; }, /* bExport= */ true); }; // end of sap/uxap/ObjectPageSubSectionRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.component.Component') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.component.Component'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.uxap.ObjectPageConfigurationMode'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.UIComponent'); // unlisted dependency retained jQuery.sap.require('sap.ui.model.json.JSONModel'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Component'); // unlisted dependency retained sap.ui.define("sap/uxap/component/Component",[ "sap/uxap/ObjectPageConfigurationMode", "sap/ui/core/UIComponent", "sap/ui/model/json/JSONModel", "sap/ui/core/Component" ], function (ObjectPageConfigurationMode, UIComponent, JSONModel /*, Component*/) { "use strict"; var Component = UIComponent.extend("sap.uxap.component.Component", { metadata: { /* nothing new compared to a standard UIComponent */ }, /** * initialize the view containing the objectPageLayout */ init: function () { //step1: create model from configuration this._oModel = null; //internal component model this._oViewConfig = { //internal view configuration viewData: { component: this } }; //step2: load model from the component configuration switch (this.oComponentData.mode) { case ObjectPageConfigurationMode.JsonURL: // jsonUrl bootstraps the ObjectPageLayout on a json config url jsonConfigurationURL // case 1: load from an XML view + json for the object page layout configuration this._oModel = new UIComponent(this.oComponentData.jsonConfigurationURL); this._oViewConfig.viewName = "sap.uxap.component.ObjectPageLayoutUXDrivenFactory"; this._oViewConfig.type = sap.ui.core.mvc.ViewType.XML; break; case ObjectPageConfigurationMode.JsonModel: // JsonModel bootstraps the ObjectPageLayout from the external model objectPageLayoutMedatadata this._oViewConfig.viewName = "sap.uxap.component.ObjectPageLayoutUXDrivenFactory"; this._oViewConfig.type = sap.ui.core.mvc.ViewType.XML; break; default: jQuery.sap.log.error("UxAPComponent :: missing bootstrap information. Expecting one of the following: JsonURL, JsonModel and FacetsAnnotation"); } //create the UIComponent UIComponent.prototype.init.call(this); }, /** * Create view corresponding to the chosen config * @returns {sap.ui.view} Created view */ createContent: function () { var oController; //step3: create view this._oView = sap.ui.view(this._oViewConfig); //step4: bind the view with the model if (this._oModel) { oController = this._oView.getController(); //some factory requires pre-processing once the view and model are created if (oController && oController.connectToComponent) { oController.connectToComponent(this._oModel); } //can now apply the model and rely on the underlying factory logic this._oView.setModel(this._oModel, "objectPageLayoutMetadata"); } return this._oView; }, /** * traps propagated properties for postprocessing on useExternalModel cases * @param {*} vName the name of the property * @returns {*} result of the function */ propagateProperties: function (vName) { if (this.oComponentData.mode === ObjectPageConfigurationMode.JsonModel) { var oController = this._oView.getController(); //some factory requires post-processing once the view and model are created if (oController && oController.connectToComponent) { oController.connectToComponent(this.getModel("objectPageLayoutMetadata")); } } return UIComponent.prototype.propagateProperties.apply(this, arguments); }, /** * destroy the view and model before exiting */ destroy: function () { if (this._oView) { this._oView.destroy(); this._oView = null; } if (this._oModel) { this._oModel.destroy(); this._oModel = null; } if (UIComponent.prototype.destroy) { UIComponent.prototype.destroy.call(this); } } }); return Component; }); }; // end of sap/uxap/component/Component.js if ( !jQuery.sap.isDeclared('sap.uxap.component.ObjectPageComponentContainer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.component.ObjectPageComponentContainer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.core.ComponentContainer'); // unlisted dependency retained jQuery.sap.require('sap.uxap.ObjectPageConfigurationMode'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Component'); // unlisted dependency retained sap.ui.define("sap/uxap/component/ObjectPageComponentContainer",['sap/ui/core/ComponentContainer', 'sap/uxap/ObjectPageConfigurationMode', "sap/ui/core/Component"], function (ComponentContainer, ObjectPageConfigurationMode /*, Component */) { "use strict"; /** * The objectPageComponentContainer initialize and render an objectPageLayout * @alias sap.uxap.component.ObjectPageComponentContainer */ var ObjectPageComponentContainer = ComponentContainer.extend("sap.uxap.component.ObjectPageComponentContainer", /** @lends sap.uxap.component.ObjectPageComponentContainer.prototype */ { metadata: { properties: { "jsonConfigurationURL": {type: "string", group: "Behavior"}, "mode": {type: "sap.uxap.ObjectPageConfigurationMode", group: "Behavior"} } }, /** * initialize the component container and set default configuration */ init: function () { //set default config this.setPropagateModel(true); this.setName("sap.uxap.component"); }, /** * this ComponentContainer is working only with one component: the objectPageLayout * unlike the standard ComponentContainer, this ones exposes properties to the outside world and pass them on to the underlying component */ onBeforeRendering: function () { this._oComponent = sap.ui.component("sap.uxap"); if (!this._oComponent) { this._oComponent = sap.ui.component({ name: this.getName(), url: this.getUrl(), componentData: { //forward configuration to underlying component jsonConfigurationURL: this.getJsonConfigurationURL(), mode: this.getMode() } }); this.setComponent(this._oComponent, true); } // call the parent onBeforeRendering if (ComponentContainer.prototype.onBeforeRendering) { ComponentContainer.prototype.onBeforeRendering.call(this); } }, /** * Returns the instantiated objectPageLayout for further api manipulations or null if not not rendered already. * @returns {sap.uxap.ObjectPageLayout} Layout instanse */ getObjectPageLayoutInstance: function () { var oObjectPageLayoutInstance = null; if (this._oComponent && this._oComponent._oView) { oObjectPageLayoutInstance = this._oComponent._oView.byId("ObjectPageLayout"); } else { jQuery.sap.log.error("ObjectPageComponentContainer :: cannot find children ObjectPageLayout, has it been rendered already?"); } return oObjectPageLayoutInstance; }, /** * use the standard renderer */ renderer: "sap.ui.core.ComponentContainerRenderer" }); return ObjectPageComponentContainer; }); }; // end of sap/uxap/component/ObjectPageComponentContainer.js if ( !jQuery.sap.isDeclared('sap.uxap.library') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ /** * Initialization Code and shared classes of library sap.uxap. */ jQuery.sap.declare('sap.uxap.library'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Core'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.library'); // unlisted dependency retained jQuery.sap.require('sap.m.library'); // unlisted dependency retained jQuery.sap.require('sap.ui.layout.library'); // unlisted dependency retained sap.ui.define("sap/uxap/library",["jquery.sap.global", "sap/ui/core/Core", "sap/ui/core/library", "sap/m/library", "sap/ui/layout/library"], function (jQuery, Core, library) { "use strict"; /** * SAP UxAP * * @namespace * @name sap.uxap * @public */ // library dependencies // delegate further initialization of this library to the Core sap.ui.getCore().initLibrary({ name: "sap.uxap", dependencies: ["sap.ui.core", "sap.m", "sap.ui.layout"], types: [ "sap.uxap.BlockBaseColumnLayout", "sap.uxap.ObjectPageConfigurationMode", "sap.uxap.ObjectPageHeaderDesign", "sap.uxap.ObjectPageHeaderPictureShape", "sap.uxap.ObjectPageSubSectionLayout", "sap.uxap.ObjectPageSubSectionMode" ], interfaces: [], controls: [ "sap.uxap.AnchorBar", "sap.uxap.BlockBase", "sap.uxap.BreadCrumbs", "sap.uxap.HierarchicalSelect", "sap.uxap.ObjectPageHeader", "sap.uxap.ObjectPageHeaderActionButton", "sap.uxap.ObjectPageHeaderContent", "sap.uxap.ObjectPageLayout", "sap.uxap.ObjectPageSection", "sap.uxap.ObjectPageSectionBase", "sap.uxap.ObjectPageSubSection" ], elements: [ "sap.uxap.ModelMapping", "sap.uxap.ObjectPageHeaderLayoutData" ], version: "1.36.6" }); /** * @class Used by the BlockBase control to define how many columns should it be assigned by the objectPageSubSection. * The allowed values can be auto (subsection assigned a number of columns based on the parent objectPageLayout subsectionLayout property), 1, 2 or 3 * (This may not be a valid value for some subSectionLayout, for example asking for 3 columns in a 2 column layout would raise warnings). * * @static * @public * @ui5-metamodel This simple type also will be described in the UI5 (legacy) designtime metamodel */ sap.uxap.BlockBaseColumnLayout = sap.ui.base.DataType.createType('sap.uxap.BlockBaseColumnLayout', { isValid: function (vValue) { return /^(auto|[1-4]{1})$/.test(vValue); } }, sap.ui.base.DataType.getType('string') ); /** * Used by the BlockBase control to define if it should do automatic adjustment of its nested forms. * * @author SAP SE * @enum {string} * @static * @public * @ui5-metamodel This simple type also will be described in the UI5 (legacy) designtime metamodel */ sap.uxap.BlockBaseFormAdjustment = { /** * Any form within the block will be automatically adjusted to have as many columns as the colspan of its parent block. * @public */ BlockColumns: "BlockColumns", /** * Any form within the block will be automatically adjusted to have only one column. * @public */ OneColumn: "OneColumn", /** * No automatic adjustment of forms. * @public */ None: "None" }; /** * Used by the sap.uxap.component.Component how to initialize the ObjectPageLayout sections and subsections. * * @author SAP SE * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel */ sap.uxap.ObjectPageConfigurationMode = { /** * Determines the JSON url * @public */ JsonURL: "JsonURL", /** * Determines the JSON model * @public */ JsonModel: "JsonModel" }; /** * Used by the ObjectPageHeader control to define which design to use. * * @author SAP SE * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel */ sap.uxap.ObjectPageHeaderDesign = { /** * Light theme for the ObjectPageHeader. * @public */ Light: "Light", /** * Dark theme for the ObjectPageHeader. * @public */ Dark: "Dark" }; /** * Used by the ObjectPageHeader control to define which shape to use for the image. * * @author SAP SE * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel */ sap.uxap.ObjectPageHeaderPictureShape = { /** * Circle shape for the images in the ObjectPageHeader. * @public */ Circle: "Circle", /** * Square shape for the images in the ObjectPageHeader. * @public */ Square: "Square" }; /** * Used by the ObjectPagSubSection control to define which layout to apply. * * @author SAP SE * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel */ sap.uxap.ObjectPageSubSectionLayout = { /** * TitleOnTop: title and actions on top of the block area. * @public */ TitleOnTop: "TitleOnTop", /** * TitleOnLeft: title and actions on the left, inside the block area. * @public */ TitleOnLeft: "TitleOnLeft" }; /** * Used by the ObjectPageLayout control to define which layout to use (either Collapsed or Expanded). * * @author SAP SE * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel */ sap.uxap.ObjectPageSubSectionMode = { /** * Collapsed mode of display of the ObjectPageLayout. * @public */ Collapsed: "Collapsed", /** * Expanded mode of displaying the ObjectPageLayout. * @public */ Expanded: "Expanded" }; /** * Used by the ObjectSectionBase control to define the importance of the content contained in it. * * @author SAP SE * @enum {string} * @public * @since 1.32.0 * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel */ sap.uxap.Importance = { /** * Low importance of the content * @public */ Low: "Low", /** * Medium importance of the content * @public */ Medium: "Medium", /** * High importance of the content * @public */ High: "High" }; sap.uxap.i18nModel = (function () { return new sap.ui.model.resource.ResourceModel({ bundleUrl: jQuery.sap.getModulePath("sap.uxap.i18n.i18n", ".properties") }); }()); /** * * @type {{getClosestOPL: Function}} */ sap.uxap.Utilities = { /** * Returns the reference to the ObjectPageLayout for a given control * @static * @param {sap.ui.core.Control} oControl - the control to find ObjectPageLayout for * @private * @returns {*} Object Page layout referance */ getClosestOPL: function (oControl) { while (oControl && oControl.getMetadata().getName() !== "sap.uxap.ObjectPageLayout") { oControl = oControl.getParent(); } return oControl; }, isPhoneScenario: function () { if (sap.ui.Device.system.phone) { return true; } return sap.uxap.Utilities._isCurrentMediaSize("Phone"); }, isTabletScenario: function () { if (sap.ui.Device.system.tablet) { return true; } return sap.uxap.Utilities._isCurrentMediaSize("Tablet"); }, _isCurrentMediaSize: function (sMedia) { if (sap.ui.Device.media.hasRangeSet(sap.ui.Device.media.RANGESETS.SAP_STANDARD_EXTENDED)) { var oRange = sap.ui.Device.media.getCurrentRange(sap.ui.Device.media.RANGESETS.SAP_STANDARD_EXTENDED); if (oRange && oRange.name === sMedia) { return true; } } return jQuery("html").hasClass("sapUiMedia-Std-" + sMedia); } }; return sap.uxap; }, /* bExport= */ true); }; // end of sap/uxap/library.js if ( !jQuery.sap.isDeclared('sap.uxap.BreadCrumbs') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.BreadCrumbs. jQuery.sap.declare('sap.uxap.BreadCrumbs'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.m.Link'); // unlisted dependency retained jQuery.sap.require('sap.m.Select'); // unlisted dependency retained jQuery.sap.require('sap.m.Text'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.ResizeHandler'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.delegate.ItemNavigation'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Item'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Icon'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained sap.ui.define("sap/uxap/BreadCrumbs",[ "sap/m/Link", "sap/m/Select", "sap/m/Text", "sap/ui/core/Control", "sap/ui/core/ResizeHandler", "sap/ui/core/delegate/ItemNavigation", "sap/ui/core/Item", "sap/ui/core/Icon", "sap/ui/Device", "./library" ], function (Link, Select, Text, Control, ResizeHandler, ItemNavigation, Item, Icon, Device, library) { "use strict"; /** * Constructor for a new BreadCrumbs. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * * The BreadCrumbs control represents the navigation steps up to the current location in the application and allows * the user to quickly navigate to a previous location on the path that got him to the current location. * It has two main modes of operation. One is a trail of links followed by separators (when there's enough space * for the control to fit on one line), and the other is a dropdown list with the links (when the trail of links * wouldn't fit on one line). * @extends sap.ui.core.Control * * @author SAP SE * * @constructor * @public * @since 1.30 * @alias sap.uxap.BreadCrumbs * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var BreadCrumbs = Control.extend("sap.uxap.BreadCrumbs", /** @lends sap.uxap.BreadCrumbs.prototype */ { metadata: { library: "sap.uxap", properties: { /** * Sets the visibility of the current/last element in the BreadCrumbs path. */ showCurrentLocation: {type: "boolean", group: "Behavior", defaultValue: true} }, defaultAggregation: "links", aggregations: { /** * A list of all the active link elements in the BreadCrumbs control. */ links: {type: "sap.m.Link", multiple: true, singularName: "link"}, /** * The current/last element in the BreadCrumbs path. */ currentLocation: {type: "sap.m.Text", multiple: false}, /** * An icon that is used as a separator after each link in the standard mode. */ _tubeIcon: {type: "sap.ui.core.Icon", multiple: false, visibility: "hidden"}, /** * * A select control which is used to display the BreadCrumbs content on smaller mobile devices or * when there's not enough space for the control to fit on one line. */ _overflowSelect: {type: "sap.m.Select", multiple: false, visibility: "hidden"} } } }); BreadCrumbs.PAGEUP_AND_PAGEDOWN_JUMP_SIZE = 5; BreadCrumbs.prototype.init = function () { this._iREMSize = parseInt(jQuery("body").css("font-size"), 10); this._iContainerMaxHeight = this._iREMSize * 2; }; BreadCrumbs.prototype.onBeforeRendering = function () { this._bOnPhone = Device.system.phone; this._resetControl(); }; BreadCrumbs.prototype.onAfterRendering = function () { this._handleInitialModeSelection(); }; /** * Handles the the initial mode selection between overflowSelect and normal mode * * @private * @returns {object} this */ BreadCrumbs.prototype._handleInitialModeSelection = function () { if (this._bOnPhone) { this._setSelectVisible(true); return this; } this._configureKeyboardHandling(); if (!this._iContainerHeight) { this._iContainerHeight = this.$().outerHeight(); } if (this._iContainerHeight > this._iContainerMaxHeight) { this._toggleOverflowMode(true); return this; } this._sResizeListenerId = ResizeHandler.register(this, this._handleScreenResize.bind(this)); return this; }; /** * Handles the switching between overflowSelect and normal mode * * @private * @param {*} bUseOverFlowSelect use overflow select * @returns {object} this */ BreadCrumbs.prototype._toggleOverflowMode = function (bUseOverFlowSelect) { if (this._sResizeListenerId) { ResizeHandler.deregister(this._sResizeListenerId); } this._setSelectVisible(bUseOverFlowSelect); this._setBreadcrumbsVisible(!bUseOverFlowSelect); this._sResizeListenerId = ResizeHandler.register(this, this._handleScreenResize.bind(this)); return this; }; /** * Retrieves the tube separator icon with lazy loading * * @returns {sap.ui.core.Icon} tube icon * @private */ BreadCrumbs.prototype._getTubeIcon = function () { if (!this.getAggregation("_tubeIcon")) { this.setAggregation("_tubeIcon", new Icon({ "src": "sap-icon://slim-arrow-right", "color": "#bfbfbf", "size": "1rem", "useIconTooltip": false }).addStyleClass("sapUxAPTubeIcon")); } return this.getAggregation("_tubeIcon"); }; /** * Retrieves the overflowSelect with lazy loading * * @returns {sap.m.Select} select * @private */ BreadCrumbs.prototype._getOverflowSelect = function () { var oOverflowSelect, aSelectItems; if (!this.getAggregation("_overflowSelect")) { aSelectItems = this.getLinks().reverse() || []; aSelectItems.unshift(this.getCurrentLocation()); oOverflowSelect = new Select({ items: aSelectItems.map(this._createSelectItem), autoAdjustWidth: true }); oOverflowSelect.attachChange(this._overflowSelectChangeHandler); this.setAggregation("_overflowSelect", oOverflowSelect); } return this.getAggregation("_overflowSelect"); }; /** * Retrieves the an overflowSelect item using an sap.m.Link or sap.m.Text * * @param {sap.m.Text} oItem item * @returns {sap.ui.core.Item} new item * @private */ BreadCrumbs.prototype._createSelectItem = function (oItem) { return new Item({ key: oItem.getId(), text: oItem.getText() }); }; /** * Handles the overflowSelect "select" event * * @param {jQuery.Event} oEvent event * @returns {object} this * @private */ BreadCrumbs.prototype._overflowSelectChangeHandler = function (oEvent) { var oSelectedKey = oEvent.getParameter("selectedItem").getKey(), oControl = sap.ui.getCore().byId(oSelectedKey), sLinkHref, sLinkTarget; if (oControl instanceof Link) { sLinkHref = oControl.getHref(); oControl.firePress(); if (sLinkHref) { sLinkTarget = oControl.getTarget(); if (sLinkTarget) { window.open(sLinkHref, sLinkTarget); } else { window.location.href = sLinkHref; } } } return this; }; /** * Handles the resize event of the Breadcrumbs control container * * @param {jQuery.Event} oEvent event * @returns {object} this * @private */ BreadCrumbs.prototype._handleScreenResize = function (oEvent) { var bShouldSwitchToOverflow = this._shouldOverflow(), bUsingOverflowSelect = this._getUsingOverflowSelect(); if (bShouldSwitchToOverflow && !bUsingOverflowSelect) { this._toggleOverflowMode(true); } else if (!bShouldSwitchToOverflow && bUsingOverflowSelect) { this._toggleOverflowMode(false); } return this; }; /** * Handles the decision making on whether or not the control should go into overflow mode * * @returns {boolean} should overflow * @private */ BreadCrumbs.prototype._shouldOverflow = function () { var $breadcrumbs = this._getBreadcrumbsAsJQueryObject(), bShouldOverflow, bUsingOverflowSelect = this._getUsingOverflowSelect(); if (bUsingOverflowSelect) { this._setBreadcrumbsVisible(true); } $breadcrumbs.addClass("sapUxAPInvisible"); bShouldOverflow = $breadcrumbs.outerHeight() > this._iContainerMaxHeight; $breadcrumbs.removeClass("sapUxAPInvisible"); if (bUsingOverflowSelect) { this._setBreadcrumbsVisible(false); } return bShouldOverflow; }; /** * Retrieves the Breadcrumbs jQuery object * * @returns {jQuery.Object} breadcrumbs jQuery instance * @private */ BreadCrumbs.prototype._getBreadcrumbsAsJQueryObject = function () { if (!this._$breadcrumbs) { this._$breadcurmbs = this.$("breadcrumbs"); } return this._$breadcurmbs; }; /** * Retrieves the overflowSelect jQuery object * * @returns {jQuery.Object} jQuery select object * @private */ BreadCrumbs.prototype._getOverflowSelectAsJQueryObject = function () { if (!this._$select) { this._$select = this.$("select"); } return this._$select; }; /** * Sets the visibility of the Breadcrumbs * * @param {boolean} bVisible visibility of breadcrumbs * @returns {jQuery.Object} $this * @private */ BreadCrumbs.prototype._setBreadcrumbsVisible = function (bVisible) { var $this = this.$(), $breadcrumbs = this._getBreadcrumbsAsJQueryObject(), sFullWidthClass = "sapUxAPFullWidth", sSapHiddenClass = "sapUiHidden"; if (bVisible) { $breadcrumbs.removeClass(sSapHiddenClass); $this.removeClass(sFullWidthClass); } else { $breadcrumbs.addClass(sSapHiddenClass); $this.addClass(sFullWidthClass); } return $this; }; /** * Sets the visibility of the overflowSelect * * @param {boolean} bVisible select visibility state * @returns {*} this * @private */ BreadCrumbs.prototype._setSelectVisible = function (bVisible) { var $select = this._getOverflowSelectAsJQueryObject(), sSapHiddenClass = "sapUiHidden"; if (bVisible) { $select.removeClass(sSapHiddenClass); } else { $select.addClass(sSapHiddenClass); } return this; }; /** * Resets all of the internally cached values used by the control * * @returns {object} this * @private */ BreadCrumbs.prototype._resetControl = function () { this._iContainerHeight = null; this._$select = null; this._$breadcrumbs = null; this.setAggregation("_overflowSelect", null, true); if (this._sResizeListenerId) { ResizeHandler.deregister(this._sResizeListenerId); } return this; }; /** * Provides a default aria-labelled text * * @private * @returns {sap.ui.core.InvisibleText} Aria Labelled By */ BreadCrumbs.prototype._getAriaLabelledBy = function () { if (!this._oAriaLabelledBy) { BreadCrumbs.prototype._oAriaLabelledBy = new sap.ui.core.InvisibleText({ text: library.i18nModel.getResourceBundle().getText("BREADCRUMB_TRAIL_LABEL") }).toStatic(); } return this._oAriaLabelledBy; }; /** * Retrieves the ItemNavigation with lazy loading * * @private * @returns {sap.ui.core.delegate.ItemNavigation} item navigation */ BreadCrumbs.prototype._getItemNavigation = function () { if (!this._ItemNavigation) { this._ItemNavigation = new ItemNavigation(); } return this._ItemNavigation; }; /** * Retrieves the items which should be included in navigation. * * @private * @returns {array} aItemsToNavigate */ BreadCrumbs.prototype._getItemsToNavigate = function () { var aItemsToNavigate = this.getLinks(), oCurrentLocation = this.getCurrentLocation(), bShowCurrentLocation = this.getShowCurrentLocation(); if (bShowCurrentLocation && oCurrentLocation) { aItemsToNavigate.push(oCurrentLocation); } return aItemsToNavigate; }; /** * Configures the Keyboard handling for the control * * @private * @returns {object} this */ BreadCrumbs.prototype._configureKeyboardHandling = function () { var oItemNavigation = this._getItemNavigation(), oHeadDomRef = this._getBreadcrumbsAsJQueryObject()[0], iSelectedDomIndex = -1, aItemsToNavigate = this._getItemsToNavigate(), aNavigationDomRefs = []; aItemsToNavigate.forEach(function (oItem) { oItem.$().attr("tabIndex", "-1"); aNavigationDomRefs.push(oItem.getDomRef()); }); this.addDelegate(oItemNavigation); oItemNavigation.setCycling(false); oItemNavigation.setRootDomRef(oHeadDomRef); oItemNavigation.setItemDomRefs(aNavigationDomRefs); oItemNavigation.setSelectedIndex(iSelectedDomIndex); // fix the tab indexes so the first link to be 0 and read correctly by the screen reader this._getBreadcrumbsAsJQueryObject().attr("tabindex", "-1"); aItemsToNavigate[0].$().attr("tabindex", "0"); return this; }; /** * Handles PAGE UP key. * * @param {jQuery.Event} oEvent event * @private */ BreadCrumbs.prototype.onsappageup = function (oEvent) { this._handlePageKeys(oEvent, false); }; /** * Handles PAGE DOWN key. * * @param {jQuery.Event} oEvent * @private */ BreadCrumbs.prototype.onsappagedown = function (oEvent) { this._handlePageKeys(oEvent, true); }; BreadCrumbs.prototype._handlePageKeys = function (oEvent, bMovingDown) { var iNextIndex, aBreadCrumbs = this._getItemsToNavigate(), iEventTargetIndex = 0, iLastIndex = bMovingDown ? aBreadCrumbs.length - 1 : 0; oEvent.preventDefault(); aBreadCrumbs.some(function (oItem, iIndex) { if (oItem.getId() === oEvent.target.id) { iEventTargetIndex = iIndex; return true; } }); if (bMovingDown) { iNextIndex = iEventTargetIndex + BreadCrumbs.PAGEUP_AND_PAGEDOWN_JUMP_SIZE; } else { iNextIndex = iEventTargetIndex - BreadCrumbs.PAGEUP_AND_PAGEDOWN_JUMP_SIZE; } if (iNextIndex && aBreadCrumbs[iNextIndex]) { aBreadCrumbs[iNextIndex].focus(); } else if (aBreadCrumbs[iLastIndex]) { aBreadCrumbs[iLastIndex].focus(); } }; BreadCrumbs.prototype._getUsingOverflowSelect = function () { return !this._getOverflowSelectAsJQueryObject().hasClass("sapUiHidden"); }; BreadCrumbs.prototype.exit = function () { if (this._ItemNavigation) { this.removeDelegate(this._ItemNavigation); this._ItemNavigation.destroy(); this._ItemNavigation = null; } this._resetControl(); }; return BreadCrumbs; }); }; // end of sap/uxap/BreadCrumbs.js if ( !jQuery.sap.isDeclared('sap.uxap.HierarchicalSelect') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.HierarchicalSelect. jQuery.sap.declare('sap.uxap.HierarchicalSelect'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained jQuery.sap.require('sap.m.Select'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained sap.ui.define("sap/uxap/HierarchicalSelect",["jquery.sap.global", "sap/m/Select", "sap/ui/Device", "./library"], function (jQuery, Select, Device, library) { "use strict"; /** * Constructor for a new HierarchicalSelect. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * A select that display items on 2 level of hierarchy. * If a provided item has a custom data named "secondLevel", then it will be displayed as a second level, otherwise it would be displayed as a first level. * @extends sap.m.Select * * @author SAP SE * * @constructor * @public * @since 1.26 * @alias sap.uxap.HierarchicalSelect * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var HierarchicalSelect = Select.extend("sap.uxap.HierarchicalSelect", /** @lends sap.uxap.HierarchicalSelect.prototype */ { metadata: { library: "sap.uxap", properties: { /** * Determines whether the HierarchicalSelect items are displayed in upper case. */ upperCase: {type: "boolean", group: "Appearance", defaultValue: false} } } }); HierarchicalSelect.POPOVER_MIN_WIDTH_REM = 11; HierarchicalSelect.prototype.onAfterRenderingPicker = function () { Select.prototype.onAfterRenderingPicker.call(this); var aItems = this.getItems() || []; aItems.forEach(function (oItem) { var sClass = (oItem.data("secondLevel") === true) ? "sapUxAPHierarchicalSelectSecondLevel" : "sapUxAPHierarchicalSelectFirstLevel"; oItem.$().addClass(sClass); }, this); }; HierarchicalSelect.prototype.setUpperCase = function (bValue, bSuppressInvalidate) { this.setProperty("upperCase", bValue, bSuppressInvalidate); this.toggleStyleClass("sapUxAPHierarchicalSelectUpperCase", bValue); var oPicker = this.getAggregation("picker"); if (oPicker) { oPicker.toggleStyleClass("sapMSltPickerFirstLevelUpperCase", bValue); if (!bSuppressInvalidate) { oPicker.invalidate(); } } return this; }; /** * Keyboard handling requirement to have the same behavior on [ENTER] key * as on [SPACE] key (namely, to toggle the open state the select dropdown) */ HierarchicalSelect.prototype.onsapenter = Select.prototype.onsapspace; /** * Keyboard handling of [UP], [PAGE-UP], [PAGE-DOWN], [HOME], [END] keys * Stops propagation to avoid triggering the listeners for the same keys of the parent control (the AnchorBar) */ ["onsapup", "onsappageup", "onsappagedown", "onsaphome", "onsapend"].forEach(function (sName) { HierarchicalSelect.prototype[sName] = function (oEvent) { Select.prototype[sName].call(this, oEvent); oEvent.stopPropagation(); }; }); HierarchicalSelect.prototype._createDialog = function () { var oDialog = Select.prototype._createDialog.call(this); oDialog.getCustomHeader().addStyleClass("sapUxAPHierarchicalSelect"); return oDialog; }; /** * Decorate a Popover instance by adding some private methods. * * We are overriding function from sap.m.Select * in order to redefine position of popover * * @param {sap.m.Popover} * @private */ HierarchicalSelect.prototype._decoratePopover = function (oPopover) { Select.prototype._decoratePopover.call(this, oPopover); oPopover._adaptPositionParams = function () { this._marginTop = 0; this._marginLeft = 0; this._marginRight = 0; this._marginBottom = 0; this._arrowOffset = 0; this._offsets = ["0 0", "0 0", "0 0", "0 0"]; this._myPositions = ["end bottom", "end center", "end top", "begin center"]; this._atPositions = ["end top", "end center", "end bottom", "begin center"]; }; // offset the popup to make it cover the scrollbar (to avoid having page-scrollbar and popup-scrollbar appearing next to each other) if (Device.system.tablet || Device.system.desktop) { var fRight = jQuery.position.scrollbarWidth(); if (fRight > 0) { oPopover.setOffsetX(fRight); } } }; /** * Overriding function from sap.m.Select to access min-width of the popover * in order to ensure that min-width is not smaller than sap.uxap.HierarchicalSelect.POPOVER_MIN_WIDTH_REM */ HierarchicalSelect.prototype._onAfterRenderingPopover = function () { var oPopover = this.getPicker(), oPopoverDomRef = oPopover.getDomRef("cont"), sMinWidth = oPopoverDomRef.style.minWidth; if (jQuery.sap.endsWith(sMinWidth, "rem")) { sMinWidth = sMinWidth.substring(0, sMinWidth.length - 3); var iMinWidth = parseFloat(sMinWidth); if (iMinWidth < HierarchicalSelect.POPOVER_MIN_WIDTH_REM && oPopoverDomRef) { oPopoverDomRef.style.minWidth = HierarchicalSelect.POPOVER_MIN_WIDTH_REM + "rem"; } } }; return HierarchicalSelect; }); }; // end of sap/uxap/HierarchicalSelect.js if ( !jQuery.sap.isDeclared('sap.uxap.ModelMapping') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ModelMapping. jQuery.sap.declare('sap.uxap.ModelMapping'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained sap.ui.define("sap/uxap/ModelMapping",["sap/ui/core/Element", "./library"], function (Element, library) { "use strict"; /** * Constructor for a new ModelMapping. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] Initial settings for the new control * * @class * * Define the entity that will be passed to the ObjectPageLayout. * @extends sap.ui.core.Element * * @author SAP SE * * @constructor * @public * @alias sap.uxap.ModelMapping * @since 1.26 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ModelMapping = Element.extend("sap.uxap.ModelMapping", /** @lends sap.uxap.ModelMapping.prototype */ { metadata: { library: "sap.uxap", properties: { /** * Determines the the external model name. */ externalModelName: {type: "string", group: "Misc", defaultValue: null}, /** * Determines the the internal model name. */ internalModelName: {type: "string", group: "Misc", defaultValue: "Model"}, /** * Determines the the external path. */ externalPath: {type: "string", group: "Misc", defaultValue: null} } } }); return ModelMapping; }); }; // end of sap/uxap/ModelMapping.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageHeaderActionButton') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ObjectPageHeaderActionButton. jQuery.sap.declare('sap.uxap.ObjectPageHeaderActionButton'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.m.Button'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageHeaderActionButton",["sap/m/Button", "./library"], function (Button, library) { "use strict"; /** * Constructor for a new ObjectPageHeaderActionButton. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * * Button that can be used in the ObjectPageHeader action aggregation. * @extends sap.m.Button * * @author SAP SE * * @constructor * @public * @since 1.26 * @alias sap.uxap.ObjectPageHeaderActionButton * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectPageHeaderActionButton = Button.extend("sap.uxap.ObjectPageHeaderActionButton", /** @lends sap.uxap.ObjectPageHeaderActionButton.prototype */ { metadata: { library: "sap.uxap", properties: { /** * Hide the button text when rendered into the headerTitle part of the ObjectPageLayout. * This is useful if you want to display icons only in the headerTitle part but still want to display text + icon in the actionSheet that appears when not enough space is available on the screen for displaying all actions. */ hideText: {type: "boolean", defaultValue: true}, /** * Hide the button icon when rendered into the headerTitle part of the ObjectPageLayout. * This is useful if you want to display texts only in the headerTitle part but still want to display text + icon in the actionSheet that appears when not enough space is available on the screen for displaying all actions. */ hideIcon: {type: "boolean", defaultValue: false}, /** * Determines the order in which the button overflows. * @since 1.34.0 */ importance: { type: "sap.uxap.Importance", group: "Behavior", defaultValue: library.Importance.High } } } }); ObjectPageHeaderActionButton.prototype.applySettings = function (mSettings, oScope) { if (Button.prototype.applySettings) { Button.prototype.applySettings.call(this, mSettings, oScope); } this.toggleStyleClass("sapUxAPObjectPageHeaderActionButtonHideText", this.getHideText()); this.toggleStyleClass("sapUxAPObjectPageHeaderActionButtonHideIcon", this.getHideIcon()); }; ObjectPageHeaderActionButton.prototype.setHideText = function (bValue, bInvalidate) { this.toggleStyleClass("sapUxAPObjectPageHeaderActionButtonHideText", bValue); return this.setProperty("hideText", bValue, bInvalidate); }; ObjectPageHeaderActionButton.prototype.setHideIcon = function (bValue, bInvalidate) { this.toggleStyleClass("sapUxAPObjectPageHeaderActionButtonHideIcon", bValue); return this.setProperty("hideIcon", bValue, bInvalidate); }; return ObjectPageHeaderActionButton; }); }; // end of sap/uxap/ObjectPageHeaderActionButton.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageHeaderContent') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ObjectPageHeaderContent. jQuery.sap.declare('sap.uxap.ObjectPageHeaderContent'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained jQuery.sap.require('sap.m.Button'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageHeaderContent",["sap/ui/core/Control", "./library", "sap/m/Button"], function (Control, library, Button) { "use strict"; /** * Constructor for a new ObjectPageHeaderContent. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * ObjectPageHeaderContent represents the dynamic part of an Object page header. May contain any control. * Unlike the Object page header title, the Object page header content is part of the scrolling area of the Object page. * This enables it to hold any amount of information and still be usable on a mobile device. * @extends sap.ui.core.Control * * @author SAP SE * * @constructor * @public * @since 1.30 * @alias sap.uxap.ObjectPageHeaderContent * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectPageHeaderContent = Control.extend("sap.uxap.ObjectPageHeaderContent", /** @lends sap.uxap.ObjectPageHeaderContent.prototype */ { metadata: { library: "sap.uxap", properties: { /** * Determines the design of the header - Light or Dark */ contentDesign: { type: "sap.uxap.ObjectPageHeaderDesign", group: "Misc", defaultValue: sap.uxap.ObjectPageHeaderDesign.Light } }, aggregations: { /** * The list of Objects of type sap.ui.core.Control. */ content: {type: "sap.ui.core.Control", multiple: true, singularName: "content"}, /** * * Internal aggregation for the "Edit Header" button. */ _editHeaderButton: {type: "sap.m.Button", multiple: false, visibility: "hidden"} } } }); ObjectPageHeaderContent.prototype.onBeforeRendering = function () { var oParent = this.getParent(); if (oParent && (oParent instanceof library.ObjectPageLayout) && oParent.getShowEditHeaderButton()) { this._getInternalBtnAggregation("_editHeaderButton", "EDIT_HEADER", "-editHeaderBtn", "Transparent").attachPress(this._handleEditHeaderButtonPress, this); } }; ObjectPageHeaderContent.prototype._handleEditHeaderButtonPress = function (oEvent) { this.getParent().fireEditHeaderButtonPress(); }; ObjectPageHeaderContent.prototype._getInternalBtnAggregation = function (sAggregationName, sBtnText, sBtnIdText, sBtnType) { if (!this.getAggregation(sAggregationName)) { var oBtn = new Button({ text: library.i18nModel.getResourceBundle().getText(sBtnText), type: sBtnType, id: this.getId() + sBtnIdText }); this.setAggregation(sAggregationName, oBtn); } return this.getAggregation(sAggregationName); }; /** * The layout data to apply to a header cluster * called from the renderer * @private */ ObjectPageHeaderContent.prototype._getLayoutDataForControl = function (oControl) { var oLayoutData = oControl.getLayoutData(); if (!oLayoutData) { return; } else if (oLayoutData instanceof library.ObjectPageHeaderLayoutData) { return oLayoutData; } else if (oLayoutData.getMetadata().getName() == "sap.ui.core.VariantLayoutData") { // multiple LayoutData available - search here var aLayoutData = oLayoutData.getMultipleLayoutData(); for (var i = 0; i < aLayoutData.length; i++) { var oLayoutData2 = aLayoutData[i]; if (oLayoutData2 instanceof library.ObjectPageHeaderLayoutData) { return oLayoutData2; } } } }; return ObjectPageHeaderContent; }); }; // end of sap/uxap/ObjectPageHeaderContent.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageHeaderLayoutData') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ObjectPageHeaderLayoutData. jQuery.sap.declare('sap.uxap.ObjectPageHeaderLayoutData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.core.LayoutData'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageHeaderLayoutData",["sap/ui/core/LayoutData", "./library"], function (LayoutData, library) { "use strict"; /** * Constructor for a new ObjectPageHeaderLayoutData. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * This is a LayoutData Element that can be added to a control if this control is used within an ObjectPage headerContent aggregation * @extends sap.ui.core.LayoutData * * @author SAP SE * * @constructor * @public * @since 1.26 * @alias sap.uxap.ObjectPageHeaderLayoutData * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectPageHeaderLayoutData = LayoutData.extend("sap.uxap.ObjectPageHeaderLayoutData", /** @lends sap.uxap.ObjectPageHeaderLayoutData.prototype */ { metadata: { library: "sap.uxap", properties: { /** * If this property is set the control will be visible (or not) in a small sized layout. */ visibleS: {type: "boolean", group: "Misc", defaultValue: true}, /** * If this property is set the control will be visible (or not) in a medium sized layout. */ visibleM: {type: "boolean", group: "Misc", defaultValue: true}, /** * If this property is set the control will be visible (or not) in a large sized layout. */ visibleL: {type: "boolean", group: "Misc", defaultValue: true}, /** * If this property is set the control will display a separator before it. */ showSeparatorBefore: {type: "boolean", group: "Misc", defaultValue: false}, /** * If this property is set the control will display a separator after it. */ showSeparatorAfter: {type: "boolean", group: "Misc", defaultValue: false}, /** * If this property is set the control will take the provided size. */ width: {type: "sap.ui.core.CSSSize", group: "Misc", defaultValue: 'auto'} } } }); /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ return ObjectPageHeaderLayoutData; }); }; // end of sap/uxap/ObjectPageHeaderLayoutData.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageSectionBase') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ObjectPageSectionBase. jQuery.sap.declare('sap.uxap.ObjectPageSectionBase'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageSectionBase",["jquery.sap.global", "sap/ui/core/Control", "./library"], function (jQuery, Control, library) { "use strict"; /** * Constructor for a new ObjectPageSectionBase. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * An abstract container for object page sections and subSections * @extends sap.ui.core.Control * * @constructor * @public * @alias sap.uxap.ObjectPageSectionBase * @since 1.26 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectPageSectionBase = Control.extend("sap.uxap.ObjectPageSectionBase", /** @lends sap.uxap.ObjectPageSectionBase.prototype */ { metadata: { "abstract": true, library: "sap.uxap", properties: { /** * Section Title */ title: {type: "string", group: "Appearance", defaultValue: null}, /** * Invisible ObjectPageSectionBase are not rendered */ visible: {type: "boolean", group: "Appearance", defaultValue: true}, /** * Determines whether the section will be hidden on low resolutions. * @since 1.32.0 */ importance: { type: "sap.uxap.Importance", group: "Behavior", defaultValue: library.Importance.High } }, aggregations: { /** * The custom button that will provide a link to the section in the ObjectPageLayout anchor bar. * This button will be used as a custom template to be into the ObjectPageLayout anchorBar area, therefore property changes happening on this button template after the first rendering won't affect the actual button copy used in the anchorBar. * * If you want to change some of the button properties, you would need to bind them to a model. */ customAnchorBarButton: {type: "sap.m.Button", multiple: false} } } }); /** * Explicitly ask to connect to the UI5 model tree * * @name sap.uxap.ObjectPageSectionBase#connectToModels * @function * @type void * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ ObjectPageSectionBase.prototype.init = function () { //handled for ux rules management this._bInternalVisible = true; this._bInternalTitleVisible = true; this._sInternalTitle = ""; //hidden status this._isHidden = false; this._oParentObjectPageLayout = undefined; //store the parent objectPageLayout }; ObjectPageSectionBase.prototype.onAfterRendering = function () { if (this._getObjectPageLayout()) { this._getObjectPageLayout()._adjustLayout(); this._getObjectPageLayout()._setSectionsFocusValues(); } }; /** * set the internal visibility of the sectionBase. This is set by the ux rules (for example don't display a section that has no subSections) * @param bValue * @param bInvalidate if set to true, the sectionBase should be rerendered in order to be added or removed to the dom (similar to what a "real" internalVisibility property would trigger * @private */ ObjectPageSectionBase.prototype._setInternalVisible = function (bValue, bInvalidate) { if (bValue != this._bInternalVisible) { this._bInternalVisible = bValue; if (bInvalidate) { this.invalidate(); } } }; ObjectPageSectionBase.prototype._getInternalVisible = function () { return this._bInternalVisible; }; /** * set the internal visibility of the sectionBase title. This is set by the ux rules (for example don't display a subSection title if there are only 1 in the section) * @param bValue * @param bInvalidate if set to true, the sectionBase should be rerendered in order to be added or removed to the dom (similar to what a "real" internalVisibility property would trigger * @private */ ObjectPageSectionBase.prototype._setInternalTitleVisible = function (bValue, bInvalidate) { if (bValue != this._bInternalTitleVisible) { this._bInternalTitleVisible = bValue; if (bInvalidate) { this.invalidate(); } } }; ObjectPageSectionBase.prototype._getInternalTitleVisible = function () { return this._bInternalTitleVisible; }; /** * set the internal title of the sectionBase. This is set by the ux rules (for example the subSection title becomes the section title if there are only 1 subSection in the section) * @param sValue * @param bInvalidate if set to true, the sectionBase should be rerendered in order to be added or removed to the dom (similar to what a "real" internalVisibility property would trigger * @private */ ObjectPageSectionBase.prototype._setInternalTitle = function (sValue, bInvalidate) { if (sValue != this._sInternalTitle) { this._sInternalTitle = sValue; if (bInvalidate) { this.invalidate(); } } }; ObjectPageSectionBase.prototype._getInternalTitle = function () { return this._sInternalTitle; }; /** * getter for the parent object page layout * @returns {*} * @private */ ObjectPageSectionBase.prototype._getObjectPageLayout = function () { if (!this._oParentObjectPageLayout) { this._oParentObjectPageLayout = library.Utilities.getClosestOPL(this); } return this._oParentObjectPageLayout; }; /** * Notify the parent objectPageLayout of structural changes after the first rendering * @private */ ObjectPageSectionBase.prototype._notifyObjectPageLayout = function () { if (this.$().length && this._getObjectPageLayout()) { this._getObjectPageLayout()._adjustLayoutAndUxRules(); } }; // Generate proxies for aggregation mutators ["addAggregation", "insertAggregation", "removeAllAggregation", "removeAggregation", "destroyAggregation"].forEach(function (sMethod) { ObjectPageSectionBase.prototype[sMethod] = function () { var vResult = Control.prototype[sMethod].apply(this, arguments); this._notifyObjectPageLayout(); return vResult; }; }); ObjectPageSectionBase.prototype.setVisible = function (bValue, bSuppressInvalidate) { if (!this._getObjectPageLayout()) { return this.setProperty("visible", bValue, bSuppressInvalidate); } this.setProperty("visible", bValue, true); /* handle invalidation ourselves in adjustLayoutAndUxRules */ this._getObjectPageLayout()._adjustLayoutAndUxRules(); this.invalidate(); return this; }; ObjectPageSectionBase.prototype.setTitle = function (sValue, bSuppressInvalidate) { this.setProperty("title", sValue, bSuppressInvalidate); this._notifyObjectPageLayout(); return this; }; ObjectPageSectionBase.prototype._shouldBeHidden = function () { return ObjectPageSectionBase._importanceMap[this.getImportance()] > ObjectPageSectionBase._importanceMap[this._sCurrentLowestImportanceLevelToShow]; }; ObjectPageSectionBase._importanceMap = { "Low": 3, "Medium": 2, "High": 1 }; ObjectPageSectionBase.prototype._updateShowHideState = function (bHide) { var oObjectPage = this._getObjectPageLayout(); this._isHidden = bHide; this.$().children(this._sContainerSelector).toggle(!bHide); if (oObjectPage) { oObjectPage._adjustLayout(); } return this; }; ObjectPageSectionBase.prototype._getIsHidden = function () { return this._isHidden; }; ObjectPageSectionBase.prototype._expandSection = function () { return this._updateShowHideState(false); }; ObjectPageSectionBase.prototype._showHideContent = function () { return this._updateShowHideState(!this._getIsHidden()); }; /** * Called to set the visibility of the section / subsection * @params oSection, sCurrentLowestImportanceLevelToShow * * @private */ ObjectPageSectionBase.prototype._applyImportanceRules = function (sCurrentLowestImportanceLevelToShow) { this._sCurrentLowestImportanceLevelToShow = sCurrentLowestImportanceLevelToShow; if (this.getDomRef()) { this._updateShowHideState(this._shouldBeHidden()); } else { this._isHidden = this._shouldBeHidden(); } }; /******************************************************************************* * Keyboard navigation ******************************************************************************/ ObjectPageSectionBase.PAGEUP_AND_PAGEDOWN_JUMP_SIZE = 5; /** * Handler for key down - handle * @param oEvent - The event object */ ObjectPageSectionBase.prototype.onkeydown = function (oEvent) { // Filter F7 key down if (oEvent.keyCode === jQuery.sap.KeyCodes.F7) { var aSubSections = this.getSubSections(), oFirstSubSection = aSubSections[0], oLastFocusedEl; if (aSubSections.length === 1) { oLastFocusedEl = oFirstSubSection._oLastFocusedControlF7; if (oLastFocusedEl) { oLastFocusedEl.$().focus(); } else { oFirstSubSection.$().firstFocusableDomRef().focus(); } } else { if (oFirstSubSection.getActions().length) { oFirstSubSection.getActions()[0].$().focus(); } } } }; /** * Handler for arrow down * @param oEvent - The event object */ ObjectPageSectionBase.prototype.onsapdown = function (oEvent) { this._handleFocusing(oEvent, oEvent.currentTarget.nextSibling); }; ObjectPageSectionBase.prototype._handleFocusing = function (oEvent, oElementToReceiveFocus) { if (this._targetIsCorrect(oEvent) && oElementToReceiveFocus) { oEvent.preventDefault(); oElementToReceiveFocus.focus(); this._scrollParent(jQuery(oElementToReceiveFocus).attr("id")); } }; ObjectPageSectionBase.prototype._targetIsCorrect = function (oEvent) { return oEvent.srcControl === this; }; /** * Handler for arrow right */ ObjectPageSectionBase.prototype.onsapright = ObjectPageSectionBase.prototype.onsapdown; /** * Handler for arrow up * @param oEvent - The event object */ ObjectPageSectionBase.prototype.onsapup = function (oEvent) { this._handleFocusing(oEvent, oEvent.currentTarget.previousSibling); }; /** * Handler for arrow left */ ObjectPageSectionBase.prototype.onsapleft = ObjectPageSectionBase.prototype.onsapup; /** * Handler for HOME key * @param oEvent - The event object */ ObjectPageSectionBase.prototype.onsaphome = function (oEvent) { this._handleFocusing(oEvent, oEvent.currentTarget.parentElement.firstChild); }; /** * Handler for END key * @param oEvent - The event object */ ObjectPageSectionBase.prototype.onsapend = function (oEvent) { this._handleFocusing(oEvent, oEvent.currentTarget.parentElement.lastChild); }; /** * Handler for PAGE UP event. * * @param {jQuery.Event} oEvent * @private */ ObjectPageSectionBase.prototype.onsappageup = function (oEvent) { if (!this._targetIsCorrect(oEvent)) { return; } oEvent.preventDefault(); var iNextIndex; var aSections = jQuery(oEvent.currentTarget).parent().children(); var focusedSectionId; aSections.each(function (iSectionIndex, oSection) { if (jQuery(oSection).attr("id") === oEvent.currentTarget.id) { iNextIndex = iSectionIndex - (ObjectPageSectionBase.PAGEUP_AND_PAGEDOWN_JUMP_SIZE + 1); return; } }); if (iNextIndex && aSections[iNextIndex]) { aSections[iNextIndex].focus(); focusedSectionId = jQuery(aSections[iNextIndex]).attr("id"); } else if (aSections[0]) { aSections[0].focus(); focusedSectionId = jQuery(aSections[0]).attr("id"); } this._scrollParent(focusedSectionId); }; /** * Handler for PAGE DOWN event. * * @param {jQuery.Event} oEvent * @private */ ObjectPageSectionBase.prototype.onsappagedown = function (oEvent) { if (!this._targetIsCorrect(oEvent)) { return; } oEvent.preventDefault(); var iNextIndex; var aSections = jQuery(oEvent.currentTarget).parent().children(); var focusedSectionId; aSections.each(function (iSectionIndex, oSection) { if (jQuery(oSection).attr("id") === oEvent.currentTarget.id) { iNextIndex = iSectionIndex + ObjectPageSectionBase.PAGEUP_AND_PAGEDOWN_JUMP_SIZE + 1; return; } }); if (iNextIndex && aSections[iNextIndex]) { aSections[iNextIndex].focus(); focusedSectionId = jQuery(aSections[iNextIndex]).attr("id"); } else if (aSections[aSections.length - 1]) { aSections[aSections.length - 1].focus(); focusedSectionId = jQuery(aSections[aSections.length - 1]).attr("id"); } this._scrollParent(focusedSectionId); }; /** * Tells the ObjectPageLayout instance to scroll itself to a given section (by Id) * @param sId * @private */ ObjectPageSectionBase.prototype._scrollParent = function (sId) { if (this._getObjectPageLayout()) { this._getObjectPageLayout().scrollToSection(sId, 0, 10); } }; return ObjectPageSectionBase; }); }; // end of sap/uxap/ObjectPageSectionBase.js if ( !jQuery.sap.isDeclared('sap.uxap.AnchorBar') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.AnchorBar. jQuery.sap.declare('sap.uxap.AnchorBar'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.m.Button'); // unlisted dependency retained jQuery.sap.require('sap.m.PlacementType'); // unlisted dependency retained jQuery.sap.require('sap.m.Popover'); // unlisted dependency retained jQuery.sap.require('sap.m.Toolbar'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.IconPool'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Item'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.ResizeHandler'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.delegate.ScrollEnablement'); // unlisted dependency retained jQuery.sap.require('sap.ui.layout.HorizontalLayout'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.CustomData'); // unlisted dependency retained sap.ui.define("sap/uxap/AnchorBar",[ "sap/m/Button", "sap/m/PlacementType", "sap/m/Popover", "sap/m/Toolbar", "sap/ui/core/IconPool", "sap/ui/core/Item", "sap/ui/core/ResizeHandler", "sap/ui/core/delegate/ScrollEnablement", "sap/ui/layout/HorizontalLayout", "sap/ui/Device", "sap/ui/core/CustomData", "./HierarchicalSelect", "./library" ], function (Button, PlacementType, Popover, Toolbar, IconPool, Item, ResizeHandler, ScrollEnablement, HorizontalLayout, Device, CustomData, HierarchicalSelect, library) { "use strict"; /** * Constructor for a new AnchorBar. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * Anchor bar is the navigation bar of an Object page. Its purpose is to provide links to all Sections and Subsections. Takes the form of a Select on phone. * @extends sap.m.Toolbar * * @author SAP SE * * @constructor * @public * @since 1.26 * @alias sap.uxap.AnchorBar * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var AnchorBar = Toolbar.extend("sap.uxap.AnchorBar", /** @lends sap.uxap.AnchorBar.prototype */ { metadata: { library: "sap.uxap", properties: { /** * Determines whether to show a Popover with Subsection links when clicking on Section links in the Anchor bar. */ showPopover: {type: "boolean", defaultValue: true}, /** * Determines whether the Anchor bar items are displayed in upper case. */ upperCase: {type: "boolean", defaultValue: false} }, associations: { /** * The button that represents the Section being scrolled by the user. */ selectedButton: {type: "sap.m.Button", multiple: false} }, aggregations: { _select: {type: "sap.uxap.HierarchicalSelect", multiple: false, visibility: "hidden"}, _popovers: {type: "sap.m.Popover", multiple: true, visibility: "hidden"}, _scrollArrowLeft: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"}, _scrollArrowRight: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"} } } }); AnchorBar.prototype.init = function () { if (Toolbar.prototype.init) { Toolbar.prototype.init.call(this); } this.addStyleClass("sapUxAPAnchorBar"); this._oPressHandlers = {}; //keep references on the press handlers we set on first level items (in case of behavior change) this._oSectionInfo = {}; //keep scrolling info on sections this._oScroller = null; //are we on a rtl scenario? //IE handles rtl in a transparent way (positions positives, scroll starts at the end) //while firefox, safari and chrome have a special management (scroll at the beginning and negative positioning) //therefore we will apply some specific actions only if are in rtl and not in IE. this._bRtlScenario = sap.ui.getCore().getConfiguration().getRTL() && !Device.browser.msie; //there are 2 different uses cases: //case 1: on a real phone we don't need the scrolling anchorBar, just the hierarchicalSelect //case 2: on a a real ipad or a desktop we need both as the size may change this._bHasButtonsBar = Device.system.tablet || Device.system.desktop; this._oSelect = this._getHierarchicalSelect(); //case 2 requires the scrolling anchorBar if (this._bHasButtonsBar) { //horizontal scrolling this._oScroller = new ScrollEnablement(this, this.getId() + "-scroll", { horizontal: true, vertical: false, nonTouchScrolling: true }); this._iREMSize = parseInt(jQuery("body").css("font-size"), 10); this._iTolerance = this._iREMSize * 1; // 1 rem this._iOffset = this._iREMSize * 3; // 3 rem //listen to resize this._sResizeListenerId = undefined; //defined in onAfterRendering } //composite controls this.setDesign("Transparent"); //styling is coming from css }; /******************************************************************************* * UX design ******************************************************************************/ AnchorBar.SCROLL_STEP = 250;// how many pixels to scroll with every overflow arrow click AnchorBar.SCROLL_DURATION = 500; // ms AnchorBar.DOM_CALC_DELAY = 200; // ms AnchorBar.prototype.setSelectedButton = function (oButton) { if (typeof oButton === "string") { oButton = sap.ui.getCore().byId(oButton); } if (oButton) { if (oButton.getId() === this.getSelectedButton()) { return; } var oSelectedSectionId = oButton.data("sectionId"); if (oSelectedSectionId) { this._oSelect.setSelectedKey(oButton.getId()); } if (this._bHasButtonsBar) { //remove selection class from the currently selected item this.$().find(".sapUxAPAnchorBarButtonSelected").removeClass("sapUxAPAnchorBarButtonSelected"); oButton.$().addClass("sapUxAPAnchorBarButtonSelected"); if (oSelectedSectionId) { this.scrollToSection(oSelectedSectionId, AnchorBar.SCROLL_DURATION); } this._setAnchorButtonsTabFocusValues(oButton); } } return this.setAssociation("selectedButton", oButton, true /* don't rerender */); }; /******************************************************************************* * Responsive behavior ******************************************************************************/ AnchorBar.prototype.setShowPopover = function (bValue, bSuppressInvalidate) { if (this.getShowPopover() === bValue) { return this; } var sSelectedButton, bNeedInvalidate = !jQuery.isEmptyObject(this._oPressHandlers); //changing the behavior after the firstRendering is removing all press handlers on first level items if (bNeedInvalidate) { var aContent = this.getContent() || []; sSelectedButton = this.getSelectedButton(); aContent.forEach(this._detachPopoverHandler, this); } this.setProperty("showPopover", bValue, true /* always trigger re-rendering manually */); if (bNeedInvalidate) { this.rerender(); if (sSelectedButton) { this.setSelectedButton(sSelectedButton); } } return this; }; AnchorBar.prototype.getSelectedSection = function () { var oSelectedButton = this.getSelectedButton(); if (oSelectedButton && (typeof (oSelectedButton) === "string" )) { oSelectedButton = sap.ui.getCore().byId(oSelectedButton); } if (oSelectedButton && (oSelectedButton instanceof Button) && oSelectedButton.data("sectionId")) { return sap.ui.getCore().byId(oSelectedButton.data("sectionId")); } return null; }; /** * create phone equivalents for each of the provided content controls */ AnchorBar.prototype.onBeforeRendering = function () { if (Toolbar.prototype.onBeforeRendering) { Toolbar.prototype.onBeforeRendering.call(this); } var aContent = this.getContent() || [], bUpperCase = this.getUpperCase(), oPopoverState = { oLastFirstLevelButton: null, oCurrentPopover: null }; //rebuild select items this._oSelect.removeAllItems(); this._oSelect.setUpperCase(bUpperCase); this.toggleStyleClass("sapUxAPAnchorBarUpperCase", bUpperCase); //create responsive equivalents of the provided controls aContent.forEach(function (oButton) { this._createSelectItem(oButton); //desktop scenario logic: builds the scrolling anchorBar if (this._bHasButtonsBar) { this._createPopoverSubMenu(oButton, oPopoverState); } }, this); }; AnchorBar.prototype.addContent = function (oButton, bInvalidate) { oButton.addStyleClass("sapUxAPAnchorBarButton"); oButton.removeAllAriaDescribedBy(); if (this._bHasButtonsBar && (oButton.data("secondLevel") === true || oButton.data("secondLevel") === "true")) { //attach handler on the scrolling mechanism oButton.attachPress(this._handleDirectScroll, this); } return this.addAggregation("content", oButton, bInvalidate); }; AnchorBar.prototype._createSelectItem = function (oButton) { var bIsSecondLevel = oButton.data("secondLevel") === true || oButton.data("secondLevel") === "true"; //create the phone equivalent item if the button has some visible text (UX rule) if (oButton.getText().trim() != "" && (!bIsSecondLevel || oButton.data("bTitleVisible") === true)) { var oPhoneItem = new Item({ key: oButton.getId(), text: oButton.getText(), customData: [ new CustomData({ key: "secondLevel", value: oButton.data("secondLevel") }) ] }); this._oSelect.addItem(oPhoneItem); } }; AnchorBar.prototype._createPopoverSubMenu = function (oButton, oPopoverState) { var bIsSecondLevel = oButton.data("secondLevel") === true || oButton.data("secondLevel") === "true", fnPressHandler = null; //handles the tablet/desktop hierarchical behavior //a second level is injected into the latest first level //at this point we know that there are children to the last firstLevel therefore we can create the popover if (bIsSecondLevel) { if (oPopoverState.oLastFirstLevelButton && oPopoverState.oCurrentPopover) { //don't attach the parent press handler for each child if (!this._oPressHandlers[oPopoverState.oLastFirstLevelButton.getId()]) { fnPressHandler = jQuery.proxy(this._handlePopover, /* closure with oLastFirstLevelButton and oCurrentPopover as context */ { oCurrentPopover: oPopoverState.oCurrentPopover, oLastFirstLevelButton: oPopoverState.oLastFirstLevelButton } ); oPopoverState.oLastFirstLevelButton.attachPress(fnPressHandler); this._oPressHandlers[oPopoverState.oLastFirstLevelButton.getId()] = fnPressHandler; } oPopoverState.oCurrentPopover.addContent(oButton); } else if (this.getShowPopover()) { jQuery.sap.log.error("sapUxApAnchorBar :: missing parent first level for item " + oButton.getText()); } else { this.removeContent(oButton); } } else { oPopoverState.oLastFirstLevelButton = oButton; //default behavior: the first level show a popover containing second levels if (this.getShowPopover()) { oPopoverState.oCurrentPopover = new Popover({ placement: PlacementType.Bottom, showHeader: false, verticalScrolling: true, horizontalScrolling: false, contentWidth: "auto", showArrow: false }); oPopoverState.oCurrentPopover.addStyleClass("sapUxAPAnchorBarPopover"); this._addKeyboardHandling(oPopoverState.oCurrentPopover); this.addAggregation('_popovers', oPopoverState.oCurrentPopover); //alternative behavior: the first level triggers direct navigation } else if (!this._oPressHandlers[oPopoverState.oLastFirstLevelButton.getId()]) { fnPressHandler = jQuery.proxy(this._handleDirectScroll, this); oPopoverState.oLastFirstLevelButton.attachPress(fnPressHandler); this._oPressHandlers[oPopoverState.oLastFirstLevelButton.getId()] = fnPressHandler; } } }; AnchorBar.prototype._addKeyboardHandling = function (oCurrentPopover) { oCurrentPopover.onsapdown = function (oEvent) { if (oEvent.target.nextSibling) { oEvent.target.nextSibling.focus(); } }; oCurrentPopover.onsapright = function (oEvent) { oCurrentPopover.onsapdown(oEvent); }; oCurrentPopover.onsapup = function (oEvent) { if (oEvent.target.previousSibling) { oEvent.target.previousSibling.focus(); } }; oCurrentPopover.onsapleft = function (oEvent) { oCurrentPopover.onsapup(oEvent); }; oCurrentPopover.onsaphome = function (oEvent) { if (oEvent.target.parentElement.firstChild) { oEvent.target.parentElement.firstChild.focus(); } }; oCurrentPopover.onsapend = function (oEvent) { if (oEvent.target.parentElement.lastChild) { oEvent.target.parentElement.lastChild.focus(); } }; oCurrentPopover.onsappageup = this._handlePageUp.bind(oCurrentPopover); oCurrentPopover.onsappagedown = this._handlePageDown.bind(oCurrentPopover); }; AnchorBar.prototype._detachPopoverHandler = function (oButton) { if (this._oPressHandlers[oButton.getId()]) { oButton.detachPress(this._oPressHandlers[oButton.getId()]); this._oPressHandlers[oButton.getId()] = null; } }; AnchorBar.prototype._handlePopover = function (oEvent) { var aPopoverButtons = this.oCurrentPopover.getContent() || []; //open the popover only if we are in Tablet/Desktop scenario = the button is visible in the anchorBar if (this.oLastFirstLevelButton.$().is(":visible")) { //specific use case management: if there are only 1 button in the popover, then we don't display it and navigate directly (= the subsection is "promoted" it to a section level) //this is a specific behavior asked by UX as of Sep 25, 2014 if (aPopoverButtons.length == 1) { aPopoverButtons[0].firePress({}); } else { this.oCurrentPopover.openBy(this.oLastFirstLevelButton); } } }; AnchorBar.prototype._handleDirectScroll = function (oEvent) { if (oEvent.getSource().getParent() instanceof Popover) { oEvent.getSource().getParent().close(); } this._requestScrollToSection(oEvent.getSource().data("sectionId")); }; AnchorBar.prototype._requestScrollToSection = function (sRequestedSectionId) { var oRequestedSection = sap.ui.getCore().byId(sRequestedSectionId), oRequestedSectionParent = oRequestedSection.getParent(); if (this.getParent() instanceof library.ObjectPageLayout) { // determine the next section that will appear selected in the anchorBar after the scroll var sNextSelectedSection = sRequestedSectionId; // if the requestedSection is a subsection, the the nextSelectedSection will be its parent (since anchorBar contains only first-level sections) if (oRequestedSection instanceof library.ObjectPageSubSection && oRequestedSectionParent instanceof library.ObjectPageSection) { sNextSelectedSection = oRequestedSectionParent.getId(); } // we set *direct* scrolling by which we instruct the page to *skip* processing of intermediate sections (sections between current and requested) this.getParent().setDirectScrollingToSection(sNextSelectedSection); // finally request the page to scroll to the requested section this.getParent().scrollToSection(oRequestedSection.getId()); } if (oRequestedSection instanceof library.ObjectPageSubSection && oRequestedSectionParent instanceof library.ObjectPageSection) { oRequestedSectionParent.setAssociation("selectedSubSection", oRequestedSection, true); } }; /** * called on phone display only when a user selects a section to navigate to * simulate the press on the corresponding button * @param {*} oEvent event * @private */ AnchorBar.prototype._onSelectChange = function (oEvent) { var oSelectedItem = oEvent.getParameter("selectedItem"), oOriginalControl; oOriginalControl = sap.ui.getCore().byId(oSelectedItem.getKey()); if (oOriginalControl) { this._requestScrollToSection(oOriginalControl.data("sectionId")); } else { jQuery.sap.log.error("AnchorBar :: cannot find corresponding button", oSelectedItem.getKey()); } }; AnchorBar.prototype._getHierarchicalSelect = function () { if (!this.getAggregation('_select')) { this.setAggregation('_select', new HierarchicalSelect({ width: "100%", icon: "sap-icon://slim-arrow-down", change: jQuery.proxy(this._onSelectChange, this) })); } return this.getAggregation('_select'); }; /** * Creates a new scroll arrow. The scroll arrow consists of two controls: * 1. A HorizontalLayout which is used to display the gradient mask and to serve as a container for the arrow. * 2. A Button which displays the arrow itself. * In bluecrystal theme the button appears when hovering over the gradient mask and is not focusable. * In HCB, the button is always visible and can receive focus. * * @param {boolean} bLeft indicates whether this is the left button * @return {sap.ui.layout.HorizontalLayout} a new scroll arrow * @private */ AnchorBar.prototype._createScrollArrow = function (bLeft) { var sArrowId, sIconName, sArrowClass, oScrollButton, that = this; if (bLeft) { sArrowId = this.getId() + "-arrowScrollLeft"; sIconName = "slim-arrow-left"; sArrowClass = "anchorBarArrowLeft"; } else { sArrowId = this.getId() + "-arrowScrollRight"; sIconName = "slim-arrow-right"; sArrowClass = "anchorBarArrowRight"; } oScrollButton = new Button(sArrowId, { icon: IconPool.getIconURI(sIconName), type: "Transparent", press: function (oEvent) { oEvent.preventDefault(); that._handleScrollButtonTap(bLeft); } }); oScrollButton.addEventDelegate({ onAfterRendering: function () { if (sap.ui.getCore().getConfiguration().getTheme() != "sap_hcb") { this.$().attr("tabindex", -1); } }, onThemeChanged: function () { if (sap.ui.getCore().getConfiguration().getTheme() == "sap_hcb") { this.$().removeAttr("tabindex"); } else { this.$().attr("tabindex", -1); } } }, oScrollButton); return new HorizontalLayout({ content: [oScrollButton] }).addStyleClass("anchorBarArrow").addStyleClass(sArrowClass); }; /** * Overwritten getter for aggregation "_scrollArrowLeft". * Implements lazy loading mechanism. * * @return {sap.ui.layout.HorizontalLayout} reference to the left scroll arrow instance * @private */ AnchorBar.prototype._getScrollArrowLeft = function () { var oScrollArrowLeft = this.getAggregation("_scrollArrowLeft"); if (oScrollArrowLeft) { return oScrollArrowLeft; } else { oScrollArrowLeft = this._createScrollArrow(true); this.setAggregation("_scrollArrowLeft", oScrollArrowLeft); return oScrollArrowLeft; } }; /** * Overwritten getter for aggregation "_scrollArrowRight". * Implements lazy loading mechanism. * * @return {sap.ui.layout.HorizontalLayout} reference to the right scroll arrow instance * @private */ AnchorBar.prototype._getScrollArrowRight = function () { var oScrollArrowRight = this.getAggregation("_scrollArrowRight"); if (oScrollArrowRight) { return oScrollArrowRight; } else { oScrollArrowRight = this._createScrollArrow(false); this.setAggregation("_scrollArrowRight", oScrollArrowRight); return oScrollArrowRight; } }; /******************************************************************************* * Horizontal scrolling ******************************************************************************/ AnchorBar._hierarchicalSelectModes = { "Icon": "icon", // Only icon - overview button mode "Text": "text" // Text - phone mode }; AnchorBar.prototype._applyHierarchicalSelectMode = function () { if (this._sHierarchicalSelectMode === AnchorBar._hierarchicalSelectModes.Icon) { this.$().find(".sapUxAPAnchorBarScrollContainer").show(); this._oSelect.setWidth("auto"); this._oSelect.setAutoAdjustWidth(true); this._oSelect.setType(sap.m.SelectType.IconOnly); this._computeBarSectionsInfo(); } else { this.$().find(".sapUxAPAnchorBarScrollContainer").hide(); this._oSelect.setWidth("100%"); this._oSelect.setAutoAdjustWidth(false); this._oSelect.setType(sap.m.SelectType.Default); } this.$().toggleClass("sapUxAPAnchorBarOverflow", this._sHierarchicalSelectMode === AnchorBar._hierarchicalSelectModes.Icon); }; AnchorBar.prototype._adjustSize = function () { //size changed => check if switch in display-mode (phone-view vs. desktop-view) needed var sNewMode = library.Utilities.isPhoneScenario() ? AnchorBar._hierarchicalSelectModes.Text : AnchorBar._hierarchicalSelectModes.Icon; if (sNewMode !== this._sHierarchicalSelectMode) { this._sHierarchicalSelectMode = sNewMode; this._applyHierarchicalSelectMode(); } //size changed => check if overflow gradients needed if (this._sHierarchicalSelectMode === AnchorBar._hierarchicalSelectModes.Icon) { //don't go any further if the positions of the items are not calculated yet if (this._iMaxPosition < 0) { return; } var $dom = this.$(), $scrollContainer = $dom.find(".sapUxAPAnchorBarScrollContainer"), bNeedScrollingBegin, bNeedScrollingEnd, iContainerWidth; iContainerWidth = $scrollContainer.width(); //do we need to scroll left or right if (this._bRtlScenario) { if (Device.browser.firefox) { bNeedScrollingEnd = Math.abs($scrollContainer.scrollLeft()) + iContainerWidth < (this._iMaxPosition - this._iTolerance); bNeedScrollingBegin = Math.abs($scrollContainer.scrollLeft()) >= this._iTolerance; } else { bNeedScrollingEnd = Math.abs($scrollContainer.scrollLeft()) >= this._iTolerance; bNeedScrollingBegin = Math.abs($scrollContainer.scrollLeft()) + iContainerWidth < (this._iMaxPosition - this._iTolerance); } } else { bNeedScrollingEnd = $scrollContainer.scrollLeft() + iContainerWidth < (this._iMaxPosition - this._iTolerance); bNeedScrollingBegin = $scrollContainer.scrollLeft() >= this._iTolerance; } jQuery.sap.log.debug("AnchorBar :: scrolled at " + $scrollContainer.scrollLeft(), "scrollBegin [" + (bNeedScrollingBegin ? "true" : "false") + "] scrollEnd [" + (bNeedScrollingEnd ? "true" : "false") + "]"); $dom.toggleClass("sapUxAPAnchorBarScrollLeft", bNeedScrollingBegin); $dom.toggleClass("sapUxAPAnchorBarScrollRight", bNeedScrollingEnd); } }; /** * Handles scrolling via the scroll buttons. * * @param boolean bScrollLeft indicates whether the left arrow button was pressed * @private */ AnchorBar.prototype._handleScrollButtonTap = function (bScrollLeft) { /* calculate the direction where to scroll increase if: - ltr and right arrow was pressed - rtl and the left arrow was pressed decrease if: - ltr and the left arrow was pressed - rtl and the right arrow was pressed */ var iScrollDirection = ((!this._bRtlScenario && bScrollLeft) || (this._bRtlScenario && !bScrollLeft)) ? -1 : 1; this._oScroller.scrollTo(this._iMaxPosition * iScrollDirection, 0, AnchorBar.SCROLL_DURATION * 3); //increase scroll duration when scrolling to the other end of the anchorBar (UX requirement) }; /** * Scroll to a specific Section. * * @param {string} sId The Section ID to scroll to * @param {int} duration Scroll duration (in ms). Default value is 0 * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ AnchorBar.prototype.scrollToSection = function (sId, duration) { if (this._bHasButtonsBar) { var iDuration = duration || AnchorBar.SCROLL_DURATION, iScrollTo; if ((this._sHierarchicalSelectMode === AnchorBar._hierarchicalSelectModes.Icon) && this._oSectionInfo[sId]) { if (this._bRtlScenario && Device.browser.firefox) { // in firefox RTL mode we are working with negative numbers and we have to add the offset in order not to hide the selected item iScrollTo = this._oSectionInfo[sId].scrollLeft + this._iOffset; } else { //scroll to the positionRtl minus the offset (so the gradient never hide the selected item) iScrollTo = this._oSectionInfo[sId].scrollLeft - this._iOffset; if (iScrollTo < 0) { //do not allow hiding part of the content if negative value for scroll is calculated here iScrollTo = 0; } } jQuery.sap.log.debug("AnchorBar :: scrolling to section " + sId + " of " + iScrollTo); //avoid triggering twice the scrolling onto the same target section if (this._sCurrentScrollId != sId) { this._sCurrentScrollId = sId; if (this._iCurrentScrollTimeout) { jQuery.sap.clearDelayedCall(this._iCurrentScrollTimeout); jQuery.sap.byId(this.getId() + "-scroll").parent().stop(true, false); } this._iCurrentScrollTimeout = jQuery.sap.delayedCall(duration, this, function () { this._sCurrentScrollId = undefined; this._iCurrentScrollTimeout = undefined; }); this._oScroller.scrollTo(iScrollTo, 0, iDuration); } } else { jQuery.sap.log.debug("AnchorBar :: no need to scroll to " + sId); } } }; // use type 'object' because Metamodel doesn't know ScrollEnablement /** * Returns a sap.ui.core.delegate.ScrollEnablement object used to handle scrolling. * * @type object * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ AnchorBar.prototype.getScrollDelegate = function () { return this._oScroller; }; /******************************************************************************* * Keyboard navigation ******************************************************************************/ AnchorBar.PAGEUP_AND_PAGEDOWN_JUMP_SIZE = 5; /** * Handles DOWN key, triggered on anchor bar level. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype.onsapdown = function (oEvent) { oEvent.preventDefault(); if (oEvent.target.nextSibling) { oEvent.target.nextSibling.focus(); } }; /** * Handles RIGHT key, triggered on anchor bar level. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype.onsapright = function (oEvent) { this.onsapdown(oEvent); }; /** * Handles UP key, triggered on anchor bar level. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype.onsapup = function (oEvent) { oEvent.preventDefault(); if (oEvent.target.previousSibling) { oEvent.target.previousSibling.focus(); } }; /** * Handles LEFT key, triggered on anchor bar level. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype.onsapleft = function (oEvent) { this.onsapup(oEvent); }; /** * Handles HOME key, triggered on anchor bar level. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype.onsaphome = function (oEvent) { oEvent.preventDefault(); if (oEvent.target.parentElement.firstChild) { oEvent.target.parentElement.firstChild.focus(); } }; /** * Handles END key, triggered on anchor bar level. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype.onsapend = function (oEvent) { oEvent.preventDefault(); if (oEvent.target.parentElement.lastChild) { oEvent.target.parentElement.lastChild.focus(); } }; /** * Handles PAGE UP key, triggered on anchor bar level. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype.onsappageup = function (oEvent) { this._handlePageUp(oEvent); }; /** * Handles PAGE DOWN key, triggered on anchor bar level. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype.onsappagedown = function (oEvent) { this._handlePageDown(oEvent); }; /** * Handler for sappageup event. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype._handlePageUp = function (oEvent) { oEvent.preventDefault(); var iNextIndex; var aAnchors = this.getContent(); aAnchors.forEach(function (oAnchor, iAnchorIndex) { if (oAnchor.getId() === oEvent.target.id) { iNextIndex = iAnchorIndex - (AnchorBar.PAGEUP_AND_PAGEDOWN_JUMP_SIZE + 1); return; } }); if (iNextIndex && aAnchors[iNextIndex]) { aAnchors[iNextIndex].focus(); } else if (aAnchors[0]) { aAnchors[0].focus(); } }; /** * Handler for sappagedown event. * * @param {jQuery.Event} oEvent * @private */ AnchorBar.prototype._handlePageDown = function (oEvent) { oEvent.preventDefault(); var iNextIndex; var aAnchors = this.getContent(); aAnchors.forEach(function (oAnchor, iAnchorIndex) { if (oAnchor.getId() === oEvent.target.id) { iNextIndex = iAnchorIndex + AnchorBar.PAGEUP_AND_PAGEDOWN_JUMP_SIZE + 1; return; } }); if (iNextIndex && aAnchors[iNextIndex]) { aAnchors[iNextIndex].focus(); } else if (aAnchors[aAnchors.length - 1]) { aAnchors[aAnchors.length - 1].focus(); } }; /** * handle tab focusing */ AnchorBar.prototype._setAnchorButtonsTabFocusValues = function (oSelectedButton) { var aAnchorBarContent = this.getContent() || [], $anchorBarItem, sFocusable = '0', sNotFocusable = '-1', sTabIndex = "tabIndex"; aAnchorBarContent.forEach(function (oAnchorBarItem) { $anchorBarItem = oAnchorBarItem.$(); if (oAnchorBarItem.sId === oSelectedButton.sId) { $anchorBarItem.attr(sTabIndex, sFocusable); } else { $anchorBarItem.attr(sTabIndex, sNotFocusable); } }); }; /** * Handler for F6 * * @param oEvent - The event object */ AnchorBar.prototype.onsapskipforward = function (oEvent) { this._handleGroupNavigation(oEvent, false); }; /** * Handler for F6 and Shift + F6 group navigation * * @param oEvent {jQuery.EventObject} * @param bShiftKey serving as a reference if shift is used * @private */ AnchorBar.prototype._handleGroupNavigation = function (oEvent, bShiftKey) { var oEventF6 = jQuery.Event("keydown"), oSettings = {}, aSections = this.getParent().getSections(), aSubSections = [this.getDomRef()], aCurruntSubSections; //this is needed in order to be sure that next F6 group will be found in sub sections aSections.forEach(function (oSection) { aCurruntSubSections = oSection.getSubSections().map(function (oSubSection) { return oSubSection.$().attr("tabindex", -1)[0]; }); aSubSections = aSubSections.concat(aCurruntSubSections); }); oSettings.scope = aSubSections; oEvent.preventDefault(); this.$().focus(); oEventF6.target = oEvent.target; oEventF6.keyCode = jQuery.sap.KeyCodes.F6; oEventF6.shiftKey = bShiftKey; jQuery.sap.handleF6GroupNavigation(oEventF6, oSettings); }; /** * called for figuring out responsive scenarios */ AnchorBar.prototype.onAfterRendering = function () { if (Toolbar.prototype.onAfterRendering) { Toolbar.prototype.onAfterRendering.call(this); } this._sHierarchicalSelectMode = AnchorBar._hierarchicalSelectModes.Text; //save max for arrow show/hide management, the max position is the required scroll for the the item to be fully visible this._iMaxPosition = -1; //show/hide scrolling arrows this._sResizeListenerId = ResizeHandler.register(this, jQuery.proxy(this._adjustSize, this)); this.$().find(".sapUxAPAnchorBarScrollContainer").scroll(jQuery.proxy(this._onScroll, this)); //restore state from previous rendering if (this.getSelectedButton()) { this.setSelectedButton(this.getSelectedButton()); } //initial state if (this._bHasButtonsBar) { jQuery.sap.delayedCall(AnchorBar.DOM_CALC_DELAY, this, function () { this._adjustSize(); }); } }; AnchorBar.prototype._onScroll = function () { if (!this._iCurrentSizeCheckTimeout) { this._iCurrentSizeCheckTimeout = jQuery.sap.delayedCall(AnchorBar.SCROLL_DURATION, this, function () { this._iCurrentSizeCheckTimeout = undefined; this._adjustSize(); }); } }; AnchorBar.prototype._computeBarSectionsInfo = function () { //reset the max position this._iMaxPosition = 0; var aContent = this.getContent() || []; aContent.forEach(this._computeNextSectionInfo, this); //post processing based on how browsers implement rtl //chrome, safari && Device.browser.webkit && firefox if (this._bRtlScenario && (Device.browser.webkit || Device.browser.firefox)) { aContent.forEach(this._adjustNextSectionInfo, this); // adjust positions depending of the browser this._oScroller.scrollTo(this._iMaxPosition, 0, 0); } }; AnchorBar.prototype._computeNextSectionInfo = function (oContent) { // set ARIA has-popup if button opens submenu if (oContent.data("bHasSubMenu")) { oContent.$().attr("aria-haspopup", "true"); } // set ARIA attributes of main buttons oContent.$().attr("aria-controls", oContent.data("sectionId")); var iWidth = oContent.$().outerWidth(true); //store info on the various sections for horizontalScrolling //scrollLeft is the amount of scroll required for reaching that item in normal mode this._oSectionInfo[oContent.data("sectionId")] = { scrollLeft: this._iMaxPosition, width: iWidth }; this._iMaxPosition += iWidth; }; /** * Adjustment for webkit only * * Reverse the position as the scroll 0 is at the far end (first item = maxPosition, last item = 0) */ AnchorBar.prototype._adjustNextSectionInfo = function (oContent) { var oSectionInfo = this._oSectionInfo[oContent.data("sectionId")]; if (Device.browser.firefox) { // 27.11.2015 fix made for the following issue // firefox not working yet see internal incident 1570001701 oSectionInfo.scrollLeft = -oSectionInfo.scrollLeft; } else { // Reverse all positions as the scroll 0 is at the far end (first item = maxPosition, last item = 0) oSectionInfo.scrollLeft = this._iMaxPosition - oSectionInfo.scrollLeft - oSectionInfo.width; } }; /** * clean created controls and deregister handlers */ AnchorBar.prototype.exit = function () { if (this._sResizeListenerId) { ResizeHandler.deregister(this._sResizeListenerId); this._sResizeListenerId = null; } if (this._oScroller) { this._oScroller.destroy(); this._oScroller = null; } }; return AnchorBar; }); }; // end of sap/uxap/AnchorBar.js if ( !jQuery.sap.isDeclared('sap.uxap.AnchorBarRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.AnchorBarRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.m.ToolbarRenderer'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Renderer'); // unlisted dependency retained jQuery.sap.require('sap.m.BarInPageEnabler'); // unlisted dependency retained sap.ui.define("sap/uxap/AnchorBarRenderer",["sap/m/ToolbarRenderer", "sap/ui/core/Renderer", "sap/m/BarInPageEnabler", "./AnchorBar", "./library"], function (ToolbarRenderer, Renderer, BarInPageEnabler, AnchorBar, library) { "use strict"; /** * @class ObjectPageRenderer renderer. * @static */ var AnchorBarRenderer = Renderer.extend(ToolbarRenderer); AnchorBarRenderer.renderBarContent = function (rm, oToolbar) { if (oToolbar._bHasButtonsBar) { rm.renderControl(oToolbar._getScrollArrowLeft()); rm.write("<div"); rm.writeAttributeEscaped("id", oToolbar.getId() + "-scrollContainer"); // ARIA attributes rm.writeAttributeEscaped("aria-label", library.i18nModel.getResourceBundle().getText("ANCHOR_BAR_LABEL")); // rm.addClass("sapUxAPAnchorBarScrollContainer"); rm.writeClasses(); rm.write(">"); rm.write("<div"); rm.writeAttributeEscaped("id", oToolbar.getId() + "-scroll"); rm.write(">"); AnchorBarRenderer.renderBarItems(rm, oToolbar); rm.write("</div>"); rm.write("</div>"); rm.renderControl(oToolbar._getScrollArrowRight()); } BarInPageEnabler.addChildClassTo(oToolbar._oSelect, oToolbar); rm.renderControl(oToolbar._oSelect); }; AnchorBarRenderer.renderBarItems = function (rm, oToolbar) { var sSelectedItemId = oToolbar.getSelectedButton(); oToolbar.getContent().forEach(function(oControl) { BarInPageEnabler.addChildClassTo(oControl, oToolbar); if (oControl.getId() === sSelectedItemId) { oControl.addStyleClass("sapUxAPAnchorBarButtonSelected"); } rm.renderControl(oControl); }); }; AnchorBarRenderer.decorateRootElement = function (rm, oToolbar) { ToolbarRenderer.decorateRootElement.apply(this, arguments); if (oToolbar._sHierarchicalSelectMode === AnchorBar._hierarchicalSelectModes.Icon) { rm.addClass("sapUxAPAnchorBarOverflow"); } }; return AnchorBarRenderer; }, /* bExport= */ true); }; // end of sap/uxap/AnchorBarRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.BlockBase') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.BlockBase. jQuery.sap.declare('sap.uxap.BlockBase'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.CustomData'); // unlisted dependency retained jQuery.sap.require('sap.ui.model.Context'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained jQuery.sap.require('sap.ui.layout.form.ResponsiveGridLayout'); // unlisted dependency retained sap.ui.define("sap/uxap/BlockBase",[ "sap/ui/core/Control", "sap/ui/core/CustomData", "./BlockBaseMetadata", "./ModelMapping", "sap/ui/model/Context", "sap/ui/Device", "sap/ui/layout/form/ResponsiveGridLayout", "./library" ], function (Control, CustomData, BlockBaseMetadata, ModelMapping, Context, Device, ResponsiveGridLayout, library) { "use strict"; /** * Constructor for a new BlockBase. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * * A block is the main element that will be displayed, mainly in an object page, but not necessarily * only there. * * A block is a control that use a XML view for storing its internal control tree. * A block is a control that has modes and a view associated to each modes. * At rendering time, the view associated to the mode is rendered. * * <b>Note:</b> The control supports only XML views. * * As any UI5 views, the XML view can have a controller which automatically comes a this.oParentBlock attribute (so that the controller can interacts with the block). * If the controller implements the onParentBlockModeChange method, this method will get called with the sMode parameter when the view is used or re-used by the block. * * @extends sap.ui.core.Control * @author SAP SE * @constructor * @public * @since 1.26 * @alias sap.uxap.BlockBase * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var BlockBase = Control.extend("sap.uxap.BlockBase", { metadata: { library: "sap.uxap", properties: { /** * Determines the mode of the block. * When block is used inside ObjectPage this mode is inherited my the SubSection. * The mode of the block is changed when SubSection mode changes. */ "mode": {type: "string", group: "Appearance"}, /** * Determines the visibility of the block. */ "visible": {type: "boolean", group: "Appearance", defaultValue: true}, /** * Determines on how columns the layout will be rendered. * Allowed values are integers from 1 to 4 and "auto". */ "columnLayout": {type: "sap.uxap.BlockBaseColumnLayout", group: "Behavior", defaultValue: "auto"}, /** * Determines if the block should automatically adjust its inner forms. * Allowed values are "BlockColumns" and "OneColumn" and "None". * If the value is "BlockColumns", then the inner form will have as many columns as the colspan of its parent block. * If the value is "OneColumn", the inner form will have exactly one column, regardless the colspan of its parent block. * If the value is "None", no automatic adjustment of inner forms will be made and the form will keep its original column count. */ "formAdjustment": { type: "sap.uxap.BlockBaseFormAdjustment", group: "Behavior", defaultValue: sap.uxap.BlockBaseFormAdjustment.BlockColumns }, /** * Determines whether the show more button should be shown. */ "showSubSectionMore": {type: "boolean", group: "Behavior", defaultValue: false} }, defaultAggregation: "mappings", aggregations: { /** * Map external UI5 model and internal Block model */ "mappings": {type: "sap.uxap.ModelMapping", multiple: true, singularName: "mapping"}, /** * Internal aggregation that contains all views inside this Block */ "_views": {type: "sap.ui.core.Control", multiple: true, singularName: "view", visibility: "hidden"} }, associations: { /** * The view that is rendered now. * Can be used as getter for the rendered view. */ "selectedView": {type: "sap.ui.core.Control", multiple: false} }, views: { // define your views here following the pattern: // "yourModeName": {viewName: "your.view.path" , type: "yourUI5ViewType" } // for example: // "Collapsed": { // viewName: "sap.uxap.testblocks.multiview.MultiViewBlockCollapsed", // type: "XML" // }, // "Expanded": { // viewName: "sap.uxap.testblocks.multiview.MultiViewBlockExpanded", // type: "XML" // } // // if no views are provided, the blockBase looks for an xml view which name is equal to the block's one // } }, renderer: "sap.uxap.BlockBaseRenderer" }, BlockBaseMetadata); BlockBase.prototype.init = function () { //convenience mechanism: //if there are no views defined by the Block, // we look for the default one which would have the same name as the block and type XML if (!this.getMetadata().hasViews()) { this.getMetadata().setView("defaultXML", {viewName: this.getMetadata().getName(), type: "XML"}); } //for performance optimization this._oMappingApplied = {}; //lazy loading this._bLazyLoading = false; //by default, no lazy loading so we can use it out of an objectPageLayout this._bConnected = false; //indicates connectToModels function has been called this._oUpdatedModels = {}; }; BlockBase.prototype.onBeforeRendering = function () { this._applyMapping(); if (!this.getMode() || this.getMode() === "") { if (this.getMetadata().getView("defaultXML")) { this.setMode("defaultXML"); } else { jQuery.sap.log.error("BlockBase ::: there is no mode defined for rendering " + this.getMetadata().getName() + ". You can either set a default mode on the block metadata or set the mode property before rendering the block."); } } this._applyFormAdjustment(); //TODO: for iconTabBar mode, specify lazyLoading for selectedTab only? this._bLazyLoading = this._getObjectPageLayout() && (this._getObjectPageLayout().getEnableLazyLoading() || this._getObjectPageLayout().getUseIconTabBar()); }; BlockBase.prototype.onAfterRendering = function () { if (this._getObjectPageLayout()) { this._getObjectPageLayout()._adjustLayout(); } }; /** * Set the parent control for the current block. * Every time the parent changes, we try to find the parent objectPageLayout in order to determine the lazy loading strategy to apply. * @param {*} oParent parent instance * @param {*} sAggregationName aggregation name * @param {*} bSuppressInvalidate invalidate */ BlockBase.prototype.setParent = function (oParent, sAggregationName, bSuppressInvalidate) { Control.prototype.setParent.call(this, oParent, sAggregationName, bSuppressInvalidate); if (oParent instanceof library.ObjectPageSubSection) { this._bLazyLoading = true; //we activate the block lazy loading since we are within an objectPageLayout this._oParentObjectPageSubSection = oParent; } }; /********************************************* * model mapping management * *******************************************/ /** * Intercept direct setModel calls. * @param {*} oModel model instance * @param {*} sName name of the model * @returns {sap.ui.base.ManagedObject} instance of managed object */ BlockBase.prototype.setModel = function (oModel, sName) { this._applyMapping(sName); return Control.prototype.setModel.call(this, oModel, sName); }; /** * Called for applying the modelmapping once all properties are set. * @private */ BlockBase.prototype._applyMapping = function () { if (this._bLazyLoading && !this._bConnected) { jQuery.sap.log.debug("BlockBase ::: Ignoring the _applyMapping as the block is not connected"); } else { this.getMappings().forEach(function (oMapping, iIndex) { var oModel, sInternalModelName = oMapping.getInternalModelName(), sExternalPath = oMapping.getExternalPath(), sExternalModelName = oMapping.getExternalModelName(), sPath; if (sExternalPath) { if (sInternalModelName == "" || sExternalPath == "") { throw new Error("BlockBase :: incorrect mapping, one of the modelMapping property is empty"); } if (!this._isMappingApplied(sInternalModelName) /* check if mapping is set already */ || (this.getModel(sInternalModelName) != this.getModel(sExternalModelName)) /* model changed, then we have to update internal model mapping */) { jQuery.sap.log.info("BlockBase :: mapping external model " + sExternalModelName + " to " + sInternalModelName); oModel = this.getModel(sExternalModelName); if (oModel) { sPath = oModel.resolve(sExternalPath, this.getBindingContext(sExternalModelName)); this._oMappingApplied[sInternalModelName] = true; Control.prototype.setModel.call(this, oModel, sInternalModelName); this.setBindingContext(new Context(oModel, sPath), sInternalModelName); } } } }, this); } }; BlockBase.prototype._isMappingApplied = function (sInternalModelName) { return this.getModel(sInternalModelName) && this._oMappingApplied[sInternalModelName]; }; /** * Intercept propagated properties. * @param {*} vName property instance or property name * @returns {*} propagateProperties function result */ BlockBase.prototype.propagateProperties = function (vName) { if (this._bLazyLoading && !this._bConnected && !this._oUpdatedModels.hasOwnProperty(vName)) { this._oUpdatedModels[vName] = true; } else { this._applyMapping(vName); } return Control.prototype.propagateProperties.call(this, vName); }; /********************************************* * mode vs views management * *******************************************/ /** * Returns an object containing the supported modes for the block. * @returns {sap.ui.core/object} supported modes */ BlockBase.prototype.getSupportedModes = function () { var oSupportedModes = jQuery.extend({}, this.getMetadata().getViews()); for (var key in oSupportedModes) { oSupportedModes[key] = key; //this is what developers expect, for ex: {Collapsed:"Collapsed"} } return oSupportedModes; }; /** * Set the view mode for this particular block. * @public * @param {string} sMode the mode to apply to the control (that should be synchronized with view declared) * @returns {*} this */ BlockBase.prototype.setMode = function (sMode) { sMode = this._validateMode(sMode); if (this.getMode() !== sMode) { this.setProperty("mode", sMode, false); //if Lazy loading is enabled, and if the block is not connected //delay the view creation (will be done in connectToModels function) if (!this._bLazyLoading || this._bConnected) { this._initView(sMode); } } return this; }; /** * Set the column layout for this particular block. * @param {string} sLayout The column layout to apply to the control * @public */ BlockBase.prototype.setColumnLayout = function (sLayout) { if (this._oParentObjectPageSubSection) { this._oParentObjectPageSubSection.invalidate(); /*the parent subsection needs to recalculate block layout data based on the changed block column layout */ } this.setProperty("columnLayout", sLayout); }; /** * Provide a clone mechanism: the selectedView needs to point to one of the _views. * @returns {sap.ui.core.Element} cloned element */ BlockBase.prototype.clone = function () { var iAssocIndex = -1, sAssoc = this.getAssociation("selectedView"), aViews = this.getAggregation("_views") || []; //find the n-view associated if (sAssoc) { aViews.forEach(function (oView, iIndex) { if (oView.getId() === sAssoc) { iAssocIndex = iIndex; } return iAssocIndex < 0; }); } var oNewThis = Control.prototype.clone.call(this); //we need to maintain the association onto the new object if (iAssocIndex >= 0) { oNewThis.setAssociation("selectedView", oNewThis.getAggregation("_views")[iAssocIndex]); } return oNewThis; }; /** * Validate that the provided mode has been declared in the metadata views section, throw an exception otherwise. * @param {*} sMode mode * @returns {*} sMode * @private */ BlockBase.prototype._validateMode = function (sMode) { this.validateProperty("mode", sMode); //type expected as per properties definition if (!this.getMetadata().getView(sMode)) { var sBlockName = this.getMetadata()._sClassName || this.getId(); //the view wasn't defined. //as a fallback mechanism: we look for the defaultXML one and raise an error before raising an exception if (this.getMetadata().getView("defaultXML")) { jQuery.sap.log.warning("BlockBase :: no view defined for block " + sBlockName + " for mode " + sMode + ", loading defaultXML instead"); sMode = "defaultXML"; } else { throw new Error("BlockBase :: no view defined for block " + sBlockName + " for mode " + sMode); } } return sMode; }; /** * Get the view associated with the selectedView. * @returns {*} Selected view * @private */ BlockBase.prototype._getSelectedViewContent = function () { var oView = null, sSelectedViewId, aViews; sSelectedViewId = this.getAssociation("selectedView"); aViews = this.getAggregation("_views"); if (aViews) { for (var i = 0; !oView && i < aViews.length; i++) { if (aViews[i].getId() === sSelectedViewId) { oView = aViews[i]; } } } return oView; }; /*** * Create view * @param {*} mParameter parameter * @returns {sap.ui.core.mvc.View} view * @protected */ BlockBase.prototype.createView = function (mParameter) { return sap.ui.xmlview(mParameter); }; /** * Initialize a view and returns it if it has not been defined already. * @param {*} sMode the valid mode corresponding to the view to initialize * @returns {sap.ui.view} view * @private */ BlockBase.prototype._initView = function (sMode) { var oView, aViews = this.getAggregation("_views") || [], mParameter = this.getMetadata().getView(sMode); //look for the views if it was already instantiated aViews.forEach(function (oCurrentView, iIndex) { if (oCurrentView.data("layoutMode") === sMode) { oView = oCurrentView; } }); //the view is not instantiated yet, handle a new view scenario if (!oView) { oView = this._initNewView(sMode); } this.setAssociation("selectedView", oView, true); //try to notify the associated controller that the view is being used for this mode if (oView.getController() && oView.getController().onParentBlockModeChange) { oView.getController().onParentBlockModeChange(sMode); } else { jQuery.sap.log.info("BlockBase ::: could not notify " + mParameter.viewName + " of loading in mode " + sMode + ": missing controller onParentBlockModeChange method"); } return oView; }; /** * Initialize new BlockBase view * @param {*} sMode the valid mode corresponding to the view to initialize * @returns {sap.ui.view} view * @private */ BlockBase.prototype._initNewView = function (sMode) { var oView = this._getSelectedViewContent(), mParameter = this.getMetadata().getView(sMode); //check if the new view is not the current one (we may want to have the same view for several modes) if (!oView || mParameter.viewName != oView.getViewName()) { oView = this.createView(mParameter); //link to the controller defined in the Block if (oView) { //inject a reference to this if (oView.getController()) { oView.getController().oParentBlock = this; } oView.addCustomData(new CustomData({ "key": "layoutMode", "value": sMode })); this.addAggregation("_views", oView, true); } else { throw new Error("BlockBase :: no view defined in metadata.views for mode " + sMode); } } return oView; }; // This offset is needed so the breakpoints of the simpleForm match those of the GridLayout (offset = left-padding of grid + margins of grid-cells [that create the horizontal spacing between the cells]) BlockBase.FORM_ADUSTMENT_OFFSET = 32; BlockBase._FORM_ADJUSTMENT_CONST = { breakpoints: { XL: Device.media._predefinedRangeSets.StdExt.points[2] - BlockBase.FORM_ADUSTMENT_OFFSET, L: Device.media._predefinedRangeSets.StdExt.points[1] - BlockBase.FORM_ADUSTMENT_OFFSET, M: Device.media._predefinedRangeSets.StdExt.points[0] - BlockBase.FORM_ADUSTMENT_OFFSET }, labelSpan: { /* values specified by design requirement */ XL: 12, L: 12, M: 12, S: 12 }, emptySpan: { /* values specified by design requirement */ XL: 0, L: 0, M: 0, S: 0 }, columns: { XL: 1, L: 1, M: 1 } }; BlockBase._PARENT_GRID_SIZE = 12; BlockBase.prototype._computeFormAdjustmentFields = function (oView, oLayoutData, sFormAdjustment, oParentColumns) { if (oView && oLayoutData && sFormAdjustment && oParentColumns) { var oColumns = this._computeFormColumns(oLayoutData, sFormAdjustment, oParentColumns), oBreakpoints = this._computeFormBreakpoints(oLayoutData, sFormAdjustment); return jQuery.extend({}, BlockBase._FORM_ADJUSTMENT_CONST, {columns: oColumns}, {breakpoints: oBreakpoints}); } }; BlockBase.prototype._computeFormColumns = function (oLayoutData, sFormAdjustment, oParentColumns) { var oColumns = jQuery.extend({}, BlockBase._FORM_ADJUSTMENT_CONST.columns); if (sFormAdjustment === sap.uxap.BlockBaseFormAdjustment.BlockColumns) { var iColumnSpanXL = BlockBase._PARENT_GRID_SIZE / oParentColumns.XL, iColumnSpanL = BlockBase._PARENT_GRID_SIZE / oParentColumns.L, iColumnSpanM = BlockBase._PARENT_GRID_SIZE / oParentColumns.M; oColumns.XL = oLayoutData.getSpanXL() / iColumnSpanXL; oColumns.L = oLayoutData.getSpanL() / iColumnSpanL; oColumns.M = oLayoutData.getSpanM() / iColumnSpanM; } return oColumns; }; BlockBase.prototype._computeFormBreakpoints = function (oLayoutData, sFormAdjustment) { var oBreakpoints = jQuery.extend({}, BlockBase._FORM_ADJUSTMENT_CONST.breakpoints); if (sFormAdjustment === sap.uxap.BlockBaseFormAdjustment.BlockColumns) { oBreakpoints.XL = Math.round(oBreakpoints.XL * oLayoutData.getSpanXL() / BlockBase._PARENT_GRID_SIZE); oBreakpoints.L = Math.round(oBreakpoints.L * oLayoutData.getSpanL() / BlockBase._PARENT_GRID_SIZE); oBreakpoints.M = Math.round(oBreakpoints.M * oLayoutData.getSpanM() / BlockBase._PARENT_GRID_SIZE); } return oBreakpoints; }; BlockBase.prototype._applyFormAdjustment = function () { var oLayoutData = this.getLayoutData(), sFormAdjustment = this.getFormAdjustment(), oView = this._getSelectedViewContent(), oParent = this._oParentObjectPageSubSection, oFormAdjustmentFields; if (sFormAdjustment && (sFormAdjustment !== sap.uxap.BlockBaseFormAdjustment.None) && oView && oLayoutData && oParent) { var oParentColumns = oParent._oLayoutConfig; oView.getContent().forEach(function (oItem) { if (oItem.getMetadata().getName() === "sap.ui.layout.form.SimpleForm") { oItem.setLayout(sap.ui.layout.form.SimpleFormLayout.ResponsiveGridLayout); if (!oFormAdjustmentFields) { oFormAdjustmentFields = this._computeFormAdjustmentFields(oView, oLayoutData, sFormAdjustment, oParentColumns); } this._applyFormAdjustmentFields(oFormAdjustmentFields, oItem); oItem.setWidth("100%"); } else if (oItem.getMetadata().getName() === "sap.ui.layout.form.Form") { var oLayout = oItem.getLayout(), oResponsiveGridLayout; if (oLayout && oLayout.getMetadata().getName() === "sap.ui.layout.form.ResponsiveGridLayout") { oResponsiveGridLayout = oLayout; // existing ResponsiveGridLayout must be reused, otherwise an error is thrown in the existing implementation } else { oResponsiveGridLayout = new ResponsiveGridLayout(); oItem.setLayout(oResponsiveGridLayout); } if (!oFormAdjustmentFields) { oFormAdjustmentFields = this._computeFormAdjustmentFields(oView, oLayoutData, sFormAdjustment, oParentColumns); } this._applyFormAdjustmentFields(oFormAdjustmentFields, oResponsiveGridLayout); oItem.setWidth("100%"); } }, this); } }; BlockBase.prototype._applyFormAdjustmentFields = function (oFormAdjustmentFields, oFormLayout) { oFormLayout.setColumnsXL(oFormAdjustmentFields.columns.XL); oFormLayout.setColumnsL(oFormAdjustmentFields.columns.L); oFormLayout.setColumnsM(oFormAdjustmentFields.columns.M); oFormLayout.setLabelSpanXL(oFormAdjustmentFields.labelSpan.XL); oFormLayout.setLabelSpanL(oFormAdjustmentFields.labelSpan.L); oFormLayout.setLabelSpanM(oFormAdjustmentFields.labelSpan.M); oFormLayout.setLabelSpanS(oFormAdjustmentFields.labelSpan.S); oFormLayout.setEmptySpanXL(oFormAdjustmentFields.emptySpan.XL); oFormLayout.setEmptySpanL(oFormAdjustmentFields.emptySpan.L); oFormLayout.setEmptySpanM(oFormAdjustmentFields.emptySpan.M); oFormLayout.setEmptySpanS(oFormAdjustmentFields.emptySpan.S); oFormLayout.setBreakpointXL(oFormAdjustmentFields.breakpoints.XL); oFormLayout.setBreakpointL(oFormAdjustmentFields.breakpoints.L); oFormLayout.setBreakpointM(oFormAdjustmentFields.breakpoints.M); }; /************************************************************************************* * objectPageLayout integration & lazy loading management ************************************************************************************/ /** * Getter for the parent object page layout. * @returns {*} OP layout * @private */ BlockBase.prototype._getObjectPageLayout = function () { if (!this._oParentObjectPageLayout) { this._oParentObjectPageLayout = library.Utilities.getClosestOPL(this); } return this._oParentObjectPageLayout; }; /** * Setter for the visibility of the block. * @public */ BlockBase.prototype.setVisible = function (bValue, bSuppressInvalidate) { this.setProperty("visible", bValue, bSuppressInvalidate); this._getObjectPageLayout() && this._getObjectPageLayout()._adjustLayoutAndUxRules(); return this; }; /** * Set the showSubSectionMore property. * Ask the parent ObjectPageSubSection to refresh its see more visibility state if present. * @param bValue * @param bInvalidate * @returns {*} */ BlockBase.prototype.setShowSubSectionMore = function (bValue, bInvalidate) { //suppress invalidate as ShowSubSectionMore has no impact on block itself. if (bValue != this.getShowSubSectionMore()) { this.setProperty("showSubSectionMore", bValue, true); //refresh the parent subsection see more visibility if we have changed it and we are within an objectPageSubSection if (this._oParentObjectPageSubSection) { this._oParentObjectPageSubSection.refreshSeeMoreVisibility(); } } return this; }; /** * Connect Block to the UI5 model tree. * Initialize view if lazy loading is enabled. * @returns {*} */ BlockBase.prototype.connectToModels = function () { if (!this._bConnected) { jQuery.sap.log.debug("BlockBase :: Connecting block to the UI5 model tree"); this._bConnected = true; if (this._bLazyLoading) { //if lazy loading is enabled, the view has not been created during the setMode //so create it now var sMode = this.getMode(); sMode && this._initView(sMode); } this.invalidate(); } }; /** * Override of the default model lifecycle method to disable the automatic binding resolution for lazyloading. * @override * @param bSkipLocal * @param bSkipChildren * @param sModelName * @param bUpdateAll * @returns {*} */ BlockBase.prototype.updateBindingContext = function (bSkipLocal, bSkipChildren, sModelName, bUpdateAll) { if (!this._bLazyLoading || this._bConnected) { return Control.prototype.updateBindingContext.call(this, bSkipLocal, bSkipChildren, sModelName, bUpdateAll); } else { jQuery.sap.log.debug("BlockBase ::: Ignoring the updateBindingContext as the block is not visible for now in the ObjectPageLayout"); } }; /** * Override of the default model lifecycle method to disable the automatic binding resolution for lazyloading. * @override * @param bUpdateAll * @param sModelName * @returns {*} */ BlockBase.prototype.updateBindings = function (bUpdateAll, sModelName) { if (!this._bLazyLoading || this._bConnected) { return Control.prototype.updateBindings.call(this, bUpdateAll, sModelName); } else { jQuery.sap.log.debug("BlockBase ::: Ignoring the updateBindingContext as the block is not visible for now in the ObjectPageLayout"); } }; return BlockBase; }); }; // end of sap/uxap/BlockBase.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageHeader') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ObjectPageHeader. jQuery.sap.declare('sap.uxap.ObjectPageHeader'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.IconPool'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.CustomData'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained jQuery.sap.require('sap.m.Breadcrumbs'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.ResizeHandler'); // unlisted dependency retained jQuery.sap.require('sap.m.Text'); // unlisted dependency retained jQuery.sap.require('sap.m.Button'); // unlisted dependency retained jQuery.sap.require('sap.m.ActionSheet'); // unlisted dependency retained jQuery.sap.require('sap.m.Image'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Icon'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageHeader",[ "sap/ui/core/Control", "sap/ui/core/IconPool", "sap/ui/core/CustomData", "sap/ui/Device", "sap/m/Breadcrumbs", "./ObjectPageHeaderActionButton", "sap/ui/core/ResizeHandler", "sap/m/Text", "sap/m/Button", "sap/m/ActionSheet", "sap/m/Image", "sap/ui/core/Icon", "./library" ], function (Control, IconPool, CustomData, Device, Breadcrumbs, ObjectPageHeaderActionButton, ResizeHandler, Text, Button, ActionSheet, Image, Icon, library) { "use strict"; /** * Constructor for a new ObjectPageHeader. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * ObjectPageHeader represents the static part of an Object page header. * Typically used to display the basic information about a business object, such as title/description/picture, as well as a list of common actions. * @extends sap.ui.core.Control * * @author SAP SE * * @constructor * @public * @alias sap.uxap.ObjectPageHeader * @since 1.26 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectPageHeader = Control.extend("sap.uxap.ObjectPageHeader", /** @lends sap.uxap.ObjectPageHeader.prototype */ { metadata: { library: "sap.uxap", properties: { /** * The URL of the image, representing the business object */ objectImageURI: {type: "string", defaultValue: null}, /** * The text to be used for the Alt and Tooltip attribute of the image, supplied via the objectImageURI property */ objectImageAlt: {type: "string", defaultValue: ''}, /** * The value of densityAware for the image, supplied via the objectImageURI property. * See sap.m.Image for more details on densityAware. */ objectImageDensityAware: {type: "boolean", defaultValue: false}, /** * The title of the object */ objectTitle: {type: "string", defaultValue: null}, /** * The description of the object */ objectSubtitle: {type: "string", defaultValue: null}, /** * Determines whether the picture should be displayed in a square or with a circle-shaped mask. */ objectImageShape: { type: "sap.uxap.ObjectPageHeaderPictureShape", defaultValue: sap.uxap.ObjectPageHeaderPictureShape.Square }, /** * Determines whether the icon should always be visible or if it should be visible only when scrolling. */ isObjectIconAlwaysVisible: {type: "boolean", defaultValue: false}, /** * Determines whether the title should always be visible or if it should be visible only when scrolling. */ isObjectTitleAlwaysVisible: {type: "boolean", defaultValue: true}, /** * Determines whether the subtitle should always be visible or if it should be visible only when scrolling. */ isObjectSubtitleAlwaysVisible: {type: "boolean", defaultValue: true}, /** * Determines whether the action buttons should always be visible or if they should be visible only when scrolling. */ isActionAreaAlwaysVisible: {type: "boolean", defaultValue: true}, /** * Determines the design of the header - Light or Dark */ headerDesign: { type: "sap.uxap.ObjectPageHeaderDesign", defaultValue: sap.uxap.ObjectPageHeaderDesign.Light }, /** * When set to true, the selector arrow icon/image is shown and can be pressed. */ showTitleSelector: {type: "boolean", group: "Misc", defaultValue: false}, /** * Set the favorite state to true or false. The showMarkers property must be true for this property to take effect. */ markFavorite: {type: "boolean", group: "Misc", defaultValue: false}, /** * Set the flagged state to true or false. The showMarkers property must be true for this property to take effect. */ markFlagged: {type: "boolean", group: "Misc", defaultValue: false}, /** * Indicates if object page header title supports showing markers such as flagged and favorite. */ showMarkers: {type: "boolean", group: "Misc", defaultValue: false}, /** * Set the locked state of the objectPageHeader. */ markLocked: {type: "boolean", group: "Misc", defaultValue: false}, /** * Enables support of a placeholder image in case no image is specified or the URL of the provided image is invalid. */ showPlaceholder: {type: "boolean", group: "Misc", defaultValue: false}, /** * Marks that there are unsaved changes in the objectPageHeader. * The markChanges state cannot be used together with the markLocked state. * If both are set to true, only the locked state will be displayed. * @since 1.34.0 */ markChanges: {type: "boolean", group: "Misc", defaultValue: false} }, defaultAggregation: "actions", aggregations: { /** * * Internal aggregation for the BreadCrumbs in the header. */ _breadCrumbs: {type: "sap.m.Breadcrumbs", multiple: false, visibility: "hidden"}, /** * * A list of all the active link elements in the BreadCrumbs control. */ breadCrumbsLinks: {type: "sap.m.Link", multiple: true, singularName: "breadCrumbLink"}, /** * * Internal aggregation for the overflow button in the header. */ _overflowButton: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, /** * * Internal aggregation for the expand header button. */ _expandButton: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, /** * * Icon for the identifier line. */ _objectImage: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"}, _lockIconCont: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, _lockIcon: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, _titleArrowIconCont: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, _titleArrowIcon: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, _favIcon: {type: "sap.ui.core.Icon", multiple: false, visibility: "hidden"}, _flagIcon: {type: "sap.ui.core.Icon", multiple: false, visibility: "hidden"}, _overflowActionSheet: {type: "sap.m.ActionSheet", multiple: false, visibility: "hidden"}, _changesIconCont: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, _changesIcon: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, /** * * An instance of sap.m.Bar to be embedded in the header */ navigationBar: {type: "sap.m.Bar", multiple: false}, /** * * List of actions that will be displayed in the header. * You can use ObjectPageHeaderActionButton controls to achieve a different visual representation of the action buttons in the action bar and the action sheet (overflow menu). * You can use ObjectPageHeaderLayoutData to display a visual separator. */ actions: {type: "sap.ui.core.Control", multiple: true, singularName: "action"} }, events: { /** * The event is fired when the objectPage header title selector (down-arrow) is pressed */ titleSelectorPress: { parameters: { /** * DOM reference of the title item's icon to be used for positioning. */ domRef: {type: "string"} } }, /** * The event is fired when the Locked button is pressed */ markLockedPress: { parameters: { /** * DOM reference of the lock item's icon to be used for positioning. */ domRef: {type: "string"} } }, /** * The event is fired when the unsaved changes button is pressed */ markChangesPress: { parameters: { /** * DOM reference of the changed item's icon to be used for positioning. * @since 1.34.0 */ domRef: {type: "string"} } } } } }); ObjectPageHeader.prototype._iAvailablePercentageForActions = 0.3; ObjectPageHeader.prototype.init = function () { if (!this.oLibraryResourceBundle) { this.oLibraryResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"); // get resource translation bundle } if (!this.oLibraryResourceBundleOP) { this.oLibraryResourceBundleOP = library.i18nModel.getResourceBundle(); // get resource translation bundle } this._iREMSize = parseInt(jQuery("body").css("font-size"), 10); this._iOffset = parseInt(0.25 * this._iREMSize, 10); this._iScrollBarWidth = jQuery.position.scrollbarWidth(); // Overflow button this._oOverflowActionSheet = this._getInternalAggregation("_overflowActionSheet"); this._oOverflowButton = this._getInternalAggregation("_overflowButton").attachPress(this._handleOverflowButtonPress, this); this._oExpandButton = this._getInternalAggregation("_expandButton"); this._oActionSheetButtonMap = {}; this._oFlagIcon = this._getInternalAggregation("_flagIcon"); this._oFavIcon = this._getInternalAggregation("_favIcon"); this._oTitleArrowIcon = this._getInternalAggregation("_titleArrowIcon").attachPress(this._handleArrowPress, this); this._oTitleArrowIconCont = this._getInternalAggregation("_titleArrowIconCont").attachPress(this._handleArrowPress, this); this._oLockIcon = this._getInternalAggregation("_lockIcon").attachPress(this._handleLockPress, this); this._oLockIconCont = this._getInternalAggregation("_lockIconCont").attachPress(this._handleLockPress, this); this._oChangesIcon = this._getInternalAggregation("_changesIcon").attachPress(this._handleChangesPress, this); this._oChangesIconCont = this._getInternalAggregation("_changesIconCont").attachPress(this._handleChangesPress, this); }; ObjectPageHeader.prototype._handleOverflowButtonPress = function (oEvent) { this._oOverflowActionSheet.openBy(this._oOverflowButton); }; ObjectPageHeader.prototype._handleArrowPress = function (oEvent) { this.fireTitleSelectorPress({ domRef: oEvent.getSource().getDomRef() }); }; ObjectPageHeader.prototype._handleLockPress = function (oEvent) { this.fireMarkLockedPress({ domRef: oEvent.getSource().getDomRef() }); }; ObjectPageHeader.prototype._handleChangesPress = function (oEvent) { this.fireMarkChangesPress({ domRef: oEvent.getSource().getDomRef() }); }; ObjectPageHeader._internalAggregationFactory = { "_objectImage": function (oParent) { var oObjectImage, sObjectImageURI = oParent.getObjectImageURI(); if (sObjectImageURI.indexOf("sap-icon://") == 0) { oObjectImage = new Icon(); } else { oObjectImage = new Image({ densityAware: oParent.getObjectImageDensityAware(), alt: oParent.getObjectImageAlt(), decorative: false }); } oObjectImage.setSrc(sObjectImageURI); oObjectImage.addStyleClass("sapUxAPObjectPageHeaderObjectImage"); if (oParent.getObjectImageAlt()) { oObjectImage.setTooltip(oParent.getObjectImageAlt()); } return oObjectImage; }, "_overflowActionSheet": function () { return new ActionSheet({placement: sap.m.PlacementType.Bottom}); }, "_lockIconCont": function (oParent) { return this._getButton(oParent, "sap-icon://locked", "lock-cont"); }, "_breadCrumbs": function (oParent) { return new Breadcrumbs({ links: oParent.getAggregation("breadCrumbLinks") }); }, "_lockIcon": function (oParent) { return this._getButton(oParent, "sap-icon://locked", "lock", oParent.oLibraryResourceBundleOP.getText("TOOLTIP_OP_LOCK_MARK_VALUE")); }, "_titleArrowIconCont": function (oParent) { return this._getButton(oParent, "sap-icon://arrow-down", "titleArrow-cont", oParent.oLibraryResourceBundleOP.getText("OP_SELECT_ARROW_TOOLTIP")); }, "_titleArrowIcon": function (oParent) { return this._getButton(oParent, "sap-icon://arrow-down", "titleArrow", oParent.oLibraryResourceBundleOP.getText("OP_SELECT_ARROW_TOOLTIP")); }, "_favIcon": function (oParent) { return this._getIcon(oParent, "favorite", oParent.oLibraryResourceBundleOP.getText("TOOLTIP_OP_FAVORITE_MARK_VALUE")); }, "_flagIcon": function (oParent) { return this._getIcon(oParent, "flag", oParent.oLibraryResourceBundleOP.getText("TOOLTIP_OP_FLAG_MARK_VALUE")); }, "_overflowButton": function (oParent) { return this._getButton(oParent, "sap-icon://overflow", "overflow"); }, "_expandButton": function (oParent) { return this._getButton(oParent, "sap-icon://slim-arrow-down", "expand", oParent.oLibraryResourceBundleOP.getText("TOOLTIP_OP_EXPAND_HEADER_BTN")); }, "_changesIconCont": function (oParent) { return this._getButton(oParent, "sap-icon://request", "changes-cont", oParent.oLibraryResourceBundleOP.getText("TOOLTIP_OP_CHANGES_MARK_VALUE")); }, "_changesIcon": function (oParent) { return this._getButton(oParent, "sap-icon://request", "changes", oParent.oLibraryResourceBundleOP.getText("TOOLTIP_OP_CHANGES_MARK_VALUE")); }, _getIcon: function (oParent, sIcon, sTooltip) { return IconPool.createControlByURI({ id: this._getParentAugmentedId(oParent, sIcon), tooltip: sTooltip, src: IconPool.getIconURI(sIcon), visible: false }); }, _getButton: function (oParent, sIcon, sChildSignature, sTooltip) { return new Button({ id: this._getParentAugmentedId(oParent, sChildSignature), tooltip: sTooltip, icon: sIcon, type: sap.m.ButtonType.Transparent }); }, _getParentAugmentedId: function (oParent, sChildSignature) { return oParent.getId() + "-" + sChildSignature; } }; ObjectPageHeader.prototype._getInternalAggregation = function (sAggregationName) { if (!this.getAggregation(sAggregationName)) { this.setAggregation(sAggregationName, ObjectPageHeader._internalAggregationFactory[sAggregationName](this)); } return this.getAggregation(sAggregationName); }; ObjectPageHeader.prototype._applyActionProperty = function (sPropertyName, aArguments) { var newValue = aArguments[0]; if (this.getProperty(sPropertyName) !== newValue) { aArguments.unshift(sPropertyName); this.setProperty.apply(this, aArguments); this._notifyParentOfChanges(); } return this; }; ObjectPageHeader.prototype._applyObjectImageProperty = function (sPropertyName, aArguments) { var newValue = aArguments[0]; if (this.getProperty(sPropertyName) !== newValue) { aArguments.unshift(sPropertyName); this.setProperty.apply(this, aArguments); this._destroyObjectImage(); this._notifyParentOfChanges(); } return this; }; ObjectPageHeader.prototype._proxyMethodToBreadCrumbControl = function (sFuncName, aArguments) { var oBreadCrumbs = this._getInternalAggregation("_breadCrumbs"); return oBreadCrumbs[sFuncName].apply(oBreadCrumbs, aArguments); }; ObjectPageHeader.prototype.setHeaderDesign = function (sHeaderDesign) { this.setProperty("headerDesign", sHeaderDesign); if (this.getParent()) { this.getParent().invalidate(); // Force rerendering of ObjectPageLayout if the design change } return this; }; ObjectPageHeader.prototype._shiftHeaderTitle = function () { var oParent = this.getParent(), iHeaderOffset = 0, sStyleAttribute = sap.ui.getCore().getConfiguration().getRTL() ? "left" : "right", $actions = this.$().find(".sapUxAPObjectPageHeaderIdentifierActions"), bHasVerticalScroll = true, iActionsOffset = this._iOffset; if (typeof oParent._hasVerticalScrollBar === "function") { bHasVerticalScroll = oParent._hasVerticalScrollBar(); } if (sap.ui.Device.system.desktop) { iHeaderOffset = this._iScrollBarWidth; if (!bHasVerticalScroll) { iHeaderOffset = 0; iActionsOffset += this._iScrollBarWidth; } } $actions.css(sStyleAttribute, iActionsOffset + "px"); if (typeof oParent._shiftHeader === "function"){ oParent._shiftHeader(sStyleAttribute, iHeaderOffset + "px"); } }; /** * get current title and if it is different from the new one rerender the HeaderContent * @param {string} sTitle title string * @return {*} this */ ObjectPageHeader.prototype.setObjectTitle = function (sTitle) { return this._applyActionProperty("objectTitle", Array.prototype.slice.call(arguments)); }; var aPropertiesToOverride = ["objectSubtitle", "showTitleSelector", "markLocked", "markFavorite", "markFlagged", "showMarkers", "showPlaceholder", "markChanges"], aObjectImageProperties = ["objectImageURI", "objectImageAlt", "objectImageDensityAware", "objectImageShape"]; var fnGenerateSetter = function (sPropertyName) { var sConvertedSetterName = "set" + sPropertyName.charAt(0).toUpperCase() + sPropertyName.slice(1); ObjectPageHeader.prototype[sConvertedSetterName] = function () { var aArgumentsPassedToTheProperty = Array.prototype.slice.call(arguments); this._applyActionProperty.call(this, sPropertyName, aArgumentsPassedToTheProperty); }; }; var fnGenerateSetterForObjectImageProperties = function (sPropertyName) { var sConvertedSetterName = "set" + sPropertyName.charAt(0).toUpperCase() + sPropertyName.slice(1); ObjectPageHeader.prototype[sConvertedSetterName] = function () { var aArgumentsPassedToTheProperty = Array.prototype.slice.call(arguments); this._applyObjectImageProperty.call(this, sPropertyName, aArgumentsPassedToTheProperty); }; }; aPropertiesToOverride.forEach(fnGenerateSetter); aObjectImageProperties.forEach(fnGenerateSetterForObjectImageProperties); ObjectPageHeader.prototype.getBreadCrumbsLinks = function () { return this._getInternalAggregation("_breadCrumbs").getLinks(); }; ObjectPageHeader.prototype.addBreadCrumbLink = function () { return this._proxyMethodToBreadCrumbControl("addLink", arguments); }; ObjectPageHeader.prototype.indexOfBreadCrumbLink = function () { return this._proxyMethodToBreadCrumbControl("indexOfLink", arguments); }; ObjectPageHeader.prototype.insertBreadCrumbLink = function () { return this._proxyMethodToBreadCrumbControl("insertLink", arguments); }; ObjectPageHeader.prototype.removeBreadCrumbLink = function () { return this._proxyMethodToBreadCrumbControl("removeLink", arguments); }; ObjectPageHeader.prototype.removeAllBreadCrumbsLinks = function () { return this._proxyMethodToBreadCrumbControl("removeAllLinks", arguments); }; ObjectPageHeader.prototype.destroyBreadCrumbsLinks = function () { return this._proxyMethodToBreadCrumbControl("destroyLinks", arguments); }; ObjectPageHeader.prototype._destroyObjectImage = function () { var sObjectImage = "_objectImage", oObjectImage = this.getAggregation(sObjectImage); if (oObjectImage) { oObjectImage.destroy(); this.setAggregation(sObjectImage, null); } }; ObjectPageHeader.prototype.onBeforeRendering = function () { if (this.getShowPlaceholder()) { this._oPlaceholder = IconPool.createControlByURI({ src: IconPool.getIconURI("picture"), visible: true }); } var aActions = this.getActions() || []; this._oOverflowActionSheet.removeAllButtons(); this._oActionSheetButtonMap = {}; //display overflow if there are more than 1 item or only 1 item and it is showing its text if (aActions.length > 1 || this._hasOneButtonShowText(aActions)) { //create responsive equivalents of the provided controls jQuery.each(aActions, jQuery.proxy(function (iIndex, oAction) { // Force the design of the button to transparent if (oAction instanceof Button && oAction.getVisible()) { if (oAction instanceof Button && (oAction.getType() === "Default" || oAction.getType() === "Unstyled")) { oAction.setProperty("type", sap.m.ButtonType.Transparent, false); } var oActionSheetButton = this._createActionSheetButton(oAction); this._oActionSheetButtonMap[oAction.getId()] = oActionSheetButton; //store the originalId/reference for later use (adaptLayout) this._oOverflowActionSheet.addButton(oActionSheetButton); } }, this)); } this._oTitleArrowIcon.setVisible(this.getShowTitleSelector()); this._oFavIcon.setVisible(this.getMarkFavorite()); this._oFlagIcon.setVisible(this.getMarkFlagged()); this._attachDetachActionButtonsHandler(false); }; /** * "clone" the button provided by the app developer in order to create an equivalent for the actionsheet (displayed in overflowing scenarios) * @param {*} oButton the button to copy * @returns {sap.m.Button} the copied button * @private */ ObjectPageHeader.prototype._createActionSheetButton = function (oButton) { //copy binding if present var oCopy = new Button({ press: jQuery.proxy(this._onSeeMoreContentSelect, this), enabled: oButton.getEnabled(), customData: new CustomData({ key: "originalId", value: oButton.getId() }) }); //carry property & binding on text var oTextBinding = oButton.getBindingInfo("text"), oIconBinding = oButton.getBindingInfo("icon"), sModelName; if (oTextBinding && oTextBinding.parts && oTextBinding.parts.length > 0) { sModelName = oTextBinding.parts[0].model; //copy binding information oCopy.bindProperty("text", { path: oTextBinding.parts[0].path, model: sModelName, formatter: oTextBinding.formatter }); //handle relative binding scenarios oCopy.setBindingContext(oButton.getBindingContext(sModelName), sModelName); oCopy.setModel(oButton.getModel(sModelName), sModelName); } else { oCopy.setText(oButton.getText()); } //carry property & binding on icon if (oIconBinding && oIconBinding.parts && oIconBinding.parts.length > 0) { sModelName = oIconBinding.parts[0].model; //copy binding information oCopy.bindProperty("icon", { path: oIconBinding.parts[0].path, model: sModelName, formatter: oIconBinding.formatter }); //handle relative binding scenarios oCopy.setBindingContext(oButton.getBindingContext(sModelName), sModelName); oCopy.setModel(oButton.getModel(sModelName), sModelName); } else { oCopy.setIcon(oButton.getIcon()); } return oCopy; }; ObjectPageHeader.prototype.onAfterRendering = function () { this._adaptLayout(); if (this.getShowPlaceholder()) { jQuery(".sapUxAPObjectPageHeaderObjectImage").off("error").error(function () { jQuery(this).hide(); jQuery(".sapUxAPObjectPageHeaderPlaceholder").removeClass("sapUxAPHidePlaceholder"); }); } else { jQuery(".sapUxAPObjectPageHeaderObjectImage").off("error").error(function () { jQuery(this).addClass("sapMNoImg"); }); } if (!this._iResizeId) { this._iResizeId = ResizeHandler.register(this, this._onHeaderResize.bind(this)); } this._shiftHeaderTitle(); this._attachDetachActionButtonsHandler(true); }; ObjectPageHeader.prototype._onHeaderResize = function () { this._adaptLayout(); if (this.getParent() && typeof this.getParent()._adjustHeaderHeights === "function") { this.getParent()._adjustHeaderHeights(); } }; ObjectPageHeader.prototype._attachDetachActionButtonsHandler = function (bAttach) { var aActions = this.getActions() || []; if (aActions.length < 1) { return; } aActions.forEach(function (oAction) { if (oAction instanceof ObjectPageHeaderActionButton) { if (bAttach) { oAction.attachEvent("_change", this._adaptLayout, this); } else { oAction.detachEvent("_change", this._adaptLayout, this); } } }, this); }; ObjectPageHeader.prototype._onSeeMoreContentSelect = function (oEvent) { var oPressedButton = oEvent.getSource(), oOriginalControl = sap.ui.getCore().byId(oPressedButton.data("originalId")); //forward press event if (oOriginalControl.firePress) { //provide parameters in case the handlers wants to know where was the event fired from oOriginalControl.firePress({ overflowButtonId: this._oOverflowButton.getId() }); } this._oOverflowActionSheet.close(); }; ObjectPageHeader._actionImportanceMap = { "Low": 3, "Medium": 2, "High": 1 }; /** * Actions custom sorter function * @private */ ObjectPageHeader._sortActionsByImportance = function (oActionA, oActionB) { var sImportanceA = (oActionA instanceof ObjectPageHeaderActionButton) ? oActionA.getImportance() : sap.uxap.Importance.High, sImportanceB = (oActionB instanceof ObjectPageHeaderActionButton) ? oActionB.getImportance() : sap.uxap.Importance.High, iImportanceDifference = ObjectPageHeader._actionImportanceMap[sImportanceA] - ObjectPageHeader._actionImportanceMap[sImportanceB]; if (iImportanceDifference === 0) { return oActionA.position - oActionB.position; } return iImportanceDifference; }; ObjectPageHeader.prototype._hasOneButtonShowText = function (aActions) { var bOneButtonShowingText = false; if (aActions.length !== 1) { return bOneButtonShowingText; } if (aActions[0] instanceof ObjectPageHeaderActionButton) { bOneButtonShowingText = (!aActions[0].getHideText() && aActions[0].getText() != "" ); } else if (aActions[0] instanceof Button) { bOneButtonShowingText = (aActions[0].getText() != "" ); } return bOneButtonShowingText; }; /************************************************************************************* * Adapting ObjectPage image, title/subtitle container and actions container ************************************************************************************/ /** * Adapt title/subtitle container and action buttons and overflow button * @private */ ObjectPageHeader.prototype._adaptLayout = function () { var iIdentifierContWidth = this.$("identifierLine").width(), iActionsWidth = this._getActionsWidth(), // the width off all actions without hidden one iActionsContProportion = iActionsWidth / iIdentifierContWidth, // the percentage(proportion) that action buttons take from the available space iAvailableSpaceForActions = this._iAvailablePercentageForActions * iIdentifierContWidth, $overflowButton = this._oOverflowButton.$(), $actionButtons = this.$("actions").find(".sapMBtn").not(".sapUxAPObjectPageHeaderExpandButton"); if (iActionsContProportion > this._iAvailablePercentageForActions) { this._adaptActions(iAvailableSpaceForActions); } $actionButtons.css("visibility", "visible"); // verify overflow button visibility if ($actionButtons.filter(":visible").length === $actionButtons.length) { $overflowButton.hide(); } this._adaptObjectPageHeaderIndentifierLine(); }; /** * Adapt title/subtitle container and action buttons * @private */ ObjectPageHeader.prototype._adaptObjectPageHeaderIndentifierLine = function () { var iIdentifierContWidth = this.$("identifierLine").width(), $subtitle = this.$("subtitle"), $identifierLineContainer = this.$("identifierLineContainer"), iSubtitleBottom, iTitleBottom, iActionsAndImageWidth = this.$("actions").width() + this.$().find(".sapUxAPObjectPageHeaderObjectImageContainer").width(), iPixelTolerance = 3; // the tolerance of pixels from which we can tell that the title and subtitle are on the same row if ($subtitle.length) { if ($subtitle.hasClass("sapOPHSubtitleBlock")) { $subtitle.removeClass("sapOPHSubtitleBlock"); } iSubtitleBottom = $subtitle.outerHeight() + $subtitle.position().top; iTitleBottom = this.$("innerTitle").outerHeight() + this.$("innerTitle").position().top; // check if subtitle is below the title and add it a display block class if (Math.abs(iSubtitleBottom - iTitleBottom) > iPixelTolerance) { $subtitle.addClass("sapOPHSubtitleBlock"); } } $identifierLineContainer.width((0.95 - (iActionsAndImageWidth / iIdentifierContWidth)) * 100 + "%"); }; /** * Show or hide action buttons depending on how much space is available * @private */ ObjectPageHeader.prototype._adaptActions = function (iAvailableSpaceForActions) { var bMobileScenario = jQuery("html").hasClass("sapUiMedia-Std-Phone") || Device.system.phone, iVisibleActionsWidth = this._oOverflowButton.$().show().width(), aActions = this.getActions(), iActionsLength = aActions.length, oActionSheetButton; for (var i = 0; i < iActionsLength; i++) { aActions[i].position = i; } aActions.sort(ObjectPageHeader._sortActionsByImportance); aActions.forEach(function (oAction) { oActionSheetButton = this._oActionSheetButtonMap[oAction.getId()]; //separators and non sap.m.Button or not visible buttons have no equivalent in the overflow if (oActionSheetButton) { iVisibleActionsWidth += oAction.$().width(); if (iAvailableSpaceForActions > iVisibleActionsWidth && !bMobileScenario) { oActionSheetButton.setVisible(false); } else { this._setActionButtonVisibility(oAction, false); } } }, this); }; /** * Set visibility of action button and the button in action sheet * @private */ ObjectPageHeader.prototype._setActionButtonVisibility = function (oAction, bVisible) { var oActionSheetButton = this._oActionSheetButtonMap[oAction.getId()]; //separators and non sap.m.Button or not visible buttons have no equivalent in the overflow if (oActionSheetButton) { if (bVisible) { oAction.$().show(); } else { oAction.$().hide(); } oActionSheetButton.setVisible(!bVisible); } }; /** * The sum of widths(+ margins) of all action buttons * @private */ ObjectPageHeader.prototype._getActionsWidth = function () { var iWidthSum = 0; this.getActions().forEach(function (oAction) { if (oAction instanceof Button) { oAction.$().show(); oAction.$().css("visibility", "hidden"); iWidthSum += oAction.$().outerWidth(true); } }); return iWidthSum; }; /*************************************************************************************/ /** * rerender the title in the ContentHeader if something in it is changed * @private */ ObjectPageHeader.prototype._notifyParentOfChanges = function () { if (this.getParent() && typeof this.getParent()._headerTitleChangeHandler === "function") { this.getParent()._headerTitleChangeHandler(); } }; /** * check if the ActionBar has padding on top, if not in case of rerendering of the control it has to be removed * @returns {boolean} * @private */ ObjectPageHeader.prototype._getActionsPaddingStatus = function () { return this.$("actions").hasClass("sapUxAPObjectPageHeaderIdentifierActionsNoPadding"); }; ObjectPageHeader.prototype._setActionsPaddingStatus = function (bShow) { return this.$("actions").toggleClass("sapUxAPObjectPageHeaderIdentifierActionsNoPadding", bShow); }; ObjectPageHeader.prototype.exit = function () { jQuery(".sapUxAPObjectPageHeaderObjectImage").off("error"); if (this._iResizeId) { ResizeHandler.deregister(this._iResizeId); } }; return ObjectPageHeader; }); }; // end of sap/uxap/ObjectPageHeader.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageLayoutABHelper') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.ObjectPageLayoutABHelper'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained jQuery.sap.require('sap.ui.base.Metadata'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.CustomData'); // unlisted dependency retained jQuery.sap.require('sap.m.Button'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.IconPool'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageLayoutABHelper",[ "jquery.sap.global", "sap/ui/base/Metadata", "sap/ui/core/CustomData", "./AnchorBar", "sap/m/Button", "sap/ui/core/IconPool" ], function (jQuery, Metadata, CustomData, AnchorBar, Button, IconPool) { "use strict"; var ABHelper = Metadata.createClass("sap.uxap._helpers.AB", { /** * @private * @param {sap.uxap.ObjectPageLayout} oObjectPageLayout Object Page layout instance */ constructor: function (oObjectPageLayout) { this._oObjectPageLayout = oObjectPageLayout; this._iScrollDuration = oObjectPageLayout._iScrollToSectionDuration; } }); ABHelper.prototype.getObjectPageLayout = function () { return this._oObjectPageLayout; }; /** * Lazy loads the hidden Aggregation "_anchorBar" * @returns {sap.uxap.AnchorBar} AnchorBar * @private */ ABHelper.prototype._getAnchorBar = function () { var oAnchorBar = this.getObjectPageLayout().getAggregation("_anchorBar"); if (!oAnchorBar) { oAnchorBar = new AnchorBar({ showPopover: this.getObjectPageLayout().getShowAnchorBarPopover() }); this.getObjectPageLayout().setAggregation("_anchorBar", oAnchorBar); } return oAnchorBar; }; /** * build the anchorBar and all the anchorBar buttons * @private */ ABHelper.prototype._buildAnchorBar = function () { var aSections = this.getObjectPageLayout().getSections() || [], oAnchorBar = this._getAnchorBar(); //tablet & desktop mechanism if (oAnchorBar && this.getObjectPageLayout().getShowAnchorBar()) { oAnchorBar.removeAllContent(); //first level aSections.forEach(function (oSection) { if (!oSection.getVisible() || !oSection._getInternalVisible()) { return true; } var oButtonClone, aSubSections = oSection.getSubSections() || []; oButtonClone = this._buildAnchorBarButton(oSection, true); if (oButtonClone) { oAnchorBar.addContent(oButtonClone); //second Level aSubSections.forEach(function (oSubSection) { if (!oSubSection.getVisible() || !oSubSection._getInternalVisible()) { return; } var oButtonClone = this._buildAnchorBarButton(oSubSection, false); if (oButtonClone) { oAnchorBar.addContent(oButtonClone); } }, this); } }, this); } }; ABHelper.prototype._focusOnSectionWhenUsingKeyboard = function (oEvent) { var oSourceData = oEvent.srcControl.data(), oSection = sap.ui.getCore().byId(oSourceData.sectionId), oObjectPage = this.getObjectPageLayout(); if (oSection && !oSourceData.bHasSubMenu && !oObjectPage.getUseIconTabBar()) { jQuery.sap.delayedCall(this._iScrollDuration, oSection.$(), "focus"); } }; /** * build a sap.m.button equivalent to a section or sub section for insertion in the anchorBar * also registers the section info for further dom position updates * @param oSectionBase * @param bIsSection * @returns {null} * @private */ ABHelper.prototype._buildAnchorBarButton = function (oSectionBase, bIsSection) { var oButtonClone = null, oObjectPageLayout = this.getObjectPageLayout(), oButton, oSectionBindingInfo, sModelName, aSubSections = oSectionBase.getAggregation("subSections"), fnButtonKeyboardUseHandler = this._focusOnSectionWhenUsingKeyboard.bind(this), oEventDelegatesForkeyBoardHandler = { onsapenter: fnButtonKeyboardUseHandler, onsapspace: fnButtonKeyboardUseHandler }; if (oSectionBase.getVisible() && oSectionBase._getInternalVisible()) { oButton = oSectionBase.getCustomAnchorBarButton(); //by default we get create a button with the section title as text if (!oButton) { oButtonClone = new Button({ ariaDescribedBy: oSectionBase }); oButtonClone.addEventDelegate(oEventDelegatesForkeyBoardHandler); //has a ux rule been applied that we need to reflect here? if (oSectionBase._getInternalTitle() != "") { oButtonClone.setText(oSectionBase._getInternalTitle()); } else { //is the section title bound to a model? in this case we need to apply the same binding oSectionBindingInfo = oSectionBase.getBindingInfo("title"); if (oSectionBindingInfo && oSectionBindingInfo.parts && oSectionBindingInfo.parts.length > 0) { sModelName = oSectionBindingInfo.parts[0].model; //handle relative binding scenarios oButtonClone.setBindingContext(oSectionBase.getBindingContext(sModelName), sModelName); //copy binding information oButtonClone.bindProperty("text", { path: oSectionBindingInfo.parts[0].path, model: sModelName }); } else { //otherwise just copy the plain text oButtonClone.setText(oSectionBase.getTitle()); } } } else { oButtonClone = oButton.clone(); //keep original button parent control hierarchy } //update the section info oObjectPageLayout._oSectionInfo[oSectionBase.getId()].buttonId = oButtonClone.getId(); //the anchorBar needs to know the sectionId for automatic horizontal scrolling oButtonClone.addCustomData(new CustomData({ key: "sectionId", value: oSectionBase.getId() })); //the anchorBar needs to know whether the title is actually displayed or not (so the anchorBar is really reflecting the objactPage layout state) oButtonClone.addCustomData(new CustomData({ key: "bTitleVisible", value: oSectionBase._getInternalTitleVisible() })); if (!bIsSection) { //the anchorBar needs to know that this is a second section because it will handle responsive scenarios oButtonClone.addCustomData(new CustomData({ key: "secondLevel", value: true })); } if (aSubSections && aSubSections.length > 1) { // the anchor bar need to know if the button has submenu for accessibility rules oButtonClone.addCustomData(new CustomData({ key: "bHasSubMenu", value: true })); if (oObjectPageLayout.getShowAnchorBarPopover()) { // Add arrow icon-down in order to indicate that on click will open popover oButtonClone.setIcon(IconPool.getIconURI("slim-arrow-down")); oButtonClone.setIconFirst(false); } } } return oButtonClone; }; return ABHelper; }, /* bExport= */ false); }; // end of sap/uxap/ObjectPageLayoutABHelper.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageSection') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ObjectPageSection. jQuery.sap.declare('sap.uxap.ObjectPageSection'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.InvisibleText'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained jQuery.sap.require('sap.m.Button'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageSection",[ "jquery.sap.global", "sap/ui/core/InvisibleText", "./ObjectPageSectionBase", "sap/ui/Device", "sap/m/Button", "./library" ], function (jQuery, InvisibleText, ObjectPageSectionBase, Device, Button, library) { "use strict"; /** * Constructor for a new ObjectPageSection. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * * An ObjectPageSection is the top-level information container of an Object page. Its purpose is to aggregate Subsections. * Disclaimer: This control is intended to be used only as part of the Object page layout * @extends sap.uxap.ObjectPageSectionBase * * @constructor * @public * @alias sap.uxap.ObjectPageSection * @since 1.26 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectPageSection = ObjectPageSectionBase.extend("sap.uxap.ObjectPageSection", /** @lends sap.uxap.ObjectPageSection.prototype */ { metadata: { library: "sap.uxap", properties: { /** * Determines whether to display the Section title or not. */ showTitle: {type: "boolean", group: "Appearance", defaultValue: true}, /** * Determines whether the Section title is displayed in upper case. */ titleUppercase: {type: "boolean", group: "Appearance", defaultValue: true} }, defaultAggregation: "subSections", aggregations: { /** * The list of Subsections. */ subSections: {type: "sap.uxap.ObjectPageSubSection", multiple: true, singularName: "subSection"}, /** * Screen Reader ariaLabelledBy */ ariaLabelledBy: {type: "sap.ui.core.InvisibleText", multiple: false, visibility: "hidden"}, _showHideAllButton: {type: "sap.m.Button", multiple: false, visibility: "hidden"}, _showHideButton: {type: "sap.m.Button", multiple: false, visibility: "hidden"} }, associations: { /** * The most recently selected Subsection by the user. */ selectedSubSection: {type: "sap.uxap.ObjectPageSubSection", multiple: false} } } }); ObjectPageSection.MEDIA_RANGE = Device.media.RANGESETS.SAP_STANDARD; ObjectPageSection.prototype._expandSection = function () { ObjectPageSectionBase.prototype._expandSection.call(this) ._updateShowHideAllButton(!this._thereAreHiddenSubSections()); }; ObjectPageSection.prototype.init = function () { ObjectPageSectionBase.prototype.init.call(this); this._sContainerSelector = ".sapUxAPObjectPageSectionContainer"; Device.media.attachHandler(this._updateImportance, this, ObjectPageSection.MEDIA_RANGE); }; ObjectPageSection.prototype.exit = function () { Device.media.detachHandler(this._updateImportance, this, ObjectPageSection.MEDIA_RANGE); }; /** * Handler for key up - handle * @param oEvent - The event object */ ObjectPageSection.prototype.onkeyup = function (oEvent) { var eventTarget = sap.ui.getCore().byId(jQuery(oEvent.target).attr("id")); if (oEvent.keyCode === jQuery.sap.KeyCodes.TAB && eventTarget instanceof sap.uxap.ObjectPageSection && this._getObjectPageLayout()._isFirstSection(this)) { this._getObjectPageLayout().$("opwrapper").scrollTop(0); } }; ObjectPageSection.prototype._getImportanceLevelToHide = function (oCurrentMedia) { var oObjectPage = this._getObjectPageLayout(), oMedia = oCurrentMedia || Device.media.getCurrentRange(ObjectPageSection.MEDIA_RANGE), bShowOnlyHighImportance = oObjectPage && oObjectPage.getShowOnlyHighImportance(); return this._determineTheLowestLevelOfImportanceToShow(oMedia.name, bShowOnlyHighImportance); }; ObjectPageSection.prototype._updateImportance = function (oCurrentMedia) { var oObjectPage = this._getObjectPageLayout(), sImportanceLevelToHide = this._getImportanceLevelToHide(oCurrentMedia); this.getSubSections().forEach(function (oSubSection) { oSubSection._applyImportanceRules(sImportanceLevelToHide); }); this._applyImportanceRules(sImportanceLevelToHide); this._updateShowHideAllButton(false); if (oObjectPage && this.getDomRef()) { oObjectPage._adjustLayout(); } }; ObjectPageSection.prototype._determineTheLowestLevelOfImportanceToShow = function (sMedia, bShowOnlyHighImportance) { if (bShowOnlyHighImportance || sMedia === "Phone") { return library.Importance.High; } if (sMedia === "Tablet") { return library.Importance.Medium; } return library.Importance.Low; }; ObjectPageSection.prototype.connectToModels = function () { this.getSubSections().forEach(function (oSubSection) { oSubSection.connectToModels(); }); }; ObjectPageSection.prototype.onBeforeRendering = function () { var sAriaLabeledBy = "ariaLabelledBy"; if (!this.getAggregation(sAriaLabeledBy)) { this.setAggregation(sAriaLabeledBy, this._getAriaLabelledBy()); } this._updateImportance(); }; /** * provide a default aria-labeled by text * @private * @returns {*} sap.ui.core.InvisibleText */ ObjectPageSection.prototype._getAriaLabelledBy = function () { return new InvisibleText({ text: this._getInternalTitle() || this.getTitle() }).toStatic(); }; /** * set subsections focus rules * @private * @returns {*} this */ ObjectPageSection.prototype._setSubSectionsFocusValues = function () { var aSubSections = this.getSubSections() || [], sLastSelectedSubSectionId = this.getSelectedSubSection(), bPreselectedSection; if (aSubSections.length === 0) { return this; } aSubSections.forEach(function (oSubsection) { if (sLastSelectedSubSectionId === oSubsection.sId) { oSubsection._setToFocusable(true); bPreselectedSection = true; } else { oSubsection._setToFocusable(false); } }); if (!bPreselectedSection) { aSubSections[0]._setToFocusable(true); } return this; }; ObjectPageSection.prototype._disableSubSectionsFocus = function () { var aSubSections = this.getSubSections() || []; aSubSections.forEach(function (oSubsection) { oSubsection._setToFocusable(false); }); return this; }; ObjectPageSection.prototype._thereAreHiddenSubSections = function () { return this.getSubSections().some(function (oSubSection) { return oSubSection._getIsHidden(); }); }; ObjectPageSection.prototype._updateShowHideSubSections = function (bHide) { this.getSubSections().forEach(function (oSubSection) { if (bHide && oSubSection._shouldBeHidden()) { oSubSection._updateShowHideState(true); } else if (!bHide) { oSubSection._updateShowHideState(false); } }); }; ObjectPageSection.prototype._getShouldDisplayShowHideAllButton = function () { return this.getSubSections().some(function (oSubSection) { return oSubSection._shouldBeHidden(); }); }; ObjectPageSection.prototype._showHideContentAllContent = function () { var bShouldShowSubSections = this._thereAreHiddenSubSections(); if (this._getIsHidden() && bShouldShowSubSections) { this._updateShowHideState(false); } this._updateShowHideSubSections(!bShouldShowSubSections); this._updateShowHideAllButton(bShouldShowSubSections); }; ObjectPageSection.prototype._updateShowHideState = function (bHide) { this._updateShowHideButton(bHide); this._getShowHideAllButton().setVisible(this._getShouldDisplayShowHideAllButton()); return ObjectPageSectionBase.prototype._updateShowHideState.call(this, bHide); }; ObjectPageSection.prototype._updateShowHideAllButton = function (bHide) { this._getShowHideAllButton() .setVisible(this._getShouldDisplayShowHideAllButton()) .setText(this._getShowHideAllButtonText(bHide)); }; ObjectPageSection.prototype._getShowHideAllButton = function () { if (!this.getAggregation("_showHideAllButton")) { this.setAggregation("_showHideAllButton", new Button({ visible: this._getShouldDisplayShowHideAllButton(), text: this._getShowHideAllButtonText(!this._thereAreHiddenSubSections()), press: this._showHideContentAllContent.bind(this), type: sap.m.ButtonType.Transparent }).addStyleClass("sapUxAPSectionShowHideButton")); } return this.getAggregation("_showHideAllButton"); }; ObjectPageSection.prototype._getShowHideButtonText = function (bHide) { return library.i18nModel.getResourceBundle().getText(bHide ? "HIDE" : "SHOW"); }; ObjectPageSection.prototype._getShowHideAllButtonText = function (bHide) { return library.i18nModel.getResourceBundle().getText(bHide ? "HIDE_ALL" : "SHOW_ALL"); }; ObjectPageSection.prototype._updateShowHideButton = function (bHide) { this._getShowHideButton() .setVisible(this._shouldBeHidden()) .setText(this._getShowHideButtonText(!bHide)); }; ObjectPageSection.prototype._getShowHideButton = function () { if (!this.getAggregation("_showHideButton")) { this.setAggregation("_showHideButton", new Button({ visible: this._shouldBeHidden(), text: this._getShowHideButtonText(!this._getIsHidden()), press: this._showHideContent.bind(this), type: sap.m.ButtonType.Transparent }).addStyleClass("sapUxAPSectionShowHideButton")); } return this.getAggregation("_showHideButton"); }; return ObjectPageSection; }); }; // end of sap/uxap/ObjectPageSection.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageSubSection') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ObjectPageSubSection. jQuery.sap.declare('sap.uxap.ObjectPageSubSection'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.core.CustomData'); // unlisted dependency retained jQuery.sap.require('sap.ui.layout.Grid'); // unlisted dependency retained jQuery.sap.require('sap.uxap.ObjectPageSubSectionLayout'); // unlisted dependency retained jQuery.sap.require('sap.uxap.ObjectPageSubSectionMode'); // unlisted dependency retained jQuery.sap.require('sap.ui.layout.GridData'); // unlisted dependency retained jQuery.sap.require('sap.m.Button'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageSubSection",[ "sap/ui/core/CustomData", "sap/ui/layout/Grid", "./ObjectPageSectionBase", "./ObjectPageSubSectionLayout", "./ObjectPageSubSectionMode", "./BlockBase", "sap/ui/layout/GridData", "sap/m/Button", "sap/ui/Device", "./library" ], function (CustomData, Grid, ObjectPageSectionBase, ObjectPageSubSectionLayout, ObjectPageSubSectionMode, BlockBase, GridData, Button, Device, library) { "use strict"; /** * Constructor for a new ObjectPageSubSection. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * * An ObjectPageSubSection is the second-level information container of an Object page and may only be used within an Object page section. * Subsections may display primary information in the so called blocks aggregation (always visible) * and not-so-important information in the moreBlocks aggregation, whose content is initially hidden, but may be accessed via a See more (...) button. * Disclaimer: This control is intended to be used only as part of the Object page layout * @extends sap.uxap.ObjectPageSectionBase * * @constructor * @public * @alias sap.uxap.ObjectPageSubSection * @since 1.26 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectPageSubSection = ObjectPageSectionBase.extend("sap.uxap.ObjectPageSubSection", /** @lends sap.uxap.ObjectPageSubSection.prototype */ { metadata: { library: "sap.uxap", properties: { /** * A mode property that will be passed to the controls in the blocks and moreBlocks aggregations. Only relevant if these aggregations use Object page blocks. */ mode: { type: "sap.uxap.ObjectPageSubSectionMode", group: "Appearance", defaultValue: ObjectPageSubSectionMode.Collapsed }, /** * Determines whether the Subsection title is displayed in upper case. */ titleUppercase: {type: "boolean", group: "Appearance", defaultValue: false} }, defaultAggregation: "blocks", aggregations: { /** * Internal grid aggregation */ _grid: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"}, /** * Controls to be displayed in the subsection */ blocks: {type: "sap.ui.core.Control", multiple: true, singularName: "block"}, /** * Additional controls to display when the Show more / See all / (...) button is pressed */ moreBlocks: {type: "sap.ui.core.Control", multiple: true, singularName: "moreBlock"}, /** * Actions available for this Subsection */ actions: {type: "sap.ui.core.Control", multiple: true, singularName: "action"} } } }); ObjectPageSubSection.MEDIA_RANGE = Device.media.RANGESETS.SAP_STANDARD; /** * @private */ ObjectPageSubSection.prototype.init = function () { ObjectPageSectionBase.prototype.init.call(this); //proxy public aggregations this._bRenderedFirstTime = false; this._aAggregationProxy = {blocks: [], moreBlocks: []}; //dom reference this._$spacer = []; this._sContainerSelector = ".sapUxAPBlockContainer"; //switch logic for the default mode this._switchSubSectionMode(this.getMode()); }; ObjectPageSubSection.prototype._expandSection = function () { ObjectPageSectionBase.prototype._expandSection.call(this); var oParent = this.getParent(); oParent && typeof oParent._expandSection === "function" && oParent._expandSection(); return this; }; ObjectPageSubSection.prototype._getGrid = function () { if (!this.getAggregation("_grid")) { this.setAggregation("_grid", new Grid({ id: this.getId() + "-innerGrid", defaultSpan: "XL12 L12 M12 S12", hSpacing: 1, vSpacing: 1, width: "100%", containerQuery: true })); } return this.getAggregation("_grid"); }; ObjectPageSubSection.prototype.connectToModels = function () { var aBlocks = this.getBlocks() || [], aMoreBlocks = this.getMoreBlocks() || [], sCurrentMode = this.getMode(); aBlocks.forEach(function (oBlock) { if (oBlock instanceof BlockBase) { if (!oBlock.getMode()) { oBlock.setMode(sCurrentMode); } oBlock.connectToModels(); } }); if (aMoreBlocks.length > 0 && sCurrentMode === ObjectPageSubSectionMode.Expanded) { aMoreBlocks.forEach(function (oMoreBlock) { if (oMoreBlock instanceof BlockBase) { if (!oMoreBlock.getMode()) { oMoreBlock.setMode(sCurrentMode); } oMoreBlock.connectToModels(); } }); } }; ObjectPageSubSection.prototype.exit = function () { if (this._oSeeMoreButton) { this._oSeeMoreButton.destroy(); this._oSeeMoreButton = null; } Device.media.detachHandler(this._updateImportance, this, ObjectPageSubSection.MEDIA_RANGE); Device.media.detachHandler(this._titleOnLeftSynchronizeLayouts, this, ObjectPageSubSection.MEDIA_RANGE); if (ObjectPageSectionBase.prototype.exit) { ObjectPageSectionBase.prototype.exit.call(this); } }; ObjectPageSubSection.prototype.onAfterRendering = function () { var oObjectPageLayout = this._getObjectPageLayout(); if (ObjectPageSectionBase.prototype.onAfterRendering) { ObjectPageSectionBase.prototype.onAfterRendering.call(this); } if (!oObjectPageLayout) { return; } if (this._getUseTitleOnTheLeft()) { Device.media.attachHandler(this._titleOnLeftSynchronizeLayouts, this, ObjectPageSubSection.MEDIA_RANGE); } else { Device.media.detachHandler(this._titleOnLeftSynchronizeLayouts, this, ObjectPageSubSection.MEDIA_RANGE); } this._$spacer = jQuery.sap.byId(oObjectPageLayout.getId() + "-spacer"); }; ObjectPageSubSection.prototype.onBeforeRendering = function () { if (ObjectPageSectionBase.prototype.onBeforeRendering) { ObjectPageSectionBase.prototype.onBeforeRendering.call(this); } this._setAggregationProxy(); this._getGrid().removeAllContent(); this._applyLayout(this._getObjectPageLayout()); this.refreshSeeMoreVisibility(); }; ObjectPageSubSection.prototype._applyLayout = function (oLayoutProvider) { var aVisibleBlocks, oGrid = this._getGrid(), sCurrentMode = this.getMode(), sLayout = oLayoutProvider.getSubSectionLayout(), oLayoutConfig = this._calculateLayoutConfiguration(sLayout, oLayoutProvider), aBlocks = this.getBlocks(), aAllBlocks = aBlocks.concat(this.getMoreBlocks()); this._oLayoutConfig = oLayoutConfig; this._resetLayoutData(aAllBlocks); //also add the more blocks defined for being visible in expanded mode only if (sCurrentMode === ObjectPageSubSectionMode.Expanded) { aVisibleBlocks = aAllBlocks; } else { aVisibleBlocks = aBlocks; } this._calcBlockColumnLayout(aVisibleBlocks, this._oLayoutConfig); try { aVisibleBlocks.forEach(function (oBlock) { this._setBlockMode(oBlock, sCurrentMode); oGrid.addContent(oBlock); }, this); } catch (sError) { jQuery.sap.log.error("ObjectPageSubSection :: error while building layout " + sLayout + ": " + sError); } return this; }; ObjectPageSubSection.prototype._calculateLayoutConfiguration = function (sLayout, oLayoutProvider) { var oLayoutConfig = {M: 2, L: 3, XL: 4}, iLargeScreenColumns = oLayoutConfig.L, iExtraLargeScreenColumns = oLayoutConfig.XL, bTitleOnTheLeft = (sLayout === ObjectPageSubSectionLayout.TitleOnLeft), bUseTwoColumnsOnLargeScreen = oLayoutProvider.getUseTwoColumnsForLargeScreen(); if (bTitleOnTheLeft) { iLargeScreenColumns -= 1; iExtraLargeScreenColumns -= 1; } if (bUseTwoColumnsOnLargeScreen) { iLargeScreenColumns -= 1; } oLayoutConfig.L = iLargeScreenColumns; oLayoutConfig.XL = iExtraLargeScreenColumns; return oLayoutConfig; }; ObjectPageSubSection.prototype.refreshSeeMoreVisibility = function () { var bBlockHasMore = !!this.getMoreBlocks().length, oSeeMoreControl = this._getSeeMoreButton(), $seeMoreControl = oSeeMoreControl.$(), $this = this.$(); if (!bBlockHasMore) { bBlockHasMore = this.getBlocks().some(function (oBlock) { //check if the block ask for the global see more the rule is //by default we don't display the see more //if one control is visible and ask for it then we display it if (oBlock instanceof BlockBase && oBlock.getVisible() && oBlock.getShowSubSectionMore()) { return true; } }); } //if the subsection is already rendered, don't rerender it all for showing a more button if ($this.length) { $this.toggleClass("sapUxAPObjectPageSubSectionWithSeeMore", bBlockHasMore); } this.toggleStyleClass("sapUxAPObjectPageSubSectionWithSeeMore", bBlockHasMore); if ($seeMoreControl.length) { $seeMoreControl.toggleClass("sapUxAPSubSectionSeeMoreButtonVisible", bBlockHasMore); } oSeeMoreControl.toggleStyleClass("sapUxAPSubSectionSeeMoreButtonVisible", bBlockHasMore); return bBlockHasMore; }; ObjectPageSubSection.prototype.setMode = function (sMode) { if (this.getMode() !== sMode) { this._switchSubSectionMode(sMode); if (this._bRenderedFirstTime) { this.rerender(); } } return this; }; /******************************************************************************* * Keyboard navigation ******************************************************************************/ /** * Handler for key down - handle * @param oEvent - The event object */ ObjectPageSubSection.prototype.onkeydown = function (oEvent) { // Filter F7 key down if (oEvent.keyCode === jQuery.sap.KeyCodes.F7) { oEvent.stopPropagation(); var oTarget = sap.ui.getCore().byId(oEvent.target.id); //define if F7 is pressed from SubSection itself or active element inside SubSection if (oTarget instanceof ObjectPageSubSection) { this._handleSubSectionF7(); } else { this._handleInteractiveElF7(); this._oLastFocusedControlF7 = oTarget; } } }; // It's used when F7 key is pressed and the focus is on interactive element ObjectPageSubSection.prototype._handleInteractiveElF7 = function () { //If there are more sub sections focus current subsection otherwise focus the parent section if (this.getParent().getSubSections().length > 1) { this.$().focus(); } else { this.getParent().$().focus(); } }; //It's used when F7 key is pressed and the focus is on SubSection ObjectPageSubSection.prototype._handleSubSectionF7 = function (oEvent) { if (this._oLastFocusedControlF7) { this._oLastFocusedControlF7.$().focus(); } else { this.$().firstFocusableDomRef().focus(); } }; /************************************************************************************* * generic block layout calculation ************************************************************************************/ /** * calculate the layout data to use for subsection blocks * Aligned with PUX specifications as of Oct 14, 2014 */ ObjectPageSubSection.prototype._calcBlockColumnLayout = function (aBlocks, oColumnConfig) { var iGridSize = 12, aVisibleBlocks, M, L, XL, aDisplaySizes; M = { iRemaining: oColumnConfig.M, iColumnConfig: oColumnConfig.M }; L = { iRemaining: oColumnConfig.L, iColumnConfig: oColumnConfig.L }; XL = { iRemaining: oColumnConfig.XL, iColumnConfig: oColumnConfig.XL }; aDisplaySizes = [XL, L, M]; //step 1: get only visible blocks into consideration aVisibleBlocks = aBlocks.filter(function (oBlock) { return oBlock.getVisible && oBlock.getVisible(); }); //step 2: set layout for each blocks based on their columnLayout configuration //As of Oct 14, 2014, the default behavior is: //on phone, blocks take always the full line //on tablet, desktop: //1 block on the line: takes 3/3 columns //2 blocks on the line: takes 1/3 columns then 2/3 columns //3 blocks on the line: takes 1/3 columns then 1/3 columns and last 1/3 columns aVisibleBlocks.forEach(function (oBlock, iIndex) { aDisplaySizes.forEach(function (oConfig) { oConfig.iCalculatedSize = this._calculateBlockSize(oBlock, oConfig.iRemaining, aVisibleBlocks, iIndex, oConfig.iColumnConfig); }, this); //set block layout based on resolution and break to a new line if necessary oBlock.setLayoutData(new GridData({ spanS: iGridSize, spanM: M.iCalculatedSize * (iGridSize / M.iColumnConfig), spanL: L.iCalculatedSize * (iGridSize / L.iColumnConfig), spanXL: XL.iCalculatedSize * (iGridSize / XL.iColumnConfig), linebreakM: (iIndex > 0 && M.iRemaining === M.iColumnConfig), linebreakL: (iIndex > 0 && L.iRemaining === L.iColumnConfig), linebreakXL: (iIndex > 0 && XL.iRemaining === XL.iColumnConfig) })); aDisplaySizes.forEach(function (oConfig) { oConfig.iRemaining -= oConfig.iCalculatedSize; if (oConfig.iRemaining < 1) { oConfig.iRemaining = oConfig.iColumnConfig; } }); }, this); return aVisibleBlocks; }; ObjectPageSubSection.prototype._calculateBlockSize = function (oBlock, iRemaining, aVisibleBlocks, iCurrentIndex, iMax) { var iCalc, iForewordBlocksToCheck = iMax, indexOffset; if (!this._hasAutoLayout(oBlock)) { return Math.min(iMax, parseInt(oBlock.getColumnLayout(), 10)); } for (indexOffset = 1; indexOffset <= iForewordBlocksToCheck; indexOffset++) { iCalc = this._calcLayout(aVisibleBlocks[iCurrentIndex + indexOffset]); if (iCalc < iRemaining) { iRemaining -= iCalc; } else { break; } } return iRemaining; }; ObjectPageSubSection.prototype._calcLayout = function (oBlock) { var iLayoutCols = 1; if (!oBlock) { iLayoutCols = 0; } else if (oBlock instanceof BlockBase && oBlock.getColumnLayout() != "auto") { iLayoutCols = parseInt(oBlock.getColumnLayout(), 10); } return iLayoutCols; }; ObjectPageSubSection.prototype._hasAutoLayout = function (oBlock) { return !(oBlock instanceof BlockBase) || oBlock.getColumnLayout() == "auto"; }; /************************************************************************************* * TitleOnLeft layout ************************************************************************************/ ObjectPageSubSection.prototype._onDesktopMediaRange = function (oCurrentMedia) { var oMedia = oCurrentMedia || Device.media.getCurrentRange(ObjectPageSubSection.MEDIA_RANGE); return ["LargeDesktop", "Desktop"].indexOf(oMedia.name) > -1; }; ObjectPageSubSection.prototype._titleOnLeftSynchronizeLayouts = function (oCurrentMedia) { this.$("header").toggleClass("titleOnLeftLayout", this._onDesktopMediaRange(oCurrentMedia)); }; /************************************************************************************* * blocks & moreBlocks aggregation proxy * getter and setters works with _aAggregationProxy instead of the blocks aggregation ************************************************************************************/ ObjectPageSubSection.prototype._setAggregationProxy = function () { if (this._bRenderedFirstTime) { return; } //empty real aggregations and feed internal ones at first rendering only jQuery.each(this._aAggregationProxy, jQuery.proxy(function (sAggregationName, aValue) { this._setAggregation(sAggregationName, this.removeAllAggregation(sAggregationName)); }, this)); this._bRenderedFirstTime = true; }; ObjectPageSubSection.prototype.hasProxy = function (sAggregationName) { return this._bRenderedFirstTime && this._aAggregationProxy.hasOwnProperty(sAggregationName); }; ObjectPageSubSection.prototype._getAggregation = function (sAggregationName) { return this._aAggregationProxy[sAggregationName]; }; ObjectPageSubSection.prototype._setAggregation = function (sAggregationName, aValue) { this._aAggregationProxy[sAggregationName] = aValue; this._notifyObjectPageLayout(); this.invalidate(); return this._aAggregationProxy[sAggregationName]; }; ObjectPageSubSection.prototype.addAggregation = function (sAggregationName, oObject) { var aAggregation; if (this.hasProxy(sAggregationName)) { aAggregation = this._getAggregation(sAggregationName); aAggregation.push(oObject); this._setAggregation(aAggregation); if (oObject instanceof BlockBase) { oObject.setParent(this); //let the block know of its parent subsection } return this; } return ObjectPageSectionBase.prototype.addAggregation.apply(this, arguments); }; ObjectPageSubSection.prototype.insertAggregation = function (sAggregationName, oObject, iIndex) { if (this.hasProxy(sAggregationName)) { jQuery.sap.log.warning("ObjectPageSubSection :: used of insertAggregation for " + sAggregationName + " is not supported, will use addAggregation instead"); return this.addAggregation(sAggregationName, oObject); } return ObjectPageSectionBase.prototype.insertAggregation.apply(this, arguments); }; ObjectPageSubSection.prototype.removeAllAggregation = function (sAggregationName) { var aInternalAggregation, aItems; if (this.hasProxy(sAggregationName)) { aInternalAggregation = this._getAggregation(sAggregationName); aItems = aInternalAggregation.slice(0, aInternalAggregation.length - 1); this._setAggregation(sAggregationName, []); return aItems; } return ObjectPageSectionBase.prototype.removeAllAggregation.apply(this, arguments); }; ObjectPageSubSection.prototype.removeAggregation = function (sAggregationName, oObject) { var bRemoved = false, aInternalAggregation; if (this.hasProxy(sAggregationName)) { aInternalAggregation = this._getAggregation(sAggregationName); aInternalAggregation.forEach(function (oObjectCandidate, iIndex) { if (oObjectCandidate.getId() === oObject.getId()) { aInternalAggregation.splice(iIndex, 1); this._setAggregation(aInternalAggregation); bRemoved = true; } return !bRemoved; }, this); return (bRemoved ? oObject : null); } return ObjectPageSectionBase.prototype.removeAggregation.apply(this, arguments); }; ObjectPageSubSection.prototype.indexOfAggregation = function (sAggregationName, oObject) { var iIndexFound = -1; if (this.hasProxy(sAggregationName)) { this._getAggregation(sAggregationName).some(function (oObjectCandidate, iIndex) { if (oObjectCandidate.getId() === oObject.getId()) { iIndexFound = iIndex; return true; } }, this); return iIndexFound; } return ObjectPageSectionBase.prototype.indexOfAggregation.apply(this, arguments); }; ObjectPageSubSection.prototype.getAggregation = function (sAggregationName) { if (this.hasProxy(sAggregationName)) { return this._getAggregation(sAggregationName); } return ObjectPageSectionBase.prototype.getAggregation.apply(this, arguments); }; ObjectPageSubSection.prototype.destroyAggregation = function (sAggregationName) { if (this.hasProxy(sAggregationName)) { this._getAggregation(sAggregationName).forEach(function (object) { object.destroy(); }); this._setAggregation(sAggregationName, []); return this; } return ObjectPageSectionBase.prototype.destroyAggregation.apply(this, arguments); }; /************************************************************************************* * Private section : should overridden with care ************************************************************************************/ /** * build the control that will used internally for the see more / see less * @private */ ObjectPageSubSection.prototype._getSeeMoreButton = function () { if (!this._oSeeMoreButton) { this._oSeeMoreButton = new Button(this.getId() + "--seeMore", { type: sap.m.ButtonType.Transparent, iconFirst: false }).addStyleClass("sapUxAPSubSectionSeeMoreButton").attachPress(this._seeMoreLessControlPressHandler, this); } return this._oSeeMoreButton; }; /** * called when a user clicks on the see more or see all button * @param oEvent * @private */ ObjectPageSubSection.prototype._seeMoreLessControlPressHandler = function (oEvent) { var sCurrentMode = this.getMode(), sTargetMode, aMoreBlocks = this.getMoreBlocks() || []; //we just switch the layoutMode for the underlying blocks if (sCurrentMode === ObjectPageSubSectionMode.Expanded) { sTargetMode = ObjectPageSubSectionMode.Collapsed; } else {/* we are in Collapsed */ sTargetMode = ObjectPageSubSectionMode.Expanded; aMoreBlocks.forEach(function (oBlock) { if (oBlock instanceof BlockBase) { oBlock.setMode(sCurrentMode); oBlock.connectToModels(); } }, this); } this._switchSubSectionMode(sTargetMode); //in case of the last subsection of an objectpage we need to compensate its height change while rerendering) if (this._$spacer.length > 0) { this._$spacer.height(this._$spacer.height() + this.$().height()); } //need to re-render the subsection in order to render all the blocks with the appropriate mode & layout //0000811842 2014 this.rerender(); }; /** * switch the state for the subsection * @param sSwitchToMode * @private */ ObjectPageSubSection.prototype._switchSubSectionMode = function (sSwitchToMode) { sSwitchToMode = this.validateProperty("mode", sSwitchToMode); if (sSwitchToMode === ObjectPageSubSectionMode.Collapsed) { this.setProperty("mode", ObjectPageSubSectionMode.Collapsed, true); this._getSeeMoreButton().setText(library.i18nModel.getResourceBundle().getText("SEE_MORE")); } else { this.setProperty("mode", ObjectPageSubSectionMode.Expanded, true); this._getSeeMoreButton().setText(library.i18nModel.getResourceBundle().getText("SEE_LESS")); } }; /** * set the mode on a control if there is such mode property * @param oBlock * @param sMode * @private */ ObjectPageSubSection.prototype._setBlockMode = function (oBlock, sMode) { if (oBlock instanceof BlockBase) { oBlock.setMode(sMode); } else { jQuery.sap.log.debug("ObjectPageSubSection :: cannot propagate mode " + sMode + " to " + oBlock.getMetadata().getName()); } }; ObjectPageSubSection.prototype._setToFocusable = function (bFocusable) { var sFocusable = '0', sNotFocusable = '-1', sTabIndex = "tabIndex"; if (bFocusable) { this.$().attr(sTabIndex, sFocusable); } else { this.$().attr(sTabIndex, sNotFocusable); } return this; }; ObjectPageSubSection.prototype._getUseTitleOnTheLeft = function () { var oObjectPageLayout = this._getObjectPageLayout(); return oObjectPageLayout.getSubSectionLayout() === ObjectPageSubSectionLayout.TitleOnLeft; }; /** * If this is the first rendering and a layout has been defined by the subsection developer, * We remove it and let the built-in mechanism decide on the layouting aspects * @param aBlocks * @private */ ObjectPageSubSection.prototype._resetLayoutData = function (aBlocks) { aBlocks.forEach(function (oBlock) { if (!this._bRenderedFirstTime && oBlock.getLayoutData()) { oBlock.destroyLayoutData(); jQuery.sap.log.warning("ObjectPageSubSection :: forbidden use of layoutData for block " + oBlock.getMetadata().getName(), "layout will be set by subSection"); } }, this); }; ObjectPageSubSection.prototype.getVisibleBlocksCount = function () { var iVisibleBlocks = 0; (this.getBlocks() || []).forEach(function (oBlock) { if (oBlock.getVisible && !oBlock.getVisible()) { return true; } iVisibleBlocks++; }); (this.getMoreBlocks() || []).forEach(function (oMoreBlock) { if (oMoreBlock.getVisible && !oMoreBlock.getVisible()) { return true; } iVisibleBlocks++; }); return iVisibleBlocks; }; return ObjectPageSubSection; }); }; // end of sap/uxap/ObjectPageSubSection.js if ( !jQuery.sap.isDeclared('sap.uxap.component.ObjectPageLayoutUXDrivenFactory.controller') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.component.ObjectPageLayoutUXDrivenFactory.controller'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.layout.GridData'); // unlisted dependency retained jQuery.sap.require('sap.ui.model.BindingMode'); // unlisted dependency retained jQuery.sap.require('sap.ui.model.Context'); // unlisted dependency retained jQuery.sap.require('sap.ui.base.ManagedObject'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.mvc.Controller'); // unlisted dependency retained sap.ui.define("sap/uxap/component/ObjectPageLayoutUXDrivenFactory.controller",[ "sap/ui/layout/GridData", "sap/ui/model/BindingMode", "sap/uxap/BlockBase", "sap/uxap/ModelMapping", "sap/ui/model/Context", "sap/ui/base/ManagedObject", "sap/ui/core/mvc/Controller" ], function (GridData, BindingMode, BlockBase, ModelMapping, Context, ManagedObject, Controller) { "use strict"; return Controller.extend("sap.uxap.component.ObjectPageLayoutUXDrivenFactory", { /** * injects the header based on configuration * @param {object} oModel model instanse */ connectToComponent: function (oModel) { var bHasPendingRequest = jQuery.isEmptyObject(oModel.getData()); //ensure a 1 way binding otherwise it cause any block property change to update the entire subSections oModel.setDefaultBindingMode(BindingMode.OneWay); var fnHeaderFactory = jQuery.proxy(function () { if (bHasPendingRequest) { oModel.detachRequestCompleted(fnHeaderFactory); } var oHeaderTitleContext = new Context(oModel, "/headerTitle"), oObjectPageLayout = this.getView().byId("ObjectPageLayout"); //create the header title if provided in the config if (oHeaderTitleContext.getProperty("")) { try { //retrieve the header class this._oHeader = this.controlFactory(oObjectPageLayout.getId(), oHeaderTitleContext); oObjectPageLayout.setHeaderTitle(this._oHeader); } catch (sError) { jQuery.sap.log.error("ObjectPageLayoutFactory :: error in header creation from config: " + sError); } } }, this); //if data are not there yet, we wait for them if (bHasPendingRequest) { oModel.attachRequestCompleted(fnHeaderFactory); } else { //otherwise we apply the header factory immediately fnHeaderFactory(); } }, /** * generates a control to be used in actions, blocks or moreBlocks aggregations * known issue: bindings are not applied, the control is built with data only * @param {string} sParentId the Id of the parent * @param {object} oBindingContext binding context * @returns {*} new control */ controlFactory: function (sParentId, oBindingContext) { var oControlInfo = oBindingContext.getProperty(""), oControl, oControlClass, oControlMetadata; try { //retrieve the block class jQuery.sap.require(oControlInfo.Type); oControlClass = jQuery.sap.getObject(oControlInfo.Type); oControlMetadata = oControlClass.getMetadata(); //pre-processing: substitute event handler as strings by their function instance jQuery.each(oControlMetadata._mAllEvents, jQuery.proxy(function (sEventName, oEventProperties) { if (typeof oControlInfo[sEventName] == "string") { oControlInfo[sEventName] = this.convertEventHandler(oControlInfo[sEventName]); } }, this)); //creates the control with control info = create with provided properties oControl = ManagedObject.create(oControlInfo); //post-processing: bind properties on the objectPageLayoutMetadata model jQuery.each(oControlMetadata._mAllProperties, jQuery.proxy(function (sPropertyName, oProperty) { if (oControlInfo[sPropertyName]) { oControl.bindProperty(sPropertyName, "objectPageLayoutMetadata>" + oBindingContext.getPath() + "/" + sPropertyName); } }, this)); } catch (sError) { jQuery.sap.log.error("ObjectPageLayoutFactory :: error in control creation from config: " + sError); } return oControl; }, /** * determine the static function to use from its name * @param {string} sStaticHandlerName the name of the handler * @returns {*|window|window} function */ convertEventHandler: function (sStaticHandlerName) { var fnNameSpace = window, aNameSpaceParts = sStaticHandlerName.split('.'); try { jQuery.each(aNameSpaceParts, function (iIndex, sNameSpacePart) { fnNameSpace = fnNameSpace[sNameSpacePart]; }); } catch (sError) { jQuery.sap.log.error("ObjectPageLayoutFactory :: undefined event handler: " + sStaticHandlerName + ". Did you forget to require its static class?"); fnNameSpace = undefined; } return fnNameSpace; } }); }, /* bExport= */ true); }; // end of sap/uxap/component/ObjectPageLayoutUXDrivenFactory.controller.js if ( !jQuery.sap.isDeclared('sap.uxap.LazyLoading') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.LazyLoading'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained jQuery.sap.require('sap.ui.base.Metadata'); // unlisted dependency retained sap.ui.define("sap/uxap/LazyLoading",["jquery.sap.global", "sap/ui/Device", "sap/ui/base/Metadata", "./ObjectPageSubSection"], function (jQuery, Device, Metadata, ObjectPageSubSection) { "use strict"; var LazyLoading = Metadata.createClass("sap.uxap._helpers.LazyLoading", { /** * @private * @param {*} oObjectPageLayout Object Layout instance */ constructor: function (oObjectPageLayout) { this._oObjectPageLayout = oObjectPageLayout; this._$html = jQuery("html"); this._iPreviousScrollTop = 0; //scroll top of the last scroll event this._iScrollProgress = 0; //progress done between the 2 last scroll events this._iPreviousScrollTimestamp = 0; //Timestamp of the last scroll event this._sLazyLoadingTimer = null; this.setLazyLoadingParameters(); } }); /** * Set the lazy loading tuning parameters. */ LazyLoading.prototype.setLazyLoadingParameters = function () { //delay before loading data for visible sub-sections //this delay avoid loading data for every subsections during scroll this.LAZY_LOADING_DELAY = 200; //ms. //lazy loading fine tuning //An extra non visible subsection will be loaded if the the top of this subsection is at //no more than LAZY_LOADING_EXTRA_PAGE_SIZE * page height from the the bottom of the page. this.LAZY_LOADING_EXTRA_PAGE_SIZE = 0.5; //number of subsections which should be preloaded : // - FirstRendering : for first loading // - ScrollToSection : default value when scrolling to a subsection if (this._isPhone()) { this.NUMBER_OF_SUBSECTIONS_TO_PRELOAD = {"FirstRendering": 1, "ScrollToSection": 1}; } else if (this._isTablet()) { //on tablet scrolling may be slow. this.NUMBER_OF_SUBSECTIONS_TO_PRELOAD = {"FirstRendering": 2, "ScrollToSection": 1}; } else if (this._isTabletSize()) { //Desktop with a "tablet" window size this.NUMBER_OF_SUBSECTIONS_TO_PRELOAD = {"FirstRendering": 2, "ScrollToSection": 2}; } else { this.NUMBER_OF_SUBSECTIONS_TO_PRELOAD = {"FirstRendering": 3, "ScrollToSection": 3}; } //Threshold beyond which we consider that user is scrolling fast and thus that lazy loading must be differed. //(percentage of the pageheight). this.LAZY_LOADING_FAST_SCROLLING_THRESHOLD = 5; }; LazyLoading.prototype.lazyLoadDuringScroll = function (iScrollTop, timeStamp, iPageHeight) { var iProgressPercentage, iDelay, bFastScrolling = false; this._iScrollProgress = iScrollTop - this._iPreviousScrollTop; iProgressPercentage = Math.round(Math.abs(this._iScrollProgress) / iPageHeight * 100); if (iProgressPercentage >= this.LAZY_LOADING_FAST_SCROLLING_THRESHOLD) { bFastScrolling = true; } this._iPreviousScrollTop = iScrollTop; this._iPreviousScrollTimestamp = timeStamp || 0; iDelay = (iScrollTop === 0 ) ? 0 : this.LAZY_LOADING_DELAY; //if we are scrolling fast, clear the previous delayed lazy loading call if any //as we don't want to load intermediate subsections which are visible only //during a brief moment during scroll. if (bFastScrolling && this._sLazyLoadingTimer) { jQuery.sap.log.debug("ObjectPageLayout :: lazyLoading", "delayed by " + iDelay + " ms because of fast scroll"); jQuery.sap.clearDelayedCall(this._sLazyLoadingTimer); this._sLazyLoadingTimer = null; } //If there's no delayed lazy loading call, create a new one. if (!this._sLazyLoadingTimer) { this._sLazyLoadingTimer = jQuery.sap.delayedCall(iDelay, this, this.doLazyLoading); } }; LazyLoading.prototype.doLazyLoading = function () { var oHeightParams = this._oObjectPageLayout._getHeightRelatedParameters(), oSectionInfo = this._oObjectPageLayout._oSectionInfo, iScrollTop, iScrollPageBottom, iPageHeight, bShouldStick = this._iPreviousScrollTop >= (oHeightParams.iHeaderContentHeight), // iHeaderContentHeight sExtraSubSectionId, iExtraSubSectionTop = -1, oSubSectionsToLoad = {}, iTimeDifference, bOnGoingScroll, iShift; //calculate the limit of visible sections to be lazy loaded iPageHeight = ( oHeightParams.iScreenHeight /* the total screen height */ - (bShouldStick ? oHeightParams.iAnchorBarHeight : 0) /* minus the part taken by the anchor bar (when sticky)*/ - (bShouldStick ? oHeightParams.iHeaderTitleHeightStickied : 0) /* minus the part taken by the header title (mandatory) */ ); iScrollTop = oHeightParams.iScrollTop; //we consider that the scroll is still ongoing if: // - a scroll event has been received for less than half of the LAZY_LOADING_DELAY (100 ms) // - progress done between the last 2 scroll event is greater than 5 pixels. iTimeDifference = Date.now() - this._iPreviousScrollTimestamp; bOnGoingScroll = (iTimeDifference < (this.LAZY_LOADING_DELAY / 2) ) && (Math.abs(this._iScrollProgress) > 5); // if scroll is ongoing, we shift the pages top and height to: // - avoid loading subsections which will likely no more be visible at the end of scroll // (Next lazyLoading calls will anyway load them if they are still visible at the end of scroll) // - load in advance subsections which will likely be visible at the end of scroll if (bOnGoingScroll) { if (this._iScrollProgress >= 0) { iShift = Math.round(Math.min(this._iScrollProgress * 20, iPageHeight / 2)); } else { iShift = -1 * Math.round(Math.min(Math.abs(this._iScrollProgress) * 20, iPageHeight / 2)); } iScrollTop += iShift; jQuery.sap.log.debug("ObjectPageLayout :: lazyLoading", "Visible page shifted from : " + iShift); } iScrollPageBottom = iScrollTop + iPageHeight; //the bottom limit //don't load subsections which are hardly visible at the top of the page (less than 16 pixels visible) //to avoid having the following subsections moving downward as subsection size will likely increase during loading iScrollTop += 16; //check the visible subsections //only consider subsections not yet loaded jQuery.each(oSectionInfo, jQuery.proxy(function (sId, oInfo) { // on desktop/tablet, find a section, not a subsection if (!oInfo.isSection && !oInfo.loaded && oInfo.sectionReference.getParent().getVisible()) { // 1D segment intersection between visible page and current sub section // C <= B and A <= D -> intersection // A-----B // C---D // C----D // C-D // C-----------D if (oInfo.positionTop <= iScrollPageBottom && iScrollTop < oInfo.positionBottom - 1) { oSubSectionsToLoad[sId] = sId; // Lazy loading will add an extra subsection : // the first (highest) subsection not yet visible (and not yet loaded) // top of this subsection must be close from page bottom (less than 0.5 page : LAZY_LOADING_EXTRA_PAGE_SIZE) } else if (oInfo.positionTop > iScrollPageBottom && oInfo.positionTop < iScrollPageBottom + iPageHeight * this.LAZY_LOADING_EXTRA_PAGE_SIZE && (iExtraSubSectionTop == -1 || oInfo.positionTop < iExtraSubSectionTop)) { iExtraSubSectionTop = oInfo.positionTop; sExtraSubSectionId = sId; } } }, this)); //add the extra subsection if: // - we have found one // - we have no visible subsections to load if (iExtraSubSectionTop != -1 && jQuery.isEmptyObject(oSubSectionsToLoad)) { jQuery.sap.log.debug("ObjectPageLayout :: lazyLoading", "extra section added : " + sExtraSubSectionId); oSubSectionsToLoad[sExtraSubSectionId] = sExtraSubSectionId; } //Load the subsections jQuery.each(oSubSectionsToLoad, jQuery.proxy(function (idx, sSectionId) { jQuery.sap.log.debug("ObjectPageLayout :: lazyLoading", "connecting " + sSectionId); sap.ui.getCore().byId(sSectionId).connectToModels(); oSectionInfo[sSectionId].loaded = true; }, this)); if (bOnGoingScroll) { //bOnGoingScroll is just a prediction, we can't be 100% sure as there's no end-of-scroll event //so we relaunch a new delayed lazy loading to ensure all visible //sections will actually be loaded (no shift) if scroll stops suddenly. this._sLazyLoadingTimer = jQuery.sap.delayedCall(this.LAZY_LOADING_DELAY, this, this.doLazyLoading); } else { if (iExtraSubSectionTop) { //An extra subsection has been found //relaunch a delayed lazy loading call to check if there's another extra subsection to load //We use a long delay (5* LAZY_LOADING_DELAY) to wait for current loading completion. this._sLazyLoadingTimer = jQuery.sap.delayedCall(5 * this.LAZY_LOADING_DELAY, this, this.doLazyLoading); } else { //reset the lazy loading timer this._sLazyLoadingTimer = null; } } }; /** * Load in advance the subsections which will likely be visible once the operation (firstRendering or scrolltoSection) * will be complete. * @private * @param {*} aAllSections all sections * @param {*} sId id of the section * @returns {*} sections to preload */ LazyLoading.prototype.getSubsectionsToPreload = function (aAllSections, sId) { var iSubsectionsToPreLoad, bTargetSubsectionReached; //if no sId, target section is the first section (first rendering). if (sId) { iSubsectionsToPreLoad = this.NUMBER_OF_SUBSECTIONS_TO_PRELOAD.ScrollToSection; bTargetSubsectionReached = false; } else { iSubsectionsToPreLoad = this.NUMBER_OF_SUBSECTIONS_TO_PRELOAD.FirstRendering; bTargetSubsectionReached = true; } var aSectionsToPreload = []; aAllSections.some(function (oSection) { if (!bTargetSubsectionReached && sId) { bTargetSubsectionReached = oSection.getId() == sId; } if (bTargetSubsectionReached && oSection instanceof ObjectPageSubSection) { if (oSection.getVisible() && oSection._getInternalVisible()) { aSectionsToPreload.push(oSection); iSubsectionsToPreLoad--; } } return iSubsectionsToPreLoad <= 0; }); return aSectionsToPreload; }; LazyLoading.prototype._isPhone = function () { return this._$html.hasClass("sapUiMedia-Std-Phone") || Device.system.phone; }; LazyLoading.prototype._isTablet = function () { return Device.system.tablet; }; LazyLoading.prototype._isTabletSize = function () { return this._$html.hasClass("sapUiMedia-Std-Tablet"); }; return LazyLoading; }, /* bExport= */ false); }; // end of sap/uxap/LazyLoading.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageLayout') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.uxap.ObjectPageLayout. jQuery.sap.declare('sap.uxap.ObjectPageLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.ResizeHandler'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.CustomData'); // unlisted dependency retained jQuery.sap.require('sap.ui.Device'); // unlisted dependency retained jQuery.sap.require('sap.ui.core.delegate.ScrollEnablement'); // unlisted dependency retained jQuery.sap.require('sap.uxap.ObjectPageSubSectionLayout'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageLayout",[ "jquery.sap.global", "sap/ui/core/ResizeHandler", "sap/ui/core/Control", "sap/ui/core/CustomData", "sap/ui/Device", "sap/ui/core/delegate/ScrollEnablement", "./ObjectPageSubSection", "./ObjectPageSubSectionLayout", "./LazyLoading", "./ObjectPageLayoutABHelper", "./library" ], function (jQuery, ResizeHandler, Control, CustomData, Device, ScrollEnablement, ObjectPageSubSection, ObjectPageSubSectionLayout, LazyLoading, ABHelper, library) { "use strict"; /** * Constructor for a new ObjectPageLayout. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * An ObjectPageLayout is the layout control, used to put together all parts of an Object page - Header, Navigation bar and Sections/Subsections. * @extends sap.ui.core.Control * * @author SAP SE * * @constructor * @public * @alias sap.uxap.ObjectPageLayout * @since 1.26 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectPageLayout = Control.extend("sap.uxap.ObjectPageLayout", /** @lends sap.uxap.ObjectPageLayout.prototype */ { metadata: { library: "sap.uxap", properties: { /** * Determines whether the Navigation bar (Anchor bar) is displayed. */ showAnchorBar: {type: "boolean", defaultValue: true}, /** * Determines whether to show a Popover with Subsection links when clicking on Section links in the Anchor bar. */ showAnchorBarPopover: {type: "boolean", defaultValue: true}, /** * Determines whether the Anchor bar items are displayed in upper case. */ upperCaseAnchorBar: {type: "boolean", defaultValue: true}, /** * Determines the height of the ObjectPage. */ height: {type: "sap.ui.core.CSSSize", defaultValue: "100%"}, /** * Enable lazy loading for the Object page Subsections. */ enableLazyLoading: {type: "boolean", defaultValue: false}, /** * Determines whether Subsection titles are displayed on top or to the left of the Subsection content. */ subSectionLayout: { type: "sap.uxap.ObjectPageSubSectionLayout", defaultValue: ObjectPageSubSectionLayout.TitleOnTop }, /** * Use sap.m.IconTabBar instead of the default Anchor bar */ useIconTabBar: {type: "boolean", group: "Misc", defaultValue: false}, /** * Determines the visibility of the Header content (headerContent aggregation). */ showHeaderContent: {type: "boolean", group: "Misc", defaultValue: true}, /** * Determines whether the to use two column layout for the L screen size. */ useTwoColumnsForLargeScreen: {type: "boolean", group: "Appearance", defaultValue: false}, /** * Determines whether the title, image, markers and selectTitleArrow are shown in the Header content area. */ showTitleInHeaderContent: {type: "boolean", group: "Appearance", defaultValue: false}, /** * Determines whether sections and subsections with importance Low and Medium are hidden even on large screens. * @since 1.32.0 */ showOnlyHighImportance: {type: "boolean", group: "Behavior", defaultValue: false}, /** * Determines whether the page is a child page and renders it with a different design. * Child pages have an additional (darker/lighter) stripe on the left side of their header content area. * @since 1.34.0 */ isChildPage: {type: "boolean", group: "Appearance", defaultValue: false}, /** * Determines whether Header Content will always be expanded on desktop. * @since 1.34.0 */ alwaysShowContentHeader: {type: "boolean", group: "Behavior", defaultValue: false}, /** * Determines whether an Edit button will be shown in Header Content. * @since 1.34.0 */ showEditHeaderButton: {type: "boolean", group: "Behavior", defaultValue: false}, /** * Specifies whether the object page enables flexibility features, such as hiding and adding sections.<br> * For more information about SAPUI5 flexibility, refer to the Developer Guide. * @since 1.34.0 */ flexEnabled: {type: "boolean", group: "Misc", defaultValue: false} }, defaultAggregation: "sections", aggregations: { /** * The sections that make up the Object page content area. */ sections: {type: "sap.uxap.ObjectPageSection", multiple: true, singularName: "section"}, /** * Object page header title - the upper, always static, part of the Object page header. */ headerTitle: {type: "sap.uxap.ObjectPageHeader", multiple: false}, /** * Object page header content - the dynamic part of the Object page header. */ headerContent: {type: "sap.ui.core.Control", multiple: true, singularName: "headerContent"}, /** * Internal aggregation to hold the reference to the AnchorBar. */ _anchorBar: {type: "sap.uxap.AnchorBar", multiple: false, visibility: "hidden"}, /** * Internal aggregation to hold the reference to the IconTabBar. */ _iconTabBar: {type: "sap.m.IconTabBar", multiple: false, visibility: "hidden"}, /** * Internal aggregation to hold the reference to the ObjectPageHeaderContent. */ _headerContent: {type: "sap.uxap.ObjectPageHeaderContent", multiple: false, visibility: "hidden"} }, events: { /** * The event is fired when the Anchor bar is switched from moving to fixed or the other way round. */ toggleAnchorBar: { parameters: { /** * False indicates that the Anchor bar has just detached from the Header and became part of the scrolling area. True means that the Anchor bar has just snapped to the Header. */ fixed: {type: "boolean"} } }, /** * The event is fired when the Edit Header button is pressed */ editHeaderButtonPress: {} }, designTime: true } }); /************************************************************************************* * life cycle management ************************************************************************************/ ObjectPageLayout.prototype.init = function () { // lazy loading this._bFirstRendering = true; this._bDomReady = false; //dom is fully ready to be inspected this._bStickyAnchorBar = false; //status of the header this._iStoredScrollPosition = 0; // anchorbar management this._bInternalAnchorBarVisible = true; this._$opWrapper = []; //dom reference to the header for Dark mode background image scrolling scenario this._$anchorBar = []; //dom reference to the anchorBar this._$headerTitle = []; //dom reference to the header title this._$stickyAnchorBar = []; //dom reference to the sticky anchorBar this._$headerContent = []; //dom reference to the headerContent this._$stickyHeaderContent = []; //dom reference to the stickyHeaderContent // header animation && anchor bar management this._bMobileScenario = false; //are we in a mobile scenario or the desktop one? this._oSectionInfo = {}; //register some of the section info sSectionId:{offset,buttonClone} for updating the anchorbar accordingly this._aSectionBases = []; //hold reference to all sections and subsections alike (for perf reasons) this._sScrolledSectionId = ""; //section id that is currently scrolled this._iScrollToSectionDuration = 600; //ms this._$spacer = []; //dom reference to the bottom padding spacing this.iHeaderContentHeight = 0; // original height of the header content this.iStickyHeaderContentHeight = 0; // original height of the sticky header content this.iHeaderTitleHeight = 0; // original height of the header title this.iHeaderTitleHeightStickied = 0; // height of the header title when stickied (can be different from the collapsed height because of isXXXAlwaysVisible options or text wrapping) this.iAnchorBarHeight = 0; // original height of the anchorBar this.iTotalHeaderSize = 0; // total size of headerTitle + headerContent this._iResizeId = ResizeHandler.register(this, this._onUpdateScreenSize.bind(this)); this._oLazyLoading = new LazyLoading(this); this._oABHelper = new ABHelper(this); }; /** * update the anchor bar content accordingly to the section info and enable the lazy loading of the first visible sections */ ObjectPageLayout.prototype.onBeforeRendering = function () { if (!this.getVisible()) { return; } this._bMobileScenario = library.Utilities.isPhoneScenario(); this._bTabletScenario = library.Utilities.isTabletScenario(); // if we have Header Content on a desktop, check if it is always expanded this._bHContentAlwaysExpanded = this._checkAlwaysShowContentHeader(); this._initializeScroller(); this._storeScrollLocation(); this._getHeaderContent().setContentDesign(this._getHeaderDesign()); this._oABHelper._getAnchorBar().setUpperCase(this.getUpperCaseAnchorBar()); this._applyUxRules(); // If we are on the first true rendering : first time we render the page with section and blocks if (!jQuery.isEmptyObject(this._oSectionInfo) && this._bFirstRendering) { this._preloadSectionsOnBeforeFirstRendering(); this._bFirstRendering = false; } this._bStickyAnchorBar = false; //reset default state in case of re-rendering var oHeaderTitle = this.getHeaderTitle(); if (oHeaderTitle && oHeaderTitle.getAggregation("_expandButton")) { oHeaderTitle.getAggregation("_expandButton").attachPress(this._handleExpandButtonPress, this); } }; ObjectPageLayout.prototype._preloadSectionsOnBeforeFirstRendering = function () { var aToLoad; if (!this.getEnableLazyLoading()) { // In case we are not lazy loaded make sure that we connect the blocks properly... aToLoad = this.getUseIconTabBar() ? [this._oFirstVisibleSection] : this.getSections(); // for iconTabBar, load only the section that corresponds to first tab } else { //lazy loading, so connect first visible subsections var aSectionBasesToLoad = this.getUseIconTabBar() ? this._grepCurrentTabSectionBases() : this._aSectionBases; aToLoad = this._oLazyLoading.getSubsectionsToPreload(aSectionBasesToLoad); } this._connectModelsForSections(aToLoad); }; ObjectPageLayout.prototype._grepCurrentTabSectionBases = function () { var oFiltered = [], oSectionToLoad = this._oCurrentTabSection || this._oFirstVisibleSection; if (oSectionToLoad) { var sSectionToLoadId = oSectionToLoad.getId(); this._aSectionBases.forEach(function (oSection) { if (oSection.getParent().getId() === sSectionToLoadId) { oFiltered.push(oSection); } }); } return oFiltered; }; /************************************************************************************* * header & scroll management ************************************************************************************/ ObjectPageLayout.prototype.onAfterRendering = function () { this._ensureCorrectParentHeight(); this._cacheDomElements(); this._$opWrapper.on("scroll", this._onScroll.bind(this)); //the dom is already ready (re-rendering case), thus we compute the header immediately //in order to avoid flickering (see Incident 1570011343) if (this._bDomReady && this.$().parents(":hidden").length === 0) { this._onAfterRenderingDomReady(); } else { jQuery.sap.delayedCall(ObjectPageLayout.HEADER_CALC_DELAY, this, this._onAfterRenderingDomReady); } }; ObjectPageLayout.prototype._onAfterRenderingDomReady = function () { this._bDomReady = true; this._adjustHeaderHeights(); if (this.getUseIconTabBar()) { this._setCurrentTabSection(this._oStoredSection || this._oFirstVisibleSection); } this._initAnchorBarScroll(); this.getHeaderTitle() && this.getHeaderTitle()._shiftHeaderTitle(); this._setSectionsFocusValues(); this._restoreScrollPosition(); }; ObjectPageLayout.prototype.exit = function () { if (this._oScroller) { this._oScroller.destroy(); this._oScroller = null; } if (this._iResizeId) { ResizeHandler.deregister(this._iResizeId); } }; ObjectPageLayout.prototype.setShowOnlyHighImportance = function (bValue) { var bOldValue = this.getShowOnlyHighImportance(); if (bOldValue !== bValue) { this.setProperty("showOnlyHighImportance", bValue, true); this.getSections().forEach(function (oSection) { oSection._updateImportance(); }); } return this; }; ObjectPageLayout.prototype.setIsHeaderContentAlwaysExpanded = function (bValue) { var bOldValue = this.getAlwaysShowContentHeader(); var bSuppressInvalidate = (Device.system.phone || Device.system.tablet); if (bOldValue !== bValue) { this.setProperty("alwaysShowContentHeader", bValue, bSuppressInvalidate); } return this; }; ObjectPageLayout.prototype._initializeScroller = function () { if (this._oScroller) { return; } //Internal Incident: 1482023778: workaround BB10 = use zynga instead of iScroll var bEnforceZynga = (Device.os.blackberry && Device.os.version >= 10.0 && Device.os.version < 11.0); this._oScroller = new ScrollEnablement(this, this.getId() + "-scroll", { horizontal: false, vertical: true, zynga: bEnforceZynga, preventDefault: true, nonTouchScrolling: "scrollbar", scrollbarClass: "sapUxAPObjectPageScroll" }); }; /** * if our container has not set a height, we need to enforce it or nothing will get displayed * the reason is the objectPageLayout has 2 containers with position:absolute, height:100% * @private */ ObjectPageLayout.prototype._ensureCorrectParentHeight = function () { if (this._bCorrectParentHeightIsSet) { return; } /* BCP: 1670054830 - returned the original check here since it was breaking in a case where the object page was embedded in sap.m.Page, the sap.m.Page already had height 100%, but we set it to its content div where the ObjectPage is resulting in the sap.m.Page footer would float above some of the ObjectPage content. Its still a bit strange that we check for the framework controls parent's height, but then we apply height 100% to the direct dom parent. */ if (this.getParent().getHeight && ["", "auto"].indexOf(this.getParent().getHeight()) !== -1) { this.$().parent().css("height", "100%"); } this._bCorrectParentHeightIsSet = true; }; ObjectPageLayout.prototype._cacheDomElements = function () { this._$headerTitle = jQuery.sap.byId(this.getId() + "-headerTitle"); this._$anchorBar = jQuery.sap.byId(this.getId() + "-anchorBar"); this._$stickyAnchorBar = jQuery.sap.byId(this.getId() + "-stickyAnchorBar"); this._$opWrapper = jQuery.sap.byId(this.getId() + "-opwrapper"); this._$spacer = jQuery.sap.byId(this.getId() + "-spacer"); this._$headerContent = jQuery.sap.byId(this.getId() + "-headerContent"); this._$stickyHeaderContent = jQuery.sap.byId(this.getId() + "-stickyHeaderContent"); this._$contentContainer = jQuery.sap.byId(this.getId() + "-scroll"); }; /** * Handles the press of the expand header button * @private */ ObjectPageLayout.prototype._handleExpandButtonPress = function (oEvent) { this._expandCollapseHeader(true); }; /** * Toggles visual rules on manually expand or collapses the sticky header * @private */ ObjectPageLayout.prototype._toggleStickyHeader = function (bExpand) { this._bIsHeaderExpanded = bExpand; this._$headerTitle.toggleClass("sapUxAPObjectPageHeaderStickied", !bExpand); this._toggleHeaderStyleRules(!bExpand); }; /** * Expands or collapses the sticky header * @private */ ObjectPageLayout.prototype._expandCollapseHeader = function (bExpand) { var oHeaderTitle = this.getHeaderTitle(); if (this._bHContentAlwaysExpanded) { return; } if (bExpand && this._bStickyAnchorBar) { // if the title in the header is not always visible but the action buttons are there we have remove the padding of the action buttons if (oHeaderTitle && oHeaderTitle.getIsActionAreaAlwaysVisible() && !oHeaderTitle.getIsObjectTitleAlwaysVisible()) { oHeaderTitle._setActionsPaddingStatus(bExpand); } this._$headerContent.css("height", this.iHeaderContentHeight).children().appendTo(this._$stickyHeaderContent); // when removing the header content, preserve the height of its placeholder, to avoid automatic repositioning of scrolled content as it gets shortened (as its topmost part is cut off) this._toggleStickyHeader(bExpand); } else if (!bExpand && this._bIsHeaderExpanded) { this._$headerContent.css("height", "auto").append(this._$stickyHeaderContent.children()); this._$stickyHeaderContent.children().remove(); this._toggleStickyHeader(bExpand); } }; /************************************************************************************* * Ux rules ************************************************************************************/ /** * updates the objectPageLayout structure based on ux rules * This affects data! * @private * @param {boolean} bInvalidate request the invalidation of the sectionBase that would turn into visible or hidden. This may not be necessary if you are already within a rendering process. */ ObjectPageLayout.prototype._applyUxRules = function (bInvalidate) { var aSections, aSubSections, iVisibleSubSections, iVisibleSection, iVisibleBlocks, bVisibleAnchorBar, bVisibleIconTabBar, oFirstVisibleSection, oFirstVisibleSubSection; aSections = this.getSections() || []; iVisibleSection = 0; bVisibleAnchorBar = this.getShowAnchorBar(); bVisibleIconTabBar = this.getUseIconTabBar(); oFirstVisibleSection = null; this._cleanMemory(); aSections.forEach(function (oSection) { //ignore hidden sections if (!oSection.getVisible()) { return true; } this._registerSectionBaseInfo(oSection); aSubSections = oSection.getSubSections() || []; iVisibleSubSections = 0; oFirstVisibleSubSection = null; aSubSections.forEach(function (oSubSection) { //ignore hidden subSection if (!oSubSection.getVisible()) { return true; } this._registerSectionBaseInfo(oSubSection); iVisibleBlocks = oSubSection.getVisibleBlocksCount(); //rule noVisibleBlock: If a subsection has no visible content the subsection will be hidden. if (iVisibleBlocks === 0) { oSubSection._setInternalVisible(false, bInvalidate); jQuery.sap.log.info("ObjectPageLayout :: noVisibleBlock UX rule matched", "subSection " + oSubSection.getTitle() + " forced to hidden"); } else { oSubSection._setInternalVisible(true, bInvalidate); //if TitleOnTop.sectionGetSingleSubSectionTitle is matched, this will be hidden back oSubSection._setInternalTitleVisible(true, bInvalidate); iVisibleSubSections++; if (!oFirstVisibleSubSection) { oFirstVisibleSubSection = oSubSection; } } }, this); //rule noVisibleSubSection: If a section has no content (or only empty subsections) the section will be hidden. if (iVisibleSubSections == 0) { oSection._setInternalVisible(false, bInvalidate); jQuery.sap.log.info("ObjectPageLayout :: noVisibleSubSection UX rule matched", "section " + oSection.getTitle() + " forced to hidden"); } else { oSection._setInternalVisible(true, bInvalidate); oSection._setInternalTitleVisible(true, bInvalidate); if (!oFirstVisibleSection) { oFirstVisibleSection = oSection; } //rule TitleOnTop.sectionGetSingleSubSectionTitle: If a section as only 1 subsection and the subsection title is not empty, the section takes the subsection title on titleOnTop layout only if (this.getSubSectionLayout() === ObjectPageSubSectionLayout.TitleOnTop && iVisibleSubSections === 1 && oFirstVisibleSubSection.getTitle().trim() !== "") { jQuery.sap.log.info("ObjectPageLayout :: TitleOnTop.sectionGetSingleSubSectionTitle UX rule matched", "section " + oSection.getTitle() + " is taking its single subsection title " + oFirstVisibleSubSection.getTitle()); oSection._setInternalTitle(oFirstVisibleSubSection.getTitle(), bInvalidate); oFirstVisibleSubSection._setInternalTitleVisible(false, bInvalidate); } else { oSection._setInternalTitle("", bInvalidate); } iVisibleSection++; } if (bVisibleIconTabBar) { oSection._setInternalTitleVisible(false, bInvalidate); } }, this); //rule notEnoughVisibleSection: If there is only 1 section overall, the navigation control shall be hidden. if (iVisibleSection <= 1) { bVisibleAnchorBar = false; jQuery.sap.log.info("ObjectPageLayout :: notEnoughVisibleSection UX rule matched", "anchorBar forced to hidden"); //rule firstSectionTitleHidden: the first section title is never visible if there is an anchorBar } else if (oFirstVisibleSection && bVisibleAnchorBar) { oFirstVisibleSection._setInternalTitleVisible(false, bInvalidate); jQuery.sap.log.info("ObjectPageLayout :: firstSectionTitleHidden UX rule matched", "section " + oFirstVisibleSection.getTitle() + " title forced to hidden"); } // the AnchorBar needs to reflect the dom state if (bVisibleAnchorBar) { this._oABHelper._buildAnchorBar(); } this._setInternalAnchorBarVisible(bVisibleAnchorBar, bInvalidate); this._oFirstVisibleSection = oFirstVisibleSection; }; /************************************************************************************* * IconTabBar management ************************************************************************************/ /** * Overrides the setter for the useIconTabBar property * @param bValue * @returns this */ ObjectPageLayout.prototype.setUseIconTabBar = function (bValue) { var bOldValue = this.getUseIconTabBar(); if (bValue != bOldValue) { this._applyUxRules(); // UxRules contain logic that depends on whether we use iconTabBar or not } this.setProperty("useIconTabBar", bValue); return this; }; /** * Sets a new section to be displayed as currently selected tab * @param oSection * @private */ ObjectPageLayout.prototype._setCurrentTabSection = function (oSection) { if (!oSection) { return; } var oSubsection; if (oSection instanceof sap.uxap.ObjectPageSubSection) { oSubsection = oSection; oSection = oSection.getParent(); } else { oSubsection = this._getFirstVisibleSubSection(oSection); } if (this._oCurrentTabSection !== oSection) { this._renderSection(oSection); this._oCurrentTabSection = oSection; } this._oCurrentTabSubSection = oSubsection; }; /** * renders the given section in the ObjectPageContainer html element, without causing re-rendering of the ObjectPageLayout, * used for switching between sections, when the navigation is through IconTabBar * @param oSection * @private */ ObjectPageLayout.prototype._renderSection = function (oSection) { var $objectPageContainer = this.$().find(".sapUxAPObjectPageContainer"), oRm; if (oSection && $objectPageContainer.length) { oRm = sap.ui.getCore().createRenderManager(); oRm.renderControl(oSection); oRm.flush($objectPageContainer[0]);// place the section in the ObjectPageContainer } oRm.destroy(); }; /************************************************************************************* * anchor bar management ************************************************************************************/ ObjectPageLayout.prototype.setShowAnchorBarPopover = function (bValue, bSuppressInvalidate) { this._oABHelper._buildAnchorBar(); this._oABHelper._getAnchorBar().setShowPopover(bValue); return this.setProperty("showAnchorBarPopover", bValue, true /* don't re-render the whole objectPageLayout */); }; ObjectPageLayout.prototype._getInternalAnchorBarVisible = function () { return this._bInternalAnchorBarVisible; }; ObjectPageLayout.prototype._setInternalAnchorBarVisible = function (bValue, bInvalidate) { if (bValue != this._bInternalAnchorBarVisible) { this._bInternalAnchorBarVisible = bValue; if (bInvalidate === true) { this.invalidate(); } } }; ObjectPageLayout.prototype._adjustLayout = function (oEvent, bImmediate, bNeedLazyLoading) { //adjust the layout only if the object page is full ready if (!this._bDomReady) { return; } //postpone until we get requests if (this._iLayoutTimer) { jQuery.sap.log.debug("ObjectPageLayout :: _adjustLayout", "delayed by " + ObjectPageLayout.DOM_CALC_DELAY + " ms because of dom modifications"); jQuery.sap.clearDelayedCall(this._iLayoutTimer); } if (bImmediate) { this._updateScreenHeightSectionBasesAndSpacer(); this._iLayoutTimer = undefined; } else { //need to "remember" if one of the adjustLayout is requesting the lazyLoading this._bNeedLazyLoading = this._bNeedLazyLoading !== undefined || bNeedLazyLoading; this._iLayoutTimer = jQuery.sap.delayedCall(ObjectPageLayout.DOM_CALC_DELAY, this, function () { jQuery.sap.log.debug("ObjectPageLayout :: _adjustLayout", "re-evaluating dom positions"); this._updateScreenHeightSectionBasesAndSpacer(); //in case the layout has changed we need to re-evaluate the lazy loading if (this._bNeedLazyLoading) { this._oLazyLoading.doLazyLoading(); } this._bNeedLazyLoading = undefined; this._iLayoutTimer = undefined; }); } }; /** * adjust the layout but also the ux rules * used for refreshing the overall structure of the objectPageLayout when it as been updated after the first rendering * @private */ ObjectPageLayout.prototype._adjustLayoutAndUxRules = function () { //in case we have added a section or subSection which change the ux rules jQuery.sap.log.debug("ObjectPageLayout :: _adjustLayout", "refreshing ux rules"); /* obtain the currently selected section in the navBar before navBar is destroyed, in order to reselect that section after that navBar is reconstructed */ var sSelectedSectionId = this._getSelectedSectionId(); this._applyUxRules(true); var oSelectedSection = sap.ui.getCore().byId(sSelectedSectionId); /* check if the section that was previously selected is still available, as it might have been deleted, or emptied, or set to hidden in the previous step */ if (oSelectedSection && oSelectedSection.getVisible() && oSelectedSection._getInternalVisible()) { this._setSelectedSectionId(sSelectedSectionId); //reselect the current section in the navBar this._adjustLayout(null, false, true /* requires a check on lazy loading */); return; } /* the section that was previously selected is not available anymore, so we cannot reselect it; in that case we have to select the first visible section instead */ oSelectedSection = this._oFirstVisibleSection; if (oSelectedSection) { this.scrollToSection(oSelectedSection.getId()); } }; ObjectPageLayout.prototype._getSelectedSectionId = function () { var oAnchorBar = this.getAggregation("_anchorBar"), sSelectedSectionId; if (oAnchorBar && oAnchorBar.getSelectedSection()) { sSelectedSectionId = oAnchorBar.getSelectedSection().getId(); } return sSelectedSectionId; }; ObjectPageLayout.prototype._setSelectedSectionId = function (sSelectedSectionId) { var oAnchorBar = this.getAggregation("_anchorBar"), oSelectedSectionInfo = sSelectedSectionId && this._oSectionInfo[sSelectedSectionId]; if (!oSelectedSectionInfo) { return; } if (oAnchorBar && oSelectedSectionInfo.buttonId) { oAnchorBar.setSelectedButton(oSelectedSectionInfo.buttonId); } }; ObjectPageLayout.prototype.isFirstRendering = function () { return this._bFirstRendering; }; /** * clean the oSectionInfo and aSectionBases internal properties * as the oSectionInfo contains references to created objects, we make sure to destroy them properly in order to avoid memory leaks * @private */ ObjectPageLayout.prototype._cleanMemory = function () { var oAnchorBar = this.getAggregation("_anchorBar"); if (oAnchorBar) { oAnchorBar.destroyContent(); } this._oSectionInfo = {}; this._aSectionBases = []; }; /** * register the section within the internal property used for lazy loading and navigation * most of these properties are going to be updated later when the dom will be ready (positions) or when the anchorBar button will be created (buttonId) * @param oSectionBase the section to register * @private */ ObjectPageLayout.prototype._registerSectionBaseInfo = function (oSectionBase) { this._oSectionInfo[oSectionBase.getId()] = { $dom: [], positionTop: 0, positionTopMobile: 0, realTop: 0.0, buttonId: "", isSection: (oSectionBase instanceof library.ObjectPageSection), sectionReference: oSectionBase }; this._aSectionBases.push(oSectionBase); }; /** * Scrolls the Object page to the given Section. * * @param {string} sId The Section ID to scroll to * @param {int} iDuration Scroll duration (in ms). Default value is 0 * @param {int} iOffset Additional pixels to scroll * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ ObjectPageLayout.prototype.scrollToSection = function (sId, iDuration, iOffset) { var oSection = sap.ui.getCore().byId(sId); if (this.getUseIconTabBar()) { this._setCurrentTabSection(oSection); var oToSelect = oSection; if (oToSelect instanceof sap.uxap.ObjectPageSubSection) { oToSelect = oToSelect.getParent(); } this.getAggregation("_anchorBar").setSelectedButton(this._oSectionInfo[oToSelect.getId()].buttonId); } if (this._bIsHeaderExpanded) { this._expandCollapseHeader(false); } iOffset = iOffset || 0; oSection._expandSection(); //call _adjustLayout synchronously to make extra sure we have the right positionTops for all sectionBase before scrolling this._adjustLayout(null, true); iDuration = this._computeScrollDuration(iDuration, oSection); var iScrollTo = this._computeScrollPosition(oSection); //avoid triggering twice the scrolling onto the same target section if (this._sCurrentScrollId != sId) { this._sCurrentScrollId = sId; if (this._iCurrentScrollTimeout) { clearTimeout(this._iCurrentScrollTimeout); this._$contentContainer.parent().stop(true, false); } this._iCurrentScrollTimeout = jQuery.sap.delayedCall(iDuration, this, function () { this._sCurrentScrollId = undefined; this._iCurrentScrollTimeout = undefined; }); this._preloadSectionsOnScroll(oSection); this.getHeaderTitle() && this.getHeaderTitle()._shiftHeaderTitle(); this._scrollTo(iScrollTo + iOffset, iDuration); } }; ObjectPageLayout.prototype._computeScrollDuration = function (iAppSpecifiedDuration, oTargetSection) { var iDuration = parseInt(iAppSpecifiedDuration, 10); iDuration = iDuration >= 0 ? iDuration : this._iScrollToSectionDuration; if (this.getUseIconTabBar() && ((oTargetSection instanceof sap.uxap.ObjectPageSection) || this._isFirstVisibleSubSection(oTargetSection)) && this._bStickyAnchorBar) { // in this case we are only scrolling // a section from expanded to sticky position, // so the scrolling animation in not needed, instead it looks unnatural, so set a 0 duration iDuration = 0; } return iDuration; }; ObjectPageLayout.prototype._computeScrollPosition = function (oTargetSection) { var bFirstLevel = oTargetSection && (oTargetSection instanceof sap.uxap.ObjectPageSection), sId = oTargetSection.getId(); var iScrollTo = this._bMobileScenario || bFirstLevel ? this._oSectionInfo[sId].positionTopMobile : this._oSectionInfo[sId].positionTop; if (this.getUseIconTabBar() && ((oTargetSection instanceof sap.uxap.ObjectPageSection) || this._isFirstVisibleSubSection(oTargetSection)) && !this._bStickyAnchorBar) { // preserve expanded header if no need to stick iScrollTo -= this.iHeaderContentHeight; // scroll to the position where the header is still expanded } return iScrollTo; }; ObjectPageLayout.prototype._preloadSectionsOnScroll = function (oTargetSection) { var sId = oTargetSection.getId(), aToLoad; if (!this.getEnableLazyLoading() && this.getUseIconTabBar()) { aToLoad = (oTargetSection instanceof sap.uxap.ObjectPageSection) ? oTargetSection : oTargetSection.getParent(); this._connectModelsForSections([aToLoad]); } if (this.getEnableLazyLoading()) { //connect target subsection to avoid delay in data loading var oSectionBasesToLoad = this.getUseIconTabBar() ? this._grepCurrentTabSectionBases() : this._aSectionBases; aToLoad = this._oLazyLoading.getSubsectionsToPreload(oSectionBasesToLoad, sId); if (Device.system.desktop) { //on desktop we delay the call to have the preload done during the scrolling animation jQuery.sap.delayedCall(50, this, function () { this._connectModelsForSections(aToLoad); }); } else { //on device, do the preload first then scroll. //doing anything during the scrolling animation may //trouble animation and lazy loading on slow devices. this._connectModelsForSections(aToLoad); } } }; /** * Returns the UI5 ID of the Section that is currently being scrolled. * * @type string * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ ObjectPageLayout.prototype.getScrollingSectionId = function () { return this._sScrolledSectionId; }; /** * Set for reference the destination section of the ongoing scroll * When this one is set, then the page will skip intermediate sections [during the scroll from the current to the destination section] * and will scroll directly to the given section * @param sDirectSectionId - the section to be scrolled directly to */ ObjectPageLayout.prototype.setDirectScrollingToSection = function (sDirectSectionId) { this.sDirectSectionId = sDirectSectionId; }; /** * Get the destination section of the ongoing scroll * When this one is non-null, then the page will skip intermediate sections [during the scroll from the current to the destination section] * and will scroll directly to the given section * @param sDirectSectionId - the section to be scrolled directly to */ ObjectPageLayout.prototype.getDirectScrollingToSection = function () { return this.sDirectSectionId; }; /** * Clear the destination section of the ongoing scroll * When this one is null, then the page will process all intermediate sections [during the scroll to some Y position] * and select each one in sequence */ ObjectPageLayout.prototype.clearDirectScrollingToSection = function () { this.sDirectSectionId = null; }; /** * Scroll to the y position in dom * @param y the position in pixel * @param time the animation time * @private */ ObjectPageLayout.prototype._scrollTo = function (y, time) { if (this._oScroller) { jQuery.sap.log.debug("ObjectPageLayout :: scrolling to " + y); this._oScroller.scrollTo(0, y, time); } return this; }; /** * update the section dom reference * @private */ ObjectPageLayout.prototype._updateScreenHeightSectionBasesAndSpacer = function () { var iLastVisibleHeight, oLastVisibleSubSection, iSpacerHeight, sPreviousSubSectionId, sPreviousSectionId, iHeaderGap = 0; this.iScreenHeight = this.$().height(); if (this.iHeaderContentHeight && !this._bHContentAlwaysExpanded) { iHeaderGap = this.iHeaderTitleHeightStickied - this.iHeaderTitleHeight; } this._aSectionBases.forEach(function (oSectionBase) { var oInfo = this._oSectionInfo[oSectionBase.getId()], $this = oSectionBase.$(), $mobileAnchor; if (!oInfo /* sectionBase is visible */ || !$this.length) { return; } oInfo.$dom = $this; //calculate the scrollTop value to get the section title at the bottom of the header //performance improvements possible here as .position() is costly oInfo.realTop = $this.position().top; //first get the dom position = scrollTop to get the section at the window top var bHasTitle = (oSectionBase._getInternalTitleVisible() && (oSectionBase.getTitle().trim() !== "")); var bHasButtons = !oInfo.isSection && oSectionBase.getAggregation("actions").length > 0; if (!oInfo.isSection && !bHasTitle && !bHasButtons) { oInfo.realTop = $this.find(".sapUiResponsiveMargin.sapUxAPBlockContainer").position().top; } //the amount of scrolling required is the distance between their position().top and the bottom of the anchorBar oInfo.positionTop = Math.ceil(oInfo.realTop) - this.iAnchorBarHeight - iHeaderGap; //the amount of scrolling required for the mobile scenario //we want to navigate just below its title //as of UX specs Oct 7, 2014 if (oInfo.isSection) { $mobileAnchor = oSectionBase.$("header"); } else { $mobileAnchor = oSectionBase.$("headerTitle"); } //calculate the mobile position if ($mobileAnchor.length > 0) { oInfo.positionTopMobile = Math.ceil($mobileAnchor.position().top) + $mobileAnchor.outerHeight() - this.iAnchorBarHeight - iHeaderGap; } else { //title wasn't found (=first section, hidden title, promoted subsection), scroll to the same position as desktop oInfo.positionTopMobile = oInfo.positionTop; } //for calculating the currently scrolled section of subsection (and for lazy loading) we also need to know the bottom of the section and subsections //we can't use oInfo.$dom.height() since the margin are not taken into account. //therefore the most reliable calculation is to consider as a bottom, the top of the next section/subsection //on mobile, each section and subsection is considered equally (a section is a very tiny subsection containing only a title) if (this._bMobileScenario) { if (sPreviousSectionId) { //except for the very first section this._oSectionInfo[sPreviousSectionId].positionBottom = oInfo.positionTop; } sPreviousSectionId = oSectionBase.getId(); oLastVisibleSubSection = oSectionBase; } else { //on desktop, we update section by section (each section is resetting the calculation) //on a desktop the previous section bottom is the top of the current section if (oInfo.isSection) { if (sPreviousSectionId) { //except for the very first section this._oSectionInfo[sPreviousSectionId].positionBottom = oInfo.positionTop; this._oSectionInfo[sPreviousSubSectionId].positionBottom = oInfo.positionTop; } sPreviousSectionId = oSectionBase.getId(); sPreviousSubSectionId = null; } else { //on desktop, the previous subsection bottom is the top of the current subsection if (sPreviousSubSectionId) { //except for the very first subSection this._oSectionInfo[sPreviousSubSectionId].positionBottom = oInfo.positionTop; } sPreviousSubSectionId = oSectionBase.getId(); oLastVisibleSubSection = oSectionBase; } } }, this); //calculate the bottom spacer height and update the last section/subSection bottom (with our algorithm of having section tops based on the next section, we need to have a special handling for the very last subSection) if (oLastVisibleSubSection) { iLastVisibleHeight = this._$spacer.position().top - this._oSectionInfo[oLastVisibleSubSection.getId()].realTop; //on desktop we need to set the bottom of the last section as well if (this._bMobileScenario) { this._oSectionInfo[sPreviousSectionId].positionBottom = this._oSectionInfo[sPreviousSectionId].positionTop + iLastVisibleHeight; } else { //update the position bottom for the last subsection this._oSectionInfo[sPreviousSubSectionId].positionBottom = this._oSectionInfo[sPreviousSubSectionId].positionTop + iLastVisibleHeight; this._oSectionInfo[sPreviousSectionId].positionBottom = this._oSectionInfo[sPreviousSubSectionId].positionTop + iLastVisibleHeight; } //calculate the required additional space for the last section only if (iLastVisibleHeight < this.iScreenHeight) {// see if this line can be skipped if (this._isSpacerRequired(oLastVisibleSubSection, iLastVisibleHeight)) { //the amount of space required is what is needed to get the latest position you can scroll to up to the "top" //therefore we need to create enough space below the last subsection to get it displayed on top = the spacer //the "top" is just below the sticky header + anchorBar, therefore we just need enough space to get the last subsection below these elements //the latest position is below the last subsection title in case of a mobile scroll to the last subsection if (this.iHeaderContentHeight || this._bHContentAlwaysExpanded) { // Not always when we scroll the HeaderTitle is in Sticky position so instead of taking out its StickyHeight we have to take out its height and the HeaderGap, // which will be zero when the HeaderTitle is in normal mode iSpacerHeight = this.iScreenHeight - iLastVisibleHeight - this.iHeaderTitleHeight - iHeaderGap - this.iAnchorBarHeight; } else { iSpacerHeight = this.iScreenHeight - iLastVisibleHeight - this.iAnchorBarHeight; } //take into account that we may need to scroll down to the positionMobile, thus we need to make sure we have enough space at the bottom if (this._bMobileScenario) { iSpacerHeight += (this._oSectionInfo[oLastVisibleSubSection.getId()].positionTopMobile - this._oSectionInfo[oLastVisibleSubSection.getId()].positionTop); } } else { iSpacerHeight = 0; } this._$spacer.height(iSpacerHeight + "px"); jQuery.sap.log.debug("ObjectPageLayout :: bottom spacer is now " + iSpacerHeight + "px"); } } }; /* * Determines wheder spacer, after the last subsection, is needed on the screen. * The main reason for spacer to exist is to have enogth space for scrolling to the last section. */ ObjectPageLayout.prototype._isSpacerRequired = function (oLastVisibleSubSection, iLastVisibleHeight) { var oSelectedSection = this.getAggregation("_anchorBar").getSelectedSection(), bIconTabBarWithOneSectionAndOneSubsection = this.getUseIconTabBar() && oSelectedSection && oSelectedSection.getSubSections().length === 1, bOneSectionOneSubsection = this.getSections().length === 1 && this.getSections()[0].getSubSections().length === 1; // When there there is only one element the scrolling is not required so the spacer is redundant. if (bIconTabBarWithOneSectionAndOneSubsection || bOneSectionOneSubsection) { return false; } if (this._bStickyAnchorBar) { // UX Rule: if the user has scrolled to sticky anchorBar, keep it sticky i.e. do not expand the header *automatically* return true; } var bContentFitsViewport = ((this._oSectionInfo[oLastVisibleSubSection.getId()].realTop + iLastVisibleHeight) <= this.iScreenHeight); if (!bContentFitsViewport) { return true; } if (!this._isFirstVisibleSubSection(this._oCurrentTabSubSection)) { return true; } return false; }; ObjectPageLayout.prototype._isFirstVisibleSubSection = function (oSectionBase) { if (oSectionBase) { var oSectionInfo = this._oSectionInfo[oSectionBase.getId()]; if (oSectionInfo) { return oSectionInfo.realTop === (this.iAnchorBarHeight + this.iHeaderContentHeight); } } return false; }; ObjectPageLayout.prototype._getFirstVisibleSubSection = function (oSection) { if (!oSection) { return; } var oFirstSubSection; this._aSectionBases.every(function (oSectionBase) { if (oSectionBase.getParent() && (oSectionBase.getParent().getId() === oSection.getId())) { oFirstSubSection = oSectionBase; return false; } return true; }); return oFirstSubSection; }; /** * init the internal section info {positionTop} * @private */ ObjectPageLayout.prototype._initAnchorBarScroll = function () { this._adjustLayout(null, true); //reset the scroll to top for anchorbar & scrolling management this._sScrolledSectionId = ""; this._onScroll({target: {scrollTop: 0}});//make sure we got the very last scroll event even on slow devices }; /** * Set a given section as the currently scrolled section and update the anchorBar relatively * @param sSectionId the section id * @private */ ObjectPageLayout.prototype._setAsCurrentSection = function (sSectionId) { var oAnchorBar, oSectionBase, bShouldDisplayParentTitle; if (this._sScrolledSectionId === sSectionId) { return; } jQuery.sap.log.debug("ObjectPageLayout :: current section is " + sSectionId); this._sScrolledSectionId = sSectionId; oAnchorBar = this.getAggregation("_anchorBar"); if (oAnchorBar && this._getInternalAnchorBarVisible()) { oSectionBase = sap.ui.getCore().byId(sSectionId); bShouldDisplayParentTitle = oSectionBase && oSectionBase instanceof ObjectPageSubSection && (oSectionBase.getTitle().trim() === "" || !oSectionBase._getInternalTitleVisible() || oSectionBase.getParent()._getIsHidden()); //the sectionBase title needs to be visible (or the user won't "feel" scrolling that sectionBase but its parent) //see Incident 1570016975 for more details if (bShouldDisplayParentTitle) { sSectionId = oSectionBase.getParent().getId(); jQuery.sap.log.debug("ObjectPageLayout :: current section is a subSection with an empty or hidden title, selecting parent " + sSectionId); } if (this._oSectionInfo[sSectionId]) { oAnchorBar.setSelectedButton(this._oSectionInfo[sSectionId].buttonId); this._setSectionsFocusValues(sSectionId); } } }; /** * called when the screen is resize by users. Updates the screen height * @param oEvent * @private */ ObjectPageLayout.prototype._onUpdateScreenSize = function (oEvent) { if (!this._bDomReady) { jQuery.sap.log.info("ObjectPageLayout :: cannot _onUpdateScreenSize before dom is ready"); return; } this._oLazyLoading.setLazyLoadingParameters(); jQuery.sap.delayedCall(ObjectPageLayout.HEADER_CALC_DELAY, this, function () { this._bMobileScenario = library.Utilities.isPhoneScenario(); this._bTabletScenario = library.Utilities.isTabletScenario(); if (this._bHContentAlwaysExpanded != this._checkAlwaysShowContentHeader()) { this.invalidate(); } this._adjustHeaderHeights(); this._adjustLayout(null, true); this._scrollTo(this._$opWrapper.scrollTop(), 0); }); }; /** * called when the user scrolls on the page * @param oEvent * @private */ ObjectPageLayout.prototype._onScroll = function (oEvent) { var iScrollTop = Math.max(oEvent.target.scrollTop, 0), // top of the visible page iPageHeight, oHeader = this.getHeaderTitle(), bShouldStick = iScrollTop >= (this.iHeaderContentHeight - (this.iHeaderTitleHeightStickied - this.iHeaderTitleHeight)), // iHeaderContentHeight minus the gap between the two headerTitle sClosestId, bScrolled = false; //calculate the limit of visible sections to be lazy loaded iPageHeight = this.iScreenHeight; if (bShouldStick && !this._bHContentAlwaysExpanded) { iPageHeight -= (this.iAnchorBarHeight + this.iHeaderTitleHeightStickied); } else { if (bShouldStick && this._bHContentAlwaysExpanded) { iPageHeight = iPageHeight - (this._$stickyAnchorBar.height() + this.iHeaderTitleHeight + this.iStickyHeaderContentHeight); // - this.iStickyHeaderContentHeight } } if (this._bIsHeaderExpanded) { this._expandCollapseHeader(false); } //don't apply parallax effects if there are not enough space for it if (!this._bHContentAlwaysExpanded && ((oHeader && this.getShowHeaderContent()) || this.getShowAnchorBar())) { this._toggleHeader(bShouldStick); //if we happen to have been able to collapse it at some point (section height had increased) //and we no longer are (section height is reduced) and we are at the top of the page we expand it back anyway } else if (iScrollTop == 0 && ((oHeader && this.getShowHeaderContent()) || this.getShowAnchorBar())) { this._toggleHeader(false); } if (!this._bHContentAlwaysExpanded) { this._adjustHeaderTitleBackgroundPosition(iScrollTop); } jQuery.sap.log.debug("ObjectPageLayout :: lazy loading : Scrolling at " + iScrollTop, "----------------------------------------"); //find the currently scrolled section = where position - iScrollTop is closest to 0 sClosestId = this._getClosestScrolledSectionId(iScrollTop, iPageHeight); if (sClosestId) { // check if scroll destination is set in advance // (this is when a particular section is requested from the anchorBar sectionsList and we are now scrolling to reach it) var sDestinationSectionId = this.getDirectScrollingToSection(); if (sClosestId !== this._sScrolledSectionId) { jQuery.sap.log.debug("ObjectPageLayout :: closest id " + sClosestId, "----------------------------------------"); // check if scroll-destination section is explicitly set var sDestinationSectionId = this.getDirectScrollingToSection(); // if scroll-destination section is explicitly set // then we do not want to process intermediate sections (i.e. sections between scroll-start section and scroll-destination sections) // so if current section is not destination section // then no need to proceed further if (sDestinationSectionId && sDestinationSectionId !== sClosestId) { return; } this.clearDirectScrollingToSection(); this._setAsCurrentSection(sClosestId); } else if (sClosestId === this.getDirectScrollingToSection()) { //we are already in the destination section this.clearDirectScrollingToSection(); } } //lazy load only the visible subSections if (this.getEnableLazyLoading()) { //calculate the progress done between this scroll event and the previous one //to see if we are scrolling fast (more than 5% of the page height) this._oLazyLoading.lazyLoadDuringScroll(iScrollTop, oEvent.timeStamp, iPageHeight); } if (oHeader && this.getShowHeaderContent() && this.getShowTitleInHeaderContent() && oHeader.getShowTitleSelector()) { if (iScrollTop === 0) { // if we have arrow from the title inside the ContentHeader and the ContentHeader isn't scrolled we have to put higher z-index to the ContentHeader // otherwise part of the arrow is cut off jQuery.sap.byId(this.getId() + "-scroll").css("z-index", "1000"); bScrolled = false; } else if (!bScrolled) { bScrolled = true; // and we have to "reset" the z-index it when we start scrolling jQuery.sap.byId(this.getId() + "-scroll").css("z-index", "0"); } } }; ObjectPageLayout.prototype._getClosestScrolledSectionId = function (iScrollTop, iPageHeight) { if (this.getUseIconTabBar() && this._oCurrentTabSection) { return this._oCurrentTabSection.getId(); } var iScrollPageBottom = iScrollTop + iPageHeight, //the bottom limit sClosestId; jQuery.each(this._oSectionInfo, function (sId, oInfo) { // on desktop/tablet, skip subsections if (oInfo.isSection || this._bMobileScenario) { //we need to set the sClosest to the first section for handling the scrollTop = 0 if (!sClosestId) { sClosestId = sId; } // current section/subsection is inside the view port if (oInfo.positionTop <= iScrollPageBottom && iScrollTop <= oInfo.positionBottom) { // scrolling position is over current section/subsection if (oInfo.positionTop <= iScrollTop && oInfo.positionBottom >= iScrollTop) { sClosestId = sId; return false; } } } }.bind(this)); return sClosestId; }; /** * toggles the header state * @param bStick boolean true for fixing the header, false for keeping it moving * @private */ ObjectPageLayout.prototype._toggleHeader = function (bStick) { var oHeaderTitle = this.getHeaderTitle(); //switch to stickied if (!this._bHContentAlwaysExpanded && !this._bIsHeaderExpanded) { this._$headerTitle.toggleClass("sapUxAPObjectPageHeaderStickied", bStick); } // if the title in the header is not always visible but the action buttons are there we have to adjust header height and remove the padding of the action buttons if (oHeaderTitle && oHeaderTitle.getIsActionAreaAlwaysVisible() && !oHeaderTitle.getIsObjectTitleAlwaysVisible()) { oHeaderTitle._setActionsPaddingStatus(!bStick); } if (!this._bStickyAnchorBar && bStick) { this._restoreFocusAfter(this._convertHeaderToStickied); oHeaderTitle && oHeaderTitle._adaptLayout(); this._adjustHeaderHeights(); } else if (this._bStickyAnchorBar && !bStick) { this._restoreFocusAfter(this._convertHeaderToExpanded); oHeaderTitle && oHeaderTitle._adaptLayout(); this._adjustHeaderHeights(); } }; /** * Restores the focus after moving the Navigation bar after moving it between containers * @private * @param fnMoveNavBar a function that moves the navigation bar * @returns this */ ObjectPageLayout.prototype._restoreFocusAfter = function (fnMoveNavBar) { var oCore = sap.ui.getCore(), oLastSelectedElement = oCore.byId(oCore.getCurrentFocusedControlId()); fnMoveNavBar.call(this); if (Device.system.phone !== true) { // FIX - can not convert to expanded on windows phone if (!oCore.byId(oCore.getCurrentFocusedControlId())) { oLastSelectedElement && oLastSelectedElement.$().focus(); } } return this; }; /** * Converts the Header to stickied (collapsed) mode * @private * @returns this */ ObjectPageLayout.prototype._convertHeaderToStickied = function () { if (!this._bHContentAlwaysExpanded) { this._$anchorBar.css("height", this.iAnchorBarHeight).children().appendTo(this._$stickyAnchorBar); this._toggleHeaderStyleRules(true); //Internal Incident: 1472003895: FIT W7 MI: Dual color in the header //we need to adjust the header background now in case its size is different if (this.iHeaderTitleHeight != this.iHeaderTitleHeightStickied) { this._adjustHeaderBackgroundSize(); } } return this; }; /** * Converts the Header to expanded (moving) mode * @private * @returns this */ ObjectPageLayout.prototype._convertHeaderToExpanded = function () { if (!this._bHContentAlwaysExpanded) { this._$anchorBar.css("height", "auto").append(this._$stickyAnchorBar.children()); this._toggleHeaderStyleRules(false); } return this; }; /** * Toggles the header styles for between stickied and expanded modes * @private * @returns this */ ObjectPageLayout.prototype._toggleHeaderStyleRules = function (bStuck) { bStuck = !!bStuck; var sValue = bStuck ? "hidden" : "inherit"; this._bStickyAnchorBar = bStuck; this._$headerContent.css("overflow", sValue); this._$headerContent.css("visibility", sValue); this._$anchorBar.css("visibility", sValue); this.fireToggleAnchorBar({fixed: bStuck}); }; // use type 'object' because Metamodel doesn't know ScrollEnablement /** * Returns a sap.ui.core.delegate.ScrollEnablement object used to handle scrolling * * @type object * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ ObjectPageLayout.prototype.getScrollDelegate = function () { return this._oScroller; }; /************************************************************************************************************ * Header specific methods ***********************************************************************************************************/ ObjectPageLayout.prototype.setHeaderTitle = function (oHeaderTitle, bSuppressInvalidate) { oHeaderTitle.addEventDelegate({ onAfterRendering: this._adjustHeaderHeights.bind(this) }); return this.setAggregation("headerTitle", oHeaderTitle, bSuppressInvalidate); }; ObjectPageLayout.prototype._adjustHeaderBackgroundSize = function () { // Update the background image size and position var oHeaderTitle = this.getHeaderTitle(); if (oHeaderTitle && oHeaderTitle.getHeaderDesign() == "Dark") { if (!this._bHContentAlwaysExpanded) { this.iTotalHeaderSize = this.iHeaderTitleHeight + this.iHeaderContentHeight; this._$headerContent.css("background-size", "100% " + this.iTotalHeaderSize + "px"); } else { // The header size in this case contains the header content and the anchor bar, we have to exclude the anchor bar, since no background is applyied to it this.iTotalHeaderSize = this.iHeaderTitleHeight - this._$stickyAnchorBar.height(); // here the sticky header content has to be updated not the content like in the upper case this._$stickyHeaderContent.css("background-size", "100% " + this.iTotalHeaderSize + "px"); } oHeaderTitle.$().css("background-size", "100% " + this.iTotalHeaderSize + "px"); this._adjustHeaderTitleBackgroundPosition(0); } }; ObjectPageLayout.prototype._adjustHeaderTitleBackgroundPosition = function (iScrollTop) { var oHeaderTitle = this.getHeaderTitle(); if (oHeaderTitle && oHeaderTitle.getHeaderDesign() == "Dark") { if (this._bStickyAnchorBar) { oHeaderTitle.$().css("background-position", "0px " + ((this.iTotalHeaderSize - this.iHeaderTitleHeightStickied) * -1) + "px"); } else { if (this._bHContentAlwaysExpanded) { // If the header is always expanded, there is no neeed to scroll the background so we setting it to 0 position oHeaderTitle.$().css("background-position", "0px 0px"); } else { oHeaderTitle.$().css("background-position", "0px " + (this.iHeaderTitleHeight + this.iHeaderContentHeight - this.iTotalHeaderSize - iScrollTop) + "px"); } } } }; ObjectPageLayout.prototype._adjustHeaderHeights = function () { //checking the $headerTitle we prevent from checking the headerHeights multiple times during the first rendering //$headerTitle is set in the objectPageLayout.onAfterRendering, thus before the objectPageLayout is fully rendered once, we don't enter here multiple times (performance tweak) if (this._$headerTitle.length > 0) { var $headerTitleClone = this._$headerTitle.clone(); //read the headerContentHeight --------------------------- this.iHeaderContentHeight = this._$headerContent.height(); //read the sticky headerContentHeight --------------------------- this.iStickyHeaderContentHeight = this._$stickyHeaderContent.height(); //figure out the anchorBarHeight ------------------------ this.iAnchorBarHeight = this._$anchorBar.height(); //prepare: make sure it won't be visible ever and fix width to the original headerTitle which is 100% $headerTitleClone.css({left: "-10000px", top: "-10000px", width: this._$headerTitle.width() + "px"}); //in sticky mode, we need to calculate the size of original header if (this._bStickyAnchorBar) { //read the headerTitleStickied --------------------------- this.iHeaderTitleHeightStickied = this._$headerTitle.height() - this.iAnchorBarHeight; //adjust the headerTitle ------------------------------- $headerTitleClone.removeClass("sapUxAPObjectPageHeaderStickied"); $headerTitleClone.appendTo(this._$headerTitle.parent()); this.iHeaderTitleHeight = $headerTitleClone.is(":visible") ? $headerTitleClone.height() - this.iAnchorBarHeight : 0; } else { //otherwise it's the sticky that we need to calculate //read the headerTitle ----------------------------------- this.iHeaderTitleHeight = this._$headerTitle.is(":visible") ? this._$headerTitle.height() : 0; //adjust headerTitleStickied ---------------------------- $headerTitleClone.addClass("sapUxAPObjectPageHeaderStickied"); $headerTitleClone.appendTo(this._$headerTitle.parent()); this.iHeaderTitleHeightStickied = $headerTitleClone.height(); } //clean dom $headerTitleClone.remove(); //adjust dom element directly depending on the adjusted height // Adjust wrapper top position var iPadding = this.iHeaderContentHeight ? this.iHeaderTitleHeight : this.iHeaderTitleHeightStickied; // if no header content, the top padding has to be larger // so that the static header does not overlap the beginning of the first section this._$opWrapper.css("padding-top", iPadding); this._adjustHeaderBackgroundSize(); jQuery.sap.log.info("ObjectPageLayout :: adjustHeaderHeight", "headerTitleHeight: " + this.iHeaderTitleHeight + " - headerTitleStickiedHeight: " + this.iHeaderTitleHeightStickied + " - headerContentHeight: " + this.iHeaderContentHeight); } else { jQuery.sap.log.debug("ObjectPageLayout :: adjustHeaderHeight", "skipped as the objectPageLayout is being rendered"); } }; /** * Retrieve the current header design that was defined in the headerTitle if available * * @private */ ObjectPageLayout.prototype._getHeaderDesign = function () { var oHeader = this.getHeaderTitle(), sDesign = library.ObjectPageHeaderDesign.Light; if (oHeader != null) { sDesign = oHeader.getHeaderDesign(); } return sDesign; }; /** * Gets only the visible sections * * @private */ ObjectPageLayout.prototype._getVisibleSections = function () { return this.getSections().filter(function (oSection) { return oSection.getVisible() && oSection._getInternalVisible(); }); }; /** * Sets appropriate focus to the sections * * @private */ ObjectPageLayout.prototype._setSectionsFocusValues = function (sSectionId) { var aSections = this._getVisibleSections() || [], $section, sFocusable = '0', sNotFocusable = '-1', sTabIndex = "tabIndex", oSelectedElement, oFirstSection = aSections[0]; aSections.forEach(function (oSection) { $section = oSection.$(); if (sSectionId === oSection.sId) { $section.attr(sTabIndex, sFocusable); oSelectedElement = oSection; oSection._setSubSectionsFocusValues(); } else { $section.attr(sTabIndex, sNotFocusable); oSection._disableSubSectionsFocus(); } }); if (!oSelectedElement && aSections.length > 0) { oFirstSection.$().attr(sTabIndex, sFocusable); oFirstSection._setSubSectionsFocusValues(); oSelectedElement = oFirstSection; } return oSelectedElement; }; /** * get current visibility of the HeaderContent and if it is different from the new one rererender it */ ObjectPageLayout.prototype.setShowHeaderContent = function (bShow) { var bOldShow = this.getShowHeaderContent(); if (bOldShow !== bShow) { if (bOldShow && this._bIsHeaderExpanded) { this._expandCollapseHeader(false); } this.setProperty("showHeaderContent", bShow); this._getHeaderContent().setProperty("visible", bShow); } return this; }; /** * Calls the renderer function that will rerender the ContentHeader when something is changed in the ObjectPageHeader Title * * @private */ ObjectPageLayout.prototype._headerTitleChangeHandler = function () { if (!this.getShowTitleInHeaderContent() || this._bFirstRendering) { return; } var oRm = sap.ui.getCore().createRenderManager(); this.getRenderer()._rerenderHeaderContentArea(oRm, this); oRm.destroy(); }; /** * Maintain ObjectPageHeaderContent aggregation * */ ObjectPageLayout.prototype.getHeaderContent = function () { return this._getHeaderContent().getAggregation("content"); }; ObjectPageLayout.prototype.insertHeaderContent = function (oObject, iIndex, bSuppressInvalidate) { return this._getHeaderContent().insertAggregation("content", oObject, iIndex, bSuppressInvalidate); }; ObjectPageLayout.prototype.addHeaderContent = function (oObject, bSuppressInvalidate) { return this._getHeaderContent().addAggregation("content", oObject, bSuppressInvalidate); }; ObjectPageLayout.prototype.removeAllHeaderContent = function (bSuppressInvalidate) { return this._getHeaderContent().removeAllAggregation("content", bSuppressInvalidate); }; ObjectPageLayout.prototype.removeHeaderContent = function (oObject, bSuppressInvalidate) { return this._getHeaderContent().removeAggregation("content", oObject, bSuppressInvalidate); }; ObjectPageLayout.prototype.destroyHeaderContent = function (bSuppressInvalidate) { return this._getHeaderContent().destroyAggregation("content", bSuppressInvalidate); }; ObjectPageLayout.prototype.indexOfHeaderContent = function (oObject) { return this._getHeaderContent().indexOfAggregation("content", oObject); }; /** * Lazy loading of the _headerContent aggregation * * @private */ ObjectPageLayout.prototype._getHeaderContent = function () { if (!this.getAggregation("_headerContent")) { this.setAggregation("_headerContent", new library.ObjectPageHeaderContent({ visible: this.getShowHeaderContent(), contentDesign: this._getHeaderDesign(), content: this.getAggregation("headerContent") }), true); } return this.getAggregation("_headerContent"); }; ObjectPageLayout.prototype._checkAlwaysShowContentHeader = function () { return !this._bMobileScenario && !this._bTabletScenario && this.getShowHeaderContent() && this.getAlwaysShowContentHeader(); }; ObjectPageLayout.prototype._connectModelsForSections = function (aSections) { aSections = aSections || []; aSections.forEach(function (oSection) { oSection.connectToModels(); }); }; ObjectPageLayout.prototype._getHeightRelatedParameters = function () { return { iHeaderContentHeight: this.iHeaderContentHeight, iScreenHeight: this.iScreenHeight, iAnchorBarHeight: this.iAnchorBarHeight, iHeaderTitleHeightStickied: this.iHeaderTitleHeightStickied, iStickyHeaderContentHeight: this.iStickyHeaderContentHeight, iScrollTop: this._$opWrapper.scrollTop() }; }; ObjectPageLayout.prototype._hasVerticalScrollBar = function () { if (this._$opWrapper.length) { return this._$opWrapper[0].scrollHeight > this._$opWrapper.innerHeight(); } else { return !this.getUseIconTabBar(); } }; ObjectPageLayout.prototype._shiftHeader = function (sDirection, sPixels) { this.$().find(".sapUxAPObjectPageHeaderTitle").css(sDirection, sPixels); }; /** * Checks if a section is the first visible one * @private */ ObjectPageLayout.prototype._isFirstSection = function (oSection) { var aSections = this._getVisibleSections(); if (oSection === aSections[0]) { return true; } return false; }; ObjectPageLayout.prototype._restoreScrollPosition = function () { this._scrollTo(this._iStoredScrollPosition, 0); }; ObjectPageLayout.prototype._storeScrollLocation = function () { this._iStoredScrollPosition = this._oScroller.getScrollTop(); this._oStoredSection = this._oCurrentTabSubSection || this._oCurrentTabSection; this._oCurrentTabSection = null; }; ObjectPageLayout.HEADER_CALC_DELAY = 350; //ms. The higher the safer and the uglier... ObjectPageLayout.DOM_CALC_DELAY = 200; //ms. return ObjectPageLayout; }); }; // end of sap/uxap/ObjectPageLayout.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageHeaderRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.ObjectPageHeaderRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder sap.ui.define("sap/uxap/ObjectPageHeaderRenderer",["./ObjectPageLayout"], function (ObjectPageLayout) { "use strict"; /** * @class HeaderBase renderer. * @static */ var ObjectPageHeaderRenderer = {}; ObjectPageHeaderRenderer.render = function (oRm, oControl) { var oNavigationBar = oControl.getNavigationBar(), bTitleVisible = (oControl.getIsObjectIconAlwaysVisible() || oControl.getIsObjectTitleAlwaysVisible() || oControl.getIsObjectSubtitleAlwaysVisible() || oControl.getIsActionAreaAlwaysVisible()), oParent = oControl.getParent(), oExpandButton = oControl.getAggregation("_expandButton"), bIsDesktop = sap.ui.Device.system.desktop, bIsHeaderContentVisible = oParent && oParent instanceof ObjectPageLayout && ((oParent.getHeaderContent() && oParent.getHeaderContent().length > 0 && oParent.getShowHeaderContent()) || (oParent.getShowHeaderContent() && oParent.getShowTitleInHeaderContent())); oRm.write("<div"); oRm.writeControlData(oControl); oRm.addClass('sapUxAPObjectPageHeader'); oRm.addClass('sapUxAPObjectPageHeaderDesign-' + oControl.getHeaderDesign()); oRm.writeClasses(); oRm.write(">"); // if an navigationBar has been provided display it if (oNavigationBar) { oRm.write("<div"); oRm.addClass('sapUxAPObjectPageHeaderNavigation'); oRm.writeClasses(); oRm.write(">"); oRm.renderControl(oNavigationBar); oRm.write("</div>"); } // first line oRm.write("<div"); oRm.writeAttributeEscaped("id", oControl.getId() + "-identifierLine"); oRm.addClass('sapUxAPObjectPageHeaderIdentifier'); if (bTitleVisible) { oRm.addClass('sapUxAPObjectPageHeaderIdentifierForce'); } oRm.writeClasses(); oRm.write(">"); if (oParent && oParent instanceof ObjectPageLayout && oParent.getIsChildPage()) { oRm.write("<div"); oRm.addClass('sapUxAPObjectChildPage'); oRm.writeClasses(); oRm.write("></div>"); } // If picturePath is provided show image if (oControl.getObjectImageURI() || oControl.getShowPlaceholder()) { oRm.write("<span "); oRm.addClass('sapUxAPObjectPageHeaderObjectImageContainer'); oRm.addClass('sapUxAPObjectPageHeaderObjectImage-' + oControl.getObjectImageShape()); if (oControl.getIsObjectIconAlwaysVisible()) { oRm.addClass('sapUxAPObjectPageHeaderObjectImageForce'); } oRm.writeClasses(); oRm.write(">"); oRm.write("<span class='sapUxAPObjectPageHeaderObjectImageContainerSub'>"); if (oControl.getObjectImageURI()) { oRm.renderControl(oControl._getInternalAggregation("_objectImage")); if (oControl.getShowPlaceholder()) { this._renderPlaceholder(oRm, oControl, false); } } else { this._renderPlaceholder(oRm, oControl, true); } oRm.write("</span>"); oRm.write("</span>"); } oRm.write("<span "); oRm.writeAttributeEscaped("id", oControl.getId() + "-identifierLineContainer"); oRm.addClass('sapUxAPObjectPageHeaderIdentifierContainer'); oRm.writeClasses(); oRm.write(">"); this._renderObjectPageTitle(oRm, oControl); oRm.write("</span>"); oRm.write("<span"); oRm.writeAttributeEscaped("id", oControl.getId() + "-actions"); oRm.addClass('sapUxAPObjectPageHeaderIdentifierActions'); if (oControl.getIsActionAreaAlwaysVisible()) { oRm.addClass('sapUxAPObjectPageHeaderIdentifierActionsForce'); } if (oControl._getActionsPaddingStatus()) { oRm.addClass("sapUxAPObjectPageHeaderIdentifierActionsNoPadding"); } oRm.writeClasses(); oRm.write(">"); // Render the expand button only if there is a content to expand and we are on desktop if (bIsDesktop && bIsHeaderContentVisible) { oExpandButton.addStyleClass("sapUxAPObjectPageHeaderExpandButton"); oRm.renderControl(oExpandButton); } var aActions = oControl.getActions(); for (var i = 0; i < aActions.length; i++) { var oAction = aActions[i]; oRm.renderControl(oAction); } var oOverflowButton = oControl.getAggregation("_overflowButton"); oRm.renderControl(oOverflowButton); oRm.write("</span>"); oRm.write("</div>"); oRm.write("</div>"); }; /** * Renders the SelectTitleArrow icon. * * @param {sap.ui.core.RenderManager} * oRm the RenderManager that can be used for writing to the render output buffer * * @param {sap.uxap.ObjecPageHeader} * oControl the ObjectPageHeader * * @param {bVisible} if the placeholder will be visible * * @private */ ObjectPageHeaderRenderer._renderPlaceholder = function (oRm, oControl, bVisible, bTitleInContent) { oRm.write("<div"); oRm.addClass('sapUxAPObjectPageHeaderPlaceholder'); oRm.addClass('sapUxAPObjectPageHeaderObjectImage'); if (!bVisible) { oRm.addClass('sapUxAPHidePlaceholder'); } oRm.writeClasses(); oRm.write(">"); oRm.renderControl(oControl._oPlaceholder); oRm.write("</div>"); }; /** * Renders the SelectTitleArrow icon. * * @param {sap.ui.core.RenderManager} * oRm the RenderManager that can be used for writing to the render output buffer * * @param {sap.uxap.ObjecPageHeader} * oControl the ObjectPageHeader * * @private */ ObjectPageHeaderRenderer._renderObjectPageTitle = function (oRm, oControl, bTitleInContent) { var sOHTitle = oControl.getObjectTitle(), bMarkers = (oControl.getShowMarkers() && (oControl.getMarkFavorite() || oControl.getMarkFlagged())), oBreadCrumbs = oControl._getInternalAggregation('_breadCrumbs'); if (!bTitleInContent && oBreadCrumbs && oBreadCrumbs.getLinks().length) { oRm.renderControl(oBreadCrumbs); } oRm.write("<h1"); oRm.addClass('sapUxAPObjectPageHeaderIdentifierTitle'); if (oControl.getIsObjectTitleAlwaysVisible()) { oRm.addClass('sapUxAPObjectPageHeaderIdentifierTitleForce'); } if (bTitleInContent) { oRm.addClass('sapUxAPObjectPageHeaderIdentifierTitleInContent'); } if (oControl.getShowTitleSelector()) { // if we have arrow to render, the subtitle should have smaller top margin oRm.addClass('sapUxAPObjectPageHeaderTitleFollowArrow'); } oRm.writeClasses(); oRm.writeAttributeEscaped("id", oControl.getId() + "-title"); oRm.write(">"); oRm.write("<span"); oRm.addClass("sapUxAPObjectPageHeaderTitleTextWrappable"); oRm.writeClasses(); oRm.writeAttributeEscaped("id", oControl.getId() + "-innerTitle"); oRm.write(">"); // if we have markers or arrow we have to cut the last word and bind it to the markers and arrow so that the icons never occur in one line but are accompanied by the last word of the title. if (bMarkers || oControl.getShowTitleSelector() || oControl.getMarkLocked() || oControl.getMarkChanges()) { var sOHTitleEnd = sOHTitle.substr(sOHTitle.lastIndexOf(" ") + 1); var sOHTitleStart = sOHTitle.substr(0, sOHTitle.lastIndexOf(" ") + 1); if (sOHTitleEnd.length === 1) { sOHTitleEnd = sOHTitle; sOHTitleStart = ''; } oRm.writeEscaped(sOHTitleStart); oRm.write("</span>"); oRm.write("<span"); oRm.addClass('sapUxAPObjectPageHeaderNowrapMarkers'); if (oControl.getMarkLocked() || oControl.getMarkChanges()) { oRm.addClass('sapUxAPObjectPageHeaderMarks'); } oRm.writeClasses(); oRm.write(">"); oRm.writeEscaped(sOHTitleEnd); // if someone has set both Locked and Unsaved Changes icons, then show only Locked icon if (oControl.getMarkLocked()) { this._renderLock(oRm, oControl, bTitleInContent); } else if (oControl.getMarkChanges()) { this._renderMarkChanges(oRm, oControl, bTitleInContent); } this._renderMarkers(oRm, oControl); this._renderSelectTitleArrow(oRm, oControl, bTitleInContent); oRm.write("</span>"); } else { oRm.writeEscaped(sOHTitle); oRm.write("</span>"); } oRm.write("</h1>"); oRm.write("<span"); oRm.addClass('sapUxAPObjectPageHeaderIdentifierDescription'); if (oControl.getIsObjectSubtitleAlwaysVisible() && oControl.getObjectSubtitle()) { oRm.addClass('sapUxAPObjectPageHeaderIdentifierDescriptionForce'); } if (bTitleInContent) { oRm.addClass('sapUxAPObjectPageHeaderIdentifierSubTitleInContent'); } oRm.writeClasses(); oRm.writeAttributeEscaped("id", oControl.getId() + "-subtitle"); oRm.write(">"); oRm.writeEscaped(oControl.getObjectSubtitle()); oRm.write("</span>"); }; /** * Renders the SelectTitleArrow icon. * * @param {sap.ui.core.RenderManager} * oRm the RenderManager that can be used for writing to the render output buffer * * @param {sap.m.ObjectHeader} * oControl the ObjectPageHeader * @param {boolean} * bTitleInContent - if the arrow will be rendered in content or in title * @private */ ObjectPageHeaderRenderer._renderSelectTitleArrow = function (oRm, oControl, bTitleInContent) { if (oControl.getShowTitleSelector()) { // render select title arrow oRm.write("<span"); // Start title arrow container oRm.addClass("sapUxAPObjectPageHeaderTitleArrow"); oRm.writeClasses(); oRm.write(">"); if (bTitleInContent) { oRm.renderControl(oControl._oTitleArrowIconCont); } else { oRm.renderControl(oControl._oTitleArrowIcon); } oRm.write("</span>"); // end title arrow container } }; /** * Renders the Unsaved Changes icon. * * @param {sap.ui.core.RenderManager} * oRm the RenderManager that can be used for writing to the render output buffer * * @param {sap.uxap.ObjectPageHeader} * oControl the ObjectPageHeader * @param {boolean} * bTitleInContent - if the Unsaved changes icon will be rendered in content or in title * @private */ ObjectPageHeaderRenderer._renderMarkChanges = function (oRm, oControl, bTitleInContent) { oRm.write("<span"); oRm.addClass("sapUxAPObjectPageHeaderChangesBtn"); oRm.addClass("sapUiSizeCompact"); oRm.writeClasses(); oRm.write(">"); if (bTitleInContent) { oRm.renderControl(oControl._oChangesIconCont); } else { oRm.renderControl(oControl._oChangesIcon); } oRm.write("</span>"); }; /** * Renders the Lock icon. * * @param {sap.ui.core.RenderManager} * oRm the RenderManager that can be used for writing to the render output buffer * * @param {sap.uxap.ObjectPageHeader} * oControl the ObjectPageHeader * @param {boolean} * bTitleInContent - if the lock will be rendered in content or in title * @private */ ObjectPageHeaderRenderer._renderLock = function (oRm, oControl, bTitleInContent) { oRm.write("<span"); oRm.addClass("sapUxAPObjectPageHeaderLockBtn"); oRm.addClass("sapUiSizeCompact"); oRm.writeClasses(); oRm.write(">"); if (bTitleInContent) { oRm.renderControl(oControl._oLockIconCont); } else { oRm.renderControl(oControl._oLockIcon); } oRm.write("</span>"); }; /** * Renders the favorite and flag icons. * * @param {sap.ui.core.RenderManager} * oRm the RenderManager that can be used for writing to the render output buffer * * @param {sap.m.ObjectHeader} * oControl the ObjectPageHeader * * @private */ ObjectPageHeaderRenderer._renderMarkers = function (oRm, oControl) { var aIcons = []; // load icons based on control state if (oControl.getShowMarkers()) { aIcons.push(oControl._oFavIcon); aIcons.push(oControl._oFlagIcon); this._renderMarkersAria(oRm, oControl); // render hidden aria description of flag and favorite icons // render icons oRm.write("<span"); oRm.addClass("sapMObjStatusMarker"); oRm.writeClasses(); oRm.writeAttributeEscaped("id", oControl.getId() + "-markers"); oRm.writeAttributeEscaped("aria-describedby", oControl.getId() + "-markers-aria"); oRm.write(">"); for (var i = 0; i < aIcons.length; i++) { oRm.renderControl(aIcons[i]); } oRm.write("</span>"); } }; /** * Renders hidden div with ARIA descriptions of the favorite and flag icons. * * @param {sap.ui.core.RenderManager} * oRm the RenderManager that can be used for writing to the render output buffer * * @param {sap.m.ObjectHeader} * oControl the ObjectPageHeader * * @private */ ObjectPageHeaderRenderer._renderMarkersAria = function (oRm, oControl) { var sAriaDescription = ""; // ARIA description message // check if flag mark is set if (oControl.getMarkFlagged()) { sAriaDescription += (oControl.oLibraryResourceBundle.getText("ARIA_FLAG_MARK_VALUE") + " "); } // check if favorite mark is set if (oControl.getMarkFavorite()) { sAriaDescription += (oControl.oLibraryResourceBundle.getText("ARIA_FAVORITE_MARK_VALUE") + " "); } // if there is a description render ARIA node if (sAriaDescription !== "") { // BEGIN ARIA hidden node oRm.write("<div"); oRm.writeAttributeEscaped("id", oControl.getId() + "-markers-aria"); oRm.writeAttribute("aria-hidden", "false"); oRm.addClass("sapUiHidden"); oRm.writeClasses(); oRm.write(">"); oRm.writeEscaped(sAriaDescription); oRm.write("</div>"); // END ARIA hidden node } }; return ObjectPageHeaderRenderer; }, /* bExport= */ true); }; // end of sap/uxap/ObjectPageHeaderRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageLayoutRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.ObjectPageLayoutRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder jQuery.sap.require('sap.ui.core.Renderer'); // unlisted dependency retained sap.ui.define("sap/uxap/ObjectPageLayoutRenderer",["sap/ui/core/Renderer", "./ObjectPageHeaderRenderer"], function (Renderer, ObjectPageHeaderRenderer) { "use strict"; /** * @class ObjectPageRenderer renderer. * @static */ var ObjectPageLayoutRenderer = {}; ObjectPageLayoutRenderer.render = function (oRm, oControl) { var aSections, oHeader = oControl.getHeaderTitle(), oAnchorBar = null, bIsHeaderContentVisible = oControl.getHeaderContent() && oControl.getHeaderContent().length > 0 && oControl.getShowHeaderContent(), bIsTitleInHeaderContent = oControl.getShowTitleInHeaderContent() && oControl.getShowHeaderContent(), bRenderHeaderContent = bIsHeaderContentVisible || bIsTitleInHeaderContent; if (oControl.getShowAnchorBar() && oControl._getInternalAnchorBarVisible()) { oAnchorBar = oControl.getAggregation("_anchorBar"); } oRm.write("<div"); oRm.writeControlData(oControl); if (oHeader) { oRm.writeAttributeEscaped("aria-label", oHeader.getObjectTitle()); } oRm.addClass("sapUxAPObjectPageLayout"); oRm.writeClasses(); oRm.addStyle("height", oControl.getHeight()); oRm.writeStyles(); oRm.write(">"); // Header oRm.write("<header "); oRm.writeAttribute("role", "header"); oRm.writeAttributeEscaped("id", oControl.getId() + "-headerTitle"); oRm.addClass("sapUxAPObjectPageHeaderTitle"); oRm.writeClasses(); oRm.write(">"); if (oHeader) { oRm.renderControl(oHeader); } // Sticky Header Content if (bRenderHeaderContent) { this._renderHeaderContentDOM(oRm, oControl, oControl._bHContentAlwaysExpanded, "-stickyHeaderContent"); } // Sticky anchorBar placeholder oRm.write("<div "); oRm.writeAttributeEscaped("id", oControl.getId() + "-stickyAnchorBar"); oRm.addClass("sapUxAPObjectPageStickyAnchorBar"); oRm.addClass("sapUxAPObjectPageNavigation"); oRm.writeClasses(); oRm.write(">"); // if the content is expanded render bars outside the scrolling div this._renderAnchorBar(oRm, oControl, oAnchorBar, oControl._bHContentAlwaysExpanded); oRm.write("</div>"); oRm.write("</header>"); oRm.write("<div "); oRm.writeAttributeEscaped("id", oControl.getId() + "-opwrapper"); oRm.addClass("sapUxAPObjectPageWrapper"); // set transform only if we don't have title arrow inside the header content, otherwise the z-index is not working if (!(oControl.getShowTitleInHeaderContent() && oHeader.getShowTitleSelector())) { oRm.addClass("sapUxAPObjectPageWrapperTransform"); } oRm.writeClasses(); oRm.write(">"); oRm.write("<div "); oRm.writeAttributeEscaped("id", oControl.getId() + "-scroll"); oRm.addClass("sapUxAPObjectPageScroll"); oRm.writeClasses(); oRm.write(">"); // Header Content if (bRenderHeaderContent) { this._renderHeaderContentDOM(oRm, oControl, !oControl._bHContentAlwaysExpanded, "-headerContent"); } // Anchor Bar oRm.write("<section "); oRm.writeAttributeEscaped("id", oControl.getId() + "-anchorBar"); // write ARIA role oRm.writeAttribute("role", "navigaiton"); oRm.addClass("sapUxAPObjectPageNavigation"); oRm.writeClasses(); oRm.write(">"); this._renderAnchorBar(oRm, oControl, oAnchorBar, !oControl._bHContentAlwaysExpanded); oRm.write("</section>"); // Content section oRm.write("<section"); oRm.addClass("sapUxAPObjectPageContainer"); if (!oAnchorBar) { oRm.addClass("sapUxAPObjectPageContainerNoBar"); } oRm.writeClasses(); oRm.write(">"); aSections = oControl.getAggregation("sections"); if (jQuery.isArray(aSections)) { jQuery.each(aSections, function (iIndex, oSection) { oRm.renderControl(oSection); }); } oRm.write("</section>"); // run hook method this.renderFooterContent(oRm, oControl); oRm.write("<div"); oRm.writeAttributeEscaped("id", oControl.getId() + "-spacer"); oRm.write("></div>"); oRm.write("</div>"); // END scroll oRm.write("</div>"); // END wrapper oRm.write("</div>"); // END page }; /** * This method is called to render AnchorBar * * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered */ ObjectPageLayoutRenderer._renderAnchorBar = function (oRm, oControl, oAnchorBar, bRender) { var aSections = oControl.getAggregation("sections"); if (bRender) { if (oControl.getIsChildPage()) { oRm.write("<div "); oRm.writeAttributeEscaped("id", oControl.getId() + "-childPageBar"); if (jQuery.isArray(aSections) && aSections.length > 1) { oRm.addClass('sapUxAPObjectChildPage'); } oRm.writeClasses(); oRm.write("></div>"); } if (oAnchorBar) { oRm.renderControl(oAnchorBar); } } }; /** * This method is called to render header content DOM structure * * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered * @param bRender - shows if the control should be rendered * @param sId - the id of the div that should be rendered * @param bRenderAlways - shows if the DOM of the control should be rendered no matter if the control is rendered inside or not */ ObjectPageLayoutRenderer._renderHeaderContentDOM = function (oRm, oControl, bRender, sId) { oRm.write("<header "); oRm.writeAttributeEscaped("id", oControl.getId() + sId); oRm.addClass("ui-helper-clearfix"); oRm.addClass("sapUxAPObjectPageHeaderDetails"); oRm.addClass("sapUxAPObjectPageHeaderDetailsDesign-" + oControl._getHeaderDesign()); oRm.writeClasses(); oRm.writeAttribute("data-sap-ui-customfastnavgroup", true); oRm.write(">"); // render Header Content control if (bRender) { this.renderHeaderContent(oRm, oControl); } oRm.write("</header>"); }; /** * This hook method is called to render objectpagelayout header content * * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered */ ObjectPageLayoutRenderer.renderHeaderContent = function (oRm, oControl) { oRm.renderControl(oControl._getHeaderContent()); }; /** * This hook method is called to render objectpagelayout footer content * * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered */ ObjectPageLayoutRenderer.renderFooterContent = function (oRm, oControl) { }; /** * This method is called to rerender headerContent * * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered */ ObjectPageLayoutRenderer._rerenderHeaderContentArea = function (oRm, oControl) { var sId = oControl.getId(); this.renderHeaderContent(oRm, oControl); oRm.flush(jQuery.sap.byId(sId + "-headerContent")[0]); }; return ObjectPageLayoutRenderer; }, /* bExport= */ true); }; // end of sap/uxap/ObjectPageLayoutRenderer.js if ( !jQuery.sap.isDeclared('sap.uxap.ObjectPageHeaderContentRenderer') ) { /*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare('sap.uxap.ObjectPageHeaderContentRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder sap.ui.define("sap/uxap/ObjectPageHeaderContentRenderer",["./ObjectPageHeaderRenderer", "./ObjectPageLayout"], function (ObjectPageHeaderRenderer, ObjectPageLayout) { "use strict"; /** * @class HeaderContent renderer. * @static */ var ObjectPageHeaderContentRenderer = {}; ObjectPageHeaderContentRenderer.render = function (oRm, oControl) { var oParent = oControl.getParent(), bParentLayout = (oParent instanceof ObjectPageLayout), oHeader = (oParent && bParentLayout) ? oParent.getHeaderTitle() : false, bRenderTitle = (oParent && bParentLayout) ? ((oParent instanceof ObjectPageLayout) && oParent.getShowTitleInHeaderContent()) : false, bRenderEditBtn = bParentLayout && oParent.getShowEditHeaderButton() && oControl.getContent() && oControl.getContent().length > 0; if (bRenderEditBtn) { oRm.write("<div "); oRm.addClass("sapUxAPObjectPageHeaderContentFlexBox"); oRm.addClass("sapUxAPObjectPageHeaderContentDesign-" + oControl.getContentDesign()); if (oHeader) { oRm.addClass('sapUxAPObjectPageContentObjectImage-' + oHeader.getObjectImageShape()); } oRm.writeClasses(); oRm.write(">"); } oRm.write("<div "); oRm.writeControlData(oControl); if (bRenderEditBtn) { oRm.addClass("sapUxAPObjectPageHeaderContentCellLeft"); } else { oRm.addClass("sapUxAPObjectPageHeaderContentDesign-" + oControl.getContentDesign()); if (oHeader) { oRm.addClass('sapUxAPObjectPageContentObjectImage-' + oHeader.getObjectImageShape()); } } oRm.addClass("ui-helper-clearfix"); oRm.addClass("sapUxAPObjectPageHeaderContent"); if (!oControl.getVisible()) { oRm.addClass("sapUxAPObjectPageHeaderContentHidden"); } oRm.writeClasses(); oRm.write(">"); if (bParentLayout && oParent.getIsChildPage()) { oRm.write("<div"); oRm.addClass('sapUxAPObjectChildPage'); oRm.writeClasses(); oRm.write("></div>"); } if (bRenderTitle) { this._renderTitleImage(oRm, oHeader); if (oControl.getContent().length == 0) { oRm.write("<span class=\"sapUxAPObjectPageHeaderContentItem\">"); this._renderTitle(oRm, oHeader); oRm.write("</span>"); } } oControl.getContent().forEach(function (oItem, iIndex) { this._renderHeaderContent(oItem, iIndex, oRm, bRenderTitle, oHeader, oControl); }, this); oRm.write("</div>"); if (bRenderEditBtn) { this._renderEditButton(oRm, oControl); oRm.write("</div>"); // end of "sapUxAPObjectPageHeaderContentFlexBox" div } }; /** * This method is called to render the content * @param {*} oHeaderContent header content * @param {*} iIndex index * @param {*} oRm oRm * @param {*} bRenderTitle render title * @param {*} oHeader header * @param {*} oControl control */ ObjectPageHeaderContentRenderer._renderHeaderContent = function (oHeaderContent, iIndex, oRm, bRenderTitle, oHeader, oControl) { var bHasSeparatorBefore = false, bHasSeparatorAfter = false, oLayoutData = oControl._getLayoutDataForControl(oHeaderContent), bIsFirstControl = iIndex === 0, bIsLastControl = iIndex === (oControl.getContent().length - 1); if (oLayoutData) { bHasSeparatorBefore = oLayoutData.getShowSeparatorBefore(); bHasSeparatorAfter = oLayoutData.getShowSeparatorAfter(); oRm.write("<span "); oRm.addClass("sapUxAPObjectPageHeaderWidthContainer"); oRm.addClass("sapUxAPObjectPageHeaderContentItem"); oRm.addStyle("width", oLayoutData.getWidth()); oRm.writeStyles(); if (bHasSeparatorAfter || bHasSeparatorBefore) { oRm.addClass("sapUxAPObjectPageHeaderSeparatorContainer"); } if (!oLayoutData.getVisibleL()) { oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenL"); } if (!oLayoutData.getVisibleM()) { oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenM"); } if (!oLayoutData.getVisibleS()) { oRm.addClass("sapUxAPObjectPageHeaderLayoutHiddenS"); } oRm.writeClasses(); oRm.write(">"); if (bHasSeparatorBefore) { oRm.write("<span class=\"sapUxAPObjectPageHeaderSeparatorBefore\"/>"); } if (bIsFirstControl && bRenderTitle) { // render title inside the first contentItem this._renderTitle(oRm, oHeader); } } else { if (bIsFirstControl && bRenderTitle) { // render title inside the first contentItem oRm.write("<span class=\"sapUxAPObjectPageHeaderContentItem\">"); this._renderTitle(oRm, oHeader); } else { oHeaderContent.addStyleClass("sapUxAPObjectPageHeaderContentItem"); } } oRm.renderControl(oHeaderContent); if (bHasSeparatorAfter) { oRm.write("<span class=\"sapUxAPObjectPageHeaderSeparatorAfter\"/>"); } if (oLayoutData || (bIsFirstControl && bRenderTitle) || bIsLastControl) { oRm.write("</span>"); } }; /** * This method is called to render title and all it's parts if the property showTitleInHeaderContent is set to true * * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered * @param {sap.ui.core.Control} oHeader an object representation of the titleHeader that should be rendered */ ObjectPageHeaderContentRenderer._renderTitleImage = function (oRm, oHeader) { if (oHeader.getObjectImageURI() || oHeader.getShowPlaceholder()) { oRm.write("<span"); oRm.addClass("sapUxAPObjectPageHeaderContentImageContainer"); oRm.addClass("sapUxAPObjectPageHeaderObjectImage-" + oHeader.getObjectImageShape()); oRm.writeClasses(); oRm.write(">"); if (oHeader.getObjectImageURI()) { oRm.renderControl(oHeader._getInternalAggregation("_objectImage")); if (oHeader.getShowPlaceholder()) { ObjectPageHeaderRenderer._renderPlaceholder(oRm, oHeader, false); } } else { ObjectPageHeaderRenderer._renderPlaceholder(oRm, oHeader, true); } oRm.write("</span>"); } }; /** * This method is called to render title and all it's parts if the property showTitleInHeaderContent is set to true * * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oHeader an object representation of the control that should be rendered */ ObjectPageHeaderContentRenderer._renderTitle = function (oRm, oHeader) { ObjectPageHeaderRenderer._renderObjectPageTitle(oRm, oHeader, true); // force title to be visible inside the content header }; /** * This method is called to render the Edit button when the property showEditHeaderButton is set to true * * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oHeader an object representation of the control that should be rendered */ ObjectPageHeaderContentRenderer._renderEditButton = function (oRm, oHeader) { oRm.write("<div class=\"sapUxAPObjectPageHeaderContentCellRight\">"); oRm.renderControl(oHeader.getAggregation("_editHeaderButton")); oRm.write("</div>"); }; return ObjectPageHeaderContentRenderer; }, /* bExport= */ true); }; // end of sap/uxap/ObjectPageHeaderContentRenderer.js
var fs = require("fs"); var sqlite3 = require('sqlite3');//.verbose(); var _ = require("../utils"); var Certificate = require("../Certificate"); var log = console.log; module.exports = _.class({ server: null, // server object seg: null, // segment name 'D<num:oct>' ring: null, // ring of segment (int) num: null, // number of segment (oct) cert: null, // certificate of data-source ds: null, // unique id of current data-source := certificate.hash():str20 info: null, // data source info (last sync time, etc.) sources: null, // { "ds": { cert:<Certificate>, seq:<seq>, _seq:<seq> },... } listeners: null, // { "uid": { "connectionID": <Response>,...}} usedSize: null, _initialized: false, /** * @param name - string "A<segment_num:oct>" */ constructor: function(name) { var sn = name.match(/^[A-Z]+([0-7]*)$/); if(!sn) throw "Incorrect segment name"; this.seg = name; // A<oct> this.num = sn[1]; // <oct> this.ring = this.num.length; }, /** * @param server - Server object */ initStorage: function(server) { this.server = server; //------ init dir ------- var dir = _.mkdir(server.dir + '/dat_' + this.seg); if(server.options.clear|0) { fs.readdirSync(dir).forEach(function(file){ fs.unlinkSync(file = dir + '/' + file); server.log('- removed ' + file); }); } //----------------- this.dir = dir; this.sources = {}; this.cert = server.cert; this.ds = this.cert.getID(); this.listeners = {}; // {uid: {connID: conn,...}} //--- init storage info --- this.info = fs.existsSync(dir + '/info.json') && _.parseJSON(fs.readFileSync(dir + '/info.json')) || {}; //---- init db ---- this.initDB(function(){ this._initialized = true; // start full synchronization. todo: use special process?? setTimeout(this.fullSynchronization.bind(this, true)); // calculate size of storage this.calcUsedSizeSync(); setInterval(this.calcUsedSizeAsync.bind(this), 73009); }.bind(this)); }, //-------- private methods --------- saveInfo: function(inf) { fs.writeFile(this.dir + '/info.json', JSON.stringify(_.ex(this.info, inf))); }, checkUid: function(uid) { return typeof uid === "string" && /^[0-9a-f]{64}$/.test(uid) && (!this.num || this.num === parseInt(uid.substr(0,12), 16).toString(8).substr(0, this.ring)); }, checkCertID: function(certID) { return /^[0-9a-zA-Z\-_]{20}$/.test(certID); }, checkDs: function(ds) { return this.checkCertID(ds); }, parseCertificate: function(cert64) { return Certificate.parsePublic(cert64); }, saveCertificate: function(cert) { // save author certificate to db var seg = this.seg; cert._saved && cert._saved[seg] || this._sql.insertAuthor.run({ $aid: cert.getID(), $cert: cert.toBuffer() }, function(err) { (cert._saved || (cert._saved = {}))[seg] = !err; }); }, calcUsedSizeSync: function() { this.usedSize = fs.readdirSync(this.dir).reduce(function(s, file) { return s + fs.statSync(this.dir + '/' + file).size; }.bind(this), 0); }, calcUsedSizeAsync: function() { var fileStat = function(files, sum) { if(!files.length) return this.usedSize = sum; fs.stat(this.dir + '/' + files.shift(), function(err, st){ fileStat(files, sum + (st && !st.isDirectory() && st.size|0)); }); }.bind(this); fs.readdir(this.dir, function(err, files) { if(files) fileStat(files, 0); }); }, isInitialized: function() { return this._initialized && this.usedSize !== null; }, //---------- Abstract ------------- getRingSize: function() { throw 'Abstract method' }, // count of segments in ring getAllocatedSize: function() { throw 'Abstract method' }, getMaxPostSize: function() { throw 'Abstract method' }, createDataTables: function() { throw 'Abstract method' }, prepareData: function(post, src, nid){ throw 'Abstract method' }, //---------- DB --------------- db: null, _sql: null, prepareSQL: function(sqlObjs) { for(var i in sqlObjs) { //this.server.debug('- SQL-preparing: ' + sqlObjs[i]); var sql = sqlObjs[i], stm = this.db.prepare(sql); stm._vars = {}; sql.replace(/\$[a-z][a-zA-Z0-9_]*/g, function(v){ stm._vars[v] = true; }); stm._filterParams = function(params) { var res = {}; for(var i in this._vars) res[i] = params[i]; return res; }; (this._sql || (this._sql = {}))[i] = stm; } }, initDB: function(fn) { this.db = new sqlite3.Database(this.dir + '/data.db'); if(this.server.options.debug|0) this.db.on('trace', log); this.db.exec( // ------ data sources --------- "CREATE TABLE IF NOT EXISTS authors ( " + // all authors " aid TEXT NOT NULL, " + // unique author-id. char20 " cert BLOB NOT NULL, " + // author certificate: (ver|public key|registrar-sign) " size INT NOT NULL DEFAULT 0, " + // " PRIMARY KEY(aid) " + "); " + // ------ data sources --------- "CREATE TABLE IF NOT EXISTS sources ( " + // all data sources (nodes) in segment " ts TIMESTAMP NOT NULL, " + // " ds TEXT NOT NULL, " + // unique name of data source. char20 " cert BLOB NOT NULL, " + // data source certificate " seq INT NOT NULL DEFAULT 0, " + // last sequence in data source " size INT NOT NULL DEFAULT 0, " + // " PRIMARY KEY(ds) " + "); " + "CREATE INDEX IF NOT EXISTS idx_sources_ts ON sources (ts); " ); this.createDataTables(); this.prepareSQL({ begin: 'BEGIN', commit: 'COMMIT', rollback: 'ROLLBACK', insertAuthor: "INSERT OR IGNORE INTO authors(aid, cert)" + "VALUES($aid, $cert)" , insertDataSource: "INSERT OR IGNORE INTO sources(ts, ds, cert)" + "VALUES(CURRENT_TIMESTAMP, $ds, $cert)" , selectAllSources: "SELECT ds, seq" + " FROM sources" + " WHERE seq>0" //todo: add limit + offset //" ORDER BY ts DESC" + //" LIMIT $limit" , selectSourcesByPeriod: "SELECT ds, seq" + " FROM sources" + " WHERE ts >= $date AND seq>0" , selectSourceInfo: "SELECT ds, cert, seq, size," + " (select dshash from data where ds=$ds order by seq desc limit 1) as dshash " + " FROM sources" + " WHERE ds = $ds" + " LIMIT 1" }); //--- init data source -------- this.getDataSourceInfo(this.ds, function(err, src){ if(err) throw err; if(src.cert) return fn(); src.cert = this.cert; this._sql.insertDataSource.run({ $ds: this.ds, $cert: src.cert.toBuffer() }, function(err){ if(err) throw err; fn(); }); }.bind(this)); this.db.wait(); }, //--------------- HTTP ----------------- getHttpInfo: function() { return { usage: (this.usedSize/this.getAllocatedSize()*10000|0)*0.01 } }, /** * Process http-request to segment data /-/A<segNum:oct>/... * * @param conn */ processHttpRequest: function(conn) { if(conn.getRequestHeader('if-modified-since')) { return conn.response(304); } if(!this.isInitialized()) { return conn.response(503); } switch(conn.urlParts[3]) { case "add": // add data to stream return this.httpCommandAdd(conn); case "data": // list elements of stream return this.httpCommandData(conn); case "sources": // list data sources return this.httpCommandSources(conn); case "source": // get data of source by ds return this.httpCommandSource(conn); case "notify": // notify me about new data return this.httpCommandNotify(conn); case "listen": // listen changes uid return this.httpCommandListen(conn); default: return conn.response400(); } }, /** * Add data to stream * * process POST request /-/<seg>/add * POST-params: uid, pos, author, ver, data, sign [, hash] */ httpCommandAdd: function(conn) { if(this.usedSize >= this.getAllocatedSize()) { return conn.response(507); } if(conn.method !== 'POST') return conn.response400('Method Not Allowed'); var src = this.sources[this.ds]; // current data source if(!src || !src.cert) return conn.response500(); conn.setMaxPostSize(this.getMaxPostSize()); conn.onPostData(function(post) { var q = this._insQueue || (this._insQueue = []); if(q.length > 1000) return conn.response(503); // todo: add anti-flood statistic by author var ins = this.prepareData(post, src); if(ins.err) return conn.response400(ins.err); ins.$ds = src.ds; ins.conn = conn; q.push(ins); if(q.length == 1) { var _processQueue = function() { if(!q.length) return; this.insertData(q[0], function(err) { var ins = q.shift(); if(err && err.errno !== sqlite3.CONSTRAINT) {// error and is not duplicate key (hash) this._insQueue = null; // clear queue return ins.conn.response500(err); } ins.conn.response(200, this.makeURI(ins)); if(q.length % 5 == 0) this.notifyNodes(this.ds); _processQueue(); }.bind(this)); }.bind(this); _processQueue(); } }.bind(this)); }, httpCommandData: function(conn) { throw 'Abstract method' }, /** * process GET-request: * /-/<seg>/listen/<uid> */ httpCommandListen: function(conn) { conn.response400('Method Not Allowed'); }, notifyListeners: function() { // abstract method }, /** * process GET-request: * /-/<seg>/sources?period=<seconds:int> */ httpCommandSources: function(conn) { if(conn.method !== 'GET') return conn.response400('Method Not Allowed'); if(conn.query.period !== undefined) { conn.responseJSONBySql(this._sql.selectSourcesByPeriod, { $date: _.date(-(conn.query.period|0)).toISOString() // $limit: Math.min(10000, query.limit|0 || 10000) }); } else { conn.responseJSONBySql(this._sql.selectAllSources); } }, /** * Get data by source * process GET-request: * /-/<seg>/source?ds=<ds>&seq=<seq:int>&limit=<limit:int> */ httpCommandSource: function(conn) { if(conn.method !== 'GET') return conn.response400('Method Not Allowed'); var ds = conn.query.ds; var seq = conn.query.seq|0; var limit = Math.min(5000, conn.query.limit|0 || 1000); if(!this.checkDs(ds)) return conn.response400('Bad ds'); this.getDataSourceInfo(ds, function(err, src) { if(err) return conn.response500(err); if(!src || !src.cert) { delete this.sources[ds]; return conn.response(404, 'Not found'); } conn.setResponseHeader('x-base-cert', src.cert.toString()); conn.responseJSONBySql(this._sql.selectSourceData, { $ds: ds, $seq: seq, $limit: limit }); }.bind(this)); }, /** * Notify about new data * process GET-request: * /-/<seg>/notify?ds=<ds>&seq=<seq:int> * request-header: * x-base-cert: <ip>/<port> */ httpCommandNotify: function(conn) { if(conn.method !== 'GET') return conn.response400('Method Not Allowed'); var query = conn.query; var ds = query.ds; var seq = query.seq|0; if(!seq) return conn.response400('Bad seq'); if(!this.checkDs(ds)) return conn.response400('Bad ds'); var nid = this.server.parseNodeHeader(conn); if(!nid) return conn.response400('Bad node-header'); var res = {}; res[ds] = (this.sources[ds] || {}).seq|0; conn.responseJSON(res); this.syncDataSource(ds, seq, nid, function(err, success){ if(success) this.notifyNodes(ds, nid); }.bind(this)); }, //-------- data source sequences ------------ getDataSourceInfo: function(ds, fn) { var src = this.sources[ds] || (this.sources[ds] = { ds: ds, seq: 0, size: 0 }); if(src.cert) return fn(null, src); this._sql.selectSourceInfo.get({ $ds: ds }, function(err, row) { if(err || !row) return fn(err, src); row.dshash = (row.dshash||"").toString("hex"); row.cert = Certificate.parsePublic(row.cert); fn(err, _.ex(src, row)); }); }, //----------- sync data source ----------- notifyNodes: function(ds, notifier) { this.requestToNodes({ path: 'notify?ds='+ds + '&seq=' + this.sources[ds].seq, excludeNode: notifier }); }, syncDataSource: function(ds, seq, nid, fn) { this.getDataSourceInfo(ds, function(err, src) { if(err) return fn(err); if(seq <= src.seq || seq <= src._seq) return fn(null, false); src._nid = nid; src._seq = seq; if(src.nid) return fn(null, false); src.nid = nid; // lock source this._syncDataSource(src, function(err, res) { src.nid = null; // unlock source fn(err, res); }); }.bind(this)); }, _syncDataSource: function(src, fn) { this._sql.begin.run(this._syncDataSourceInTransaction.bind(this, src, fn)); }, _syncDataSourceInTransaction: function(src, fn) { var nid = src.nid, ds = src.ds, cnt = 0, lastRow; var conn = this.server.requestToNode({ nid: nid, path: '/-/'+this.seg+'/source?ds='+ds+'&seq='+src.seq, type: 'json', async: true, onData: function(row) { if(!src.cert) { // unknow source. check and save pubkey var srcCert64 = conn.getResponseHeader('x-base-cert'); if(!srcCert64) throw 'Empty x-base-cert header'; var cert = Certificate.parsePublic(srcCert64); if(!cert || ds != cert.getID()) throw 'Incorrect x-base-cert header: ' + srcCert64; src.cert = cert; this._sql.insertDataSource.run({ $ds: ds, $cert: src.cert.toBuffer() }); } // check sequence, data, hash, sign if(!row.seq) throw 'Empty seq'; if(row.seq <= src.seq) { conn.next(); return; } if(row.seq != src.seq + 1) throw 'Unexpected sequence'; var ins = this.prepareData(row, src, nid); if(ins.err) return conn.abort(ins.err); var seq = row.seq | 0; var hashHex = _.hex(row.hash, "base64"); var $dsHash = _.buf(row.dshash, "base64"); var $dsSign = _.buf(row.dssign, "base64"); // verify data by source var dsHashHex = _.sha256(_.str(src.dshash || src.cert.pub + this.seg) + hashHex); if(dsHashHex !== $dsHash.toString("hex")) throw 'Invalid ds-hash'; ins.$ds = ds; ins.$seq = seq; ins.$dshash = $dsHash; ins.$dssign = $dsSign; cnt++; this.insertData(ins, function(err) { if(err) return conn.abort(err); lastRow = ins; conn.next(); }.bind(this)); }.bind(this), onFinish: function(err) { if(!cnt) err = 'Empty data'; if(!err && lastRow) { // check ds-sign if(!src.cert.verify(lastRow.$dshash.toString("hex"), lastRow.$dssign.toString("hex"))) err = 'Invalid ds-sign'; } this._sql[err? 'rollback' : 'commit'].run(function(errCommit){ //log('---- COMMIT ', cnt, 'records, time:',+new Date()-t0,'msec, avg:',(+new Date()-t0)/cnt|0,'msec'); if(err = err || errCommit) { this.sources[ds] = null; // clear ds-cache return fn(err); } if(src._nid == nid && src._seq > src.seq) // continue sync return this._syncDataSource(src, fn); fn(null, true); // - success sync }.bind(this)); }.bind(this) }); }, insertData: function(data, callback) { // overwrite function var src = this.sources[data.$ds]; if(!data.$seq) { //new data data.$seq = (src.seq || 0) + 1; data.$dshash = _.sha256((src.dshash || this.cert.pub + this.seg) + data.$hash.toString('hex'), 'utf8', 'buffer'); data.$dssign = this.cert.sign(data.$dshash); } this._sql.insertData.run(this._sql.insertData._filterParams(data), function(err) { if(src.seq != data.$seq - 1) err = 'Sequence was corrupted'; if(err) return callback.call(this, err); src.seq = data.$seq; src.dshash = data.$dshash.toString("hex"); callback.call(this, null, src.seq); this.notifyListeners(data); }.bind(this)); }, makeURI: function(data) { return this.seg[0] + this.ring + "/" + (data.$uid || data.$hash).toString("hex"); }, requestToNodes: function(op) { op = _.ex({ path: null, type: 'json', countNodes: 2, excludeNode: null, onData: null, onFinish: null }, op); var seg = this.seg, path = '/-/'+seg+'/' + op.path; var server = this.server, errors, i, nodes = server.getNodesBySegment(seg, op.countNodes); if(op.excludeNode && (i = nodes.indexOf(op.excludeNode)) >= 0) nodes.splice(i, 1); var cnt = nodes.length; if(!cnt) return op.onFinish && op.onFinish('Not found nodes'); nodes.forEach(function(nid) { // todo: add limit on count of opened requests server.requestToNode({ nid: nid, path: path, type: op.type, onData: op.onData && function(row) { op.onData(row, nid); }, onFinish: function(err) { if(err) (errors = errors || {})[nid] = err; if(!--cnt) op.onFinish && op.onFinish(errors, nodes); } }); }); }, //---------- full sync ---------- fullSynchronization: function(start) { var tStart = +new Date(); var periodSync = 614657; // ~10 min var tLastSync = this.info.tLastSync; if(!start && tLastSync > tStart - periodSync) { return setTimeout(this.fullSynchronization.bind(this), tLastSync - tStart + periodSync + Math.random() * 15551); } var self = this, sources = {}; this.requestToNodes({ path: 'sources/' + (tLastSync? '?period=' + ((tStart - tLastSync) * 1e-3 + 86400 |0) : ''), onData: function(data, nid) { if(!data || !self.checkDs(data.ds)) { throw 'Bad data'; } var ds = data.ds, seq = data.seq|0; if(seq <= 0) throw 'Bad seq'; if((!self.sources[ds] || self.sources[ds].seq < seq) && (!sources[ds] || sources[ds].seq<seq)) { sources[ds] = { seq: seq, nid: nid }; // todo: use file or db } }, onFinish: function(errors) { var syncSources = function(){ var ds = _.firstKey(sources); if(ds) return self.syncDataSource(ds, sources[ds].seq, sources[ds].nid, function(err, success) { delete sources[ds]; errors = errors || err; syncSources(); }); // finish sync if(!errors) { self.saveInfo({ tLastSync: tStart }); self._initialized = true; } setTimeout(self.fullSynchronization.bind(self), 18181); }; syncSources(); } }); } });
define(["exports"], function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var GridConnector = exports.GridConnector = function () { function GridConnector(datasource) { _classCallCheck(this, GridConnector); this.datasource = datasource; this.vGrid = {}; } GridConnector.prototype.datasourceEvents = function datasourceEvents(event) { switch (event) { case "collectionChange": this.vGrid.vGridGenerator.collectionChange(true); break; case "collectionChange_newAdded": this.vGrid.vGridGenerator.collectionChange(false, true); break; case "collectionChange_update": case "collectionChange_oneRemoved": this.vGrid.vGridGenerator.collectionChange(false); break; case "selection_changed": this.vGrid.vGridGenerator.updateSelectionOnAllRows(); break; default: console.log("unknown event"); console.log(event); } }; GridConnector.prototype.setDatasource = function setDatasource(datasource, errorHandler) { this.datasource = datasource; this.errorHandler = errorHandler || function (err) {}; this.datasource.addEventListener(this.datasourceEvents.bind(this)); this.vGrid.vGridGenerator.collectionChange(true); }; GridConnector.prototype.length = function length() { var length = 0; if (this.datasource) { length = this.datasource.collection.length; } return length; }; GridConnector.prototype.rowClick = function rowClick(e) { if (this.datasource) { this.datasource.select(e.row); } }; GridConnector.prototype.getElement = function getElement(e) { var _this = this; if (this.datasource) { e.callback(); if (this.datasource.collection.length > e.row && e.row >= 0) { this.datasource.getElement(e.row).then(function (data) { if (e.row === e.div.top / e.rowHeight) { e.callback(data, e.row); } }).catch(function (err) { e.callback(); _this.errorHandler("getElement", err); }); } } else { e.callback(); } }; GridConnector.prototype.filter = function filter(e) { var _this2 = this; e.activateLoadingScreen(); var filter = this.createQueryString(e.filter); var sort = this.createOrderByString(e.sort); this.datasource.query(filter, { orderby: sort, releaseEntitySet: true }).then(function (data) { e.callback(); }).catch(function (err) { e.callback(); _this2.errorHandler("filter", err); }); }; GridConnector.prototype.sort = function sort(e) { var _this3 = this; e.activateLoadingScreen(); var sort = this.createOrderByString(e.sort); this.datasource.orderby(sort, true).then(function (data) { e.callback(); }).catch(function (err) { e.callback(); _this3.errorHandler("sort", err); }); }; GridConnector.prototype.setValueToRow = function setValueToRow(attribute, value, row) { if (this.datasource) { this.datasource.collection.setValueToRow(attribute, value, row); } }; GridConnector.prototype.isRowSelected = function isRowSelected(row) { var result = false; if (this.datasource) { result = this.datasource.selection.isRowSelected(row); } return result; }; GridConnector.prototype.deSelectRow = function deSelectRow(row) { this.datasource.selection.deSelectRow(row); }; GridConnector.prototype.addRowToSelection = function addRowToSelection(row, addToSelection) { this.datasource.selection.addRowToSelection(row, addToSelection); }; GridConnector.prototype.setSelectionRange = function setSelectionRange(start, end) { this.datasource.selection.setSelectionRange(start, end); }; GridConnector.prototype.getSelectedRows = function getSelectedRows() { return this.datasource.selection.getSelectedRows(); }; GridConnector.prototype.setSelectedRows = function setSelectedRows(newRows) { this.datasource.selection.setSelectedRows(newRows); }; GridConnector.prototype.getSelectionMode = function getSelectionMode() { return "multiple"; }; GridConnector.prototype.createOrderByString = function createOrderByString(orderByArray) { var sortArray = []; if (orderByArray) { orderByArray.forEach(function (param) { sortArray.push(param.attribute + " " + (param.asc ? "asc" : "desc")); }); if (orderByArray.length === 0) { return null; } return sortArray; } else { return null; } }; GridConnector.prototype.createQueryString = function createQueryString(queryArray) { if (queryArray) { var queryString = ''; queryArray.forEach(function (param, index) { if (index === 0) { queryString = ''; } else { queryString = queryString + ' and '; } switch (param.operator) { case "=": queryString = queryString + (param.attribute + "=" + param.value); break; case "*": queryString = queryString + (param.attribute + "=*" + param.value + "*"); break; case "!=": queryString = queryString + (param.attribute + "!=" + param.value); break; case "<": queryString = queryString + ("" + param.attribute + param.operator + param.value); break; case ">": queryString = queryString + ("" + param.attribute + param.operator + param.value); break; case "<=": queryString = queryString + ("" + param.attribute + param.operator + param.value); break; case ">=": queryString = queryString + ("" + param.attribute + param.operator + param.value); break; case "*=": queryString = queryString + (param.attribute + "=" + param.value + "*"); break; case "=*": queryString = queryString + (param.attribute + "=*" + param.value); break; case "!*": queryString = queryString + (param.attribute + "!=*" + param.value + "*"); break; } }); return queryString; } else { return null; } }; return GridConnector; }(); });
import { OrderedMap, Map } from 'immutable' import IdOrderedMap, { ITEMS_KEY, SELECTED_ID_KEY } from './IdOrderedMap' describe('(Models) IdOrderedMap', () => { it('Should export a constant ITEMS_KEY.', () => { expect(ITEMS_KEY).to.eql('items') }) it('Should export a constant SELECTED_ID_KEY.', () => { expect(SELECTED_ID_KEY).to.eql('selectedId') }) it('Should create instance by default constructor', () => { const instance = new IdOrderedMap() expect(instance).to.be.ok expect(instance.get(SELECTED_ID_KEY)).to.eql('0') expect(instance.get(ITEMS_KEY).toObject()).to.eql(OrderedMap().toObject()) }) it('Should create instance by constructor', () => { const instance = new IdOrderedMap(Map({ [SELECTED_ID_KEY]: '12', [ITEMS_KEY]: Map({ '0': Map({ id: 0 }), '1': Map({ id: 1 }) }) })) expect(instance).to.be.ok expect(instance.get(SELECTED_ID_KEY)).to.eql('12') const expected = Map({ '0': Map({ id: 0 }), '1': Map({ id: 1 }) }) expect(instance.get(ITEMS_KEY).toObject()).to.eql(expected.toObject()) }) })
'use strict'; describe('Controller: TestUploadCtrl', function () { // load the controller's module beforeEach(module('vadsenceNodeApp')); var TestUploadCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); TestUploadCtrl = $controller('TestUploadCtrl', { $scope: scope }); })); it('should ...', function () { expect(1).toEqual(1); }); });
(function () { if (!Object.keys) { /** * Define object keys overrides * @param hash * @returns {Array} */ Object.prototype.keys = function (hash) { var keys = [], k; for (k in hash) { if (hash.hasOwnProperty(k)) { keys.push(k); } } return keys; }; } if (!String.repeat) { /** * Define string repeat * @param times * @returns {string} */ String.prototype.repeat = function (times) { return new Array(times + 1).join(this); } } /** * Abstract item * @param {string} instance * @param {object} [opts] * @class Item * @constructor */ function Item(instance, opts) { opts = opts || {}; /** * Define type of instance * @property Item * @type {string} */ this.instance = instance; /** * Define items collector * @property Item * @type {object} */ this.items = {}; /** * Define Crud * @param scope * @class Crud * @private * @constructor */ function _Crud(scope) { this.scope = scope; } _Crud.prototype = { constructor: _Crud, /** * Define create * @param node * @param index * @param [opts] * @returns {*} */ create: function create(node, index, opts) { if (this.read(index)) { // Item already exist return false; } this.scope.items[index] = new Item(node, opts); return this.scope.items[index]; }, /** * Define destroy * @param index * @returns {*} */ destroy: function destroy(index) { if (!this.read(index)) { return false; } delete this.scope.items[index]; return this.scope; }, /** * Define read * @param index * @returns {*} */ read: function read(index) { if (!this.scope.items.hasOwnProperty(index)) { // Undefined item return false; } return this.scope.items[index]; }, /** * Define update * @param indexOld * @param indexNew * @returns {*} */ update: function update(indexOld, indexNew) { if (!this.read(indexOld)) { return false; } /** * Define copy if instance * @type {string} */ var instance = this.scope.items[indexOld].instance; this.destroy(indexOld); this.create(instance, indexNew); return this.scope.items[indexNew]; } }; /** * define Crud instance * @property Item * @type {_Crud} */ this.crud = new _Crud(this); if (Object.prototype.toString.call(opts) === '[object Object]') { var index; for (index in opts) { if (opts.hasOwnProperty(index)) { /** * Define properties * @property Item */ this[index] = opts[index]; } } } else { /** * Define data * @property Item * @type {Object} */ this.content = opts; } } /** * Define collector * @param item * @param node * @param index * @param collector * @private * @returns {object} */ function _collectItems(node, index, collector) { var i = 0, l = collector.length; /** * Define instance * @type {node} */ var instance = hotel.crud.create(node, index); for (; i < l; i++) { // Define items of instance instance.crud.create(node, i, collector[i]); } return instance; } /** * Define images renderer * @param data * @private */ function _renderImages(data) { var index, content = []; for (index in data) { if (data.hasOwnProperty(index)) { var prefs = data[index]; content.push( $('<li />').append( $('<a />').append( $('<img />').attr({ src: prefs.thumbnail, alt: prefs.description }) ).attr({href: prefs.large}) ) ); } } $('section.photos > ul').append(content); } /** * Define description renderer * @param data * @private */ function _renderDescription(data) { var index, content = []; for (index in data) { if (data.hasOwnProperty(index)) { content.push( $('<p />').text(data[index].content) ) } } $('section.description div:first').append(content); } /** * Define facilities renderer * @param data * @private */ function _renderFacilities(data) { var index, content = []; for (index in data) { if (data.hasOwnProperty(index) && data[index].available) { content.push( $('<li />').text(data[index].type) ) } } $('section.facilities > ul').append(content); } /** * Define rooms renderer * @param data * @private */ function _renderRooms(data) { var index, content = []; for (index in data) { if (data.hasOwnProperty(index)) { var prefs = data[index], options = [], range = prefs.quantity.range.split('-'), i = range[0], l = range[1]; for (; i < l; i++) { var $option = $('<option />').attr({ value: i }).text(i); if (!i) $option.attr({selected: 'selected'}); options.push($option); } content.push( $('<tr />').append([ $('<td />').addClass('room_name').text(prefs.name), $('<td />').addClass('room_occupancy').text(prefs.occupancy), $('<td />').addClass('room_price').text(prefs.price), $('<td />').addClass('room_quantity').append( $('<select />').attr({ name: 'room' + prefs.quantity.type }).append(options).on('change', function () { var $this = $(this), $selects = $this.parents('table').find('select'), $wrapper = $('.total td:last'), pattern = /\d+\.\d+/, currency = $this.parents('tr').find('.room_price').text().replace(pattern, ''), total = 0; $.each($selects, function () { var $select = $(this), rooms = +$select.val(), price = $select.parents('tr').find('.room_price').text(); if (rooms) { total += +price.match(pattern)[0] * rooms; } }); $wrapper.text(currency + (total.toFixed(2))); }) ) ]) ); } } $('section.rooms tbody').append(content); } /** * Define reviews renderer * @param data * @private */ function _renderReviews(data, from, to) { var index, content = [], i = 0; from = from || 0; for (index in data) { if (data.hasOwnProperty(index) && from <= to - 1) { if (i !== from) { i++; continue; } var prefs = data[index]; content.push( $('<li />').append([ $('<strong />').addClass('review_score').text(prefs.ranking), $('<blockquote />').addClass('review_content').text(prefs.text), $('<cite />').text(prefs.author) ]).addClass('one_review') ); i++; from++; } } var keys = Object.keys(data).length, current = to > keys ? keys : to, $h2 = $('section.reviews h2'), matchers = $h2.html().match(/\d+/g); if (matchers) $h2.html($h2.html().replace(matchers[0], current).replace(matchers[1], keys)); else $h2.html('Reviews (<span>' + current + '</span> of <span>' + keys + '</span>)'); $('ul.reviews_list').html(content); } /** * Define sort asc/desc * @param element * @returns {boolean} * @private */ function _defineSorted(element) { if ($(element).attr('sorted') === 'asc') { $(element).attr('sorted', 'desc'); } else { $(element).attr('sorted', 'asc'); } return $(element).attr('sorted') === 'asc'; } /** * Define table sorter * @private */ function _bindTableSort() { var $wrapper = $('.rooms_table tbody'); // Sort by Name $('.rooms_table th.room_name').on('click', function () { var sorted = _defineSorted(this); $wrapper.find('tr').sort(function (a, b) { if ($(a).find('.room_name').text() < $(b).find('.room_name').text()) return sorted ? -1 : 1; if ($(a).find('.room_name').text() > $(b).find('.room_name').text()) return sorted ? 1 : -1; return 0; }).appendTo($wrapper); }); // Sort by Occupancy $('.rooms_table th.room_occupancy').on('click', function () { var sorted = _defineSorted(this); $wrapper.find('tr').sort(function (a, b) { return sorted ? +$(a).find('.room_occupancy').text() - +$(b).find('.room_occupancy').text() : +$(b).find('.room_occupancy').text() - +$(a).find('.room_occupancy').text(); }).appendTo($wrapper); }); // Sort by Price $('.rooms_table th.room_price').on('click', function () { var sorted = _defineSorted(this); $wrapper.find('tr').sort(function (a, b) { return sorted ? +$(a).find('.room_price').text().replace(/€/, '') - +$(b).find('.room_price').text().replace(/€/, '') : +$(b).find('.room_price').text().replace(/€/, '') - +$(a).find('.room_price').text().replace(/€/, ''); }).appendTo($wrapper); }); } /** * Define review sort asc/desc * @param data * @private */ function _bindReviewSort(data, step) { var $wrapper = $('.reviews_list'), $document = $(document); // Sort by score $document.on('click', '.reviews h2 span:first', function () { var sorted = _defineSorted(this); $wrapper.find('.one_review').sort(function (a, b) { return sorted ? +$(b).find('.review_score').text() - +$(a).find('.review_score').text() : +$(a).find('.review_score').text() - +$(b).find('.review_score').text(); }).appendTo($wrapper); }); $document.on('click', '.reviews h2 span:last', function () { var sorted = _defineSorted(this), items = [], res = {}, key, i; for (key in data) items[key] = data[key]; items.sort(function (a, b) { var a1, b1; if (sorted) { a1 = +a.ranking; b1 = +b.ranking; } else { b1 = +a.ranking; a1 = +b.ranking; } return a1 < b1 ? -1 : (a1 > b1 ? 1 : 0); }); for (i = 0; i < items.length; i++) res[i] = items[i]; $('.reviews_paginate li').off(); _renderReviewsPagination(items, step); }); } /** * Define reviews pagination * @param data * @param step * @private */ function _renderReviewsPagination(data, step) { var $paginate = $('.reviews_paginate').html(''), content = [], i = 0, l = Math.ceil(Object.keys(data).length / step); for (; i < l; i++) { content.push('<li>' + (i + 1) + '</li>'); } $paginate.append(content); $paginate.find('li').on('click', function () { var $li = $(this); if ($li.hasClass('current')) { return false; } $paginate.find('li').removeClass('current'); var current = +$li.addClass('current').text(); _renderReviews(data, (current - 1) * step, current * step); }); $paginate.find('li:first').trigger('click'); } /** * Define image gallery binding * @private */ function _bindImageGallery() { var $photos = $('.photos li'); function _resize() { var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); var $modal = $('.modal-gallery'), $html = $('html'), delta = ($html.outerHeight() - $html.height()) / 2; if ($modal.length) { $modal.css({ left: w / 2 - $modal.width() / 2, top: h / 2 - $modal.height() / 2 - delta }); } } $(window).on('resize', _resize); $.each($photos, function () { var $anchor = $(this).find('a'); var img = new Image; img.src = $anchor[0].href; img.onload = function () { }; img.onerror = function () { $anchor.off(); }; $anchor.on('click', function (e) { e.preventDefault(); var $this = $(e.target), interval; /** * Update image * @param {Event} event * @param {string} side * @param which * @private */ function _updateImage(event, side, which) { if (which.length) { $('.modal-gallery img').attr('src', which.attr('href')); $('.modal-gallery .image-alt').text($('img', which).attr('alt')), $('.arrow.left').removeClass('disabled'); $('.arrow.right').removeClass('disabled'); $this = which; } else { $('.arrow.' + side).addClass('disabled'); side === 'left' ? _updateImage(event, side, $('.photos li:last>a')) : _updateImage(event, side, $('.photos li:first>a')); } if (event.hasOwnProperty('originalEvent')) { _stopLoader(); } else { _imageAutoLoader(side); } } /** * Define image auto rotate * @private */ function _imageAutoLoader(side) { var $preload = $('.modal-gallery .preload'), maxWidth = parseInt($('.modal-gallery').width(), 10); interval = setInterval(function () { $preload.css('width', parseInt($preload.css('width'), 10) + 2 + 'px'); if (parseInt($preload.css('width'), 10) > maxWidth) { _stopLoader(); $('.modal-gallery .' + side).trigger('click'); $('.modal-gallery .preload').css('width', 0); } }, 30); $('.image-play').html('&#9616;&#9616;').addClass('image-stop'); } /** * Define stop loader * @private */ function _stopLoader() { clearInterval(interval); $('.image-play').html('&#9658;').removeClass('image-stop'); } $('<div />').addClass('overlay').append( $('<div />'). addClass('modal-gallery'). append([ $('<div title="Move left" class="arrow left" />').html('&#10094;').on('click', function (e) { _updateImage(e, 'left', $this.parents('li').prev().find('a')); }), $('<img />').attr('src', this.href), $('<div class="image-play" />').html('&#9658;').on('click', function () { if ($(this).html() === $('<div />').html('&#9658;').html()) { $(this).html('&#9616;&#9616;').addClass('image-stop'); _imageAutoLoader('right'); } else { _stopLoader(); } }), $('<div class="image-alt" />').text($('img', $this.parents('li')).attr('alt')), $('<div title="Move right" class="arrow right" />').html('&#10095;').on('click', function (e) { _updateImage(e, 'right', $this.parents('li').next().find('a')); }), $('<div title="Close" class="close" />').html('&#10006;').on('click', function () { $('.overlay').off().remove(); _stopLoader(); }), $('<div class="preload" />') ]) ).appendTo('body'); $('.image-alt').slideDown(); _resize(); }); }); } /** * Update info * @param hotel * @private */ function _updateHotelInfo(hotel) { $('.hotel_name').html( hotel.name + ' <span class="stars">' + '★'.repeat(hotel.ranking) + '</span>' ); $('.hotel_address').text(hotel.location); } /** * Define map renderer * @param hotel * @private */ function _renderMap(hotel) { var geocoder = new google.maps.Geocoder(), mapOptions = {zoom: 15}, map = new google.maps.Map($('.description .map')[0], mapOptions), infowindow = new google.maps.InfoWindow(), location, address = hotel.location; /** * Create marker * @param place */ function createMarker(place) { var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function () { infowindow.setContent(place.name); infowindow.open(map, this); }); } geocoder.geocode({'address': address}, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { location = results[0].geometry.location; map.setCenter(location); var marker = new google.maps.Marker({ map: map, icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', position: results[0].geometry.location }); var request = { location: location, radius: '500', types: ['store'] }; var service = new google.maps.places.PlacesService(map); service.nearbySearch(request, function (results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { createMarker(results[i]); } } }); } else { alert('Geocode was not successful for the following reason: ' + status); } }); } /** * Define hotel instance * @type {Item} */ var hotel; $(document).ready(function () { /** * Define hotel instance * @type {Item} */ hotel = new Item("Hotel", { name: data.name, ranking: data.ranking, location: data.location }); var paginationStep = 5; var images = _collectItems('Images', 0, data.images), description = _collectItems('Description', 1, data.description), facilities = _collectItems('Facilities', 2, data.facilities), rooms = _collectItems('Rooms', 3, data.rooms), reviews = _collectItems('Reviews', 4, data.reviews); _updateHotelInfo(hotel); _renderImages(images.items); _renderDescription(description.items); _renderFacilities(facilities.items); _renderRooms(rooms.items); _renderReviewsPagination(reviews.items, paginationStep); _renderMap(hotel); _bindTableSort(); _bindReviewSort(reviews.items, paginationStep); _bindImageGallery(); }); })();
import fs from 'fs' import bluebird from 'bluebird' const readFile = bluebird.promisify(fs.readFile) const writeFile = bluebird.promisify(fs.writeFile) const upload = (array) => bluebird.each(array, (file) => readFile(file.path).then((img) => writeFile('/tmp/' + file.filename, img))) export default upload
Ext.define('Flux.controller.UserExperience', { extend: 'Ext.app.Controller', requires: [ 'Ext.form.field.Display', 'Ext.form.field.TextArea', 'Ext.window.Window' ], refs: [{ ref: 'sourcePanel', selector: 'sourcepanel' }, { ref: 'symbology', selector: 'symbology' }, { 'ref': 'topToolbar', 'selector': 'viewport toolbar' }], init: function () { var params = window.location.href.split('?'); // Get the HTTP GET query parameters, if any // Create a new state Provider if one doesn't already exist if (Ext.state.Manager.getProvider().path === undefined) { Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider')); } // If HTTP GET query parameters were specified, use them to set the // application state if (params.length > 1) { params = Ext.Object.fromQueryString(params.pop()); // Since Aggregation and Difference views cannot be simultaneously shown, // if both are set to true, reset Difference to false if (params.hasOwnProperty('showAggregation') && params.showAggregation === 'true' && params.hasOwnProperty('showDifference') && params.showDifference === 'true') { params.showDifference = false; } this.setStateFromParams(params); // Automatically load data if "source" is specified if (params.hasOwnProperty('source') && params.source.length > 0) { Ext.onReady(function () { this.preloadDataFromGetParams(params); }, this); } // // Send notice that date/time are ignored unless "source" is specified // if (((params.hasOwnProperty('date') && params.date.length > 0) || // (params.hasOwnProperty('time') && params.time.length > 0)) && // !params.hasOwnProperty('source') || !params.source.length) { // Ext.Msg.alert('Alert','"date" and "time" URL parameters are ignored unless "source" is specified'); // } } //////////////////////////////////////////////////////////////////////// // Event Listeners ///////////////////////////////////////////////////// this.control({ '#clear-local-state': { click: this.clearLocalState }, '#get-share-link': { click: this.displaySharingLink }, '#settings-menu menucheckitem': { checkchange: this.onStatsChange }, '#settings-menu numberfield[name=tendencyCustomValue]': { change: this.onStatsChange }, 'sourcepanel fieldset': { afterrender: this.initFieldsets }, 'viewport #content': { beforerender: this.initContent } }); }, //////////////////////////////////////////////////////////////////////////// // Event Handlers ////////////////////////////////////////////////////////// /** Wipes out all state information stored on the client's web browser. */ clearLocalState: function () { Ext.each(this.getFieldNames(), function (key) { Ext.state.Manager.clear(key); }); }, /** Displays a pop-up utility that has a link (URI) that can be used to load the application with the user's current state and data view. */ displaySharingLink: function () { var w = Ext.create('Ext.window.Window', { modal: true, width: 400, height: 300, bodyPadding: '5 10 0 10', layout: 'form', title: 'Share the Current View', buttons: [{ text: 'OK', handler: function () { this.up('window').close(); } }], items: [{ xtype: 'displayfield', labelWidth: '100%', labelSeparator: '', fieldLabel: "Use this link to restore the application to the way it looks right now. Share this link with someone else so they can see exactly what you're seeing." }, { xtype: 'textarea', height: 150, readOnly: true, fieldStyle: 'font-family:monospace;', value: Ext.String.format('{0}?{1}', window.location.href.split('?')[0], this.getStateHash()) }] }); w.show(); }, /** Returns an Array of all the field names in the application. @return {Array} */ getFieldNames: function () { var names = Ext.Array.map(Ext.ComponentQuery.query('field[name]'), function (i) { return i.stateId || ((typeof i.getName === 'function') ? i.getName() : i.name); }); names = names.concat(Ext.Array.map(this.getTopToolbar().query('field[name], menuitem[name]'), function (i) { return i.stateId || ((typeof i.getName === 'function') ? i.getName() : i.name); })); names = Ext.Array.map(names, function (name) { return (Ext.String.endsWith(name, '-inputEl')) ? undefined : name; }); return Ext.Array.clean(names); }, /** Returns an HTTP GET query string encapsulating all the selections made by a user. @return {String} */ getStateHash: function () { return Ext.Object.toQueryString(this.getUserSelections()); }, /** Returns an Object encapsulating all the selections made by a user. @return {Object} */ getUserSelections: function () { var query = Ext.ComponentQuery.query('form'); var params = {}; var cmp = Ext.ComponentQuery.query('tabbedpanel[itemId=single-map]')[0]; Ext.each(query, function (form) { // This conditional basically just says to ignore the inactive Data Sources tab // ...otherwise, a value in the inactive tab may overwrite the same-named value // in the active tab if (!(['gridded-map','non-gridded-map'].indexOf(form.itemId) > -1 && cmp.getActiveTab().itemId != form.itemId)) { Ext.merge(params, form.getValues()); } }); return params; }, /** Ensures that the Aggreation Fieldset is enabled if the "Statistics from..." setting is set to the "Current Data Frame" and the initial date/time fields have been filled out. @param fieldset {Ext.form.Fieldset} */ initFieldsets: function (fieldset) { if (this.getSymbology().down('hiddenfield[name=statsFrom]').getValue() === 'data' && this.getSourcePanel().initialSelectionsMade()) { fieldset.enable(); } else { fieldset.disable(); } }, /** Initializes the #content panel; determines which view(s) are drawn initially. @param panel {Ext.panel.Panel} The #content panel */ initContent: function (panel) { var opts = this.getUserSelections(); if (opts.showLinePlot) { panel.add([{ xtype: 'd3geomap', title: 'Single Map', anchor: '100% 80%', enableZoomControls: true, enableTransitions: true }, { xtype: 'd3lineplot', anchor: '100% 20%' }]); } else { panel.add([{ xtype: 'd3geomap', title: 'Single Map', anchor: '100% 100%', enableZoomControls: true, enableTransitions: true }]); } }, /** Chains server requests so as to preload data according to GET parameters specified in URL @param params {Ext.Object.fromQueryString} */ preloadDataFromGetParams: function (params) { var gridded = true; var tabPanel = Ext.ComponentQuery.query('tabbedpanel[itemId=single-map]')[0] if (params.hasOwnProperty('start') && params.start.length > 0 && params.hasOwnProperty('end') && params.end.length > 0) { gridded = false; tabPanel.setActiveTab('non-gridded-map'); } if (gridded) { tabPanel.getActiveTab().down('checkbox[name=showGridded]').setValue(params.showGridded); // tabPanel.getActiveTab().down('checkbox[name=showGridded]').setDisabled(false); } // First get metadata Ext.Ajax.request({ method: 'GET', url: '/flux/api/scenarios.json', params: { scenario: params.source }, failure: function (response) { Ext.Msg.alert('Request Error: scenarios.json', Ext.String.format('{0}: Ensure that source "{1}" exists', response.responseText, params.source ) ); }, // If successful, bindMetadata and get xy data success: function (response) { var request_params = {}; var ui = this.getController('UserInteraction'); var view = ui.getMap(); var meta = Ext.create('Flux.model.Metadata', Ext.JSON.decode(response.responseText)); ui._initLoad = true; this.getStore('metadata').add(meta); ui.bindMetadata(view, meta); var date = meta.get('dates')[0].format('YYYY-MM-DD'); if (params.hasOwnProperty('date') && params.date.length > 0) { date = params.date; } var time = meta.getTimes()[0]; if (params.hasOwnProperty('time') && params.time.length > 0) { time = params.time; } datetime = Ext.String.format('{0}T{1}:00.000Z', date, time); //////////////////////////////////////////////////////////// // Handle request // Set date/time to first value in metadata unless specified // in the GET request if (!gridded) { request_params = { start: params.start, end: params.end } } else { request_params = { time: datetime } // Reformat request parameters if aggregation params are included if (params.hasOwnProperty('showAggregation') && params.showAggregation && params.hasOwnProperty('intervals') && params.intervals.length > 0 && params.hasOwnProperty('intervalGrouping') && params.intervalGrouping.length > 0 && params.hasOwnProperty('aggregate') && params.aggregate.length > 0) { request_params = { aggregate: params.aggregate, start: datetime, end: moment(datetime). clone(). add(params.intervals,params.intervalGrouping). toISOString() }; } } Ext.Ajax.request({ method: 'GET', url: Ext.String.format('/flux/api/scenarios/{0}/xy.json', params.source), params: request_params, failure: function (response) { Ext.Msg.alert('Request Error: xy.json', Ext.String.format('{0}: Source="{1}"; Params="{2}', response.responseText, params.source, request_params ) ); }, // If successful, bind layer and get raster grid success: function (response, opts) { // This basically recreated fetchRaster. Merged as needed. var rast; rast = Ext.create('Flux.model.Raster', Ext.JSON.decode(response.responseText)); // Create a unique ID that can be used to find this grid rast.set('_id', Ext.String.format('source={0}&{1}', params.source, Ext.Object.toQueryString(opts.params) ) ); // Create a unique ID that can be used to find this grid rast.set('features_raw', JSON.parse(JSON.stringify(rast.get('features')))); rast.set('offset', 0); rast.set('source', params.source); ui.bindLayer(view, rast); ui.onMapLoad(rast); Ext.Ajax.request({ method: 'GET', url: Ext.String.format('/flux/api/scenarios/{0}/grid.json', params.source), failure: function (response) { Ext.Msg.alert('Request Error: grid.json', Ext.String.format('{0}: Ensure that source "{1}" exists', response.responseText, params.source ) ); }, // Now that everything is loaded, set the source field and redraw the map success: function (response) { var grid = Ext.create('Flux.model.RasterGrid', Ext.JSON.decode(response.responseText)); ui.getStore('rastergrids').add(grid); ui.bindRasterGrid(view, grid); // Now that all the data has been successfully retrieved, set the // source drop-down field name to the parameter name. // The date/time fields are set w/in propagateMetadata tabPanel.getActiveTab().down('field[name=source]').setValue(params.source); tabPanel.getActiveTab().down('recheckbox[name=showAggregation]').setValue(params.showAggregation); tabPanel.getActiveTab().down('checkbox[name=showGridded]').setValue(params.showGridded); tabPanel.getActiveTab().down('checkbox[name=showGridded]').setDisabled(false); // Finally, trigger redraw() to draw the data on the map view.redraw(); view.mostRecentRasterParams = request_params; //////////////////////////////////////////////////////////// // Now that source data is loaded, handle difference view request if (params.hasOwnProperty('showDifference') && params.showDifference && params.hasOwnProperty('source2') && params.source2.length > 0 && params.hasOwnProperty('date2') && params.date2.length > 0 && params.hasOwnProperty('time2') && params.time2.length > 0) { // NOTE: Only available for the Single Map visualization thus far diffTime = moment.utc(Ext.String.format('{0}T{1}:00', params.date2, params.time2)); if (diffTime.isSame(moment.utc(datetime))) { Ext.Msg.alert('Request Error', 'First timestamp and second timestamp are the same in requested difference image; will not display.'); return; } Ext.Ajax.request({ method: 'GET', url: Ext.String.format('/flux/api/scenarios/{0}/xy.json', params.source2), params: {time: diffTime.toISOString()}, failure: function (response) { Ext.Msg.alert('Request Error: xy.json', Ext.String.format('{0}: Source="{1}"; Params="{2}', response.responseText, params.source2, params ) ); }, success: function (response, opts) { var rast2; rast2 = Ext.create('Flux.model.Raster', Ext.JSON.decode(response.responseText)); // Create a unique ID that can be used to find this grid rast2.set('_id', Ext.String.format('source={0}&{1}', params.source2, Ext.Object.toQueryString(opts.params) ) ); // Create the differenced grid var rastNew; var f1 = rast.get('features'); var f2 = rast2.get('features'); if (f1.length !== f2.length) { Ext.Msg.alert('Data Error', 'Cannot display the difference of two maps with difference grids. Choose instead maps from two different data sources and/or times that have the same underlying grid.'); } // Add these model instances to the view's store //ui.getStore.add(rast, rast2); rastNew = Ext.create('Flux.model.Raster', { features: (function () { var i; var g = []; for (i = 0; i < f1.length; i += 1) { g.push(f1[i] - f2[i]); } return g; }()), timestamp: rast.get('timestamp'), properties: { title: ui.getDifferencedMapTitle(rast, rast2, view.timeFormat), timestamp_diff: rast2.get('timestamp') } }); ui.bindLayer(view, rastNew); ui.onMapLoad(rastNew); // Now that all the data has been successfully retrieved, set the // source2 drop-down field name to the parameter name. ui._initLoad = true; tabPanel.getActiveTab().down('recheckbox[name=showDifference]').setValue(true); tabPanel.getActiveTab().down('field[name=source2]').setValue(params.source2); tabPanel.getActiveTab().down('field[name=date2]').setValue(params.date2); tabPanel.getActiveTab().down('field[name=time2]').setValue(params.time2); tabPanel.getActiveTab().down('recheckbox[name=syncDifference]').setValue(params.syncDifference); ui._initLoad = false; } }); } ui._initLoad = false; }, scope: this }); }, scope: this }); }, scope: this }) }, /** If checked, update all hidden "tendency" fields with the measure of central tendency chosen. @param cb {Ext.menu.MenuCheckItem} @param checked {Boolean} */ onStatsChange: function (cb, checked) { var targets; if (checked) { if (cb.name === 'tendencyCustomValue') { this.getSymbology().down('hiddenfield[name=tendency]').setValue(cb.value); } else { this.getSymbology().down(Ext.String.format('hiddenfield[name={0}]', cb.group)).setValue(cb.name); if (cb.name === 'population' || cb.name === 'data') { targets = this.getSourcePanel().query('fieldset checkbox'); Ext.each(targets, Ext.Function.bind(function (target) { if (cb.name === 'population') { target.setValue(false); } // Enable the FieldSet only if the initial selections at // the top of the form have been made target.up('fieldset').setDisabled(cb.name === 'population' || !this.getSourcePanel().initialSelectionsMade()); }, this)); } } } this.saveFieldState(cb, checked); }, /** Saves state for a given field that cannot otherwise save its own state (usually because it lacks a setter/getter method). @param field {Ext.form.Field} @param value {Object|Number|String} */ saveFieldState: function (field, value) { Ext.state.Manager.set(field.stateId, value); }, /** Sets UI state based on params object 'params' can be either interpreted by fromQueryString or passed directly from the getUserSelections() method @param {Object} */ setStateFromParams: function (params) { Ext.Object.each(params, function (key, value) { // Replace "true" or "false" (String) with Boolean if (value === 'true' || value === 'false') { params[key] = value = (value === 'true'); } // IMPORTANT: Makes sure that applyState() recalls the correct state Ext.state.Manager.set(key, {value: value}); // Initialize global settings (Ext.menu.CheckItem instances) if (Ext.Array.contains(['tendency', 'display', 'statsFrom'], key)) { Ext.onReady(function () { var cmp = Ext.ComponentQuery.query(Ext.String.format('menucheckitem[name={0}]', value))[0]; if (cmp) { cmp.setChecked(true); } }); } // If a custom central tendency is selected, enable the numberfield // (it is disabled by default) and set the provided value if (key === 'tendency' && ['mean','median'].indexOf(value) === -1) { Ext.onReady(function () { var cmp = Ext.ComponentQuery.query('field[name=tendencyCustomValue]')[0]; cmp.setDisabled(false); cmp.setValue(value); }); } }); } });
define("Cedtory/mods/qwery",function(require,exports,module){ (function (name, context, definition) { module.exports = definition() })('qwery', this, function () { var doc = document , html = doc.documentElement , byClass = 'getElementsByClassName' , byTag = 'getElementsByTagName' , qSA = 'querySelectorAll' , useNativeQSA = 'useNativeQSA' , tagName = 'tagName' , nodeType = 'nodeType' , select , id = /#([\w\-]+)/ , clas = /\.[\w\-]+/g , idOnly = /^#([\w\-]+)$/ , classOnly = /^\.([\w\-]+)$/ , tagOnly = /^([\w\-]+)$/ , tagAndOrClass = /^([\w]+)?\.([\w\-]+)$/ , splittable = /(^|,)\s*[>~+]/ , normalizr = /^\s+|\s*([,\s\+\~>]|$)\s*/g , splitters = /[\s\>\+\~]/ , splittersMore = /(?![\s\w\-\/\?\&\=\:\.\(\)\!,@#%<>\{\}\$\*\^'"]*\]|[\s\w\+\-]*\))/ , specialChars = /([.*+?\^=!:${}()|\[\]\/\\])/g , simple = /^(\*|[a-z0-9]+)?(?:([\.\#]+[\w\-\.#]+)?)/ , attr = /\[([\w\-]+)(?:([\|\^\$\*\~]?\=)['"]?([ \w\-\/\?\&\=\:\.\(\)\!,@#%<>\{\}\$\*\^]+)["']?)?\]/ , pseudo = /:([\w\-]+)(\(['"]?([^()]+)['"]?\))?/ , easy = new RegExp(idOnly.source + '|' + tagOnly.source + '|' + classOnly.source) , dividers = new RegExp('(' + splitters.source + ')' + splittersMore.source, 'g') , tokenizr = new RegExp(splitters.source + splittersMore.source) , chunker = new RegExp(simple.source + '(' + attr.source + ')?' + '(' + pseudo.source + ')?') var walker = { ' ': function (node) { return node && node !== html && node.parentNode } , '>': function (node, contestant) { return node && node.parentNode == contestant.parentNode && node.parentNode } , '~': function (node) { return node && node.previousSibling } , '+': function (node, contestant, p1, p2) { if (!node) return false return (p1 = previous(node)) && (p2 = previous(contestant)) && p1 == p2 && p1 } } function cache() { this.c = {} } cache.prototype = { g: function (k) { return this.c[k] || undefined } , s: function (k, v, r) { v = r ? new RegExp(v) : v return (this.c[k] = v) } } var classCache = new cache() , cleanCache = new cache() , attrCache = new cache() , tokenCache = new cache() function classRegex(c) { return classCache.g(c) || classCache.s(c, '(^|\\s+)' + c + '(\\s+|$)', 1) } function each(a, fn) { var i = 0, l = a.length for (; i < l; i++) fn(a[i]) } function flatten(ar) { for (var r = [], i = 0, l = ar.length; i < l; ++i) arrayLike(ar[i]) ? (r = r.concat(ar[i])) : (r[r.length] = ar[i]) return r } function arrayify(ar) { var i = 0, l = ar.length, r = [] for (; i < l; i++) r[i] = ar[i] return r } function previous(n) { while (n = n.previousSibling) if (n[nodeType] == 1) break; return n } function q(query) { return query.match(chunker) } function interpret(whole, tag, idsAndClasses, wholeAttribute, attribute, qualifier, value, wholePseudo, pseudo, wholePseudoVal, pseudoVal) { var i, m, k, o, classes if (this[nodeType] !== 1) return false if (tag && tag !== '*' && this[tagName] && this[tagName].toLowerCase() !== tag) return false if (idsAndClasses && (m = idsAndClasses.match(id)) && m[1] !== this.id) return false if (idsAndClasses && (classes = idsAndClasses.match(clas))) { for (i = classes.length; i--;) if (!classRegex(classes[i].slice(1)).test(this.className)) return false } if (pseudo && qwery.pseudos[pseudo] && !qwery.pseudos[pseudo](this, pseudoVal)) return false if (wholeAttribute && !value) { o = this.attributes for (k in o) { if (Object.prototype.hasOwnProperty.call(o, k) && (o[k].name || k) == attribute) { return this } } } if (wholeAttribute && !checkAttr(qualifier, getAttr(this, attribute) || '', value)) { return false } return this } function clean(s) { return cleanCache.g(s) || cleanCache.s(s, s.replace(specialChars, '\\$1')) } function checkAttr(qualify, actual, val) { switch (qualify) { case '=': return actual == val case '^=': return actual.match(attrCache.g('^=' + val) || attrCache.s('^=' + val, '^' + clean(val), 1)) case '$=': return actual.match(attrCache.g('$=' + val) || attrCache.s('$=' + val, clean(val) + '$', 1)) case '*=': return actual.match(attrCache.g(val) || attrCache.s(val, clean(val), 1)) case '~=': return actual.match(attrCache.g('~=' + val) || attrCache.s('~=' + val, '(?:^|\\s+)' + clean(val) + '(?:\\s+|$)', 1)) case '|=': return actual.match(attrCache.g('|=' + val) || attrCache.s('|=' + val, '^' + clean(val) + '(-|$)', 1)) } return 0 } function _qwery(selector, _root) { var r = [], ret = [], i, l, m, token, tag, els, intr, item, root = _root , tokens = tokenCache.g(selector) || tokenCache.s(selector, selector.split(tokenizr)) , dividedTokens = selector.match(dividers) if (!tokens.length) return r token = (tokens = tokens.slice(0)).pop() if (tokens.length && (m = tokens[tokens.length - 1].match(idOnly))) root = byId(_root, m[1]) if (!root) return r intr = q(token) els = root !== _root && root[nodeType] !== 9 && dividedTokens && /^[+~]$/.test(dividedTokens[dividedTokens.length - 1]) ? function (r) { while (root = root.nextSibling) { root[nodeType] == 1 && (intr[1] ? intr[1] == root[tagName].toLowerCase() : 1) && (r[r.length] = root) } return r }([]) : root[byTag](intr[1] || '*') for (i = 0, l = els.length; i < l; i++) { if (item = interpret.apply(els[i], intr)) r[r.length] = item } if (!tokens.length) return r each(r, function (e) { if (ancestorMatch(e, tokens, dividedTokens)) ret[ret.length] = e }) return ret } function is(el, selector, root) { if (isNode(selector)) return el == selector if (arrayLike(selector)) return !!~flatten(selector).indexOf(el) var selectors = selector.split(','), tokens, dividedTokens while (selector = selectors.pop()) { tokens = tokenCache.g(selector) || tokenCache.s(selector, selector.split(tokenizr)) dividedTokens = selector.match(dividers) tokens = tokens.slice(0) if (interpret.apply(el, q(tokens.pop())) && (!tokens.length || ancestorMatch(el, tokens, dividedTokens, root))) { return true } } return false } function ancestorMatch(el, tokens, dividedTokens, root) { var cand function crawl(e, i, p) { while (p = walker[dividedTokens[i]](p, e)) { if (isNode(p) && (interpret.apply(p, q(tokens[i])))) { if (i) { if (cand = crawl(p, i - 1, p)) return cand } else return p } } } return (cand = crawl(el, tokens.length - 1, el)) && (!root || isAncestor(cand, root)) } function isNode(el, t) { return el && typeof el === 'object' && (t = el[nodeType]) && (t == 1 || t == 9) } function uniq(ar) { var a = [], i, j; o: for (i = 0; i < ar.length; ++i) { for (j = 0; j < a.length; ++j) if (a[j] == ar[i]) continue o a[a.length] = ar[i] } return a } function arrayLike(o) { return (typeof o === 'object' && isFinite(o.length)) } function normalizeRoot(root) { if (!root) return doc if (typeof root == 'string') return qwery(root)[0] if (!root[nodeType] && arrayLike(root)) return root[0] return root } function byId(root, id, el) { return root[nodeType] === 9 ? root.getElementById(id) : root.ownerDocument && (((el = root.ownerDocument.getElementById(id)) && isAncestor(el, root) && el) || (!isAncestor(root, root.ownerDocument) && select('[id="' + id + '"]', root)[0])) } function qwery(selector, _root) { var m, el, root = normalizeRoot(_root) if (!root || !selector) return [] if (selector === window || isNode(selector)) { return !_root || (selector !== window && isNode(root) && isAncestor(selector, root)) ? [selector] : [] } if (selector && arrayLike(selector)) return flatten(selector) if (m = selector.match(easy)) { if (m[1]) return (el = byId(root, m[1])) ? [el] : [] if (m[2]) return arrayify(root[byTag](m[2])) if (hasByClass && m[3]) return arrayify(root[byClass](m[3])) } return select(selector, root) } function collectSelector(root, collector) { return function (s) { var oid, nid if (splittable.test(s)) { if (root[nodeType] !== 9) { if (!(nid = oid = root.getAttribute('id'))) root.setAttribute('id', nid = '__qwerymeupscotty') s = '[id="' + nid + '"]' + s collector(root.parentNode || root, s, true) oid || root.removeAttribute('id') } return; } s.length && collector(root, s, false) } } var isAncestor = 'compareDocumentPosition' in html ? function (element, container) { return (container.compareDocumentPosition(element) & 16) == 16 } : 'contains' in html ? function (element, container) { container = container[nodeType] === 9 || container == window ? html : container return container !== element && container.contains(element) } : function (element, container) { while (element = element.parentNode) if (element === container) return 1 return 0 } , getAttr = function () { var e = doc.createElement('p') return ((e.innerHTML = '<a href="#x">x</a>') && e.firstChild.getAttribute('href') != '#x') ? function (e, a) { return a === 'class' ? e.className : (a === 'href' || a === 'src') ? e.getAttribute(a, 2) : e.getAttribute(a) } : function (e, a) { return e.getAttribute(a) } }() , hasByClass = !!doc[byClass] , hasQSA = doc.querySelector && doc[qSA] , selectQSA = function (selector, root) { var result = [], ss, e try { if (root[nodeType] === 9 || !splittable.test(selector)) { return arrayify(root[qSA](selector)) } each(ss = selector.split(','), collectSelector(root, function (ctx, s) { e = ctx[qSA](s) if (e.length == 1) result[result.length] = e.item(0) else if (e.length) result = result.concat(arrayify(e)) })) return ss.length > 1 && result.length > 1 ? uniq(result) : result } catch (ex) { } return selectNonNative(selector, root) } , selectNonNative = function (selector, root) { var result = [], items, m, i, l, r, ss selector = selector.replace(normalizr, '$1') if (m = selector.match(tagAndOrClass)) { r = classRegex(m[2]) items = root[byTag](m[1] || '*') for (i = 0, l = items.length; i < l; i++) { if (r.test(items[i].className)) result[result.length] = items[i] } return result } each(ss = selector.split(','), collectSelector(root, function (ctx, s, rewrite) { r = _qwery(s, ctx) for (i = 0, l = r.length; i < l; i++) { if (ctx[nodeType] === 9 || rewrite || isAncestor(r[i], root)) result[result.length] = r[i] } })) return ss.length > 1 && result.length > 1 ? uniq(result) : result } , configure = function (options) { if (typeof options[useNativeQSA] !== 'undefined') select = !options[useNativeQSA] ? selectNonNative : hasQSA ? selectQSA : selectNonNative } configure({ useNativeQSA: true }) qwery.configure = configure qwery.uniq = uniq qwery.is = is qwery.pseudos = {} return qwery }); });
import React from 'react'; import { IconInfoBadgedSmallFilled, IconMarkerSmallOutline } from '@teamleader/ui-icons'; import { Icon, Input, Label, TextSmall, Tooltip } from '../../index'; import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils'; const TooltippedIcon = Tooltip(Icon); export default { component: Label, title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Form elements/Label'), }; export const DefaultStory = (args) => ( <Label {...args} htmlFor="input1" connectedLeft={ <Icon> <IconMarkerSmallOutline /> </Icon> } connectedRight={ <TooltippedIcon tooltip={<TextSmall>This is the label tooltip text</TextSmall>} tooltipSize="small"> <IconInfoBadgedSmallFilled /> </TooltippedIcon> } > Input label <Input id="input1" placeholder="I am the placeholder" /> </Label> ); DefaultStory.args = { helpText: 'Optional', };
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_network_endpointservice");
// 문자열의 오른쪽을 trim 합니다.역쉬 트림 수정하신분 세세함이 돋보입니다! clean.string.rTrim = (function(){ var regExTrim; // rTrim 을 지원하면 if( !!String.prototype.rTrim ){ return function( target ){ //REQUIRED: target: 바꿀 대상의 문자열입니다! return target.rTrim(); }; // rTrim 을 지원하지 않으면 }else{ regExTrim = /\s+$/; return function( target ){ //REQUIRED: target: 바꿀 대상의 문자열입니다! return target.replace( regExTrim, '' ); }; } })();
function konami() { var arr = []; var konami = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13]; document.addEventListener('keyup', function(e) { arr.push(e.keyCode); if (arr.length >= 12) arr.shift(); if (arr.toString() === konami.toString()) cheatMode(); }); } function cheatMode() {}
// Example webpack configuration for React with live reloading in development // and asset fingerprinting in production. "use strict"; var path = require("path"); var webpack = require("webpack"); // Helpers are hardcoded to expect dev assets at http://localhost:3808/webpack/* var devServerPort = 3808; // set TARGET=production on the environment to add asset fingerprints & // omit hot-reloading var production = process.env.TARGET === "production"; var config = { entry: { // Sources are expected to live in $app_root/webpack application: [ "./webpack/application.js" ] }, output: { // Build assets directly in to public/webpack/, let webpack know // that all webpacked assets start with webpack/ path: path.join(__dirname, "public", "webpack"), publicPath: "/webpack", // Add asset fingerprinting to production compiled assets with 'chunkhash' filename: production ? "[name]-[chunkhash].js" : "[name].js" }, module: { loaders: [ // Example react JSX loader, with hot-reloading in development { test: /\.jsx?$/, loaders: production ? ["jsx?harmony"] : ["react-hot", "jsx?harmony"], include: path.join(__dirname, "webpack") } ] }, resolve: { extensions: ["", ".js", ".jsx"] }, // Sourcemaps in both production & development devtool: "cheap-module-eval-source-map" }; if(!production) { config.devServer = { port: devServerPort }; // react-hot-loader configuration bits config.plugins = [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ]; Object.keys(config.entry).forEach(function(entryPoint) { config.entry[entryPoint] = [ "webpack-dev-server/client?http://0.0.0.0:" + devServerPort, "webpack/hot/only-dev-server" ].concat(config.entry[entryPoint]); }); } module.exports = config;
define([ "src/extender", "src/events", "src/hash.route", "src/model", "src/fetch", "src/style", "src/tmpl", "src/view", "src/resources", "src/spromise", "src/module" ], function(Extender, Events, Hash, Model, Fetch, Style, Tmpl, View, Resources, Promise, Module) { return { Extender: Extender, Events: Events, Hash: Hash, Model: Model, Fetch: Fetch, Style: Style, Tmpl: Tmpl, View: View, Resources: Resources, Promise: Promise, Module: Module }; });
'use strict'; // From: https://github.com/w3c/web-platform-tests/blob/fa9436d12c/encoding/api-surrogates-utf8.html require('../common'); const assert = require('assert'); const { TextDecoder, TextEncoder } = require('util'); const badStrings = [ { input: 'abc123', expected: [0x61, 0x62, 0x63, 0x31, 0x32, 0x33], decoded: 'abc123', name: 'Sanity check' }, { input: '\uD800', expected: [0xef, 0xbf, 0xbd], decoded: '\uFFFD', name: 'Surrogate half (low)' }, { input: '\uDC00', expected: [0xef, 0xbf, 0xbd], decoded: '\uFFFD', name: 'Surrogate half (high)' }, { input: 'abc\uD800123', expected: [0x61, 0x62, 0x63, 0xef, 0xbf, 0xbd, 0x31, 0x32, 0x33], decoded: 'abc\uFFFD123', name: 'Surrogate half (low), in a string' }, { input: 'abc\uDC00123', expected: [0x61, 0x62, 0x63, 0xef, 0xbf, 0xbd, 0x31, 0x32, 0x33], decoded: 'abc\uFFFD123', name: 'Surrogate half (high), in a string' }, { input: '\uDC00\uD800', expected: [0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd], decoded: '\uFFFD\uFFFD', name: 'Wrong order' } ]; badStrings.forEach((t) => { const encoded = new TextEncoder().encode(t.input); assert.deepStrictEqual([].slice.call(encoded), t.expected); assert.strictEqual(new TextDecoder('utf-8').decode(encoded), t.decoded); });
/** * Created by w1 on 8/7/2015. */ /* Run this app to view effects of illum 0 to illum 7 on sphere 0. neon, require Kd, optional map_Kd 1. diffuse, require Kd, Ka, optional map_Kd, map_Ka 2. specular, (1) and require Ks, Ns, optional map_Ks 3. reflection, (2) and require refl (environment map) 4. dissolve, (3) and require d (alpha value) alpha <- d, reflection <- 1-d 5. fresnel, (3) only, add fresnel reflection 6. refraction, (4) and Ni, add refraction effects 7. refraction + fresnel, (6) only, add fresnel effects Texture effects for various map is shown on the four cube from left to right. 1. Kd set to green, map_Kd set to image, illum 0 it's just filtered neon 2. Kd set to green, map_Kd to image, illum 1 it's what green filtered image look like 3. Ks set to green, map_Ks to image, illum 2 this is specular component where reflection from each part of surface is not uniform, i.e. determined by image 4. How the cube should look like without filter. and with constant specular reflection. */ function recursivePrintMesh(mesh, level){ var padding = ""; for(var i=0; i<level; i++){ padding += " "; } console.log(padding + (typeof mesh)); for(var i=0; i < mesh.children.length; i++){ recursivePrintMesh(mesh.children[i], level + 1); } } MtlLoaderDemo = function(){ VG.UI.RenderWidget.call(this); this.viewPort = new VG.Render.Camera(60, this.rect.width/this.rect.height,0.1, 1000); this.viewPort.position = new VG.Math.Vector3(1, -4, 10); this.viewPort.setLookAt(new VG.Math.Vector3(0, 0, 0), new VG.Math.Vector3(0, 0, 1)); this.context = new VG.Render.Context(); this.context.camera = this.viewPort; this.pipeline = new VG.Render.Pipeline(); this.scene = new VG.Render.SceneManager(); files['sample.mtl'] = [ "newmtl textureTest", "Ka 1.0 1.0 0.0", "Kd 1.0 1.0 0.0", "Ks 1.0 1.0 1.0", "Ns 50.0", "map_Ka cube_nx.png", "map_Kd cube_ny.png", "map_Ks cube_nz.png", "illum 2", "newmtl reflTest", "Ka 0.0000 0.0000 0.0000", // glass should have Ka = 0 "Kd 0.0000 0.0000 0.0000", // the color of glass, //"Ks 0.3000 0.3000 0.3000", // slightly reflect "Ks 0.0000 0.0000 0.0000", // no reflect "Ns 100.0", //"refl -type sphere sky-sphere.png", // sphere will be ignored "refl -type cube_top cube_nx.png", "refl -type cube_bottom cube_px.png", "refl -type cube_front cube_py.png", "refl -type cube_back cube_ny.png", "refl -type cube_left cube_nz.png", "refl -type cube_right cube_pz.png", "illum 7", "d 0.5", "Ni 2.0", "newmtl fresnelTest",//illum 5 & 7 "", /** This is a bright green material. When applied to an object, it will remain bright green regardless of any lighting in the scene. */ "newmtl neon_green", "Kd 0.0000 1.0000 0.0000", "illum 0", /** This is a flat green material. */ "newmtl flat_green", "Ka 0.0000 1.0000 0.0000", "Kd 0.0000 1.0000 0.0000", "illum 1", /** This is a flat green, partially dissolved material. */ "newmtl diss_green", "Ka 0.0000 1.0000 0.0000", "Kd 0.0000 1.0000 0.0000", "d 0.8000", "illum 1", /** This is a shiny green material. When applied to an object, it shows a white specular highlight. */ "newmtl shiny_green", "Ka 0.0000 1.0000 0.0000", "Kd 0.0000 1.0000 0.0000", "Ks 1.0000 1.0000 1.0000", "Ns 200.0000", "illum 2", /** This is a reflective green material. When applied to an object, it reflects other objects in the same scene.*/ "newmtl green_mirror", "Ka 0.0000 1.0000 0.0000", "Kd 0.0000 1.0000 0.0000", "Ks 0.0000 1.0000 0.0000", "Ns 200.0000", "illum 3", "newmtl neon_red", "Kd 1.0000 0.0000 0.0000", "illum 0", "newmtl shiny_yellow", "Ka 1.0000 1.0000 0.0000", "Kd 1.0000 1.0000 0.0000", "Ks 1.0000 1.0000 1.0000", "Ns 200.0000", "illum 2", ].join('\n'); files['asteroid.mtl'] = [ "newmtl asteroid_rock", "Ns 0", "Ka 0.000000 0.000000 0.000000", "Kd 0.8 0.8 0.8", "Ks 0.8 0.8 0.8", "d 1", "illum 2", "map_Kd asteroid.jpg", ].join('\n'); var lights = [ { name: 'L0', color:{ ambient: new VG.Core.Color(20, 20, 20), diffuse: new VG.Core.Color(200, 200, 200), specular: new VG.Core.Color(255, 255, 255) }, position: new VG.Math.Vector4(0, 1, 1, 0) } ]; this.context.lights = lights; //var box = VG.Import.loadObj(files['cube1.obj'], files, 0.4); //box.position = new VG.Math.Vector3(1, 1, 1); //box.parent = this.scene; //var box2 = VG.Import.loadObj(files['cube2.obj'], files, 0.5); //box2.parent = this.scene; //var bricks = this.addBricks(this.scene, 2); //var brick = bricks[0]; //brick.material = new VG.Render.MtlMaterial({ // 'Ka':[0, 1, 0], // 'Kd':[0, 1, 0], // 'name': 'green', // 'illum': 1 //}); var reflectMtl = new VG.Render.MtlMaterial({ Ka: [1, 1, 0], Kd: [1, 1, 0], Ks: [1, 1, 1], Ns: 100, refl: { cube_top: {filename: 'cube_nx.png'}, cube_bottom: {filename: 'cube_px.png'}, cube_front: {filename: 'cube_py.png'}, cube_back: {filename: 'cube_ny.png'}, cube_left: {filename: 'cube_nz.png'}, cube_right: {filename: 'cube_pz.png'} }, illum: 3 }); var cube = VG.Import.loadObj(files['cube-textures.obj'], files, 0.5); cube.parent = this.scene; var cube0 = cube.clone(); cube0.children[0].material = new VG.Render.MtlMaterial({ Kd: [0, 1, 0], illum: 0, map_Kd: {filename: 'cube_nx.png'} }); cube0.position = new VG.Math.Vector3(-2.1, 0, 0); cube0.parent = this.scene; var cube1 = cube.clone(); cube1.children[0].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [0, 1, 0], illum: 1, map_Kd: {filename: 'cube_nx.png'} }); cube1.position = new VG.Math.Vector3(-1.5, 0, 0); cube1.parent = this.scene; var cube2 = cube.clone(); cube2.children[0].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [0, 0, 0], Ks: [0, 1, 0], Ns: 1, illum: 2, map_Ks: {filename: 'cube_nx.png'} }); cube2.position = new VG.Math.Vector3(-0.9, 0, 0); cube2.parent = this.scene; var sphere = new VG.Render.SphereMesh(undefined, 64); sphere.setRadius(0.28); sphere.update(); var spheres = []; for(var i = 0; i <= 7; i++) { var s = sphere.clone(); s.position = new VG.Math.Vector3(-2+i*0.6, 1.5, 0); s.parent = this.scene; spheres.push(s); } spheres[0].material = new VG.Render.MtlMaterial({ Kd: [1, 0, 0], illum: 0, }); spheres[1].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [1, 0, 0], illum: 1, }); spheres[2].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [0, 0, 0], Ks: [1, 0, 0], Ns: 10, illum: 2, }); spheres[3].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [0, 0, 0], Ks: [1, 0, 0], Ns: 10, refl: { cube_top: {filename: 'cube_nx.png'}, cube_bottom: {filename: 'cube_px.png'}, cube_front: {filename: 'cube_py.png'}, cube_back: {filename: 'cube_ny.png'}, cube_left: {filename: 'cube_nz.png'}, cube_right: {filename: 'cube_pz.png'} }, illum: 3, }); spheres[4].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [0, 0, 0], Ks: [1, 0, 0], Ns: 10, d: 0.3, refl: { cube_top: {filename: 'cube_nx.png'}, cube_bottom: {filename: 'cube_px.png'}, cube_front: {filename: 'cube_py.png'}, cube_back: {filename: 'cube_ny.png'}, cube_left: {filename: 'cube_nz.png'}, cube_right: {filename: 'cube_pz.png'} }, illum: 4, }); spheres[5].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [0, 0, 0], Ks: [1, 0, 0], Ns: 10, d: 0.3, refl: { cube_top: {filename: 'cube_nx.png'}, cube_bottom: {filename: 'cube_px.png'}, cube_front: {filename: 'cube_py.png'}, cube_back: {filename: 'cube_ny.png'}, cube_left: {filename: 'cube_nz.png'}, cube_right: {filename: 'cube_pz.png'} }, illum: 5, }); spheres[6].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [0, 0, 0], Ks: [1, 0, 0], Ns: 10, d: 0.3, Ni: 2, refl: { cube_top: {filename: 'cube_nx.png'}, cube_bottom: {filename: 'cube_px.png'}, cube_front: {filename: 'cube_py.png'}, cube_back: {filename: 'cube_ny.png'}, cube_left: {filename: 'cube_nz.png'}, cube_right: {filename: 'cube_pz.png'} }, illum: 6, }); spheres[7].material = new VG.Render.MtlMaterial({ Ka: [0, 0, 0], Kd: [0, 0, 0], Ks: [1, 0, 0], Ns: 10, Ni: 2, d: 0.3, refl: { cube_top: {filename: 'cube_nx.png'}, cube_bottom: {filename: 'cube_px.png'}, cube_front: {filename: 'cube_py.png'}, cube_back: {filename: 'cube_ny.png'}, cube_left: {filename: 'cube_nz.png'}, cube_right: {filename: 'cube_pz.png'} }, illum: 7, }); //var cubeIndexed = VG.Render.Mesh.makeBoxIndexed(1, 1, 1); // //cubeIndexed.position = new VG.Math.Vector3(-3.0, 0, 0); //cubeIndexed.parent = this.scene; //var aste = VG.Import.loadObj(files['asteroid.obj'], files, 0.5); //aste.parent = this.scene; var that = this; var dTheta = 0.005; this.render = function(delta) { that.viewPort.aspect = that.rect.width / that.rect.height; that.viewPort.updateProjection(); that.viewPort.rotate(dTheta * 0.5, dTheta); that.pipeline.drawScene(that.context, that.scene, delta); }; }; MtlLoaderDemo.prototype = Object.create(VG.UI.RenderWidget.prototype); MtlLoaderDemo.prototype.addBricks = function (node, count) { /** * Add bricks to node. * Just demo utility * @type {MeshEditor} */ var that = this; var bricks = []; function addBrickAt(x, y, vertical) { var brick = VG.Render.Mesh.makeBox(vertical ? 0.08 : 0.5, vertical ? 0.5 : 0.08, 0.2); brick.position.set(x, y, 0.0); brick.parent = node; /* Some meta data */ brick.vertical = true; bricks.push(brick); } for(var i=0;i<count;i++) { for(var j=0;j<3;j++) { addBrickAt((i - count / 2)*0.5, j*1 -1, true); } } return bricks; }; function vgMain(workspace) { /** * boot function */ var widget = new MtlLoaderDemo(); workspace.layout = VG.UI.Layout(widget); } var files = { 'cube1.obj' :[ "mtllib sample.mtl", "v 0.000000 2.000000 2.000000", "v 0.000000 0.000000 2.000000", "v 2.000000 0.000000 2.000000", "v 2.000000 2.000000 2.000000", "v 0.000000 2.000000 0.000000", "v 0.000000 0.000000 0.000000", "v 2.000000 0.000000 0.000000", "v 2.000000 2.000000 0.000000", "# 8 vertices", "g front cube", "usemtl unknown_material", "f 1 2 3 4", "g back cube", "usemtl flat_green", "f 8 7 6 5", "g right cube", "usemtl neon_green", "f 4 3 7 8", "g top cube", "usemtl shiny_green", "f 5 1 4 8", "g left cube", "usemtl diss_green", "f 5 6 2 1", ].join("\n"), 'cube2.obj' : [ "mtllib sample.mtl", "v 0.000000 2.000000 2.000000", "v 0.000000 0.000000 2.000000", "v 2.000000 0.000000 2.000000", "v 2.000000 2.000000 2.000000", "v 0.000000 2.000000 0.000000", "v 0.000000 0.000000 0.000000", "v 2.000000 0.000000 0.000000", "v 2.000000 2.000000 0.000000", "# 8 vertices", "g front cube", "f 1 2 3 4", "g back cube", "f 8 7 6 5", "g right cube", "usemtl flat_green", "f 4 3 7 8", "g top cube", "usemtl shiny_yellow", "f 5 1 4 8", "g bottom cube", "usemtl neon_red", "f 2 6 7 3", "# 6 elements" ].join("\n"), 'cube3.obj' :[ "v 0.000000 2.000000 2.000000", "v 0.000000 0.000000 2.000000", "v 2.000000 0.000000 2.000000", "v 2.000000 2.000000 2.000000", "v 0.000000 2.000000 0.000000", "v 0.000000 0.000000 0.000000", "v 2.000000 0.000000 0.000000", "v 2.000000 2.000000 0.000000", "f 1 2 3 4", "f 8 7 6 5", "f 4 3 7 8", "f 5 1 4 8", "f 5 6 2 1", "f 7 3 2 6", ].join("\n"), 'asteroid.obj': [ //"mtllib asteroid.mtl", "mtllib sample.mtl", "o Sphere", "v 0.000317 1.255835 -0.000460", "v 0.296554 1.101046 -0.068380", "v 0.350818 0.938378 0.091908", "v 0.597113 0.748474 -0.075610", "v 1.109780 0.120537 -0.000000", "v 0.822984 -0.568065 0.000000", "v 0.239315 -0.970942 0.000000", "v -0.009773 -1.139008 0.015165", "v 0.242118 -1.074288 -0.137984", "v 0.441707 -0.988802 -0.242736", "v 0.587166 -0.748511 -0.308168", "v 0.868153 -0.568065 -0.382460", "v 0.967353 -0.354605 -0.434524", "v 1.018437 -0.120537 -0.461335", "v 0.879000 0.120537 -0.461335", "v 0.827916 0.354605 -0.434524", "v 0.662706 0.568028 -0.458070", "v 0.587166 0.748511 -0.308169", "v 0.411492 0.885456 -0.215968", "v 0.244176 1.024881 -0.142294", "v 0.193185 1.101046 -0.265332", "v 0.263993 0.885456 -0.382460", "v 0.376697 0.748511 -0.545739", "v 0.467508 0.568065 -0.677302", "v 0.531150 0.354605 -0.769503", "v 0.563923 0.120537 -0.816983", "v 0.563923 -0.120537 -0.816983", "v 0.531150 -0.354605 -0.769503", "v 0.606945 -0.568065 -0.677302", "v 0.376697 -0.748511 -0.545739", "v 0.294208 -0.988802 -0.409228", "v 0.135947 -0.970942 -0.196953", "v 0.028846 -0.970942 -0.237571", "v 0.056016 -0.885456 -0.461335", "v 0.079931 -0.748511 -0.658288", "v 0.099200 -0.568065 -0.816983", "v 0.112704 -0.354605 -0.928199", "v 0.119658 -0.120537 -0.985471", "v 0.112697 0.086072 -0.839889", "v 0.105743 0.320140 -0.782617", "v 0.099200 0.568065 -0.816983", "v 0.079931 0.748511 -0.658288", "v 0.056016 0.885456 -0.461335", "v 0.086084 1.101046 -0.305950", "v -0.027624 1.101046 -0.292144", "v -0.148707 1.031706 -0.411219", "v -0.235147 0.748511 -0.620031", "v -0.298795 0.533600 -0.623921", "v -0.331561 0.354605 -0.874255", "v -0.418479 0.120537 -0.882325", "v -0.418479 -0.120537 -0.882325", "v -0.331561 -0.354605 -0.874255", "v -0.250046 -0.504788 -0.708963", "v -0.193358 -0.685234 -0.559490", "v -0.164793 -0.885456 -0.434524", "v -0.084862 -0.970942 -0.223764", "v -0.179130 -0.970942 -0.158695", "v -0.347850 -0.885456 -0.308168", "v -0.454566 -0.685234 -0.379191", "v -0.574224 -0.504788 -0.485199", "v -0.699870 -0.354605 -0.620031", "v -0.809513 -0.120537 -0.612414", "v -0.809513 0.120537 -0.612414", "v -0.699870 0.354605 -0.620031", "v -0.616012 0.568065 -0.545739", "v -0.496354 0.748511 -0.439732", "v -0.331764 1.031706 -0.284864", "v -0.163044 1.203156 -0.135391", "v -0.232362 1.180973 -0.057272", "v -0.451219 1.009522 -0.111216", "v -0.643854 0.748511 -0.158696", "v -0.917637 0.628486 -0.290053", "v -1.026414 0.415026 -0.223764", "v -0.878709 0.120537 -0.237571", "v -0.878709 -0.120537 -0.237571", "v -0.907846 -0.354605 -0.223764", "v -0.799070 -0.568065 -0.196953", "v -0.643853 -0.748511 -0.158696", "v -0.422990 -0.813186 -0.111215", "v -0.204133 -0.898672 -0.057272", "v -0.232361 -0.970942 0.057272", "v -0.422990 -0.813186 0.111216", "v -0.697084 -0.750309 0.238998", "v -0.852300 -0.569863 0.277255", "v -0.812495 -0.319098 0.143199", "v -0.878709 -0.120537 0.237571", "v -0.878709 0.120537 0.237571", "v -0.907846 0.354605 0.223764", "v -0.917637 0.628486 0.103853", "v -0.643854 0.748511 0.158696", "v -0.451219 0.885456 0.111215", "v -0.232362 1.180973 0.057272", "v -0.227905 1.120137 0.229358", "v -0.347850 0.885456 0.308168", "v -0.496355 0.748511 0.439732", "v -0.616012 0.568065 0.545739", "v -0.699870 0.354605 0.620030", "v -0.743053 0.120537 0.658288", "v -0.647702 -0.085029 0.577722", "v -0.607843 -0.259373 0.679487", "v -0.691716 -0.522164 0.579247", "v -0.549585 -0.750309 0.520034", "v -0.347850 -0.885456 0.308168", "v -0.179130 -0.970942 0.158696", "v -0.084862 -0.970942 0.223764", "v -0.164793 -0.885456 0.434524", "v -0.403914 -0.778650 0.682687", "v -0.460601 -0.598204 0.832160", "v -0.331561 -0.354605 0.874255", "v -0.256668 -0.085029 0.847633", "v -0.352019 0.120537 0.928199", "v -0.313392 0.277789 0.724615", "v -0.273665 0.491249 0.619863", "v -0.235147 0.748511 0.620030", "v -0.172823 1.009403 0.500657", "v -0.133637 1.120137 0.294427", "v 0.028846 1.180973 0.237571", "v 0.047986 1.009403 0.527468", "v 0.079931 0.748511 0.658288", "v 0.117369 0.491249 0.667343", "v 0.130873 0.277789 0.778559", "v 0.119658 0.120537 0.985471", "v 0.119658 -0.120537 0.985471", "v 0.111766 -0.350520 0.920473", "v 0.098262 -0.563980 0.809258", "v 0.042417 -0.744955 0.639197", "v 0.056016 -0.885456 0.461335", "v 0.024360 -0.954771 0.249843", "v 0.131460 -0.954771 0.209225", "v 0.246732 -0.812519 0.361050", "v 0.376697 -0.748511 0.545739", "v 0.467508 -0.568065 0.677303", "v 0.648221 -0.354605 0.769503", "v 0.680994 -0.120537 0.816983", "v 0.680994 0.120537 0.816983", "v 0.531150 0.354605 0.769503", "v 0.467508 0.568065 0.677302", "v 0.376697 0.748511 0.545739", "v 0.297744 0.941935 0.437767", "v 0.135947 1.180973 0.196953", "v 0.211903 1.180973 0.111215", "v 0.363597 0.938414 0.383486", "v 0.587166 0.748511 0.308169", "v 0.612858 0.507257 0.353903", "v 0.712057 0.293798 0.405967", "v 0.880212 0.059729 0.432778", "v 0.879000 -0.120537 0.461335", "v 0.944987 -0.354605 0.434524", "v 0.728716 -0.568065 0.382460", "v 0.587166 -0.748511 0.308169", "v 0.394231 -0.812519 0.194558", "v 0.211903 -0.970942 0.111215", "v 0.464723 -0.885456 0.000000", "v 0.663123 -0.748511 0.000000", "v 1.052087 -0.354605 0.000000", "v 1.109780 -0.120537 0.000000", "v 0.819158 0.293798 -0.028556", "v 0.707125 0.507257 -0.028557", "", "", "vn 0.000317 1.255835 -0.000460", "vn 0.296554 1.101046 -0.068380", "vn 0.350818 0.938378 0.091908", "vn 0.597113 0.748474 -0.075610", "vn 1.109780 0.120537 -0.000000", "vn 0.822984 -0.568065 0.000000", "vn 0.239315 -0.970942 0.000000", "vn -0.009773 -1.139008 0.015165", "vn 0.242118 -1.074288 -0.137984", "vn 0.441707 -0.988802 -0.242736", "vn 0.587166 -0.748511 -0.308168", "vn 0.868153 -0.568065 -0.382460", "vn 0.967353 -0.354605 -0.434524", "vn 1.018437 -0.120537 -0.461335", "vn 0.879000 0.120537 -0.461335", "vn 0.827916 0.354605 -0.434524", "vn 0.662706 0.568028 -0.458070", "vn 0.587166 0.748511 -0.308169", "vn 0.411492 0.885456 -0.215968", "vn 0.244176 1.024881 -0.142294", "vn 0.193185 1.101046 -0.265332", "vn 0.263993 0.885456 -0.382460", "vn 0.376697 0.748511 -0.545739", "vn 0.467508 0.568065 -0.677302", "vn 0.531150 0.354605 -0.769503", "vn 0.563923 0.120537 -0.816983", "vn 0.563923 -0.120537 -0.816983", "vn 0.531150 -0.354605 -0.769503", "vn 0.606945 -0.568065 -0.677302", "vn 0.376697 -0.748511 -0.545739", "vn 0.294208 -0.988802 -0.409228", "vn 0.135947 -0.970942 -0.196953", "vn 0.028846 -0.970942 -0.237571", "vn 0.056016 -0.885456 -0.461335", "vn 0.079931 -0.748511 -0.658288", "vn 0.099200 -0.568065 -0.816983", "vn 0.112704 -0.354605 -0.928199", "vn 0.119658 -0.120537 -0.985471", "vn 0.112697 0.086072 -0.839889", "vn 0.105743 0.320140 -0.782617", "vn 0.099200 0.568065 -0.816983", "vn 0.079931 0.748511 -0.658288", "vn 0.056016 0.885456 -0.461335", "vn 0.086084 1.101046 -0.305950", "vn -0.027624 1.101046 -0.292144", "vn -0.148707 1.031706 -0.411219", "vn -0.235147 0.748511 -0.620031", "vn -0.298795 0.533600 -0.623921", "vn -0.331561 0.354605 -0.874255", "vn -0.418479 0.120537 -0.882325", "vn -0.418479 -0.120537 -0.882325", "vn -0.331561 -0.354605 -0.874255", "vn -0.250046 -0.504788 -0.708963", "vn -0.193358 -0.685234 -0.559490", "vn -0.164793 -0.885456 -0.434524", "vn -0.084862 -0.970942 -0.223764", "vn -0.179130 -0.970942 -0.158695", "vn -0.347850 -0.885456 -0.308168", "vn -0.454566 -0.685234 -0.379191", "vn -0.574224 -0.504788 -0.485199", "vn -0.699870 -0.354605 -0.620031", "vn -0.809513 -0.120537 -0.612414", "vn -0.809513 0.120537 -0.612414", "vn -0.699870 0.354605 -0.620031", "vn -0.616012 0.568065 -0.545739", "vn -0.496354 0.748511 -0.439732", "vn -0.331764 1.031706 -0.284864", "vn -0.163044 1.203156 -0.135391", "vn -0.232362 1.180973 -0.057272", "vn -0.451219 1.009522 -0.111216", "vn -0.643854 0.748511 -0.158696", "vn -0.917637 0.628486 -0.290053", "vn -1.026414 0.415026 -0.223764", "vn -0.878709 0.120537 -0.237571", "vn -0.878709 -0.120537 -0.237571", "vn -0.907846 -0.354605 -0.223764", "vn -0.799070 -0.568065 -0.196953", "vn -0.643853 -0.748511 -0.158696", "vn -0.422990 -0.813186 -0.111215", "vn -0.204133 -0.898672 -0.057272", "vn -0.232361 -0.970942 0.057272", "vn -0.422990 -0.813186 0.111216", "vn -0.697084 -0.750309 0.238998", "vn -0.852300 -0.569863 0.277255", "vn -0.812495 -0.319098 0.143199", "vn -0.878709 -0.120537 0.237571", "vn -0.878709 0.120537 0.237571", "vn -0.907846 0.354605 0.223764", "vn -0.917637 0.628486 0.103853", "vn -0.643854 0.748511 0.158696", "vn -0.451219 0.885456 0.111215", "vn -0.232362 1.180973 0.057272", "vn -0.227905 1.120137 0.229358", "vn -0.347850 0.885456 0.308168", "vn -0.496355 0.748511 0.439732", "vn -0.616012 0.568065 0.545739", "vn -0.699870 0.354605 0.620030", "vn -0.743053 0.120537 0.658288", "vn -0.647702 -0.085029 0.577722", "vn -0.607843 -0.259373 0.679487", "vn -0.691716 -0.522164 0.579247", "vn -0.549585 -0.750309 0.520034", "vn -0.347850 -0.885456 0.308168", "vn -0.179130 -0.970942 0.158696", "vn -0.084862 -0.970942 0.223764", "vn -0.164793 -0.885456 0.434524", "vn -0.403914 -0.778650 0.682687", "vn -0.460601 -0.598204 0.832160", "vn -0.331561 -0.354605 0.874255", "vn -0.256668 -0.085029 0.847633", "vn -0.352019 0.120537 0.928199", "vn -0.313392 0.277789 0.724615", "vn -0.273665 0.491249 0.619863", "vn -0.235147 0.748511 0.620030", "vn -0.172823 1.009403 0.500657", "vn -0.133637 1.120137 0.294427", "vn 0.028846 1.180973 0.237571", "vn 0.047986 1.009403 0.527468", "vn 0.079931 0.748511 0.658288", "vn 0.117369 0.491249 0.667343", "vn 0.130873 0.277789 0.778559", "vn 0.119658 0.120537 0.985471", "vn 0.119658 -0.120537 0.985471", "vn 0.111766 -0.350520 0.920473", "vn 0.098262 -0.563980 0.809258", "vn 0.042417 -0.744955 0.639197", "vn 0.056016 -0.885456 0.461335", "vn 0.024360 -0.954771 0.249843", "vn 0.131460 -0.954771 0.209225", "vn 0.246732 -0.812519 0.361050", "vn 0.376697 -0.748511 0.545739", "vn 0.467508 -0.568065 0.677303", "vn 0.648221 -0.354605 0.769503", "vn 0.680994 -0.120537 0.816983", "vn 0.680994 0.120537 0.816983", "vn 0.531150 0.354605 0.769503", "vn 0.467508 0.568065 0.677302", "vn 0.376697 0.748511 0.545739", "vn 0.297744 0.941935 0.437767", "vn 0.135947 1.180973 0.196953", "vn 0.211903 1.180973 0.111215", "vn 0.363597 0.938414 0.383486", "vn 0.587166 0.748511 0.308169", "vn 0.612858 0.507257 0.353903", "vn 0.712057 0.293798 0.405967", "vn 0.880212 0.059729 0.432778", "vn 0.879000 -0.120537 0.461335", "vn 0.944987 -0.354605 0.434524", "vn 0.728716 -0.568065 0.382460", "vn 0.587166 -0.748511 0.308169", "vn 0.394231 -0.812519 0.194558", "vn 0.211903 -0.970942 0.111215", "vn 0.464723 -0.885456 0.000000", "vn 0.663123 -0.748511 0.000000", "vn 1.052087 -0.354605 0.000000", "vn 1.109780 -0.120537 0.000000", "vn 0.819158 0.293798 -0.028556", "vn 0.707125 0.507257 -0.028557", "", "", "vt 0.961538 0.500000", "vt 1.000000 0.500000", "vt 0.965801 0.535474", "vt 0.923077 0.500000", "vt 0.930763 0.569291", "vt 0.884615 0.500000", "vt 0.894133 0.599716", "vt 0.846154 0.500000", "vt 0.855383 0.624923", "vt 0.807692 0.500000", "vt 0.814405 0.643083", "vt 0.769231 0.500000", "vt 0.771690 0.652629", "vt 0.730769 0.500000", "vt 0.728310 0.652629", "vt 0.692308 0.500000", "vt 0.685595 0.643083", "vt 0.653846 0.500000", "vt 0.644617 0.624923", "vt 0.615385 0.500000", "vt 0.605867 0.599716", "vt 0.576923 0.500000", "vt 0.569237 0.569291", "vt 0.538462 0.500000", "vt 0.534199 0.535474", "vt 0.500000 0.500000", "vt 0.522140 0.563105", "vt 0.546116 0.624923", "vt 0.574207 0.683751", "vt 0.609594 0.736851", "vt 0.656312 0.779496", "vt 0.716485 0.804355", "vt 0.783514 0.804355", "vt 0.843688 0.779496", "vt 0.890406 0.736851", "vt 0.925793 0.683751", "vt 0.953884 0.624923", "vt 0.977860 0.563105", "vt 0.995273 0.576351", "vt 0.989945 0.652629", "vt 0.983069 0.728719", "vt 0.972485 0.804355", "vt 0.951023 0.878643", "vt 0.875582 0.945673", "vt 0.624418 0.945673", "vt 0.548977 0.878643", "vt 0.527515 0.804355", "vt 0.516931 0.728719", "vt 0.510055 0.652629", "vt 0.504727 0.576351", "vt 0.486125 0.571835", "vt 0.470715 0.643083", "vt 0.451555 0.712880", "vt 0.424469 0.779496", "vt 0.380343 0.838650", "vt 0.475067 0.862749", "vt 0.457525 0.920242", "vt 0.359726 0.891359", "vt 0.791311 0.948852", "vt 0.875630 0.808707", "vt 0.789906 0.805528", "vt 0.879497 0.878643", "vt 0.988527 0.873618", "vt 0.985302 0.945400", "vt 1.075531 0.779496", "vt 1.119657 0.838650", "vt 1.048445 0.712880", "vt 1.029285 0.643083", "vt 1.013875 0.571834", "vt 0.013875 0.571834", "vt 0.000000 0.500000", "vt 0.029036 0.550729", "vt 0.029285 0.643083", "vt 0.059576 0.599716", "vt 0.048445 0.712880", "vt 0.093192 0.644926", "vt 0.075531 0.779496", "vt 0.131441 0.683751", "vt 0.119657 0.838650", "vt 0.175361 0.712880", "vt 0.197495 0.878643", "vt 0.224405 0.728719", "vt 0.302505 0.878643", "vt 0.275595 0.728719", "vt 0.324639 0.712880", "vt 0.368559 0.683751", "vt 0.406808 0.644926", "vt 0.440424 0.599716", "vt 0.470964 0.550729", "vt 0.462615 0.518240", "vt 0.424992 0.535474", "vt 0.386940 0.550729", "vt 0.348359 0.563105", "vt 0.309266 0.571835", "vt 0.269800 0.576351", "vt 0.230200 0.576351", "vt 0.190734 0.571835", "vt 0.151641 0.563105", "vt 0.113060 0.550729", "vt 0.075008 0.535474", "vt 0.037385 0.518240", "vt 0.037385 0.481760", "vt 0.075008 0.464526", "vt 0.113060 0.449271", "vt 0.151641 0.436895", "vt 0.190734 0.428166", "vt 0.230200 0.423649", "vt 0.269800 0.423649", "vt 0.309266 0.428166", "vt 0.348359 0.436895", "vt 0.386940 0.449271", "vt 0.424992 0.464526", "vt 0.462615 0.481760", "vt 0.470964 0.449271", "vt 0.440424 0.400284", "vt 0.406808 0.355074", "vt 0.368559 0.316249", "vt 0.324639 0.287120", "vt 0.275595 0.271281", "vt 0.224405 0.271281", "vt 0.175361 0.287120", "vt 0.131441 0.316249", "vt 0.093192 0.355074", "vt 0.059576 0.400284", "vt 0.029036 0.449271", "vt 0.013875 0.428166", "vt 0.029285 0.356917", "vt 0.048445 0.287120", "vt 0.075531 0.220504", "vt 0.119657 0.161350", "vt 0.197495 0.121357", "vt 0.302505 0.121357", "vt 0.380343 0.161350", "vt 0.424469 0.220504", "vt 0.451555 0.287120", "vt 0.470715 0.356917", "vt 0.486125 0.428165", "vt 0.504727 0.423649", "vt 0.510055 0.347371", "vt 0.516931 0.271281", "vt 0.527515 0.195645", "vt 0.548977 0.121357", "vt 0.359726 0.114999", "vt 0.426530 0.095652", "vt 0.432152 0.146788", "vt 0.659729 0.121357", "vt 0.699677 0.106098", "vt 0.686755 0.028895", "vt 0.624418 0.054326", "vt 0.989594 0.060322", "vt 0.991865 0.118117", "vt 0.951023 0.121357", "vt 0.949969 0.051783", "vt 1.119657 0.161350", "vt 1.075531 0.220504", "vt 0.972485 0.195645", "vt 1.048445 0.287120", "vt 0.983069 0.271281", "vt 1.029285 0.356917", "vt 0.989945 0.347371", "vt 1.013875 0.428166", "vt 0.995273 0.423649", "vt 0.977860 0.436895", "vt 0.953884 0.375077", "vt 0.925793 0.316249", "vt 0.890406 0.263149", "vt 0.843688 0.220504", "vt 0.875582 0.054326", "vt 0.783515 0.195645", "vt 0.717401 0.105189", "vt 0.782599 0.105189", "vt 0.716486 0.195645", "vt 0.656312 0.220504", "vt 0.609594 0.263149", "vt 0.574207 0.316249", "vt 0.546116 0.375077", "vt 0.522140 0.436895", "vt 0.534199 0.464526", "vt 0.569237 0.430709", "vt 0.605867 0.400284", "vt 0.644617 0.375077", "vt 0.685595 0.356917", "vt 0.728310 0.347371", "vt 0.771690 0.347371", "vt 0.814405 0.356917", "vt 0.855383 0.375077", "vt 0.894133 0.400284", "vt 0.930763 0.430709", "vt 0.965801 0.464526", //"usemtl asteroid_rock", "usemtl reflTest", "s off", "f 7/1/7 8/2/8 9/3/9", "f 153/4/153 7/1/7 9/3/9 10/5/10", "f 154/6/154 153/4/153 10/5/10 11/7/11", "f 6/8/6 154/6/154 11/7/11 12/9/12", "f 155/10/155 6/8/6 12/9/12 13/11/13", "f 156/12/156 155/10/155 13/11/13 14/13/14", "f 5/14/5 156/12/156 14/13/14 15/15/15", "f 157/16/157 5/14/5 15/15/15 16/17/16", "f 158/18/158 157/16/157 16/17/16 17/19/17", "f 4/20/4 158/18/158 17/19/17 18/21/18", "f 3/22/3 4/20/4 18/21/18 19/23/19", "f 2/24/2 3/22/3 19/23/19 20/25/20", "f 1/26/1 2/24/2 20/25/20", "f 1/26/1 20/25/20 21/27/21", "f 20/25/20 19/23/19 22/28/22 21/27/21", "f 19/23/19 18/21/18 23/29/23 22/28/22", "f 18/21/18 17/19/17 24/30/24 23/29/23", "f 17/19/17 16/17/16 25/31/25 24/30/24", "f 16/17/16 15/15/15 26/32/26 25/31/25", "f 15/15/15 14/13/14 27/33/27 26/32/26", "f 14/13/14 13/11/13 28/34/28 27/33/27", "f 13/11/13 12/9/12 29/35/29 28/34/28", "f 12/9/12 11/7/11 30/36/30 29/35/29", "f 11/7/11 10/5/10 31/37/31 30/36/30", "f 10/5/10 9/3/9 32/38/32 31/37/31", "f 9/3/9 8/2/8 32/38/32", "f 32/38/32 8/2/8 33/39/33", "f 31/37/31 32/38/32 33/39/33 34/40/34", "f 30/36/30 31/37/31 34/40/34 35/41/35", "f 29/35/29 30/36/30 35/41/35 36/42/36", "f 28/34/28 29/35/29 36/42/36 37/43/37", "f 27/33/27 28/34/28 37/43/37 38/44/38", "f 26/32/26 27/33/27 38/44/38 39/45/39", "f 25/31/25 26/32/26 39/45/39 40/46/40", "f 24/30/24 25/31/25 40/46/40 41/47/41", "f 23/29/23 24/30/24 41/47/41 42/48/42", "f 22/28/22 23/29/23 42/48/42 43/49/43", "f 21/27/21 22/28/22 43/49/43 44/50/44", "f 1/26/1 21/27/21 44/50/44", "f 1/26/1 44/50/44 45/51/45", "f 44/50/44 43/49/43 46/52/46 45/51/45", "f 43/49/43 42/48/42 47/53/47 46/52/46", "f 42/48/42 41/47/41 48/54/48 47/53/47", "f 41/47/41 40/46/40 49/55/49 48/54/48", "f 40/56/40 39/57/39 50/58/50 49/55/49", "f 39/59/39 38/44/38 51/60/51 50/61/50", "f 38/44/38 37/62/37 52/63/52 51/64/51", "f 37/43/37 36/42/36 53/65/53 52/66/52", "f 36/42/36 35/41/35 54/67/54 53/65/53", "f 35/41/35 34/40/34 55/68/55 54/67/54", "f 34/40/34 33/39/33 56/69/56 55/68/55", "f 33/39/33 8/2/8 56/69/56", "f 56/70/56 8/71/8 57/72/57", "f 55/73/55 56/70/56 57/72/57 58/74/58", "f 54/75/54 55/73/55 58/74/58 59/76/59", "f 53/77/53 54/75/54 59/76/59 60/78/60", "f 52/79/52 53/77/53 60/78/60 61/80/61", "f 51/81/51 52/79/52 61/80/61 62/82/62", "f 50/83/50 51/81/51 62/82/62 63/84/63", "f 49/55/49 50/83/50 63/84/63 64/85/64", "f 48/54/48 49/55/49 64/85/64 65/86/65", "f 47/53/47 48/54/48 65/86/65 66/87/66", "f 46/52/46 47/53/47 66/87/66 67/88/67", "f 45/51/45 46/52/46 67/88/67 68/89/68", "f 1/26/1 45/51/45 68/89/68", "f 1/26/1 68/89/68 69/90/69", "f 68/89/68 67/88/67 70/91/70 69/90/69", "f 67/88/67 66/87/66 71/92/71 70/91/70", "f 66/87/66 65/86/65 72/93/72 71/92/71", "f 65/86/65 64/85/64 73/94/73 72/93/72", "f 64/85/64 63/84/63 74/95/74 73/94/73", "f 63/84/63 62/82/62 75/96/75 74/95/74", "f 62/82/62 61/80/61 76/97/76 75/96/75", "f 61/80/61 60/78/60 77/98/77 76/97/76", "f 60/78/60 59/76/59 78/99/78 77/98/77", "f 59/76/59 58/74/58 79/100/79 78/99/78", "f 58/74/58 57/72/57 80/101/80 79/100/79", "f 57/72/57 8/71/8 80/101/80", "f 80/101/80 8/71/8 81/102/81", "f 79/100/79 80/101/80 81/102/81 82/103/82", "f 78/99/78 79/100/79 82/103/82 83/104/83", "f 77/98/77 78/99/78 83/104/83 84/105/84", "f 76/97/76 77/98/77 84/105/84 85/106/85", "f 75/96/75 76/97/76 85/106/85 86/107/86", "f 74/95/74 75/96/75 86/107/86 87/108/87", "f 73/94/73 74/95/74 87/108/87 88/109/88", "f 72/93/72 73/94/73 88/109/88 89/110/89", "f 71/92/71 72/93/72 89/110/89 90/111/90", "f 70/91/70 71/92/71 90/111/90 91/112/91", "f 69/90/69 70/91/70 91/112/91 92/113/92", "f 1/26/1 69/90/69 92/113/92", "f 1/26/1 92/113/92 93/114/93", "f 92/113/92 91/112/91 94/115/94 93/114/93", "f 91/112/91 90/111/90 95/116/95 94/115/94", "f 90/111/90 89/110/89 96/117/96 95/116/95", "f 89/110/89 88/109/88 97/118/97 96/117/96", "f 88/109/88 87/108/87 98/119/98 97/118/97", "f 87/108/87 86/107/86 99/120/99 98/119/98", "f 86/107/86 85/106/85 100/121/100 99/120/99", "f 85/106/85 84/105/84 101/122/101 100/121/100", "f 84/105/84 83/104/83 102/123/102 101/122/101", "f 83/104/83 82/103/82 103/124/103 102/123/102", "f 82/103/82 81/102/81 104/125/104 103/124/103", "f 81/102/81 8/71/8 104/125/104", "f 104/125/104 8/71/8 105/126/105", "f 103/124/103 104/125/104 105/126/105 106/127/106", "f 102/123/102 103/124/103 106/127/106 107/128/107", "f 101/122/101 102/123/102 107/128/107 108/129/108", "f 100/121/100 101/122/101 108/129/108 109/130/109", "f 99/120/99 100/121/100 109/130/109 110/131/110", "f 98/119/98 99/120/99 110/131/110 111/132/111", "f 97/118/97 98/119/98 111/132/111 112/133/112", "f 96/117/96 97/118/97 112/133/112 113/134/113", "f 95/116/95 96/117/96 113/134/113 114/135/114", "f 94/115/94 95/116/95 114/135/114 115/136/115", "f 93/114/93 94/115/94 115/136/115 116/137/116", "f 1/26/1 93/114/93 116/137/116", "f 1/26/1 116/137/116 117/138/117", "f 116/137/116 115/136/115 118/139/118 117/138/117", "f 115/136/115 114/135/114 119/140/119 118/139/118", "f 114/135/114 113/134/113 120/141/120 119/140/119", "f 113/134/113 112/133/112 121/142/121 120/141/120", "f 112/133/112 111/143/111 122/144/122 121/145/121", "f 111/146/111 110/147/110 123/148/123 122/149/122", "f 110/150/110 109/151/109 124/152/124 123/153/123", "f 109/154/109 108/155/108 125/156/125 124/152/124", "f 108/155/108 107/157/107 126/158/126 125/156/125", "f 107/157/107 106/159/106 127/160/127 126/158/126", "f 106/159/106 105/161/105 128/162/128 127/160/127", "f 105/161/105 8/2/8 128/162/128", "f 128/162/128 8/2/8 129/163/129", "f 127/160/127 128/162/128 129/163/129 130/164/130", "f 126/158/126 127/160/127 130/164/130 131/165/131", "f 125/156/125 126/158/126 131/165/131 132/166/132", "f 124/152/124 125/156/125 132/166/132 133/167/133", "f 123/168/123 124/152/124 133/167/133 134/169/134", "f 122/170/122 123/171/123 134/169/134 135/172/135", "f 121/142/121 122/149/122 135/172/135 136/173/136", "f 120/141/120 121/142/121 136/173/136 137/174/137", "f 119/140/119 120/141/120 137/174/137 138/175/138", "f 118/139/118 119/140/119 138/175/138 139/176/139", "f 117/138/117 118/139/118 139/176/139 140/177/140", "f 1/26/1 117/138/117 140/177/140", "f 1/26/1 140/177/140 141/178/141", "f 140/177/140 139/176/139 142/179/142 141/178/141", "f 139/176/139 138/175/138 143/180/143 142/179/142", "f 138/175/138 137/174/137 144/181/144 143/180/143", "f 137/174/137 136/173/136 145/182/145 144/181/144", "f 136/173/136 135/172/135 146/183/146 145/182/145", "f 135/172/135 134/169/134 147/184/147 146/183/146", "f 134/169/134 133/167/133 148/185/148 147/184/147", "f 133/167/133 132/166/132 149/186/149 148/185/148", "f 132/166/132 131/165/131 150/187/150 149/186/149", "f 131/165/131 130/164/130 151/188/151 150/187/150", "f 130/164/130 129/163/129 152/189/152 151/188/151", "f 129/163/129 8/2/8 152/189/152", "f 152/189/152 8/2/8 7/1/7", "f 151/188/151 152/189/152 7/1/7 153/4/153", "f 150/187/150 151/188/151 153/4/153 154/6/154", "f 149/186/149 150/187/150 154/6/154 6/8/6", "f 148/185/148 149/186/149 6/8/6 155/10/155", "f 147/184/147 148/185/148 155/10/155 156/12/156", "f 146/183/146 147/184/147 156/12/156 5/14/5", "f 145/182/145 146/183/146 5/14/5 157/16/157", "f 144/181/144 145/182/145 157/16/157 158/18/158", "f 143/180/143 144/181/144 158/18/158 4/20/4", "f 142/179/142 143/180/143 4/20/4 3/22/3", "f 141/178/141 142/179/142 3/22/3 2/24/2", "f 1/26/1 141/178/141 2/24/2" ].join('\n'), 'cube-textures.obj' : [ 'mtllib cube-textures.mtl', '# v1 is origin: back lower left (bll)', '# v2=fll, v3=bul, v4=ful, v5=blr, v6=flr, v7=', 'v 0.0 0.0 0.0', 'v 0.0 0.0 1.0', 'v 0.0 1.0 0.0', 'v 0.0 1.0 1.0', 'v 1.0 0.0 0.0', 'v 1.0 0.0 1.0', 'v 1.0 1.0 0.0', 'v 1.0 1.0 1.0', '', 'vn 0.0 0.0 1.0', 'vn 0.0 0.0 -1.0', 'vn 0.0 1.0 0.0', 'vn 0.0 -1.0 0.0', 'vn 1.0 0.0 0.0', 'vn -1.0 0.0 0.0', '', 'vt 0.0 0.0 # vt=1 is upper left of texture', 'vt 0.0 1.0 # vt=2 is lower left of texture', 'vt 1.0 0.0 # vt=3 is upper right of texture', 'vt 1.0 1.0 # vt=4 is lower right of texture', '', '# remember, syntax is v/vt/vn', 'usemtl texture', 'f 1/4/2 7/1/2 5/2/2', 'f 1/4/2 3/3/2 7/1/2', 'f 1/2/6 4/3/6 3/1/6', 'f 1/2/6 2/4/6 4/3/6', 'f 3/1/3 8/4/3 7/3/3', 'f 3/1/3 4/2/3 8/4/3', 'f 5/4/5 7/3/5 8/1/5', 'f 5/4/5 8/1/5 6/2/5', 'f 1/2/4 5/4/4 6/3/4', 'f 1/2/4 6/3/4 2/1/4', 'f 2/2/1 6/4/1 8/3/1', 'f 2/2/1 8/3/1 4/1/1', ].join('\n'), 'cube-textures.mtl':[ 'newmtl texture', 'illum 2', 'Kd 1.0 1.0 1.0', 'Ka 0.00 0.00 0.00', 'Ks 1.00 1.00 1.00', 'Tf 1.00 1.00 1.00', 'Ns 10', 'map_Kd cube/cube_nx.png', ].join('\n') };
'use strict' const React = require('react') // import _ from 'lodash' // // import hashHistory from 'react-router' // import initStore from '../../src/front-end/js/store' // import initRouter from '../../src/front-end/js/router' const _ = require('lodash') const { hashHistory } = require('react-router') const initStore = require('../../src/front-end/js/store') const initRouter = require('../../src/front-end/js/router') const pkg = require(process.cwd() + '/package.json') function reduxHandler (req, res, next) { let initialState = { application: { token: null, user: null, nextTransitionPath: req.query.targetPath || '' }, cv: {} } if (_.result(req, 'session.user')) { initialState.application = _.merge(initialState.application, { token: req.cookies.token, user: req.session.user }) } global.INITIAL_STATE = JSON.stringify(initialState) let store = initStore() global.RESPONSE = res initRouter(hashHistory, store) .then(({content}) => { const html = React.renderToString(content) var opts = { title: pkg.name, author: pkg.author, description: pkg.description, version: pkg.version, keywords: pkg.keywords.join(', '), html: html, initialState: JSON.stringify(initialState) } if (!res.headersSent) { res.render('index', opts) } }) .catch((err) => { console.error(err) next(err) }) } module.exports = (app) => app.get('/app*', reduxHandler)
JalaliDate = { g_days_in_month : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], j_days_in_month : [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29] }; JalaliDate.jalaliToGregorian = function (j_y, j_m, j_d) { j_y = parseInt(j_y); j_m = parseInt(j_m); j_d = parseInt(j_d); var jy = j_y - 979; var jm = j_m - 1; var jd = j_d - 1; var j_day_no = 365 * jy + parseInt(jy / 33) * 8 + parseInt((jy % 33 + 3) / 4); for (var i = 0; i < jm; ++i) j_day_no += JalaliDate.j_days_in_month[i]; j_day_no += jd; var g_day_no = j_day_no + 79; var gy = 1600 + 400 * parseInt(g_day_no / 146097); g_day_no = g_day_no % 146097; var leap = true; if (g_day_no >= 36525) { g_day_no--; gy += 100 * parseInt(g_day_no / 36524); g_day_no = g_day_no % 36524; if (g_day_no >= 365) g_day_no++; else leap = false; } gy += 4 * parseInt(g_day_no / 1461); g_day_no %= 1461; if (g_day_no >= 366) { leap = false; g_day_no--; gy += parseInt(g_day_no / 365); g_day_no = g_day_no % 365; } for (var i = 0; g_day_no >= JalaliDate.g_days_in_month[i] + (i == 1 && leap); i++) g_day_no -= JalaliDate.g_days_in_month[i] + (i == 1 && leap); var gm = i + 1; var gd = g_day_no + 1; return [gy, gm, gd]; } JalaliDate.checkDate = function (j_y, j_m, j_d) { return !(j_y < 0 || j_y > 32767 || j_m < 1 || j_m > 12 || j_d < 1 || j_d > (JalaliDate.j_days_in_month[j_m - 1] + (j_m == 12 && !((j_y - 979) % 33 % 4)))); } module.exports = JalaliDate; JalaliDate.gregorianToJalali = function (g_y, g_m, g_d) { g_y = parseInt(g_y); g_m = parseInt(g_m); g_d = parseInt(g_d); var gy = g_y - 1600; var gm = g_m - 1; var gd = g_d - 1; var g_day_no = 365 * gy + parseInt((gy + 3) / 4) - parseInt((gy + 99) / 100) + parseInt((gy + 399) / 400); for (var i = 0; i < gm; ++i) g_day_no += JalaliDate.g_days_in_month[i]; if (gm > 1 && ((gy % 4 == 0 && gy % 100 != 0) || (gy % 400 == 0))) /* leap and after Feb */ ++g_day_no; g_day_no += gd; var j_day_no = g_day_no - 79; var j_np = parseInt(j_day_no / 12053); j_day_no %= 12053; var jy = 979 + 33 * j_np + 4 * parseInt(j_day_no / 1461); j_day_no %= 1461; if (j_day_no >= 366) { jy += parseInt((j_day_no - 1) / 365); j_day_no = (j_day_no - 1) % 365; } for (var i = 0; i < 11 && j_day_no >= JalaliDate.j_days_in_month[i]; ++i) { j_day_no -= JalaliDate.j_days_in_month[i]; } var jm = i + 1; var jd = j_day_no + 1; return [jy, jm, jd]; }
'use strict'; const fs = require('fs'); const sharedData = require('@render/shared_data.js'); const Config = require('@render/config.js'); const { getKeyFromConfig, get } = require('@aux/aux_global.js'); const Logger = require('@render/logger.js'); const aux_webManager = require('@render/aux_web_manager.js'); const aux_viewer = require('@render/aux_viewer.js'); const { promisify } = require('util'); const path = require('path'); module.exports = context => { return { config: { maxTxtFileSize: 100 * 1024, minTxtFileSize: 10, disableExtensions: [], userExtensions: [], viewer: true, }, viewer: false, init() { this.viewer = this.config.viewer; if (this.config.viewer === 'auto') { this.viewer = false; const onKey = event => { let lastRule = context.getLastRuleSelected(); let isTab = event && event.code === 'Tab'; let isFile = context.get(lastRule, 'params.drive_path'); if (isTab && isFile) { if (event && event.preventDefault) event.preventDefault(); this.viewer = !this.viewer; if (context.forceRefreshRules) context.forceRefreshRules(); } }; if (document && document.addEventListener) document.addEventListener('keydown', onKey); } }, defineTypeViewers() { if (!this.config.viewer) return; const disableExtensions = this.config.disableExtensions || []; const userExtensions = this.config.userExtensions || []; const getRuleExtension = rule => { const drive_path = context.get(rule, 'params.drive_path'); if (!drive_path) return null; let drive_path_ext = path.extname(drive_path); drive_path_ext = drive_path_ext.length > 0 ? drive_path_ext.substr(1) : drive_path_ext; return drive_path_ext; }; const isValidTxt = rule => { const drive_path = context.get(rule, 'params.drive_path'); if (!drive_path === null) return null; const drive_path_ext = getRuleExtension(rule); const textextensions = context.require('textextensions'); const isText = drive_path && !disableExtensions.includes(drive_path_ext) && (drive_path_ext === '' || textextensions.includes(drive_path_ext) || userExtensions.includes(drive_path_ext)); if (!isText) return false; let stats = null; try { stats = fs.statSync(drive_path); } catch (e) { Logger.warn(e); } if (!stats) return false; let fileSizeInBytes = stats['size']; let big = fileSizeInBytes > this.config.maxTxtFileSize; let small = fileSizeInBytes < this.config.minTxtFileSize; if (big || small) return false; return true; }; const viewerTxtComp = context.createViewerHtml({}, async (resolve, reject, rule) => { const fileName = context.get(rule, 'params.drive_path'); const data = await promisify(fs.readFile)(fileName, 'utf8'); const drive_path_ext = getRuleExtension(rule); const isCode = drive_path_ext !== 'txt' && drive_path_ext !== '' && drive_path_ext !== 'doc'; resolve({ component: context.createComponentFromHtml(aux_viewer.string2HtmlCode(data, isCode)) }); }); return [ { type: 'file', title: 'File String Viewer', enabled: rule => { return this.viewer && isValidTxt(rule); }, viewerComp: viewerTxtComp, }, ]; }, }; };
/* globals describe, it */ var assert = require('assert'); var t = require('../index'); var util = require('./util'); describe('t.intersection(types, [name])', function () { var Min = t.subtype(t.String, function (s) { return s.length > 2; }, 'Min'); var Max = t.subtype(t.String, function (s) { return s.length < 5; }, 'Max'); var MinMax = t.intersection([Min, Max], 'MinMax'); describe('combinator', function () { it('should throw if used with wrong arguments', function () { util.throwsWithMessage(function () { t.intersection(); }, '[tcomb] Invalid argument types undefined supplied to intersection(types, [name]) combinator (expected an array of at least 2 types)'); util.throwsWithMessage(function () { t.intersection([]); }, '[tcomb] Invalid argument types [] supplied to intersection(types, [name]) combinator (expected an array of at least 2 types)'); util.throwsWithMessage(function () { t.intersection([1]); }, '[tcomb] Invalid argument types [\n 1\n] supplied to intersection(types, [name]) combinator (expected an array of at least 2 types)'); util.throwsWithMessage(function () { t.intersection([Min, Max], 1); }, '[tcomb] Invalid argument name 1 supplied to intersection(types, [name]) combinator (expected a string)'); }); }); describe('ctor', function () { it('should throw with a contextual error message if used with wrong arguments', function () { util.throwsWithMessage(function () { MinMax('a'); }, '[tcomb] Invalid value "a" supplied to MinMax'); util.throwsWithMessage(function () { MinMax('a', ['root']); }, '[tcomb] Invalid value "a" supplied to root'); }); }); describe('is(x)', function () { it('should return true when x is an instance of the intersection', function () { assert.strictEqual(MinMax.is('123'), true); assert.strictEqual(MinMax.is('12'), false); assert.strictEqual(MinMax.is('12345'), false); }); }); });
--- layout: null --- $(document).ready(function () { $('a.blog-button').click(function (e) { if ($('.panel-cover').hasClass('panel-cover--collapsed')){ return; } currentWidth = $('.panel-cover').width(); if (currentWidth < 960) { $('.panel-cover').addClass('panel-cover--collapsed'); $('.content-wrapper').addClass('animated slideInRight'); } else { $('.panel-cover').css('max-width', currentWidth); $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {}); } }); if (window.location.hash && window.location.hash == '#blog') { $('.panel-cover').addClass('panel-cover--collapsed'); } if(window.location.pathname !== "/" || window.location.hash !== ""){ $('.panel-cover').addClass('panel-cover--collapsed'); } // if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') { // $('.panel-cover').addClass('panel-cover--collapsed'); // } $('.btn-mobile-menu').click(function () { $('.navigation-wrapper').toggleClass('visible animated bounceInDown'); $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn'); }); $('.navigation-wrapper .blog-button').click(function () { $('.navigation-wrapper').toggleClass('visible'); $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn'); }); });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from '../actions'; class CommentBox extends Component { constructor(props) { super(props); this.state = { comment: '' } } handleChange(e) { this.setState({ comment: e.target.value }) } handleSubmit(e) { e.preventDefault(); this.props.saveComment(this.state.comment); this.setState({ comment: '' }) } render() { return ( <form onSubmit={this.handleSubmit.bind(this)} className='comment-box'> <h4>Add a Comment</h4> <textarea value={this.state.comment} onChange={this.handleChange.bind(this)} /> <div> <button action='submit'>Submit Comment</button> </div> </form> ) } } export default connect(null, actions)(CommentBox);
#!/usr/bin/env node 'use strict'; var getStdin = require('get-stdin'); var meow = require('meow'); var detectNewline = require('./'); var cli = meow({ help: [ 'Usage', ' $ detect-newline <string>', ' $ cat unicorn.txt | detect-newline', '', 'Example', ' $ detect-newline "$(printf \'Unicorns\\nRainbows\')"', ' \\n' ] }); function init(data) { process.stdout.write(detectNewline(data) || ''); } if (process.stdin.isTTY) { if (!cli.input[0]) { console.error('Expected a string'); process.exit(1); } init(cli.input[0]); } else { getStdin(init); }
import React, { Component } from 'react' import { connect } from 'react-redux' import * as actions from '../../redux/modules/ReceiversReducer' import { studentsArraySelector, teachersArraySelector, groupsArraySelector, lessonsArraySelector, activeReceiversArraySelector } from '../../selectors/ReceiversSelector' import StudentReceiverListItem from './StudentReceiverListItem' import TeacherReceiverListItem from './TeacherReceiverListItem' import GroupReceiverListItem from './GroupReceiverListItem' import LessonReceiverListItem from './LessonReceiverListItem' import Pagination from './Pagination' class Receivers extends Component { constructor(props) { super(props) this.changeActiveTab = this.changeActiveTab.bind(this) this.renderPagination = this.renderPagination.bind(this) this.renderStudents = this.renderStudents.bind(this) this.renderTeachers = this.renderTeachers.bind(this) this.renderGroups = this.renderGroups.bind(this) this.renderLessons = this.renderLessons.bind(this) this.state = {showList: true} } changeActiveTab(newTab) { this.props.changeActiveTab(newTab) switch(newTab) { case 'students': this.props.getPaginatedStudents() break; case 'teachers': this.props.getPaginatedTeachers() break; case 'groups': this.props.getPaginatedGroups() break; case 'lessons': this.props.getPaginatedLessons() break; } } renderStudents() { const { students, studentsLoaded, addReceiver } = this.props let receiverLI = [] if(studentsLoaded) { students.map((el) => { receiverLI.push(<StudentReceiverListItem student={el} key={el.id} groups={el.studentGroups} changeReceiver={addReceiver}/>) }) } return ( <div className="row"> <div className="list-group"> {receiverLI} </div> </div> ) } renderTeachers() { const { teachers, teachersLoaded, addReceiver } = this.props let receiverLI = [] if(teachersLoaded) { teachers.map((el) => { receiverLI.push(<TeacherReceiverListItem teacher={el} key={el.id} lessons={el.lessons} changeReceiver={addReceiver}/>) }) } return ( <div className="row"> <div className="list-group"> {receiverLI} </div> </div> ) } renderGroups() { const { groups, groupsLoaded, addReceiver } = this.props let receiverLI = [] if(groupsLoaded) { groups.map((el) => { receiverLI.push(<GroupReceiverListItem group={el} key={el.id} lessons={el.lessons} totalStudents={el.totalStudents} changeReceiver={addReceiver}/>) }) } return ( <div className="row"> <div className="list-group"> {receiverLI} </div> </div> ) } renderLessons() { const { lessons, lessonsLoaded, addReceiver } = this.props let receiverLI = [] if(lessonsLoaded) { lessons.map((el) => { receiverLI.push(<LessonReceiverListItem lesson={el} key={el.id} groups={el.groups} totalStudents={el.totalStudents} changeReceiver={addReceiver}/>) }) } return ( <div className="row"> <div className="list-group"> {receiverLI} </div> </div> ) } renderPagination() { const { activeTab, getPaginatedStudents, getPaginatedTeachers, getPaginatedGroups, getPaginatedLessons, studentsCount, teachersCount, groupsCount, lessonsCount, activePage } = this.props switch(activeTab) { case 'students': return <Pagination getData={getPaginatedStudents} count={studentsCount} currentPage={activePage}/> break; case 'teachers': return <Pagination getData={getPaginatedTeachers} count={teachersCount} currentPage={activePage}/> break; case 'groups': return <Pagination getData={getPaginatedGroups} count={groupsCount} currentPage={activePage}/> break; case 'lessons': return <Pagination getData={getPaginatedLessons} count={lessonsCount} currentPage={activePage}/> break; default: return <Pagination count={0}/> break; } } componentDidMount() { this.props.getPaginatedStudents() this.props.changeActiveTab() } render() { const { activeTab } = this.props let listToRender = this.renderStudents switch(activeTab) { case 'students': listToRender = this.renderStudents break; case 'teachers': listToRender = this.renderTeachers break; case 'groups': listToRender = this.renderGroups break; case 'lessons': listToRender = this.renderLessons break; } return ( <div> <ul className="nav nav-tabs"> <li role="presentation" className={activeTab == 'students' ? 'active' : ''} onClick={(e) => { this.changeActiveTab('students') }}> <a style={{cursor: 'pointer'}}>Students</a> </li> <li role="presentation" className={activeTab == 'teachers' ? 'active' : ''} onClick={(e) => { this.changeActiveTab('teachers') }}> <a style={{cursor: 'pointer'}}>Teachers</a> </li> <li role="presentation" className={activeTab == 'groups' ? 'active' : ''} onClick={(e) => { this.changeActiveTab('groups') }}> <a style={{cursor: 'pointer'}}>Groups</a> </li> <li role="presentation" className={activeTab == 'lessons' ? 'active' : ''} onClick={(e) => { this.changeActiveTab('lessons') }}> <a style={{cursor: 'pointer'}}>Lessons</a> </li> <li className="pull-right"> <a style={{cursor: 'pointer'}} onClick={(e) => { let toggled = !this.state.showList this.setState({showList: toggled}) }}> {this.state.showList ? "Hide list" : "Show List"} </a> </li> </ul> <div className={this.state.showList ? "" : "hidden"}> {this.renderPagination()} {listToRender()} {this.renderPagination()} </div> </div> ) } } const mapStateToProps = (state) => { return { activeTab: state.receivers.activeTab, students: studentsArraySelector(state), teachers: teachersArraySelector(state), groups: groupsArraySelector(state), lessons: lessonsArraySelector(state), studentsCount: state.receivers.students.count, teachersCount: state.receivers.teachers.count, groupsCount: state.receivers.groups.count, lessonsCount: state.receivers.lessons.count, studentsLoaded: state.receivers.students.loaded, teachersLoaded: state.receivers.teachers.loaded, groupsLoaded: state.receivers.groups.loaded, lessonsLoaded: state.receivers.lessons.loaded, activePage: state.receivers.activePage } } export default connect(mapStateToProps, actions)(Receivers)
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * Lithuanian Translations (UTF-8) * Vladas Saulis (vladas at prodata dot lt), 03-29-2009 * Vladas Saulis (vladas at prodata dot lt), 10-18-2007 */ Ext.onReady(function() { if (Ext.Date) { Ext.Date.monthNames = ["Sausis", "Vasaris", "Kovas", "Balandis", "Gegužė", "Birželis", "Liepa", "Rugpjūtis", "Rugsėjis", "Spalis", "Lapkritis", "Gruodis"]; Ext.Date.getShortMonthName = function(month) { // Uncommons if (month == 7) return "Rgp"; if (month == 8) return "Rgs"; if (month == 11) return "Grd"; return Ext.Date.monthNames[month].substring(0, 3); }; Ext.Date.monthNumbers = { Sau: 0, Vas: 1, Kov: 2, Bal: 3, Geg: 4, Bir: 5, Lie: 6, Rgp: 7, Rgs: 8, Spa: 9, Lap: 10, Grd: 11 }; Ext.Date.getMonthNumber = function(name) { // Some uncommons if (name == "Rugpjūtis") return 7; if (name == "Rugsėjis") return 8; if (name == "Gruodis") return 11; return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; }; Ext.Date.dayNames = ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"]; Ext.Date.parseCodes.S.s = "(?:as|as|as|as)"; Ext.Date.getShortDayName = function(day) { return Ext.Date.dayNames[day].substring(0, 3); }; } if (Ext.util && Ext.util.Format) { Ext.apply(Ext.util.Format, { thousandSeparator: '.', decimalSeparator: ',', currencySign: 'Lt', // Lithuanian Litai dateFormat: 'Y-m-d' }); } }); Ext.define("Ext.locale.lt.view.View", { override: "Ext.view.View", emptyText: "" }); Ext.define("Ext.locale.lt.view.View", { override: "Ext.view.View", emptyText: "" }); Ext.define("Ext.locale.lt.grid.plugin.DragDrop", { override: "Ext.grid.plugin.DragDrop", dragText: "{0} pažymėtų eilučių" }); Ext.define("Ext.locale.lt.tab.Tab", { override: "Ext.tab.Tab", closeText: "Uždaryti šią užsklandą" }); Ext.define("Ext.locale.lt.form.field.Base", { override: "Ext.form.field.Base", invalidText: "Šio lauko reikšmė neteisinga" }); // changing the msg text below will affect the LoadMask Ext.define("Ext.locale.lt.view.AbstractView", { override: "Ext.view.AbstractView", loadingText: "Kraunasi..." }); Ext.define("Ext.locale.lt.picker.Date", { override: "Ext.picker.Date", todayText: "Šiandien", minText: "Ši data yra mažesnė už leistiną", maxText: "Ši data yra didesnė už leistiną", disabledDaysText: "", disabledDatesText: "", nextText: 'Kitas mėnuo (Control+Right)', prevText: 'Ankstesnis mėnuo (Control+Left)', monthYearText: 'Pasirinkti mėnesį (Control+Up/Down perėjimui tarp metų)', todayTip: "{0} (Tarpas)", format: "y-m-d", startDay: 1 }); Ext.define("Ext.locale.lt.picker.Month", { override: "Ext.picker.Month", okText: "&#160;Gerai&#160;", cancelText: "Atsisaktyi" }); Ext.define("Ext.locale.lt.toolbar.Paging", { override: "Ext.PagingToolbar", beforePageText: "Puslapis", afterPageText: "iš {0}", firstText: "Pirmas puslapis", prevText: "Ankstesnis pusl.", nextText: "Kitas puslapis", lastText: "Pakutinis pusl.", refreshText: "Atnaujinti", displayMsg: "Rodomi įrašai {0} - {1} iš {2}", emptyMsg: 'Nėra duomenų' }); Ext.define("Ext.locale.lt.form.field.Text", { override: "Ext.form.field.Text", minLengthText: "Minimalus šio lauko ilgis yra {0}", maxLengthText: "Maksimalus šio lauko ilgis yra {0}", blankText: "Šis laukas yra privalomas", regexText: "", emptyText: null }); Ext.define("Ext.locale.lt.form.field.Number", { override: "Ext.form.field.Number", minText: "Minimalus šio lauko ilgis yra {0}", maxText: "Maksimalus šio lauko ilgis yra {0}", nanText: "{0} yra neleistina reikšmė" }); Ext.define("Ext.locale.lt.form.field.Date", { override: "Ext.form.field.Date", disabledDaysText: "Neprieinama", disabledDatesText: "Neprieinama", minText: "Šiame lauke data turi būti didesnė už {0}", maxText: "Šiame lauke data turi būti mažesnėė už {0}", invalidText: "{0} yra neteisinga data - ji turi būti įvesta formatu {1}", format: "y-m-d", altFormats: "y-m-d|y/m/d|Y-m-d|m/d|m-d|md|ymd|Ymd|d|Y-m-d" }); Ext.define("Ext.locale.lt.form.field.ComboBox", { override: "Ext.form.field.ComboBox", valueNotFoundText: undefined }, function() { Ext.apply(Ext.form.field.ComboBox.prototype.defaultListConfig, { loadingText: "Kraunasi..." }); }); Ext.define("Ext.locale.lt.form.field.VTypes", { override: "Ext.form.field.VTypes", emailText: 'Šiame lauke turi būti el.pašto adresas formatu "user@example.com"', urlText: 'Šiame lauke turi būti nuoroda (URL) formatu "http:/' + '/www.example.com"', alphaText: 'Šiame lauke gali būti tik raidės ir ženklas "_"', alphanumText: 'Šiame lauke gali būti tik raidės, skaičiai ir ženklas "_"' }); Ext.define("Ext.locale.lt.form.field.HtmlEditor", { override: "Ext.form.field.HtmlEditor", createLinkText: 'Įveskite URL šiai nuorodai:' }, function() { Ext.apply(Ext.form.field.HtmlEditor.prototype, { buttonTips: { bold: { title: 'Bold (Ctrl+B)', text: 'Teksto paryškinimas.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, italic: { title: 'Italic (Ctrl+I)', text: 'Kursyvinis tekstas.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, underline: { title: 'Underline (Ctrl+U)', text: 'Teksto pabraukimas.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, increasefontsize: { title: 'Padidinti šriftą', text: 'Padidinti šrifto dydį.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, decreasefontsize: { title: 'Sumažinti šriftą', text: 'Sumažinti šrifto dydį.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, backcolor: { title: 'Nuspalvinti teksto foną', text: 'Pakeisti teksto fono spalvą.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, forecolor: { title: 'Teksto spalva', text: 'Pakeisti pažymėto teksto spalvą.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifyleft: { title: 'Išlyginti kairen', text: 'Išlyginti tekstą į kairę.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifycenter: { title: 'Centruoti tekstą', text: 'Centruoti tektą redaktoriaus lange.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, justifyright: { title: 'Išlyginti dešinėn', text: 'Išlyginti tekstą į dešinę.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, insertunorderedlist: { title: 'Paprastas sąrašas', text: 'Pradėti neorganizuotą sąrašą.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, insertorderedlist: { title: 'Numeruotas sąrašas', text: 'Pradėti numeruotą sąrašą.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, createlink: { title: 'Nuoroda', text: 'Padaryti pažymėta tekstą nuoroda.', cls: Ext.baseCSSPrefix + 'html-editor-tip' }, sourceedit: { title: 'Išeities tekstas', text: 'Persijungti į išeities teksto koregavimo režimą.', cls: Ext.baseCSSPrefix + 'html-editor-tip' } } }); }); Ext.define("Ext.locale.lt.form.Basic", { override: "Ext.form.Basic", waitTitle: "Palaukite..." }); Ext.define("Ext.locale.lt.grid.header.Container", { override: "Ext.grid.header.Container", sortAscText: "Rūšiuoti didėjančia tvarka", sortDescText: "Rūšiuoti mažėjančia tvarka", lockText: "Užfiksuoti stulpelį", unlockText: "Atlaisvinti stulpelį", columnsText: "Stulpeliai" }); Ext.define("Ext.locale.lt.grid.GroupingFeature", { override: "Ext.grid.GroupingFeature", emptyGroupText: '(Nėra)', groupByText: 'Grupuoti pagal šį lauką', showGroupsText: 'Rodyti grupėse' }); Ext.define("Ext.locale.lt.grid.PropertyColumnModel", { override: "Ext.grid.PropertyColumnModel", nameText: "Pavadinimas", valueText: "Reikšmė", dateFormat: "Y-m-d" }); Ext.define("Ext.locale.lt.form.field.Time", { override: "Ext.form.field.Time", minText: "Laikas turi buti lygus arba vėlesnis už {0}", maxText: "Laikas turi būti lygus arba ankstesnis už {0}", invalidText: "{0} yra neteisingas laikas", format: "H:i", altFormats: "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H" }); Ext.define("Ext.locale.lt.form.CheckboxGroup", { override: "Ext.form.CheckboxGroup", blankText: "Jūs turite padaryti bent vieną pasirinkimą šioje grupėje" }); Ext.define("Ext.locale.lt.form.RadioGroup", { override: "Ext.form.RadioGroup", blankText: "Jūs turite padaryti bent vieną pasirinkimą šioje grupėje" }); Ext.define("Ext.locale.lt.window.MessageBox", { override: "Ext.window.MessageBox", buttonText: { ok: "Gerai", cancel: "Atsisakyti", yes: "Taip", no: "Ne" } }); // This is needed until we can refactor all of the locales into individual files Ext.define("Ext.locale.lt.Component", { override: "Ext.Component" });
import React from 'react'; import { connect } from 'react-redux'; import Colors from './../../constants/PolygonColors.js'; import Operations from './../../constants/Operations.js'; import { LOCALE } from './../../constants/Config'; import './Range.css'; const scaleFactor = 2; let Range = ({min, max, operationType}) => { let style = { background: `linear-gradient(${Colors})` }; let values = []; if(min && max){ let step = ((max - min) / Colors.length) * scaleFactor; for(let i = 0; i < Colors.length / scaleFactor + 1; i ++){ values.push(min + step * i); } } return ( <div className="Range"> <h3>Leyenda</h3> <div className="Gradient" style={style}>&nbsp;</div> <div className="Values">{values.map(v => <div key={v}>{Operations[operationType].unit}{Math.floor(v).toLocaleString(LOCALE)}</div>)}</div> </div> ); }; Range = connect((state) => ({ min: state.map.range.min, max: state.map.range.max, operationType: state.filters.operationType }))(Range); export default Range;
// Stwórz dwie funkcje, jedną nazwij range - powinna tworzyć tablicę // zawierającą wszystkie liczby całkowite ze wskazanego przedziału, // a jako dodatkowy argument przyjmować wielkość "kroku" // np range(1, 10, 2) powinno stworzyć tablicę [1,3,5,7,9] // druga funkcja o nazwie sum powinna sumować elementy tablicy
"use strict"; var Promise = require('bluebird'); var twilio = require('twilio'); var xoauth2 = require('xoauth2'); var crypto = require('crypto'); var crypto_pbkdf2 = Promise.promisify(crypto.pbkdf2); var phone_regex = /\b[0-9]{10}\b/; module.exports = function(api){ var client; return { phone: { settings: { accountSid: '', authToken: '', number: '' }, configure: function(){ if (!api.phone.settings.accountSid || !api.phone.settings.authToken || !api.phone.settings.number) { console.log("Twilio phone client has not been configured."); return; } client = twilio(api.phone.settings.accountSid, api.phone.settings.authToken); }, state: { // this is what will be stored in the database specific to each resource independent: { // what can be set directly number: String, signin: Boolean // should this phone be used as a step in signing in. }, dependent: { // what is set indirectly according to the api verified: Boolean, verifySalt: String, verifyCodeHash: String }, index: { }, }, static: { view: { }, action:{ root: { handler: function(req) { if (!phone_regex.test(this.number)){ throw new api.phone.Error('invalidphone', 'The phone number must be 10 digits with no spaces or puncuation.', [], 400); } // this will actually return the default return value return Promise.resolve(); } } } }, view: { root: { secure: true }, 'verified': { parameter: ':code', handler: function(req, res) { var phone = this; res.render('verified', { _id: phone._id, number: phone.number, code: req.params.code }); } } }, action: { root: { secure: true, handler: function(req) { if (!phone_regex.test(this.number)){ throw new api.phone.Error('invalidphone', 'The phone address is not a valid format.', [], 400); } this.verified = false; } }, 'send-code-link': { secure: true, handler: function(req, res){ var phone = this; phone.verifySalt = crypto.randomBytes(16).toString('hex'); var code = crypto.randomBytes(16).toString('hex'); return crypto_pbkdf2(code, phone.verifySalt, 1000, 64, 'sha256') .then(function(codeHash) { phone.verifyCodeHash = codeHash.toString('hex'); return phone.save(); }) .then(function(phone){ return phone.sendSms({ text: 'http://localhost:3000/api/phone/' + phone._id + '/verified/' + code }); }); } }, verify: { secure: false, handler: function(req, res) { var phone = this; if (phone.verified) { return { verified: true }; } return crypto_pbkdf2(req.body.code, phone.verifySalt, 1000, 64, 'sha256') .then(function(codeHash) { if (phone.verifyCodeHash === codeHash.toString('hex')){ phone.verified = true; return phone.save(); } return phone; }) .then(function(phone) { return { verified: phone.verified }; }); } } }, internal: { sendSms: function(data) { var phone = this; return new Promise(function(resolve, reject){ try{ //https://www.twilio.com/blog/2013/03/introducing-the-twilio-module-for-node-js.html client.sendSms({ to: phone.number, from: api.phone.settings.number, body: data.text }, function(error, message) { if (error) { reject(error); }else{ resolve(message); } }); }catch(error){ reject(error); } }); } } } }; };
define([], function () { var parser = (function(){ function parseMessage(message){ var parsedMessage = '', laughingEmoticon = '<img src=\\"../server/media/emoticons/laughing.png\\"/>', likeEmoticon = '<img src="../server/media/emoticons/like.png"/>', sadEmoticon = '<img src="../server/media/emoticons/sad.png"/>', smileEmoticon = '<img src="../server/media/emoticons/smile.png"/>', winkEmoticon = '<img src="../server/media/emoticons/wink.png"/>', dislikeEmoticon = '<img src="../server/media/emoticons/dislike.png"/>', awesomeEmoticon = '<img src="../server/media/emoticons/awesome.png"/>' poopEmoticon = '<img src="../server/media/emoticons/poop.png"/>', tongueEmoticon = '<img src="../server/media/emoticons/tongue.png"/>', wtfEmoticon = '<img src="../server/media/emoticons/wtf.png"/>', kissEmoticon = '<img src="../server/media/emoticons/kiss.png"/>'; for (var i = 0; i < message.length; i++){ if (message[i] === ':' && (message[i + 1] === 'D' || message[i + 1] === 'd')) { parsedMessage += laughingEmoticon; i += 1; } else if (message[i] === ':' && message[i + 1] === ')') { parsedMessage += smileEmoticon; i += 1; } else if (message[i] === ':' && message[i + 1] === '(') { parsedMessage += sadEmoticon; i += 1; } else if (message[i] === ';' && message[i + 1] === ')') { parsedMessage += winkEmoticon; i += 1; } else if (message[i] === '(' && (message[i + 1] === 'y' || message[i + 1] === 'Y') && message[i + 2] === ')') { parsedMessage += likeEmoticon; i += 2; } else if (message[i] === '(' && (message[i + 1] === 'n' || message[i + 1] === 'N') && message[i + 2] === ')') { parsedMessage += dislikeEmoticon; i += 2; } else if (message[i] === ':' && message[i + 1] === '3'){ parsedMessage += awesomeEmoticon; i += 1; } else if (message[i] === ':' && message[i + 1] === '*'){ parsedMessage += kissEmoticon; i += 1; } else if (message[i] === 'o' && message[i + 1] === '.' && message[i + 2] === 'O'){ parsedMessage += wtfEmoticon; i += 2; } else if (message[i] === ':' && message[i + 4] === 'p' && message[i + 5] === ':'){ parsedMessage += poopEmoticon; i += 5; } else if (message[i] === ':' && (message[i + 1] === 'P' || message[i + 1] === 'p')){ parsedMessage += tongueEmoticon; i += 1; } else { parsedMessage += message[i]; } } console.log(parsedMessage); return parsedMessage; } return { parseMessage: parseMessage }; }()); return parser; });
import { createIterable } from '../helpers/helpers'; import from from 'core-js-pure/es/array/from'; import Set from 'core-js-pure/features/set'; QUnit.test('Set#symmetricDifference', assert => { const { symmetricDifference } = Set.prototype; assert.isFunction(symmetricDifference); assert.arity(symmetricDifference, 1); assert.name(symmetricDifference, 'symmetricDifference'); assert.nonEnumerable(Set.prototype, 'symmetricDifference'); const set = new Set([1]); assert.notSame(set.symmetricDifference([2]), set); assert.deepEqual(from(new Set([1, 2, 3]).symmetricDifference([4, 5])), [1, 2, 3, 4, 5]); assert.deepEqual(from(new Set([1, 2, 3]).symmetricDifference([3, 4])), [1, 2, 4]); assert.deepEqual(from(new Set([1, 2, 3]).symmetricDifference(createIterable([3, 4]))), [1, 2, 4]); assert.throws(() => new Set([1, 2, 3]).symmetricDifference(), TypeError); assert.throws(() => symmetricDifference.call({}, [1, 2, 3]), TypeError); assert.throws(() => symmetricDifference.call(undefined, [1, 2, 3]), TypeError); assert.throws(() => symmetricDifference.call(null, [1, 2, 3]), TypeError); });
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin') var TARGET = process.env.TARGET; var config = { devtool: 'eval-source-map', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './app/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'App/Views/template.html' }) ], module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'app') }] }, resolve: { root: [ path.resolve(__dirname) ] } }; if (TARGET === 'prod') { var config = { devtool: 'source-map', entry: [ './app/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/ui/' }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false }, sourceMap: false }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'App/Views/template.html' }) ], module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'app') }] }, resolve: { root: [ path.resolve(__dirname) ] } }; } module.exports = config;
const { each } = require('async') const executeInitializers = async (ready, params) => new Promise(async (resolve, reject) => { const $ = Object.keys(ready).filter(r => r[0] === '$') try { resolve(await each($, async i => await ready[i](params))) } catch (e) { reject(e) } }) module.exports = executeInitializers
// Random number utilities let retV = false, vVal = 0.0, /** * * @name Utility * @type {object} * @property {function} assert * @property {function} getDirection: * @property {function} getElementPosition * @property {function} getOpt * @property {function} loadJSON * @property {function} rgbToHex * @property {function} hexToRgb * @property {object} Arrays * @property {function} Arrays.arrContains * @property {function} Arrays.arrUnique * @property {function} Arrays.findObject * @property {object} Maths * @property {number} Maths.ONED * @property {function} Maths.clamp * @property {function} Maths.degree * @property {function} Maths.gaussRandom * @property {function} Maths.map * @property {function} Maths.maxMin * @property {function} Maths.randf * @property {function} Maths.randi * @property {function} Maths.randn * @property {function} Maths.randperm * @property {function} Maths.radian * @property {function} Maths.range * @property {function} Maths.weightedSample * @property {function} Maths.zeros * @property {object} Strings * @property {function} Strings.flt2str * @property {function} Strings.parse * @property {function} Strings.stringify * @property {function} Strings.guid * @property {function} Strings.S4 */ Utility = { /** * Utility fun * @param {*} condition * @param {string} message */ assert(condition, message) { // from http://stackoverflow.com/questions/15313418/javascript-assert if (!condition) { message = message || 'Assertion failed'; if (Error !== undefined) { throw new Error(message); } throw message; // Fallback } }, /** * Calculate the direction. * @param {number} angle * @return {string} */ getDirection(angle) { if (angle < 0) { angle += 360; } let directions = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'], octant = Math.round(8 * angle / (2 * Math.PI) + 8) % 8; return directions[octant]; }, /** * * @param {HTMLElement} element * @return {{x: number, y: number}} */ getElementPosition: function (element) { let elem = element, tagname = "", x = 0, y = 0; while ((typeof (elem) === "object") && (typeof (elem.tagName) !== "undefined")) { y += elem.offsetTop; x += elem.offsetLeft; tagname = elem.tagName.toUpperCase(); if (tagname === "BODY") { elem = 0; } if (typeof (elem) === "object") { if (typeof (elem.offsetParent) === "object") { elem = elem.offsetParent; } } } return {x: x, y: y}; }, /** * Syntactic sugar function for getting default parameter values * @param {Object} opt * @param {string} fieldName * @param {*} defaultV * @return {*} */ getOpt(opt, fieldName, defaultV) { if (opt === undefined) { return defaultV; } return (typeof opt[fieldName] !== 'undefined') ? opt[fieldName] : defaultV; }, /** * * @param {number|string} hex * @return {*} */ hexToRgb(hex) { if (!isNaN(hex)) { hex = "#" + hex.toString(16); } let ret = {r: 0, g: 0, b: 0}, shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function (m, r, g, b) { return r + r + g + g + b + b; }); let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if (result) { ret.r = parseInt(result[1], 16); ret.g = parseInt(result[2], 16); ret.b = parseInt(result[3], 16); return ret; } else { return null; } }, /** * Load JSON * @param {string} file * @param {function} callback */ loadJSON(file, callback) { let xObj = new XMLHttpRequest(); xObj.overrideMimeType('application/json'); xObj.open('GET', file, true); xObj.onreadystatechange = function () { if (xObj.readyState === 4 && xObj.status === 200) { callback(xObj.responseText); } }; xObj.send(null); }, /** * Usage: Load different file types with one callback * Promise.all([ * load.js('lib/highlighter.js'), * load.js('lib/main.js'), * load.css('lib/highlighter.css'), * load.img('images/logo.png') * ]).then(function() { * console.log('Everything has loaded!'); * }).catch(function() { * console.log('Oh no, epic failure!'); * }); * @type {{css, js, img}} */ Loader() { /** * Function which returns a function: * https://davidwalsh.name/javascript-functions */ function _load(tag) { return function (url) { // This promise will be used by Promise.all // to determine success or failure return new Promise(function (resolve, reject) { var element = document.createElement(tag), parent = 'body', attr = 'src'; // Important success and error for the promise element.onload = function () { resolve(url); }; element.onerror = function () { reject(url); }; // Need to set different attributes depending on tag type switch (tag) { case 'script': element.async = true; break; case 'link': element.type = 'text/css'; element.rel = 'stylesheet'; attr = 'href'; parent = 'head'; } // Inject into document to kick off loading element[attr] = url; document[parent].appendChild(element); }); }; } return { css: _load('link'), js: _load('script'), img: _load('img') }; }, /** * * @param {number} r * @param {number} g * @param {number} b * @return {number} */ rgbToHex(r, g, b) { return parseInt("0x" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)); }, /** * */ Arrays: { /** * * @param {Array} arr * @return {Array} */ arrUnique: function (arr) { let h = {}, output = []; for (let i = 0, n = arr.length; i < n; i++) { if (!h[arr[i]]) { h[arr[i]] = true; output.push(arr[i]); } } return output; }, /** * * @param {Array} arr * @param {object} elt * @return {number|boolean} */ arrContains: function (arr, elt) { for (let i = 0, n = arr.length; i < n; i++) { if (arr[i] === elt) { return i; } } return false; }, /** * Find an object in the array via id attribute * @param {Array} ar * @param {string} id * @return {object} */ findObject: function (ar, id) { ar.map(function (el) { return el.id; }).indexOf(id); } }, /** * */ Maths: { /** * Gaussian random number * @return {number} */ gaussRandom: function () { if (retV) { retV = false; return vVal; } let u = 2 * Math.random() - 1, v = 2 * Math.random() - 1, r = u * u + v * v, c = Math.sqrt(-2 * Math.log(r) / r); if (r === 0 || r > 1) { return this.gaussRandom(); } vVal = v * c; // cache this retV = true; return u * c; }, /** * Return max and min of a given non-empty array. * @param {Array} w * @returns {*} */ maxMin: function (w) { if (w.length === 0) { return {}; } // ... ;s let maxv = w[0], minv = w[0], maxi = 0, mini = 0, n = w.length; for (let i = 1; i < n; i++) { if (w[i] > maxv) { maxv = w[i]; maxi = i; } if (w[i] < minv) { minv = w[i]; mini = i; } } return { maxi: maxi, maxv: maxv, mini: mini, minv: minv, dv: maxv - minv }; }, /** * Return a random Float within the range of a-b * @param {number} lo * @param {number} hi * @return {number} */ randf: function (lo, hi) { return Math.random() * (hi - lo) + lo; }, /** * Return a random Integer within the range of a-b * @param {number} lo * @param {number} hi * @return {number} */ randi: function (lo, hi) { return Math.floor(this.randf(lo, hi)); }, /** * Return a random Number * @param {float} mu * @param {float} std * @return {number} */ randn: function (mu, std) { return mu + this.gaussRandom() * std; }, /** * create random permutation of numbers, in range [0...n-1] * @param {number} n * @return {Array} */ randperm: function (n) { let i = n, j = 0, temp, array = []; for (let q = 0; q < n; q++) { array[q] = q; } while (i--) { j = Math.floor(Math.random() * (i + 1)); temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }, /** * A helper function returns array of zeros of length n * and uses typed arrays if available * @param {number} n * @return {Float64Array|Array} */ zeros: function (n) { if (typeof n === 'undefined' || isNaN(n)) { return []; } if (typeof ArrayBuffer === 'undefined') { // lacking browser support let arr = new Array(n); for (let i = 0; i < n; i++) { arr[i] = 0; } return arr; } else { return new Float64Array(n); } }, /** * * @param {number} min * @param {number} max * @param {boolean} round * @return {*} */ range: function (min, max, round) { if (typeof round === "undefined") { round = true; } if (round) { return Math.floor(Math.random() * (max - min + 1)) + min; } else { return Math.random() * (max - min) + min; } }, /** * * @param {number} value * @return {number} */ degree: function (value) { return value / this.ONED; }, /** * * @param {number} value * @return {number} */ radian: function (value) { return value * this.ONED; }, /** * * @param {number} val * @param {number} min * @param {number} max * @return {number} */ clamp: function (val, min, max) { return Math.max(min, Math.min(max, val)); }, /** * * @param {number} value * @param {number} low * @param {number} high * @param {number} low2 * @param {number} high2 * @return {*} */ map: function (value, low, high, low2, high2) { let percent = (value - low) / (high - low); return low2 + percent * (high2 - low2); }, /** * sample from list lst according to probabilities in list probs * the two lists are of same size, and probs adds up to 1 * @param {Array} lst * @param {Array} probs * @return {*} */ weightedSample: function (lst, probs) { let p = Utility.Maths.randf(0, 1.0), cumprob = 0.0; for (let k = 0, n = lst.length; k < n; k++) { cumprob += probs[k]; if (p < cumprob) { return lst[k]; } } }, ONED: Math.PI / 180 }, /** * */ Strings: { /** * Returns string representation of float * but truncated to length of d digits * @param {number} x Float * @param {number} d Decimals * @return {String} */ flt2str: function (x, d) { d = (d === undefined) ? 5 : d; let dd = Math.pow(10, d); return '' + Math.floor(x * dd) / dd; } , /** * Parse an object that has been stringified, and rebuild it's functions * @param {String} str */ parse: function (str) { return JSON.parse(str, function (key, value) { if (typeof value !== 'string') { return value; } return (value.substring(0, 8) === 'function') ? eval('(' + value + ')') : value; }); } , /** * Stringify an object including it's functions if it has any * @param {Object} obj */ stringify: function (obj) { return JSON.stringify(obj, function (key, value) { return (typeof value === 'function') ? value.toString() : value; }); } , /** * Generate a UUID * @return {String} */ guid: function () { let i1 = this.S4() + this.S4(), i2 = this.S4() + '-4' + this.S4().substr(0, 3), i3 = this.S4(), i4 = this.S4() + this.S4() + this.S4(); return (i1 + '-' + i2 + '-' + i3 + '-' + i4).toLowerCase(); } , /** * Do stuff * @return {string} */ S4: function () { return (((1 + Math.random()) * 0x10000) || 0).toString(16).substring(1); } } };
module.exports = { "env": { "es6": true, "node": true, "mocha": true, }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module", }, "parser": "babel-eslint", "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
var button = document.getElementById('create-event-button'); button.addEventListener('click', function(e) { e.preventDefault(); // Submit data to DB. db.collection('events') .add({ title: document.getElementById('event-title').value, date: document.getElementById('event-date').value, location: document.getElementById('event-location').value, description: document.getElementById('event-description').value, }) // Show success alert upon completion. .then(function() { activateSuccessAlert(); document.getElementById('create-event-form').reset(); }) // Show fail Alert if error. .catch(function(error) { activateFailedAlert(); console.log(error); }); });
'use strict'; require('es6-promise').polyfill(); window.regeneratorRuntime = require('regenerator-runtime'); // https://www.npmjs.com/package/browser-cookies const Cookies = require('browser-cookies'); const qs = require('qs'); const co = require('co'); const Enums = require('billund-enums'); const WidgetEnums = Enums.widget; const StateEnums = Enums.state; const RenderEnums = Enums.render; const SupportorEnums = Enums.supportor; const RenderTypeEnums = Enums.renderType; const ReactWidgetBridge = require('../bridge/reactwidgetbridge'); const VueWidgetBridge = require('../bridge/vuewidgetbridge'); const Util = require('../util/index.js'); /* 注册api关联 */ const API_ALIAS_CONFIG = { registerMapStateToProps: 'registMapStateToProps', registerOnStartListener: 'registOnStartListener', registerOnFailListener: 'registOnFailListener', registerOnChangeListener: 'registOnChangeListener' }; /** * 基础的前端支持组件 */ class BaseFESupportor { constructor() { // lego不能初始化两次 if (window[SupportorEnums.BROWSER_SUPPORTOR]) { console.error(`duplicate init fe supportor!please check the billund-supportor version!`); return; } /* 基础中间件 */ this.registBaseMiddlewares(); /* 数据相关 */ this.initialState = window[StateEnums.INITIAL_STATE] || {}; this.store = null; // store根据具体类型初始化 this.widgetConfigs = null; /* 组件相关 */ // 重要的组件 this.importantWidgets = []; // 成功的重要组件 this.successImportantWidgets = []; // 失败的组件 this.fallbackWidgets = []; // widgetName到widget实例们的关联 this.name2Widgets = {}; // widgetName到widget-module的关联 this.name2WidgetModules = {}; // 关于widgetBridge缓存 this.widgetBridgeCache = {}; // 收集到的参数 this.collectedParams = {}; // 是否页面已经展示 this.hasTakedViewToFrontEnd = false; // 组件id和渲染类型的mapping this.id2RenderTypeMapping = {}; // 组件的id和单页面路径的映射 this.id2PathsMapping = {}; // 一些与上下文强相关的事件是否已经处理 this.sthDependentOnContextProcessed = false; // 是否被注册过router this.routerRegistered = false; this.router = null; const self = this; /** * 实例中的启动方法 */ function init() { Util.initGetComputedStyle(); // 先进行启动,尝试展示pageView self.tryTakeViewToFrontEnd(); // 记录id与渲染类型的对应关系 self.remId2RenderType(); // 关联api self.aliasApi(); } init(); } aliasApi() { Object.keys(API_ALIAS_CONFIG).forEach((newApi) => { const apiName = API_ALIAS_CONFIG[newApi]; this[newApi] = this[apiName]; }); } /** * 挂载基本的中间件 */ registBaseMiddlewares() { const self = this; this.cookies = Cookies; function querystring() { const search = window.location.search || ''; if (search.indexOf('?') == -1) return ''; return search.slice(1, search.length); } this.querystring = querystring(); function query() { const str = self.querystring; return qs.parse(str); } this.query = query(); } /** * 记录id与renderType的对应关系 */ remId2RenderType() { const configs = window[WidgetEnums.WIDGET_CONFIGS] || []; configs.forEach((config) => { this.id2RenderTypeMapping[config.id] = config.renderType; }); } /** * 尝试展示当前的pageview */ tryTakeViewToFrontEnd() { const self = this; /** * 抓取重要模块,判断是否应该启动 */ function extractImportantWidgets() { self.importantWidgets = window[WidgetEnums.WIDGETS_IMPORTANT] || []; self.successImportantWidgets = window[WidgetEnums.WIDGETS_IMPORTANT_SUCCESSED] || []; self.successImportantWidgets.forEach((widgetId) => { self.shouldTakeViewToFrontEnd(widgetId); }); } extractImportantWidgets(); // 兜底,如果3000ms后还没有启动 window.setTimeout(() => { this.takeViewToFrontEnd(); }, 3000); } /** * 解析与组件配置的内容 */ parseWidgetConfigs() { const configs = this.widgetConfigs = window[WidgetEnums.WIDGET_CONFIGS] || []; const self = this; /** * 关联widget的id与name * * @param {String} id - 组件id * @param {String} name - 组件name */ function relatedWidget2Name(id, name) { if (!self.name2Widgets[name]) { self.name2Widgets[name] = []; } let widgetBridge = self.getWidgetBridgeById(id); if (!widgetBridge) return; self.name2Widgets[name].push(widgetBridge); } /** * 关联组件的id与paths * * @param {String} id - 组件id * @param {Array} paths - 路径列表 */ function relatedWidgetId2Paths(id, paths) { self.id2PathsMapping[id] = paths; } /** * 单个widgetConfig的初始化操作 * * @param {Object} config - 目前字段如下: * { * id: [String],// widget的id * name: [String],// widget的名称, * renderType: [Number]// 渲染类型 * } */ function parseWidgetConfig(config) { if (!(config && config.id)) return; const widgetBridge = self.getWidgetBridgeById(config.id); if (!widgetBridge) return; widgetBridge.initConfig(config); } configs.forEach((config) => { parseWidgetConfig(config); relatedWidget2Name(config.id, config.name); relatedWidgetId2Paths(config.id, config.paths); }); } /** * 注册上下文预处理器 * * @param {GeneratorFunction} fn - 预处理器函数 */ [SupportorEnums.BROWSER_SUPPORTOR_REGIST_PREPROCESSOR_NAME](fn) { if (!fn) return; const self = this; co(function*() { return yield fn(self); }).then(() => { self.doSthDependentOnContext(); }).catch((err) => { if (!err) return; console.log(err.stack); }); } /** * 注册store配置 */ [SupportorEnums.BROWSER_SUPPORTOR_REGIST_STORE_CONFIG]() { throw new Error(`you should impletement ${SupportorEnums.BROWSER_SUPPORTOR_REGIST_STORE_CONFIG} function.`); } /** * 注册router配置 * important!!! 如果有这个方法,需要提前预设! */ [SupportorEnums.BROWSER_SUPPORTOR_REGISTER_ROUTER_CONFIG]() { throw new Error(`you should impletement ${SupportorEnums.BROWSER_SUPPORTOR_REGISTER_ROUTER_CONFIG} function.`); } /** * 尝试执行一些与上下文强相关的事,是useContextPreProcessor的兜底 */ tryDoSthDependentOnContext() { window.setTimeout(() => { const processedByMe = this.doSthDependentOnContext(); if (processedByMe) { console.warn(`passing 1000ms without call useContextPreProcessor,so run directly.maybe you should regist a context pre-processor`); } }, 1000); } /** * 执行一些与上下文强相关的事情,可能强依赖预处理的注册 * * @return {Boolean} - 是否被调用方法处理 */ doSthDependentOnContext() { if (this.sthDependentOnContextProcessed) return false; this.sthDependentOnContextProcessed = true; this.loadFallWidgets(); return true; } /** * 解析失败模块 */ loadFallWidgets() { const self = this; let isExecuted = false; /** * 解析失败的模块 */ function resolve() { // 确认只支持一次 if (isExecuted) return; isExecuted = true; self.fallbackWidgets = window[WidgetEnums.WIDGETS_FALLBACK] || []; self.traversalFallWidgets(); } /** * domContentLoaded监听,过或不过能接收 * * @return {Function} */ function domReady() { const fns = []; let listener = null; const hack = document.documentElement.doScroll; const domContentLoaded = 'DOMContentLoaded'; let loaded = (hack ? /^loaded|^c/ : /^loaded|^i|^c/).test(document.readyState); if (!loaded) { Util.addEventListener(window, domContentLoaded, listener = function() { Util.removeEventListener(window, domContentLoaded, listener); loaded = 1; while ((listener = fns.shift())) { listener(); } }); } return function(fn) { loaded ? setTimeout(fn, 0) : fns.push(fn); }; } // 先判断是否已经是load的了,如果是的话直接执行 if (document.readyState === 'complete') { window.setTimeout(() => { resolve(); }, 5); return; } domReady()(() => { window.setTimeout(() => { resolve(); }, 1500); }); Util.addEventListener(window, 'load', () => { window.setTimeout(() => { resolve(); }, 5); }); } /** * widget的props初始化操作 */ initWidgetProps() { const widgetProps = window[WidgetEnums.WIDGET_PROPS] || []; const self = this; function pushProps(config) { self.parseWidgetProp.call(self, config); } widgetProps.forEach(pushProps); // 将props接收对象向全局暴露 window[WidgetEnums.WIDGET_PROPS] = { push: pushProps }; } /** * 初始化widget的props信息 * * @param {Object} config - 目前字段如下: * { * id: [String],// widget的id, * meta: [Object], // widget的元数据信息 * props: [Object]// widget的props * } */ parseWidgetProp(config) { if (!(config && config.id)) return; // 查看之前是否有对应的widget配置 const widgetBridge = this.getWidgetBridgeById(config.id); if (!widgetBridge) return; widgetBridge.initProps(Object.assign({}, config.meta, config.props)); } /** * 遍历失败的模块 */ traversalFallWidgets() { /* 尝试遍历过滤失败的模块,满足以下两个条件的才能运行 1.widget-module已经注册 2.参数满足条件 */ this.fallbackWidgets = this.fallbackWidgets.filter((widget) => { const name = widget.name; const widgetModule = this.name2WidgetModules[name]; if (!widgetModule) return true; const requireParams = widget.fallbackParams; const params = Util.extend({}, widget.params, this.collectedParams); const meetRequireParams = this.isMeetRequireParams(params, requireParams); if (!meetRequireParams) return true; this.executeWidget(widget.id, widgetModule, params, widget.meta).then(() => { // 尝试去将页面放入前端 this.shouldTakeViewToFrontEnd(widget.id); }); }); } /** * 检查参数是否满足条件 * * @param {Object} params - 可以发送的参数 * @param {Array} requireParams - 要求的参数和校验规则 * @return {Boolean} - 是否满足条件 */ isMeetRequireParams(params, requireParams) { if (!(requireParams && requireParams.length)) return true; return requireParams.every((requireParam) => { /* 这里现在可以支持一些校验规则 requireParam可以用 {paramname}!0!false!''!null来判断 */ requireParam = requireParam.split('!'); const value = params[requireParam[0]]; if (value === undefined) return false; const rules = requireParam.slice(1); if (!(rules && rules.length)) return true; return rules.every((rule) => { if (rule === '0') return value !== 0 || value !== '0'; if (rule === '""' || rule === '\'\'') return value !== ''; if (rule === 'null') return value !== null; if (rule === 'false') return value !== false; return true; }); }); } /** * 执行单个widget * * @param {String} id - 当在页面上时的widgetId * @param {Object} widgetModule - widget的module内容 * @param {Object} params - 参数 * @param {Object} meta - 组件的元数据 * @return {Promise} */ executeWidget(id, widgetModule, params, meta) { params = params || {}; /* 判断有没有dataGenerator 1.没有,直接将params作为数据传入 2.有 作为dataGenerator使用 */ const self = this; return co(function*() { const hasDataGenerator = !!widgetModule.dataGenerator; let props = params; if (hasDataGenerator) { props = yield widgetModule.dataGenerator.call(self, params); } window.setTimeout(() => { self.parseWidgetProp({ id, meta, props }); }, 5); return props; }).catch((err) => { if (!err) err = new Error(`unknown error`); console.log(err.stack); throw err; }); } /** * 将已经存在的重要模块出栈,如果全部存在了,那么将页面展示到前端 * * @param {String} id - 组件id */ shouldTakeViewToFrontEnd(id) { if (this.hasTakedViewToFrontEnd) return; this.importantWidgets = this.importantWidgets.filter((widgetId) => { return id != widgetId; }); if (this.importantWidgets.length) return; this.takeViewToFrontEnd(); } /** * 将页面展示给前端 */ takeViewToFrontEnd() { if (this.hasTakedViewToFrontEnd) return; const contentPage = document.getElementById(RenderEnums.ID_MAIN_PAGE); if (contentPage) { Util.showDiv(contentPage); } if (window.performance && window.performance.timing) { window[RenderEnums.FIRST_SHOW_POINT] = new Date() - window.performance.timing.navigationStart; } this.hasTakedViewToFrontEnd = true; } /** * 根据id查找对应的widget信息 * 如果没有的话会尝试初始化 * !important(保证对应的store已经初始化) * * @param {String} id - widget的id * @return {Object} - 组件信息 */ getWidgetBridgeById(id) { // 先尝试从缓存中获取 let widgetBridge = this.widgetBridgeCache[id]; if (widgetBridge) return widgetBridge; // 这里需要确保store已经初始化 let renderType = this.id2RenderTypeMapping[id] || RenderTypeEnums.RENDER_TYPE_REACT; const WidgetClass = renderType == RenderTypeEnums.RENDER_TYPE_VUE ? VueWidgetBridge : ReactWidgetBridge; widgetBridge = new WidgetClass(id, this.store, this.initialState, this); this.widgetBridgeCache[id] = widgetBridge; return widgetBridge; } /** * 根据name查找对应的widget们的信息 * * @param {String} name - widget的名称 * @return {Array} */ getWidgetBridgesByName(name) { return this.name2Widgets[name] || []; } /** * 分发action的操作 */ dispatch() { throw new Error(`you should impletement dispatch function.`); } /** * 获取当前的state */ getState() { throw new Error(`you should impletement getState function.`); } getRouter() { return this.router; } /** * 注册store变更数据监听 */ registStoreOnChangeListener() { throw new Error(`you should impletement registStoreOnChangeListener function.`); } /** * 注册widget的mapStateToProps方法,是通过name来注册的 * * @param {String} name - widget的名称 * @param {Function} mapStateToProps - 函数名称 */ registMapStateToProps(name, mapStateToProps) { const relatedWidgets = this.getWidgetBridgesByName(name); relatedWidgets.forEach((widget) => { if (!widget) return true; widget.registMapStateToProps(mapStateToProps); }); } /** * 根据名称注册widget的onStartListener回调,启动了会立即调用(多个相同组件会被调用多次) * * @param {String} name - widget的名称 * @param {Function} onStartListener - 启动函数 */ registOnStartListener(name, onStartListener) { const relatedWidgets = this.getWidgetBridgesByName(name); relatedWidgets.forEach((widget) => { if (!widget) return true; widget.registOnStartListener(onStartListener); }); } /** * 注册widget的onFailListener回调,从注册开始,超过一定时间仍然没有启动组件,认定为失败 * * @param {String} name - widget的名称 * @param {Function} onFailListener - 组件失败的回调方法 * @param {Object} option - 对应的失败配置,目前字段如下: * { * timeout: [Number] // 超时毫秒数 * } */ registOnFailListener(name, onFailListener, option) { const relatedWidgets = this.getWidgetBridgesByName(name); relatedWidgets.forEach((widget) => { if (!widget) return true; widget.registOnFailListener(onFailListener, option); }); } /** * 注册widget的onChangeListener回调 * * @param {String} name - widget的名称 * @param {Function} onChangeListener - 组件props变更回调方法 */ registOnChangeListener(name, onChangeListener) { const relatedWidgets = this.getWidgetBridgesByName(name); relatedWidgets.forEach((widget) => { if (!widget) return true; widget.registOnChangeListener(onChangeListener); }); } /** * 注册组件模块 * * @param {Object} widgetModule - 组件内容 */ registWidgetModule(widgetModule) { if (!(widgetModule && widgetModule.name)) return; const name = widgetModule.name; const relatedWidgets = this.getWidgetBridgesByName(name); relatedWidgets.forEach((widget) => { if (!widget) return true; widget.registWidgetModule(widgetModule); }); // 记录到mapping中 this.name2WidgetModules[name] = widgetModule; // 尝试遍历失败的模块 this.traversalFallWidgets(); } /** * 设置参数函数,设置后会去检查是否应该执行调用方法 * * 1:只有一个参数时的情况 * Object data = { * "key1": "val1" * "key2": "val2" * } * 2:两个参数时的情况 key,value */ setSharedParams() { let argsLength = arguments.length; if (!argsLength) { return; } // 大于两个参数时,以key value形式加入,忽视其他参数 if (argsLength > 1) { let paraObj = {}; paraObj[arguments[0]] = arguments[1]; arguments[0] = paraObj; } this.collectedParams = Util.extend(this.collectedParams, arguments[0]); // 尝试遍历失败的模块 this.traversalFallWidgets(); } /** * 获取组件的初始化状态,但是很有可能拿不到(bigpipe) * 建议在组件自身的回调里使用 * * @param {String} id - 组件id * @return {Object} */ getWidgetBridgeInitialProps(id) { let widgetBridge = this.getWidgetBridgeById(id); if (!widgetBridge) return {}; return widgetBridge.getInitialProps() || {}; } /** * 获取组件的私有state状态. * * @param {String} id - 组件id * @return {Object} */ getWidgetBridgeOwnState(id) { let widgetBridge = this.getWidgetBridgeById(id); if (!widgetBridge) return {}; return widgetBridge.getOwnState() || {}; } /** * 获取组件的容器 * * @param {String} id - 组件id * @return {HtmlElement} */ getWidgetBridgeContainer(id) { let widgetBridge = this.getWidgetBridgeById(id); if (!widgetBridge) return null; return widgetBridge.getContainer(); } /** * 隐藏widget模块 * * @param {String|Array} widgetNames - 组件名称 */ hideWidgets(widgetNames) { if (Util.isString(widgetNames)) { widgetNames = [widgetNames]; } if (!(Util.isArray(widgetNames)) && widgetNames.length) return; widgetNames.forEach((widgetName) => { const containers = document.querySelectorAll(`[data-widget-name="${widgetName}"]`); if (!(containers && containers.length)) return true; Array.prototype.slice.call(containers).forEach((container) => { Util.hideDiv(container); }); }); } /** * 展示widget模块 * * @param {String|Array} widgetNames - 组件名称 */ showWidgets(widgetNames) { if (Util.isString(widgetNames)) { widgetNames = [widgetNames]; } if (!(Util.isArray(widgetNames)) && widgetNames.length) return; widgetNames.forEach((widgetName) => { const containers = document.querySelectorAll(`[data-widget-name="${widgetName}"]`); if (!(containers && containers.length)) return true; Array.prototype.slice.call(containers).forEach((container) => { Util.showDiv(container); }); }); } } module.exports = BaseFESupportor;
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.16-7-b-11 description: > Array.prototype.every - deleting property of prototype causes prototype index property not to be visited on an Array includes: [runTestCase.js] ---*/ function testcase() { var accessed = false; function callbackfn(val, idx, obj) { accessed = true; return idx !== 1; } var arr = [0, , 2]; Object.defineProperty(arr, "0", { get: function () { delete Array.prototype[1]; return 0; }, configurable: true }); try { Array.prototype[1] = 1; return arr.every(callbackfn) && accessed; } finally { delete Array.prototype[1]; } } runTestCase(testcase);
'use strict'; // virtual-dom var h = require('virtual-dom/h'); // lodash var difference = require('lodash/difference'); // bpmn-questionnaire var BpmnQuestionnaire = require('../../../../lib/BpmnQuestionnaire'); var interactive = BpmnQuestionnaire.createType({ renderQuestion: function() { var html = h('div', [ h('p', this.options.text), this.diagram.render(this.state) ]); return html; }, renderResult: function() { var html; if (this.state.rightAnswer) { html = h('div.panel.panel-success', [ h('div.panel-heading', h('h3.panel-title', 'Glückwunsch!') ), h('div.panel-body', 'Sie haben diese Frage richtig beantwortet!') ]); } else { html = [ h('div.panel.panel-danger', [ h('div.panel-heading', h('h3.panel-title', 'Oh nein!') ), h('div.panel-body', 'Ihre Antwort war leider falsch! Die richtige Antwort lautet:') ]), this.diagram.render(this.state) ] } return html; }, checkIfValidAnswer: function() { return this.diagram.state.selected.length > 0; }, checkIfRightAnswer: function() { return difference(this.options.diagram.rightAnswers, this.diagram.state.selected).length < 1; } }); module.exports = interactive;
(function () { var default_item_width = 120; var last_list_num = 0; function getInt16String() { return parseInt(Math.random()*200+56).toString(16); } let Random = { color: function () { return '#' + getInt16String() + getInt16String() + getInt16String() ; }, size: function (min, max) { return parseInt(min + Math.random() * (max - min)); }, el: function (min = 100, max = 300) { var size = this.size(min, max); return `<div class="preview-item" style="background-color: ${this.color()};height: ${size}px;line-height: ${size}px;top: 0;left: 0;">${default_item_width} X ${size}</div>` } } var _preview = document.getElementsByClassName('preview')[0]; var _main = document.getElementsByClassName('main')[0]; function init () { for (var i = 0; i < 50; i++) { _preview.innerHTML += Random.el(100, 200); } } function relayout () { _preview.style.height = ''; var list_num = Math.floor(_main.offsetWidth / default_item_width); if (list_num === last_list_num) { return; } _preview.style.width = `${list_num * default_item_width}px`; var lists = []; for (var i = 0; i < list_num; i++) { lists.push({top: 0,left: i*default_item_width}); } items = document.getElementsByClassName('preview-item'); for (var i = 0; i < items.length; i++) { var min_height_list, min_height = Number.MAX_VALUE; for (var j = 0; j < lists.length; j++) { if (lists[j].top < min_height) { min_height_list = j; min_height = lists[j].top; } } items[i].style.width = default_item_width - 20 + 'px'; items[i].style.transitionDelay = (list_num > last_list_num ? i : (items.length - i)) * 0.2 + 's'; items[i].style.left = lists[min_height_list].left + 'px'; items[i].style.top = lists[min_height_list].top + 10 + 'px'; lists[min_height_list].top += items[i].offsetHeight + 20; } var total_height = 0; for (var i = 0; i < list_num; i++) { if (total_height < lists[i].top) { total_height = lists[i].top; } } setTimeout(() => { _preview.style.height = `${total_height + 20}px`; }, items.length * 0.2); last_list_num = list_num; } window.onload = function () { init(); relayout(); } window.onresize = relayout; })();
// Generated by CoffeeScript 1.9.1 (function() { var bcv_parser, bcv_passage, bcv_utils, root, hasProp = {}.hasOwnProperty; root = this; bcv_parser = (function() { bcv_parser.prototype.s = ""; bcv_parser.prototype.entities = []; bcv_parser.prototype.passage = null; bcv_parser.prototype.regexps = {}; bcv_parser.prototype.options = { consecutive_combination_strategy: "combine", osis_compaction_strategy: "b", book_sequence_strategy: "ignore", invalid_sequence_strategy: "ignore", sequence_combination_strategy: "combine", invalid_passage_strategy: "ignore", non_latin_digits_strategy: "ignore", passage_existence_strategy: "bcv", zero_chapter_strategy: "error", zero_verse_strategy: "error", book_alone_strategy: "ignore", book_range_strategy: "ignore", captive_end_digits_strategy: "delete", end_range_digits_strategy: "verse", include_apocrypha: false, ps151_strategy: "c", versification_system: "default", case_sensitive: "none" }; function bcv_parser() { var key, ref, val; this.options = {}; ref = bcv_parser.prototype.options; for (key in ref) { if (!hasProp.call(ref, key)) continue; val = ref[key]; this.options[key] = val; } this.versification_system(this.options.versification_system); } bcv_parser.prototype.parse = function(s) { var ref; this.reset(); this.s = s; s = this.replace_control_characters(s); ref = this.match_books(s), s = ref[0], this.passage.books = ref[1]; this.entities = this.match_passages(s)[0]; return this; }; bcv_parser.prototype.parse_with_context = function(s, context) { var entities, ref, ref1, ref2; this.reset(); ref = this.match_books(this.replace_control_characters(context)), context = ref[0], this.passage.books = ref[1]; ref1 = this.match_passages(context), entities = ref1[0], context = ref1[1]; this.reset(); this.s = s; s = this.replace_control_characters(s); ref2 = this.match_books(s), s = ref2[0], this.passage.books = ref2[1]; this.passage.books.push({ value: "", parsed: [], start_index: 0, type: "context", context: context }); s = "\x1f" + (this.passage.books.length - 1) + "/9\x1f" + s; this.entities = this.match_passages(s)[0]; return this; }; bcv_parser.prototype.reset = function() { this.s = ""; this.entities = []; if (this.passage) { this.passage.books = []; return this.passage.indices = {}; } else { this.passage = new bcv_passage; this.passage.options = this.options; return this.passage.translations = this.translations; } }; bcv_parser.prototype.set_options = function(options) { var key, val; for (key in options) { if (!hasProp.call(options, key)) continue; val = options[key]; if (key === "include_apocrypha" || key === "versification_system" || key === "case_sensitive") { this[key](val); } else { this.options[key] = val; } } return this; }; bcv_parser.prototype.include_apocrypha = function(arg) { var base, base1, ref, translation, verse_count; if (!((arg != null) && (arg === true || arg === false))) { return this; } this.options.include_apocrypha = arg; this.regexps.books = this.regexps.get_books(arg, this.options.case_sensitive); ref = this.translations; for (translation in ref) { if (!hasProp.call(ref, translation)) continue; if (translation === "aliases" || translation === "alternates") { continue; } if ((base = this.translations[translation]).chapters == null) { base.chapters = {}; } if ((base1 = this.translations[translation].chapters)["Ps"] == null) { base1["Ps"] = bcv_utils.shallow_clone_array(this.translations["default"].chapters["Ps"]); } if (arg === true) { if (this.translations[translation].chapters["Ps151"] != null) { verse_count = this.translations[translation].chapters["Ps151"][0]; } else { verse_count = this.translations["default"].chapters["Ps151"][0]; } this.translations[translation].chapters["Ps"][150] = verse_count; } else { if (this.translations[translation].chapters["Ps"].length === 151) { this.translations[translation].chapters["Ps"].pop(); } } } return this; }; bcv_parser.prototype.versification_system = function(system) { var base, base1, base2, book, chapter_list, ref, ref1; if (!((system != null) && (this.translations[system] != null))) { return this; } if (this.translations.alternates["default"] != null) { if (system === "default") { if (this.translations.alternates["default"].order != null) { this.translations["default"].order = bcv_utils.shallow_clone(this.translations.alternates["default"].order); } ref = this.translations.alternates["default"].chapters; for (book in ref) { if (!hasProp.call(ref, book)) continue; chapter_list = ref[book]; this.translations["default"].chapters[book] = bcv_utils.shallow_clone_array(chapter_list); } } else { this.versification_system("default"); } } if ((base = this.translations.alternates)["default"] == null) { base["default"] = { order: null, chapters: {} }; } if (system !== "default" && (this.translations[system].order != null)) { if ((base1 = this.translations.alternates["default"]).order == null) { base1.order = bcv_utils.shallow_clone(this.translations["default"].order); } this.translations["default"].order = bcv_utils.shallow_clone(this.translations[system].order); } if (system !== "default" && (this.translations[system].chapters != null)) { ref1 = this.translations[system].chapters; for (book in ref1) { if (!hasProp.call(ref1, book)) continue; chapter_list = ref1[book]; if ((base2 = this.translations.alternates["default"].chapters)[book] == null) { base2[book] = bcv_utils.shallow_clone_array(this.translations["default"].chapters[book]); } this.translations["default"].chapters[book] = bcv_utils.shallow_clone_array(chapter_list); } } this.options.versification_system = system; this.include_apocrypha(this.options.include_apocrypha); return this; }; bcv_parser.prototype.case_sensitive = function(arg) { if (!((arg != null) && (arg === "none" || arg === "books"))) { return this; } if (arg === this.options.case_sensitive) { return this; } this.options.case_sensitive = arg; this.regexps.books = this.regexps.get_books(this.options.include_apocrypha, arg); return this; }; bcv_parser.prototype.translation_info = function(new_translation) { var book, chapter_list, id, old_translation, out, ref, ref1, ref2; if (new_translation == null) { new_translation = "default"; } if ((new_translation != null) && (((ref = this.translations.aliases[new_translation]) != null ? ref.alias : void 0) != null)) { new_translation = this.translations.aliases[new_translation].alias; } if (!((new_translation != null) && (this.translations[new_translation] != null))) { new_translation = "default"; } old_translation = this.options.versification_system; if (new_translation !== old_translation) { this.versification_system(new_translation); } out = { order: bcv_utils.shallow_clone(this.translations["default"].order), books: [], chapters: {} }; ref1 = this.translations["default"].chapters; for (book in ref1) { if (!hasProp.call(ref1, book)) continue; chapter_list = ref1[book]; out.chapters[book] = bcv_utils.shallow_clone_array(chapter_list); } ref2 = out.order; for (book in ref2) { if (!hasProp.call(ref2, book)) continue; id = ref2[book]; out.books[id - 1] = book; } if (new_translation !== old_translation) { this.versification_system(old_translation); } return out; }; bcv_parser.prototype.replace_control_characters = function(s) { s = s.replace(this.regexps.control, " "); if (this.options.non_latin_digits_strategy === "replace") { s = s.replace(/[٠۰߀०০੦૦୦0౦೦൦๐໐༠၀႐០᠐᥆᧐᪀᪐᭐᮰᱀᱐꘠꣐꤀꧐꩐꯰0]/g, "0"); s = s.replace(/[١۱߁१১੧૧୧௧౧೧൧๑໑༡၁႑១᠑᥇᧑᪁᪑᭑᮱᱁᱑꘡꣑꤁꧑꩑꯱1]/g, "1"); s = s.replace(/[٢۲߂२২੨૨୨௨౨೨൨๒໒༢၂႒២᠒᥈᧒᪂᪒᭒᮲᱂᱒꘢꣒꤂꧒꩒꯲2]/g, "2"); s = s.replace(/[٣۳߃३৩੩૩୩௩౩೩൩๓໓༣၃႓៣᠓᥉᧓᪃᪓᭓᮳᱃᱓꘣꣓꤃꧓꩓꯳3]/g, "3"); s = s.replace(/[٤۴߄४৪੪૪୪௪౪೪൪๔໔༤၄႔៤᠔᥊᧔᪄᪔᭔᮴᱄᱔꘤꣔꤄꧔꩔꯴4]/g, "4"); s = s.replace(/[٥۵߅५৫੫૫୫௫౫೫൫๕໕༥၅႕៥᠕᥋᧕᪅᪕᭕᮵᱅᱕꘥꣕꤅꧕꩕꯵5]/g, "5"); s = s.replace(/[٦۶߆६৬੬૬୬௬౬೬൬๖໖༦၆႖៦᠖᥌᧖᪆᪖᭖᮶᱆᱖꘦꣖꤆꧖꩖꯶6]/g, "6"); s = s.replace(/[٧۷߇७৭੭૭୭௭౭೭൭๗໗༧၇႗៧᠗᥍᧗᪇᪗᭗᮷᱇᱗꘧꣗꤇꧗꩗꯷7]/g, "7"); s = s.replace(/[٨۸߈८৮੮૮୮௮౮೮൮๘໘༨၈႘៨᠘᥎᧘᪈᪘᭘᮸᱈᱘꘨꣘꤈꧘꩘꯸8]/g, "8"); s = s.replace(/[٩۹߉९৯੯૯୯௯౯೯൯๙໙༩၉႙៩᠙᥏᧙᪉᪙᭙᮹᱉᱙꘩꣙꤉꧙꩙꯹9]/g, "9"); } return s; }; bcv_parser.prototype.match_books = function(s) { var book, books, has_replacement, k, len, ref; books = []; ref = this.regexps.books; for (k = 0, len = ref.length; k < len; k++) { book = ref[k]; has_replacement = false; s = s.replace(book.regexp, function(full, prev, bk) { var extra; has_replacement = true; books.push({ value: bk, parsed: book.osis, type: "book" }); extra = book.extra != null ? "/" + book.extra : ""; return prev + "\x1f" + (books.length - 1) + extra + "\x1f"; }); if (has_replacement === true && /^[\s\x1f\d:.,;\-\u2013\u2014]+$/.test(s)) { break; } } s = s.replace(this.regexps.translations, function(match) { books.push({ value: match, parsed: match.toLowerCase(), type: "translation" }); return "\x1e" + (books.length - 1) + "\x1e"; }); return [s, this.get_book_indices(books, s)]; }; bcv_parser.prototype.get_book_indices = function(books, s) { var add_index, match, re; add_index = 0; re = /([\x1f\x1e])(\d+)(?:\/\d+)?\1/g; while (match = re.exec(s)) { books[match[2]].start_index = match.index + add_index; add_index += books[match[2]].value.length - match[0].length; } return books; }; bcv_parser.prototype.match_passages = function(s) { var accum, book_id, entities, full, match, next_char, original_part_length, part, passage, post_context, re, ref, regexp_index_adjust, start_index_adjust; entities = []; post_context = {}; while (match = this.regexps.escaped_passage.exec(s)) { full = match[0], part = match[1], book_id = match[2]; original_part_length = part.length; match.index += full.length - original_part_length; if (/\s[2-9]\d\d\s*$|\s\d{4,}\s*$/.test(part)) { re = /\s+\d+\s*$/; part = part.replace(re, ""); } if (!/[\d\x1f\x1e)]$/.test(part)) { part = this.replace_match_end(part); } if (this.options.captive_end_digits_strategy === "delete") { next_char = match.index + part.length; if (s.length > next_char && /^\w/.test(s.substr(next_char, 1))) { part = part.replace(/[\s*]+\d+$/, ""); } part = part.replace(/(\x1e[)\]]?)[\s*]*\d+$/, "$1"); } part = part.replace(/[A-Z]+/g, function(capitals) { return capitals.toLowerCase(); }); start_index_adjust = part.substr(0, 1) === "\x1f" ? 0 : part.split("\x1f")[0].length; passage = { value: grammar.parse(part), type: "base", start_index: this.passage.books[book_id].start_index - start_index_adjust, match: part }; if (this.options.book_alone_strategy === "full" && this.options.book_range_strategy === "include" && passage.value[0].type === "b" && (passage.value.length === 1 || (passage.value.length > 1 && passage.value[1].type === "translation_sequence")) && start_index_adjust === 0 && (this.passage.books[book_id].parsed.length === 1 || (this.passage.books[book_id].parsed.length > 1 && this.passage.books[book_id].parsed[1].type === "translation")) && /^[234]/.test(this.passage.books[book_id].parsed[0])) { this.create_book_range(s, passage, book_id); } ref = this.passage.handle_obj(passage), accum = ref[0], post_context = ref[1]; entities = entities.concat(accum); regexp_index_adjust = this.adjust_regexp_end(accum, original_part_length, part.length); if (regexp_index_adjust > 0) { this.regexps.escaped_passage.lastIndex -= regexp_index_adjust; } } return [entities, post_context]; }; bcv_parser.prototype.adjust_regexp_end = function(accum, old_length, new_length) { var regexp_index_adjust; regexp_index_adjust = 0; if (accum.length > 0) { regexp_index_adjust = old_length - accum[accum.length - 1].indices[1] - 1; } else if (old_length !== new_length) { regexp_index_adjust = old_length - new_length; } return regexp_index_adjust; }; bcv_parser.prototype.replace_match_end = function(part) { var match, remove; remove = part.length; while (match = this.regexps.match_end_split.exec(part)) { remove = match.index + match[0].length; } if (remove < part.length) { part = part.substr(0, remove); } return part; }; bcv_parser.prototype.create_book_range = function(s, passage, book_id) { var cases, i, k, limit, prev, range_regexp, ref; cases = [bcv_parser.prototype.regexps.first, bcv_parser.prototype.regexps.second, bcv_parser.prototype.regexps.third]; limit = parseInt(this.passage.books[book_id].parsed[0].substr(0, 1), 10); for (i = k = 1, ref = limit; 1 <= ref ? k < ref : k > ref; i = 1 <= ref ? ++k : --k) { range_regexp = i === limit - 1 ? bcv_parser.prototype.regexps.range_and : bcv_parser.prototype.regexps.range_only; prev = s.match(RegExp("(?:^|\\W)(" + cases[i - 1] + "\\s*" + range_regexp + "\\s*)\\x1f" + book_id + "\\x1f", "i")); if (prev != null) { return this.add_book_range_object(passage, prev, i); } } return false; }; bcv_parser.prototype.add_book_range_object = function(passage, prev, start_book_number) { var i, k, length, ref, ref1, results; length = prev[1].length; passage.value[0] = { type: "b_range_pre", value: [ { type: "b_pre", value: start_book_number.toString(), indices: [prev.index, prev.index + length] }, passage.value[0] ], indices: [0, passage.value[0].indices[1] + length] }; passage.value[0].value[1].indices[0] += length; passage.value[0].value[1].indices[1] += length; passage.start_index -= length; passage.match = prev[1] + passage.match; if (passage.value.length === 1) { return; } results = []; for (i = k = 1, ref = passage.value.length; 1 <= ref ? k < ref : k > ref; i = 1 <= ref ? ++k : --k) { if (passage.value[i].value == null) { continue; } if (((ref1 = passage.value[i].value[0]) != null ? ref1.indices : void 0) != null) { passage.value[i].value[0].indices[0] += length; passage.value[i].value[0].indices[1] += length; } passage.value[i].indices[0] += length; results.push(passage.value[i].indices[1] += length); } return results; }; bcv_parser.prototype.osis = function() { var k, len, osis, out, ref; out = []; ref = this.parsed_entities(); for (k = 0, len = ref.length; k < len; k++) { osis = ref[k]; if (osis.osis.length > 0) { out.push(osis.osis); } } return out.join(","); }; bcv_parser.prototype.osis_and_translations = function() { var k, len, osis, out, ref; out = []; ref = this.parsed_entities(); for (k = 0, len = ref.length; k < len; k++) { osis = ref[k]; if (osis.osis.length > 0) { out.push([osis.osis, osis.translations.join(",")]); } } return out; }; bcv_parser.prototype.osis_and_indices = function() { var k, len, osis, out, ref; out = []; ref = this.parsed_entities(); for (k = 0, len = ref.length; k < len; k++) { osis = ref[k]; if (osis.osis.length > 0) { out.push({ osis: osis.osis, translations: osis.translations, indices: osis.indices }); } } return out; }; bcv_parser.prototype.parsed_entities = function() { var entity, entity_id, i, k, l, last_i, len, len1, length, m, n, osis, osises, out, passage, ref, ref1, ref2, ref3, strings, translation, translation_alias, translation_osis, translations; out = []; for (entity_id = k = 0, ref = this.entities.length; 0 <= ref ? k < ref : k > ref; entity_id = 0 <= ref ? ++k : --k) { entity = this.entities[entity_id]; if (entity.type && entity.type === "translation_sequence" && out.length > 0 && entity_id === out[out.length - 1].entity_id + 1) { out[out.length - 1].indices[1] = entity.absolute_indices[1]; } if (entity.passages == null) { continue; } if ((entity.type === "b" && this.options.book_alone_strategy === "ignore") || (entity.type === "b_range" && this.options.book_range_strategy === "ignore") || entity.type === "context") { continue; } translations = []; translation_alias = null; if (entity.passages[0].translations != null) { ref1 = entity.passages[0].translations; for (l = 0, len = ref1.length; l < len; l++) { translation = ref1[l]; translation_osis = ((ref2 = translation.osis) != null ? ref2.length : void 0) > 0 ? translation.osis : ""; if (translation_alias == null) { translation_alias = translation.alias; } translations.push(translation_osis); } } else { translations = [""]; translation_alias = "default"; } osises = []; length = entity.passages.length; for (i = m = 0, ref3 = length; 0 <= ref3 ? m < ref3 : m > ref3; i = 0 <= ref3 ? ++m : --m) { passage = entity.passages[i]; if (passage.type == null) { passage.type = entity.type; } if (passage.valid.valid === false) { if (this.options.invalid_sequence_strategy === "ignore" && entity.type === "sequence") { this.snap_sequence("ignore", entity, osises, i, length); } if (this.options.invalid_passage_strategy === "ignore") { continue; } } if ((passage.type === "b" || passage.type === "b_range") && this.options.book_sequence_strategy === "ignore" && entity.type === "sequence") { this.snap_sequence("book", entity, osises, i, length); continue; } if ((passage.type === "b_range_start" || passage.type === "range_end_b") && this.options.book_range_strategy === "ignore") { this.snap_range(entity, i); } if (passage.absolute_indices == null) { passage.absolute_indices = entity.absolute_indices; } osises.push({ osis: passage.valid.valid ? this.to_osis(passage.start, passage.end, translation_alias) : "", type: passage.type, indices: passage.absolute_indices, translations: translations, start: passage.start, end: passage.end, enclosed_indices: passage.enclosed_absolute_indices, entity_id: entity_id, entities: [passage] }); } if (osises.length === 0) { continue; } if (osises.length > 1 && this.options.consecutive_combination_strategy === "combine") { osises = this.combine_consecutive_passages(osises, translation_alias); } if (this.options.sequence_combination_strategy === "separate") { out = out.concat(osises); } else { strings = []; last_i = osises.length - 1; if ((osises[last_i].enclosed_indices != null) && osises[last_i].enclosed_indices[1] >= 0) { entity.absolute_indices[1] = osises[last_i].enclosed_indices[1]; } for (n = 0, len1 = osises.length; n < len1; n++) { osis = osises[n]; if (osis.osis.length > 0) { strings.push(osis.osis); } } out.push({ osis: strings.join(","), indices: entity.absolute_indices, translations: translations, entity_id: entity_id, entities: osises }); } } return out; }; bcv_parser.prototype.to_osis = function(start, end, translation) { var osis, out; if ((end.c == null) && (end.v == null) && start.b === end.b && (start.c == null) && (start.v == null) && this.options.book_alone_strategy === "first_chapter") { end.c = 1; } osis = { start: "", end: "" }; if (start.c == null) { start.c = 1; } if (start.v == null) { start.v = 1; } if (end.c == null) { if (this.options.passage_existence_strategy.indexOf("c") >= 0 || ((this.passage.translations[translation].chapters[end.b] != null) && this.passage.translations[translation].chapters[end.b].length === 1)) { end.c = this.passage.translations[translation].chapters[end.b].length; } else { end.c = 999; } } if (end.v == null) { if ((this.passage.translations[translation].chapters[end.b][end.c - 1] != null) && this.options.passage_existence_strategy.indexOf("v") >= 0) { end.v = this.passage.translations[translation].chapters[end.b][end.c - 1]; } else { end.v = 999; } } if (this.options.include_apocrypha && this.options.ps151_strategy === "b" && ((start.c === 151 && start.b === "Ps") || (end.c === 151 && end.b === "Ps"))) { this.fix_ps151(start, end, translation); } if (this.options.osis_compaction_strategy === "b" && start.c === 1 && start.v === 1 && end.c === this.passage.translations[translation].chapters[end.b].length && end.v === this.passage.translations[translation].chapters[end.b][end.c - 1]) { osis.start = start.b; osis.end = end.b; } else if (this.options.osis_compaction_strategy.length <= 2 && start.v === 1 && (end.v === 999 || end.v === this.passage.translations[translation].chapters[end.b][end.c - 1])) { osis.start = start.b + "." + start.c.toString(); osis.end = end.b + "." + end.c.toString(); } else { osis.start = start.b + "." + start.c.toString() + "." + start.v.toString(); osis.end = end.b + "." + end.c.toString() + "." + end.v.toString(); } if (osis.start === osis.end) { out = osis.start; } else { out = osis.start + "-" + osis.end; } if (start.extra != null) { out = start.extra + "," + out; } if (end.extra != null) { out += "," + end.extra; } return out; }; bcv_parser.prototype.fix_ps151 = function(start, end, translation) { var ref; if (translation !== "default" && (((ref = this.translations[translation]) != null ? ref.chapters["Ps151"] : void 0) == null)) { this.passage.promote_book_to_translation("Ps151", translation); } if (start.c === 151 && start.b === "Ps") { if (end.c === 151 && end.b === "Ps") { start.b = "Ps151"; start.c = 1; end.b = "Ps151"; return end.c = 1; } else { start.extra = this.to_osis({ b: "Ps151", c: 1, v: start.v }, { b: "Ps151", c: 1, v: this.passage.translations[translation].chapters["Ps151"][0] }, translation); start.b = "Prov"; start.c = 1; return start.v = 1; } } else { end.extra = this.to_osis({ b: "Ps151", c: 1, v: 1 }, { b: "Ps151", c: 1, v: end.v }, translation); end.c = 150; return end.v = this.passage.translations[translation].chapters["Ps"][149]; } }; bcv_parser.prototype.combine_consecutive_passages = function(osises, translation) { var enclosed_sequence_start, has_enclosed, i, is_enclosed_last, k, last_i, osis, out, prev, prev_i, ref; out = []; prev = {}; last_i = osises.length - 1; enclosed_sequence_start = -1; has_enclosed = false; for (i = k = 0, ref = last_i; 0 <= ref ? k <= ref : k >= ref; i = 0 <= ref ? ++k : --k) { osis = osises[i]; if (osis.osis.length > 0) { prev_i = out.length - 1; is_enclosed_last = false; if (osis.enclosed_indices[0] !== enclosed_sequence_start) { enclosed_sequence_start = osis.enclosed_indices[0]; } if (enclosed_sequence_start >= 0 && (i === last_i || osises[i + 1].enclosed_indices[0] !== osis.enclosed_indices[0])) { is_enclosed_last = true; has_enclosed = true; } if (this.is_verse_consecutive(prev, osis.start, translation)) { out[prev_i].end = osis.end; out[prev_i].is_enclosed_last = is_enclosed_last; out[prev_i].indices[1] = osis.indices[1]; out[prev_i].enclosed_indices[1] = osis.enclosed_indices[1]; out[prev_i].osis = this.to_osis(out[prev_i].start, osis.end, translation); } else { out.push(osis); } prev = { b: osis.end.b, c: osis.end.c, v: osis.end.v }; } else { out.push(osis); prev = {}; } } if (has_enclosed) { this.snap_enclosed_indices(out); } return out; }; bcv_parser.prototype.snap_enclosed_indices = function(osises) { var k, len, osis; for (k = 0, len = osises.length; k < len; k++) { osis = osises[k]; if (osis.is_enclosed_last != null) { if (osis.enclosed_indices[0] < 0 && osis.is_enclosed_last) { osis.indices[1] = osis.enclosed_indices[1]; } delete osis.is_enclosed_last; } } return osises; }; bcv_parser.prototype.is_verse_consecutive = function(prev, check, translation) { var translation_order; if (prev.b == null) { return false; } translation_order = this.passage.translations[translation].order != null ? this.passage.translations[translation].order : this.passage.translations["default"].order; if (prev.b === check.b) { if (prev.c === check.c) { if (prev.v === check.v - 1) { return true; } } else if (check.v === 1 && prev.c === check.c - 1) { if (prev.v === this.passage.translations[translation].chapters[prev.b][prev.c - 1]) { return true; } } } else if (check.c === 1 && check.v === 1 && translation_order[prev.b] === translation_order[check.b] - 1) { if (prev.c === this.passage.translations[translation].chapters[prev.b].length && prev.v === this.passage.translations[translation].chapters[prev.b][prev.c - 1]) { return true; } } return false; }; bcv_parser.prototype.snap_range = function(entity, passage_i) { var entity_i, key, pluck, ref, source_entity, target_entity, temp, type; if (entity.type === "b_range_start" || (entity.type === "sequence" && entity.passages[passage_i].type === "b_range_start")) { entity_i = 1; source_entity = "end"; type = "b_range_start"; } else { entity_i = 0; source_entity = "start"; type = "range_end_b"; } target_entity = source_entity === "end" ? "start" : "end"; ref = entity.passages[passage_i][target_entity]; for (key in ref) { if (!hasProp.call(ref, key)) continue; entity.passages[passage_i][target_entity][key] = entity.passages[passage_i][source_entity][key]; } if (entity.type === "sequence") { if (passage_i >= entity.value.length) { passage_i = entity.value.length - 1; } pluck = this.passage.pluck(type, entity.value[passage_i]); if (pluck != null) { temp = this.snap_range(pluck, 0); if (passage_i === 0) { entity.absolute_indices[0] = temp.absolute_indices[0]; } else { entity.absolute_indices[1] = temp.absolute_indices[1]; } } } else { entity.original_type = entity.type; entity.type = entity.value[entity_i].type; entity.absolute_indices = [entity.value[entity_i].absolute_indices[0], entity.value[entity_i].absolute_indices[1]]; } return entity; }; bcv_parser.prototype.snap_sequence = function(type, entity, osises, i, length) { var passage; passage = entity.passages[i]; if (passage.absolute_indices[0] === entity.absolute_indices[0] && i < length - 1 && this.get_snap_sequence_i(entity.passages, i, length) !== i) { entity.absolute_indices[0] = entity.passages[i + 1].absolute_indices[0]; this.remove_absolute_indices(entity.passages, i + 1); } else if (passage.absolute_indices[1] === entity.absolute_indices[1] && i > 0) { entity.absolute_indices[1] = osises.length > 0 ? osises[osises.length - 1].indices[1] : entity.passages[i - 1].absolute_indices[1]; } else if (type === "book" && i < length - 1 && !this.starts_with_book(entity.passages[i + 1])) { entity.passages[i + 1].absolute_indices[0] = passage.absolute_indices[0]; } return entity; }; bcv_parser.prototype.get_snap_sequence_i = function(passages, i, length) { var j, k, ref, ref1; for (j = k = ref = i + 1, ref1 = length; ref <= ref1 ? k < ref1 : k > ref1; j = ref <= ref1 ? ++k : --k) { if (this.starts_with_book(passages[j])) { return j; } if (passages[j].valid.valid) { return i; } } return i; }; bcv_parser.prototype.starts_with_book = function(passage) { if (passage.type.substr(0, 1) === "b") { return true; } if ((passage.type === "range" || passage.type === "ff") && passage.start.type.substr(0, 1) === "b") { return true; } return false; }; bcv_parser.prototype.remove_absolute_indices = function(passages, i) { var end, k, len, passage, ref, ref1, start; if (passages[i].enclosed_absolute_indices[0] < 0) { return false; } ref = passages[i].enclosed_absolute_indices, start = ref[0], end = ref[1]; ref1 = passages.slice(i); for (k = 0, len = ref1.length; k < len; k++) { passage = ref1[k]; if (passage.enclosed_absolute_indices[0] === start && passage.enclosed_absolute_indices[1] === end) { passage.enclosed_absolute_indices = [-1, -1]; } else { break; } } return true; }; return bcv_parser; })(); root.bcv_parser = bcv_parser; bcv_passage = (function() { function bcv_passage() {} bcv_passage.prototype.books = []; bcv_passage.prototype.indices = {}; bcv_passage.prototype.options = {}; bcv_passage.prototype.translations = {}; bcv_passage.prototype.handle_array = function(passages, accum, context) { var k, len, passage, ref; if (accum == null) { accum = []; } if (context == null) { context = {}; } for (k = 0, len = passages.length; k < len; k++) { passage = passages[k]; if (passage == null) { continue; } if (passage.type === "stop") { break; } ref = this.handle_obj(passage, accum, context), accum = ref[0], context = ref[1]; } return [accum, context]; }; bcv_passage.prototype.handle_obj = function(passage, accum, context) { if ((passage.type != null) && (this[passage.type] != null)) { return this[passage.type](passage, accum, context); } else { return [accum, context]; } }; bcv_passage.prototype.b = function(passage, accum, context) { var alternates, b, k, len, obj, ref, valid; passage.start_context = bcv_utils.shallow_clone(context); passage.passages = []; alternates = []; ref = this.books[passage.value].parsed; for (k = 0, len = ref.length; k < len; k++) { b = ref[k]; valid = this.validate_ref(passage.start_context.translations, { b: b }); obj = { start: { b: b }, end: { b: b }, valid: valid }; if (passage.passages.length === 0 && valid.valid) { passage.passages.push(obj); } else { alternates.push(obj); } } if (passage.passages.length === 0) { passage.passages.push(alternates.shift()); } if (alternates.length > 0) { passage.passages[0].alternates = alternates; } if (passage.start_context.translations != null) { passage.passages[0].translations = passage.start_context.translations; } if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } accum.push(passage); context = { b: passage.passages[0].start.b }; if (passage.start_context.translations != null) { context.translations = passage.start_context.translations; } return [accum, context]; }; bcv_passage.prototype.b_range = function(passage, accum, context) { return this.range(passage, accum, context); }; bcv_passage.prototype.b_range_pre = function(passage, accum, context) { var alternates, book, end, ref, ref1, start_obj; passage.start_context = bcv_utils.shallow_clone(context); passage.passages = []; alternates = []; book = this.pluck("b", passage.value); ref = this.b(book, [], context), (ref1 = ref[0], end = ref1[0]), context = ref[1]; if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } start_obj = { b: passage.value[0].value + end.passages[0].start.b.substr(1), type: "b" }; passage.passages = [ { start: start_obj, end: end.passages[0].end, valid: end.passages[0].valid } ]; if (passage.start_context.translations != null) { passage.passages[0].translations = passage.start_context.translations; } accum.push(passage); return [accum, context]; }; bcv_passage.prototype.b_range_start = function(passage, accum, context) { return this.range(passage, accum, context); }; bcv_passage.prototype.base = function(passage, accum, context) { this.indices = this.calculate_indices(passage.match, passage.start_index); return this.handle_array(passage.value, accum, context); }; bcv_passage.prototype.bc = function(passage, accum, context) { var alternates, b, c, context_key, k, len, obj, ref, ref1, valid; passage.start_context = bcv_utils.shallow_clone(context); passage.passages = []; this.reset_context(context, ["b", "c", "v"]); c = this.pluck("c", passage.value).value; alternates = []; ref = this.books[this.pluck("b", passage.value).value].parsed; for (k = 0, len = ref.length; k < len; k++) { b = ref[k]; context_key = "c"; valid = this.validate_ref(passage.start_context.translations, { b: b, c: c }); obj = { start: { b: b }, end: { b: b }, valid: valid }; if (valid.messages.start_chapter_not_exist_in_single_chapter_book) { obj.valid = this.validate_ref(passage.start_context.translations, { b: b, v: c }); obj.valid.messages.start_chapter_not_exist_in_single_chapter_book = 1; obj.start.c = 1; obj.end.c = 1; context_key = "v"; } obj.start[context_key] = c; ref1 = this.fix_start_zeroes(obj.valid, obj.start.c, obj.start.v), obj.start.c = ref1[0], obj.start.v = ref1[1]; if (obj.start.v == null) { delete obj.start.v; } obj.end[context_key] = obj.start[context_key]; if (passage.passages.length === 0 && obj.valid.valid) { passage.passages.push(obj); } else { alternates.push(obj); } } if (passage.passages.length === 0) { passage.passages.push(alternates.shift()); } if (alternates.length > 0) { passage.passages[0].alternates = alternates; } if (passage.start_context.translations != null) { passage.passages[0].translations = passage.start_context.translations; } if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } this.set_context_from_object(context, ["b", "c", "v"], passage.passages[0].start); accum.push(passage); return [accum, context]; }; bcv_passage.prototype.bc_title = function(passage, accum, context) { var bc, i, k, ref, ref1, ref2, title; passage.start_context = bcv_utils.shallow_clone(context); ref = this.bc(this.pluck("bc", passage.value), [], context), (ref1 = ref[0], bc = ref1[0]), context = ref[1]; if (bc.passages[0].start.b.substr(0, 2) !== "Ps" && (bc.passages[0].alternates != null)) { for (i = k = 0, ref2 = bc.passages[0].alternates.length; 0 <= ref2 ? k < ref2 : k > ref2; i = 0 <= ref2 ? ++k : --k) { if (bc.passages[0].alternates[i].start.b.substr(0, 2) !== "Ps") { continue; } bc.passages[0] = bc.passages[0].alternates[i]; break; } } if (bc.passages[0].start.b.substr(0, 2) !== "Ps") { accum.push(bc); return [accum, context]; } this.books[this.pluck("b", bc.value).value].parsed = ["Ps"]; title = this.pluck("title", passage.value); if (title == null) { title = this.pluck("v", passage.value); } passage.value[1] = { type: "v", value: [ { type: "integer", value: 1, indices: title.indices } ], indices: title.indices }; passage.type = "bcv"; return this.bcv(passage, accum, passage.start_context); }; bcv_passage.prototype.bcv = function(passage, accum, context) { var alternates, b, bc, c, k, len, obj, ref, ref1, v, valid; passage.start_context = bcv_utils.shallow_clone(context); passage.passages = []; this.reset_context(context, ["b", "c", "v"]); bc = this.pluck("bc", passage.value); c = this.pluck("c", bc.value).value; v = this.pluck("v", passage.value).value; alternates = []; ref = this.books[this.pluck("b", bc.value).value].parsed; for (k = 0, len = ref.length; k < len; k++) { b = ref[k]; valid = this.validate_ref(passage.start_context.translations, { b: b, c: c, v: v }); ref1 = this.fix_start_zeroes(valid, c, v), c = ref1[0], v = ref1[1]; obj = { start: { b: b, c: c, v: v }, end: { b: b, c: c, v: v }, valid: valid }; if (passage.passages.length === 0 && valid.valid) { passage.passages.push(obj); } else { alternates.push(obj); } } if (passage.passages.length === 0) { passage.passages.push(alternates.shift()); } if (alternates.length > 0) { passage.passages[0].alternates = alternates; } if (passage.start_context.translations != null) { passage.passages[0].translations = passage.start_context.translations; } if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } this.set_context_from_object(context, ["b", "c", "v"], passage.passages[0].start); accum.push(passage); return [accum, context]; }; bcv_passage.prototype.bv = function(passage, accum, context) { var b, bcv, ref, ref1, ref2, v; passage.start_context = bcv_utils.shallow_clone(context); ref = passage.value, b = ref[0], v = ref[1]; bcv = { indices: passage.indices, value: [ { type: "bc", value: [ b, { type: "c", value: [ { type: "integer", value: 1 } ] } ] }, v ] }; ref1 = this.bcv(bcv, [], context), (ref2 = ref1[0], bcv = ref2[0]), context = ref1[1]; passage.passages = bcv.passages; if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } accum.push(passage); return [accum, context]; }; bcv_passage.prototype.c = function(passage, accum, context) { var c, valid; passage.start_context = bcv_utils.shallow_clone(context); c = passage.type === "integer" ? passage.value : this.pluck("integer", passage.value).value; valid = this.validate_ref(passage.start_context.translations, { b: context.b, c: c }); if (!valid.valid && valid.messages.start_chapter_not_exist_in_single_chapter_book) { return this.v(passage, accum, context); } c = this.fix_start_zeroes(valid, c)[0]; passage.passages = [ { start: { b: context.b, c: c }, end: { b: context.b, c: c }, valid: valid } ]; if (passage.start_context.translations != null) { passage.passages[0].translations = passage.start_context.translations; } accum.push(passage); context.c = c; this.reset_context(context, ["v"]); if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } return [accum, context]; }; bcv_passage.prototype.c_psalm = function(passage, accum, context) { var c; passage.type = "bc"; c = parseInt(this.books[passage.value].value.match(/^\d+/)[0], 10); passage.value = [ { type: "b", value: passage.value, indices: passage.indices }, { type: "c", value: [ { type: "integer", value: c, indices: passage.indices } ], indices: passage.indices } ]; return this.bc(passage, accum, context); }; bcv_passage.prototype.c_title = function(passage, accum, context) { var title; passage.start_context = bcv_utils.shallow_clone(context); if (context.b !== "Ps") { return this.c(passage.value[0], accum, context); } title = this.pluck("title", passage.value); passage.value[1] = { type: "v", value: [ { type: "integer", value: 1, indices: title.indices } ], indices: title.indices }; passage.type = "cv"; return this.cv(passage, accum, passage.start_context); }; bcv_passage.prototype.cv = function(passage, accum, context) { var c, ref, v, valid; passage.start_context = bcv_utils.shallow_clone(context); c = this.pluck("c", passage.value).value; v = this.pluck("v", passage.value).value; valid = this.validate_ref(passage.start_context.translations, { b: context.b, c: c, v: v }); ref = this.fix_start_zeroes(valid, c, v), c = ref[0], v = ref[1]; passage.passages = [ { start: { b: context.b, c: c, v: v }, end: { b: context.b, c: c, v: v }, valid: valid } ]; if (passage.start_context.translations != null) { passage.passages[0].translations = passage.start_context.translations; } accum.push(passage); context.c = c; context.v = v; if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } return [accum, context]; }; bcv_passage.prototype.cb_range = function(passage, accum, context) { var b, end_c, ref, start_c; passage.type = "range"; ref = passage.value, b = ref[0], start_c = ref[1], end_c = ref[2]; passage.value = [ { type: "bc", value: [b, start_c], indices: passage.indices }, end_c ]; end_c.indices[1] = passage.indices[1]; return this.range(passage, accum, context); }; bcv_passage.prototype.context = function(passage, accum, context) { var key, ref; passage.start_context = bcv_utils.shallow_clone(context); passage.passages = []; ref = this.books[passage.value].context; for (key in ref) { if (!hasProp.call(ref, key)) continue; context[key] = this.books[passage.value].context[key]; } accum.push(passage); return [accum, context]; }; bcv_passage.prototype.cv_psalm = function(passage, accum, context) { var bc, c_psalm, ref, v; passage.start_context = bcv_utils.shallow_clone(context); passage.type = "bcv"; ref = passage.value, c_psalm = ref[0], v = ref[1]; bc = this.c_psalm(c_psalm, [], passage.start_context)[0][0]; passage.value = [bc, v]; return this.bcv(passage, accum, context); }; bcv_passage.prototype.ff = function(passage, accum, context) { var ref, ref1; passage.start_context = bcv_utils.shallow_clone(context); passage.value.push({ type: "integer", indices: passage.indices, value: 999 }); ref = this.range(passage, [], passage.start_context), (ref1 = ref[0], passage = ref1[0]), context = ref[1]; passage.value[0].indices = passage.value[1].indices; passage.value[0].absolute_indices = passage.value[1].absolute_indices; passage.value.pop(); if (passage.passages[0].valid.messages.end_verse_not_exist != null) { delete passage.passages[0].valid.messages.end_verse_not_exist; } if (passage.passages[0].valid.messages.end_chapter_not_exist != null) { delete passage.passages[0].valid.messages.end_chapter_not_exist; } if (passage.passages[0].end.original_c != null) { delete passage.passages[0].end.original_c; } accum.push(passage); return [accum, context]; }; bcv_passage.prototype.integer_title = function(passage, accum, context) { var v_indices; passage.start_context = bcv_utils.shallow_clone(context); if (context.b !== "Ps") { return this.integer(passage.value[0], accum, context); } passage.value[0] = { type: "c", value: [passage.value[0]], indices: [passage.value[0].indices[0], passage.value[0].indices[1]] }; v_indices = [passage.indices[1] - 5, passage.indices[1]]; passage.value[1] = { type: "v", value: [ { type: "integer", value: 1, indices: v_indices } ], indices: v_indices }; passage.type = "cv"; return this.cv(passage, accum, passage.start_context); }; bcv_passage.prototype.integer = function(passage, accum, context) { if (context.v != null) { return this.v(passage, accum, context); } return this.c(passage, accum, context); }; bcv_passage.prototype.sequence = function(passage, accum, context) { var k, l, len, len1, obj, psg, ref, ref1, ref2, ref3, sub_psg; passage.start_context = bcv_utils.shallow_clone(context); passage.passages = []; ref = passage.value; for (k = 0, len = ref.length; k < len; k++) { obj = ref[k]; ref1 = this.handle_array(obj, [], context), (ref2 = ref1[0], psg = ref2[0]), context = ref1[1]; ref3 = psg.passages; for (l = 0, len1 = ref3.length; l < len1; l++) { sub_psg = ref3[l]; if (sub_psg.type == null) { sub_psg.type = psg.type; } if (sub_psg.absolute_indices == null) { sub_psg.absolute_indices = psg.absolute_indices; } if (psg.start_context.translations != null) { sub_psg.translations = psg.start_context.translations; } sub_psg.enclosed_absolute_indices = psg.type === "sequence_post_enclosed" ? psg.absolute_indices : [-1, -1]; passage.passages.push(sub_psg); } } if (passage.absolute_indices == null) { if (passage.passages.length > 0 && passage.type === "sequence") { passage.absolute_indices = [passage.passages[0].absolute_indices[0], passage.passages[passage.passages.length - 1].absolute_indices[1]]; } else { passage.absolute_indices = this.get_absolute_indices(passage.indices); } } accum.push(passage); return [accum, context]; }; bcv_passage.prototype.sequence_post_enclosed = function(passage, accum, context) { return this.sequence(passage, accum, context); }; bcv_passage.prototype.v = function(passage, accum, context) { var c, no_c, ref, v, valid; v = passage.type === "integer" ? passage.value : this.pluck("integer", passage.value).value; passage.start_context = bcv_utils.shallow_clone(context); c = context.c != null ? context.c : 1; valid = this.validate_ref(passage.start_context.translations, { b: context.b, c: c, v: v }); ref = this.fix_start_zeroes(valid, 0, v), no_c = ref[0], v = ref[1]; passage.passages = [ { start: { b: context.b, c: c, v: v }, end: { b: context.b, c: c, v: v }, valid: valid } ]; if (passage.start_context.translations != null) { passage.passages[0].translations = passage.start_context.translations; } if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } accum.push(passage); context.v = v; return [accum, context]; }; bcv_passage.prototype.range = function(passage, accum, context) { var end, end_obj, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, return_now, return_value, start, start_obj, valid; passage.start_context = bcv_utils.shallow_clone(context); ref = passage.value, start = ref[0], end = ref[1]; ref1 = this.handle_obj(start, [], context), (ref2 = ref1[0], start = ref2[0]), context = ref1[1]; if (end.type === "v" && ((start.type === "bc" && !((ref3 = start.passages) != null ? (ref4 = ref3[0]) != null ? (ref5 = ref4.valid) != null ? (ref6 = ref5.messages) != null ? ref6.start_chapter_not_exist_in_single_chapter_book : void 0 : void 0 : void 0 : void 0)) || start.type === "c") && this.options.end_range_digits_strategy === "verse") { passage.value[0] = start; return this.range_change_integer_end(passage, accum); } ref7 = this.handle_obj(end, [], context), (ref8 = ref7[0], end = ref8[0]), context = ref7[1]; passage.value = [start, end]; passage.indices = [start.indices[0], end.indices[1]]; delete passage.absolute_indices; start_obj = { b: start.passages[0].start.b, c: start.passages[0].start.c, v: start.passages[0].start.v, type: start.type }; end_obj = { b: end.passages[0].end.b, c: end.passages[0].end.c, v: end.passages[0].end.v, type: end.type }; if (end.passages[0].valid.messages.start_chapter_is_zero) { end_obj.c = 0; } if (end.passages[0].valid.messages.start_verse_is_zero) { end_obj.v = 0; } valid = this.validate_ref(passage.start_context.translations, start_obj, end_obj); if (valid.valid) { ref9 = this.range_handle_valid(valid, passage, start, start_obj, end, end_obj, accum), return_now = ref9[0], return_value = ref9[1]; if (return_now) { return return_value; } } else { return this.range_handle_invalid(valid, passage, start, start_obj, end, end_obj, accum); } if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } passage.passages = [ { start: start_obj, end: end_obj, valid: valid } ]; if (passage.start_context.translations != null) { passage.passages[0].translations = passage.start_context.translations; } if (start_obj.type === "b") { if (end_obj.type === "b") { passage.type = "b_range"; } else { passage.type = "b_range_start"; } } else if (end_obj.type === "b") { passage.type = "range_end_b"; } accum.push(passage); return [accum, context]; }; bcv_passage.prototype.range_change_end = function(passage, accum, new_end) { var end, new_obj, ref, start; ref = passage.value, start = ref[0], end = ref[1]; if (end.type === "integer") { end.original_value = end.value; end.value = new_end; } else if (end.type === "v") { new_obj = this.pluck("integer", end.value); new_obj.original_value = new_obj.value; new_obj.value = new_end; } else if (end.type === "cv") { new_obj = this.pluck("c", end.value); new_obj.original_value = new_obj.value; new_obj.value = new_end; } return this.handle_obj(passage, accum, passage.start_context); }; bcv_passage.prototype.range_change_integer_end = function(passage, accum) { var end, ref, start; ref = passage.value, start = ref[0], end = ref[1]; if (passage.original_type == null) { passage.original_type = passage.type; } if (passage.original_value == null) { passage.original_value = [start, end]; } passage.type = start.type === "integer" ? "cv" : start.type + "v"; if (start.type === "integer") { passage.value[0] = { type: "c", value: [start], indices: start.indices }; } if (end.type === "integer") { passage.value[1] = { type: "v", value: [end], indices: end.indices }; } return this.handle_obj(passage, accum, passage.start_context); }; bcv_passage.prototype.range_check_new_end = function(translations, start_obj, end_obj, valid) { var new_end, new_valid, obj_to_validate, type; new_end = 0; type = null; if (valid.messages.end_chapter_before_start) { type = "c"; } else if (valid.messages.end_verse_before_start) { type = "v"; } if (type != null) { new_end = this.range_get_new_end_value(start_obj, end_obj, valid, type); } if (new_end > 0) { obj_to_validate = { b: end_obj.b, c: end_obj.c, v: end_obj.v }; obj_to_validate[type] = new_end; new_valid = this.validate_ref(translations, obj_to_validate); if (!new_valid.valid) { new_end = 0; } } return new_end; }; bcv_passage.prototype.range_end_b = function(passage, accum, context) { return this.range(passage, accum, context); }; bcv_passage.prototype.range_get_new_end_value = function(start_obj, end_obj, valid, key) { var new_end; new_end = 0; if ((key === "c" && valid.messages.end_chapter_is_zero) || (key === "v" && valid.messages.end_verse_is_zero)) { return new_end; } if (start_obj[key] >= 10 && end_obj[key] < 10 && start_obj[key] - 10 * Math.floor(start_obj[key] / 10) < end_obj[key]) { new_end = end_obj[key] + 10 * Math.floor(start_obj[key] / 10); } else if (start_obj[key] >= 100 && end_obj[key] < 100 && start_obj[key] - 100 < end_obj[key]) { new_end = end_obj[key] + 100; } return new_end; }; bcv_passage.prototype.range_handle_invalid = function(valid, passage, start, start_obj, end, end_obj, accum) { var new_end, ref, temp_valid, temp_value; if (valid.valid === false && (valid.messages.end_chapter_before_start || valid.messages.end_verse_before_start) && (end.type === "integer" || end.type === "v") || (valid.valid === false && valid.messages.end_chapter_before_start && end.type === "cv")) { new_end = this.range_check_new_end(passage.start_context.translations, start_obj, end_obj, valid); if (new_end > 0) { return this.range_change_end(passage, accum, new_end); } } if (this.options.end_range_digits_strategy === "verse" && (start_obj.v == null) && (end.type === "integer" || end.type === "v")) { temp_value = end.type === "v" ? this.pluck("integer", end.value) : end.value; temp_valid = this.validate_ref(passage.start_context.translations, { b: start_obj.b, c: start_obj.c, v: temp_value }); if (temp_valid.valid) { return this.range_change_integer_end(passage, accum); } } if (passage.original_type == null) { passage.original_type = passage.type; } passage.type = "sequence"; ref = [[start, end], [[start], [end]]], passage.original_value = ref[0], passage.value = ref[1]; return this.sequence(passage, accum, passage.start_context); }; bcv_passage.prototype.range_handle_valid = function(valid, passage, start, start_obj, end, end_obj, accum) { var temp_valid, temp_value; if (valid.messages.end_chapter_not_exist && this.options.end_range_digits_strategy === "verse" && (start_obj.v == null) && (end.type === "integer" || end.type === "v") && this.options.passage_existence_strategy.indexOf("v") >= 0) { temp_value = end.type === "v" ? this.pluck("integer", end.value) : end.value; temp_valid = this.validate_ref(passage.start_context.translations, { b: start_obj.b, c: start_obj.c, v: temp_value }); if (temp_valid.valid) { return [true, this.range_change_integer_end(passage, accum)]; } } this.range_validate(valid, start_obj, end_obj, passage); return [false, null]; }; bcv_passage.prototype.range_validate = function(valid, start_obj, end_obj, passage) { var ref; if (valid.messages.end_chapter_not_exist || valid.messages.end_chapter_not_exist_in_single_chapter_book) { end_obj.original_c = end_obj.c; end_obj.c = valid.messages.end_chapter_not_exist ? valid.messages.end_chapter_not_exist : valid.messages.end_chapter_not_exist_in_single_chapter_book; if (end_obj.v != null) { end_obj.v = this.validate_ref(passage.start_context.translations, { b: end_obj.b, c: end_obj.c, v: 999 }).messages.end_verse_not_exist; delete valid.messages.end_verse_is_zero; } } else if (valid.messages.end_verse_not_exist) { end_obj.original_v = end_obj.v; end_obj.v = valid.messages.end_verse_not_exist; } if (valid.messages.end_verse_is_zero && this.options.zero_verse_strategy !== "allow") { end_obj.v = valid.messages.end_verse_is_zero; } if (valid.messages.end_chapter_is_zero) { end_obj.c = valid.messages.end_chapter_is_zero; } ref = this.fix_start_zeroes(valid, start_obj.c, start_obj.v), start_obj.c = ref[0], start_obj.v = ref[1]; return true; }; bcv_passage.prototype.translation_sequence = function(passage, accum, context) { var k, l, len, len1, ref, translation, translations, val; passage.start_context = bcv_utils.shallow_clone(context); translations = []; translations.push({ translation: this.books[passage.value[0].value].parsed }); ref = passage.value[1]; for (k = 0, len = ref.length; k < len; k++) { val = ref[k]; val = this.books[this.pluck("translation", val).value].parsed; if (val != null) { translations.push({ translation: val }); } } for (l = 0, len1 = translations.length; l < len1; l++) { translation = translations[l]; if (this.translations.aliases[translation.translation] != null) { translation.alias = this.translations.aliases[translation.translation].alias; translation.osis = this.translations.aliases[translation.translation].osis || ""; } else { translation.alias = "default"; translation.osis = translation.translation.toUpperCase(); } } if (accum.length > 0) { context = this.translation_sequence_apply(accum, translations); } if (passage.absolute_indices == null) { passage.absolute_indices = this.get_absolute_indices(passage.indices); } accum.push(passage); this.reset_context(context, ["translations"]); return [accum, context]; }; bcv_passage.prototype.translation_sequence_apply = function(accum, translations) { var context, i, k, new_accum, ref, ref1, use_i; use_i = 0; for (i = k = ref = accum.length - 1; ref <= 0 ? k <= 0 : k >= 0; i = ref <= 0 ? ++k : --k) { if (accum[i].original_type != null) { accum[i].type = accum[i].original_type; } if (accum[i].original_value != null) { accum[i].value = accum[i].original_value; } if (accum[i].type !== "translation_sequence") { continue; } use_i = i + 1; break; } if (use_i < accum.length) { accum[use_i].start_context.translations = translations; ref1 = this.handle_array(accum.slice(use_i), [], accum[use_i].start_context), new_accum = ref1[0], context = ref1[1]; } else { context = bcv_utils.shallow_clone(accum[accum.length - 1].start_context); } return context; }; bcv_passage.prototype.pluck = function(type, passages) { var k, len, passage; for (k = 0, len = passages.length; k < len; k++) { passage = passages[k]; if (!((passage != null) && (passage.type != null) && passage.type === type)) { continue; } if (type === "c" || type === "v") { return this.pluck("integer", passage.value); } return passage; } return null; }; bcv_passage.prototype.set_context_from_object = function(context, keys, obj) { var k, len, results, type; results = []; for (k = 0, len = keys.length; k < len; k++) { type = keys[k]; if (obj[type] == null) { continue; } results.push(context[type] = obj[type]); } return results; }; bcv_passage.prototype.reset_context = function(context, keys) { var k, len, results, type; results = []; for (k = 0, len = keys.length; k < len; k++) { type = keys[k]; results.push(delete context[type]); } return results; }; bcv_passage.prototype.fix_start_zeroes = function(valid, c, v) { if (valid.messages.start_chapter_is_zero && this.options.zero_chapter_strategy === "upgrade") { c = valid.messages.start_chapter_is_zero; } if (valid.messages.start_verse_is_zero && this.options.zero_verse_strategy === "upgrade") { v = valid.messages.start_verse_is_zero; } return [c, v]; }; bcv_passage.prototype.calculate_indices = function(match, adjust) { var character, end_index, indices, k, l, len, len1, len2, m, match_index, part, part_length, parts, ref, switch_type, temp; switch_type = "book"; indices = []; match_index = 0; adjust = parseInt(adjust, 10); parts = [match]; ref = ["\x1e", "\x1f"]; for (k = 0, len = ref.length; k < len; k++) { character = ref[k]; temp = []; for (l = 0, len1 = parts.length; l < len1; l++) { part = parts[l]; temp = temp.concat(part.split(character)); } parts = temp; } for (m = 0, len2 = parts.length; m < len2; m++) { part = parts[m]; switch_type = switch_type === "book" ? "rest" : "book"; part_length = part.length; if (part_length === 0) { continue; } if (switch_type === "book") { part = part.replace(/\/\d+$/, ""); end_index = match_index + part_length; if (indices.length > 0 && indices[indices.length - 1].index === adjust) { indices[indices.length - 1].end = end_index; } else { indices.push({ start: match_index, end: end_index, index: adjust }); } match_index += part_length + 2; adjust = this.books[part].start_index + this.books[part].value.length - match_index; indices.push({ start: end_index + 1, end: end_index + 1, index: adjust }); } else { end_index = match_index + part_length - 1; if (indices.length > 0 && indices[indices.length - 1].index === adjust) { indices[indices.length - 1].end = end_index; } else { indices.push({ start: match_index, end: end_index, index: adjust }); } match_index += part_length; } } return indices; }; bcv_passage.prototype.get_absolute_indices = function(arg1) { var end, end_out, index, k, len, ref, start, start_out; start = arg1[0], end = arg1[1]; start_out = null; end_out = null; ref = this.indices; for (k = 0, len = ref.length; k < len; k++) { index = ref[k]; if (start_out === null && (index.start <= start && start <= index.end)) { start_out = start + index.index; } if ((index.start <= end && end <= index.end)) { end_out = end + index.index + 1; break; } } return [start_out, end_out]; }; bcv_passage.prototype.validate_ref = function(translations, start, end) { var k, len, messages, temp_valid, translation, valid; if (!((translations != null) && translations.length > 0)) { translations = [ { translation: "default", osis: "", alias: "default" } ]; } valid = false; messages = {}; for (k = 0, len = translations.length; k < len; k++) { translation = translations[k]; if (translation.alias == null) { translation.alias = "default"; } if (translation.alias == null) { if (messages.translation_invalid == null) { messages.translation_invalid = []; } messages.translation_invalid.push(translation); continue; } if (this.translations.aliases[translation.alias] == null) { translation.alias = "default"; if (messages.translation_unknown == null) { messages.translation_unknown = []; } messages.translation_unknown.push(translation); } temp_valid = this.validate_start_ref(translation.alias, start, messages)[0]; if (end) { temp_valid = this.validate_end_ref(translation.alias, start, end, temp_valid, messages)[0]; } if (temp_valid === true) { valid = true; } } return { valid: valid, messages: messages }; }; bcv_passage.prototype.validate_start_ref = function(translation, start, messages) { var ref, ref1, translation_order, valid; valid = true; if (translation !== "default" && (((ref = this.translations[translation]) != null ? ref.chapters[start.b] : void 0) == null)) { this.promote_book_to_translation(start.b, translation); } translation_order = ((ref1 = this.translations[translation]) != null ? ref1.order : void 0) != null ? translation : "default"; if (start.v != null) { start.v = parseInt(start.v, 10); } if (this.translations[translation_order].order[start.b] != null) { if (start.c == null) { start.c = 1; } start.c = parseInt(start.c, 10); if (isNaN(start.c)) { valid = false; messages.start_chapter_not_numeric = true; return [valid, messages]; } if (start.c === 0) { messages.start_chapter_is_zero = 1; if (this.options.zero_chapter_strategy === "error") { valid = false; } else { start.c = 1; } } if ((start.v != null) && start.v === 0) { messages.start_verse_is_zero = 1; if (this.options.zero_verse_strategy === "error") { valid = false; } else if (this.options.zero_verse_strategy === "upgrade") { start.v = 1; } } if (start.c > 0 && (this.translations[translation].chapters[start.b][start.c - 1] != null)) { if (start.v != null) { if (isNaN(start.v)) { valid = false; messages.start_verse_not_numeric = true; } else if (start.v > this.translations[translation].chapters[start.b][start.c - 1]) { if (this.options.passage_existence_strategy.indexOf("v") >= 0) { valid = false; messages.start_verse_not_exist = this.translations[translation].chapters[start.b][start.c - 1]; } } } } else { if (start.c !== 1 && this.translations[translation].chapters[start.b].length === 1) { valid = false; messages.start_chapter_not_exist_in_single_chapter_book = 1; } else if (start.c > 0 && this.options.passage_existence_strategy.indexOf("c") >= 0) { valid = false; messages.start_chapter_not_exist = this.translations[translation].chapters[start.b].length; } } } else { if (this.options.passage_existence_strategy.indexOf("b") >= 0) { valid = false; } messages.start_book_not_exist = true; } return [valid, messages]; }; bcv_passage.prototype.validate_end_ref = function(translation, start, end, valid, messages) { var ref, translation_order; translation_order = ((ref = this.translations[translation]) != null ? ref.order : void 0) != null ? translation : "default"; if (end.c != null) { end.c = parseInt(end.c, 10); if (isNaN(end.c)) { valid = false; messages.end_chapter_not_numeric = true; } else if (end.c === 0) { messages.end_chapter_is_zero = 1; if (this.options.zero_chapter_strategy === "error") { valid = false; } else { end.c = 1; } } } if (end.v != null) { end.v = parseInt(end.v, 10); if (isNaN(end.v)) { valid = false; messages.end_verse_not_numeric = true; } else if (end.v === 0) { messages.end_verse_is_zero = 1; if (this.options.zero_verse_strategy === "error") { valid = false; } else if (this.options.zero_verse_strategy === "upgrade") { end.v = 1; } } } if (this.translations[translation_order].order[end.b] != null) { if ((end.c == null) && this.translations[translation].chapters[end.b].length === 1) { end.c = 1; } if ((this.translations[translation_order].order[start.b] != null) && this.translations[translation_order].order[start.b] > this.translations[translation_order].order[end.b]) { if (this.options.passage_existence_strategy.indexOf("b") >= 0) { valid = false; } messages.end_book_before_start = true; } if (start.b === end.b && (end.c != null) && !isNaN(end.c)) { if (start.c == null) { start.c = 1; } if (!isNaN(parseInt(start.c, 10)) && start.c > end.c) { valid = false; messages.end_chapter_before_start = true; } else if (start.c === end.c && (end.v != null) && !isNaN(end.v)) { if (start.v == null) { start.v = 1; } if (!isNaN(parseInt(start.v, 10)) && start.v > end.v) { valid = false; messages.end_verse_before_start = true; } } } if ((end.c != null) && !isNaN(end.c)) { if (this.translations[translation].chapters[end.b][end.c - 1] == null) { if (this.translations[translation].chapters[end.b].length === 1) { messages.end_chapter_not_exist_in_single_chapter_book = 1; } else if (end.c > 0 && this.options.passage_existence_strategy.indexOf("c") >= 0) { messages.end_chapter_not_exist = this.translations[translation].chapters[end.b].length; } } } if ((end.v != null) && !isNaN(end.v)) { if (end.c == null) { end.c = this.translations[translation].chapters[end.b].length; } if (end.v > this.translations[translation].chapters[end.b][end.c - 1] && this.options.passage_existence_strategy.indexOf("v") >= 0) { messages.end_verse_not_exist = this.translations[translation].chapters[end.b][end.c - 1]; } } } else { valid = false; messages.end_book_not_exist = true; } return [valid, messages]; }; bcv_passage.prototype.promote_book_to_translation = function(book, translation) { var base, base1; if ((base = this.translations)[translation] == null) { base[translation] = {}; } if ((base1 = this.translations[translation]).chapters == null) { base1.chapters = {}; } if (this.translations[translation].chapters[book] == null) { return this.translations[translation].chapters[book] = bcv_utils.shallow_clone_array(this.translations["default"].chapters[book]); } }; return bcv_passage; })(); bcv_utils = { shallow_clone: function(obj) { var key, out, val; if (obj == null) { return obj; } out = {}; for (key in obj) { if (!hasProp.call(obj, key)) continue; val = obj[key]; out[key] = val; } return out; }, shallow_clone_array: function(arr) { var i, k, out, ref; if (arr == null) { return arr; } out = []; for (i = k = 0, ref = arr.length; 0 <= ref ? k <= ref : k >= ref; i = 0 <= ref ? ++k : --k) { if (typeof arr[i] !== "undefined") { out[i] = arr[i]; } } return out; } }; bcv_parser.prototype.regexps.translations = /(?:ERV)\b/gi; bcv_parser.prototype.translations = { aliases: { "default": { osis: "", alias: "default" } }, alternates: {}, "default": { order: { "Gen": 1, "Exod": 2, "Lev": 3, "Num": 4, "Deut": 5, "Josh": 6, "Judg": 7, "Ruth": 8, "1Sam": 9, "2Sam": 10, "1Kgs": 11, "2Kgs": 12, "1Chr": 13, "2Chr": 14, "Ezra": 15, "Neh": 16, "Esth": 17, "Job": 18, "Ps": 19, "Prov": 20, "Eccl": 21, "Song": 22, "Isa": 23, "Jer": 24, "Lam": 25, "Ezek": 26, "Dan": 27, "Hos": 28, "Joel": 29, "Amos": 30, "Obad": 31, "Jonah": 32, "Mic": 33, "Nah": 34, "Hab": 35, "Zeph": 36, "Hag": 37, "Zech": 38, "Mal": 39, "Matt": 40, "Mark": 41, "Luke": 42, "John": 43, "Acts": 44, "Rom": 45, "1Cor": 46, "2Cor": 47, "Gal": 48, "Eph": 49, "Phil": 50, "Col": 51, "1Thess": 52, "2Thess": 53, "1Tim": 54, "2Tim": 55, "Titus": 56, "Phlm": 57, "Heb": 58, "Jas": 59, "1Pet": 60, "2Pet": 61, "1John": 62, "2John": 63, "3John": 64, "Jude": 65, "Rev": 66, "Tob": 67, "Jdt": 68, "GkEsth": 69, "Wis": 70, "Sir": 71, "Bar": 72, "PrAzar": 73, "Sus": 74, "Bel": 75, "SgThree": 76, "EpJer": 77, "1Macc": 78, "2Macc": 79, "3Macc": 80, "4Macc": 81, "1Esd": 82, "2Esd": 83, "PrMan": 84 }, chapters: { "Gen": [31, 25, 24, 26, 32, 22, 24, 22, 29, 32, 32, 20, 18, 24, 21, 16, 27, 33, 38, 18, 34, 24, 20, 67, 34, 35, 46, 22, 35, 43, 55, 32, 20, 31, 29, 43, 36, 30, 23, 23, 57, 38, 34, 34, 28, 34, 31, 22, 33, 26], "Exod": [22, 25, 22, 31, 23, 30, 25, 32, 35, 29, 10, 51, 22, 31, 27, 36, 16, 27, 25, 26, 36, 31, 33, 18, 40, 37, 21, 43, 46, 38, 18, 35, 23, 35, 35, 38, 29, 31, 43, 38], "Lev": [17, 16, 17, 35, 19, 30, 38, 36, 24, 20, 47, 8, 59, 57, 33, 34, 16, 30, 37, 27, 24, 33, 44, 23, 55, 46, 34], "Num": [54, 34, 51, 49, 31, 27, 89, 26, 23, 36, 35, 16, 33, 45, 41, 50, 13, 32, 22, 29, 35, 41, 30, 25, 18, 65, 23, 31, 40, 16, 54, 42, 56, 29, 34, 13], "Deut": [46, 37, 29, 49, 33, 25, 26, 20, 29, 22, 32, 32, 18, 29, 23, 22, 20, 22, 21, 20, 23, 30, 25, 22, 19, 19, 26, 68, 29, 20, 30, 52, 29, 12], "Josh": [18, 24, 17, 24, 15, 27, 26, 35, 27, 43, 23, 24, 33, 15, 63, 10, 18, 28, 51, 9, 45, 34, 16, 33], "Judg": [36, 23, 31, 24, 31, 40, 25, 35, 57, 18, 40, 15, 25, 20, 20, 31, 13, 31, 30, 48, 25], "Ruth": [22, 23, 18, 22], "1Sam": [28, 36, 21, 22, 12, 21, 17, 22, 27, 27, 15, 25, 23, 52, 35, 23, 58, 30, 24, 42, 15, 23, 29, 22, 44, 25, 12, 25, 11, 31, 13], "2Sam": [27, 32, 39, 12, 25, 23, 29, 18, 13, 19, 27, 31, 39, 33, 37, 23, 29, 33, 43, 26, 22, 51, 39, 25], "1Kgs": [53, 46, 28, 34, 18, 38, 51, 66, 28, 29, 43, 33, 34, 31, 34, 34, 24, 46, 21, 43, 29, 53], "2Kgs": [18, 25, 27, 44, 27, 33, 20, 29, 37, 36, 21, 21, 25, 29, 38, 20, 41, 37, 37, 21, 26, 20, 37, 20, 30], "1Chr": [54, 55, 24, 43, 26, 81, 40, 40, 44, 14, 47, 40, 14, 17, 29, 43, 27, 17, 19, 8, 30, 19, 32, 31, 31, 32, 34, 21, 30], "2Chr": [17, 18, 17, 22, 14, 42, 22, 18, 31, 19, 23, 16, 22, 15, 19, 14, 19, 34, 11, 37, 20, 12, 21, 27, 28, 23, 9, 27, 36, 27, 21, 33, 25, 33, 27, 23], "Ezra": [11, 70, 13, 24, 17, 22, 28, 36, 15, 44], "Neh": [11, 20, 32, 23, 19, 19, 73, 18, 38, 39, 36, 47, 31], "Esth": [22, 23, 15, 17, 14, 14, 10, 17, 32, 3], "Job": [22, 13, 26, 21, 27, 30, 21, 22, 35, 22, 20, 25, 28, 22, 35, 22, 16, 21, 29, 29, 34, 30, 17, 25, 6, 14, 23, 28, 25, 31, 40, 22, 33, 37, 16, 33, 24, 41, 30, 24, 34, 17], "Ps": [6, 12, 8, 8, 12, 10, 17, 9, 20, 18, 7, 8, 6, 7, 5, 11, 15, 50, 14, 9, 13, 31, 6, 10, 22, 12, 14, 9, 11, 12, 24, 11, 22, 22, 28, 12, 40, 22, 13, 17, 13, 11, 5, 26, 17, 11, 9, 14, 20, 23, 19, 9, 6, 7, 23, 13, 11, 11, 17, 12, 8, 12, 11, 10, 13, 20, 7, 35, 36, 5, 24, 20, 28, 23, 10, 12, 20, 72, 13, 19, 16, 8, 18, 12, 13, 17, 7, 18, 52, 17, 16, 15, 5, 23, 11, 13, 12, 9, 9, 5, 8, 28, 22, 35, 45, 48, 43, 13, 31, 7, 10, 10, 9, 8, 18, 19, 2, 29, 176, 7, 8, 9, 4, 8, 5, 6, 5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 13, 10, 7, 12, 15, 21, 10, 20, 14, 9, 6], "Prov": [33, 22, 35, 27, 23, 35, 27, 36, 18, 32, 31, 28, 25, 35, 33, 33, 28, 24, 29, 30, 31, 29, 35, 34, 28, 28, 27, 28, 27, 33, 31], "Eccl": [18, 26, 22, 16, 20, 12, 29, 17, 18, 20, 10, 14], "Song": [17, 17, 11, 16, 16, 13, 13, 14], "Isa": [31, 22, 26, 6, 30, 13, 25, 22, 21, 34, 16, 6, 22, 32, 9, 14, 14, 7, 25, 6, 17, 25, 18, 23, 12, 21, 13, 29, 24, 33, 9, 20, 24, 17, 10, 22, 38, 22, 8, 31, 29, 25, 28, 28, 25, 13, 15, 22, 26, 11, 23, 15, 12, 17, 13, 12, 21, 14, 21, 22, 11, 12, 19, 12, 25, 24], "Jer": [19, 37, 25, 31, 31, 30, 34, 22, 26, 25, 23, 17, 27, 22, 21, 21, 27, 23, 15, 18, 14, 30, 40, 10, 38, 24, 22, 17, 32, 24, 40, 44, 26, 22, 19, 32, 21, 28, 18, 16, 18, 22, 13, 30, 5, 28, 7, 47, 39, 46, 64, 34], "Lam": [22, 22, 66, 22, 22], "Ezek": [28, 10, 27, 17, 17, 14, 27, 18, 11, 22, 25, 28, 23, 23, 8, 63, 24, 32, 14, 49, 32, 31, 49, 27, 17, 21, 36, 26, 21, 26, 18, 32, 33, 31, 15, 38, 28, 23, 29, 49, 26, 20, 27, 31, 25, 24, 23, 35], "Dan": [21, 49, 30, 37, 31, 28, 28, 27, 27, 21, 45, 13], "Hos": [11, 23, 5, 19, 15, 11, 16, 14, 17, 15, 12, 14, 16, 9], "Joel": [20, 32, 21], "Amos": [15, 16, 15, 13, 27, 14, 17, 14, 15], "Obad": [21], "Jonah": [17, 10, 10, 11], "Mic": [16, 13, 12, 13, 15, 16, 20], "Nah": [15, 13, 19], "Hab": [17, 20, 19], "Zeph": [18, 15, 20], "Hag": [15, 23], "Zech": [21, 13, 10, 14, 11, 15, 14, 23, 17, 12, 17, 14, 9, 21], "Mal": [14, 17, 18, 6], "Matt": [25, 23, 17, 25, 48, 34, 29, 34, 38, 42, 30, 50, 58, 36, 39, 28, 27, 35, 30, 34, 46, 46, 39, 51, 46, 75, 66, 20], "Mark": [45, 28, 35, 41, 43, 56, 37, 38, 50, 52, 33, 44, 37, 72, 47, 20], "Luke": [80, 52, 38, 44, 39, 49, 50, 56, 62, 42, 54, 59, 35, 35, 32, 31, 37, 43, 48, 47, 38, 71, 56, 53], "John": [51, 25, 36, 54, 47, 71, 53, 59, 41, 42, 57, 50, 38, 31, 27, 33, 26, 40, 42, 31, 25], "Acts": [26, 47, 26, 37, 42, 15, 60, 40, 43, 48, 30, 25, 52, 28, 41, 40, 34, 28, 41, 38, 40, 30, 35, 27, 27, 32, 44, 31], "Rom": [32, 29, 31, 25, 21, 23, 25, 39, 33, 21, 36, 21, 14, 23, 33, 27], "1Cor": [31, 16, 23, 21, 13, 20, 40, 13, 27, 33, 34, 31, 13, 40, 58, 24], "2Cor": [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 14], "Gal": [24, 21, 29, 31, 26, 18], "Eph": [23, 22, 21, 32, 33, 24], "Phil": [30, 30, 21, 23], "Col": [29, 23, 25, 18], "1Thess": [10, 20, 13, 18, 28], "2Thess": [12, 17, 18], "1Tim": [20, 15, 16, 16, 25, 21], "2Tim": [18, 26, 17, 22], "Titus": [16, 15, 15], "Phlm": [25], "Heb": [14, 18, 19, 16, 14, 20, 28, 13, 28, 39, 40, 29, 25], "Jas": [27, 26, 18, 17, 20], "1Pet": [25, 25, 22, 19, 14], "2Pet": [21, 22, 18], "1John": [10, 29, 24, 21, 21], "2John": [13], "3John": [15], "Jude": [25], "Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 17, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21], "Tob": [22, 14, 17, 21, 22, 18, 16, 21, 6, 13, 18, 22, 17, 15], "Jdt": [16, 28, 10, 15, 24, 21, 32, 36, 14, 23, 23, 20, 20, 19, 14, 25], "GkEsth": [22, 23, 15, 17, 14, 14, 10, 17, 32, 13, 12, 6, 18, 19, 16, 24], "Wis": [16, 24, 19, 20, 23, 25, 30, 21, 18, 21, 26, 27, 19, 31, 19, 29, 21, 25, 22], "Sir": [30, 18, 31, 31, 15, 37, 36, 19, 18, 31, 34, 18, 26, 27, 20, 30, 32, 33, 30, 31, 28, 27, 27, 34, 26, 29, 30, 26, 28, 25, 31, 24, 33, 31, 26, 31, 31, 34, 35, 30, 22, 25, 33, 23, 26, 20, 25, 25, 16, 29, 30], "Bar": [22, 35, 37, 37, 9], "PrAzar": [68], "Sus": [64], "Bel": [42], "SgThree": [39], "EpJer": [73], "1Macc": [64, 70, 60, 61, 68, 63, 50, 32, 73, 89, 74, 53, 53, 49, 41, 24], "2Macc": [36, 32, 40, 50, 27, 31, 42, 36, 29, 38, 38, 45, 26, 46, 39], "3Macc": [29, 33, 30, 21, 51, 41, 23], "4Macc": [35, 24, 21, 26, 38, 35, 23, 29, 32, 21, 27, 19, 27, 20, 32, 25, 24, 24], "1Esd": [58, 30, 24, 63, 73, 34, 15, 96, 55], "2Esd": [40, 48, 36, 52, 56, 59, 70, 63, 47, 59, 46, 51, 58, 48, 63, 78], "PrMan": [15], "Ps151": [7] } }, vulgate: { chapters: { "Ps": [6, 13, 9, 10, 13, 11, 18, 10, 39, 8, 9, 6, 7, 5, 10, 15, 51, 15, 10, 14, 32, 6, 10, 22, 12, 14, 9, 11, 13, 25, 11, 22, 23, 28, 13, 40, 23, 14, 18, 14, 12, 5, 26, 18, 12, 10, 15, 21, 23, 21, 11, 7, 9, 24, 13, 12, 12, 18, 14, 9, 13, 12, 11, 14, 20, 8, 36, 37, 6, 24, 20, 28, 23, 11, 13, 21, 72, 13, 20, 17, 8, 19, 13, 14, 17, 7, 19, 53, 17, 16, 16, 5, 23, 11, 13, 12, 9, 9, 5, 8, 29, 22, 35, 45, 48, 43, 14, 31, 7, 10, 10, 9, 26, 9, 19, 2, 29, 176, 7, 8, 9, 4, 8, 5, 6, 5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 14, 10, 8, 12, 15, 21, 10, 11, 20, 14, 9, 7] } }, ceb: { chapters: { "2Cor": [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 13], "Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 18, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21], "Tob": [22, 14, 17, 21, 22, 18, 16, 21, 6, 13, 18, 22, 18, 15], "PrAzar": [67], "EpJer": [72], "1Esd": [55, 26, 24, 63, 71, 33, 15, 92, 55] } }, kjv: { chapters: { "3John": [14] } }, nab: { order: { "Gen": 1, "Exod": 2, "Lev": 3, "Num": 4, "Deut": 5, "Josh": 6, "Judg": 7, "Ruth": 8, "1Sam": 9, "2Sam": 10, "1Kgs": 11, "2Kgs": 12, "1Chr": 13, "2Chr": 14, "PrMan": 15, "Ezra": 16, "Neh": 17, "1Esd": 18, "2Esd": 19, "Tob": 20, "Jdt": 21, "Esth": 22, "GkEsth": 23, "1Macc": 24, "2Macc": 25, "3Macc": 26, "4Macc": 27, "Job": 28, "Ps": 29, "Prov": 30, "Eccl": 31, "Song": 32, "Wis": 33, "Sir": 34, "Isa": 35, "Jer": 36, "Lam": 37, "Bar": 38, "EpJer": 39, "Ezek": 40, "Dan": 41, "PrAzar": 42, "Sus": 43, "Bel": 44, "SgThree": 45, "Hos": 46, "Joel": 47, "Amos": 48, "Obad": 49, "Jonah": 50, "Mic": 51, "Nah": 52, "Hab": 53, "Zeph": 54, "Hag": 55, "Zech": 56, "Mal": 57, "Matt": 58, "Mark": 59, "Luke": 60, "John": 61, "Acts": 62, "Rom": 63, "1Cor": 64, "2Cor": 65, "Gal": 66, "Eph": 67, "Phil": 68, "Col": 69, "1Thess": 70, "2Thess": 71, "1Tim": 72, "2Tim": 73, "Titus": 74, "Phlm": 75, "Heb": 76, "Jas": 77, "1Pet": 78, "2Pet": 79, "1John": 80, "2John": 81, "3John": 82, "Jude": 83, "Rev": 84 }, chapters: { "Gen": [31, 25, 24, 26, 32, 22, 24, 22, 29, 32, 32, 20, 18, 24, 21, 16, 27, 33, 38, 18, 34, 24, 20, 67, 34, 35, 46, 22, 35, 43, 54, 33, 20, 31, 29, 43, 36, 30, 23, 23, 57, 38, 34, 34, 28, 34, 31, 22, 33, 26], "Exod": [22, 25, 22, 31, 23, 30, 29, 28, 35, 29, 10, 51, 22, 31, 27, 36, 16, 27, 25, 26, 37, 30, 33, 18, 40, 37, 21, 43, 46, 38, 18, 35, 23, 35, 35, 38, 29, 31, 43, 38], "Lev": [17, 16, 17, 35, 26, 23, 38, 36, 24, 20, 47, 8, 59, 57, 33, 34, 16, 30, 37, 27, 24, 33, 44, 23, 55, 46, 34], "Num": [54, 34, 51, 49, 31, 27, 89, 26, 23, 36, 35, 16, 33, 45, 41, 35, 28, 32, 22, 29, 35, 41, 30, 25, 19, 65, 23, 31, 39, 17, 54, 42, 56, 29, 34, 13], "Deut": [46, 37, 29, 49, 33, 25, 26, 20, 29, 22, 32, 31, 19, 29, 23, 22, 20, 22, 21, 20, 23, 29, 26, 22, 19, 19, 26, 69, 28, 20, 30, 52, 29, 12], "1Sam": [28, 36, 21, 22, 12, 21, 17, 22, 27, 27, 15, 25, 23, 52, 35, 23, 58, 30, 24, 42, 16, 23, 28, 23, 44, 25, 12, 25, 11, 31, 13], "2Sam": [27, 32, 39, 12, 25, 23, 29, 18, 13, 19, 27, 31, 39, 33, 37, 23, 29, 32, 44, 26, 22, 51, 39, 25], "1Kgs": [53, 46, 28, 20, 32, 38, 51, 66, 28, 29, 43, 33, 34, 31, 34, 34, 24, 46, 21, 43, 29, 54], "2Kgs": [18, 25, 27, 44, 27, 33, 20, 29, 37, 36, 20, 22, 25, 29, 38, 20, 41, 37, 37, 21, 26, 20, 37, 20, 30], "1Chr": [54, 55, 24, 43, 41, 66, 40, 40, 44, 14, 47, 41, 14, 17, 29, 43, 27, 17, 19, 8, 30, 19, 32, 31, 31, 32, 34, 21, 30], "2Chr": [18, 17, 17, 22, 14, 42, 22, 18, 31, 19, 23, 16, 23, 14, 19, 14, 19, 34, 11, 37, 20, 12, 21, 27, 28, 23, 9, 27, 36, 27, 21, 33, 25, 33, 27, 23], "Neh": [11, 20, 38, 17, 19, 19, 72, 18, 37, 40, 36, 47, 31], "Job": [22, 13, 26, 21, 27, 30, 21, 22, 35, 22, 20, 25, 28, 22, 35, 22, 16, 21, 29, 29, 34, 30, 17, 25, 6, 14, 23, 28, 25, 31, 40, 22, 33, 37, 16, 33, 24, 41, 30, 32, 26, 17], "Ps": [6, 11, 9, 9, 13, 11, 18, 10, 21, 18, 7, 9, 6, 7, 5, 11, 15, 51, 15, 10, 14, 32, 6, 10, 22, 12, 14, 9, 11, 13, 25, 11, 22, 23, 28, 13, 40, 23, 14, 18, 14, 12, 5, 27, 18, 12, 10, 15, 21, 23, 21, 11, 7, 9, 24, 14, 12, 12, 18, 14, 9, 13, 12, 11, 14, 20, 8, 36, 37, 6, 24, 20, 28, 23, 11, 13, 21, 72, 13, 20, 17, 8, 19, 13, 14, 17, 7, 19, 53, 17, 16, 16, 5, 23, 11, 13, 12, 9, 9, 5, 8, 29, 22, 35, 45, 48, 43, 14, 31, 7, 10, 10, 9, 8, 18, 19, 2, 29, 176, 7, 8, 9, 4, 8, 5, 6, 5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 14, 10, 8, 12, 15, 21, 10, 20, 14, 9, 6], "Eccl": [18, 26, 22, 17, 19, 12, 29, 17, 18, 20, 10, 14], "Song": [17, 17, 11, 16, 16, 12, 14, 14], "Isa": [31, 22, 26, 6, 30, 13, 25, 23, 20, 34, 16, 6, 22, 32, 9, 14, 14, 7, 25, 6, 17, 25, 18, 23, 12, 21, 13, 29, 24, 33, 9, 20, 24, 17, 10, 22, 38, 22, 8, 31, 29, 25, 28, 28, 25, 13, 15, 22, 26, 11, 23, 15, 12, 17, 13, 12, 21, 14, 21, 22, 11, 12, 19, 11, 25, 24], "Jer": [19, 37, 25, 31, 31, 30, 34, 23, 25, 25, 23, 17, 27, 22, 21, 21, 27, 23, 15, 18, 14, 30, 40, 10, 38, 24, 22, 17, 32, 24, 40, 44, 26, 22, 19, 32, 21, 28, 18, 16, 18, 22, 13, 30, 5, 28, 7, 47, 39, 46, 64, 34], "Ezek": [28, 10, 27, 17, 17, 14, 27, 18, 11, 22, 25, 28, 23, 23, 8, 63, 24, 32, 14, 44, 37, 31, 49, 27, 17, 21, 36, 26, 21, 26, 18, 32, 33, 31, 15, 38, 28, 23, 29, 49, 26, 20, 27, 31, 25, 24, 23, 35], "Dan": [21, 49, 100, 34, 30, 29, 28, 27, 27, 21, 45, 13, 64, 42], "Hos": [9, 25, 5, 19, 15, 11, 16, 14, 17, 15, 11, 15, 15, 10], "Joel": [20, 27, 5, 21], "Jonah": [16, 11, 10, 11], "Mic": [16, 13, 12, 14, 14, 16, 20], "Nah": [14, 14, 19], "Zech": [17, 17, 10, 14, 11, 15, 14, 23, 17, 12, 17, 14, 9, 21], "Mal": [14, 17, 24], "Acts": [26, 47, 26, 37, 42, 15, 60, 40, 43, 49, 30, 25, 52, 28, 41, 40, 34, 28, 40, 38, 40, 30, 35, 27, 27, 32, 44, 31], "2Cor": [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 13], "Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 18, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21], "Tob": [22, 14, 17, 21, 22, 18, 17, 21, 6, 13, 18, 22, 18, 15], "Sir": [30, 18, 31, 31, 15, 37, 36, 19, 18, 31, 34, 18, 26, 27, 20, 30, 32, 33, 30, 31, 28, 27, 27, 33, 26, 29, 30, 26, 28, 25, 31, 24, 33, 31, 26, 31, 31, 34, 35, 30, 22, 25, 33, 23, 26, 20, 25, 25, 16, 29, 30], "Bar": [22, 35, 38, 37, 9, 72], "2Macc": [36, 32, 40, 50, 27, 31, 42, 36, 29, 38, 38, 46, 26, 46, 39] } }, nlt: { chapters: { "Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 18, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21] } }, nrsv: { chapters: { "2Cor": [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 13], "Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 18, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21] } } }; bcv_parser.prototype.regexps.space = "[\\s\\xa0]"; bcv_parser.prototype.regexps.escaped_passage = /(?:^|[^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:(?:ch(?:apters?|a?pts?\.?|a?p?s?\.?)?\s*\d+\s*(?:[\u2013\u2014\-]|through|thru|to)\s*\d+\s*(?:from|of|in)(?:\s+the\s+book\s+of)?\s*)|(?:ch(?:apters?|a?pts?\.?|a?p?s?\.?)?\s*\d+\s*(?:from|of|in)(?:\s+the\s+book\s+of)?\s*)|(?:\d+(?:th|nd|st)\s*ch(?:apter|a?pt\.?|a?p?\.?)?\s*(?:from|of|in)(?:\s+the\s+book\s+of)?\s*))?\x1f(\d+)(?:\/\d+)?\x1f(?:\/\d+\x1f|[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014]|title(?![a-z])|chapter|verse|and|ff|to|[a-e](?!\w)|$)+)/gi; bcv_parser.prototype.regexps.match_end_split = /\d\W*title|\d\W*ff(?:[\s\xa0*]*\.)?|\d[\s\xa0*]*[a-e](?!\w)|\x1e(?:[\s\xa0*]*[)\]\uff09])?|[\d\x1f]/gi; bcv_parser.prototype.regexps.control = /[\x1e\x1f]/g; bcv_parser.prototype.regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ]"; bcv_parser.prototype.regexps.first = "(?:पहिल|1)\\.?" + bcv_parser.prototype.regexps.space + "*"; bcv_parser.prototype.regexps.second = "(?:दुसरे|2)\\.?" + bcv_parser.prototype.regexps.space + "*"; bcv_parser.prototype.regexps.third = "(?:तिसरे|3)\\.?" + bcv_parser.prototype.regexps.space + "*"; bcv_parser.prototype.regexps.range_and = "(?:[&\u2013\u2014-]|and|to)"; bcv_parser.prototype.regexps.range_only = "(?:[\u2013\u2014-]|to)"; bcv_parser.prototype.regexps.get_books = function(include_apocrypha, case_sensitive) { var book, books, k, len, out; books = [ { osis: ["Ps"], apocrypha: true, extra: "2", regexp: /(\b)(Ps151)(?=\.1)/g }, { osis: ["Gen"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:utpatti|उत्पत(?:्ति|ि)|Gen))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Exod"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:nirgam|निर्गम|Exod))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Bel"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Bel)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Lev"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:lew[iī]y|लेवीय|Lev))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Num"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:ga[nṇ]an[aā]|गणना|Num))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Sir"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Sir)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Wis"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Wis)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Lam"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:wil[aā]pg(?:[iī]t)|विलापगीत|Lam))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["EpJer"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(EpJer)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Rev"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:yoh[aā]n(?:[aā]l(?:[aā][\\s\\xa0]*dzʰ(?:[aā]lele[\\s\\xa0]*praka(?:[tṭ](?:[iī]kara[nṇ])))))|योहानाला[\\s\\xa0]*झालेले[\\s\\xa0]*प्रकटीकरण|Rev)|(?:praka[ṭt](?:[īi]kara[nṇ])|प्रकटीकरण))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["PrMan"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(PrMan)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Deut"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:anuw[aā]d|अनुवाद|Deut))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Josh"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:yaho[sŝ]aw[aā]|यहोशवा|Josh))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Judg"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:शास्ते|[sŝ](?:[aā]ste)|Judg))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Ruth"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Ruth|r[uū]tʰ|रूथ))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["1Esd"], apocrypha: true, regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])(1Esd)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["2Esd"], apocrypha: true, regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])(2Esd)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["Isa"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:ya[sŝ]ay[aā]|यश(?:या|ाय)|Isa))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["2Sam"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:दुसरे[\s\xa0]*शमुवेल|2(?:[\s\xa0]*(?:[sŝ]amuwel|शमुवेल)|Sam)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["1Sam"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पहिले[\s\xa0]*शमुवेल|1(?:[\s\xa0]*(?:[sŝ]amuwel|शमुवेल)|Sam)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["2Kgs"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:दुसरे[\s\xa0]*राजे|2(?:[\s\xa0]*(?:r[aā]dze|राजे)|Kgs)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["1Kgs"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पहिले[\s\xa0]*राजे|1(?:[\s\xa0]*(?:r[aā]dze|राजे)|Kgs)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["2Chr"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:दुसरे[\s\xa0]*इतिहास|2(?:[\s\xa0]*(?:itih[aā]s|इतिहास)|Chr)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["1Chr"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पहिले[\s\xa0]*इतिहास|1(?:[\s\xa0]*(?:itih[aā]s|इतिहास)|Chr)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["Ezra"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:एज्रा|Ezra|e(?:dzr[aā]|dzr[aā])))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Neh"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:nahemy[aā]|नहेम्या|Neh))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["GkEsth"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(GkEsth)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Esth"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:एस्तेर|ester|Esth))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Job"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:[iī]yob|[इई]योब|Job))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Ps"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:stotrasa[mṃ]hit[aā]|स्त(?:्रोत्रसंहिता|ोत्र(?:संहिता)?)|Ps))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["PrAzar"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(PrAzar)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Prov"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:नीतिसूत्रें?|n[iī]tis(?:[uū]tre)|Prov))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Eccl"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:upade[sŝ]ak|उपदेशक|Eccl))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["SgThree"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(SgThree)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Song"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:g[iī]tratna|गीतरत्न|Song))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Jer"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:yirmay[aā]|यिर्मया|Jer))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Ezek"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:yahe(?:dzkel|dzkel)|यहेज्केल|Ezek))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Dan"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:d[aā]n(?:[iī]el)|दानीएल(?:्र)?|Dan))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Hos"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:ho[sŝ]ey|होशेय|Hos))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Joel"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:[Jy]oel|योएल))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Amos"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:[Aaā]mos|[अआ]मोस))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Obad"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:obadʰ[aā]|Obad|ओब(?:द्या|धा)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Jonah"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Jonah|yon[aā]|योना))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Mic"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:m[iī]kʰ[aā]|मीखा|Mic))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Nah"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:nah[uū]m|नहूम|Nah))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Hab"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:habakk[uū]k|हबक्कूक?|Hab))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Zeph"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:sapʰany[aā]|सफन्या|Zeph))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Hag"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:h[aā]ggay|हाग्गय|Hag))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Zech"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:jakʰary[aā]|जख[रऱ]्या|Zech))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Mal"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:mal[aā]kʰ[iī]|मलाखी|Mal))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Matt"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(mattay[aā]ne[\\s\\xa0]*lihilele[\\s\\xa0]*(?:[sŝ]ubʰavartam(?:[aā]n))|(?:mattay[aā]ne|मत्तय(?:ाने(?:[\\s\\xa0]*लिहिलेले[\\s\\xa0]*शुभवर्तमान)?)?|Matt))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Mark"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:m[aā]rk(?:[aā]ne[\\s\\xa0]*lihilele[\\s\\xa0]*(?:[sŝ]ubʰavartam(?:[aā]n)))|मार्क(?:ाने[\\s\\xa0]*लिहिलेले[\\s\\xa0]*शुभवर्तमान)?|Mark)|(?:मार्काने|m[āa]rk(?:[aā]ne)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Luke"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:l[uū]k(?:[aā]ne[\\s\\xa0]*lihilele[\\s\\xa0]*(?:[sŝ]ubʰavartam(?:[aā]n)))|Luke|लूक(?:ा(?:ने[\\s\\xa0]*लिहिलेले[\\s\\xa0]*शुभवर्तमान)?)?)|(?:l[uū]k(?:[aā]ne)|लूकाने))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["1John"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:yoh[aā]n(?:[aā]ce(?:[mṃ][\s\xa0]*pahile[\s\xa0]*patra))|योहानाचें[\s\xa0]*पहिले[\s\xa0]*पत्र|1(?:[\s\xa0]*(?:yoh[aā]n(?:[aā]ce[mṃ])|योहान(?:ाच)?)|John)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["2John"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:yoh[aā]n(?:[aā]ce(?:[mṃ][\s\xa0]*dusre[\s\xa0]*patra))|योहानाचें[\s\xa0]*दुसरे[\s\xa0]*पत्र|2(?:[\s\xa0]*(?:yoh[aā]n(?:[aā]ce[mṃ])|योहान(?:ाच)?)|John)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["3John"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:yoh[aā]n(?:[aā]ce(?:[mṃ][\s\xa0]*tisre[\s\xa0]*patra))|योहानाचें[\s\xa0]*तिसरे[\s\xa0]*पत्र|3(?:[\s\xa0]*(?:yoh[aā]n(?:[aā]ce[mṃ])|योहान(?:ाच)?)|John)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["John"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:yoh[aā]n(?:[aā]ne[\\s\\xa0]*lihilele[\\s\\xa0]*(?:[sŝ]ubʰavartam(?:[aā]n)))|योहान(?:ाने[\\s\\xa0]*लिहिलेले[\\s\\xa0]*शुभवर्तमान)?|John)|(?:योहानाने|yoh[āa]n(?:[aā]ne)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Acts"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:pre[sš]it(?:[aā](?:[mṃ]c(?:[iī](?:[mṃ][\\s\\xa0]*kr̥tye[mṃ]))))|प्रेषितांची(?:[\\s\\xa0]*कृत्यें|ं[\\s\\xa0]*कृत्यें?)|Acts))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Rom"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:पौलाचे[\\s\\xa0]*रोमकरांस[\\s\\xa0]*पत्र|romkar(?:[aā](?:[mṃ]s(?:[\\s\\xa0]*patra)?))|रोमक(?:ंरास|रांस(?:[\\s\\xa0]*पत्र)?)|Rom))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["2Cor"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पौलाचे[\s\xa0]*करिंथकरांस[\s\xa0]*दूसरे[\s\xa0]*पत्र|kari[mṃ]tʰkar(?:[aā](?:[mṃ]s[\s\xa0]*dusre[\s\xa0]*patra))|करिंथकरांस[\s\xa0]*दुसरे[\s\xa0]*पत्र|2(?:[\s\xa0]*(?:kari[mṃ]tʰkar(?:[aā](?:[mṃ]s))|करिंथकरांस)|Cor)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["1Cor"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पौलाचे[\s\xa0]*करिंथकरांस[\s\xa0]*पहिले[\s\xa0]*पत्र|kari[mṃ]tʰkar(?:[aā](?:[mṃ]s[\s\xa0]*pahile[\s\xa0]*patra))|करिंथकरांस[\s\xa0]*पहिले[\s\xa0]*पत्र|1(?:[\s\xa0]*(?:kari[mṃ]tʰkar(?:[aā](?:[mṃ]s))|करिंथकरांस)|Cor)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["Gal"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:पौलाचे[\\s\\xa0]*गलतीकरांस[\\s\\xa0]*पत्र|galat(?:[iī]kar(?:[aā](?:[mṃ]s(?:[\\s\\xa0]*patra)?)))|गलतीकरांस(?:[\\s\\xa0]*पत्र)?|Gal))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Eph"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:पौलाचे[\\s\\xa0]*इफिसकरांस[\\s\\xa0]*पत्र|ipʰiskar(?:[aā](?:[mṃ]s(?:[\\s\\xa0]*patra)?))|इफिसकरांस(?:[\\s\\xa0]*पत्र)?|Eph))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Phil"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:पौलाचे[\\s\\xa0]*फिलिप्पैकरांस[\\s\\xa0]*पत्र|pʰilippaikar(?:[aā](?:[mṃ]s(?:[\\s\\xa0]*patra)?))|फिलिप्पैकरांस(?:[\\s\\xa0]*पत्र)?|Phil))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Col"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:पौलाचे[\\s\\xa0]*कलस्सैकरांस[\\s\\xa0]*पत्र|kalassaikar(?:[aā](?:[mṃ]s(?:[\\s\\xa0]*patra)?))|कलस(?:्सैकरांस(?:[\\s\\xa0]*पत्र)?|ैकरांस)|Col))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["2Thess"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पौलाचे[\s\xa0]*थेस्सलनीकाकरांस[\s\xa0]*दुसरे[\s\xa0]*पत्र|tʰessalan[iī]k(?:[aā]kar(?:[aā](?:[mṃ]s[\s\xa0]*dusre[\s\xa0]*patra)))|2(?:[\s\xa0]*(?:tʰessalan[iī]k(?:[aā]kar(?:[aā](?:[mṃ]s)))|थेस्सलनीकाकरांस)|Thess))|थेस्सलनीकाकरांस[\s\xa0]*दुसरे[\s\xa0]*पत्र)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["1Thess"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पौलाचे[\s\xa0]*थेस्सलनीकाकरांस[\s\xa0]*पहिले[\s\xa0]*पत्र|tʰessalan[iī]k(?:[aā]kar(?:[aā](?:[mṃ]s[\s\xa0]*pahile[\s\xa0]*patra)))|1(?:[\s\xa0]*(?:tʰessalan[iī]k(?:[aā]kar(?:[aā](?:[mṃ]s)))|थेस्सलनीकाकरांस)|Thess))|थेस्सलनीकाकरांस[\s\xa0]*पहिले[\s\xa0]*पत्र)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["2Tim"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पौलाचे[\s\xa0]*तीमथ्थाला[\s\xa0]*दुसरे[\s\xa0]*पत्र|t[iī]matʰtʰ(?:[aā]l(?:[aā][\s\xa0]*dusre[\s\xa0]*patra))|तीमथ्थाला[\s\xa0]*दुसरे[\s\xa0]*पत्र|2(?:[\s\xa0]*(?:t[iī]matʰtʰ(?:[aā]l[aā])|तीमथ्थाला)|Tim)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["1Tim"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:पौलाचे[\s\xa0]*तीमथ्याला[\s\xa0]*पहिले[\s\xa0]*पत्र|t[iī]matʰtʰ(?:[aā]l(?:[aā][\s\xa0]*pahile[\s\xa0]*patra))|तीमथ्थाला[\s\xa0]*पहिले[\s\xa0]*पत्र|1(?:[\s\xa0]*(?:t[iī]matʰtʰ(?:[aā]l[aā])|तीमथ्[थय]ाला)|Tim)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["Titus"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:पौलाचे[\\s\\xa0]*तीताला[\\s\\xa0]*पत्र|t(?:[iī]t(?:[aā]l(?:[aā](?:[\\s\\xa0]*patra)?)))|तीताला(?:[\\s\\xa0]*पत्र)?|Titus))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Phlm"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:पौलाचे[\\s\\xa0]*फिलेमोनाला[\\s\\xa0]*पत्र|pʰilemon(?:[aā]l(?:[aā](?:[\\s\\xa0]*patra)?))|फिलेमोना(?:ला(?:[\\s\\xa0]*पत्र)?)?|Phlm))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Heb"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:ibr(?:[iī][\\s\\xa0]*lok(?:[aā](?:[mṃ]s(?:[\\s\\xa0]*patra)?)))|इब्री(?:[\\s\\xa0]*लोकांस(?:[\\s\\xa0]*पत्र)?)?|Heb))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Jas"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:y(?:[aā]kob(?:[aā]ce(?:[mṃ](?:[\\s\\xa0]*patra)?)))|याकोब(?:ाचें(?:[\\s\\xa0]*पत्र)?)?|Jas))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["2Pet"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:petr[aā]ce(?:[mṃ][\s\xa0]*dusre[\s\xa0]*patra)|प(?:ेत्राचें[\s\xa0]*दुसरे[\s\xa0]*पत्र|ौलाचें[\s\xa0]*दुसरे[\s\xa0]*पत्र)|2(?:[\s\xa0]*(?:petr[aā]ce[mṃ]|पेत्र(?:ाचें)?)|Pet)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["1Pet"], regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])((?:petr[aā]ce(?:[mṃ][\s\xa0]*pahile[\s\xa0]*patra)|पेत्राचे(?:ं[\s\xa0]*पहिले[\s\xa0]*पत्र|[\s\xa0]*पहिले[\s\xa0]*पत्र)|1(?:[\s\xa0]*(?:petr[aā]ce[mṃ]|पेत्र(?:ाचें)?)|Pet)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["Jude"], regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:yah(?:[uū]d(?:[aā]ce(?:[mṃ](?:[\\s\\xa0]*patra)?)))|यहूदा(?:चें(?:[\\s\\xa0]*पत्र)?)?|Jude))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Tob"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Tob)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Jdt"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Jdt)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Bar"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Bar)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["Sus"], apocrypha: true, regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Sus)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi") }, { osis: ["2Macc"], apocrypha: true, regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])(2Macc)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["3Macc"], apocrypha: true, regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])(3Macc)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["4Macc"], apocrypha: true, regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])(4Macc)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi }, { osis: ["1Macc"], apocrypha: true, regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏऀ-ंऄ-ऺ़-ऽु-ै्ॐ-ॣॱ-ॷॹ-ॿḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ꣠-ꣷꣻ])(1Macc)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi } ]; if (include_apocrypha === true && case_sensitive === "none") { return books; } out = []; for (k = 0, len = books.length; k < len; k++) { book = books[k]; if (include_apocrypha === false && (book.apocrypha != null) && book.apocrypha === true) { continue; } if (case_sensitive === "books") { book.regexp = new RegExp(book.regexp.source, "g"); } out.push(book); } return out; }; bcv_parser.prototype.regexps.books = bcv_parser.prototype.regexps.get_books(false, "none"); var grammar = (function() { /* * Generated by PEG.js 0.8.0. * * http://pegjs.majda.cz/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function SyntaxError(message, expected, found, offset, line, column) { this.message = message; this.expected = expected; this.found = found; this.offset = offset; this.line = line; this.column = column; this.name = "SyntaxError"; } peg$subclass(SyntaxError, Error); function parse(input) { var options = arguments.length > 1 ? arguments[1] : {}, peg$FAILED = {}, peg$startRuleFunctions = { start: peg$parsestart }, peg$startRuleFunction = peg$parsestart, peg$c0 = [], peg$c1 = peg$FAILED, peg$c2 = null, peg$c3 = function(val_1, val_2) { val_2.unshift([val_1]); return {"type": "sequence", "value": val_2, "indices": [offset(), peg$currPos - 1]} }, peg$c4 = "(", peg$c5 = { type: "literal", value: "(", description: "\"(\"" }, peg$c6 = ")", peg$c7 = { type: "literal", value: ")", description: "\")\"" }, peg$c8 = function(val_1, val_2) { if (typeof(val_2) === "undefined") val_2 = []; val_2.unshift([val_1]); return {"type": "sequence_post_enclosed", "value": val_2, "indices": [offset(), peg$currPos - 1]} }, peg$c9 = void 0, peg$c10 = function(val_1, val_2) { if (val_1.length && val_1.length === 2) val_1 = val_1[0]; // for `b`, which returns [object, undefined] return {"type": "range", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c11 = "\x1F", peg$c12 = { type: "literal", value: "\x1F", description: "\"\\x1F\"" }, peg$c13 = "/", peg$c14 = { type: "literal", value: "/", description: "\"/\"" }, peg$c15 = /^[1-8]/, peg$c16 = { type: "class", value: "[1-8]", description: "[1-8]" }, peg$c17 = function(val) { return {"type": "b", "value": val.value, "indices": [offset(), peg$currPos - 1]} }, peg$c18 = function(val_1, val_2) { return {"type": "bc", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c19 = ",", peg$c20 = { type: "literal", value: ",", description: "\",\"" }, peg$c21 = function(val_1, val_2) { return {"type": "bc_title", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c22 = ".", peg$c23 = { type: "literal", value: ".", description: "\".\"" }, peg$c24 = function(val_1, val_2) { return {"type": "bcv", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c25 = "-", peg$c26 = { type: "literal", value: "-", description: "\"-\"" }, peg$c27 = function(val_1, val_2, val_3, val_4) { return {"type": "range", "value": [{"type": "bcv", "value": [{"type": "bc", "value": [val_1, val_2], "indices": [val_1.indices[0], val_2.indices[1]]}, val_3], "indices": [val_1.indices[0], val_3.indices[1]]}, val_4], "indices": [offset(), peg$currPos - 1]} }, peg$c28 = function(val_1, val_2) { return {"type": "bv", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c29 = function(val_1, val_2) { return {"type": "bc", "value": [val_2, val_1], "indices": [offset(), peg$currPos - 1]} }, peg$c30 = function(val_1, val_2, val_3) { return {"type": "cb_range", "value": [val_3, val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c31 = "th", peg$c32 = { type: "literal", value: "th", description: "\"th\"" }, peg$c33 = "nd", peg$c34 = { type: "literal", value: "nd", description: "\"nd\"" }, peg$c35 = "st", peg$c36 = { type: "literal", value: "st", description: "\"st\"" }, peg$c37 = "/1\x1F", peg$c38 = { type: "literal", value: "/1\x1F", description: "\"/1\\x1F\"" }, peg$c39 = function(val) { return {"type": "c_psalm", "value": val.value, "indices": [offset(), peg$currPos - 1]} }, peg$c40 = function(val_1, val_2) { return {"type": "cv_psalm", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c41 = function(val_1, val_2) { return {"type": "c_title", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c42 = function(val_1, val_2) { return {"type": "cv", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} }, peg$c43 = function(val) { return {"type": "c", "value": [val], "indices": [offset(), peg$currPos - 1]} }, peg$c44 = "ff", peg$c45 = { type: "literal", value: "ff", description: "\"ff\"" }, peg$c46 = /^[a-z]/, peg$c47 = { type: "class", value: "[a-z]", description: "[a-z]" }, peg$c48 = function(val_1) { return {"type": "ff", "value": [val_1], "indices": [offset(), peg$currPos - 1]} }, peg$c49 = "title", peg$c50 = { type: "literal", value: "title", description: "\"title\"" }, peg$c51 = function(val_1) { return {"type": "integer_title", "value": [val_1], "indices": [offset(), peg$currPos - 1]} }, peg$c52 = "/9\x1F", peg$c53 = { type: "literal", value: "/9\x1F", description: "\"/9\\x1F\"" }, peg$c54 = function(val) { return {"type": "context", "value": val.value, "indices": [offset(), peg$currPos - 1]} }, peg$c55 = "/2\x1F", peg$c56 = { type: "literal", value: "/2\x1F", description: "\"/2\\x1F\"" }, peg$c57 = ".1", peg$c58 = { type: "literal", value: ".1", description: "\".1\"" }, peg$c59 = /^[0-9]/, peg$c60 = { type: "class", value: "[0-9]", description: "[0-9]" }, peg$c61 = function(val) { return {"type": "bc", "value": [val, {"type": "c", "value": [{"type": "integer", "value": 151, "indices": [peg$currPos - 2, peg$currPos - 1]}], "indices": [peg$currPos - 2, peg$currPos - 1]}], "indices": [offset(), peg$currPos - 1]} }, peg$c62 = function(val_1, val_2) { return {"type": "bcv", "value": [val_1, {"type": "v", "value": [val_2], "indices": [val_2.indices[0], val_2.indices[1]]}], "indices": [offset(), peg$currPos - 1]} }, peg$c63 = /^[a-e]/, peg$c64 = { type: "class", value: "[a-e]", description: "[a-e]" }, peg$c65 = function(val) { return {"type": "v", "value": [val], "indices": [offset(), peg$currPos - 1]} }, peg$c66 = "chapter", peg$c67 = { type: "literal", value: "chapter", description: "\"chapter\"" }, peg$c68 = function() { return {"type": "c_explicit"} }, peg$c69 = "verse", peg$c70 = { type: "literal", value: "verse", description: "\"verse\"" }, peg$c71 = function() { return {"type": "v_explicit"} }, peg$c72 = ":", peg$c73 = { type: "literal", value: ":", description: "\":\"" }, peg$c74 = /^["']/, peg$c75 = { type: "class", value: "[\"']", description: "[\"']" }, peg$c76 = /^[,;\/:&\-\u2013\u2014~]/, peg$c77 = { type: "class", value: "[,;\\/:&\\-\\u2013\\u2014~]", description: "[,;\\/:&\\-\\u2013\\u2014~]" }, peg$c78 = "and", peg$c79 = { type: "literal", value: "and", description: "\"and\"" }, peg$c80 = function() { return "" }, peg$c81 = /^[\-\u2013\u2014]/, peg$c82 = { type: "class", value: "[\\-\\u2013\\u2014]", description: "[\\-\\u2013\\u2014]" }, peg$c83 = "to", peg$c84 = { type: "literal", value: "to", description: "\"to\"" }, peg$c85 = function(val) { return {type:"title", value: [val], "indices": [offset(), peg$currPos - 1]} }, peg$c86 = "from", peg$c87 = { type: "literal", value: "from", description: "\"from\"" }, peg$c88 = "of", peg$c89 = { type: "literal", value: "of", description: "\"of\"" }, peg$c90 = "in", peg$c91 = { type: "literal", value: "in", description: "\"in\"" }, peg$c92 = "the", peg$c93 = { type: "literal", value: "the", description: "\"the\"" }, peg$c94 = "book", peg$c95 = { type: "literal", value: "book", description: "\"book\"" }, peg$c96 = /^[([]/, peg$c97 = { type: "class", value: "[([]", description: "[([]" }, peg$c98 = /^[)\]]/, peg$c99 = { type: "class", value: "[)\\]]", description: "[)\\]]" }, peg$c100 = function(val) { return {"type": "translation_sequence", "value": val, "indices": [offset(), peg$currPos - 1]} }, peg$c101 = "\x1E", peg$c102 = { type: "literal", value: "\x1E", description: "\"\\x1E\"" }, peg$c103 = function(val) { return {"type": "translation", "value": val.value, "indices": [offset(), peg$currPos - 1]} }, peg$c104 = ",000", peg$c105 = { type: "literal", value: ",000", description: "\",000\"" }, peg$c106 = function(val) { return {"type": "integer", "value": parseInt(val.join(""), 10), "indices": [offset(), peg$currPos - 1]} }, peg$c107 = /^[^\x1F\x1E([]/, peg$c108 = { type: "class", value: "[^\\x1F\\x1E([]", description: "[^\\x1F\\x1E([]" }, peg$c109 = function(val) { return {"type": "word", "value": val.join(""), "indices": [offset(), peg$currPos - 1]} }, peg$c110 = function(val) { return {"type": "stop", "value": val, "indices": [offset(), peg$currPos - 1]} }, peg$c111 = /^[\s\xa0*]/, peg$c112 = { type: "class", value: "[\\s\\xa0*]", description: "[\\s\\xa0*]" }, peg$currPos = 0, peg$reportedPos = 0, peg$cachedPos = 0, peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$reportedPos, peg$currPos); } function offset() { return peg$reportedPos; } function line() { return peg$computePosDetails(peg$reportedPos).line; } function column() { return peg$computePosDetails(peg$reportedPos).column; } function expected(description) { throw peg$buildException( null, [{ type: "other", description: description }], peg$reportedPos ); } function error(message) { throw peg$buildException(message, null, peg$reportedPos); } function peg$computePosDetails(pos) { function advance(details, startPos, endPos) { var p, ch; for (p = startPos; p < endPos; p++) { ch = input.charAt(p); if (ch === "\n") { if (!details.seenCR) { details.line++; } details.column = 1; details.seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { details.line++; details.column = 1; details.seenCR = true; } else { details.column++; details.seenCR = false; } } } if (peg$cachedPos !== pos) { if (peg$cachedPos > pos) { peg$cachedPos = 0; peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; } advance(peg$cachedPosDetails, peg$cachedPos, pos); peg$cachedPos = pos; } return peg$cachedPosDetails; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildException(message, expected, pos) { function cleanupExpected(expected) { var i = 1; expected.sort(function(a, b) { if (a.description < b.description) { return -1; } else if (a.description > b.description) { return 1; } else { return 0; } }); while (i < expected.length) { if (expected[i - 1] === expected[i]) { expected.splice(i, 1); } else { i++; } } } function buildMessage(expected, found) { function stringEscape(s) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\x08/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); } var expectedDescs = new Array(expected.length), expectedDesc, foundDesc, i; for (i = 0; i < expected.length; i++) { expectedDescs[i] = expected[i].description; } expectedDesc = expected.length > 1 ? expectedDescs.slice(0, -1).join(", ") + " or " + expectedDescs[expected.length - 1] : expectedDescs[0]; foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; return "Expected " + expectedDesc + " but " + foundDesc + " found."; } var posDetails = peg$computePosDetails(pos), found = pos < input.length ? input.charAt(pos) : null; if (expected !== null) { cleanupExpected(expected); } return new SyntaxError( message !== null ? message : buildMessage(expected, found), expected, found, pos, posDetails.line, posDetails.column ); } function peg$parsestart() { var s0, s1; s0 = []; s1 = peg$parsebcv_hyphen_range(); if (s1 === peg$FAILED) { s1 = peg$parsesequence(); if (s1 === peg$FAILED) { s1 = peg$parsecb_range(); if (s1 === peg$FAILED) { s1 = peg$parserange(); if (s1 === peg$FAILED) { s1 = peg$parseff(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_comma(); if (s1 === peg$FAILED) { s1 = peg$parsebc_title(); if (s1 === peg$FAILED) { s1 = peg$parseps151_bcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_weak(); if (s1 === peg$FAILED) { s1 = peg$parseps151_bc(); if (s1 === peg$FAILED) { s1 = peg$parsebc(); if (s1 === peg$FAILED) { s1 = peg$parsecv_psalm(); if (s1 === peg$FAILED) { s1 = peg$parsebv(); if (s1 === peg$FAILED) { s1 = peg$parsec_psalm(); if (s1 === peg$FAILED) { s1 = peg$parseb(); if (s1 === peg$FAILED) { s1 = peg$parsecbv(); if (s1 === peg$FAILED) { s1 = peg$parsecbv_ordinal(); if (s1 === peg$FAILED) { s1 = peg$parsecb(); if (s1 === peg$FAILED) { s1 = peg$parsecb_ordinal(); if (s1 === peg$FAILED) { s1 = peg$parsetranslation_sequence_enclosed(); if (s1 === peg$FAILED) { s1 = peg$parsetranslation_sequence(); if (s1 === peg$FAILED) { s1 = peg$parsesequence_sep(); if (s1 === peg$FAILED) { s1 = peg$parsec_title(); if (s1 === peg$FAILED) { s1 = peg$parseinteger_title(); if (s1 === peg$FAILED) { s1 = peg$parsecv(); if (s1 === peg$FAILED) { s1 = peg$parsecv_weak(); if (s1 === peg$FAILED) { s1 = peg$parsev_letter(); if (s1 === peg$FAILED) { s1 = peg$parseinteger(); if (s1 === peg$FAILED) { s1 = peg$parsec(); if (s1 === peg$FAILED) { s1 = peg$parsev(); if (s1 === peg$FAILED) { s1 = peg$parseword(); if (s1 === peg$FAILED) { s1 = peg$parseword_parenthesis(); if (s1 === peg$FAILED) { s1 = peg$parsecontext(); } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } if (s1 !== peg$FAILED) { while (s1 !== peg$FAILED) { s0.push(s1); s1 = peg$parsebcv_hyphen_range(); if (s1 === peg$FAILED) { s1 = peg$parsesequence(); if (s1 === peg$FAILED) { s1 = peg$parsecb_range(); if (s1 === peg$FAILED) { s1 = peg$parserange(); if (s1 === peg$FAILED) { s1 = peg$parseff(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_comma(); if (s1 === peg$FAILED) { s1 = peg$parsebc_title(); if (s1 === peg$FAILED) { s1 = peg$parseps151_bcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_weak(); if (s1 === peg$FAILED) { s1 = peg$parseps151_bc(); if (s1 === peg$FAILED) { s1 = peg$parsebc(); if (s1 === peg$FAILED) { s1 = peg$parsecv_psalm(); if (s1 === peg$FAILED) { s1 = peg$parsebv(); if (s1 === peg$FAILED) { s1 = peg$parsec_psalm(); if (s1 === peg$FAILED) { s1 = peg$parseb(); if (s1 === peg$FAILED) { s1 = peg$parsecbv(); if (s1 === peg$FAILED) { s1 = peg$parsecbv_ordinal(); if (s1 === peg$FAILED) { s1 = peg$parsecb(); if (s1 === peg$FAILED) { s1 = peg$parsecb_ordinal(); if (s1 === peg$FAILED) { s1 = peg$parsetranslation_sequence_enclosed(); if (s1 === peg$FAILED) { s1 = peg$parsetranslation_sequence(); if (s1 === peg$FAILED) { s1 = peg$parsesequence_sep(); if (s1 === peg$FAILED) { s1 = peg$parsec_title(); if (s1 === peg$FAILED) { s1 = peg$parseinteger_title(); if (s1 === peg$FAILED) { s1 = peg$parsecv(); if (s1 === peg$FAILED) { s1 = peg$parsecv_weak(); if (s1 === peg$FAILED) { s1 = peg$parsev_letter(); if (s1 === peg$FAILED) { s1 = peg$parseinteger(); if (s1 === peg$FAILED) { s1 = peg$parsec(); if (s1 === peg$FAILED) { s1 = peg$parsev(); if (s1 === peg$FAILED) { s1 = peg$parseword(); if (s1 === peg$FAILED) { s1 = peg$parseword_parenthesis(); if (s1 === peg$FAILED) { s1 = peg$parsecontext(); } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } else { s0 = peg$c1; } return s0; } function peg$parsesequence() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsecb_range(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_hyphen_range(); if (s1 === peg$FAILED) { s1 = peg$parserange(); if (s1 === peg$FAILED) { s1 = peg$parseff(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_comma(); if (s1 === peg$FAILED) { s1 = peg$parsebc_title(); if (s1 === peg$FAILED) { s1 = peg$parseps151_bcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_weak(); if (s1 === peg$FAILED) { s1 = peg$parseps151_bc(); if (s1 === peg$FAILED) { s1 = peg$parsebc(); if (s1 === peg$FAILED) { s1 = peg$parsecv_psalm(); if (s1 === peg$FAILED) { s1 = peg$parsebv(); if (s1 === peg$FAILED) { s1 = peg$parsec_psalm(); if (s1 === peg$FAILED) { s1 = peg$parseb(); if (s1 === peg$FAILED) { s1 = peg$parsecbv(); if (s1 === peg$FAILED) { s1 = peg$parsecbv_ordinal(); if (s1 === peg$FAILED) { s1 = peg$parsecb(); if (s1 === peg$FAILED) { s1 = peg$parsecb_ordinal(); if (s1 === peg$FAILED) { s1 = peg$parsecontext(); } } } } } } } } } } } } } } } } } } } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$currPos; s4 = peg$parsesequence_sep(); if (s4 === peg$FAILED) { s4 = peg$c2; } if (s4 !== peg$FAILED) { s5 = peg$parsesequence_post(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$currPos; s4 = peg$parsesequence_sep(); if (s4 === peg$FAILED) { s4 = peg$c2; } if (s4 !== peg$FAILED) { s5 = peg$parsesequence_post(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } } } else { s2 = peg$c1; } if (s2 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c3(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsesequence_post_enclosed() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 40) { s1 = peg$c4; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s1 !== peg$FAILED) { s2 = peg$parsesp(); if (s2 !== peg$FAILED) { s3 = peg$parsesequence_sep(); if (s3 === peg$FAILED) { s3 = peg$c2; } if (s3 !== peg$FAILED) { s4 = peg$parsesequence_post(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$currPos; s7 = peg$parsesequence_sep(); if (s7 === peg$FAILED) { s7 = peg$c2; } if (s7 !== peg$FAILED) { s8 = peg$parsesequence_post(); if (s8 !== peg$FAILED) { s7 = [s7, s8]; s6 = s7; } else { peg$currPos = s6; s6 = peg$c1; } } else { peg$currPos = s6; s6 = peg$c1; } while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$currPos; s7 = peg$parsesequence_sep(); if (s7 === peg$FAILED) { s7 = peg$c2; } if (s7 !== peg$FAILED) { s8 = peg$parsesequence_post(); if (s8 !== peg$FAILED) { s7 = [s7, s8]; s6 = s7; } else { peg$currPos = s6; s6 = peg$c1; } } else { peg$currPos = s6; s6 = peg$c1; } } if (s5 !== peg$FAILED) { s6 = peg$parsesp(); if (s6 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s7 = peg$c6; peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c7); } } if (s7 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c8(s4, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsesequence_post() { var s0; s0 = peg$parsesequence_post_enclosed(); if (s0 === peg$FAILED) { s0 = peg$parsecb_range(); if (s0 === peg$FAILED) { s0 = peg$parsebcv_hyphen_range(); if (s0 === peg$FAILED) { s0 = peg$parserange(); if (s0 === peg$FAILED) { s0 = peg$parseff(); if (s0 === peg$FAILED) { s0 = peg$parsebcv_comma(); if (s0 === peg$FAILED) { s0 = peg$parsebc_title(); if (s0 === peg$FAILED) { s0 = peg$parseps151_bcv(); if (s0 === peg$FAILED) { s0 = peg$parsebcv(); if (s0 === peg$FAILED) { s0 = peg$parsebcv_weak(); if (s0 === peg$FAILED) { s0 = peg$parseps151_bc(); if (s0 === peg$FAILED) { s0 = peg$parsebc(); if (s0 === peg$FAILED) { s0 = peg$parsecv_psalm(); if (s0 === peg$FAILED) { s0 = peg$parsebv(); if (s0 === peg$FAILED) { s0 = peg$parsec_psalm(); if (s0 === peg$FAILED) { s0 = peg$parseb(); if (s0 === peg$FAILED) { s0 = peg$parsecbv(); if (s0 === peg$FAILED) { s0 = peg$parsecbv_ordinal(); if (s0 === peg$FAILED) { s0 = peg$parsecb(); if (s0 === peg$FAILED) { s0 = peg$parsecb_ordinal(); if (s0 === peg$FAILED) { s0 = peg$parsec_title(); if (s0 === peg$FAILED) { s0 = peg$parseinteger_title(); if (s0 === peg$FAILED) { s0 = peg$parsecv(); if (s0 === peg$FAILED) { s0 = peg$parsecv_weak(); if (s0 === peg$FAILED) { s0 = peg$parsev_letter(); if (s0 === peg$FAILED) { s0 = peg$parseinteger(); if (s0 === peg$FAILED) { s0 = peg$parsec(); if (s0 === peg$FAILED) { s0 = peg$parsev(); } } } } } } } } } } } } } } } } } } } } } } } } } } } return s0; } function peg$parserange() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$parsebcv_comma(); if (s1 === peg$FAILED) { s1 = peg$parsebc_title(); if (s1 === peg$FAILED) { s1 = peg$parseps151_bcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_weak(); if (s1 === peg$FAILED) { s1 = peg$parseps151_bc(); if (s1 === peg$FAILED) { s1 = peg$parsebc(); if (s1 === peg$FAILED) { s1 = peg$parsecv_psalm(); if (s1 === peg$FAILED) { s1 = peg$parsebv(); if (s1 === peg$FAILED) { s1 = peg$currPos; s2 = peg$parseb(); if (s2 !== peg$FAILED) { s3 = peg$currPos; peg$silentFails++; s4 = peg$currPos; s5 = peg$parserange_sep(); if (s5 !== peg$FAILED) { s6 = peg$parsebcv_comma(); if (s6 === peg$FAILED) { s6 = peg$parsebc_title(); if (s6 === peg$FAILED) { s6 = peg$parseps151_bcv(); if (s6 === peg$FAILED) { s6 = peg$parsebcv(); if (s6 === peg$FAILED) { s6 = peg$parsebcv_weak(); if (s6 === peg$FAILED) { s6 = peg$parseps151_bc(); if (s6 === peg$FAILED) { s6 = peg$parsebc(); if (s6 === peg$FAILED) { s6 = peg$parsebv(); if (s6 === peg$FAILED) { s6 = peg$parseb(); } } } } } } } } if (s6 !== peg$FAILED) { s5 = [s5, s6]; s4 = s5; } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } peg$silentFails--; if (s4 !== peg$FAILED) { peg$currPos = s3; s3 = peg$c9; } else { s3 = peg$c1; } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$c1; } } else { peg$currPos = s1; s1 = peg$c1; } if (s1 === peg$FAILED) { s1 = peg$parsecbv(); if (s1 === peg$FAILED) { s1 = peg$parsecbv_ordinal(); if (s1 === peg$FAILED) { s1 = peg$parsec_psalm(); if (s1 === peg$FAILED) { s1 = peg$parsecb(); if (s1 === peg$FAILED) { s1 = peg$parsecb_ordinal(); if (s1 === peg$FAILED) { s1 = peg$parsec_title(); if (s1 === peg$FAILED) { s1 = peg$parseinteger_title(); if (s1 === peg$FAILED) { s1 = peg$parsecv(); if (s1 === peg$FAILED) { s1 = peg$parsecv_weak(); if (s1 === peg$FAILED) { s1 = peg$parsev_letter(); if (s1 === peg$FAILED) { s1 = peg$parseinteger(); if (s1 === peg$FAILED) { s1 = peg$parsec(); if (s1 === peg$FAILED) { s1 = peg$parsev(); } } } } } } } } } } } } } } } } } } } } } } if (s1 !== peg$FAILED) { s2 = peg$parserange_sep(); if (s2 !== peg$FAILED) { s3 = peg$parseff(); if (s3 === peg$FAILED) { s3 = peg$parsebcv_comma(); if (s3 === peg$FAILED) { s3 = peg$parsebc_title(); if (s3 === peg$FAILED) { s3 = peg$parseps151_bcv(); if (s3 === peg$FAILED) { s3 = peg$parsebcv(); if (s3 === peg$FAILED) { s3 = peg$parsebcv_weak(); if (s3 === peg$FAILED) { s3 = peg$parseps151_bc(); if (s3 === peg$FAILED) { s3 = peg$parsebc(); if (s3 === peg$FAILED) { s3 = peg$parsecv_psalm(); if (s3 === peg$FAILED) { s3 = peg$parsebv(); if (s3 === peg$FAILED) { s3 = peg$parseb(); if (s3 === peg$FAILED) { s3 = peg$parsecbv(); if (s3 === peg$FAILED) { s3 = peg$parsecbv_ordinal(); if (s3 === peg$FAILED) { s3 = peg$parsec_psalm(); if (s3 === peg$FAILED) { s3 = peg$parsecb(); if (s3 === peg$FAILED) { s3 = peg$parsecb_ordinal(); if (s3 === peg$FAILED) { s3 = peg$parsec_title(); if (s3 === peg$FAILED) { s3 = peg$parseinteger_title(); if (s3 === peg$FAILED) { s3 = peg$parsecv(); if (s3 === peg$FAILED) { s3 = peg$parsev_letter(); if (s3 === peg$FAILED) { s3 = peg$parseinteger(); if (s3 === peg$FAILED) { s3 = peg$parsecv_weak(); if (s3 === peg$FAILED) { s3 = peg$parsec(); if (s3 === peg$FAILED) { s3 = peg$parsev(); } } } } } } } } } } } } } } } } } } } } } } } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c10(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parseb() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 31) { s1 = peg$c11; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c12); } } if (s1 !== peg$FAILED) { s2 = peg$parseany_integer(); if (s2 !== peg$FAILED) { s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 47) { s4 = peg$c13; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c14); } } if (s4 !== peg$FAILED) { if (peg$c15.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c16); } } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } if (s3 === peg$FAILED) { s3 = peg$c2; } if (s3 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 31) { s4 = peg$c11; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c12); } } if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c17(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsebc() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; s1 = peg$parseb(); if (s1 !== peg$FAILED) { s2 = peg$currPos; s3 = peg$parsev_explicit(); if (s3 !== peg$FAILED) { s4 = peg$currPos; peg$silentFails++; s5 = peg$currPos; s6 = peg$parsec(); if (s6 !== peg$FAILED) { s7 = peg$parsecv_sep(); if (s7 !== peg$FAILED) { s8 = peg$parsev(); if (s8 !== peg$FAILED) { s6 = [s6, s7, s8]; s5 = s6; } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } peg$silentFails--; if (s5 !== peg$FAILED) { peg$currPos = s4; s4 = peg$c9; } else { s4 = peg$c1; } if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c1; } } else { peg$currPos = s2; s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = []; s3 = peg$parsecv_sep(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parsecv_sep(); } } else { s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = []; s3 = peg$parsecv_sep_weak(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parsecv_sep_weak(); } } else { s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = []; s3 = peg$parserange_sep(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parserange_sep(); } } else { s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = peg$parsesp(); } } } } if (s2 !== peg$FAILED) { s3 = peg$parsec(); if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c18(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsebc_comma() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parseb(); if (s1 !== peg$FAILED) { s2 = peg$parsesp(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c19; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } if (s3 !== peg$FAILED) { s4 = peg$parsesp(); if (s4 !== peg$FAILED) { s5 = peg$parsec(); if (s5 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c18(s1, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsebc_title() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parseps151_bc(); if (s1 === peg$FAILED) { s1 = peg$parsebc(); } if (s1 !== peg$FAILED) { s2 = peg$parsetitle(); if (s2 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c21(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsebcv() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$parseps151_bc(); if (s1 === peg$FAILED) { s1 = peg$parsebc(); } if (s1 !== peg$FAILED) { s2 = peg$currPos; peg$silentFails++; s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s4 = peg$c22; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s4 !== peg$FAILED) { s5 = peg$parsev_explicit(); if (s5 !== peg$FAILED) { s6 = peg$parsev(); if (s6 !== peg$FAILED) { s4 = [s4, s5, s6]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } if (s3 === peg$FAILED) { s3 = peg$currPos; s4 = peg$parsesequence_sep(); if (s4 === peg$FAILED) { s4 = peg$c2; } if (s4 !== peg$FAILED) { s5 = peg$parsev_explicit(); if (s5 !== peg$FAILED) { s6 = peg$parsecv(); if (s6 !== peg$FAILED) { s4 = [s4, s5, s6]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } } peg$silentFails--; if (s3 === peg$FAILED) { s2 = peg$c9; } else { peg$currPos = s2; s2 = peg$c1; } if (s2 !== peg$FAILED) { s3 = peg$currPos; s4 = peg$parsecv_sep(); if (s4 === peg$FAILED) { s4 = peg$parsesequence_sep(); } if (s4 === peg$FAILED) { s4 = peg$c2; } if (s4 !== peg$FAILED) { s5 = peg$parsev_explicit(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } if (s3 === peg$FAILED) { s3 = peg$parsecv_sep(); } if (s3 !== peg$FAILED) { s4 = peg$parsev_letter(); if (s4 === peg$FAILED) { s4 = peg$parsev(); } if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c24(s1, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsebcv_weak() { var s0, s1, s2, s3, s4, s5, s6, s7; s0 = peg$currPos; s1 = peg$parseps151_bc(); if (s1 === peg$FAILED) { s1 = peg$parsebc(); } if (s1 !== peg$FAILED) { s2 = peg$parsecv_sep_weak(); if (s2 !== peg$FAILED) { s3 = peg$parsev_letter(); if (s3 === peg$FAILED) { s3 = peg$parsev(); } if (s3 !== peg$FAILED) { s4 = peg$currPos; peg$silentFails++; s5 = peg$currPos; s6 = peg$parsecv_sep(); if (s6 !== peg$FAILED) { s7 = peg$parsev(); if (s7 !== peg$FAILED) { s6 = [s6, s7]; s5 = s6; } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } peg$silentFails--; if (s5 === peg$FAILED) { s4 = peg$c9; } else { peg$currPos = s4; s4 = peg$c1; } if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c24(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsebcv_comma() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; s0 = peg$currPos; s1 = peg$parsebc_comma(); if (s1 !== peg$FAILED) { s2 = peg$parsesp(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c19; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } if (s3 !== peg$FAILED) { s4 = peg$parsesp(); if (s4 !== peg$FAILED) { s5 = peg$parsev_letter(); if (s5 === peg$FAILED) { s5 = peg$parsev(); } if (s5 !== peg$FAILED) { s6 = peg$currPos; peg$silentFails++; s7 = peg$currPos; s8 = peg$parsecv_sep(); if (s8 !== peg$FAILED) { s9 = peg$parsev(); if (s9 !== peg$FAILED) { s8 = [s8, s9]; s7 = s8; } else { peg$currPos = s7; s7 = peg$c1; } } else { peg$currPos = s7; s7 = peg$c1; } peg$silentFails--; if (s7 === peg$FAILED) { s6 = peg$c9; } else { peg$currPos = s6; s6 = peg$c1; } if (s6 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c24(s1, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsebcv_hyphen_range() { var s0, s1, s2, s3, s4, s5, s6, s7; s0 = peg$currPos; s1 = peg$parseb(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 45) { s2 = peg$c25; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s2 === peg$FAILED) { s2 = peg$parsespace(); } if (s2 === peg$FAILED) { s2 = peg$c2; } if (s2 !== peg$FAILED) { s3 = peg$parsec(); if (s3 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 45) { s4 = peg$c25; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s4 !== peg$FAILED) { s5 = peg$parsev(); if (s5 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 45) { s6 = peg$c25; peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s6 !== peg$FAILED) { s7 = peg$parsev(); if (s7 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c27(s1, s3, s5, s7); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsebv() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parseb(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parsecv_sep(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parsecv_sep(); } } else { s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = []; s3 = peg$parsecv_sep_weak(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parsecv_sep_weak(); } } else { s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = []; s3 = peg$parserange_sep(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parserange_sep(); } } else { s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = peg$currPos; s3 = []; s4 = peg$parsesequence_sep(); if (s4 !== peg$FAILED) { while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parsesequence_sep(); } } else { s3 = peg$c1; } if (s3 !== peg$FAILED) { s4 = peg$currPos; peg$silentFails++; s5 = peg$parsev_explicit(); peg$silentFails--; if (s5 !== peg$FAILED) { peg$currPos = s4; s4 = peg$c9; } else { s4 = peg$c1; } if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c1; } } else { peg$currPos = s2; s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = peg$parsesp(); } } } } if (s2 !== peg$FAILED) { s3 = peg$parsev_letter(); if (s3 === peg$FAILED) { s3 = peg$parsev(); } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c28(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecb() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parsec_explicit(); if (s1 !== peg$FAILED) { s2 = peg$parsec(); if (s2 !== peg$FAILED) { s3 = peg$parsein_book_of(); if (s3 === peg$FAILED) { s3 = peg$c2; } if (s3 !== peg$FAILED) { s4 = peg$parseb(); if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c29(s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecb_range() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$parsec_explicit(); if (s1 !== peg$FAILED) { s2 = peg$parsec(); if (s2 !== peg$FAILED) { s3 = peg$parserange_sep(); if (s3 !== peg$FAILED) { s4 = peg$parsec(); if (s4 !== peg$FAILED) { s5 = peg$parsein_book_of(); if (s5 === peg$FAILED) { s5 = peg$c2; } if (s5 !== peg$FAILED) { s6 = peg$parseb(); if (s6 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c30(s2, s4, s6); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecbv() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parsecb(); if (s1 !== peg$FAILED) { s2 = peg$parsesequence_sep(); if (s2 === peg$FAILED) { s2 = peg$c2; } if (s2 !== peg$FAILED) { s3 = peg$parsev_explicit(); if (s3 !== peg$FAILED) { s4 = peg$parsev(); if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c24(s1, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecb_ordinal() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsec(); if (s1 !== peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c31) { s2 = peg$c31; peg$currPos += 2; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c32); } } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c33) { s2 = peg$c33; peg$currPos += 2; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c34); } } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c35) { s2 = peg$c35; peg$currPos += 2; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c36); } } } } if (s2 !== peg$FAILED) { s3 = peg$parsec_explicit(); if (s3 !== peg$FAILED) { s4 = peg$parsein_book_of(); if (s4 === peg$FAILED) { s4 = peg$c2; } if (s4 !== peg$FAILED) { s5 = peg$parseb(); if (s5 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c29(s1, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecbv_ordinal() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parsecb_ordinal(); if (s1 !== peg$FAILED) { s2 = peg$parsesequence_sep(); if (s2 === peg$FAILED) { s2 = peg$c2; } if (s2 !== peg$FAILED) { s3 = peg$parsev_explicit(); if (s3 !== peg$FAILED) { s4 = peg$parsev(); if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c24(s1, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsec_psalm() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 31) { s1 = peg$c11; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c12); } } if (s1 !== peg$FAILED) { s2 = peg$parseany_integer(); if (s2 !== peg$FAILED) { if (input.substr(peg$currPos, 3) === peg$c37) { s3 = peg$c37; peg$currPos += 3; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c38); } } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c39(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecv_psalm() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parsec_psalm(); if (s1 !== peg$FAILED) { s2 = peg$parsesequence_sep(); if (s2 === peg$FAILED) { s2 = peg$c2; } if (s2 !== peg$FAILED) { s3 = peg$parsev_explicit(); if (s3 !== peg$FAILED) { s4 = peg$parsev(); if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c40(s1, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsec_title() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsec_explicit(); if (s1 !== peg$FAILED) { s2 = peg$parsec(); if (s2 !== peg$FAILED) { s3 = peg$parsetitle(); if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c41(s2, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecv() { var s0, s1, s2, s3, s4, s5, s6, s7; s0 = peg$currPos; s1 = peg$parsev_explicit(); if (s1 === peg$FAILED) { s1 = peg$c2; } if (s1 !== peg$FAILED) { s2 = peg$parsec(); if (s2 !== peg$FAILED) { s3 = peg$currPos; peg$silentFails++; s4 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s5 = peg$c22; peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s5 !== peg$FAILED) { s6 = peg$parsev_explicit(); if (s6 !== peg$FAILED) { s7 = peg$parsev(); if (s7 !== peg$FAILED) { s5 = [s5, s6, s7]; s4 = s5; } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } peg$silentFails--; if (s4 === peg$FAILED) { s3 = peg$c9; } else { peg$currPos = s3; s3 = peg$c1; } if (s3 !== peg$FAILED) { s4 = peg$currPos; s5 = peg$parsecv_sep(); if (s5 === peg$FAILED) { s5 = peg$c2; } if (s5 !== peg$FAILED) { s6 = peg$parsev_explicit(); if (s6 !== peg$FAILED) { s5 = [s5, s6]; s4 = s5; } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } if (s4 === peg$FAILED) { s4 = peg$parsecv_sep(); } if (s4 !== peg$FAILED) { s5 = peg$parsev_letter(); if (s5 === peg$FAILED) { s5 = peg$parsev(); } if (s5 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c42(s2, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecv_weak() { var s0, s1, s2, s3, s4, s5, s6, s7; s0 = peg$currPos; s1 = peg$parsec(); if (s1 !== peg$FAILED) { s2 = peg$parsecv_sep_weak(); if (s2 !== peg$FAILED) { s3 = peg$parsev_letter(); if (s3 === peg$FAILED) { s3 = peg$parsev(); } if (s3 !== peg$FAILED) { s4 = peg$currPos; peg$silentFails++; s5 = peg$currPos; s6 = peg$parsecv_sep(); if (s6 !== peg$FAILED) { s7 = peg$parsev(); if (s7 !== peg$FAILED) { s6 = [s6, s7]; s5 = s6; } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } peg$silentFails--; if (s5 === peg$FAILED) { s4 = peg$c9; } else { peg$currPos = s4; s4 = peg$c1; } if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c42(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsec() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parsec_explicit(); if (s1 === peg$FAILED) { s1 = peg$c2; } if (s1 !== peg$FAILED) { s2 = peg$parseinteger(); if (s2 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c43(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parseff() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$parsebcv(); if (s1 === peg$FAILED) { s1 = peg$parsebcv_weak(); if (s1 === peg$FAILED) { s1 = peg$parsebc(); if (s1 === peg$FAILED) { s1 = peg$parsebv(); if (s1 === peg$FAILED) { s1 = peg$parsecv(); if (s1 === peg$FAILED) { s1 = peg$parsecv_weak(); if (s1 === peg$FAILED) { s1 = peg$parseinteger(); if (s1 === peg$FAILED) { s1 = peg$parsec(); if (s1 === peg$FAILED) { s1 = peg$parsev(); } } } } } } } } if (s1 !== peg$FAILED) { s2 = peg$parsesp(); if (s2 !== peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c44) { s3 = peg$c44; peg$currPos += 2; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s3 !== peg$FAILED) { s4 = peg$parseabbrev(); if (s4 === peg$FAILED) { s4 = peg$c2; } if (s4 !== peg$FAILED) { s5 = peg$currPos; peg$silentFails++; if (peg$c46.test(input.charAt(peg$currPos))) { s6 = input.charAt(peg$currPos); peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c47); } } peg$silentFails--; if (s6 === peg$FAILED) { s5 = peg$c9; } else { peg$currPos = s5; s5 = peg$c1; } if (s5 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c48(s1); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parseinteger_title() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parseinteger(); if (s1 !== peg$FAILED) { s2 = peg$parsecv_sep(); if (s2 === peg$FAILED) { s2 = peg$parsesequence_sep(); } if (s2 === peg$FAILED) { s2 = peg$c2; } if (s2 !== peg$FAILED) { if (input.substr(peg$currPos, 5) === peg$c49) { s3 = peg$c49; peg$currPos += 5; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c50); } } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c51(s1); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecontext() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 31) { s1 = peg$c11; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c12); } } if (s1 !== peg$FAILED) { s2 = peg$parseany_integer(); if (s2 !== peg$FAILED) { if (input.substr(peg$currPos, 3) === peg$c52) { s3 = peg$c52; peg$currPos += 3; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c53); } } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c54(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parseps151_b() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 31) { s1 = peg$c11; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c12); } } if (s1 !== peg$FAILED) { s2 = peg$parseany_integer(); if (s2 !== peg$FAILED) { if (input.substr(peg$currPos, 3) === peg$c55) { s3 = peg$c55; peg$currPos += 3; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c56); } } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c17(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parseps151_bc() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parseps151_b(); if (s1 !== peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c57) { s2 = peg$c57; peg$currPos += 2; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c58); } } if (s2 !== peg$FAILED) { s3 = peg$currPos; peg$silentFails++; if (peg$c59.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c60); } } peg$silentFails--; if (s4 === peg$FAILED) { s3 = peg$c9; } else { peg$currPos = s3; s3 = peg$c1; } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c61(s1); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parseps151_bcv() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parseps151_bc(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s2 = peg$c22; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s2 !== peg$FAILED) { s3 = peg$parseinteger(); if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c62(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsev_letter() { var s0, s1, s2, s3, s4, s5, s6, s7; s0 = peg$currPos; s1 = peg$parsev_explicit(); if (s1 === peg$FAILED) { s1 = peg$c2; } if (s1 !== peg$FAILED) { s2 = peg$parseinteger(); if (s2 !== peg$FAILED) { s3 = peg$parsesp(); if (s3 !== peg$FAILED) { s4 = peg$currPos; peg$silentFails++; if (input.substr(peg$currPos, 2) === peg$c44) { s5 = peg$c44; peg$currPos += 2; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } peg$silentFails--; if (s5 === peg$FAILED) { s4 = peg$c9; } else { peg$currPos = s4; s4 = peg$c1; } if (s4 !== peg$FAILED) { if (peg$c63.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c64); } } if (s5 !== peg$FAILED) { s6 = peg$currPos; peg$silentFails++; if (peg$c46.test(input.charAt(peg$currPos))) { s7 = input.charAt(peg$currPos); peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c47); } } peg$silentFails--; if (s7 === peg$FAILED) { s6 = peg$c9; } else { peg$currPos = s6; s6 = peg$c1; } if (s6 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c65(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsev() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parsev_explicit(); if (s1 === peg$FAILED) { s1 = peg$c2; } if (s1 !== peg$FAILED) { s2 = peg$parseinteger(); if (s2 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c65(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsec_explicit() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { if (input.substr(peg$currPos, 7) === peg$c66) { s2 = peg$c66; peg$currPos += 7; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c67); } } if (s2 !== peg$FAILED) { s3 = peg$parsesp(); if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c68(); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsev_explicit() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { if (input.substr(peg$currPos, 5) === peg$c69) { s2 = peg$c69; peg$currPos += 5; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c70); } } if (s2 !== peg$FAILED) { s3 = peg$currPos; peg$silentFails++; if (peg$c46.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c47); } } peg$silentFails--; if (s4 === peg$FAILED) { s3 = peg$c9; } else { peg$currPos = s3; s3 = peg$c1; } if (s3 !== peg$FAILED) { s4 = peg$parsesp(); if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c71(); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecv_sep() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { s2 = []; if (input.charCodeAt(peg$currPos) === 58) { s3 = peg$c72; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c73); } } if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); if (input.charCodeAt(peg$currPos) === 58) { s3 = peg$c72; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c73); } } } } else { s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s3 = peg$c22; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s3 !== peg$FAILED) { s4 = peg$currPos; peg$silentFails++; s5 = peg$currPos; s6 = peg$parsesp(); if (s6 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s7 = peg$c22; peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s7 !== peg$FAILED) { s8 = peg$parsesp(); if (s8 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s9 = peg$c22; peg$currPos++; } else { s9 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s9 !== peg$FAILED) { s6 = [s6, s7, s8, s9]; s5 = s6; } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } peg$silentFails--; if (s5 === peg$FAILED) { s4 = peg$c9; } else { peg$currPos = s4; s4 = peg$c1; } if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c1; } } else { peg$currPos = s2; s2 = peg$c1; } } if (s2 !== peg$FAILED) { s3 = peg$parsesp(); if (s3 !== peg$FAILED) { s1 = [s1, s2, s3]; s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsecv_sep_weak() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { if (peg$c74.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c75); } } if (s2 !== peg$FAILED) { s3 = peg$parsesp(); if (s3 !== peg$FAILED) { s1 = [s1, s2, s3]; s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } if (s0 === peg$FAILED) { s0 = peg$parsespace(); } return s0; } function peg$parsesequence_sep() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; s0 = peg$currPos; s1 = []; if (peg$c76.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c77); } } if (s2 === peg$FAILED) { s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s3 = peg$c22; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s3 !== peg$FAILED) { s4 = peg$currPos; peg$silentFails++; s5 = peg$currPos; s6 = peg$parsesp(); if (s6 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s7 = peg$c22; peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s7 !== peg$FAILED) { s8 = peg$parsesp(); if (s8 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s9 = peg$c22; peg$currPos++; } else { s9 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s9 !== peg$FAILED) { s6 = [s6, s7, s8, s9]; s5 = s6; } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } peg$silentFails--; if (s5 === peg$FAILED) { s4 = peg$c9; } else { peg$currPos = s4; s4 = peg$c1; } if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c1; } } else { peg$currPos = s2; s2 = peg$c1; } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 3) === peg$c78) { s2 = peg$c78; peg$currPos += 3; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c79); } } if (s2 === peg$FAILED) { s2 = peg$parsespace(); } } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c76.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c77); } } if (s2 === peg$FAILED) { s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s3 = peg$c22; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s3 !== peg$FAILED) { s4 = peg$currPos; peg$silentFails++; s5 = peg$currPos; s6 = peg$parsesp(); if (s6 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s7 = peg$c22; peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s7 !== peg$FAILED) { s8 = peg$parsesp(); if (s8 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s9 = peg$c22; peg$currPos++; } else { s9 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s9 !== peg$FAILED) { s6 = [s6, s7, s8, s9]; s5 = s6; } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } } else { peg$currPos = s5; s5 = peg$c1; } peg$silentFails--; if (s5 === peg$FAILED) { s4 = peg$c9; } else { peg$currPos = s4; s4 = peg$c1; } if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c1; } } else { peg$currPos = s2; s2 = peg$c1; } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 3) === peg$c78) { s2 = peg$c78; peg$currPos += 3; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c79); } } if (s2 === peg$FAILED) { s2 = peg$parsespace(); } } } } } else { s1 = peg$c1; } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c80(); } s0 = s1; return s0; } function peg$parserange_sep() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$currPos; if (peg$c81.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c82); } } if (s4 !== peg$FAILED) { s5 = peg$parsesp(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c83) { s4 = peg$c83; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c84); } } if (s4 !== peg$FAILED) { s5 = peg$parsesp(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } } if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$currPos; if (peg$c81.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c82); } } if (s4 !== peg$FAILED) { s5 = peg$parsesp(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c83) { s4 = peg$c83; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c84); } } if (s4 !== peg$FAILED) { s5 = peg$parsesp(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } } } } else { s2 = peg$c1; } if (s2 !== peg$FAILED) { s1 = [s1, s2]; s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsetitle() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parsecv_sep(); if (s1 === peg$FAILED) { s1 = peg$parsesequence_sep(); } if (s1 === peg$FAILED) { s1 = peg$c2; } if (s1 !== peg$FAILED) { if (input.substr(peg$currPos, 5) === peg$c49) { s2 = peg$c49; peg$currPos += 5; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c50); } } if (s2 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c85(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsein_book_of() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c86) { s2 = peg$c86; peg$currPos += 4; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c87); } } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c88) { s2 = peg$c88; peg$currPos += 2; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c89); } } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c90) { s2 = peg$c90; peg$currPos += 2; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c91); } } } } if (s2 !== peg$FAILED) { s3 = peg$parsesp(); if (s3 !== peg$FAILED) { s4 = peg$currPos; if (input.substr(peg$currPos, 3) === peg$c92) { s5 = peg$c92; peg$currPos += 3; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c93); } } if (s5 !== peg$FAILED) { s6 = peg$parsesp(); if (s6 !== peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c94) { s7 = peg$c94; peg$currPos += 4; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c95); } } if (s7 !== peg$FAILED) { s8 = peg$parsesp(); if (s8 !== peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c88) { s9 = peg$c88; peg$currPos += 2; } else { s9 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c89); } } if (s9 !== peg$FAILED) { s10 = peg$parsesp(); if (s10 !== peg$FAILED) { s5 = [s5, s6, s7, s8, s9, s10]; s4 = s5; } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } if (s4 === peg$FAILED) { s4 = peg$c2; } if (s4 !== peg$FAILED) { s1 = [s1, s2, s3, s4]; s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parseabbrev() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s2 = peg$c22; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s2 !== peg$FAILED) { s3 = peg$currPos; peg$silentFails++; s4 = peg$currPos; s5 = peg$parsesp(); if (s5 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s6 = peg$c22; peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s6 !== peg$FAILED) { s7 = peg$parsesp(); if (s7 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s8 = peg$c22; peg$currPos++; } else { s8 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s8 !== peg$FAILED) { s5 = [s5, s6, s7, s8]; s4 = s5; } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } peg$silentFails--; if (s4 === peg$FAILED) { s3 = peg$c9; } else { peg$currPos = s3; s3 = peg$c1; } if (s3 !== peg$FAILED) { s1 = [s1, s2, s3]; s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsetranslation_sequence_enclosed() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { if (peg$c96.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c97); } } if (s2 !== peg$FAILED) { s3 = peg$parsesp(); if (s3 !== peg$FAILED) { s4 = peg$currPos; s5 = peg$parsetranslation(); if (s5 !== peg$FAILED) { s6 = []; s7 = peg$currPos; s8 = peg$parsesequence_sep(); if (s8 !== peg$FAILED) { s9 = peg$parsetranslation(); if (s9 !== peg$FAILED) { s8 = [s8, s9]; s7 = s8; } else { peg$currPos = s7; s7 = peg$c1; } } else { peg$currPos = s7; s7 = peg$c1; } while (s7 !== peg$FAILED) { s6.push(s7); s7 = peg$currPos; s8 = peg$parsesequence_sep(); if (s8 !== peg$FAILED) { s9 = peg$parsetranslation(); if (s9 !== peg$FAILED) { s8 = [s8, s9]; s7 = s8; } else { peg$currPos = s7; s7 = peg$c1; } } else { peg$currPos = s7; s7 = peg$c1; } } if (s6 !== peg$FAILED) { s5 = [s5, s6]; s4 = s5; } else { peg$currPos = s4; s4 = peg$c1; } } else { peg$currPos = s4; s4 = peg$c1; } if (s4 !== peg$FAILED) { s5 = peg$parsesp(); if (s5 !== peg$FAILED) { if (peg$c98.test(input.charAt(peg$currPos))) { s6 = input.charAt(peg$currPos); peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c99); } } if (s6 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c100(s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsetranslation_sequence() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; s1 = peg$parsesp(); if (s1 !== peg$FAILED) { s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c19; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } if (s3 !== peg$FAILED) { s4 = peg$parsesp(); if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c1; } } else { peg$currPos = s2; s2 = peg$c1; } if (s2 === peg$FAILED) { s2 = peg$c2; } if (s2 !== peg$FAILED) { s3 = peg$currPos; s4 = peg$parsetranslation(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$currPos; s7 = peg$parsesequence_sep(); if (s7 !== peg$FAILED) { s8 = peg$parsetranslation(); if (s8 !== peg$FAILED) { s7 = [s7, s8]; s6 = s7; } else { peg$currPos = s6; s6 = peg$c1; } } else { peg$currPos = s6; s6 = peg$c1; } while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$currPos; s7 = peg$parsesequence_sep(); if (s7 !== peg$FAILED) { s8 = peg$parsetranslation(); if (s8 !== peg$FAILED) { s7 = [s7, s8]; s6 = s7; } else { peg$currPos = s6; s6 = peg$c1; } } else { peg$currPos = s6; s6 = peg$c1; } } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c1; } } else { peg$currPos = s3; s3 = peg$c1; } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c100(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parsetranslation() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 30) { s1 = peg$c101; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c102); } } if (s1 !== peg$FAILED) { s2 = peg$parseany_integer(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 30) { s3 = peg$c101; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c102); } } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c103(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } } else { peg$currPos = s0; s0 = peg$c1; } return s0; } function peg$parseinteger() { var res; if (res = /^[0-9]{1,3}(?!\d|,000)/.exec(input.substr(peg$currPos))) { peg$reportedPos = peg$currPos; peg$currPos += res[0].length; return {"type": "integer", "value": parseInt(res[0], 10), "indices": [peg$reportedPos, peg$currPos - 1]} } else { return peg$c1; } } function peg$parseany_integer() { var res; if (res = /^[0-9]+/.exec(input.substr(peg$currPos))) { peg$reportedPos = peg$currPos; peg$currPos += res[0].length; return {"type": "integer", "value": parseInt(res[0], 10), "indices": [peg$reportedPos, peg$currPos - 1]} } else { return peg$c1; } } function peg$parseword() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (peg$c107.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c108); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c107.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c108); } } } } else { s1 = peg$c1; } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c109(s1); } s0 = s1; return s0; } function peg$parseword_parenthesis() { var s0, s1; s0 = peg$currPos; if (peg$c96.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c97); } } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c110(s1); } s0 = s1; return s0; } function peg$parsesp() { var s0; s0 = peg$parsespace(); if (s0 === peg$FAILED) { s0 = peg$c2; } return s0; } function peg$parsespace() { var res; if (res = /^[\s\xa0*]+/.exec(input.substr(peg$currPos))) { peg$reportedPos = peg$currPos; peg$currPos += res[0].length; return []; } return peg$c1; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail({ type: "end", description: "end of input" }); } throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); } } return { SyntaxError: SyntaxError, parse: parse }; })(); }).call(this);
var express = require('express'); var nodemailer = require('nodemailer'); var williamJHitchcock = express(); //default port to 8000 for dev var PORT = process.env.PORT || 8000; console.log(__dirname); //serve static files williamJHitchcock.use(express.static(__dirname + '/public/')); //send email williamJHitchcock.get('/contact', function(req, res) { // create reusable transporter object using the default SMTP transport var transporter = nodemailer.createTransport('smtps://william.hitchcock1%40gmail.com:omusofgnvqpvezqd@smtp.gmail.com'); console.log(req.query); // setup e-mail data var mailOptions = { from: '"' + req.query.name + '" <contact@willhitchcock.me>', replyTo: req.query.email, to: 'hi@willhitchcock.me', subject: req.query.sub, text: req.query.msg }; // send mail with defined transport object transporter.sendMail(mailOptions, function(error, info) { if (error) { setTimeout(function() { res.send('{' + '"status":"error",' + '"message":"An error occured, your message may not have been sent!",' + '"icon":"error"' + '}'); }, 3000); return console.log(error); } setTimeout(function() { res.send('{' + '"status":"success",' + '"message":"Message sent!",' + '"icon":"check_circle"' + '}'); }, 3000); console.log('Message sent: ' + info.response); }); }); var server = williamJHitchcock.listen(PORT, function() { console.log('Listening on port ' + PORT) });
describe("hapi-rest-methods", function() { var testMethods = ['any', 'get', 'post', 'put', 'patch', 'delete', 'options']; var hapi = require('hapi'); var request = require('request'); var restMethods = require('../lib/index') var server; beforeEach(function() { server = new hapi.Server(); server.connection({ port: 8080 }); server.register(restMethods); }); afterEach(function() { server.stop(); server = null; }); function it_for(specName, methodName, callback) { it(specName + " for " + methodName + "()", callback); } describe("when configuring server", function() { testMethods.forEach(function(methodName) { it_for("should decorate hapi.server and make it respond", methodName, function() { expect(typeof server[methodName]).toBe("function"); }); }); }); describe("when running server", function() { function testServer(methodName, path) { server.start(function(err) { if(err) throw err; if(methodName === 'any') methodName = 'patch'; // this can be anything, choosing patch for convenience request({ uri: server.info.uri + path, method: methodName }, function(error, response, body) { expect(response.statusCode).toBe(200); expect(body).toBe('test'); }); }); } function routeHandler(done) { return function(response, reply) { reply('test'); done(); } } testMethods.forEach(function(methodName) { it_for("should create route path and handler", methodName, function(done) { var path = '/test/' + methodName; server[methodName](path, routeHandler(done)); testServer(methodName, path); }); it_for("should create route path, config and handler", methodName, function(done) { var path = '/test/' + methodName; server[methodName](path, {}, routeHandler(done)); testServer(methodName, path); }); }); }); });
import {VelocityAnimator} from '../src/animator'; import {initialize} from 'aurelia-pal-browser'; jasmine.getFixtures().fixturesPath = 'base/test/fixtures/'; describe('stop function', () => { let animator; let container; beforeAll(() => initialize()); beforeEach(() => { let elem = $('#test-simple').eq(0)[0]; //stop all animations running on the test element if (animator) animator.stop(elem, true); loadFixtures('animation.html'); container = $('#animation').eq(0)[0]; animator = new VelocityAnimator(container); let elems = container.querySelectorAll('.group1'); animator.stop(elem, true); animator.stop(elems, true); }); it('returns the animator instance for a fluent api', () => { let elem = $('#test-simple').eq(0)[0]; let result = animator.stop(elem); expect(result).toBe(animator); }); it('stops the animation without resetting it', (done) => { let elem = $('#test-simple').eq(0)[0]; animator.animate(elem, 'fadeIn', {duration: 100}); //the fixture does not have an opacity at the begining expect(elem.style.opacity).toBe(''); //stop the animation halfway through setTimeout(()=> { //get current opacity value let opacity = elem.style.opacity; //check if opacity was being animated expect(opacity > 0, opacity < 1).toBe(true); //stop animation animator.stop(elem); //check if opacity hasn't been reset or changed because of the stop expect(opacity === elem.style.opacity).toBe(true); //make sure the animation didn't continue afterwards setTimeout(()=> { expect(opacity === elem.style.opacity).toBe(true); done(); }, 10); }, 50); }); it('stops multiple elements', (done) => { let elems = container.querySelectorAll('.group1'); animator.stop(elems, true); expect(elems[0].style.opacity).toBe(''); animator.animate(elems, 'fadeIn', {duration: 100}); //stop the animation halfway through setTimeout(()=> { //get current opacity value let opacity0 = elems[0].style.opacity; let opacity1 = elems[1].style.opacity; //stop animations animator.stop(elems); //check if opacity was being animated expect(opacity0 > 0, opacity0 < 1).toBe(true); //check if opacity hasn't been reset or changed because of the stop expect(opacity0 === elems[0].style.opacity).toBe(true); //check if opacity was being animated expect(opacity1 > 0, opacity1 < 1).toBe(true); //check if opacity hasn't been reset or changed because of the stop expect(opacity1 === elems[0].style.opacity).toBe(true); done(); }, 50); }); it('sets isAnimating to false', () => { let elem = $('#test-simple').eq(0)[0]; animator.animate(elem, 'fadeIn', {duration: 100}); expect(animator.isAnimating).toBe(true); animator.stop(elem); expect(animator.isAnimating).toBe(false); }); });
var MERU = {}; MERU.options = { requestGet: { host: 'mobileapp.merucabs.com', port: 80, method: 'GET', path: '' }, requestPost: { host: 'merucabapp.com', port: 80, method: 'POST', path: '', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': 0, 'Host': 'merucabapp.com', } } }; MERU.Taxi_Name_Map = { genie: 'Genie', meru: 'Meru', } module.exports = MERU;
if ( typeof Promise == 'undefined' ) { var _P = require('../lib/promise.min.js').Promise; } else { var _P = Promise; } var Excp = require('excp.js'); var Session = require('session.js'); var Table = require('table.js'); function Wss( option ) { this.isOpen = false; this.events = {}; this.conn_events = {}; this.host = option['wss'] || option['host']; this.ss = new Session( option ); this.ss.start(); this.cid = option.app || ''; this.prefix= option['table.prefix'] || ''; this.table_name = option['ws.table'] || 'message'; this.user_table = option['user.table'] || 'user'; this.tab = new Table( option, this.table_name ); /** * 读取当前线上用户 * @return Promise */ this.liveUsers = function() { var that = this; return new _P(function (resolve, reject) { var eventBack = null; if ( typeof that.events['getConnections'] == 'function' ) { eventBack = that.events['getConnections']; } that.events['getConnections'] = function( res, status ) { if ( eventBack != null ) { that.events['getConnections'] = eventBack; } if ( status == 'success' ) { resolve( res.response ); return; } else { var error = res.error || '读取当前线上用户失败'; reject(new Excp( error ,500, { 'status': status, 'res':res })); } } that.send('getConnections').catch( function( e ) {reject(e)} ); }); } /** * 查询用户是否在线 ( xpm-server 1.0rc4 以上 ) * @param string uid 用户ID * @return Promise 在线 true 不在线 false */ this.isOnline = function( uid ) { var that = this; return new _P(function (resolve, reject) { var eventBack = null; if ( typeof that.events['ping'] == 'function' ) { eventBack = that.events['ping']; } that.events['ping'] = function( res, status ) { if ( eventBack != null ) { that.events['ping'] = eventBack; } if ( status == 'success' ) { if ( res.response.resp == 'pong' ) { resolve(true); return; } resolve(false); return; } else { var error = res.error || '读取用户在线信息失败'; reject(new Excp( error ,500, { 'status': status, 'res':res })); } } that.send('ping','user online', uid).catch( function( e ) {reject(e)} ); }); } /** * 接收 WebSocket Sever 事件 * @param string evnet 事件名称,有效值 ( open/close/message/error ) * @param function callback( res ) 回调函数 * @return this */ this.bind = function ( evnet, callback ) { this.conn_events[evnet] = callback; return this; } /** * 接收指令并响应 * @param string command 指令名称 * @param function callback( res, status ) 指定响应函数 * callback 参数表: * object res.request 请求参数 {"c": "command","b": {"info": "你好!"},"t": 2 } * object res.response 请求用户 * 登录用户: {"_id": 2, "nickName": "柳敏", "gender": 0, "avatarUrl": "..","language": "zh_CN","id": "e8e989e04627b7b5d73f019456f65d7d"} * 未登录用户: {"id": "e8e989e04627b7b5d73f019456f65d7d"} * * string res.error 错误描述 * string status 返回状态 succes/error * @return this */ this.listen = function ( command, callback ) { this.events[command] = callback; return this; } /** * 发送指令 * @param string command 指令名称 * @param object params 请求参数 * @param string/int receiver 接受者 ( 连接 id 或者用户 id ) * @return Promise */ this.send = function ( command, params, receiver ) { var that = this; return new _P(function (resolve, reject) { if (that.isOpen !== true ) { reject(new Excp('WebSocket未连接', 401, { 'command':command, 'params': params, 'receiver': receiver })); } receiver = receiver || null; wx.sendSocketMessage({ data:JSON.stringify({'c':command, 'b':params, 't':receiver }), success: function( res ){ resolve( true ); }, fail: function( res ){ reject(new Excp('消息发送失败',500, { 'command':command, 'params': params, 'res':res })); } }); }); } /** * 打开 Websocket 信道 * @param string channel 信道地址 * @param boolen ignore true: 如果信道已连接反返回正确信息,默认为 true * @return Promise */ this.open = function( channel, ignore ) { var that = this; if ( typeof ignore == 'undefined') ignore = true; return new _P(function (resolve, reject) { if ( ignore && that.isOpen) { resolve(true); return } // wx.connectSocket BUG Android success (函数返回值不正确 ) wx.connectSocket({ url: 'wss://' + that.host + channel + '?_sid=' + that.ss.id() + '&_prefix=' + that.prefix + '&_table=' + that.table_name + '&_user=' + that.user_table+ '&_cid=' + that.cid, success:function( res, status ){}, fail: function( res ){ // console.log( 'wx.connectSocket fail', res); reject( new Excp( 'WebSocket Error', 500, { 'res':res, 'isOpen': that.isOpen, 'channel':channel, 'host':that.host } )); return; } }); wx.onSocketOpen(function(res) { that.isOpen = true; if ( typeof that.conn_events['open'] == 'function' ) { try { that.conn_events['open']( res ); } catch(e){} } resolve( res ); return; }); // BUG Android 接收不到错误通知 wx.onSocketError(function(res){ // that.isOpen = false; if ( typeof that.conn_events['error'] == 'function' ) { try { that.conn_events['error']( res ); } catch(e){} } reject( new Excp( 'WebSocket Error', 500, { 'res':res, 'isOpen': that.isOpen, 'channel':channel, 'host':that.host } )); return; }); wx.onSocketClose(function(res) { that.isOpen = false; if ( typeof that.conn_events['close'] == 'function' ) { try { that.conn_events['close']( res ); } catch(e){} } }); wx.onSocketMessage(function( res ){ if ( typeof that.conn_events['message'] == 'function' ) { try { that.conn_events['message']( res ); } catch(e){} } if ( typeof res.data !== 'string' ) { return; } var resp = JSON.parse( res.data ); resp['data'] = resp['data'] || {}; var code = resp['code']; var req = resp['data']['request'] || {}; var res = resp['data']['response'] || {}; var error = resp['data']['error'] || null; var cmd = req['c'] || null; if ( code !== 0 ) { if ( typeof that.events[cmd] == 'function' ) { that.events[cmd]( {'request':req, 'response':res,'error':error}, 'error'); } return; } if ( typeof that.events[cmd] == 'function' ) { that.events[cmd]( {'request':req, 'response':res}, 'success'); } }); }); } /** * 关闭 Websocket 信道 * @return null */ this.close = function() { wx.closeSocket(); } /** * 设定/查询信道鉴权 ( 需要管理员权限 ) * @return Promise */ this._acl = function() { } } module.exports = Wss;
/** * @since 2.2.0 */ process.traceDeprecation = true; process.env.BABEL_ENV = 'test'; const path = require('path'); require('@babel/register'); let ci = process.env.CI || process.env.APPVEYOR; let webpackConfig = require('./build-config/webpack.prod.main.js'); let support_dir = path.resolve(__dirname, 'test', 'support'); let fakeAudioStream = path.join(support_dir, 'Front_Center.wav'); let fakeVideoStream = path.join(support_dir, 'bus_qcif_7.5fps.y4m'); //------------------------------------------- // Chrome CLI options //------------------------------------------- // http://peter.sh/experiments/chromium-command-line-switches/ const chromeFlags = [ '--no-sandbox', '--disable-gpu', '--no-first-run', '--noerrdialogs', '--no-default-browser-check', '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', '--use-file-for-fake-audio-capture=' + fakeAudioStream, '--use-file-for-fake-video-capture=' + fakeVideoStream, '--autoplay-policy=no-user-gesture-required', '--user-data-dir=' + path.resolve('.chrome'), '--disable-translate', '--disable-extensions', '--disable-infobars', '--ignore-certificate-errors', '--allow-insecure-localhost', '--enable-experimental-web-platform-features', '--js-flags=--max-old-space-size=8196' ]; //------------------------------------------- // Firefox CLI options //------------------------------------------- const firefoxFlags = { 'media.navigator.permission.disabled': true, 'media.navigator.streams.fake': true, 'media.getusermedia.screensharing.enabled': true, 'media.setsinkid.enabled': true, 'javascript.options.streams': true, // devtools 'devtools.theme': 'dark', 'devtools.webconsole.timestampMessages': true, 'devtools.toolbox.host': 'right', 'devtools.toolbox.selectedTool': 'webconsole', 'devtools.chrome.enabled': true, // disable autoplay blocking, see: // https://www.ghacks.net/2018/09/21/firefox-improved-autoplay-blocking/ 'media.autoplay.default': 1, 'media.autoplay.ask-permission': false, 'media.autoplay.enabled.user-gestures-needed': false, 'media.autoplay.block-webaudio': false, // disable update and startup 'extensions.update.enabled': false, 'app.update.enabled': false, 'browser.startup.page': 0, 'startup.homepage_welcome_url': '', 'browser.shell.checkDefaultBrowser': false }; module.exports = function(config) { let configuration = { basePath: '', frameworks: ['jasmine', 'jasmine-matchers', 'host-environment', 'detectBrowsers', 'webpack'], hostname: 'localhost', port: 9876, logLevel: config.LOG_INFO, singleRun: true, // enable for headless testing autoWatch: false, files: [ // ------------------------------------------- // demo files // ------------------------------------------- { pattern: 'test/support/*', included: false, watched: false, served: true }, // style 'node_modules/video.js/dist/video-js.css', 'node_modules/videojs-wavesurfer/dist/css/videojs.wavesurfer.css', // library dependencies 'node_modules/video.js/dist/video.js', 'node_modules/webrtc-adapter/out/adapter.js', 'node_modules/recordrtc/RecordRTC.js', // ------------------------------------------- // third-party dependencies for audio-only // ------------------------------------------- // wavesurfer.js 'node_modules/wavesurfer.js/dist/wavesurfer.min.js', 'node_modules/wavesurfer.js/dist/plugin/wavesurfer.microphone.js', // videojs-wavesurfer 'node_modules/videojs-wavesurfer/dist/videojs.wavesurfer.js', // ------------------------------------------- // plugin style // ------------------------------------------- 'dist/css/videojs.record.css', // ----------------------------------------------- // third-party dependencies for (optional) plugins // ----------------------------------------------- // recorder.js 'node_modules/recorderjs/dist/recorder.js', // libvorbis.js 'node_modules/libvorbis.js/js/libvorbis.min.js', // lamejs {pattern: 'node_modules/lamejs/worker-example/*worker*.js', included: false, served: true}, 'node_modules/lamejs/lame.min.js', // opus-recorder {pattern: 'node_modules/opus-recorder/dist/*Worker.min.js', included: false, served: true}, {pattern: 'node_modules/opus-recorder/dist/*.wasm', included: false, served: true, type: 'wasm'}, 'node_modules/opus-recorder/dist/recorder.min.js', // opus-media-recorder {pattern: 'node_modules/opus-media-recorder/encoderWorker.umd.js', included: false, served: true}, {pattern: 'node_modules/opus-media-recorder/*.wasm', included: false, served: true, type: 'wasm'}, // vmsg {pattern: 'node_modules/vmsg/*.wasm', included: false, served: true, type: 'wasm'}, // web streams API polyfill to support Firefox (for webm-wasm) 'node_modules/@mattiasbuelens/web-streams-polyfill/dist/polyfill.min.js', // webm-wasm {pattern: 'node_modules/webm-wasm/dist/webm-worker.js', included: false, served: true}, {pattern: 'node_modules/webm-wasm/dist/webm-wasm.wasm', included: false, served: true, type: 'wasm'}, // ffmpeg.js {pattern: 'node_modules/ffmpeg.js/ffmpeg-worker-mp4.js', included: false, served: true}, // ffmpeg.wasm {pattern: 'node_modules/@ffmpeg/ffmpeg/dist/ffmpeg.min.js', included: false, served: true}, {pattern: 'node_modules/@ffmpeg/core/dist/ffmpeg-core.js', included: false, served: true}, // gif-recorder: only available on CDN 'https://cdn.webrtc-experiment.com/gif-recorder.js', // ------------------------------------------- // specs // ------------------------------------------- {pattern: 'test/**/*.spec.js', watched: false} ], // for CDN scripts crossOriginAttribute: false, proxies: { // necessary workaround for opus-recorder plugin '/encoderWorker.min.js': '/base/node_modules/opus-recorder/dist/encoderWorker.min.js', '/encoderWorker.min.wasm': '/base/node_modules/opus-recorder/dist/encoderWorker.min.wasm' }, mime: { 'application/wasm': ['wasm'] }, preprocessors: { 'test/**/*.spec.js': ['webpack'], // source files to generate coverage for, // do not include tests or libraries 'src/js/**/*.js': ['coverage'] }, webpackMiddleware: { stats: 'errors-only' }, plugins: [ 'karma-webpack', 'karma-jasmine', 'karma-jasmine-matchers', 'karma-chrome-launcher', 'karma-firefox-launcher', '@chiragrupani/karma-chromium-edge-launcher', 'karma-coverage', 'karma-verbose-reporter', 'karma-host-environment', 'karma-detect-browsers' ], detectBrowsers: { enabled: true, usePhantomJS: false, preferHeadless: true, postDetection: function(availableBrowsers) { if (availableBrowsers.length > 1) { // use custom browser launchers let result = availableBrowsers; let cr = availableBrowsers.indexOf('Chrome'); if (cr > -1) { availableBrowsers[cd] = 'Chrome_dev'; } let cd = availableBrowsers.indexOf('ChromeHeadless'); if (cd > -1) { availableBrowsers[cd] = 'Chrome_headless'; } let fd = availableBrowsers.indexOf('FirefoxHeadless'); if (fd > -1) { availableBrowsers[fd] = 'Firefox_headless'; } let fh = availableBrowsers.indexOf('Firefox'); if (fh > -1) { availableBrowsers[fh] = 'Firefox_dev'; } let ch = availableBrowsers.indexOf('ChromiumHeadless'); if (ch > -1) { availableBrowsers[ch] = 'Chromium_dev'; } let ce = availableBrowsers.indexOf('Chromium'); if (ce > -1) { availableBrowsers[ce] = 'Chromium_dev'; } // ignore IE let ie = availableBrowsers.indexOf('IE'); if (ie > -1) { availableBrowsers.splice(ie, 1); } // ignore Safari (until it's supported...) let safariTechPreview = availableBrowsers.indexOf('SafariTechPreview'); if (safariTechPreview > -1) { availableBrowsers.splice(safariTechPreview, 1); } let safari = availableBrowsers.indexOf('Safari'); if (safari > -1) { availableBrowsers.splice(safari, 1); } return result; } } }, captureConsole: true, concurrency: 1, browserSocketTimeout: 20000, browserDisconnectTimeout : 10000, browserDisconnectTolerance : 1, browserNoActivityTimeout : 60000, colors: true, reporters: ['verbose', 'progress', 'coverage'], coverageReporter: { dir: 'coverage', reporters: [ { type: 'html', subdir: 'html' }, { type: 'lcov', subdir: 'lcov' } ] }, webpack: webpackConfig, customLaunchers: { Chrome_dev: { base: 'Chrome', flags: chromeFlags, chromeDataDir: path.resolve(__dirname, '.chrome') }, Chrome_headless: { base: 'ChromeHeadless', flags: chromeFlags }, Chromium_dev: { base: 'ChromiumHeadless', flags: chromeFlags }, Firefox_dev: { base: 'Firefox', prefs: firefoxFlags }, Firefox_headless: { base: 'FirefoxHeadless', prefs: firefoxFlags }, Edge_dev: { base: 'Edge', flags: chromeFlags, chromeDataDir: path.resolve(__dirname, '.edge') }, Edge_headless: { base: 'EdgeHeadless', flags: chromeFlags, chromeDataDir: path.resolve(__dirname, '.edge') } } }; if (ci) { configuration.browsers = ['Firefox_headless', 'Chrome_headless']; configuration.singleRun = true; configuration.detectBrowsers.enabled = false; if (process.env.APPVEYOR) { configuration.browsers.push('Edge_headless'); } } config.set(configuration); };
// Imports var Entity = require('../entity'); // Utils var fillChar = function(data, char, fieldLength, rTL) { var result = data.toString(); if (rTL === true) { for (var i = result.length; i < fieldLength; i++) result = char.concat(result); } else { for (var i = result.length; i < fieldLength; i++) result = result.concat(char); } return result; }; function getTime(t) { t /= 1000; if (t <= 1) return "right now"; else if (t < 120) return "in " + t + " seconds"; else { var minutes = Math.round(t / 60), minCeil = Math.ceil(t / 60), minFloor = Math.floor(t / 60); if (minutes == minCeil) return "in a little under " + minutes + " minutes"; else return "in a little over " + minutes + " minutes"; } } function getTicks(i, d) { var t = d ? d : "s"; var m = isNaN(parseFloat(i)) ? 1 : parseFloat(i); switch (t) { case "d": return m * 86400000; break; case "h": return m * 3600000; break; case "m": return m * 60000; break; default: return m * 1000; break; } } function getDate(d) { return d.toISOString().replace(/T/, ' ').replace(/\..+/, ''); } function Commands() { this.list = { help: { f: function(gameServer, split) { console.log("[Help] ======================== HELP ======================"); console.log("[Help] <x> is a required field, [x] is an optional field."); gameServer.pluginHandler.onHelpCommand(); console.log("[Help] ===================================================="); }, name: "help", desc: "Shows all commands and their info", vars: "" }, addbot: { f: function(gameServer, split) { var add = parseInt(split[1]); if (isNaN(add)) { add = 1; // Adds 1 bot if user doesnt specify a number } for (var i = 0; i < add; i++) { setTimeout(gameServer.bots.addBot.bind(gameServer.bots), i); } console.log("[Console] Added " + add + " player bots"); }, name: "addbot", desc: "Adds a number of bots", vars: "[n]" }, kickbot: { f: function(gameServer, split) { var toRemove = parseInt(split[1]); if (isNaN(toRemove)) { toRemove = -1; // Kick all bots if user doesnt specify a number } var removed = 0; var i = 0; while (i < gameServer.clients.length && removed != toRemove) { if (typeof gameServer.clients[i].remoteAddress == 'undefined') { // if client i is a bot kick him var client = gameServer.clients[i].playerTracker; var len = client.cells.length; for (var j = 0; j < len; j++) { gameServer.removeNode(client.cells[0]); } client.socket.close(); removed++; } else i++; } if (toRemove == -1) console.log("[Console] Kicked all bots (" + removed + ")"); else if (toRemove == removed) console.log("[Console] Kicked " + toRemove + " bots"); else console.log("[Console] Only " + removed + " bots could be kicked"); }, name: "kickbot", desc: "Kicks a number of bots", vars: "[n]" }, /* TODO: Fix board and boardreset commands. board: { f: function(gameServer, split) { var newLB = []; for (var i = 1; i < split.length; i++) { if (split[i]) { newLB[i - 1] = split[i]; } else { newLB[i - 1] = " "; } } // Clears the update leaderboard function and replaces it with our own gameServer.gameMode.packetLB = 48; gameServer.gameMode.specByLeaderboard = false; gameServer.gameMode.updateLB = function(gameServer) { gameServer.leaderboard = newLB; }; console.log("[Console] Successfully changed leaderboard values"); } }, boardreset: { function(gameServer) { // Gets the current gamemode var gm = GameMode.get(gameServer.gameMode.ID); // Replace functions gameServer.gameMode.packetLB = gm.packetLB; gameServer.gameMode.updateLB = gm.updateLB; console.log("[Console] Successfully reset leaderboard"); } }, */ change: { f: function(gameServer, split) { var key = split[1]; var value = split[2]; // Check if int/float if (value.indexOf('.') != -1) { value = parseFloat(value); } else { value = parseInt(value); } if (typeof gameServer.config[key] != 'undefined') { gameServer.config[key] = value; console.log("[Console] Set " + key + " to " + value); } else { console.log("[Console] Invalid config value"); } }, name: "change", desc: "Temporarily changes a config value", vars: "<name> <value>" }, clear: { f: function() { process.stdout.write("\u001b[2J\u001b[0;0H"); }, name: "clear", desc: "Clears the console.", vars: "" }, color: { f: function(gameServer, split) { // Validation checks var id = parseInt(split[1]); if (isNaN(id)) { console.log("[Console] Please specify a valid player ID!"); return; } var color = { r: 0, g: 0, b: 0 }; color.r = Math.max(Math.min(parseInt(split[2]), 255), 0); color.g = Math.max(Math.min(parseInt(split[3]), 255), 0); color.b = Math.max(Math.min(parseInt(split[4]), 255), 0); // Sets color to the specified amount for (var i in gameServer.clients) { if (gameServer.clients[i].playerTracker.pID == id) { var client = gameServer.clients[i].playerTracker; client.setColor(color); // Set color for (var j in client.cells) { client.cells[j].setColor(color); } break; } } }, name: "color", desc: "Changes color of a player.", vars: "<id> <r> <g> <b>" }, exit: { f: function(gameServer, split) { console.log("[Console] Closing server..."); gameServer.socketServer.close(); gameServer.shutdownHandle(); }, name: "exit", desc: "Gracefully stops the server.", vars: "" }, quit: { f: function(gameServer, split) { gameServer.pluginHandler.executeCommand("exit", split); }, name: "quit", desc: "Alias for exit", vars: "" }, shutdown: { f: function(gameServer, split) { gameServer.pluginHandler.executeCommand("exit", split); }, name: "shutdown", desc: "Alias for exit", vars: "" }, restart: { f: function(gameServer, split) { if (split[1] == "schedule" || split[1] == "at" || split[1] == "when" || split[1] == "time" || split[1] == "set") { if (gameServer.restartAt) { console.log("[Restart] Restart scheduled at " + getDate(gameServer.restartScheduled)); console.log("[Restart] Restart will happen at " + getDate(gameServer.restartAt)); var remaining = (gameServer.restartAt - Date.now()); console.log("[Restart] Restart will happen " + getTime(remaining)); } else { console.log("[Console] Restart not scheduled"); } } else if (split[1] == "abort" || split[1] == "stop" || split[1] == "reset") { if (!gameServer.restartId) { console.log("[Restart] Restart not scheduled"); return; } clearTimeout(gameServer.restartId); console.log("[Restart] Restart has been stopped"); } else if (split[1] == "delay" || split[1] == "increase") { if (!gameServer.restartId) { console.log("[Restart] Restart not scheduled"); return; } var newRemaining = (gameServer.restartAt - Date.now()) + getTicks(split[2], split[3]); if (newRemaining < 1000) newRemaining = 1000; clearTimeout(gameServer.restartId); gameServer.restartHandle(newRemaining); console.log("[Console] Restart delayed and will happen " + getTime(newRemaining)); } else if (split[1] == "help" || split[1] == "?") { console.log("[Restart] Restart command is versatile and accepts many arguments.\n"); console.log(" Uses:"); console.log(" restart schedule"); console.log(" Shows if a restart is scheduled and time to restart if it is."); console.log(" Aliases: at, when, time, set\n"); console.log(" restart abort"); console.log(" Aborts restarting, if any."); console.log(" Aliases: stop, reset\n"); console.log(" restart delay [interval] [s/m/h/d]"); console.log(" Delays restarting for specified period, if any. Negative intervals will decrease the restart time. Unspecified interval will immediately stop the server."); console.log(" Aliases: increase\n"); console.log(" restart <timeout> [s/m/h/d]"); console.log(" Starts a restart."); } else if (!isNaN(parseFloat(split[1])) || split.length == 1) { if (gameServer.restartId) { console.log("[Restart] Restart already scheduled"); return; } var a = getTicks(split[1], split[2]); gameServer.restartHandle(a); console.log("[Restart] Restart scheduled for " + getTime(a) + "!"); } else console.log("[Restart] Couldn't parse command. Type in \"restart help\" for details."); }, name: "restart", desc: "Restarts the server without memory leaking.", vars: "[timeout/help] [s/m/h/d]" }, reset: { f: function(gameServer, split) { gameServer.pluginHandler.executeCommand("exit", split); }, name: "reset", desc: "Alias for restart", vars: "[timeout]" }, food: { f: function(gameServer, split) { var pos = { x: parseInt(split[1]), y: parseInt(split[2]) }; var mass = parseInt(split[3]); // Make sure the input values are numbers if (isNaN(pos.x) || isNaN(pos.y)) { console.log("[Console] Invalid coordinates"); return; } if (isNaN(mass)) mass = gameServer.config.foodStartMass; // Spawn var f = new Entity.Food(gameServer.getNextNodeId(), null, pos, mass, gameServer); f.setColor(gameServer.getRandomColor()); gameServer.addNode(f); gameServer.currentFood++; console.log("[Console] Spawned 1 food cell at (" + pos.x + " , " + pos.y + ")"); }, name: "food", desc: "Spawns a food pellet in the game.", vars: "<x> <y> [mass]" }, gamemode: { f: function(gameServer, split) { try { var n = parseInt(split[1]); var gm = gameServer.pluginHandler.gamemodes.retrieveGamemode(n); // If there is an invalid gamemode, the function will exit gameServer.gameMode.onChange(gameServer); // Reverts the changes of the old gamemode gameServer.gameMode = gm; // Apply new gamemode gameServer.gameMode.onServerInit(gameServer); // Resets the server console.log("[Game] Changed game mode to " + gameServer.gameMode.name); } catch (e) { console.log("[Console] Invalid game mode selected"); } }, name: "gamemode", desc: "Changes the gamemode.", vars: "<id>" }, kick: { f: function(gameServer, split) { var id = parseInt(split[1]); if (isNaN(id)) { console.log("[Console] Please specify a valid player ID!"); return; } for (var i in gameServer.clients) { if (gameServer.clients[i].playerTracker.pID == id) { var client = gameServer.clients[i].playerTracker; var len = client.cells.length; for (var j = 0; j < len; j++) { gameServer.removeNode(client.cells[0]); } client.socket.close(); console.log("[Console] Kicked " + client.name); break; } } }, name: "kick", desc: "Kicks a player by player ID.", vars: "<id>" }, kickall: { f: function(gameServer, split) { for (var i in gameServer.clients) { var client = gameServer.clients[i].playerTracker; var len = client.cells.length; for (var j = 0; j < len; j++) { gameServer.removeNode(client.cells[0]); } client.socket.close(); console.log("[Console] Kicked " + client.name); } }, name: "kickall", desc: "Kicks all players and bots in the game.", vars: "" }, kill: { f: function(gameServer, split) { var id = parseInt(split[1]); if (isNaN(id)) { console.log("[Console] Please specify a valid player ID!"); return; } var count = 0; for (var i in gameServer.clients) { if (gameServer.clients[i].playerTracker.pID == id) { var client = gameServer.clients[i].playerTracker; var len = client.cells.length; for (var j = 0; j < len; j++) { gameServer.removeNode(client.cells[0]); count++; } console.log("[Console] Removed " + count + " cells"); break; } } }, name: "kill", desc: "Removes player's cells from a game.", vars: "<id>" }, killall: { f: function(gameServer, split) { var count = 0; var len = gameServer.nodesPlayer.length; for (var i = 0; i < len; i++) { gameServer.removeNode(gameServer.nodesPlayer[0]); count++; } console.log("[Console] Removed " + count + " cells"); }, name: "killall", desc: "Removes all players from the game.", vars: "" }, mass: { f: function(gameServer, split) { // Validation checks var id = parseInt(split[1]); if (isNaN(id)) { console.log("[Console] Please specify a valid player ID!"); return; } var amount = Math.max(parseInt(split[2]), 9); if (isNaN(amount)) { console.log("[Console] Please specify a valid number"); return; } // Sets mass to the specified amount for (var i in gameServer.clients) { if (gameServer.clients[i].playerTracker.pID == id) { var client = gameServer.clients[i].playerTracker; for (var j in client.cells) { client.cells[j].mass = amount; } console.log("[Console] Set mass of " + client.name + " to " + amount); break; } } }, name: "mass", desc: "Sets player's cells' mass to specified number.", vars: "<id> <mass>" }, merge: { f: function(gameServer, split) { // Validation checks var id = parseInt(split[1]); var set = split[2]; if (isNaN(id)) { console.log("[Console] Please specify a valid player ID!"); return; } // Find client with same ID as player entered var client; for (var i = 0; i < gameServer.clients.length; i++) { if (id == gameServer.clients[i].playerTracker.pID) { client = gameServer.clients[i].playerTracker; break; } } if (!client) { console.log("[Console] Client is nonexistent!"); return; } if (client.cells.length == 1) { console.log("[Console] Client already has one cell!"); return; } // Set client's merge override var state; if (set == "true" || set == "yes" || set == "1") { client.mergeOverride = true; state = true; } else if (set == "false" || set == "no" || set == "0") { client.mergeOverride = false; state = false; } else { if (client.mergeOverride) { client.mergeOverride = false; } else { client.mergeOverride = true; } state = client.mergeOverride; } // Log if (state) console.log("[Console] Player " + id + " is now force merging"); else console.log("[Console] Player " + id + " isn't force merging anymore"); }, name: "merge", desc: "Toggles or sets force merging on player.", vars: "<id> [state]" }, name: { f: function(gameServer, split) { // Validation checks var id = parseInt(split[1]); if (isNaN(id)) { console.log("[Console] Please specify a valid player ID!"); return; } var name = split.slice(2, split.length).join(' '); if (name == undefined) { console.log("[Console] Please type a valid name"); return; } // Change name for (var i = 0; i < gameServer.clients.length; i++) { var client = gameServer.clients[i].playerTracker; if (client.pID == id) { console.log("[Console] Changing " + client.name + " to " + name); client.name = name; return; } } // Error console.log("[Console] Player " + id + " was not found"); }, name: "name", desc: "Changes the name of a player.", vars: "<id> <name>" }, playerlist: { f: function(gameServer, split) { console.log("[Console] Showing " + gameServer.clients.length + " players: "); console.log(" ID | IP | " + fillChar('NICK', ' ', gameServer.config.playerMaxNickLength) + " | CELLS | SCORE | POSITION "); // Fill space console.log(fillChar('', '-', ' ID | IP | | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength)); for (var i = 0; i < gameServer.clients.length; i++) { var client = gameServer.clients[i].playerTracker; // ID with 3 digits length var id = fillChar((client.pID), ' ', 10, true); // Get ip (15 digits length) var ip = "Bot"; if (typeof gameServer.clients[i].remoteAddress != 'undefined') { ip = gameServer.clients[i].remoteAddress; } ip = fillChar(ip, ' ', 15); // Get name and data var nick = '', cells = '', score = '', position = '', data = ''; if (client.spectate) { try { nick = gameServer.largestClient.name; } catch (e) { // Specating in free-roam mode nick = "in free-roam"; } nick = (nick == "") ? "An unnamed cell" : nick; data = fillChar("Spectating " + nick, '-', ' | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength, true); console.log(" " + id + " | " + ip + " | " + data); } else if (client.cells.length > 0) { nick = fillChar((client.name == "") ? "An unnamed cell" : client.name, ' ', gameServer.config.playerMaxNickLength); cells = fillChar(client.cells.length, ' ', 5, true); score = fillChar(client.getScore(true), ' ', 6, true); position = fillChar(client.centerPos.x >> 0, ' ', 5, true) + ', ' + fillChar(client.centerPos.y >> 0, ' ', 5, true); console.log(" " + id + " | " + ip + " | " + nick + " | " + cells + " | " + score + " | " + position); } else { // No cells = dead player or in-menu data = fillChar('Dead or not playing', '-', ' | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength, true); console.log(" " + id + " | " + ip + " | " + data); } } }, name: "playerlist", desc: "Shows info about players.", vars: "" }, pause: { f: function(gameServer, split) { gameServer.run = !gameServer.run; // Switches the pause state var s = gameServer.run ? "Unpaused" : "Paused"; console.log("[Console] " + s + " the game."); }, name: "pause", desc: "Toggles pause of the game.", vars: "" }, reload: { f: function(gameServer) { gameServer.loadConfig(); console.log("[Console] Reloaded the config file successfully"); }, name: "reload", desc: "Reloads the configuration file.", vars: "" }, resetantiteam: { f: function(gameServer, split) { // Validation checks var id = parseInt(split[1]); if (isNaN(id)) { console.log("[Console] Please specify a valid player ID!"); return; } for (var i in gameServer.clients) { var client = gameServer.clients[i]; if (!client) continue; // Nonexistent if (client.playerTracker.pID == id) { // Found client client.playerTracker.massGainMult = 0; client.playerTracker.massLossMult = 0; console.log("[Console] Successfully reset client's anti-team effect"); return; } } }, name: "resetantiteam", desc: "Resets anti-teaming effect on a player.", vars: "<id>" }, status: { f: function(gameServer, split) { // Get amount of humans/bots var humans = 0, bots = 0; for (var i = 0; i < gameServer.clients.length; i++) { if ('_socket' in gameServer.clients[i]) { humans++; } else { bots++; } } console.log("[Console] Connected players: " + gameServer.clients.length + "/" + gameServer.config.serverMaxConnections); console.log("[Console] Players: " + humans + " - Bots: " + bots); console.log("[Console] Server has been running for " + Math.floor(process.uptime() / 60) + " minutes"); console.log("[Console] Current memory usage: " + Math.round(process.memoryUsage().heapUsed / 1048576 * 10) * 0.1 + "/" + Math.round(process.memoryUsage().heapTotal / 1048576 * 10) * 0.1 + " mb"); console.log("[Console] Current game mode: " + gameServer.gameMode.name); console.log("[Console] Node amount: " + gameServer.nodes.length + ", quadtree node amount: " + gameServer.quadTree.getNodes().length + ", branch count: " + gameServer.quadTree.getBranches()); console.log("[Console] Running " + (gameServer.internalClock - gameServer.lastUpdate) + " ticks behind"); }, name: "status", desc: "Gives status about the server.", vars: "" }, delay: { f: function(gameServer, split) { gameServer.internalClock += 2000; }, name: "delay", desc: "Lags the game.", vars: "" }, debug: { f: function(gameServer, split) { console.log(gameServer.updateLog); console.log(gameServer.nodes.length + " nodes, " + gameServer.quadTree.getNodes().length + " in quad"); }, name: "debug", desc: "Gives debug information.", vars: "" }, tp: { f: function(gameServer, split) { var id = parseInt(split[1]); if (isNaN(id)) { console.log("[Console] Please specify a valid player ID!"); return; } // Make sure the input values are numbers var pos = { x: parseInt(split[2]), y: parseInt(split[3]) }; if (isNaN(pos.x) || isNaN(pos.y)) { console.log("[Console] Invalid coordinates"); return; } // Spawn for (var i in gameServer.clients) { if (gameServer.clients[i].playerTracker.pID == id) { var client = gameServer.clients[i].playerTracker; for (var j in client.cells) { client.cells[j].position.x = pos.x; client.cells[j].position.y = pos.y; } console.log("[Console] Teleported " + client.name + " to (" + pos.x + " , " + pos.y + ")"); break; } } }, name: "tp", desc: "Teleports a player to specified coordinates", vars: "<id> <x> <y>", }, virus: { f: function(gameServer, split) { var pos = { x: parseInt(split[1]), y: parseInt(split[2]) }; var mass = parseInt(split[3]); // Make sure the input values are numbers if (isNaN(pos.x) || isNaN(pos.y)) { console.log("[Console] Invalid coordinates"); return; } if (isNaN(mass)) { mass = gameServer.config.virusStartMass; } // Spawn var v = new Entity.Virus(gameServer.getNextNodeId(), null, pos, mass); gameServer.addNode(v); console.log("[Console] Spawned 1 virus at (" + pos.x + " , " + pos.y + ")"); }, name: "virus", desc: "Spawns a virus at given coordinates.", vars: "<x> <y> [mass]" }, //Aliases st: { f: function (gameServer, split) { gameServer.pluginHandler.executeCommand("status", split); }, name: "st", desc: "Alias for status.", vars: "" }, pl: { f: function (gameServer, split) { gameServer.pluginHandler.executeCommand("playerlist", split); }, name: "pl", desc: "Alias for playerlist.", vars: "" }, }; } module.exports = Commands;
version https://git-lfs.github.com/spec/v1 oid sha256:8dab13cd84b3c528037755762df99084451664baa1c87b6b0c9cd81d547fac00 size 39149
version https://git-lfs.github.com/spec/v1 oid sha256:cc9206eb96354984cfaaece07ee4ce59c3d753ea120208abe0ee5626ad8621fe size 2958
version https://git-lfs.github.com/spec/v1 oid sha256:d332f13e7f0b16ef6915ebf6faeb3c55a9fa54c5828092777166a289835bcd2a size 846
var TouchendBtn = require('../../../lib/touch/default/touchend-button'), Q = require('q'), expect = require('expect.js'), initElement = function () { var el = document.createElement('div'); el.style.width = '100px'; el.style.height = '100px'; el.style.position = 'absolute'; el.style.zIndex = '100'; el.style.top = 0; el.style.left = 0; window.document.body.appendChild(el); return el; }; describe('default/TouchendButton', function () { it('must be an function', function () { expect(TouchendBtn).to.be.an('function'); }); describe('instance', function () { it('should raise an Error when calling .bind() if already binded', function () { var btn = new TouchendBtn({ el : initElement(), f : function () { } }); expect(function () { btn.bind(); }).to.throwException("Can't bind an already binded button."); }); it('should raise an Error when calling .unbind() if unbinded', function () { var btn = new TouchendBtn({ el : initElement(), f : function () { } }); btn.unbind(); expect(function () { btn.unbind(); }).to.throwException("Can't unbind a unbinded button."); }); it('should have a setActiveBorder method', function () { var btn = new TouchendBtn({ el : initElement(), f : function () { } }); expect(btn.setActiveBorder).to.be.an('function'); }); it('can not be activated if already activated', function (done) { var i = 0, btn = new TouchendBtn({ el : initElement(), f : function () { i = i+1; return Q.delay(200); } }); // first fake activation btn.onTouchstart({ changedTouches:[{ identifier : 0 }] }); btn.onTouchend({ changedTouches:[{ identifier : 0 }] }); setTimeout(function () { // second activation while the first is not done btn.onTouchstart({ changedTouches:[{ identifier : 1 }] }); btn.onTouchend({ changedTouches:[{ identifier : 1 }] }); },50); setTimeout(function () { expect(i).to.be(1); done(); },300); }); it('should add the `.active` css class on the underlying DOM element when touched', function (done) { var btn = new TouchendBtn({ el : initElement(), f : function () { return Q.delay(200); } }); // fake activation btn.onTouchstart({ changedTouches:[{ identifier : 0 }] }); expect(btn.el.classList.contains('active')).to.be(true); btn.onTouchend({ changedTouches:[{ identifier : 0 }] }); done(); }); it('should remove the `.active` css class on the underlying DOM element after being touched', function (done) { var btn = new TouchendBtn({ el : initElement(), f : function () { return Q.delay(100); } }); // fake activation btn.onTouchstart({ changedTouches:[{ identifier : 0 }] }); btn.onTouchend({ changedTouches:[{ identifier : 0 }] }); expect(btn.el.classList.contains('active')).to.be(false); done(); }); it('.bind should return the button', function () { var btn = new TouchendBtn({ el : initElement(), f : function () { }, autobind: false }); expect(btn.bind()).to.be.equal(btn); }); it('.unbind should return the button', function () { var btn = new TouchendBtn({ el : initElement(), f : function () { }, autobind: false }); expect(btn.bind().unbind()).to.be.equal(btn); }); }); });
// Generated by CoffeeScript 1.8.0 var BITSTR, DERNULL, INTERGER, OID, PRTSTR, SEQUENCE, SET, TAG, UTF8STR, asn1Util, cryptoUtil, generateCSR, generateKeyPair, j, keyUtil, onmessage; postMessage({ type: 'status', message: 'Importing JSRSASign library ...' }); importScripts('jsrsasign-4.7.0-all-min.js'); j = KJUR; keyUtil = KEYUTIL; asn1Util = j.asn1.ASN1Util; cryptoUtil = j.crypto.Util; SEQUENCE = function(arr) { return new j.asn1.DERSequence({ 'array': arr }); }; SET = function(arr) { return new j.asn1.DERSet({ 'array': arr }); }; INTERGER = function(num) { return new j.asn1.DERInteger({ 'int': num }); }; PRTSTR = function(str) { return new j.asn1.DERPrintableString({ 'str': str }); }; UTF8STR = function(str) { return new j.asn1.DERUTF8String({ 'str': str }); }; BITSTR = function(hex) { return new j.asn1.DERBitString({ 'hex': hex }); }; OID = function(oid) { return j.asn1.x509.OID.name2obj(oid); }; TAG = function(tag) { return new j.asn1.DERTaggedObject({ 'tag': tag || 'a0' }); }; DERNULL = function() { return new j.asn1.DERNull(); }; generateKeyPair = function(len) { var keyPair, privateKeyHex, privateKeyObj, privateKeyPEM, publicKeyHex, publicKeyObj, publicKeyPEM, ret, tbl; ret = {}; tbl = [324, 588]; keyPair = keyUtil.generateKeypair("RSA", len); privateKeyObj = ret.privateKeyObj = keyPair.prvKeyObj; publicKeyObj = ret.publicKeyObj = keyPair.pubKeyObj; privateKeyObj.isPrivate = true; privateKeyPEM = ret.privateKeyPEM = keyUtil.getPEM(privateKeyObj, "PKCS8PRV"); privateKeyHex = ret.privateKeyHex = keyUtil.getHexFromPEM(privateKeyPEM, "PRIVATE KEY"); publicKeyPEM = ret.publicKeyPEM = keyUtil.getPEM(publicKeyObj); publicKeyHex = ret.publicKeyHex = keyUtil.getHexFromPEM(publicKeyPEM, "PUBLIC KEY"); if (tbl.indexOf(ret.publicKeyHex.length) === -1) { return false; } return ret; }; generateCSR = function(data, keyPair, alg) { var certificateRequestInfo, sig; alg = alg || 'SHA256withRSA'; certificateRequestInfo = SEQUENCE([INTERGER(0), SEQUENCE([SET([SEQUENCE([OID("countryName"), PRTSTR(data.countryName)])]), SET([SEQUENCE([OID("stateOrProvinceName"), UTF8STR(data.stateOrProvinceName)])]), SET([SEQUENCE([OID("locality"), UTF8STR(data.locality)])]), SET([SEQUENCE([OID("organization"), UTF8STR(data.organization)])]), SET([SEQUENCE([OID("commonName"), UTF8STR(data.commonName)])])]), new j.asn1.x509.SubjectPublicKeyInfo(keyPair.publicKeyObj), TAG()]); sig = new j.crypto.Signature({ alg: alg }); sig.init(keyPair.privateKeyPEM); sig.updateHex(certificateRequestInfo.getEncodedHex()); return SEQUENCE([certificateRequestInfo, SEQUENCE([OID(alg), DERNULL()]), BITSTR('00' + sig.sign())]); }; onmessage = function(e) { var CSR, CSRPEM, data, keyPair; data = e.data.workload; postMessage({ type: 'status', message: 'Generating private key ...' }); keyPair = false; while (1) { keyPair = generateKeyPair(parseInt(data.keySize)); if (keyPair === false) { postMessage({ type: 'status', message: 'Regenerating private key ...' }); } else { break; } } postMessage({ type: 'status', message: 'Generating CSR ...' }); CSR = generateCSR(data, keyPair, "SHA256withRSA"); postMessage({ type: 'status', message: 'Converting CSR to PEM format ...' }); CSRPEM = asn1Util.getPEMStringFromHex(CSR.getEncodedHex(), "CERTIFICATE REQUEST"); postMessage({ type: 'private', pem: keyPair.privateKeyPEM }); postMessage({ type: 'csr', pem: CSRPEM }); return postMessage({ type: 'done' }); };
$(document).ready(function () { $(document).on('click', '.loading', function () { var btn = $(this); btn.button('loading'); setTimeout(function () { btn.button('reset') }, 5000); }); });
// Generated by CoffeeScript 1.6.3 (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; define(['backbone', 'underscore', 'jquery', 'leaflet'], function(Backbone, _, $) { var RouteMapDetailView, _ref; RouteMapDetailView = (function(_super) { __extends(RouteMapDetailView, _super); function RouteMapDetailView() { _ref = RouteMapDetailView.__super__.constructor.apply(this, arguments); return _ref; } RouteMapDetailView.prototype.el = '.map-block'; RouteMapDetailView.prototype.initialize = function() { return this.render(); }; RouteMapDetailView.prototype.render = function() { var layer, map, vectorData, vectorLayer; this.$el.html('<div id="map"></div>'); map = new L.Map('map'); layer = L.tileLayer('http://{s}.tile.cloudmade.com/9d0b97ba4e6d403aad532091aaafbc0b/997/256/{z}/{x}/{y}.png', { attribution: 'Cloudmade', maxZoom: 18 }); layer.addTo(map); vectorData = { type: 'Feature', geometry: this.model.get('st_asgeojson') }; vectorLayer = L.geoJson(); vectorLayer.addTo(map); vectorLayer.addData(vectorData); console.log(vectorLayer.getBounds()); return map.fitBounds(vectorLayer.getBounds()); }; return RouteMapDetailView; })(Backbone.View); return RouteMapDetailView; }); }).call(this);
'use strict'; // TODO: best name? Better to call it Helpers? Utils is already taken var Core = function () {}; Core.prototype.reserved = function (name) { return (name && name.length >= 1 && name.charAt(0) === '$') ? true : false; }; module.exports = new Core();
/** * @ngdoc directive * @name ui.controls.uiIcon * @description * * uiIcon is used to render font icons. When uiIcon is placed inside a uiButton or uiToolbar it adjusts it's size to * match it's parent size. * * @param {string} name The name of the font icon. * * @restrict E * @example <example module="ui"> <file name="index.html"> <ui-icon name="fa-home"></ui-icon> </file> </example> */ (function (app) { app.directive('uiIcon', [ '$uiSize', function (/** UI.Size */$uiSize) { /** * @param {angular.IScope} scope * @param {Array.<Element>} el * @param {$compile.directive.Attributes} attr * @param {ui.components.uiHeight.Controller} $uiHeight */ function _link(scope, el, attr, $uiHeight) { var $el = angular.element(el); $el.addClass('ui-icon'); scope.$watch('name', function (value) { // using font-awesome if (_.startsWith(value, 'fa-')) { $el.addClass('fa'); $el.addClass(value); return; } // using Material Icons el.addClass('material-icons'); el.text(value); }); if(!$uiHeight) { $el.addClass('ui-height-md'); return; } $uiHeight.setHeight($el); if($uiHeight.getHeight() === 'sd' && $uiHeight.getParentHeight() === 'md') { $el.addClass('ui-fit-md'); } } return { restrict: 'E', require: '?^uiHeight', scope: { name: '@' }, link: _link, controller: '$uiSizeController' } }]); })(angular.module('thinkingmedia.ui.controls'));
var ViewAbstract = function () { this.initialited = false; this.$viewContainer = null; }; ViewAbstract.prototype.setViewContainer = function($viewContainer) { this.$viewContainer = $viewContainer; return this; }; ViewAbstract.prototype.getViewContainer = function() { return this.$viewContainer; }; ViewAbstract.prototype.setController = function(controller) { this.controller = controller; return this; }; ViewAbstract.prototype.getController = function() { return this.controller; }; ViewAbstract.prototype.setInitialized = function(state) { this.initialited = state; return this; }; ViewAbstract.prototype.getInitialized = function() { return this.initialited; }; /** * Called, when contructed */ ViewAbstract.prototype.onInit = function() { console.log('INIT'); }; /** * called when view is open */ ViewAbstract.prototype.onOpen = function() { console.log('OPENED'); }; /** * called when view is closed */ ViewAbstract.prototype.onClose = function() { console.log('CLOSED'); }; console.log('ViewAbstract', ViewAbstract);
//= require jquery/jquery //= require raphael //= require_tree . $(document).ready(function(){ function arcs(id,n,type,mod,size){ var top = $(id).position().top; var height = $(id).height(); var width = $(id).width(); var center = width/2; var R = 100; var paper = Raphael(0, top, width, height); xmod = 0; for (i = 0; i < n; i++) { var xmod = xmod + mod; switch(type) { case 1: var startx = center+xmod; var starty = height+xmod; var spin = -90; var angle = 90; var elx = size-(xmod*4); var ely = size+(size*0.25)-(xmod*4); var dir = 1; var quad = 1; break; case 2: var startx = 0; var starty = height/2+xmod; var spin = -90; var angle = 90; var elx = size-xmod*4; var ely = size+(size*0.25)-(xmod*4); var dir = 0; var quad = 1; break; case 3: var startx = center+xmod; var starty = height+xmod; var spin = 90; var angle = 90; var elx = size-(xmod*4); var ely = size+(size*0.25)-(xmod*4); var dir = 0; var quad = 1; break; case 4: var startx = center+xmod; var starty = -(height/2); var spin = 90; var angle = 180; var elx = size-xmod*4; var ely = size+(size*0.25)-(xmod*4); var dir = 1; var quad = 1; break; default: var startx = center+xmod; var starty = height+xmod; break; } var path_string = ['m', startx, starty, 'a', elx, ely, 3, quad, dir, spin, angle]; var arcs = paper.path(path_string); arcs.attr("stroke", "#4babe0"); arcs.toBack(); }; }; // ElementID , number of arcs, arctype, offset, size // TODO: ADD RESIZE EVENT var a = arcs('#overview',5,1,15,1500); var a = arcs('#overview',5,2,30,2500); var a = arcs('#overview',5,3,15,2000); var a = arcs('#overview',5,4,15,1000); });
angular.module('ps.core.service') .service('dataTranslationService', function(i18n) { 'use strict'; var s = this; s.translate = translate; s.setStorageDataLabels = setStorageDataLabels; function translate(data) { angular.forEach(data, function(value, key) { switch (key) { case 'widgets': value = translateWidgets(value); break; case 'layout': value = translateLayout(value); break; default: } }); return data; } function translateLayout(data) { angular.forEach(data, function(value) { value.title = i18n.get('c_l_' + value.label); }); return data; } function translateWidgets(data) { angular.forEach(data, function(value, key) { value.title = i18n.get('w_' + key); value.help = i18n.get('w_' + key + '_help'); }); return data; } function setStorageDataLabels(data) { var i = 0; angular.forEach(data, function(value, key) { switch (key) { case 'layout': case 'badgeLayout': case 'styles': value.title = i18n.get('c_o_' + key); value.order = -1; i++; break; default: if (i18n.get('w_' + key) !== '') { value.title = i18n.get('w_' + key); value.order = +1; i++; } } }); return data; } });
var expect = require('chai').expect; var errors = require('../lib/Errors'); describe('Errors', function() { it('maps status codes to custom errors', function() { var unauthorized = errors('401'); expect(unauthorized.name).to.eq('Error'); expect(unauthorized.type).to.eq('AuthenticationError'); expect(unauthorized.message).to.eq(undefined); expect(unauthorized.stack).to.be.a('string'); var unacceptable = errors('406', 'foo'); expect(unauthorized.name).to.eq('Error'); expect(unacceptable.type).to.eq('UnsupportedFormatRequestedError'); expect(unacceptable.message).to.eq('foo'); expect(unauthorized.stack).to.be.a('string'); var rateLimited = errors('429', 'foo', { retryAfter: 5 }); expect(rateLimited.name).to.eq('Error'); expect(rateLimited.type).to.eq('TooManyRequestsError'); expect(rateLimited.message).to.eq('foo'); expect(rateLimited.stack).to.be.a('string'); expect(rateLimited.retryAfter).to.eq(5); }); });
'use strict'; describe('Unit Test', function() { beforeEach(module('appServices', 'serviceMocks')); describe('Services', function(){ var Github; var httpBackend; var scope; beforeEach(inject(function(_Github_, $httpBackend, $rootScope) { Github = _Github_; scope = $rootScope.$new(); httpBackend = $httpBackend; })); afterEach(function() { httpBackend.verifyNoOutstandingExpectation(); httpBackend.verifyNoOutstandingRequest(); }); it('should have all the required methods', function(){ expect(angular.isFunction(Github.getUser)).toBe(true); expect(angular.isFunction(Github.getRepos)).toBe(true); expect(angular.isFunction(Github.getIssues)).toBe(true); expect(angular.isFunction(Github.getWatchers)).toBe(true); }); describe('getUser', function() { var userResponse; beforeEach(inject(function(userMock) { userResponse = userMock; httpBackend.whenJSONP('https://api.github.com/users/angular?callback=JSON_CALLBACK').respond(userResponse); })); afterEach(function(){ httpBackend.flush(); scope.$root.$digest(); }); it('should return angular', function(){ Github.getUser('angular').$promise.then(function(response) { expect(response.data.login).toEqual('angular'); }); }); it('should return a number of public repos', function(){ Github.getUser('angular').$promise.then(function(response) { expect(response.data.public_repos).toBeGreaterThan(50); }); }); }); describe('getRepos', function(){ var reposResponse; beforeEach(inject(function(reposMock) { reposResponse = reposMock; httpBackend.whenJSONP('https://api.github.com/users/angular/repos?callback=JSON_CALLBACK').respond(reposResponse); })); afterEach(function(){ httpBackend.flush(); }); it('should return multiple repos', function(){ Github.getRepos('angular').$promise.then(function(response) { expect(response.data).not.toBeNull(); }); }); it('should return angular/angular for sure', function(){ Github.getRepos('angular').$promise.then(function(response) { expect(response.data[0].id).toEqual(24195339); expect(response.data[0].full_name).toEqual('angular/angular'); }); }); }); describe('getIssues', function(){ var issuesResponse; beforeEach(inject(function(issuesMock) { issuesResponse = issuesMock; httpBackend.whenJSONP('https://api.github.com/repos/angular/angular/issues?callback=JSON_CALLBACK').respond(issuesResponse); })); afterEach(function(){ httpBackend.flush(); }); it('should return multiple issues', function(){ Github.getIssues('angular', 'angular').$promise.then(function(response) { expect(response.data).not.toBeNull(); }); }); it('should return issue 492', function(){ Github.getIssues('angular', 'angular').$promise.then(function(response) { expect(response.data[0].number).toEqual(492); expect(response.data[0].title).toEqual(jasmine.any(String)); }); }); }); describe('getWatcherss', function(){ var watchersResponse; beforeEach(inject(function(watchersMock) { watchersResponse = watchersMock; httpBackend.whenJSONP('https://api.github.com/repos/angular/angular/subscribers?callback=JSON_CALLBACK').respond(watchersResponse); })); afterEach(function(){ httpBackend.flush(); }); it('should return multiple watchers', function(){ Github.getWatchers('angular', 'angular').$promise.then(function(response) { expect(response.data).not.toBeNull(); }); }); it('should return watcher chirayuk', function(){ Github.getWatchers('angular', 'angular').$promise.then(function(response) { expect(response.data[0].login).toEqual('chirayuk'); }); }); }); }); });
var cron = require('./lib/cron'); cron.aliases(require('./lib/aliases.json')); /** * I have always hated these little individual files, literally taking one file and re-exporting it * Turns out, in this situation it's needed, due to the way node require's modules * * Take two files: "cronfile" and "./lib/cron.js" * With package.json, "cronfile" => "./lib/cron.js", easy * But then referring it internally, "../lib/cron", doesn't work since "cronfile" has been cached somewhere else * So to get around that, we have to force node to cache our actual cron lib as a file, not a module */ module.exports = cron;
window.onload = function() { var prod_img = document.getElementById("prod_img"); // Set an interval o keep rotating the image every 256 milliseconds setInterval(function(){ prod_img.src = getImageSrc(); },1000); var imgIndex = 1; function getImageSrc() { imgIndex = (imgIndex + 1) > 5? 1 : imgIndex + 1; return imgIndex + ".jpeg"; } var home = document.getElementById("pic"); var details = document.getElementById("inf"); var review = document.getElementById("rev"); document.getElementById("home").onclick = function() { home.style.display = "block"; details.style.display = "none"; review.style.display = "none"; } document.getElementById("details").onclick = function() { home.style.display = "none"; details.style.display = "block"; review.style.display = "none"; } document.getElementById("review").onclick = function() { home.style.display = "none"; details.style.display = "none"; review.style.display = "block"; } }
/* globals window, _, VIZI, THREE */ (function() { "use strict"; /** * Blueprint debug circles output * @author Robin Hawkes - vizicities.com * @author Edward Oliver Greer - eogreer.me */ // output: { // type: "BlueprintOutputDebugCircles", // options: {} // } VIZI.BlueprintOutputDebugCircles = function(options) { var self = this; VIZI.BlueprintOutput.call(self, options); _.defaults(self.options, {}); // Triggers and actions reference self.triggers = [ {name: "initialised", arguments: []} ]; self.actions = [ {name: "outputCircles", arguments: ["data"]} ]; self.world; }; VIZI.BlueprintOutputDebugCircles.prototype = Object.create( VIZI.BlueprintOutput.prototype ); // Initialise instance and start automated processes VIZI.BlueprintOutputDebugCircles.prototype.init = function() { var self = this; self.emit("initialised"); }; // { // coordinates: [lon, lat], // distance: 123 // } VIZI.BlueprintOutputDebugCircles.prototype.outputCircles = function(data) { var self = this; var material = new THREE.MeshBasicMaterial({ color: 0xff0000, }); if (self.options.opacity) { material.opacity = self.options.opacity; material.transparent = true; } var geom; // = new THREE.CircleGeometry(); // Local pixels per meter - set once per tile var pixelsPerMeter; _.each(data, function(point) { var latLon = new VIZI.LatLon(point.coordinates[1], point.coordinates[0]); var geoCoord = self.world.project(latLon); // Set local pixels per meter if not set if (pixelsPerMeter === undefined) { pixelsPerMeter = self.world.pixelsPerMeter(latLon); } // TODO: Get this from options var height = 50; var radius = 100; var segments = 32; // Multiply height in meters by pixels per meter ratio at latitude height *= pixelsPerMeter.y; geom = new THREE.CircleGeometry(radius, segments); geom.vertices.push(new THREE.Vector3( geoCoord.x, height, geoCoord.y )); }); var circle = new THREE.Mesh( geom, material ); circle.rotateX(-90*(Math.PI/180)); circle.position.y = 100; self.add(circle); }; VIZI.BlueprintOutputDebugCircles.prototype.onAdd = function(world) { var self = this; self.world = world; self.init(); }; }());
"use strict"; var gulp = require("gulp"); var cfg = require("../../../gulp.config"); function serve() { try { var browserSync = require("browser-sync").create(); gulp.task("build:sync", ["build"], browserSync.reload); gulp.task("serve", function (done) { browserSync.init({ server: "./" }); var opts = { interval: 100, debounceDelay: 500, mode: 'auto', cwd: process.cwd() }; // When emails, styles or components are compiled we reload the browser gulp.watch([ cfg.src.emails.base + "/**/*.js", cfg.styles + "/**/*.*", cfg.src.components.base + "/**/*.js"], opts, ["build:sync"]); }); } catch (error) { console.warn([ "WARN: browser-sync not insalled.", "Run 'npm install browser-sync --save-dev' to activate the 'serve' gulp task.", "Windows see http://www.browsersync.io/docs/#windows-users"].join("\n")); } } module.exports = serve;
/*global jQuery,alert*/ this.mytodo = (function (mytodo) { mytodo.MyTodoView = function () { var self, newTodoItemView, todoListView, eventBus, myTodoService; self = this; eventBus = new mytodo.EventBus(); myTodoService = new mytodo.MyTodoService(); todoListView = new mytodo.TodoListView(eventBus, myTodoService); newTodoItemView = new mytodo.NewTodoItemView(eventBus, myTodoService); eventBus.onError(function (message) { alert(message); }); self.init = function () { todoListView.init(); newTodoItemView.init(); }; }; return mytodo; }(this.mytodo || {}));
window.Mobi = window.Mobi || {}; window.Mobi.View = Backbone.View.extend({ delegateEvents: function(events) { var key, newKey, oldValue; this.events = this.events || events; for (key in this.events) { if (key.indexOf('click') === 0) { if (window.Modernizr.touch) { newKey = key.replace('click', 'touchend'); oldValue = this.events[key]; this.events[newKey] = oldValue; delete this.events[key]; } } } return Backbone.View.prototype.delegateEvents.call(this, this.events); } });
/*! localForage -- Offline Storage, Improved Version 1.4.2 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ (function (global){ 'use strict'; var Mutation = global.MutationObserver || global.WebKitMutationObserver; var scheduleDrain; { if (Mutation) { var called = 0; var observer = new Mutation(nextTick); var element = global.document.createTextNode(''); observer.observe(element, { characterData: true }); scheduleDrain = function () { element.data = (called = ++called % 2); }; } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') { var channel = new global.MessageChannel(); channel.port1.onmessage = nextTick; scheduleDrain = function () { channel.port2.postMessage(0); }; } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) { scheduleDrain = function () { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var scriptEl = global.document.createElement('script'); scriptEl.onreadystatechange = function () { nextTick(); scriptEl.onreadystatechange = null; scriptEl.parentNode.removeChild(scriptEl); scriptEl = null; }; global.document.documentElement.appendChild(scriptEl); }; } else { scheduleDrain = function () { setTimeout(nextTick, 0); }; } } var draining; var queue = []; //named nextTick for less confusing stack traces function nextTick() { draining = true; var i, oldQueue; var len = queue.length; while (len) { oldQueue = queue; queue = []; i = -1; while (++i < len) { oldQueue[i](); } len = queue.length; } draining = false; } module.exports = immediate; function immediate(task) { if (queue.push(task) === 1 && !draining) { scheduleDrain(); } } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],2:[function(_dereq_,module,exports){ 'use strict'; var immediate = _dereq_(1); /* istanbul ignore next */ function INTERNAL() {} var handlers = {}; var REJECTED = ['REJECTED']; var FULFILLED = ['FULFILLED']; var PENDING = ['PENDING']; module.exports = exports = Promise; function Promise(resolver) { if (typeof resolver !== 'function') { throw new TypeError('resolver must be a function'); } this.state = PENDING; this.queue = []; this.outcome = void 0; if (resolver !== INTERNAL) { safelyResolveThenable(this, resolver); } } Promise.prototype["catch"] = function (onRejected) { return this.then(null, onRejected); }; Promise.prototype.then = function (onFulfilled, onRejected) { if (typeof onFulfilled !== 'function' && this.state === FULFILLED || typeof onRejected !== 'function' && this.state === REJECTED) { return this; } var promise = new this.constructor(INTERNAL); if (this.state !== PENDING) { var resolver = this.state === FULFILLED ? onFulfilled : onRejected; unwrap(promise, resolver, this.outcome); } else { this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); } return promise; }; function QueueItem(promise, onFulfilled, onRejected) { this.promise = promise; if (typeof onFulfilled === 'function') { this.onFulfilled = onFulfilled; this.callFulfilled = this.otherCallFulfilled; } if (typeof onRejected === 'function') { this.onRejected = onRejected; this.callRejected = this.otherCallRejected; } } QueueItem.prototype.callFulfilled = function (value) { handlers.resolve(this.promise, value); }; QueueItem.prototype.otherCallFulfilled = function (value) { unwrap(this.promise, this.onFulfilled, value); }; QueueItem.prototype.callRejected = function (value) { handlers.reject(this.promise, value); }; QueueItem.prototype.otherCallRejected = function (value) { unwrap(this.promise, this.onRejected, value); }; function unwrap(promise, func, value) { immediate(function () { var returnValue; try { returnValue = func(value); } catch (e) { return handlers.reject(promise, e); } if (returnValue === promise) { handlers.reject(promise, new TypeError('Cannot resolve promise with itself')); } else { handlers.resolve(promise, returnValue); } }); } handlers.resolve = function (self, value) { var result = tryCatch(getThen, value); if (result.status === 'error') { return handlers.reject(self, result.value); } var thenable = result.value; if (thenable) { safelyResolveThenable(self, thenable); } else { self.state = FULFILLED; self.outcome = value; var i = -1; var len = self.queue.length; while (++i < len) { self.queue[i].callFulfilled(value); } } return self; }; handlers.reject = function (self, error) { self.state = REJECTED; self.outcome = error; var i = -1; var len = self.queue.length; while (++i < len) { self.queue[i].callRejected(error); } return self; }; function getThen(obj) { // Make sure we only access the accessor once as required by the spec var then = obj && obj.then; if (obj && typeof obj === 'object' && typeof then === 'function') { return function appyThen() { then.apply(obj, arguments); }; } } function safelyResolveThenable(self, thenable) { // Either fulfill, reject or reject with error var called = false; function onError(value) { if (called) { return; } called = true; handlers.reject(self, value); } function onSuccess(value) { if (called) { return; } called = true; handlers.resolve(self, value); } function tryToUnwrap() { thenable(onSuccess, onError); } var result = tryCatch(tryToUnwrap); if (result.status === 'error') { onError(result.value); } } function tryCatch(func, value) { var out = {}; try { out.value = func(value); out.status = 'success'; } catch (e) { out.status = 'error'; out.value = e; } return out; } exports.resolve = resolve; function resolve(value) { if (value instanceof this) { return value; } return handlers.resolve(new this(INTERNAL), value); } exports.reject = reject; function reject(reason) { var promise = new this(INTERNAL); return handlers.reject(promise, reason); } exports.all = all; function all(iterable) { var self = this; if (Object.prototype.toString.call(iterable) !== '[object Array]') { return this.reject(new TypeError('must be an array')); } var len = iterable.length; var called = false; if (!len) { return this.resolve([]); } var values = new Array(len); var resolved = 0; var i = -1; var promise = new this(INTERNAL); while (++i < len) { allResolver(iterable[i], i); } return promise; function allResolver(value, i) { self.resolve(value).then(resolveFromAll, function (error) { if (!called) { called = true; handlers.reject(promise, error); } }); function resolveFromAll(outValue) { values[i] = outValue; if (++resolved === len && !called) { called = true; handlers.resolve(promise, values); } } } } exports.race = race; function race(iterable) { var self = this; if (Object.prototype.toString.call(iterable) !== '[object Array]') { return this.reject(new TypeError('must be an array')); } var len = iterable.length; var called = false; if (!len) { return this.resolve([]); } var i = -1; var promise = new this(INTERNAL); while (++i < len) { resolver(iterable[i]); } return promise; function resolver(value) { self.resolve(value).then(function (response) { if (!called) { called = true; handlers.resolve(promise, response); } }, function (error) { if (!called) { called = true; handlers.reject(promise, error); } }); } } },{"1":1}],3:[function(_dereq_,module,exports){ (function (global){ 'use strict'; if (typeof global.Promise !== 'function') { global.Promise = _dereq_(2); } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"2":2}],4:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function getIDB() { /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */ if (typeof indexedDB !== 'undefined') { return indexedDB; } if (typeof webkitIndexedDB !== 'undefined') { return webkitIndexedDB; } if (typeof mozIndexedDB !== 'undefined') { return mozIndexedDB; } if (typeof OIndexedDB !== 'undefined') { return OIndexedDB; } if (typeof msIndexedDB !== 'undefined') { return msIndexedDB; } } var idb = getIDB(); function isIndexedDBValid() { try { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. if (!idb) { return false; } // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof openDatabase !== 'undefined' && typeof navigator !== 'undefined' && navigator.userAgent && /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) { return false; } return idb && typeof idb.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof IDBKeyRange !== 'undefined'; } catch (e) { return false; } } function isWebSQLValid() { return typeof openDatabase === 'function'; } function isLocalStorageValid() { try { return typeof localStorage !== 'undefined' && 'setItem' in localStorage && localStorage.setItem; } catch (e) { return false; } } // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function createBlob(parts, properties) { /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder; var builder = new Builder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // This is CommonJS because lie is an external dependency, so Rollup // can just ignore it. if (typeof Promise === 'undefined' && typeof _dereq_ !== 'undefined') { _dereq_(3); } var Promise$1 = Promise; function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // // Blobs are not supported in all versions of IndexedDB, notably // Chrome <37 and Android <5. In those versions, storing a blob will throw. // // Various other blob bugs exist in Chrome v37-42 (inclusive). // Detecting them is expensive and confusing to users, and Chrome 37-42 // is at very low usage worldwide, so we do a hacky userAgent check instead. // // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120 // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // // Code borrowed from PouchDB. See: // https://github.com/pouchdb/pouchdb/blob/9c25a23/src/adapters/idb/blobSupport.js // function _checkBlobSupportWithoutCaching(txn) { return new Promise$1(function (resolve) { var blob = createBlob(['']); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.onabort = function (e) { // If the transaction aborts now its due to not being able to // write to the database, likely due to the disk being full e.preventDefault(); e.stopPropagation(); resolve(false); }; txn.oncomplete = function () { var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); var matchedEdge = navigator.userAgent.match(/Edge\//); // MS Edge pretends to be Chrome 42: // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); }; })["catch"](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise$1.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } function _deferReadiness(dbInfo) { var dbContext = dbContexts[dbInfo.name]; // Create a deferred object representing the current database operation. var deferredOperation = {}; deferredOperation.promise = new Promise$1(function (resolve) { deferredOperation.resolve = resolve; }); // Enqueue the deferred operation. dbContext.deferredOperations.push(deferredOperation); // Chain its promise to the database readiness. if (!dbContext.dbReady) { dbContext.dbReady = deferredOperation.promise; } else { dbContext.dbReady = dbContext.dbReady.then(function () { return deferredOperation.promise; }); } } function _advanceReadiness(dbInfo) { var dbContext = dbContexts[dbInfo.name]; // Dequeue a deferred operation. var deferredOperation = dbContext.deferredOperations.pop(); // Resolve its promise (which is part of the database readiness // chain of promises). if (deferredOperation) { deferredOperation.resolve(); } } function _getConnection(dbInfo, upgradeNeeded) { return new Promise$1(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { _deferReadiness(dbInfo); dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = idb.open.apply(idb, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); _advanceReadiness(dbInfo); }; }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise$1(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Specialize the default `ready()` function by making it dependent // on the current database operations. Thus, the driver will be actually // ready when it's been initialized (default) *and* there are no pending // operations on the database (initiated by some other instances). function _fullyReady(callback) { var self = this; var promise = self._initReady().then(function () { var dbContext = dbContexts[self._dbInfo.name]; if (dbContext && dbContext.dbReady) { return dbContext.dbReady; } }); promise.then(callback, callback); return promise; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null, // Database readiness (promise). dbReady: null, // Deferred operations on the database. deferredOperations: [] }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(self); // Replace the default `ready()` function with the specialized one. if (!self._initReady) { self._initReady = self.ready; self.ready = _fullyReady; } // Create an array of initialization states of the related localForages. var initPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise$1.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== self) { // Don't wait for itself... initPromises.push(forage._initReady()["catch"](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise$1.all(initPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k = 0; k < forages.length; k++) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })["catch"](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor["continue"](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })["catch"](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise$1(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; if (value instanceof Blob) { return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { if (blobSupport) { return value; } return _encodeBlob(value); }); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; var req = store.put(value, key); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `.delete()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store["delete"](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })["catch"](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })["catch"](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })["catch"](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })["catch"](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor["continue"](); }; req.onerror = function () { reject(req.error); }; })["catch"](reject); }); executeCallback(promise, callback); return promise; } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage$1(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise$1(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return reject(e); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); dbInfo.serializer = localforageSerializer; return dbInfoPromise; } function getItem$1(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function iterate$1(iterator, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function setItem$1(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function removeItem$1(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear$1(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length$1(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key$1(n, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function keys$1(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage$1, iterate: iterate$1, getItem: getItem$1, setItem: setItem$1, removeItem: removeItem$1, clear: clear$1, length: length$1, key: key$1, keys: keys$1 }; // Config the localStorage backend, using options set in the config. function _initStorage$2(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; dbInfo.serializer = localforageSerializer; return Promise$1.resolve(); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear$2(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem$2(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate$2(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key$2(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys$2(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length$2(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem$2(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem$2(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise$1(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage$2, // Default API, from Gaia/localStorage. iterate: iterate$2, getItem: getItem$2, setItem: setItem$2, removeItem: removeItem$2, clear: clear$2, length: length$2, key: key$2, keys: keys$2 }; function executeTwoCallbacks(promise, callback, errorCallback) { if (typeof callback === 'function') { promise.then(callback); } if (typeof errorCallback === 'function') { promise["catch"](errorCallback); } } // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; var driverSupport = {}; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 driverSupport[DriverType.INDEXEDDB] = isIndexedDBValid(); driverSupport[DriverType.WEBSQL] = isWebSQLValid(); driverSupport[DriverType.LOCALSTORAGE] = isLocalStorageValid(); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise$1(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise$1.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise$1.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); executeTwoCallbacks(promise, callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = Promise$1.resolve().then(function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return asyncStorage; case self.LOCALSTORAGE: return localStorageWrapper; case self.WEBSQL: return webSQLStorage; } } else if (CustomDrivers[driverName]) { return CustomDrivers[driverName]; } else { throw new Error('Driver not found.'); } }); executeTwoCallbacks(getDriverPromise, callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = Promise$1.resolve(localforageSerializer); executeTwoCallbacks(serializerPromise, callback); return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); executeTwoCallbacks(promise, callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })["catch"](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise$1.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () { return Promise$1.resolve(); }) : Promise$1.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })["catch"](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise$1.reject(error); return self._driverSet; }); executeTwoCallbacks(this._driverSet, callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; }(); // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localforage_js = new LocalForage(); module.exports = localforage_js; },{"3":3}]},{},[4])(4) }); /** * angular-localforage - Angular service & directive for https://github.com/mozilla/localForage (Offline storage, improved.) * @version v1.3.1 * @link https://github.com/ocombe/angular-localForage * @license MIT * @author Olivier Combe <olivier.combe@gmail.com> */ (function(root, factory) { 'use strict'; var angular = (root && root.angular) || (window && window.angular); if(typeof define === 'function' && define.amd) { // AMD define(['localforage'], function(localforage) { factory(angular, localforage); }); } else if(typeof exports === 'object' || typeof global === 'object') { module.exports = factory(angular, require('localforage')); // Node/Browserify } else { return factory(angular, root.localforage); // Browser } })(this, function(angular, localforage, undefined) { 'use strict'; var angularLocalForage = angular.module('LocalForageModule', ['ng']); angularLocalForage.provider('$localForage', function() { var lfInstances = {}, defaultConfig = { name: 'lf' }, // Send signals for each of the following actions ? notify = { setItem: false, removeItem: false }, watchers = {}; // Setter for notification config, itemSet & itemRemove should be booleans this.setNotify = function(itemSet, itemRemove) { notify = { setItem: itemSet, removeItem: itemRemove }; }; this.config = function(config) { if(!angular.isObject(config)) { throw new Error('The config parameter should be an object'); } angular.extend(defaultConfig, config); }; this.$get = ['$rootScope', '$q', '$parse', function($rootScope, $q, $parse) { var LocalForageInstance = function LocalForageInstance(params) { if(angular.isDefined(params)) { this._localforage = localforage.createInstance(params); } else { this._localforage = localforage; localforage.config(defaultConfig); } }; LocalForageInstance.prototype.createInstance = function createInstance(config) { if(angular.isObject(config)) { // create new instance config = angular.extend({}, defaultConfig, config); if(angular.isDefined(lfInstances[config.name])) { throw new Error('A localForage instance with the name ' + config.name + ' is already defined.'); } lfInstances[config.name] = new LocalForageInstance(config); return lfInstances[config.name]; } else { throw new Error('The parameter should be a config object.') } }; LocalForageInstance.prototype.instance = function instance(name) { if(angular.isUndefined(name)) { return lfInstances[defaultConfig.name]; } else if(angular.isString(name)) { if(angular.isDefined(lfInstances[name])) { return lfInstances[name]; } else { throw new Error('No localForage instance of that name exists.') } } else { throw new Error('The parameter should be a string.') } }; // Setter for the storage driver LocalForageInstance.prototype.setDriver = function setDriver(driver) { return this._localforage.setDriver(driver); }; // Getter for the storage driver LocalForageInstance.prototype.driver = function driver() { return this._localforage.driver(); }; // Directly adds a value to storage LocalForageInstance.prototype.setItem = function setItem(key, value) { // throw error on undefined key, we allow undefined value because... why not ? if(angular.isUndefined(key)) { throw new Error("You must define a key to set"); } var self = this; if(angular.isArray(key)) { if(!angular.isArray(value)) { throw new Error('If you set an array of keys, the values should be an array too'); } var promises = []; angular.forEach(key, function(k, index) { promises.push(self.setItem(k, value[index])) }); return $q.all(promises); } else { var deferred = $q.defer(), args = arguments, localCopy = typeof Blob !== 'undefined' && typeof ArrayBuffer !== 'undefined' && (value instanceof Blob || value instanceof ArrayBuffer) ? value : angular.copy(value); //avoid $promises attributes from value objects, if present. if(angular.isObject(localCopy) && angular.isDefined(localCopy.$promise)) { delete localCopy.$promise; //delete attribut from object structure. } self._localforage.setItem(self.prefix() + key, localCopy).then(function success() { if(notify.setItem) { $rootScope.$broadcast('LocalForageModule.setItem', { key: key, newvalue: localCopy, driver: self.driver() }); } deferred.resolve(localCopy); }, function error(data) { self.onError(data, args, self.setItem, deferred); }); return deferred.promise; } }; // Directly get a value from storage LocalForageInstance.prototype.getItem = function getItem(key, rejectOnNull) { // throw error on undefined key if(angular.isUndefined(key)) { throw new Error("You must define a key to get"); } var deferred = $q.defer(), args = arguments, self = this, promise; if(angular.isArray(key)) { var res = [], found = 0; promise = self._localforage.iterate(function(value, k) { var index = key.indexOf(self.prefix() + k); if(index > -1) { res[index] = value; found++; } if(found === key.length) { return res; } }).then(function() { var shouldResolve = true; for (var i = 0; i < key.length; i++) { if (angular.isUndefined(res[i])) { res[i] = null; shouldResolve = false; } } if (shouldResolve || !rejectOnNull) { deferred.resolve(res); } else { deferred.reject(res); } }); } else { promise = self._localforage.getItem(self.prefix() + key).then(function(item) { if (rejectOnNull && item === null) { deferred.reject(item); } else { deferred.resolve(item); } }); } promise.then(null, function error(data) { self.onError(data, args, self.getItem, deferred); }); return deferred.promise; }; // Iterate over all the values in storage LocalForageInstance.prototype.iterate = function iterate(callback) { // throw error on undefined key if(angular.isUndefined(callback)) { throw new Error("You must define a callback to iterate"); } var deferred = $q.defer(), args = arguments, self = this; self._localforage.iterate(callback).then(function success(item) { deferred.resolve(item); }, function error(data) { self.onError(data, args, self.iterate, deferred); }); return deferred.promise; }; // Remove an item from storage LocalForageInstance.prototype.removeItem = function removeItem(key) { // throw error on undefined key if(angular.isUndefined(key)) { throw new Error("You must define a key to remove"); } var self = this; if(angular.isArray(key)) { var promises = []; angular.forEach(key, function(k, index) { promises.push(self.removeItem(k)); }); return $q.all(promises); } else { var deferred = $q.defer(), args = arguments; self._localforage.removeItem(self.prefix() + key).then(function success() { if(notify.removeItem) { $rootScope.$broadcast('LocalForageModule.removeItem', {key: key, driver: self.driver()}); } deferred.resolve(); }, function error(data) { self.onError(data, args, self.removeItem, deferred); }); return deferred.promise; } }; // Get an item and removes it from storage LocalForageInstance.prototype.pull = function pull(key) { // throw error on undefined key if(angular.isUndefined(key)) { throw new Error("You must define a key to pull"); } var self = this, deferred = $q.defer(), onError = function error(err) { deferred.reject(err); }; self.getItem(key).then(function success(value) { self.removeItem(key).then(function success() { deferred.resolve(value); }, onError); }, onError); return deferred.promise; }; // Remove all data for this app from storage LocalForageInstance.prototype.clear = function clear() { var deferred = $q.defer(), args = arguments, self = this; self._localforage.clear().then(function success(keys) { deferred.resolve(); }, function error(data) { self.onError(data, args, self.clear, deferred); }); return deferred.promise; }; // Return the key for item at position n LocalForageInstance.prototype.key = function key(n) { // throw error on undefined n if(angular.isUndefined(n)) { throw new Error("You must define a position to get for the key function"); } var deferred = $q.defer(), args = arguments, self = this; self._localforage.key(n).then(function success(key) { deferred.resolve(key); }, function error(data) { self.onError(data, args, self.key, deferred); }); return deferred.promise; }; var keys = function keys() { var deferred = $q.defer(), args = arguments, self = this; self._localforage.keys().then(function success(keyList) { if(defaultConfig.oldPrefix && self.driver() === 'localStorageWrapper') { var tempKeyList = []; for(var i = 0, len = keyList.length; i < len; i++) { tempKeyList.push(keyList[i].substr(self.prefix().length, keyList[i].length)); } keyList = tempKeyList; } deferred.resolve(keyList); }, function error(data) { self.onError(data, args, self.keys, deferred); }); return deferred.promise; }; // Return the list of keys stored for this application LocalForageInstance.prototype.keys = keys; // deprecated LocalForageInstance.prototype.getKeys = keys; // Returns the number of keys in this storage LocalForageInstance.prototype.length = function() { var deferred = $q.defer(), args = arguments, self = this; self._localforage.length().then(function success(length) { deferred.resolve(length); }, function error(data) { self.onError(data, args, length, deferred); }); return deferred.promise; }; /** * Bind - let's you directly bind a LocalForage value to a $scope variable * @param {Angular $scope} $scope - the current scope you want the variable available in * @param {String/Object} opts - the key name of the variable you are binding OR an object with the key and custom options like default value or instance name * Here are the available options you can set: * * key: the key used in storage and in the scope (if scopeKey isn't defined) * * defaultValue: the default value * * name: name of the instance that should store the data * * scopeKey: the key used in the scope * @returns {*} - returns whatever the stored value is */ LocalForageInstance.prototype.bind = function bind($scope, opts) { if(angular.isString(opts)) { opts = { key: opts } } else if(!angular.isObject(opts) || angular.isUndefined(opts.key)) { throw new Error("You must define a key to bind"); } var defaultOpts = { defaultValue: '', name: defaultConfig.name }; // If no defined options we use defaults otherwise extend defaults opts = angular.extend({}, defaultOpts, opts); var self = lfInstances[opts.name]; if(angular.isUndefined(self)) { throw new Error("You must use the name of an existing instance"); } // Set the storeName key for the LocalForage entry // use user defined in specified var scopeKey = opts.scopeKey || opts.key, model = $parse(scopeKey); return self.getItem(opts.key).then(function(item) { if (item !== null) { // If it does exist assign it to the $scope value model.assign($scope, item); } else if(!angular.isUndefined(opts.defaultValue)) { // If a value doesn't already exist store it as is model.assign($scope, opts.defaultValue); self.setItem(opts.key, opts.defaultValue); } // Register a listener for changes on the $scope value // to update the localForage value if(angular.isDefined(watchers[opts.key])) { watchers[opts.key](); } watchers[opts.key] = $scope.$watch(scopeKey, function(val) { if(angular.isDefined(val)) { self.setItem(opts.key, val); } }, true); return item; }); }; /** * Unbind - let's you unbind a variable from localForage while removing the value from both * the localForage and the local variable and sets it to null * @param {String/Object} opts - the key name of the variable you are unbinding OR an object with the key and custom options like default value or instance name * Here are the available options you can set: * * key: the key used in storage and in the scope (if scopeKey isn't defined) * * name: name of the instance that should store the data * * scopeKey: the key used in the scope */ LocalForageInstance.prototype.unbind = function unbind($scope, opts) { if(angular.isString(opts)) { opts = { key: opts } } else if(!angular.isObject(opts) || angular.isUndefined(opts.key)) { throw new Error("You must define a key to unbind"); } var defaultOpts = { scopeKey: opts.key, name: defaultConfig.name }; // If no defined options we use defaults otherwise extend defaults opts = angular.extend({}, defaultOpts, opts); var self = lfInstances[opts.name]; if(angular.isUndefined(self)) { throw new Error("You must use the name of an existing instance"); } $parse(opts.scopeKey).assign($scope, null); if(angular.isDefined(watchers[opts.key])) { watchers[opts.key](); // unwatch delete watchers[opts.key]; } return self.removeItem(opts.key); }; LocalForageInstance.prototype.prefix = function() { return this.driver() === 'localStorageWrapper' && defaultConfig.oldPrefix ? this._localforage.config().name + '.' : ''; }; // Handling errors LocalForageInstance.prototype.onError = function(err, args, fct, deferred) { // test for private browsing errors in Firefox & Safari if(((angular.isObject(err) && err.name ? err.name === 'InvalidStateError' : (angular.isString(err) && err === 'InvalidStateError')) && this.driver() === 'asyncStorage') || (angular.isObject(err) && err.code && err.code === 5)) { var self = this; self.setDriver('localStorageWrapper').then(function() { fct.apply(self, args).then(function(item) { deferred.resolve(item); }, function(data) { deferred.reject(data); }); }, function() { deferred.reject(err); }); } else { deferred.reject(err); } }; lfInstances[defaultConfig.name] = new LocalForageInstance(); return lfInstances[defaultConfig.name]; }] }); angularLocalForage.directive('localForage', ['$localForage', function($localForage) { return { restrict: 'A', link: function($scope, $element, $attrs) { var opts = $scope.$eval($attrs.localForage); if(angular.isObject(opts) && angular.isDefined(opts.key)) { $localForage.bind($scope, opts); } else { $localForage.bind($scope, $attrs.localForage); } } } }]); return angularLocalForage.name; }); /* * ---------------------------------------- * * Based on https://github.com/mozilla/localForage/blob/master/src/drivers/websql.js * */ var localforageSsatbDriver = { DRIVER_NAME : 'localForage-SsatbDriver' }; (function () { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? require('promise') : this.Promise; var globalObject = this; var serializer = null; var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } function _initStorage(options) { var self = this; var apiInfo = null; if (options) { self._apiInfo = options.apiInfo; } return Promise.resolve(); } function appendServiceResponseHeaders(obj, jqXHR) { var headers = null; if (obj != null) if (jqXHR != null) { var headersStr = jqXHR.getAllResponseHeaders(); var headersArray = headersStr.split("\n"); var headers = {}; for (var i in headersArray) { var header = headersArray[i]; var kvs = header.split(":"); var key = kvs[0]; if (key) { key = key.trim(); if (key.length != 0) { var val = kvs[1]; if (val) val = val.trim(); headers[key] = val; } } } } else console.warn("jqXHR is null. Headers not populated"); if (headers != null) obj.responseHeaders = headers; return obj; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var apiInfo = getDefaultApiDetails(self._apiInfo); $.ajax({ method: apiInfo.iterate.verb ? apiInfo.iterate.verb : "GET", url: apiInfo.Url + apiInfo.iterate.url, headers: apiInfo.Headers, global: false, cache: false, dataType: "json", contentType: 'application/json; charset=utf-8', }).done(function (items) { var length = items.length; for (var i = 0; i < length; i++) { var item = items[i]; item = iterator(item, item[apiInfo.iterate.keyProperty], i + 1); if (item !== void (0)) { resolve(item); return; } } resolve(); }).fail(function (jqXHR, textStatus, errorThrown) { reject(getServerError(apiInfo, jqXHR, textStatus, errorThrown)); }); }).catch(reject); }); executeCallback(promise, callback); return promise; } function getItem(key, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var apiDetails = getApiDetails(key); var apiInfo = self._apiInfo[apiDetails.serviceName]; $.ajax({ method: apiDetails.verb, url: apiInfo.Url + apiDetails.url, dataType: "json", global: false, cache: false, contentType: 'application/json; charset=utf-8', headers: apiInfo.Headers }).done(function (obj, responseStatus, jqXHR) { resolve(appendServiceResponseHeaders(obj, jqXHR)); }).fail(function (jqXHR, textStatus, errorThrown) { reject(getServerError(apiDetails,jqXHR, textStatus, errorThrown)); }); }).catch(reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var apiDetails = getApiDetails(key); var apiInfo = self._apiInfo[apiDetails.serviceName]; $.ajax({ method: apiDetails.verb, url: apiInfo.Url + apiDetails.url, dataType: "json", global: false, cache: false, contentType: 'application/json; charset=utf-8', headers: apiInfo.Headers, data: JSON.stringify(value) }).done(function (response, responseStatus, jqXHR) { value.response = response; resolve(appendServiceResponseHeaders(value, jqXHR)); }).fail(function (jqXHR, textStatus, errorThrown) { reject(getServerError(apiDetails, jqXHR, textStatus, errorThrown)); }); }).catch(reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var apiDetails = getApiDetails(key); var apiInfo = self._apiInfo[apiDetails.serviceName]; $.ajax({ method: apiDetails.verb, url: apiInfo.Url + apiDetails.url, global: false, cache: false, headers: apiInfo.Headers }).done(function () { resolve() }).fail(function (jqXHR, textStatus, errorThrown) { reject(getServerError(apiDetails, jqXHR, textStatus, errorThrown)); }); }).catch(reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { }).catch(reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { }).catch(reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { }).catch(reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { }).catch(reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } function getApiDetails(key) { var api = key.split("|"); return { serviceName: api[0], verb: api[1], url: api[2] }; } function getDefaultApiDetails(apiHashmap) { var defaultKey = null; for (var firstKey in apiHashmap) { defaultKey = firstKey; break; } if (defaultKey == null) return null; return apiHashmap[defaultKey]; } function getServerError(apiDetails, jqXHR, textStatus, errorThrown) { return { serviceName: apiDetails.serviceName, method: apiDetails.verb, status: jqXHR.status, url: apiDetails.url, statusText: textStatus, errorThrown: errorThrown, data: jqXHR.responseJSON }; } var driver = { _driver: localforageSsatbDriver.DRIVER_NAME, _initStorage: _initStorage, _support: true, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.DEFINE) { define(localforageSsatbDriver.DRIVER_NAME, function () { return driver; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = driver; } else { this[localforageSsatbDriver.DRIVER_NAME] = driver; } localforage.defineDriver(driver); }).call(window); angular.module('SSATB.LocalForage', ['LocalForageModule']) .provider('ssatbHttp', ['$localForageProvider', function ($localForageProvider) { var _config = { driver: [localforageSsatbDriver.DRIVER_NAME] }; this.config = function (config) { if (!angular.isObject(config)) throw new Error('The config parameter should be an object'); _config = angular.extend(_config, config); $localForageProvider.config(_config); }; var interceptorFactories = this.interceptors = []; function getApiNameByUrl(url) { if (!angular.isObject(_config.apiInfo)) return null; var service = null; angular.forEach(_config.apiInfo, function (value, key) { if (url.toLowerCase().indexOf(value.Url.toLowerCase()) === 0) { service = key; } }); return service; } this.$get = ['$localForage', '$q', '$injector', function ($localForage, $q, $injector) { var reversedInterceptors = []; angular.forEach(interceptorFactories, function (interceptorFactory) { reversedInterceptors.unshift(angular.isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); function ssatbHttp(requestConfig) { if (!angular.isObject(requestConfig)) throw new Error('Http request configuration must be an object.'); if (!angular.isString(requestConfig.url)) throw new Error('Http request configuration url must be a string.'); var config = angular.extend({ method: 'get' }, requestConfig); config.method = angular.uppercase(config.method); var service = getApiNameByUrl(requestConfig.url); if (service === null) throw new Error('No matching apiInfo was found in the provider configuration for the service URL ' + requestConfig.url); var requestInterceptors = []; var responseInterceptors = []; var promise = $q.when(config); // apply interceptors angular.forEach(reversedInterceptors, function (interceptor) { if (interceptor.request || interceptor.requestError) { requestInterceptors.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { responseInterceptors.push(interceptor.response, interceptor.responseError); } }); promise = chainInterceptors(promise, requestInterceptors); promise = promise.then(function (result) { var apiInfo = _config.apiInfo[service]; var key = service + '|' + config.method + '|' + requestConfig.url.substring(apiInfo.Url.length); if (config.method === 'GET') return $localForage.getItem(key); else if (config.method === 'DELETE') return $localForage.removeItem(key); else return $localForage.setItem(key, requestConfig.data); }); promise = promise.then(function (response) { if (response != null) response.config = config; else return { config: config }; return response; }, function (response) { if (response != null) { response.config = config throw response } else { throw new { config: config }; } }); return chainInterceptors(promise, responseInterceptors); } createShortMethods('get', 'delete'); createShortMethodsWithData('post', 'put'); return ssatbHttp; function createShortMethods(names) { angular.forEach(arguments, function (name) { ssatbHttp[name] = function (url, config) { return ssatbHttp(angular.extend({}, config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { angular.forEach(arguments, function (name) { ssatbHttp[name] = function (url, data, config) { return ssatbHttp(angular.extend({}, config || {}, { method: name, url: url, data: data })); }; }); } function chainInterceptors(promise, interceptors) { for (var i = 0, ii = interceptors.length; i < ii;) { var thenFn = interceptors[i++]; var rejectFn = interceptors[i++]; promise = promise.then(thenFn, rejectFn); } interceptors.length = 0; return promise; } }]; }]); (function () { var authTokenRefreshService = ( function authTokenRefreshService($window, $http) { this.$window = $window; this.$http = $http; return { refreshToken: refreshToken } function refreshToken(refreshTokenBaseUrl,serviceName) { var refreshTokenUrl = refreshTokenBaseUrl + '?serviceName=' + serviceName; return $http.get(refreshTokenUrl).then(refreshTokenComplete); function refreshTokenComplete(response) { return response; } } } ); var messageInterceptorsConfig = function ($provide, provider) { // push function to the interceptors which will intercept all the http responses provider.interceptors.push(['$q', '$injector', '$localForage', function ($q, $injector, $localForage) { return { responseError: function (errorResponse) { var deferred = $q.defer(); var apiInfoObject = $localForage._localforage._apiInfo; var serviceName = getServiceNameFromApiInfo(apiInfoObject, errorResponse); var config = $injector.get('ssatbAuthTokenRefreshConfig'); if (serviceName != null && config.refreshTokenUrl != null && !angular.isUndefined(errorResponse.config) && errorResponse.config != null && (angular.isUndefined(errorResponse.config.retry) || errorResponse.config.retry == false) && errorResponse.status === 401) { $injector.get('authTokenRefreshService').refreshToken(config.refreshTokenUrl, serviceName).then(function (response) { var apiInfo = apiInfoObject[errorResponse.serviceName]; apiInfo.Headers = response.data; _retrySsatbHttpRequest(errorResponse.config, deferred, $injector); }, function () { if (!angular.isUndefined(errorResponse.errorHandler) && config.errorHandler != null) config.errorHandler('An unexpected error occurred. For assistance, please email info@enrollment.org.'); deferred.reject(errorResponse); }); } else { if (!angular.isUndefined(errorResponse.errorHandler) && config.errorHandler != null) config.errorHandler('An unexpected error occurred. For assistance, please email info@enrollment.org.'); deferred.reject(errorResponse); } return deferred.promise; function getServiceNameFromApiInfo(apiInfoObject, errorResponse) { if (errorResponse.serviceName == null) return null; var apiInfo = apiInfoObject[errorResponse.serviceName]; if (apiInfo == null) return null; return apiInfo.ServiceName; } } }; } ]) }; var _retrySsatbHttpRequest = function (config, deferred, $injector) { $ssatbHttp = $injector.get('ssatbHttp'); config.retry = true; $ssatbHttp(config).then(function (response) { deferred.resolve(response); }, function (response) { alertDialog('An unexpected error occurred. For assistance, please email info@enrollment.org.'); deferred.reject(response); }); } angular.module('ssatb.authtokenrefresh', ['SSATB.LocalForage']) .provider('ssatbAuthTokenRefreshConfig', ['ssatbHttpProvider', function (ssatbHttpProvider) { var _config = {}; this.config = function (config) { if (!angular.isObject(config)) throw new Error('The config parameter should be an object'); _config = config; } this.$get = function () { return _config; } }]) .config(['$provide', 'ssatbHttpProvider', messageInterceptorsConfig]) .service('authTokenRefreshService', ['$window', '$http', authTokenRefreshService]); })();
'use strict'; /** * @ngdoc function * @name uniappApp.controller:MainCtrl * @description * # MainCtrl * Controller of the uniappApp */ angular.module('uniappApp') .controller('MainCtrl', function ($scope) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; });
import React from 'react' import PropTypes from 'prop-types' import ReactDisqusComments from 'react-disqus-comments' import * as S from './styled' const Comments = ({ url, title }) => { const completeURL = `https://muniz95.com.br${url}` return ( <S.CommentsWrapper> <S.CommentsTitle>Comentários</S.CommentsTitle> <ReactDisqusComments shortname="muniz95" identifier={completeURL} title={title} url={completeURL} /> </S.CommentsWrapper> ) } Comments.propTypes = { url: PropTypes.string.isRequired, title: PropTypes.string.isRequired } export default Comments
(function( $ ){ var multiSelectId=-1; $.fn.multiSelect=function(options){ multiSelectId++; var settings = { 'createCallback':false, 'createText':false, 'title':this.attr('title'), 'checked':[], 'oncheck':false, 'onuncheck':false, }; $.extend(settings,options); var button=$('<div class="multiselect button"><span>'+settings.title+'</span><span>▾</span></div>'); if(settings.checked.length>0){ button.children('span').first().text(settings.checked.join(', ')); } var span=$('<span/>'); span.append(button); button.data('id',multiSelectId); button.selectedItems=[]; this.hide(); this.before(span); settings.minWidth=button.width(); button.css('min-width',settings.minWidth); settings.minOuterWidth=button.outerWidth()-2; button.data('settings',settings); button.click(function(event){ var button=$(this); if(button.parent().children('ul').length>0){ button.parent().children('ul').slideUp(400,function(){ button.parent().children('ul').remove(); button.removeClass('active'); }); return; } var lists=$('ul.multiselectoptions'); lists.slideUp(400,function(){ lists.remove(); $('div.multiselect').removeClass('active'); button.addClass('active'); }); button.addClass('active'); event.stopPropagation(); var options=$(this).parent().next().children().map(function(){return $(this).val();}); var list=$('<ul class="multiselectoptions"/>').hide().appendTo($(this).parent()); function createItem(item,checked){ var id='ms'+multiSelectId+'-option-'+item; var input=$('<input id="'+id+'" type="checkbox"/>'); var label=$('<label for="'+id+'">'+item+'</label>'); if(settings.checked.indexOf(item)!=-1 || checked){ input.attr('checked',true); } if(checked){ settings.checked.push(item); } input.change(function(){ var groupname=$(this).next().text(); if($(this).is(':checked')){ settings.checked.push(groupname); if(settings.oncheck){ if(settings.oncheck(groupname)===false){ $(this).attr('checked', false); return; } } }else{ var index=settings.checked.indexOf(groupname); settings.checked.splice(index,1); if(settings.onuncheck){ if(settings.onuncheck(groupname)===false){ $(this).attr('checked',true); return; } } } var oldWidth=button.width(); if(settings.checked.length>0){ button.children('span').first().text(settings.checked.join(', ')); }else{ button.children('span').first().text(settings.title); } var newOuterWidth=Math.max((button.outerWidth()-2),settings.minOuterWidth)+'px'; var newWidth=Math.max(button.width(),settings.minWidth); button.css('height',button.height()); button.css('white-space','nowrap'); button.css('width',oldWidth); button.animate({'width':newWidth},undefined,undefined,function(){ button.css('width',''); }); list.animate({'width':newOuterWidth}); }); var li=$('<li></li>'); li.append(input).append(label); return li; } $.each(options,function(index,item){ list.append(createItem(item)); }); button.parent().data('preventHide',false); if(settings.createText){ var li=$('<li>+ <em>'+settings.createText+'<em></li>'); li.click(function(event){ li.empty(); var input=$('<input class="new">'); li.append(input); input.focus(); input.css('width',button.width()); button.parent().data('preventHide',true); input.keypress(function(event) { if(event.keyCode == 13) { event.preventDefault(); event.stopPropagation(); var li=$(this).parent(); $(this).remove(); li.text('+ '+settings.createText); li.before(createItem($(this).val())); li.prev().children('input').trigger('click'); button.parent().data('preventHide',false); var select=button.parent().next(); select.append($('<option value="'+$(this).val()+'">'+$(this).val()+'</option>')); if(settings.createCallback){ settings.createCallback(); } } }); input.blur(function(){ event.preventDefault(); event.stopPropagation(); $(this).remove(); li.text('+ '+settings.createText); setTimeout(function(){ button.parent().data('preventHide',false); },100); }); }); list.append(li); } var pos=button.position(); list.css('top',pos.top+button.outerHeight()-5); list.css('left',pos.left+3); list.css('width',(button.outerWidth()-2)+'px'); list.slideDown(); list.click(function(event){ event.stopPropagation(); }); }); $(window).click(function(){ if(!button.parent().data('preventHide')){ button.parent().children('ul').slideUp(400,function(){ button.parent().children('ul').remove(); button.removeClass('active'); }); } }); return span; }; })( jQuery );
var currentTagsArray = new Array(); var popularTagsArray = new Array(); var separatorArray = new Array(); var currIdArray = new Array(); $(document).ready(function(){ for (var currDivId in currentTagsArray) for(var index in currentTagsArray[currDivId]) if(isInteger(index) && currentTagsArray[currDivId][index] != '') addCurrentTag(currentTagsArray[currDivId][index], currIdArray[currDivId], true); for (var popDivId in popularTagsArray) for(var tag in popularTagsArray[popDivId]) if(isInteger(tag)) addPopularTag(popularTagsArray[popDivId][tag], popDivId); $("div[id$='DTICurrTags'] > * > .DTICancelButton").live("click", function(){ var i = 0; for(i=0;i<currentTagsArray.length;i++) { if(currIdArray[i] == $(this).closest("div[id$='DTICurrTags']").attr("id")) { currentTagsArray[i].remove($(this).next().text()); $(this).parent().remove(); break; } } }); $("div[id$='DTIPopularTags'] > .DTIPopularTag").click(function(){ addCurrentTag($(this).text(), $(this).parent().parent().prev().attr("id"), false); }); }); function addCurrentTag(tag, addToDivId, staticAdd){ if (staticAdd){ $("#" + addToDivId).append("<div class=\"DTICurrentTag\"><div class=\"DTICancelButton\">X</div><div class=\"DTITagText\">" + tag + "</div></div>"); } else { for (var index in currIdArray) if (currIdArray[index] == addToDivId) if(jQuery.inArray(tag, currentTagsArray[index]) < 0) { currentTagsArray[index].push(tag); $("#" + addToDivId).append("<div class=\"DTICurrentTag\"><div class=\"DTICancelButton\">X</div><div class=\"DTITagText\">" + tag + "</div></div>"); } } } function addPopularTag(tag, addToDivId){ $("#" + addToDivId).append("<div class=\"DTIPopularTag\">" + tag + "</div>"); } function isInteger(s) { return (s.toString().search(/^-?[0-9]+$/) == 0); } function prepareCurrentTags(){ var currDivId = 0; for (currDivId = 0; currDivId < currentTagsArray.length; currDivId++) { var tags = ''; var index = 0; for (index = 0; index < currentTagsArray[currDivId].length; index++) { if(currentTagsArray[currDivId][index].toString().trim() != '') { tags = tags + separatorArray[currIdArray[currDivId]] + currentTagsArray[currDivId][index]; } } $("#" + currIdArray[currDivId] + " input[id$='hfTags']").attr("value",tags.substring(1)); } return true; }