code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
define([ './addExtensionsRequired', './addToArray', './ForEach', './getAccessorByteStride', '../../Core/Cartesian3', '../../Core/Math', '../../Core/clone', '../../Core/defaultValue', '../../Core/defined', '../../Core/Quaternion', '../../Core/WebGLConstants' ], function( addExtensionsRequired, addToArray, ForEach, getAccessorByteStride, Cartesian3, CesiumMath, clone, defaultValue, defined, Quaternion, WebGLConstants) { 'use strict'; var updateFunctions = { '0.8' : glTF08to10, '1.0' : glTF10to20, '2.0' : undefined }; /** * Update the glTF version to the latest version (2.0), or targetVersion if specified. * Applies changes made to the glTF spec between revisions so that the core library * only has to handle the latest version. * * @param {Object} gltf A javascript object containing a glTF asset. * @param {Object} [options] Options for updating the glTF. * @param {String} [options.targetVersion] The glTF will be upgraded until it hits the specified version. * @returns {Object} The updated glTF asset. */ function updateVersion(gltf, options) { options = defaultValue(options, {}); var targetVersion = options.targetVersion; var version = gltf.version; gltf.asset = defaultValue(gltf.asset, { version: '1.0' }); version = defaultValue(version, gltf.asset.version); // invalid version if (!updateFunctions.hasOwnProperty(version)) { // try truncating trailing version numbers, could be a number as well if it is 0.8 if (defined(version)) { version = ('' + version).substring(0, 3); } // default to 1.0 if it cannot be determined if (!updateFunctions.hasOwnProperty(version)) { version = '1.0'; } } var updateFunction = updateFunctions[version]; while (defined(updateFunction)) { if (version === targetVersion) { break; } updateFunction(gltf); version = gltf.asset.version; updateFunction = updateFunctions[version]; } return gltf; } function updateInstanceTechniques(gltf) { var materials = gltf.materials; for (var materialId in materials) { if (materials.hasOwnProperty(materialId)) { var material = materials[materialId]; var instanceTechnique = material.instanceTechnique; if (defined(instanceTechnique)) { material.technique = instanceTechnique.technique; material.values = instanceTechnique.values; delete material.instanceTechnique; } } } } function setPrimitiveModes(gltf) { var meshes = gltf.meshes; for (var meshId in meshes) { if (meshes.hasOwnProperty(meshId)) { var mesh = meshes[meshId]; var primitives = mesh.primitives; if (defined(primitives)) { var primitivesLength = primitives.length; for (var i = 0; i < primitivesLength; i++) { var primitive = primitives[i]; var defaultMode = defaultValue(primitive.primitive, WebGLConstants.TRIANGLES); primitive.mode = defaultValue(primitive.mode, defaultMode); delete primitive.primitive; } } } } } function updateNodes(gltf) { var nodes = gltf.nodes; var axis = new Cartesian3(); var quat = new Quaternion(); for (var nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { var node = nodes[nodeId]; if (defined(node.rotation)) { var rotation = node.rotation; Cartesian3.fromArray(rotation, 0, axis); Quaternion.fromAxisAngle(axis, rotation[3], quat); node.rotation = [quat.x, quat.y, quat.z, quat.w]; } var instanceSkin = node.instanceSkin; if (defined(instanceSkin)) { node.skeletons = instanceSkin.skeletons; node.skin = instanceSkin.skin; node.meshes = instanceSkin.meshes; delete node.instanceSkin; } } } } function removeTechniquePasses(gltf) { var techniques = gltf.techniques; for (var techniqueId in techniques) { if (techniques.hasOwnProperty(techniqueId)) { var technique = techniques[techniqueId]; var passes = technique.passes; if (defined(passes)) { var passName = defaultValue(technique.pass, 'defaultPass'); if (passes.hasOwnProperty(passName)) { var pass = passes[passName]; var instanceProgram = pass.instanceProgram; technique.attributes = defaultValue(technique.attributes, instanceProgram.attributes); technique.program = defaultValue(technique.program, instanceProgram.program); technique.uniforms = defaultValue(technique.uniforms, instanceProgram.uniforms); technique.states = defaultValue(technique.states, pass.states); } delete technique.passes; delete technique.pass; } } } } function glTF08to10(gltf) { if (!defined(gltf.asset)) { gltf.asset = {}; } var asset = gltf.asset; asset.version = '1.0'; // profile should be an object, not a string if (!defined(asset.profile) || (typeof asset.profile === 'string')) { asset.profile = {}; } // version property should be in asset, not on the root element if (defined(gltf.version)) { delete gltf.version; } // material.instanceTechnique properties should be directly on the material updateInstanceTechniques(gltf); // primitive.primitive should be primitive.mode setPrimitiveModes(gltf); // node rotation should be quaternion, not axis-angle // node.instanceSkin is deprecated updateNodes(gltf); // technique.pass and techniques.passes are deprecated removeTechniquePasses(gltf); // gltf.lights -> khrMaterialsCommon.lights if (defined(gltf.lights)) { var extensions = defaultValue(gltf.extensions, {}); gltf.extensions = extensions; var materialsCommon = defaultValue(extensions.KHR_materials_common, {}); extensions.KHR_materials_common = materialsCommon; materialsCommon.lights = gltf.lights; delete gltf.lights; } // gltf.allExtensions -> extensionsUsed if (defined(gltf.allExtensions)) { gltf.extensionsUsed = gltf.allExtensions; gltf.allExtensions = undefined; } } function removeAnimationSamplersIndirection(gltf) { var animations = gltf.animations; for (var animationId in animations) { if (animations.hasOwnProperty(animationId)) { var animation = animations[animationId]; var parameters = animation.parameters; if (defined(parameters)) { var samplers = animation.samplers; for (var samplerId in samplers) { if (samplers.hasOwnProperty(samplerId)) { var sampler = samplers[samplerId]; sampler.input = parameters[sampler.input]; sampler.output = parameters[sampler.output]; } } delete animation.parameters; } } } } function objectToArray(object, mapping) { var array = []; for (var id in object) { if (object.hasOwnProperty(id)) { var value = object[id]; mapping[id] = array.length; array.push(value); if (!defined(value.name) && typeof(value) === 'object') { value.name = id; } } } return array; } function objectsToArrays(gltf) { var i; var globalMapping = { accessors: {}, animations: {}, bufferViews: {}, buffers: {}, cameras: {}, materials: {}, meshes: {}, nodes: {}, programs: {}, shaders: {}, skins: {}, techniques: {} }; // Map joint names to id names var jointName; var jointNameToId = {}; var nodes = gltf.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { jointName = nodes[id].jointName; if (defined(jointName)) { jointNameToId[jointName] = id; } } } // Convert top level objects to arrays for (var topLevelId in gltf) { if (gltf.hasOwnProperty(topLevelId) && topLevelId !== 'extras' && topLevelId !== 'asset' && topLevelId !== 'extensions') { var objectMapping = {}; var object = gltf[topLevelId]; if (typeof(object) === 'object' && !Array.isArray(object)) { gltf[topLevelId] = objectToArray(object, objectMapping); globalMapping[topLevelId] = objectMapping; if (topLevelId === 'animations') { objectMapping = {}; object.samplers = objectToArray(object.samplers, objectMapping); globalMapping[topLevelId].samplers = objectMapping; } } } } // Remap joint names to array indexes for (jointName in jointNameToId) { if (jointNameToId.hasOwnProperty(jointName)) { jointNameToId[jointName] = globalMapping.nodes[jointNameToId[jointName]]; } } // Fix references if (defined(gltf.scene)) { gltf.scene = globalMapping.scenes[gltf.scene]; } ForEach.bufferView(gltf, function(bufferView) { if (defined(bufferView.buffer)) { bufferView.buffer = globalMapping.buffers[bufferView.buffer]; } }); ForEach.accessor(gltf, function(accessor) { if (defined(accessor.bufferView)) { accessor.bufferView = globalMapping.bufferViews[accessor.bufferView]; } }); ForEach.shader(gltf, function(shader) { var extensions = shader.extensions; if (defined(extensions)) { var binaryGltf = extensions.KHR_binary_glTF; if (defined(binaryGltf)) { shader.bufferView = globalMapping.bufferViews[binaryGltf.bufferView]; delete extensions.KHR_binary_glTF; } if (Object.keys(extensions).length === 0) { delete shader.extensions; } } }); ForEach.program(gltf, function(program) { if (defined(program.vertexShader)) { program.vertexShader = globalMapping.shaders[program.vertexShader]; } if (defined(program.fragmentShader)) { program.fragmentShader = globalMapping.shaders[program.fragmentShader]; } }); ForEach.technique(gltf, function(technique) { if (defined(technique.program)) { technique.program = globalMapping.programs[technique.program]; } ForEach.techniqueParameter(technique, function(parameter) { if (defined(parameter.node)) { parameter.node = globalMapping.nodes[parameter.node]; } var value = parameter.value; if (defined(value)) { if (Array.isArray(value)) { if (value.length === 1) { var textureId = value[0]; if (typeof textureId === 'string') { value[0] = globalMapping.textures[textureId]; } } } else if (typeof value === 'string') { parameter.value = [globalMapping.textures[value]]; } } }); }); ForEach.mesh(gltf, function(mesh) { ForEach.meshPrimitive(mesh, function(primitive) { if (defined(primitive.indices)) { primitive.indices = globalMapping.accessors[primitive.indices]; } ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) { primitive.attributes[semantic] = globalMapping.accessors[accessorId]; }); if (defined(primitive.material)) { primitive.material = globalMapping.materials[primitive.material]; } }); }); ForEach.node(gltf, function(node) { var children = node.children; if (defined(children)) { var childrenLength = children.length; for (i = 0; i < childrenLength; i++) { children[i] = globalMapping.nodes[children[i]]; } } if (defined(node.meshes)) { // Split out meshes on nodes var meshes = node.meshes; var meshesLength = meshes.length; if (meshesLength > 0) { node.mesh = globalMapping.meshes[meshes[0]]; for (i = 1; i < meshesLength; i++) { var meshNode = { mesh: globalMapping.meshes[meshes[i]], extras: { _pipeline: {} } }; var meshNodeId = addToArray(gltf.nodes, meshNode); if (!defined(children)) { children = []; node.children = children; } children.push(meshNodeId); } } delete node.meshes; } if (defined(node.camera)) { node.camera = globalMapping.cameras[node.camera]; } if (defined(node.skeletons)) { // Assign skeletons to skins var skeletons = node.skeletons; var skeletonsLength = skeletons.length; if ((skeletonsLength > 0) && defined(node.skin)) { var skin = gltf.skins[globalMapping.skins[node.skin]]; skin.skeleton = globalMapping.nodes[skeletons[0]]; } delete node.skeletons; } if (defined(node.skin)) { node.skin = globalMapping.skins[node.skin]; } if (defined(node.jointName)) { delete(node.jointName); } }); ForEach.skin(gltf, function(skin) { if (defined(skin.inverseBindMatrices)) { skin.inverseBindMatrices = globalMapping.accessors[skin.inverseBindMatrices]; } var joints = []; var jointNames = skin.jointNames; if (defined(jointNames)) { for (i = 0; i < jointNames.length; i++) { joints[i] = jointNameToId[jointNames[i]]; } skin.joints = joints; delete skin.jointNames; } }); ForEach.scene(gltf, function(scene) { var sceneNodes = scene.nodes; if (defined(sceneNodes)) { var sceneNodesLength = sceneNodes.length; for (i = 0; i < sceneNodesLength; i++) { sceneNodes[i] = globalMapping.nodes[sceneNodes[i]]; } } }); ForEach.animation(gltf, function(animation) { var samplerMapping = {}; animation.samplers = objectToArray(animation.samplers, samplerMapping); ForEach.animationSampler(animation, function(sampler) { sampler.input = globalMapping.accessors[sampler.input]; sampler.output = globalMapping.accessors[sampler.output]; }); var channels = animation.channels; if (defined(channels)) { var channelsLength = channels.length; for (i = 0; i < channelsLength; i++) { var channel = channels[i]; channel.sampler = samplerMapping[channel.sampler]; var target = channel.target; if (defined(target)) { target.node = globalMapping.nodes[target.id]; delete target.id; } } } }); ForEach.material(gltf, function(material) { if (defined(material.technique)) { material.technique = globalMapping.techniques[material.technique]; } ForEach.materialValue(material, function(value, name) { if (Array.isArray(value)) { if (value.length === 1) { var textureId = value[0]; if (typeof textureId === 'string') { value[0] = globalMapping.textures[textureId]; } } } else if (typeof value === 'string') { material.values[name] = { index : globalMapping.textures[value] }; } }); var extensions = material.extensions; if (defined(extensions)) { var materialsCommon = extensions.KHR_materials_common; if (defined(materialsCommon)) { ForEach.materialValue(materialsCommon, function(value, name) { if (Array.isArray(value)) { if (value.length === 1) { var textureId = value[0]; if (typeof textureId === 'string') { value[0] = globalMapping.textures[textureId]; } } } else if (typeof value === 'string') { materialsCommon.values[name] = { index: globalMapping.textures[value] }; } }); } } }); ForEach.image(gltf, function(image) { var extensions = image.extensions; if (defined(extensions)) { var binaryGltf = extensions.KHR_binary_glTF; if (defined(binaryGltf)) { image.bufferView = globalMapping.bufferViews[binaryGltf.bufferView]; image.mimeType = binaryGltf.mimeType; delete extensions.KHR_binary_glTF; } if (Object.keys(extensions).length === 0) { delete image.extensions; } } if (defined(image.extras)) { var compressedImages = image.extras.compressedImage3DTiles; for (var type in compressedImages) { if (compressedImages.hasOwnProperty(type)) { var compressedImage = compressedImages[type]; var compressedExtensions = compressedImage.extensions; if (defined(compressedExtensions)) { var compressedBinaryGltf = compressedExtensions.KHR_binary_glTF; if (defined(compressedBinaryGltf)) { compressedImage.bufferView = globalMapping.bufferViews[compressedBinaryGltf.bufferView]; compressedImage.mimeType = compressedBinaryGltf.mimeType; delete compressedExtensions.KHR_binary_glTF; } if (Object.keys(compressedExtensions).length === 0) { delete compressedImage.extensions; } } } } } }); ForEach.texture(gltf, function(texture) { if (defined(texture.sampler)) { texture.sampler = globalMapping.samplers[texture.sampler]; } if (defined(texture.source)) { texture.source = globalMapping.images[texture.source]; } }); } function stripProfile(gltf) { var asset = gltf.asset; delete asset.profile; } var knownExtensions = { CESIUM_RTC : true, KHR_materials_common : true, WEB3D_quantized_attributes : true }; function requireKnownExtensions(gltf) { var extensionsUsed = gltf.extensionsUsed; gltf.extensionsRequired = defaultValue(gltf.extensionsRequired, []); if (defined(extensionsUsed)) { var extensionsUsedLength = extensionsUsed.length; for (var i = 0; i < extensionsUsedLength; i++) { var extension = extensionsUsed[i]; if (defined(knownExtensions[extension])) { gltf.extensionsRequired.push(extension); } } } } function removeBufferType(gltf) { ForEach.buffer(gltf, function(buffer) { delete buffer.type; }); } function requireAttributeSetIndex(gltf) { ForEach.mesh(gltf, function(mesh) { ForEach.meshPrimitive(mesh, function(primitive) { ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) { if (semantic === 'TEXCOORD') { primitive.attributes.TEXCOORD_0 = accessorId; } else if (semantic === 'COLOR') { primitive.attributes.COLOR_0 = accessorId; } }); delete primitive.attributes.TEXCOORD; delete primitive.attributes.COLOR; }); }); ForEach.technique(gltf, function(technique) { ForEach.techniqueParameter(technique, function(parameter) { var semantic = parameter.semantic; if (defined(semantic)) { if (semantic === 'TEXCOORD') { parameter.semantic = 'TEXCOORD_0'; } else if (semantic === 'COLOR') { parameter.semantic = 'COLOR_0'; } } }); }); } var knownSemantics = { POSITION: true, NORMAL: true, TEXCOORD: true, COLOR: true, JOINT: true, WEIGHT: true }; function underscoreApplicationSpecificSemantics(gltf) { var mappedSemantics = {}; ForEach.mesh(gltf, function(mesh) { ForEach.meshPrimitive(mesh, function(primitive) { /* jshint unused:vars */ ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) { if (semantic.charAt(0) !== '_') { var setIndex = semantic.search(/_[0-9]+/g); var strippedSemantic = semantic; if (setIndex >= 0) { strippedSemantic = semantic.substring(0, setIndex); } if (!defined(knownSemantics[strippedSemantic])) { var newSemantic = '_' + semantic; mappedSemantics[semantic] = newSemantic; } } }); for (var semantic in mappedSemantics) { if (mappedSemantics.hasOwnProperty(semantic)) { var mappedSemantic = mappedSemantics[semantic]; var accessorId = primitive.attributes[semantic]; if (defined(accessorId)) { delete primitive.attributes[semantic]; primitive.attributes[mappedSemantic] = accessorId; } } } }); }); ForEach.technique(gltf, function(technique) { ForEach.techniqueParameter(technique, function(parameter) { var mappedSemantic = mappedSemantics[parameter.semantic]; if (defined(mappedSemantic)) { parameter.semantic = mappedSemantic; } }); }); } function removeScissorFromTechniques(gltf) { ForEach.technique(gltf, function(technique) { var techniqueStates = technique.states; if (defined(techniqueStates)) { var techniqueFunctions = techniqueStates.functions; if (defined(techniqueFunctions)) { delete techniqueFunctions.scissor; } var enableStates = techniqueStates.enable; if (defined(enableStates)) { var scissorIndex = enableStates.indexOf(WebGLConstants.SCISSOR_TEST); if (scissorIndex >= 0) { enableStates.splice(scissorIndex, 1); } } } }); } function clampTechniqueFunctionStates(gltf) { ForEach.technique(gltf, function(technique) { var techniqueStates = technique.states; if (defined(techniqueStates)) { var functions = techniqueStates.functions; if (defined(functions)) { var blendColor = functions.blendColor; if (defined(blendColor)) { for (var i = 0; i < 4; i++) { blendColor[i] = CesiumMath.clamp(blendColor[i], 0.0, 1.0); } } var depthRange = functions.depthRange; if (defined(depthRange)) { depthRange[1] = CesiumMath.clamp(depthRange[1], 0.0, 1.0); depthRange[0] = CesiumMath.clamp(depthRange[0], 0.0, depthRange[1]); } } } }); } function clampCameraParameters(gltf) { ForEach.camera(gltf, function(camera) { var perspective = camera.perspective; if (defined(perspective)) { var aspectRatio = perspective.aspectRatio; if (defined(aspectRatio) && aspectRatio === 0.0) { delete perspective.aspectRatio; } var yfov = perspective.yfov; if (defined(yfov) && yfov === 0.0) { perspective.yfov = 1.0; } } }); } function requireByteLength(gltf) { ForEach.buffer(gltf, function(buffer) { if (!defined(buffer.byteLength)) { buffer.byteLength = buffer.extras._pipeline.source.length; } }); ForEach.bufferView(gltf, function(bufferView) { if (!defined(bufferView.byteLength)) { var bufferViewBufferId = bufferView.buffer; var bufferViewBuffer = gltf.buffers[bufferViewBufferId]; bufferView.byteLength = bufferViewBuffer.byteLength; } }); } function moveByteStrideToBufferView(gltf) { var bufferViews = gltf.bufferViews; var bufferViewsToDelete = {}; ForEach.accessor(gltf, function(accessor) { var oldBufferViewId = accessor.bufferView; if (defined(oldBufferViewId)) { if (!defined(bufferViewsToDelete[oldBufferViewId])) { bufferViewsToDelete[oldBufferViewId] = true; } var bufferView = clone(bufferViews[oldBufferViewId]); var accessorByteStride = (defined(accessor.byteStride) && accessor.byteStride !== 0) ? accessor.byteStride : getAccessorByteStride(gltf, accessor); if (defined(accessorByteStride)) { bufferView.byteStride = accessorByteStride; if (bufferView.byteStride !== 0) { bufferView.byteLength = accessor.count * accessorByteStride; } bufferView.byteOffset += accessor.byteOffset; accessor.byteOffset = 0; delete accessor.byteStride; } accessor.bufferView = addToArray(bufferViews, bufferView); } }); var bufferViewShiftMap = {}; var bufferViewRemovalCount = 0; /* jshint unused:vars */ ForEach.bufferView(gltf, function(bufferView, bufferViewId) { if (defined(bufferViewsToDelete[bufferViewId])) { bufferViewRemovalCount++; } else { bufferViewShiftMap[bufferViewId] = bufferViewId - bufferViewRemovalCount; } }); var removedCount = 0; for (var bufferViewId in bufferViewsToDelete) { if (defined(bufferViewId)) { var index = parseInt(bufferViewId) - removedCount; bufferViews.splice(index, 1); removedCount++; } } ForEach.accessor(gltf, function(accessor) { var accessorBufferView = accessor.bufferView; if (defined(accessorBufferView)) { accessor.bufferView = bufferViewShiftMap[accessorBufferView]; } }); ForEach.shader(gltf, function(shader) { var shaderBufferView = shader.bufferView; if (defined(shaderBufferView)) { shader.bufferView = bufferViewShiftMap[shaderBufferView]; } }); ForEach.image(gltf, function(image) { var imageBufferView = image.bufferView; if (defined(imageBufferView)) { image.bufferView = bufferViewShiftMap[imageBufferView]; } if (defined(image.extras)) { var compressedImages = image.extras.compressedImage3DTiles; for (var type in compressedImages) { if (compressedImages.hasOwnProperty(type)) { var compressedImage = compressedImages[type]; var compressedImageBufferView = compressedImage.bufferView; if (defined(compressedImageBufferView)) { compressedImage.bufferView = bufferViewShiftMap[compressedImageBufferView]; } } } } }); } function stripTechniqueAttributeValues(gltf) { ForEach.technique(gltf, function(technique) { ForEach.techniqueAttribute(technique, function(attribute) { var parameter = technique.parameters[attribute]; if (defined(parameter.value)) { delete parameter.value; } }); }); } function stripTechniqueParameterCount(gltf) { ForEach.technique(gltf, function(technique) { ForEach.techniqueParameter(technique, function(parameter) { if (defined(parameter.count)) { var semantic = parameter.semantic; if (!defined(semantic) || (semantic !== 'JOINTMATRIX' && semantic.indexOf('_') !== 0)) { delete parameter.count; } } }); }); } function addKHRTechniqueExtension(gltf) { var techniques = gltf.techniques; if (defined(techniques) && techniques.length > 0) { addExtensionsRequired(gltf, 'KHR_technique_webgl'); } } function glTF10to20(gltf) { if (!defined(gltf.asset)) { gltf.asset = {}; } var asset = gltf.asset; asset.version = '2.0'; // material.instanceTechnique properties should be directly on the material. instanceTechnique is a gltf 0.8 property but is seen in some 1.0 models. updateInstanceTechniques(gltf); // animation.samplers now refers directly to accessors and animation.parameters should be removed removeAnimationSamplersIndirection(gltf); // top-level objects are now arrays referenced by index instead of id objectsToArrays(gltf); // asset.profile no longer exists stripProfile(gltf); // move known extensions from extensionsUsed to extensionsRequired requireKnownExtensions(gltf); // bufferView.byteLength and buffer.byteLength are required requireByteLength(gltf); // byteStride moved from accessor to bufferView moveByteStrideToBufferView(gltf); // buffer.type is unnecessary and should be removed removeBufferType(gltf); // TEXCOORD and COLOR attributes must be written with a set index (TEXCOORD_#) requireAttributeSetIndex(gltf); // Add underscores to application-specific parameters underscoreApplicationSpecificSemantics(gltf); // remove scissor from techniques removeScissorFromTechniques(gltf); // clamp technique function states to min/max clampTechniqueFunctionStates(gltf); // clamp camera parameters clampCameraParameters(gltf); // a technique parameter specified as an attribute cannot have a value stripTechniqueAttributeValues(gltf); // only techniques with a JOINTMATRIX or application specific semantic may have a defined count property stripTechniqueParameterCount(gltf); // add KHR_technique_webgl extension addKHRTechniqueExtension(gltf); } return updateVersion; });
EnquistLab/ffdm-frontend
public/assets/images/Workers/ThirdParty/GltfPipeline/updateVersion.js
JavaScript
apache-2.0
36,201
goog.module('javascript.protobuf.conformance'); const ConformanceRequest = goog.require('proto.conformance.ConformanceRequest'); const ConformanceResponse = goog.require('proto.conformance.ConformanceResponse'); const TestAllTypesProto2 = goog.require('proto.conformance.TestAllTypesProto2'); const TestAllTypesProto3 = goog.require('proto.conformance.TestAllTypesProto3'); const WireFormat = goog.require('proto.conformance.WireFormat'); const base64 = goog.require('goog.crypt.base64'); /** * Creates a `proto.conformance.ConformanceResponse` response according to the * `proto.conformance.ConformanceRequest` request. * @param {!ConformanceRequest} request * @return {!ConformanceResponse} response */ function doTest(request) { const response = ConformanceResponse.createEmpty(); if(request.getPayloadCase() === ConformanceRequest.PayloadCase.JSON_PAYLOAD) { response.setSkipped('Json is not supported as input format.'); return response; } if(request.getPayloadCase() === ConformanceRequest.PayloadCase.TEXT_PAYLOAD) { response.setSkipped('Text format is not supported as input format.'); return response; } if(request.getPayloadCase() === ConformanceRequest.PayloadCase.PAYLOAD_NOT_SET) { response.setRuntimeError('Request didn\'t have payload.'); return response; } if(request.getPayloadCase() !== ConformanceRequest.PayloadCase.PROTOBUF_PAYLOAD) { throw new Error('Request didn\'t have accepted input format.'); } if (request.getRequestedOutputFormat() === WireFormat.JSON) { response.setSkipped('Json is not supported as output format.'); return response; } if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) { response.setSkipped('Text format is not supported as output format.'); return response; } if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) { response.setRuntimeError('Unspecified output format'); return response; } if (request.getRequestedOutputFormat() !== WireFormat.PROTOBUF) { throw new Error('Request didn\'t have accepted output format.'); } if (request.getMessageType() === 'conformance.FailureSet') { response.setProtobufPayload(new ArrayBuffer(0)); } else if ( request.getMessageType() === 'protobuf_test_messages.proto2.TestAllTypesProto2') { try { const testMessage = TestAllTypesProto2.deserialize(request.getProtobufPayload()); response.setProtobufPayload(testMessage.serialize()); } catch (err) { response.setParseError(err.toString()); } } else if ( request.getMessageType() === 'protobuf_test_messages.proto3.TestAllTypesProto3') { try { const testMessage = TestAllTypesProto3.deserialize(request.getProtobufPayload()); response.setProtobufPayload(testMessage.serialize()); } catch (err) { response.setParseError(err.toString()); } } else { throw new Error( `Payload message not supported: ${request.getMessageType()}.`); } return response; } /** * Same as doTest, but both request and response are in base64. * @param {string} base64Request * @return {string} response */ function runConformanceTest(base64Request) { const request = ConformanceRequest.deserialize( base64.decodeStringToUint8Array(base64Request).buffer); const response = doTest(request); return base64.encodeByteArray(new Uint8Array(response.serialize())); } // Needed for node test exports.doTest = doTest; // Needed for browser test goog.exportSymbol('runConformanceTest', runConformanceTest);
nwjs/chromium.src
third_party/protobuf/js/experimental/runtime/kernel/conformance/conformance_testee.js
JavaScript
bsd-3-clause
3,602
/** Messages for Sinhala (සිංහල) * Exported from translatewiki.net * * Translators: * - Singhalawap */ var I18n = { on_leave_page: "ඔබගේ වෙනස්කිරීම් අහිමිවනු ඇත" };
railsfactory-sriman/knowledgeBase
public/javascripts/i18n/si.js
JavaScript
agpl-3.0
235
'use strict'; var utils = require('./utils'); var normalizeHeaderName = require('./helpers/normalizeHeaderName'); var PROTECTION_PREFIX = /^\)\]\}',?\n/; var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } module.exports = { transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { data = data.replace(PROTECTION_PREFIX, ''); try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], headers: { common: { 'Accept': 'application/json, text/plain, */*' }, patch: utils.merge(DEFAULT_CONTENT_TYPE), post: utils.merge(DEFAULT_CONTENT_TYPE), put: utils.merge(DEFAULT_CONTENT_TYPE) }, timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } };
MichaelTsao/yanpei
web/js/node_modules/leancloud-realtime/node_modules/axios/lib/defaults.js
JavaScript
bsd-3-clause
1,867
module.exports = require('./lib/rework');
atomify/atomify-css
test/fixtures/css/node_modules/rework-clone/node_modules/rework/index.js
JavaScript
mit
42
import { __extends } from "tslib"; /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { dataLoader } from "./DataLoader"; import { JSONParser } from "./JSONParser"; import { CSVParser } from "./CSVParser"; import { BaseObjectEvents } from "../Base"; import { Adapter } from "../utils/Adapter"; import { Language } from "../utils/Language"; import { DateFormatter } from "../formatters/DateFormatter"; import { registry } from "../Registry"; import * as $type from "../utils/Type"; import * as $object from "../utils/Object"; ; ; /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * Represents a single data source - external file with all of its settings, * such as format, data parsing, etc. * * ```TypeScript * chart.dataSource.url = "http://www.myweb.com/data.json"; * chart.dataSource.parser = am4core.JSONParser; * ``` * ```JavaScript * chart.dataSource.url = "http://www.myweb.com/data.json"; * chart.dataSource.parser = am4core.JSONParser; * ``` * ```JSON * { * // ... * "dataSource": { * "url": "http://www.myweb.com/data.json", * "parser": "JSONParser" * }, * // ... * } * ``` * * @see {@link IDataSourceEvents} for a list of available events * @see {@link IDataSourceAdapters} for a list of available Adapters */ var DataSource = /** @class */ (function (_super) { __extends(DataSource, _super); /** * Constructor */ function DataSource(url, parser) { var _this = // Init _super.call(this) || this; /** * Adapter. */ _this.adapter = new Adapter(_this); /** * Custom options for HTTP(S) request. */ _this._requestOptions = {}; /** * If set to `true`, any subsequent data loads will be considered incremental * (containing only new data points that are supposed to be added to existing * data). * * NOTE: this setting works only with element's `data` property. It won't * work with any other externally-loadable data property. * * @default false */ _this._incremental = false; /** * A collection of key/value pairs to attach to a data source URL when making * an incremental request. */ _this._incrementalParams = {}; /** * This setting is used only when `incremental = true`. If set to `true`, * it will try to retain the same number of data items across each load. * * E.g. if incremental load yeilded 5 new records, then 5 items from the * beginning of data will be removed so that we end up with the same number * of data items. * * @default false */ _this._keepCount = false; /** * If set to `true`, each subsequent load will be treated as an update to * currently loaded data, meaning that it will try to update values on * existing data items, not overwrite the whole data. * * This will work faster than complete update, and also will animate the * values to their new positions. * * Data sources across loads must contain the same number of data items. * * Loader will not truncate the data set if loaded data has fewer data items, * and if it is longer, the excess data items will be ignored. * * @default false * @since 4.5.5 */ _this._updateCurrentData = false; /** * Will show loading indicator when loading files. */ _this.showPreloader = true; _this.className = "DataSource"; // Set defaults if (url) { _this.url = url; } // Set parser if (parser) { if (typeof parser == "string") { _this.parser = dataLoader.getParserByType(parser); } else { _this.parser = parser; } } return _this; } /** * Processes the loaded data. * * @ignore Exclude from docs * @param data Raw (unparsed) data * @param contentType Content type of the loaded data (optional) */ DataSource.prototype.processData = function (data, contentType) { // Parsing started this.dispatchImmediately("parsestarted"); // Check if parser is set if (!this.parser) { // Try to resolve from data this.parser = dataLoader.getParserByData(data, contentType); if (!this.parser) { // We have a problem - nobody knows what to do with the data // Raise error if (this.events.isEnabled("parseerror")) { var event_1 = { type: "parseerror", message: this.language.translate("No parser available for file: %1", null, this.url), target: this }; this.events.dispatchImmediately("parseerror", event_1); } this.dispatchImmediately("parseended"); return; } } // Apply options adapters this.parser.options = this.adapter.apply("parserOptions", this.parser.options); this.parser.options.dateFields = this.adapter.apply("dateFields", this.parser.options.dateFields || []); this.parser.options.numberFields = this.adapter.apply("numberFields", this.parser.options.numberFields || []); // Check if we need to pass in date formatter if (this.parser.options.dateFields && !this.parser.options.dateFormatter) { this.parser.options.dateFormatter = this.dateFormatter; } // Parse this.data = this.adapter.apply("parsedData", this.parser.parse(this.adapter.apply("unparsedData", data))); // Check for parsing errors if (!$type.hasValue(this.data) && this.events.isEnabled("parseerror")) { var event_2 = { type: "parseerror", message: this.language.translate("Error parsing file: %1", null, this.url), target: this }; this.events.dispatchImmediately("parseerror", event_2); } // Wrap up this.dispatchImmediately("parseended"); if ($type.hasValue(this.data)) { this.dispatchImmediately("done", { "data": this.data }); } // The component is responsible for updating its own data vtriggered via // events. // Update last data load this.lastLoad = new Date(); }; Object.defineProperty(DataSource.prototype, "url", { /** * @return URL */ get: function () { // Get URL var url = this.disableCache ? this.timestampUrl(this._url) : this._url; // Add incremental params if (this.incremental && this.component.data.length) { url = this.addUrlParams(url, this.incrementalParams); } return this.adapter.apply("url", url); }, /** * URL of the data source. * * @param value URL */ set: function (value) { this._url = value; }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "requestOptions", { /** * @return Options */ get: function () { return this.adapter.apply("requestOptions", this._requestOptions); }, /** * Custom options for HTTP(S) request. * * At this moment the only option supported is: `requestHeaders`, which holds * an array of objects for custom request headers, e.g.: * * ```TypeScript * chart.dataSource.requestOptions.requestHeaders = [{ * "key": "x-access-token", * "value": "123456789" * }]; * ``````JavaScript * chart.dataSource.requestOptions.requestHeaders = [{ * "key": "x-access-token", * "value": "123456789" * }]; * ``` * ```JSON * { * // ... * "dataSource": { * // ... * "requestOptions": { * "requestHeaders": [{ * "key": "x-access-token", * "value": "123456789" * }] * } * } * } * ``` * * NOTE: setting this options on an-already loaded DataSource will not * trigger a reload. * * @param value Options */ set: function (value) { this._requestOptions = value; }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "parser", { /** * @return Data parser */ get: function () { if (!this._parser) { this._parser = new JSONParser(); } return this.adapter.apply("parser", this._parser); }, /** * A parser to be used to parse data. * * ```TypeScript * chart.dataSource.url = "http://www.myweb.com/data.json"; * chart.dataSource.parser = am4core.JSONParser; * ``` * ```JavaScript * chart.dataSource.url = "http://www.myweb.com/data.json"; * chart.dataSource.parser = am4core.JSONParser; * ``` * ```JSON * { * // ... * "dataSource": { * "url": "http://www.myweb.com/data.json", * "parser": { * "type": "JSONParser" * } * }, * // ... * } * ``` * * @default JSONParser * @param value Data parser */ set: function (value) { this._parser = value; }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "reloadFrequency", { /** * @return Reload frequency (ms) */ get: function () { return this.adapter.apply("reloadTimeout", this._reloadFrequency); }, /** * Data source reload frequency. * * If set, it will reload the same URL every X milliseconds. * * @param value Reload frequency (ms) */ set: function (value) { var _this = this; if (this._reloadFrequency != value) { this._reloadFrequency = value; // Should we schedule a reload? if (value) { if (!$type.hasValue(this._reloadDisposer)) { this._reloadDisposer = this.events.on("ended", function (ev) { _this._reloadTimeout = setTimeout(function () { _this.load(); }, _this.reloadFrequency); }); } } else if ($type.hasValue(this._reloadDisposer)) { this._reloadDisposer.dispose(); this._reloadDisposer = undefined; } } }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "incremental", { /** * @return Incremental load? */ get: function () { return this.adapter.apply("incremental", this._incremental); }, /** * Should subsequent reloads be treated as incremental? * * Incremental loads will assume that they contain only new data items * since the last load. * * If `incremental = false` the loader will replace all of the target's * data with each load. * * This setting does not have any effect trhe first time data is loaded. * * NOTE: this setting works only with element's `data` property. It won't * work with any other externally-loadable data property. * * @default false * @param Incremental load? */ set: function (value) { this._incremental = value; }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "incrementalParams", { /** * @return Incremental request parameters */ get: function () { return this.adapter.apply("incrementalParams", this._incrementalParams); }, /** * An object consisting of key/value pairs to apply to an URL when data * source is making an incremental request. * * @param value Incremental request parameters */ set: function (value) { this._incrementalParams = value; }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "keepCount", { /** * @return keepCount load? */ get: function () { return this.adapter.apply("keepCount", this._keepCount); }, /** * This setting is used only when `incremental = true`. If set to `true`, * it will try to retain the same number of data items across each load. * * E.g. if incremental load yeilded 5 new records, then 5 items from the * beginning of data will be removed so that we end up with the same number * of data items. * * @default false * @param Keep record count? */ set: function (value) { this._keepCount = value; }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "updateCurrentData", { /** * @return Update current data? */ get: function () { return this.adapter.apply("updateCurrentData", this._updateCurrentData); }, /** * If set to `true`, each subsequent load will be treated as an update to * currently loaded data, meaning that it will try to update values on * existing data items, not overwrite the whole data. * * This will work faster than complete update, and also will animate the * values to their new positions. * * Data sources across loads must contain the same number of data items. * * Loader will not truncate the data set if loaded data has fewer data items, * and if it is longer, the excess data items will be ignored. * * NOTE: this setting is ignored if `incremental = true`. * * @default false * @since 2.5.5 * @param Update current data? */ set: function (value) { this._updateCurrentData = value; }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "language", { /** * @return A [[Language]] instance to be used */ get: function () { if (this._language) { return this._language; } else if (this.component) { this._language = this.component.language; return this._language; } this.language = new Language(); return this.language; }, /** * Language instance to use. * * Will inherit and use chart's language, if not set. * * @param value An instance of Language */ set: function (value) { this._language = value; }, enumerable: true, configurable: true }); Object.defineProperty(DataSource.prototype, "dateFormatter", { /** * @return A [[DateFormatter]] instance to be used */ get: function () { if (this._dateFormatter) { return this._dateFormatter; } else if (this.component) { this._dateFormatter = this.component.dateFormatter; return this._dateFormatter; } this.dateFormatter = new DateFormatter(); return this.dateFormatter; }, /** * A [[DateFormatter]] to use when parsing dates from string formats. * * Will inherit and use chart's DateFormatter if not ser. * * @param value An instance of [[DateFormatter]] */ set: function (value) { this._dateFormatter = value; }, enumerable: true, configurable: true }); /** * Adds current timestamp to the URL. * * @param url Source URL * @return Timestamped URL */ DataSource.prototype.timestampUrl = function (url) { var tstamp = new Date().getTime().toString(); var params = {}; params[tstamp] = ""; return this.addUrlParams(url, params); }; /** * Disposes of this object. */ DataSource.prototype.dispose = function () { _super.prototype.dispose.call(this); if (this._reloadTimeout) { clearTimeout(this._reloadTimeout); } if ($type.hasValue(this._reloadDisposer)) { this._reloadDisposer.dispose(); this._reloadDisposer = undefined; } }; /** * Initiate the load. * * All loading in JavaScript is asynchronous. This function will trigger the * load and will exit immediately. * * Use DataSource's events to watch for loaded data and errors. */ DataSource.prototype.load = function () { if (this.url) { if (this._reloadTimeout) { clearTimeout(this._reloadTimeout); } dataLoader.load(this); } }; /** * Adds parameters to `url` as query strings. Will take care of proper * separators. * * @param url Source URL * @param params Parameters * @return New URL */ DataSource.prototype.addUrlParams = function (url, params) { var join = url.match(/\?/) ? "&" : "?"; var add = []; $object.each(params, function (key, value) { if (value != "") { add.push(key + "=" + encodeURIComponent(value)); } else { add.push(key); } }); if (add.length) { return url + join + add.join("&"); } return url; }; /** * Processes JSON-based config before it is applied to the object. * * @ignore Exclude from docs * @param config Config */ DataSource.prototype.processConfig = function (config) { registry.registeredClasses["json"] = JSONParser; registry.registeredClasses["JSONParser"] = JSONParser; registry.registeredClasses["csv"] = CSVParser; registry.registeredClasses["CSVParser"] = CSVParser; _super.prototype.processConfig.call(this, config); }; return DataSource; }(BaseObjectEvents)); export { DataSource }; //# sourceMappingURL=DataSource.js.map
cdnjs/cdnjs
ajax/libs/amcharts4/4.10.9/.internal/core/data/DataSource.js
JavaScript
mit
20,447
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-93-1.js * @description Object.defineProperties will update [[Value]] attribute of named data property 'P' successfully when [[Configurable]] attribute is true and [[Writable]] attribute is false but not when both are false (8.12.9 - step Note & 10.a.ii.1) */ function testcase() { var obj = {}; Object.defineProperty(obj, "property", { value: 1001, writable: false, configurable: true }); Object.defineProperty(obj, "property1", { value: 1003, writable: false, configurable: false }); try { Object.defineProperties(obj, { property: { value: 1002 }, property1: { value: 1004 } }); return false; } catch (e) { return e instanceof TypeError && dataPropertyAttributesAreCorrect(obj, "property", 1002, false, false, true) && dataPropertyAttributesAreCorrect(obj, "property1", 1003, false, false, false); } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-93-1.js
JavaScript
bsd-3-clause
1,285
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-7-c-ii-10.js * @description Array.prototype.some - callbackfn is called with 1 formal parameter */ function testcase() { function callbackfn(val) { return val > 10; } return [11, 12].some(callbackfn); } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-7-c-ii-10.js
JavaScript
bsd-3-clause
388
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch10/10.4/10.4.3/10.4.3-1-49gs.js * @description Strict - checking 'this' from a global scope (FunctionExpression with a strict directive prologue defined within a FunctionExpression) * @noStrict */ var f1 = function () { var f = function () { "use strict"; return typeof this; } return (f()==="undefined") && (this===fnGlobalObject()); } if (! f1()) { throw "'this' had incorrect value!"; }
Oceanswave/NiL.JS
Tests/tests/sputnik/ch10/10.4/10.4.3/10.4.3-1-49gs.js
JavaScript
bsd-3-clause
506
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-b-16.js * @description Array.prototype.map - decreasing length of array does not delete non-configurable properties */ function testcase() { function callbackfn(val, idx, obj) { if (idx === 2 && val === "unconfigurable") { return false; } else { return true; } } var arr = [0, 1, 2]; Object.defineProperty(arr, "2", { get: function () { return "unconfigurable"; }, configurable: false }); Object.defineProperty(arr, "1", { get: function () { arr.length = 2; return 1; }, configurable: true }); var testResult = arr.map(callbackfn); return testResult.length === 3 && testResult[2] === false; } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-b-16.js
JavaScript
bsd-3-clause
1,006
define([ 'css!theme/liveblog', 'tmpl!theme/container', 'tmpl!theme/item/base', 'plugins/wrappup-toggle', 'plugins/scroll-pagination', 'plugins/permanent-link', 'plugins/user-comments' ], function(){ });
vladnicoara/SDLive-Blog
plugins/livedesk-embed/gui-themes/themes/tageswoche.min.js
JavaScript
agpl-3.0
209
const url_base = "/permissions-policy/experimental-features/resources/"; window.messageResponseCallback = null; function setFeatureState(iframe, feature, origins) { iframe.setAttribute("allow", `${feature} ${origins};`); } // Returns a promise which is resolved when the <iframe> is navigated to |url| // and "load" handler has been called. function loadUrlInIframe(iframe, url) { return new Promise((resolve) => { iframe.addEventListener("load", resolve); iframe.src = url; }); } // Posts |message| to |target| and resolves the promise with the response coming // back from |target|. function sendMessageAndGetResponse(target, message) { return new Promise((resolve) => { window.messageResponseCallback = resolve; target.postMessage(message, "*"); }); } function onMessage(e) { if (window.messageResponseCallback) { window.messageResponseCallback(e.data); window.messageResponseCallback = null; } } window.addEventListener("message", onMessage); // Waits for |load_timeout| before resolving the promise. It will resolve the // promise sooner if a message event with |e.data.id| of |id| is received. // In such a case the response is the contents of the message |e.data.contents|. // Otherwise, returns false (when timeout occurs). function waitForMessageOrTimeout(t, id, load_timeout) { return new Promise((resolve) => { window.addEventListener( "message", (e) => { if (!e.data || e.data.id !== id) return; resolve(e.data.contents); } ); t.step_timeout(() => { resolve(false); }, load_timeout); }); } function createIframe(container, attributes) { var new_iframe = document.createElement("iframe"); for (attr_name in attributes) new_iframe.setAttribute(attr_name, attributes[attr_name]); container.appendChild(new_iframe); return new_iframe; } // Returns a promise which is resolved when |load| event is dispatched for |e|. function wait_for_load(e) { return new Promise((resolve) => { e.addEventListener("load", resolve); }); } setup(() => { window.reporting_observer_instance = new ReportingObserver((reports, observer) => { if (window.reporting_observer_callback) { reports.forEach(window.reporting_observer_callback); } }, {types: ["permissions-policy-violation"]}); window.reporting_observer_instance.observe(); window.reporting_observer_callback = null; }); // Waits for a violation in |feature| and source file containing |file_name|. function wait_for_violation_in_file(feature, file_name) { return new Promise( (resolve) => { assert_equals(null, window.reporting_observer_callback); window.reporting_observer_callback = (report) => { var feature_match = (feature === report.body.featureId); var file_name_match = !file_name || (report.body.sourceFile.indexOf(file_name) !== -1); if (feature_match && file_name_match) { window.reporting_observer_callback = null; resolve(report); } }; }); }
chromium/chromium
third_party/blink/web_tests/external/wpt/permissions-policy/experimental-features/resources/common.js
JavaScript
bsd-3-clause
3,063
var assert = require('assert'); var R = require('..'); describe('add', function() { it('adds together two numbers', function() { assert.strictEqual(R.add(3, 7), 10); }); it('is curried', function() { var incr = R.add(1); assert.strictEqual(incr(42), 43); }); });
kairyan/ramda
test/add.js
JavaScript
mit
287
var URL = require("../url2"); var tests = [ { source: "", target: "", relative: "" }, { source: "foo/bar/", target: "foo/bar/", relative: "" }, { source: "foo/bar/baz", target: "foo/bar/", relative: "./" }, { source: "foo/bar/", target: "/foo/bar/", relative: "/foo/bar/" }, { source: "/foo/bar/baz", target: "/foo/bar/quux", relative: "quux" }, { source: "/foo/bar/baz", target: "/foo/bar/quux/asdf", relative: "quux/asdf" }, { source: "/foo/bar/baz", target: "/foo/bar/quux/baz", relative: "quux/baz" }, { source: "/foo/bar/baz", target: "/foo/quux/baz", relative: "../quux/baz" }, { source: "/foo/bar/baz", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "/foo/bar/baz?a=10", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "/foo/bar/baz?b=20", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "http://example.com", target: "/foo/bar", relative: "/foo/bar" }, { source: "", target: "http://example.com/foo/bar", relative: "http://example.com/foo/bar" }, { source: "", target: "#foo", relative: "#foo" }, { source: "", target: "?a=10", relative: "?a=10" }, { source: "?a=10", target: "#foo", relative: "?a=10#foo" }, { source: "file:///test.js", target: "file:///test.js", relative: "test.js" }, { source: "file:///test.js", target: "file:///test/test.js", relative: "test/test.js" } ]; describe("relative", function () { tests.forEach(function (test) { (test.focus ? iit : it)( test.label || ( "from " + JSON.stringify(test.source) + " " + "to " + JSON.stringify(test.target) ), function () { expect(URL.relative(test.source, test.target)) .toBe(test.relative) } ) }); it("should format a url with a path property", function () { expect(URL.format({path: "a/b"})).toEqual("a/b"); expect(URL.format({path: "a/b?c=d"})).toEqual("a/b?c=d"); }); });
AlexanderDolgan/sputnik
wp-content/themes/node_modules/gulp.spritesmith/node_modules/url2/test/url2-spec.js
JavaScript
gpl-2.0
2,582
import { Mongo } from "meteor/mongo"; /** * Client side collections */ export const Countries = new Mongo.Collection(null);
deetail/kimchi4u
client/collections/countries.js
JavaScript
gpl-3.0
128
/* * Planck.js v0.1.34 * * Copyright (c) 2016-2017 Ali Shakiba http://shakiba.me/planck.js * Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* * Stage.js * * @copyright 2017 Ali Shakiba http://shakiba.me/stage.js * @license The MIT License */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.planck=e()}}(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(require,module,exports){ var planck = require("../lib/"); var Stage = require("stage-js/platform/web"); module.exports = planck; planck.testbed = function(opts, callback) { if (typeof opts === "function") { callback = opts; opts = null; } Stage(function(stage, canvas) { stage.on(Stage.Mouse.START, function() { window.focus(); document.activeElement && document.activeElement.blur(); canvas.focus(); }); stage.MAX_ELAPSE = 1e3 / 30; var Vec2 = planck.Vec2; var testbed = {}; var paused = false; stage.on("resume", function() { paused = false; testbed._resume && testbed._resume(); }); stage.on("pause", function() { paused = true; testbed._pause && testbed._pause(); }); testbed.isPaused = function() { return paused; }; testbed.togglePause = function() { paused ? testbed.play() : testbed.pause(); }; testbed.pause = function() { stage.pause(); }; testbed.resume = function() { stage.resume(); testbed.focus(); }; testbed.focus = function() { document.activeElement && document.activeElement.blur(); canvas.focus(); }; testbed.focus = function() { document.activeElement && document.activeElement.blur(); canvas.focus(); }; testbed.debug = false; testbed.width = 80; testbed.height = 60; testbed.x = 0; testbed.y = -10; testbed.ratio = 16; testbed.hz = 60; testbed.speed = 1; testbed.activeKeys = {}; testbed.background = "#222222"; var statusText = ""; var statusMap = {}; function statusSet(name, value) { if (typeof value !== "function" && typeof value !== "object") { statusMap[name] = value; } } function statusMerge(obj) { for (var key in obj) { statusSet(key, obj[key]); } } testbed.status = function(a, b) { if (typeof b !== "undefined") { statusSet(a, b); } else if (a && typeof a === "object") { statusMerge(a); } else if (typeof a === "string") { statusText = a; } testbed._status && testbed._status(statusText, statusMap); }; testbed.info = function(text) { testbed._info && testbed._info(text); }; var lastDrawHash = "", drawHash = ""; (function() { var drawingTexture = new Stage.Texture(); stage.append(Stage.image(drawingTexture)); var buffer = []; stage.tick(function() { buffer.length = 0; }, true); drawingTexture.draw = function(ctx) { ctx.save(); ctx.transform(1, 0, 0, -1, -testbed.x, -testbed.y); ctx.lineWidth = 2 / testbed.ratio; ctx.lineCap = "round"; for (var drawing = buffer.shift(); drawing; drawing = buffer.shift()) { drawing(ctx, testbed.ratio); } ctx.restore(); }; testbed.drawPoint = function(p, r, color) { buffer.push(function(ctx, ratio) { ctx.beginPath(); ctx.arc(p.x, p.y, 5 / ratio, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "point" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawCircle = function(p, r, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "circle" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawSegment = function(a, b, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "segment" + a.x + "," + a.y + "," + b.x + "," + b.y + "," + color; }; testbed.drawPolygon = function(points, color) { if (!points || !points.length) { return; } buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); for (var i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i].y); } ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "segment"; for (var i = 1; i < points.length; i++) { drawHash += points[i].x + "," + points[i].y + ","; } drawHash += color; }; testbed.drawAABB = function(aabb, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(aabb.lowerBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.upperBound.y); ctx.lineTo(aabb.lowerBound.x, aabb.upperBound.y); ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "aabb"; drawHash += aabb.lowerBound.x + "," + aabb.lowerBound.y + ","; drawHash += aabb.upperBound.x + "," + aabb.upperBound.y + ","; drawHash += color; }; testbed.color = function(r, g, b) { r = r * 256 | 0; g = g * 256 | 0; b = b * 256 | 0; return "rgb(" + r + ", " + g + ", " + b + ")"; }; })(); var world = callback(testbed); var viewer = new Viewer(world, testbed); var lastX = 0, lastY = 0; stage.tick(function(dt, t) { if (lastX !== testbed.x || lastY !== testbed.y) { viewer.offset(-testbed.x, -testbed.y); lastX = testbed.x, lastY = testbed.y; } }); viewer.tick(function(dt, t) { if (typeof testbed.step === "function") { testbed.step(dt, t); } if (targetBody) { testbed.drawSegment(targetBody.getPosition(), mouseMove, "rgba(255,255,255,0.2)"); } if (lastDrawHash !== drawHash) { lastDrawHash = drawHash; stage.touch(); } drawHash = ""; return true; }); viewer.scale(1, -1); stage.background(testbed.background); stage.viewbox(testbed.width, testbed.height); stage.pin("alignX", -.5); stage.pin("alignY", -.5); stage.prepend(viewer); function findBody(point) { var body; var aabb = planck.AABB(point, point); world.queryAABB(aabb, function(fixture) { if (body) { return; } if (!fixture.getBody().isDynamic() || !fixture.testPoint(point)) { return; } body = fixture.getBody(); return true; }); return body; } var mouseGround = world.createBody(); var mouseJoint; var targetBody; var mouseMove = { x: 0, y: 0 }; viewer.attr("spy", true).on(Stage.Mouse.START, function(point) { if (targetBody) { return; } var body = findBody(point); if (!body) { return; } if (testbed.mouseForce) { targetBody = body; } else { mouseJoint = planck.MouseJoint({ maxForce: 1e3 }, mouseGround, body, Vec2(point)); world.createJoint(mouseJoint); } }).on(Stage.Mouse.MOVE, function(point) { if (mouseJoint) { mouseJoint.setTarget(point); } mouseMove.x = point.x; mouseMove.y = point.y; }).on(Stage.Mouse.END, function(point) { if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { var force = Vec2.sub(point, targetBody.getPosition()); targetBody.applyForceToCenter(force.mul(testbed.mouseForce), true); targetBody = null; } }).on(Stage.Mouse.CANCEL, function(point) { if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { targetBody = null; } }); window.addEventListener("keydown", function(e) { switch (e.keyCode) { case "P".charCodeAt(0): testbed.togglePause(); break; } }, false); var downKeys = {}; window.addEventListener("keydown", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = true; updateActiveKeys(keyCode, true); testbed.keydown && testbed.keydown(keyCode, String.fromCharCode(keyCode)); }); window.addEventListener("keyup", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = false; updateActiveKeys(keyCode, false); testbed.keyup && testbed.keyup(keyCode, String.fromCharCode(keyCode)); }); var activeKeys = testbed.activeKeys; function updateActiveKeys(keyCode, down) { var char = String.fromCharCode(keyCode); if (/\w/.test(char)) { activeKeys[char] = down; } activeKeys.right = downKeys[39] || activeKeys["D"]; activeKeys.left = downKeys[37] || activeKeys["A"]; activeKeys.up = downKeys[38] || activeKeys["W"]; activeKeys.down = downKeys[40] || activeKeys["S"]; activeKeys.fire = downKeys[32] || downKeys[13]; } }); }; Viewer._super = Stage; Viewer.prototype = Stage._create(Viewer._super.prototype); function Viewer(world, opts) { Viewer._super.call(this); this.label("Planck"); opts = opts || {}; var options = this._options = {}; this._options.speed = opts.speed || 1; this._options.hz = opts.hz || 60; if (Math.abs(this._options.hz) < 1) { this._options.hz = 1 / this._options.hz; } this._options.ratio = opts.ratio || 16; this._options.lineWidth = 2 / this._options.ratio; this._world = world; var timeStep = 1 / this._options.hz; var elapsedTime = 0; this.tick(function(dt) { dt = dt * .001 * options.speed; elapsedTime += dt; while (elapsedTime > timeStep) { world.step(timeStep); elapsedTime -= timeStep; } this.renderWorld(); return true; }, true); world.on("remove-fixture", function(obj) { obj.ui && obj.ui.remove(); }); world.on("remove-joint", function(obj) { obj.ui && obj.ui.remove(); }); } Viewer.prototype.renderWorld = function(world) { var world = this._world; var viewer = this; for (var b = world.getBodyList(); b; b = b.getNext()) { for (var f = b.getFixtureList(); f; f = f.getNext()) { if (!f.ui) { if (f.render && f.render.stroke) { this._options.strokeStyle = f.render.stroke; } else if (b.render && b.render.stroke) { this._options.strokeStyle = b.render.stroke; } else if (b.isDynamic()) { this._options.strokeStyle = "rgba(255,255,255,0.9)"; } else if (b.isKinematic()) { this._options.strokeStyle = "rgba(255,255,255,0.7)"; } else if (b.isStatic()) { this._options.strokeStyle = "rgba(255,255,255,0.5)"; } if (f.render && f.render.fill) { this._options.fillStyle = f.render.fill; } else if (b.render && b.render.fill) { this._options.fillStyle = b.render.fill; } else { this._options.fillStyle = ""; } var type = f.getType(); var shape = f.getShape(); if (type == "circle") { f.ui = viewer.drawCircle(shape, this._options); } if (type == "edge") { f.ui = viewer.drawEdge(shape, this._options); } if (type == "polygon") { f.ui = viewer.drawPolygon(shape, this._options); } if (type == "chain") { f.ui = viewer.drawChain(shape, this._options); } if (f.ui) { f.ui.appendTo(viewer); } } if (f.ui) { var p = b.getPosition(), r = b.getAngle(); if (f.ui.__lastX !== p.x || f.ui.__lastY !== p.y || f.ui.__lastR !== r) { f.ui.__lastX = p.x; f.ui.__lastY = p.y; f.ui.__lastR = r; f.ui.offset(p.x, p.y); f.ui.rotate(r); } } } } for (var j = world.getJointList(); j; j = j.getNext()) { var type = j.getType(); var a = j.getAnchorA(); var b = j.getAnchorB(); if (!j.ui) { this._options.strokeStyle = "rgba(255,255,255,0.2)"; j.ui = viewer.drawJoint(j, this._options); j.ui.pin("handle", .5); if (j.ui) { j.ui.appendTo(viewer); } } if (j.ui) { var cx = (a.x + b.x) * .5; var cy = (a.y + b.y) * .5; var dx = a.x - b.x; var dy = a.y - b.y; var d = Math.sqrt(dx * dx + dy * dy); j.ui.width(d); j.ui.rotate(Math.atan2(dy, dx)); j.ui.offset(cx, cy); } } }; Viewer.prototype.drawJoint = function(joint, options) { var lw = options.lineWidth; var ratio = options.ratio; var length = 10; var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).stretch(); return image; }; Viewer.prototype.drawCircle = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var r = shape.m_radius; var cx = r + lw; var cy = r + lw; var w = r * 2 + lw * 2; var h = r * 2 + lw * 2; var texture = Stage.canvas(function(ctx) { this.size(w, h, ratio); ctx.scale(ratio, ratio); ctx.arc(cx, cy, r, 0, 2 * Math.PI); if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); } ctx.lineTo(cx, cy); ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).offset(shape.m_p.x - cx, shape.m_p.y - cy); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawEdge = function(edge, options) { var lw = options.lineWidth; var ratio = options.ratio; var v1 = edge.m_vertex1; var v2 = edge.m_vertex2; var dx = v2.x - v1.x; var dy = v2.y - v1.y; var length = Math.sqrt(dx * dx + dy * dy); var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var minX = Math.min(v1.x, v2.x); var minY = Math.min(v1.y, v2.y); var image = Stage.image(texture); image.rotate(Math.atan2(dy, dx)); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawPolygon = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) { ctx.closePath(); } if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawChain = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) {} if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; },{"../lib/":27,"stage-js/platform/web":82}],2:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Body; var common = require("./util/common"); var options = require("./util/options"); var Vec2 = require("./common/Vec2"); var Rot = require("./common/Rot"); var Math = require("./common/Math"); var Sweep = require("./common/Sweep"); var Transform = require("./common/Transform"); var Velocity = require("./common/Velocity"); var Position = require("./common/Position"); var Fixture = require("./Fixture"); var Shape = require("./Shape"); var World = require("./World"); var staticBody = Body.STATIC = "static"; var kinematicBody = Body.KINEMATIC = "kinematic"; var dynamicBody = Body.DYNAMIC = "dynamic"; var BodyDef = { type: staticBody, position: Vec2.zero(), angle: 0, linearVelocity: Vec2.zero(), angularVelocity: 0, linearDamping: 0, angularDamping: 0, fixedRotation: false, bullet: false, gravityScale: 1, allowSleep: true, awake: true, active: true, userData: null }; function Body(world, def) { def = options(def, BodyDef); ASSERT && common.assert(Vec2.isValid(def.position)); ASSERT && common.assert(Vec2.isValid(def.linearVelocity)); ASSERT && common.assert(Math.isFinite(def.angle)); ASSERT && common.assert(Math.isFinite(def.angularVelocity)); ASSERT && common.assert(Math.isFinite(def.angularDamping) && def.angularDamping >= 0); ASSERT && common.assert(Math.isFinite(def.linearDamping) && def.linearDamping >= 0); this.m_world = world; this.m_awakeFlag = def.awake; this.m_autoSleepFlag = def.allowSleep; this.m_bulletFlag = def.bullet; this.m_fixedRotationFlag = def.fixedRotation; this.m_activeFlag = def.active; this.m_islandFlag = false; this.m_toiFlag = false; this.m_userData = def.userData; this.m_type = def.type; if (this.m_type == dynamicBody) { this.m_mass = 1; this.m_invMass = 1; } else { this.m_mass = 0; this.m_invMass = 0; } this.m_I = 0; this.m_invI = 0; this.m_xf = Transform.identity(); this.m_xf.p = Vec2.clone(def.position); this.m_xf.q.setAngle(def.angle); this.m_sweep = new Sweep(); this.m_sweep.setTransform(this.m_xf); this.c_velocity = new Velocity(); this.c_position = new Position(); this.m_force = Vec2.zero(); this.m_torque = 0; this.m_linearVelocity = Vec2.clone(def.linearVelocity); this.m_angularVelocity = def.angularVelocity; this.m_linearDamping = def.linearDamping; this.m_angularDamping = def.angularDamping; this.m_gravityScale = def.gravityScale; this.m_sleepTime = 0; this.m_jointList = null; this.m_contactList = null; this.m_fixtureList = null; this.m_prev = null; this.m_next = null; } Body.prototype.isWorldLocked = function() { return this.m_world && this.m_world.isLocked() ? true : false; }; Body.prototype.getWorld = function() { return this.m_world; }; Body.prototype.getNext = function() { return this.m_next; }; Body.prototype.setUserData = function(data) { this.m_userData = data; }; Body.prototype.getUserData = function() { return this.m_userData; }; Body.prototype.getFixtureList = function() { return this.m_fixtureList; }; Body.prototype.getJointList = function() { return this.m_jointList; }; Body.prototype.getContactList = function() { return this.m_contactList; }; Body.prototype.isStatic = function() { return this.m_type == staticBody; }; Body.prototype.isDynamic = function() { return this.m_type == dynamicBody; }; Body.prototype.isKinematic = function() { return this.m_type == kinematicBody; }; Body.prototype.setStatic = function() { this.setType(staticBody); return this; }; Body.prototype.setDynamic = function() { this.setType(dynamicBody); return this; }; Body.prototype.setKinematic = function() { this.setType(kinematicBody); return this; }; Body.prototype.getType = function() { return this.m_type; }; Body.prototype.setType = function(type) { ASSERT && common.assert(type === staticBody || type === kinematicBody || type === dynamicBody); ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type == type) { return; } this.m_type = type; this.resetMassData(); if (this.m_type == staticBody) { this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_sweep.forward(); this.synchronizeFixtures(); } this.setAwake(true); this.m_force.setZero(); this.m_torque = 0; var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { var proxyCount = f.m_proxyCount; for (var i = 0; i < proxyCount; ++i) { broadPhase.touchProxy(f.m_proxies[i].proxyId); } } }; Body.prototype.isBullet = function() { return this.m_bulletFlag; }; Body.prototype.setBullet = function(flag) { this.m_bulletFlag = !!flag; }; Body.prototype.isSleepingAllowed = function() { return this.m_autoSleepFlag; }; Body.prototype.setSleepingAllowed = function(flag) { this.m_autoSleepFlag = !!flag; if (this.m_autoSleepFlag == false) { this.setAwake(true); } }; Body.prototype.isAwake = function() { return this.m_awakeFlag; }; Body.prototype.setAwake = function(flag) { if (flag) { if (this.m_awakeFlag == false) { this.m_awakeFlag = true; this.m_sleepTime = 0; } } else { this.m_awakeFlag = false; this.m_sleepTime = 0; this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_force.setZero(); this.m_torque = 0; } }; Body.prototype.isActive = function() { return this.m_activeFlag; }; Body.prototype.setActive = function(flag) { ASSERT && common.assert(this.isWorldLocked() == false); if (flag == this.m_activeFlag) { return; } this.m_activeFlag = !!flag; if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.createProxies(broadPhase, this.m_xf); } } else { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.destroyProxies(broadPhase); } var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; } }; Body.prototype.isFixedRotation = function() { return this.m_fixedRotationFlag; }; Body.prototype.setFixedRotation = function(flag) { if (this.m_fixedRotationFlag == flag) { return; } this.m_fixedRotationFlag = !!flag; this.m_angularVelocity = 0; this.resetMassData(); }; Body.prototype.getTransform = function() { return this.m_xf; }; Body.prototype.setTransform = function(position, angle) { ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } this.m_xf.set(position, angle); this.m_sweep.setTransform(this.m_xf); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, this.m_xf, this.m_xf); } }; Body.prototype.synchronizeTransform = function() { this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.synchronizeFixtures = function() { var xf = Transform.identity(); this.m_sweep.getTransform(xf, 0); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, xf, this.m_xf); } }; Body.prototype.advance = function(alpha) { this.m_sweep.advance(alpha); this.m_sweep.c.set(this.m_sweep.c0); this.m_sweep.a = this.m_sweep.a0; this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.getPosition = function() { return this.m_xf.p; }; Body.prototype.setPosition = function(p) { this.setTransform(p, this.m_sweep.a); }; Body.prototype.getAngle = function() { return this.m_sweep.a; }; Body.prototype.setAngle = function(angle) { this.setTransform(this.m_xf.p, angle); }; Body.prototype.getWorldCenter = function() { return this.m_sweep.c; }; Body.prototype.getLocalCenter = function() { return this.m_sweep.localCenter; }; Body.prototype.getLinearVelocity = function() { return this.m_linearVelocity; }; Body.prototype.getLinearVelocityFromWorldPoint = function(worldPoint) { var localCenter = Vec2.sub(worldPoint, this.m_sweep.c); return Vec2.add(this.m_linearVelocity, Vec2.cross(this.m_angularVelocity, localCenter)); }; Body.prototype.getLinearVelocityFromLocalPoint = function(localPoint) { return this.getLinearVelocityFromWorldPoint(this.getWorldPoint(localPoint)); }; Body.prototype.setLinearVelocity = function(v) { if (this.m_type == staticBody) { return; } if (Vec2.dot(v, v) > 0) { this.setAwake(true); } this.m_linearVelocity.set(v); }; Body.prototype.getAngularVelocity = function() { return this.m_angularVelocity; }; Body.prototype.setAngularVelocity = function(w) { if (this.m_type == staticBody) { return; } if (w * w > 0) { this.setAwake(true); } this.m_angularVelocity = w; }; Body.prototype.getLinearDamping = function() { return this.m_linearDamping; }; Body.prototype.setLinearDamping = function(linearDamping) { this.m_linearDamping = linearDamping; }; Body.prototype.getAngularDamping = function() { return this.m_angularDamping; }; Body.prototype.setAngularDamping = function(angularDamping) { this.m_angularDamping = angularDamping; }; Body.prototype.getGravityScale = function() { return this.m_gravityScale; }; Body.prototype.setGravityScale = function(scale) { this.m_gravityScale = scale; }; Body.prototype.getMass = function() { return this.m_mass; }; Body.prototype.getInertia = function() { return this.m_I + this.m_mass * Vec2.dot(this.m_sweep.localCenter, this.m_sweep.localCenter); }; function MassData() { this.mass = 0; this.center = Vec2.zero(); this.I = 0; } Body.prototype.getMassData = function(data) { data.mass = this.m_mass; data.I = this.getInertia(); data.center.set(this.m_sweep.localCenter); }; Body.prototype.resetMassData = function() { this.m_mass = 0; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_sweep.localCenter.setZero(); if (this.isStatic() || this.isKinematic()) { this.m_sweep.c0.set(this.m_xf.p); this.m_sweep.c.set(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a; return; } ASSERT && common.assert(this.isDynamic()); var localCenter = Vec2.zero(); for (var f = this.m_fixtureList; f; f = f.m_next) { if (f.m_density == 0) { continue; } var massData = new MassData(); f.getMassData(massData); this.m_mass += massData.mass; localCenter.wAdd(massData.mass, massData.center); this.m_I += massData.I; } if (this.m_mass > 0) { this.m_invMass = 1 / this.m_mass; localCenter.mul(this.m_invMass); } else { this.m_mass = 1; this.m_invMass = 1; } if (this.m_I > 0 && this.m_fixedRotationFlag == false) { this.m_I -= this.m_mass * Vec2.dot(localCenter, localCenter); ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } else { this.m_I = 0; this.m_invI = 0; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(localCenter, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.setMassData = function(massData) { ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type != dynamicBody) { return; } this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_mass = massData.mass; if (this.m_mass <= 0) { this.m_mass = 1; } this.m_invMass = 1 / this.m_mass; if (massData.I > 0 && this.m_fixedRotationFlag == false) { this.m_I = massData.I - this.m_mass * Vec2.dot(massData.center, massData.center); ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(massData.center, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.applyForce = function(force, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); this.m_torque += Vec2.cross(Vec2.sub(point, this.m_sweep.c), force); } }; Body.prototype.applyForceToCenter = function(force, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); } }; Body.prototype.applyTorque = function(torque, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_torque += torque; } }; Body.prototype.applyLinearImpulse = function(impulse, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_linearVelocity.wAdd(this.m_invMass, impulse); this.m_angularVelocity += this.m_invI * Vec2.cross(Vec2.sub(point, this.m_sweep.c), impulse); } }; Body.prototype.applyAngularImpulse = function(impulse, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_angularVelocity += this.m_invI * impulse; } }; Body.prototype.shouldCollide = function(that) { if (this.m_type != dynamicBody && that.m_type != dynamicBody) { return false; } for (var jn = this.m_jointList; jn; jn = jn.next) { if (jn.other == that) { if (jn.joint.m_collideConnected == false) { return false; } } } return true; }; Body.prototype.createFixture = function(shape, fixdef) { ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return null; } var fixture = new Fixture(this, shape, fixdef); if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.createProxies(broadPhase, this.m_xf); } fixture.m_next = this.m_fixtureList; this.m_fixtureList = fixture; if (fixture.m_density > 0) { this.resetMassData(); } this.m_world.m_newFixture = true; return fixture; }; Body.prototype.destroyFixture = function(fixture) { ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } ASSERT && common.assert(fixture.m_body == this); var node = this.m_fixtureList; var found = false; while (node != null) { if (node == fixture) { node = fixture.m_next; found = true; break; } node = node.m_next; } ASSERT && common.assert(found); var edge = this.m_contactList; while (edge) { var c = edge.contact; edge = edge.next; var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); if (fixture == fixtureA || fixture == fixtureB) { this.m_world.destroyContact(c); } } if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.destroyProxies(broadPhase); } fixture.m_body = null; fixture.m_next = null; this.m_world.publish("remove-fixture", fixture); this.resetMassData(); }; Body.prototype.getWorldPoint = function(localPoint) { return Transform.mul(this.m_xf, localPoint); }; Body.prototype.getWorldVector = function(localVector) { return Rot.mul(this.m_xf.q, localVector); }; Body.prototype.getLocalPoint = function(worldPoint) { return Transform.mulT(this.m_xf, worldPoint); }; Body.prototype.getLocalVector = function(worldVector) { return Rot.mulT(this.m_xf.q, worldVector); }; },{"./Fixture":4,"./Shape":8,"./World":10,"./common/Math":18,"./common/Position":19,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Velocity":25,"./util/common":51,"./util/options":53}],3:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var DEBUG_SOLVER = false; var common = require("./util/common"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Mat22 = require("./common/Mat22"); var Rot = require("./common/Rot"); var Settings = require("./Settings"); var Manifold = require("./Manifold"); var Distance = require("./collision/Distance"); module.exports = Contact; function ContactEdge(contact) { this.contact = contact; this.prev; this.next; this.other; } function Contact(fA, indexA, fB, indexB, evaluateFcn) { this.m_nodeA = new ContactEdge(this); this.m_nodeB = new ContactEdge(this); this.m_fixtureA = fA; this.m_fixtureB = fB; this.m_indexA = indexA; this.m_indexB = indexB; this.m_evaluateFcn = evaluateFcn; this.m_manifold = new Manifold(); this.m_prev = null; this.m_next = null; this.m_toi = 1; this.m_toiCount = 0; this.m_toiFlag = false; this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); this.m_tangentSpeed = 0; this.m_enabledFlag = true; this.m_islandFlag = false; this.m_touchingFlag = false; this.m_filterFlag = false; this.m_bulletHitFlag = false; this.v_points = []; this.v_normal = Vec2.zero(); this.v_normalMass = new Mat22(); this.v_K = new Mat22(); this.v_pointCount; this.v_tangentSpeed; this.v_friction; this.v_restitution; this.v_invMassA; this.v_invMassB; this.v_invIA; this.v_invIB; this.p_localPoints = []; this.p_localNormal = Vec2.zero(); this.p_localPoint = Vec2.zero(); this.p_localCenterA = Vec2.zero(); this.p_localCenterB = Vec2.zero(); this.p_type; this.p_radiusA; this.p_radiusB; this.p_pointCount; this.p_invMassA; this.p_invMassB; this.p_invIA; this.p_invIB; } Contact.prototype.initConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var manifold = this.getManifold(); var pointCount = manifold.pointCount; ASSERT && common.assert(pointCount > 0); this.v_invMassA = bodyA.m_invMass; this.v_invMassB = bodyB.m_invMass; this.v_invIA = bodyA.m_invI; this.v_invIB = bodyB.m_invI; this.v_friction = this.m_friction; this.v_restitution = this.m_restitution; this.v_tangentSpeed = this.m_tangentSpeed; this.v_pointCount = pointCount; DEBUG && common.debug("pc", this.v_pointCount, pointCount); this.v_K.setZero(); this.v_normalMass.setZero(); this.p_invMassA = bodyA.m_invMass; this.p_invMassB = bodyB.m_invMass; this.p_invIA = bodyA.m_invI; this.p_invIB = bodyB.m_invI; this.p_localCenterA = Vec2.clone(bodyA.m_sweep.localCenter); this.p_localCenterB = Vec2.clone(bodyB.m_sweep.localCenter); this.p_radiusA = shapeA.m_radius; this.p_radiusB = shapeB.m_radius; this.p_type = manifold.type; this.p_localNormal = Vec2.clone(manifold.localNormal); this.p_localPoint = Vec2.clone(manifold.localPoint); this.p_pointCount = pointCount; for (var j = 0; j < pointCount; ++j) { var cp = manifold.points[j]; var vcp = this.v_points[j] = new VelocityConstraintPoint(); if (step.warmStarting) { vcp.normalImpulse = step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = step.dtRatio * cp.tangentImpulse; } else { vcp.normalImpulse = 0; vcp.tangentImpulse = 0; } vcp.rA.setZero(); vcp.rB.setZero(); vcp.normalMass = 0; vcp.tangentMass = 0; vcp.velocityBias = 0; this.p_localPoints[j] = Vec2.clone(cp.localPoint); } }; Contact.prototype.getManifold = function() { return this.m_manifold; }; Contact.prototype.getWorldManifold = function(worldManifold) { var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); return this.m_manifold.getWorldManifold(worldManifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius); }; Contact.prototype.setEnabled = function(flag) { this.m_enabledFlag = !!flag; }; Contact.prototype.isEnabled = function() { return this.m_enabledFlag; }; Contact.prototype.isTouching = function() { return this.m_touchingFlag; }; Contact.prototype.getNext = function() { return this.m_next; }; Contact.prototype.getFixtureA = function() { return this.m_fixtureA; }; Contact.prototype.getFixtureB = function() { return this.m_fixtureB; }; Contact.prototype.getChildIndexA = function() { return this.m_indexA; }; Contact.prototype.getChildIndexB = function() { return this.m_indexB; }; Contact.prototype.flagForFiltering = function() { this.m_filterFlag = true; }; Contact.prototype.setFriction = function(friction) { this.m_friction = friction; }; Contact.prototype.getFriction = function() { return this.m_friction; }; Contact.prototype.resetFriction = function() { this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); }; Contact.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Contact.prototype.getRestitution = function() { return this.m_restitution; }; Contact.prototype.resetRestitution = function() { this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); }; Contact.prototype.setTangentSpeed = function(speed) { this.m_tangentSpeed = speed; }; Contact.prototype.getTangentSpeed = function() { return this.m_tangentSpeed; }; Contact.prototype.evaluate = function(manifold, xfA, xfB) { this.m_evaluateFcn(manifold, xfA, this.m_fixtureA, this.m_indexA, xfB, this.m_fixtureB, this.m_indexB); }; Contact.prototype.update = function(listener) { this.m_enabledFlag = true; var touching = false; var wasTouching = this.m_touchingFlag; var sensorA = this.m_fixtureA.isSensor(); var sensorB = this.m_fixtureB.isSensor(); var sensor = sensorA || sensorB; var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var xfA = bodyA.getTransform(); var xfB = bodyB.getTransform(); if (sensor) { var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); touching = Distance.testOverlap(shapeA, this.m_indexA, shapeB, this.m_indexB, xfA, xfB); this.m_manifold.pointCount = 0; } else { var oldManifold = this.m_manifold; this.m_manifold = new Manifold(); this.evaluate(this.m_manifold, xfA, xfB); touching = this.m_manifold.pointCount > 0; for (var i = 0; i < this.m_manifold.pointCount; ++i) { var nmp = this.m_manifold.points[i]; nmp.normalImpulse = 0; nmp.tangentImpulse = 0; for (var j = 0; j < oldManifold.pointCount; ++j) { var omp = oldManifold.points[j]; if (omp.id.key == nmp.id.key) { nmp.normalImpulse = omp.normalImpulse; nmp.tangentImpulse = omp.tangentImpulse; break; } } } if (touching != wasTouching) { bodyA.setAwake(true); bodyB.setAwake(true); } } this.m_touchingFlag = touching; if (wasTouching == false && touching == true && listener) { listener.beginContact(this); } if (wasTouching == true && touching == false && listener) { listener.endContact(this); } if (sensor == false && touching && listener) { listener.preSolve(this, oldManifold); } }; Contact.prototype.solvePositionConstraint = function(step) { return this._solvePositionConstraint(step, false); }; Contact.prototype.solvePositionConstraintTOI = function(step, toiA, toiB) { return this._solvePositionConstraint(step, true, toiA, toiB); }; Contact.prototype._solvePositionConstraint = function(step, toi, toiA, toiB) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var localCenterA = Vec2.clone(this.p_localCenterA); var localCenterB = Vec2.clone(this.p_localCenterB); var mA = 0; var iA = 0; if (!toi || (bodyA == toiA || bodyA == toiB)) { mA = this.p_invMassA; iA = this.p_invIA; } var mB = 0; var iB = 0; if (!toi || (bodyB == toiA || bodyB == toiB)) { mB = this.p_invMassB; iB = this.p_invIB; } var cA = Vec2.clone(positionA.c); var aA = positionA.a; var cB = Vec2.clone(positionB.c); var aB = positionB.a; var minSeparation = 0; for (var j = 0; j < this.p_pointCount; ++j) { var xfA = Transform.identity(); var xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p = Vec2.sub(cA, Rot.mul(xfA.q, localCenterA)); xfB.p = Vec2.sub(cB, Rot.mul(xfB.q, localCenterB)); var normal, point, separation; switch (this.p_type) { case Manifold.e_circles: var pointA = Transform.mul(xfA, this.p_localPoint); var pointB = Transform.mul(xfB, this.p_localPoints[0]); normal = Vec2.sub(pointB, pointA); normal.normalize(); point = Vec2.wAdd(.5, pointA, .5, pointB); separation = Vec2.dot(Vec2.sub(pointB, pointA), normal) - this.p_radiusA - this.p_radiusB; break; case Manifold.e_faceA: normal = Rot.mul(xfA.q, this.p_localNormal); var planePoint = Transform.mul(xfA, this.p_localPoint); var clipPoint = Transform.mul(xfB, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; break; case Manifold.e_faceB: normal = Rot.mul(xfB.q, this.p_localNormal); var planePoint = Transform.mul(xfB, this.p_localPoint); var clipPoint = Transform.mul(xfA, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; normal.mul(-1); break; } var rA = Vec2.sub(point, cA); var rB = Vec2.sub(point, cB); minSeparation = Math.min(minSeparation, separation); var baumgarte = toi ? Settings.toiBaugarte : Settings.baumgarte; var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var C = Math.clamp(baumgarte * (separation + linearSlop), -maxLinearCorrection, 0); var rnA = Vec2.cross(rA, normal); var rnB = Vec2.cross(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; var impulse = K > 0 ? -C / K : 0; var P = Vec2.mul(impulse, normal); cA.wSub(mA, P); aA -= iA * Vec2.cross(rA, P); cB.wAdd(mB, P); aB += iB * Vec2.cross(rB, P); } positionA.c.set(cA); positionA.a = aA; positionB.c.set(cB); positionB.a = aB; return minSeparation; }; function VelocityConstraintPoint() { this.rA = Vec2.zero(); this.rB = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.normalMass = 0; this.tangentMass = 0; this.velocityBias = 0; } Contact.prototype.initVelocityConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var radiusA = this.p_radiusA; var radiusB = this.p_radiusB; var manifold = this.getManifold(); var mA = this.v_invMassA; var mB = this.v_invMassB; var iA = this.v_invIA; var iB = this.v_invIB; var localCenterA = Vec2.clone(this.p_localCenterA); var localCenterB = Vec2.clone(this.p_localCenterB); var cA = Vec2.clone(positionA.c); var aA = positionA.a; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var cB = Vec2.clone(positionB.c); var aB = positionB.a; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; ASSERT && common.assert(manifold.pointCount > 0); var xfA = Transform.identity(); var xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.wSet(1, cA, -1, Rot.mul(xfA.q, localCenterA)); xfB.p.wSet(1, cB, -1, Rot.mul(xfB.q, localCenterB)); var worldManifold = manifold.getWorldManifold(null, xfA, radiusA, xfB, radiusB); this.v_normal.set(worldManifold.normal); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; vcp.rA.set(Vec2.sub(worldManifold.points[j], cA)); vcp.rB.set(Vec2.sub(worldManifold.points[j], cB)); DEBUG && common.debug("vcp.rA", worldManifold.points[j].x, worldManifold.points[j].y, cA.x, cA.y, vcp.rA.x, vcp.rA.y); var rnA = Vec2.cross(vcp.rA, this.v_normal); var rnB = Vec2.cross(vcp.rB, this.v_normal); var kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0 ? 1 / kNormal : 0; var tangent = Vec2.cross(this.v_normal, 1); var rtA = Vec2.cross(vcp.rA, tangent); var rtB = Vec2.cross(vcp.rB, tangent); var kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0 ? 1 / kTangent : 0; vcp.velocityBias = 0; var vRel = Vec2.dot(this.v_normal, vB) + Vec2.dot(this.v_normal, Vec2.cross(wB, vcp.rB)) - Vec2.dot(this.v_normal, vA) - Vec2.dot(this.v_normal, Vec2.cross(wA, vcp.rA)); if (vRel < -Settings.velocityThreshold) { vcp.velocityBias = -this.v_restitution * vRel; } } if (this.v_pointCount == 2 && step.blockSolve) { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var rn1A = Vec2.cross(vcp1.rA, this.v_normal); var rn1B = Vec2.cross(vcp1.rB, this.v_normal); var rn2A = Vec2.cross(vcp2.rA, this.v_normal); var rn2B = Vec2.cross(vcp2.rB, this.v_normal); var k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; var k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; var k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; var k_maxConditionNumber = 1e3; DEBUG && common.debug("k1x2: ", k11, k22, k12, mA, mB, iA, rn1A, rn2A, iB, rn1B, rn2B); if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { this.v_K.ex.set(k11, k12); this.v_K.ey.set(k12, k22); this.v_normalMass.set(this.v_K.getInverse()); } else { this.v_pointCount = 1; } } positionA.c.set(cA); positionA.a = aA; velocityA.v.set(vA); velocityA.w = wA; positionB.c.set(cB); positionB.a = aB; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.warmStartConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.cross(normal, 1); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var P = Vec2.wAdd(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent); DEBUG && common.debug(iA, iB, vcp.rA.x, vcp.rA.y, vcp.rB.x, vcp.rB.y, P.x, P.y); wA -= iA * Vec2.cross(vcp.rA, P); vA.wSub(mA, P); wB += iB * Vec2.cross(vcp.rB, P); vB.wAdd(mB, P); } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.storeConstraintImpulses = function(step) { var manifold = this.m_manifold; for (var j = 0; j < this.v_pointCount; ++j) { manifold.points[j].normalImpulse = this.v_points[j].normalImpulse; manifold.points[j].tangentImpulse = this.v_points[j].tangentImpulse; } }; Contact.prototype.solveVelocityConstraint = function(step) { var bodyA = this.m_fixtureA.m_body; var bodyB = this.m_fixtureB.m_body; var velocityA = bodyA.c_velocity; var positionA = bodyA.c_position; var velocityB = bodyB.c_velocity; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.cross(normal, 1); var friction = this.v_friction; ASSERT && common.assert(this.v_pointCount == 1 || this.v_pointCount == 2); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var dv = Vec2.zero(); dv.wAdd(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.wSub(1, vA, 1, Vec2.cross(wA, vcp.rA)); var vt = Vec2.dot(dv, tangent) - this.v_tangentSpeed; var lambda = vcp.tangentMass * -vt; var maxFriction = friction * vcp.normalImpulse; var newImpulse = Math.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; var P = Vec2.mul(lambda, tangent); vA.wSub(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } if (this.v_pointCount == 1 || step.blockSolve == false) { for (var i = 0; i < this.v_pointCount; ++i) { var vcp = this.v_points[i]; var dv = Vec2.zero(); dv.wAdd(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.wSub(1, vA, 1, Vec2.cross(wA, vcp.rA)); var vn = Vec2.dot(dv, normal); var lambda = -vcp.normalMass * (vn - vcp.velocityBias); var newImpulse = Math.max(vcp.normalImpulse + lambda, 0); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; var P = Vec2.mul(lambda, normal); vA.wSub(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } } else { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var a = Vec2.neo(vcp1.normalImpulse, vcp2.normalImpulse); ASSERT && common.assert(a.x >= 0 && a.y >= 0); var dv1 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp1.rB)).sub(vA).sub(Vec2.cross(wA, vcp1.rA)); var dv2 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp2.rB)).sub(vA).sub(Vec2.cross(wA, vcp2.rA)); var vn1 = Vec2.dot(dv1, normal); var vn2 = Vec2.dot(dv2, normal); var b = Vec2.neo(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias); b.sub(Mat22.mul(this.v_K, a)); var k_errorTol = .001; for (;;) { var x = Vec2.neg(Mat22.mul(this.v_normalMass, b)); if (x.x >= 0 && x.y >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { dv1 = vB + Vec2.cross(wB, vcp1.rB) - vA - Vec2.cross(wA, vcp1.rA); dv2 = vB + Vec2.cross(wB, vcp2.rB) - vA - Vec2.cross(wA, vcp2.rA); vn1 = Dot(dv1, normal); vn2 = Dot(dv2, normal); ASSERT && common.assert(Abs(vn1 - vcp1.velocityBias) < k_errorTol); ASSERT && common.assert(Abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = -vcp1.normalMass * b.x; x.y = 0; vn1 = 0; vn2 = this.v_K.ex.y * x.x + b.y; if (x.x >= 0 && vn2 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv1B = Vec2.add(vB, Vec2.cross(wB, vcp1.rB)); var dv1A = Vec2.add(vA, Vec2.cross(wA, vcp1.rA)); var dv1 = Vec2.sub(dv1B, dv1A); vn1 = Vec2.dot(dv1, normal); ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = -vcp2.normalMass * b.y; vn1 = this.v_K.ey.x * x.y + b.x; vn2 = 0; if (x.y >= 0 && vn1 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv2B = Vec2.add(vB, Vec2.cross(wB, vcp2.rB)); var dv2A = Vec2.add(vA, Vec2.cross(wA, vcp2.rA)); var dv1 = Vec2.sub(dv2B, dv2A); vn2 = Vec2.dot(dv2, normal); ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = 0; vn1 = b.x; vn2 = b.y; if (vn1 >= 0 && vn2 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; break; } break; } } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; function mixFriction(friction1, friction2) { return Math.sqrt(friction1 * friction2); } function mixRestitution(restitution1, restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } var s_registers = []; Contact.addType = function(type1, type2, callback) { s_registers[type1] = s_registers[type1] || {}; s_registers[type1][type2] = callback; }; Contact.create = function(fixtureA, indexA, fixtureB, indexB) { var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var contact, evaluateFcn; if (evaluateFcn = s_registers[typeA] && s_registers[typeA][typeB]) { contact = new Contact(fixtureA, indexA, fixtureB, indexB, evaluateFcn); } else if (evaluateFcn = s_registers[typeB] && s_registers[typeB][typeA]) { contact = new Contact(fixtureB, indexB, fixtureA, indexA, evaluateFcn); } else { return null; } fixtureA = contact.getFixtureA(); fixtureB = contact.getFixtureB(); indexA = contact.getChildIndexA(); indexB = contact.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); contact.m_nodeA.contact = contact; contact.m_nodeA.other = bodyB; contact.m_nodeA.prev = null; contact.m_nodeA.next = bodyA.m_contactList; if (bodyA.m_contactList != null) { bodyA.m_contactList.prev = contact.m_nodeA; } bodyA.m_contactList = contact.m_nodeA; contact.m_nodeB.contact = contact; contact.m_nodeB.other = bodyA; contact.m_nodeB.prev = null; contact.m_nodeB.next = bodyB.m_contactList; if (bodyB.m_contactList != null) { bodyB.m_contactList.prev = contact.m_nodeB; } bodyB.m_contactList = contact.m_nodeB; if (fixtureA.isSensor() == false && fixtureB.isSensor() == false) { bodyA.setAwake(true); bodyB.setAwake(true); } return contact; }; Contact.destroy = function(contact, listener) { var fixtureA = contact.m_fixtureA; var fixtureB = contact.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (contact.isTouching()) { listener.endContact(contact); } if (contact.m_nodeA.prev) { contact.m_nodeA.prev.next = contact.m_nodeA.next; } if (contact.m_nodeA.next) { contact.m_nodeA.next.prev = contact.m_nodeA.prev; } if (contact.m_nodeA == bodyA.m_contactList) { bodyA.m_contactList = contact.m_nodeA.next; } if (contact.m_nodeB.prev) { contact.m_nodeB.prev.next = contact.m_nodeB.next; } if (contact.m_nodeB.next) { contact.m_nodeB.next.prev = contact.m_nodeB.prev; } if (contact.m_nodeB == bodyB.m_contactList) { bodyB.m_contactList = contact.m_nodeB.next; } if (contact.m_manifold.pointCount > 0 && fixtureA.isSensor() == false && fixtureB.isSensor() == false) { bodyA.setAwake(true); bodyB.setAwake(true); } var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var destroyFcn = s_registers[typeA][typeB].destroyFcn; if (typeof destroyFcn === "function") { destroyFcn(contact); } }; },{"./Manifold":6,"./Settings":7,"./collision/Distance":13,"./common/Mat22":16,"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],4:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Fixture; var common = require("./util/common"); var options = require("./util/options"); var Vec2 = require("./common/Vec2"); var AABB = require("./collision/AABB"); var FixtureDef = { userData: null, friction: .2, restitution: 0, density: 0, isSensor: false, filterGroupIndex: 0, filterCategoryBits: 1, filterMaskBits: 65535 }; function FixtureProxy(fixture, childIndex) { this.aabb = new AABB(); this.fixture = fixture; this.childIndex = childIndex; this.proxyId; } function Fixture(body, shape, def) { if (shape.shape) { def = shape; shape = shape.shape; } else if (typeof def === "number") { def = { density: def }; } def = options(def, FixtureDef); this.m_body = body; this.m_friction = def.friction; this.m_restitution = def.restitution; this.m_density = def.density; this.m_isSensor = def.isSensor; this.m_filterGroupIndex = def.filterGroupIndex; this.m_filterCategoryBits = def.filterCategoryBits; this.m_filterMaskBits = def.filterMaskBits; this.m_shape = shape; this.m_next = null; this.m_proxies = []; this.m_proxyCount = 0; var childCount = this.m_shape.getChildCount(); for (var i = 0; i < childCount; ++i) { this.m_proxies[i] = new FixtureProxy(this, i); } this.m_userData = def.userData; } Fixture.prototype.getType = function() { return this.m_shape.getType(); }; Fixture.prototype.getShape = function() { return this.m_shape; }; Fixture.prototype.isSensor = function() { return this.m_isSensor; }; Fixture.prototype.setSensor = function(sensor) { if (sensor != this.m_isSensor) { this.m_body.setAwake(true); this.m_isSensor = sensor; } }; Fixture.prototype.getUserData = function() { return this.m_userData; }; Fixture.prototype.setUserData = function(data) { this.m_userData = data; }; Fixture.prototype.getBody = function() { return this.m_body; }; Fixture.prototype.getNext = function() { return this.m_next; }; Fixture.prototype.getDensity = function() { return this.m_density; }; Fixture.prototype.setDensity = function(density) { ASSERT && common.assert(Math.isFinite(density) && density >= 0); this.m_density = density; }; Fixture.prototype.getFriction = function() { return this.m_friction; }; Fixture.prototype.setFriction = function(friction) { this.m_friction = friction; }; Fixture.prototype.getRestitution = function() { return this.m_restitution; }; Fixture.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Fixture.prototype.testPoint = function(p) { return this.m_shape.testPoint(this.m_body.getTransform(), p); }; Fixture.prototype.rayCast = function(output, input, childIndex) { return this.m_shape.rayCast(output, input, this.m_body.getTransform(), childIndex); }; Fixture.prototype.getMassData = function(massData) { this.m_shape.computeMass(massData, this.m_density); }; Fixture.prototype.getAABB = function(childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_proxyCount); return this.m_proxies[childIndex].aabb; }; Fixture.prototype.createProxies = function(broadPhase, xf) { ASSERT && common.assert(this.m_proxyCount == 0); this.m_proxyCount = this.m_shape.getChildCount(); for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; this.m_shape.computeAABB(proxy.aabb, xf, i); proxy.proxyId = broadPhase.createProxy(proxy.aabb, proxy); } }; Fixture.prototype.destroyProxies = function(broadPhase) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; broadPhase.destroyProxy(proxy.proxyId); proxy.proxyId = null; } this.m_proxyCount = 0; }; Fixture.prototype.synchronize = function(broadPhase, xf1, xf2) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; var aabb1 = new AABB(); var aabb2 = new AABB(); this.m_shape.computeAABB(aabb1, xf1, proxy.childIndex); this.m_shape.computeAABB(aabb2, xf2, proxy.childIndex); proxy.aabb.combine(aabb1, aabb2); var displacement = Vec2.sub(xf2.p, xf1.p); broadPhase.moveProxy(proxy.proxyId, proxy.aabb, displacement); } }; Fixture.prototype.setFilterData = function(filter) { this.m_filterGroupIndex = filter.groupIndex; this.m_filterCategoryBits = filter.categoryBits; this.m_filterMaskBits = filter.maskBits; this.refilter(); }; Fixture.prototype.getFilterGroupIndex = function() { return this.m_filterGroupIndex; }; Fixture.prototype.getFilterCategoryBits = function() { return this.m_filterCategoryBits; }; Fixture.prototype.getFilterMaskBits = function() { return this.m_filterMaskBits; }; Fixture.prototype.refilter = function() { if (this.m_body == null) { return; } var edge = this.m_body.getContactList(); while (edge) { var contact = edge.contact; var fixtureA = contact.getFixtureA(); var fixtureB = contact.getFixtureB(); if (fixtureA == this || fixtureB == this) { contact.flagForFiltering(); } edge = edge.next; } var world = this.m_body.getWorld(); if (world == null) { return; } var broadPhase = world.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) { broadPhase.touchProxy(this.m_proxies[i].proxyId); } }; Fixture.prototype.shouldCollide = function(that) { if (that.m_filterGroupIndex == this.m_filterGroupIndex && that.m_filterGroupIndex != 0) { return that.m_filterGroupIndex > 0; } var collide = (that.m_filterMaskBits & this.m_filterCategoryBits) != 0 && (that.m_filterCategoryBits & this.m_filterMaskBits) != 0; return collide; }; },{"./collision/AABB":11,"./common/Vec2":23,"./util/common":51,"./util/options":53}],5:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Joint; var common = require("./util/common"); function JointEdge() { this.other = null; this.joint = null; this.prev = null; this.next = null; } var JointDef = { userData: null, collideConnected: false }; function Joint(def, bodyA, bodyB) { bodyA = def.bodyA || bodyA; bodyB = def.bodyB || bodyB; ASSERT && common.assert(bodyA); ASSERT && common.assert(bodyB); ASSERT && common.assert(bodyA != bodyB); this.m_type = "unknown-joint"; this.m_bodyA = bodyA; this.m_bodyB = bodyB; this.m_index = 0; this.m_collideConnected = !!def.collideConnected; this.m_prev = null; this.m_next = null; this.m_edgeA = new JointEdge(); this.m_edgeB = new JointEdge(); this.m_islandFlag = false; this.m_userData = def.userData; } Joint.prototype.isActive = function() { return this.m_bodyA.isActive() && this.m_bodyB.isActive(); }; Joint.prototype.getType = function() { return this.m_type; }; Joint.prototype.getBodyA = function() { return this.m_bodyA; }; Joint.prototype.getBodyB = function() { return this.m_bodyB; }; Joint.prototype.getNext = function() { return this.m_next; }; Joint.prototype.getUserData = function() { return this.m_userData; }; Joint.prototype.setUserData = function(data) { this.m_userData = data; }; Joint.prototype.getCollideConnected = function() { return this.m_collideConnected; }; Joint.prototype.getAnchorA = function() {}; Joint.prototype.getAnchorB = function() {}; Joint.prototype.getReactionForce = function(inv_dt) {}; Joint.prototype.getReactionTorque = function(inv_dt) {}; Joint.prototype.shiftOrigin = function(newOrigin) {}; Joint.prototype.initVelocityConstraints = function(step) {}; Joint.prototype.solveVelocityConstraints = function(step) {}; Joint.prototype.solvePositionConstraints = function(step) {}; },{"./util/common":51}],6:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Math = require("./common/Math"); var Rot = require("./common/Rot"); module.exports = Manifold; module.exports.clipSegmentToLine = clipSegmentToLine; module.exports.clipVertex = ClipVertex; module.exports.getPointStates = getPointStates; module.exports.PointState = PointState; Manifold.e_circles = 0; Manifold.e_faceA = 1; Manifold.e_faceB = 2; Manifold.e_vertex = 0; Manifold.e_face = 1; function Manifold() { this.type; this.localNormal = Vec2.zero(); this.localPoint = Vec2.zero(); this.points = [ new ManifoldPoint(), new ManifoldPoint() ]; this.pointCount = 0; } function ManifoldPoint() { this.localPoint = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id = new ContactID(); } function ContactID() { this.cf = new ContactFeature(); this.key; } ContactID.prototype.set = function(o) { this.key = o.key; this.cf.set(o.cf); }; function ContactFeature() { this.indexA; this.indexB; this.typeA; this.typeB; } ContactFeature.prototype.set = function(o) { this.indexA = o.indexA; this.indexB = o.indexB; this.typeA = o.typeA; this.typeB = o.typeB; }; function WorldManifold() { this.normal; this.points = []; this.separations = []; } Manifold.prototype.getWorldManifold = function(wm, xfA, radiusA, xfB, radiusB) { if (this.pointCount == 0) { return; } wm = wm || new WorldManifold(); var normal = wm.normal; var points = wm.points; var separations = wm.separations; switch (this.type) { case Manifold.e_circles: normal = Vec2.neo(1, 0); var pointA = Transform.mul(xfA, this.localPoint); var pointB = Transform.mul(xfB, this.points[0].localPoint); var dist = Vec2.sub(pointB, pointA); if (Vec2.lengthSquared(dist) > Math.EPSILON * Math.EPSILON) { normal.set(dist); normal.normalize(); } points[0] = Vec2.mid(pointA, pointB); separations[0] = -radiusB - radiusA; points.length = 1; separations.length = 1; break; case Manifold.e_faceA: normal = Rot.mul(xfA.q, this.localNormal); var planePoint = Transform.mul(xfA, this.localPoint); DEBUG && common.debug("faceA", this.localPoint.x, this.localPoint.y, this.localNormal.x, this.localNormal.y, normal.x, normal.y); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mul(xfB, this.points[i].localPoint); var cA = Vec2.clone(clipPoint).wAdd(radiusA - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cB = Vec2.clone(clipPoint).wSub(radiusB, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cB, cA), normal); DEBUG && common.debug(i, this.points[i].localPoint.x, this.points[i].localPoint.y, planePoint.x, planePoint.y, xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s, xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s, radiusA, radiusB, clipPoint.x, clipPoint.y, cA.x, cA.y, cB.x, cB.y, separations[i], points[i].x, points[i].y); } points.length = this.pointCount; separations.length = this.pointCount; break; case Manifold.e_faceB: normal = Rot.mul(xfB.q, this.localNormal); var planePoint = Transform.mul(xfB, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mul(xfA, this.points[i].localPoint); var cB = Vec2.zero().wSet(1, clipPoint, radiusB - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cA = Vec2.zero().wSet(1, clipPoint, -radiusA, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cA, cB), normal); } points.length = this.pointCount; separations.length = this.pointCount; normal.mul(-1); break; } wm.normal = normal; wm.points = points; wm.separations = separations; return wm; }; var PointState = { nullState: 0, addState: 1, persistState: 2, removeState: 3 }; function getPointStates(state1, state2, manifold1, manifold2) { for (var i = 0; i < manifold1.pointCount; ++i) { var id = manifold1.points[i].id; state1[i] = PointState.removeState; for (var j = 0; j < manifold2.pointCount; ++j) { if (manifold2.points[j].id.key == id.key) { state1[i] = PointState.persistState; break; } } } for (var i = 0; i < manifold2.pointCount; ++i) { var id = manifold2.points[i].id; state2[i] = PointState.addState; for (var j = 0; j < manifold1.pointCount; ++j) { if (manifold1.points[j].id.key == id.key) { state2[i] = PointState.persistState; break; } } } } function ClipVertex() { this.v = Vec2.zero(); this.id = new ContactID(); } ClipVertex.prototype.set = function(o) { this.v.set(o.v); this.id.set(o.id); }; function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) { var numOut = 0; var distance0 = Vec2.dot(normal, vIn[0].v) - offset; var distance1 = Vec2.dot(normal, vIn[1].v) - offset; if (distance0 <= 0) vOut[numOut++].set(vIn[0]); if (distance1 <= 0) vOut[numOut++].set(vIn[1]); if (distance0 * distance1 < 0) { var interp = distance0 / (distance0 - distance1); vOut[numOut].v.wSet(1 - interp, vIn[0].v, interp, vIn[1].v); vOut[numOut].id.cf.indexA = vertexIndexA; vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; vOut[numOut].id.cf.typeA = ContactFeature.e_vertex; vOut[numOut].id.cf.typeB = ContactFeature.e_face; ++numOut; } return numOut; } },{"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],7:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = exports; Settings.maxManifoldPoints = 2; Settings.maxPolygonVertices = 12; Settings.aabbExtension = .1; Settings.aabbMultiplier = 2; Settings.linearSlop = .005; Settings.linearSlopSquared = Settings.linearSlop * Settings.linearSlop; Settings.angularSlop = 2 / 180 * Math.PI; Settings.polygonRadius = 2 * Settings.linearSlop; Settings.maxSubSteps = 8; Settings.maxTOIContacts = 32; Settings.maxTOIIterations = 20; Settings.maxDistnceIterations = 20; Settings.velocityThreshold = 1; Settings.maxLinearCorrection = .2; Settings.maxAngularCorrection = 8 / 180 * Math.PI; Settings.maxTranslation = 2; Settings.maxTranslationSquared = Settings.maxTranslation * Settings.maxTranslation; Settings.maxRotation = .5 * Math.PI; Settings.maxRotationSquared = Settings.maxRotation * Settings.maxRotation; Settings.baumgarte = .2; Settings.toiBaugarte = .75; Settings.timeToSleep = .5; Settings.linearSleepTolerance = .01; Settings.linearSleepToleranceSqr = Math.pow(Settings.linearSleepTolerance, 2); Settings.angularSleepTolerance = 2 / 180 * Math.PI; Settings.angularSleepToleranceSqr = Math.pow(Settings.angularSleepTolerance, 2); },{}],8:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Shape; var Math = require("./common/Math"); function Shape() { this.m_type; this.m_radius; } Shape.isValid = function(shape) { return !!shape; }; Shape.prototype.getRadius = function() { return this.m_radius; }; Shape.prototype.getType = function() { return this.m_type; }; Shape.prototype._clone = function() {}; Shape.prototype.getChildCount = function() {}; Shape.prototype.testPoint = function(xf, p) {}; Shape.prototype.rayCast = function(output, input, transform, childIndex) {}; Shape.prototype.computeAABB = function(aabb, xf, childIndex) {}; Shape.prototype.computeMass = function(massData, density) {}; Shape.prototype.computeDistanceProxy = function(proxy) {}; },{"./common/Math":18}],9:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Solver; module.exports.TimeStep = TimeStep; var Settings = require("./Settings"); var common = require("./util/common"); var Timer = require("./util/Timer"); var Vec2 = require("./common/Vec2"); var Math = require("./common/Math"); var Body = require("./Body"); var Contact = require("./Contact"); var Joint = require("./Joint"); var TimeOfImpact = require("./collision/TimeOfImpact"); var TOIInput = TimeOfImpact.Input; var TOIOutput = TimeOfImpact.Output; var Distance = require("./collision/Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function Profile() { this.solveInit; this.solveVelocity; this.solvePosition; } function TimeStep(dt) { this.dt = 0; this.inv_dt = 0; this.velocityIterations = 0; this.positionIterations = 0; this.warmStarting = false; this.blockSolve = true; this.inv_dt0 = 0; this.dtRatio = 1; } TimeStep.prototype.reset = function(dt) { if (this.dt > 0) { this.inv_dt0 = this.inv_dt; } this.dt = dt; this.inv_dt = dt == 0 ? 0 : 1 / dt; this.dtRatio = dt * this.inv_dt0; }; function Solver(world) { this.m_world = world; this.m_profile = new Profile(); this.m_stack = []; this.m_bodies = []; this.m_contacts = []; this.m_joints = []; } Solver.prototype.clear = function() { this.m_stack.length = 0; this.m_bodies.length = 0; this.m_contacts.length = 0; this.m_joints.length = 0; }; Solver.prototype.addBody = function(body) { ASSERT && common.assert(body instanceof Body, "Not a Body!", body); this.m_bodies.push(body); }; Solver.prototype.addContact = function(contact) { ASSERT && common.assert(contact instanceof Contact, "Not a Contact!", contact); this.m_contacts.push(contact); }; Solver.prototype.addJoint = function(joint) { ASSERT && common.assert(joint instanceof Joint, "Not a Joint!", joint); this.m_joints.push(joint); }; Solver.prototype.solveWorld = function(step) { var world = this.m_world; var profile = this.m_profile; profile.solveInit = 0; profile.solveVelocity = 0; profile.solvePosition = 0; for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; } for (var c = world.m_contactList; c; c = c.m_next) { c.m_islandFlag = false; } for (var j = world.m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } var stack = this.m_stack; var loop = -1; for (var seed = world.m_bodyList; seed; seed = seed.m_next) { loop++; if (seed.m_islandFlag) { continue; } if (seed.isAwake() == false || seed.isActive() == false) { continue; } if (seed.isStatic()) { continue; } this.clear(); stack.push(seed); seed.m_islandFlag = true; while (stack.length > 0) { var b = stack.pop(); ASSERT && common.assert(b.isActive() == true); this.addBody(b); b.setAwake(true); if (b.isStatic()) { continue; } for (var ce = b.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } if (contact.isEnabled() == false || contact.isTouching() == false) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } this.addContact(contact); contact.m_islandFlag = true; var other = ce.other; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } for (var je = b.m_jointList; je; je = je.next) { if (je.joint.m_islandFlag == true) { continue; } var other = je.other; if (other.isActive() == false) { continue; } this.addJoint(je.joint); je.joint.m_islandFlag = true; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } } this.solveIsland(step); for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; if (b.isStatic()) { b.m_islandFlag = false; } } } }; Solver.prototype.solveIsland = function(step) { var world = this.m_world; var profile = this.m_profile; var gravity = world.m_gravity; var allowSleep = world.m_allowSleep; var timer = Timer.now(); var h = step.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.m_sweep.c); var a = body.m_sweep.a; var v = Vec2.clone(body.m_linearVelocity); var w = body.m_angularVelocity; body.m_sweep.c0.set(body.m_sweep.c); body.m_sweep.a0 = body.m_sweep.a; DEBUG && common.debug("P: ", a, c.x, c.y, w, v.x, v.y); if (body.isDynamic()) { v.wAdd(h * body.m_gravityScale, gravity); v.wAdd(h * body.m_invMass, body.m_force); w += h * body.m_invI * body.m_torque; DEBUG && common.debug("N: " + h, body.m_gravityScale, gravity.x, gravity.y, body.m_invMass, body.m_force.x, body.m_force.y); v.mul(1 / (1 + h * body.m_linearDamping)); w *= 1 / (1 + h * body.m_angularDamping); } common.debug("A: ", a, c.x, c.y, w, v.x, v.y); body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; } timer = Timer.now(); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(step); } DEBUG && this.printBodies("M: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(step); } DEBUG && this.printBodies("R: "); if (step.warmStarting) { for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.warmStartConstraint(step); } } DEBUG && this.printBodies("Q: "); for (var i = 0; i < this.m_joints.length; ++i) { var joint = this.m_joints[i]; joint.initVelocityConstraints(step); } DEBUG && this.printBodies("E: "); profile.solveInit = Timer.diff(timer); timer = Timer.now(); for (var i = 0; i < step.velocityIterations; ++i) { DEBUG && common.debug("--", i); for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; joint.solveVelocityConstraints(step); } for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(step); } } DEBUG && this.printBodies("D: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.storeConstraintImpulses(step); } profile.solveVelocity = Timer.diff(timer); DEBUG && this.printBodies("C: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.lengthSquared(translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.wAdd(h, v); a += h * w; body.c_position.c.set(c); body.c_position.a = a; body.c_velocity.v.set(v); body.c_velocity.w = w; } DEBUG && this.printBodies("B: "); timer = Timer.now(); var positionSolved = false; for (var i = 0; i < step.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraint(step); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -3 * Settings.linearSlop; var jointsOkay = true; for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; var jointOkay = joint.solvePositionConstraints(step); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { positionSolved = true; break; } } DEBUG && this.printBodies("L: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_sweep.c.set(body.c_position.c); body.m_sweep.a = body.c_position.a; body.m_linearVelocity.set(body.c_velocity.v); body.m_angularVelocity = body.c_velocity.w; body.synchronizeTransform(); } profile.solvePosition = Timer.diff(timer); this.postSolveIsland(); if (allowSleep) { var minSleepTime = Infinity; var linTolSqr = Settings.linearSleepToleranceSqr; var angTolSqr = Settings.angularSleepToleranceSqr; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; if (body.isStatic()) { continue; } if (body.m_autoSleepFlag == false || body.m_angularVelocity * body.m_angularVelocity > angTolSqr || Vec2.lengthSquared(body.m_linearVelocity) > linTolSqr) { body.m_sleepTime = 0; minSleepTime = 0; } else { body.m_sleepTime += h; minSleepTime = Math.min(minSleepTime, body.m_sleepTime); } } if (minSleepTime >= Settings.timeToSleep && positionSolved) { for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.setAwake(false); } } } }; Solver.prototype.printBodies = function(tag) { for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; common.debug(tag, b.c_position.a, b.c_position.c.x, b.c_position.c.y, b.c_velocity.w, b.c_velocity.v.x, b.c_velocity.v.y); } }; var s_subStep = new TimeStep(); Solver.prototype.solveWorldTOI = function(step) { DEBUG && common.debug("TOI++++++World"); var world = this.m_world; var profile = this.m_profile; DEBUG && common.debug("Z:", world.m_stepComplete); if (world.m_stepComplete) { for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; b.m_sweep.alpha0 = 0; DEBUG && common.debug("b.alpha0:", b.m_sweep.alpha0); } for (var c = world.m_contactList; c; c = c.m_next) { c.m_toiFlag = false; c.m_islandFlag = false; c.m_toiCount = 0; c.m_toi = 1; } } if (DEBUG) for (var c = world.m_contactList; c; c = c.m_next) { DEBUG && common.debug("X:", c.m_toiFlag); } for (;;) { DEBUG && common.debug(";;"); var minContact = null; var minAlpha = 1; for (var c = world.m_contactList; c; c = c.m_next) { DEBUG && common.debug("alpha0::", c.getFixtureA().getBody().m_sweep.alpha0, c.getFixtureB().getBody().m_sweep.alpha0); if (c.isEnabled() == false) { continue; } DEBUG && common.debug("toiCount:", c.m_toiCount, Settings.maxSubSteps); if (c.m_toiCount > Settings.maxSubSteps) { continue; } DEBUG && common.debug("toiFlag:", c.m_toiFlag); var alpha = 1; if (c.m_toiFlag) { alpha = c.m_toi; } else { var fA = c.getFixtureA(); var fB = c.getFixtureB(); DEBUG && common.debug("sensor:", fA.isSensor(), fB.isSensor()); if (fA.isSensor() || fB.isSensor()) { continue; } var bA = fA.getBody(); var bB = fB.getBody(); ASSERT && common.assert(bA.isDynamic() || bB.isDynamic()); var activeA = bA.isAwake() && !bA.isStatic(); var activeB = bB.isAwake() && !bB.isStatic(); DEBUG && common.debug("awakestatic:", bA.isAwake(), bA.isStatic()); DEBUG && common.debug("awakestatic:", bB.isAwake(), bB.isStatic()); DEBUG && common.debug("active:", activeA, activeB); if (activeA == false && activeB == false) { continue; } DEBUG && common.debug("alpha:", alpha, bA.m_sweep.alpha0, bB.m_sweep.alpha0); var collideA = bA.isBullet() || !bA.isDynamic(); var collideB = bB.isBullet() || !bB.isDynamic(); DEBUG && common.debug("collide:", collideA, collideB); if (collideA == false && collideB == false) { continue; } var alpha0 = bA.m_sweep.alpha0; if (bA.m_sweep.alpha0 < bB.m_sweep.alpha0) { alpha0 = bB.m_sweep.alpha0; bA.m_sweep.advance(alpha0); } else if (bB.m_sweep.alpha0 < bA.m_sweep.alpha0) { alpha0 = bA.m_sweep.alpha0; bB.m_sweep.advance(alpha0); } DEBUG && common.debug("alpha0:", alpha0, bA.m_sweep.alpha0, bB.m_sweep.alpha0); ASSERT && common.assert(alpha0 < 1); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var sweepA = bA.m_sweep; var sweepB = bB.m_sweep; DEBUG && common.debug("sweepA", sweepA.localCenter.x, sweepA.localCenter.y, sweepA.c.x, sweepA.c.y, sweepA.a, sweepA.alpha0, sweepA.c0.x, sweepA.c0.y, sweepA.a0); DEBUG && common.debug("sweepB", sweepB.localCenter.x, sweepB.localCenter.y, sweepB.c.x, sweepB.c.y, sweepB.a, sweepB.alpha0, sweepB.c0.x, sweepB.c0.y, sweepB.a0); var input = new TOIInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.sweepA.set(bA.m_sweep); input.sweepB.set(bB.m_sweep); input.tMax = 1; var output = new TOIOutput(); TimeOfImpact(output, input); var beta = output.t; DEBUG && common.debug("state:", output.state, TOIOutput.e_touching); if (output.state == TOIOutput.e_touching) { alpha = Math.min(alpha0 + (1 - alpha0) * beta, 1); } else { alpha = 1; } c.m_toi = alpha; c.m_toiFlag = true; } DEBUG && common.debug("minAlpha:", minAlpha, alpha); if (alpha < minAlpha) { minContact = c; minAlpha = alpha; } } DEBUG && common.debug("minContact:", minContact == null, 1 - 10 * Math.EPSILON < minAlpha, minAlpha); if (minContact == null || 1 - 10 * Math.EPSILON < minAlpha) { world.m_stepComplete = true; break; } var fA = minContact.getFixtureA(); var fB = minContact.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var backup1 = bA.m_sweep.clone(); var backup2 = bB.m_sweep.clone(); bA.advance(minAlpha); bB.advance(minAlpha); minContact.update(world); minContact.m_toiFlag = false; ++minContact.m_toiCount; if (minContact.isEnabled() == false || minContact.isTouching() == false) { minContact.setEnabled(false); bA.m_sweep.set(backup1); bB.m_sweep.set(backup2); bA.synchronizeTransform(); bB.synchronizeTransform(); continue; } bA.setAwake(true); bB.setAwake(true); this.clear(); this.addBody(bA); this.addBody(bB); this.addContact(minContact); bA.m_islandFlag = true; bB.m_islandFlag = true; minContact.m_islandFlag = true; var bodies = [ bA, bB ]; for (var i = 0; i < bodies.length; ++i) { var body = bodies[i]; if (body.isDynamic()) { for (var ce = body.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } var other = ce.other; if (other.isDynamic() && !body.isBullet() && !other.isBullet()) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } var backup = other.m_sweep.clone(); if (other.m_islandFlag == false) { other.advance(minAlpha); } contact.update(world); if (contact.isEnabled() == false || contact.isTouching() == false) { other.m_sweep.set(backup); other.synchronizeTransform(); continue; } contact.m_islandFlag = true; this.addContact(contact); if (other.m_islandFlag) { continue; } other.m_islandFlag = true; if (!other.isStatic()) { other.setAwake(true); } this.addBody(other); } } } s_subStep.reset((1 - minAlpha) * step.dt); s_subStep.dtRatio = 1; s_subStep.positionIterations = 20; s_subStep.velocityIterations = step.velocityIterations; s_subStep.warmStarting = false; this.solveIslandTOI(s_subStep, bA, bB); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_islandFlag = false; if (!body.isDynamic()) { continue; } body.synchronizeFixtures(); for (var ce = body.m_contactList; ce; ce = ce.next) { ce.contact.m_toiFlag = false; ce.contact.m_islandFlag = false; } } world.findNewContacts(); if (world.m_subStepping) { world.m_stepComplete = false; break; } } if (DEBUG) for (var b = world.m_bodyList; b; b = b.m_next) { var c = b.m_sweep.c; var a = b.m_sweep.a; var v = b.m_linearVelocity; var w = b.m_angularVelocity; DEBUG && common.debug("== ", a, c.x, c.y, w, v.x, v.y); } }; Solver.prototype.solveIslandTOI = function(subStep, toiA, toiB) { DEBUG && common.debug("TOI++++++Island"); var world = this.m_world; var profile = this.m_profile; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.c_position.c.set(body.m_sweep.c); body.c_position.a = body.m_sweep.a; body.c_velocity.v.set(body.m_linearVelocity); body.c_velocity.w = body.m_angularVelocity; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(subStep); } for (var i = 0; i < subStep.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraintTOI(subStep, toiA, toiB); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -1.5 * Settings.linearSlop; if (contactsOkay) { break; } } if (false) { for (var i = 0; i < this.m_contacts.length; ++i) { var c = this.m_contacts[i]; var fA = c.getFixtureA(); var fB = c.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var input = new DistanceInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.transformA = bA.getTransform(); input.transformB = bB.getTransform(); input.useRadii = false; var output = new DistanceOutput(); var cache = new SimplexCache(); Distance(output, cache, input); if (output.distance == 0 || cache.count == 3) { cache.count += 0; } } } toiA.m_sweep.c0.set(toiA.c_position.c); toiA.m_sweep.a0 = toiA.c_position.a; toiB.m_sweep.c0.set(toiB.c_position.c); toiB.m_sweep.a0 = toiB.c_position.a; for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(subStep); } for (var i = 0; i < subStep.velocityIterations; ++i) { for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(subStep); } } var h = subStep.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.dot(translation, translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.wAdd(h, v); a += h * w; body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; body.m_sweep.c = c; body.m_sweep.a = a; body.m_linearVelocity = v; body.m_angularVelocity = w; body.synchronizeTransform(); } this.postSolveIsland(); DEBUG && common.debug("TOI------Island"); }; function ContactImpulse() { this.normalImpulses = []; this.tangentImpulses = []; } Solver.prototype.postSolveIsland = function() { var impulse = new ContactImpulse(); for (var c = 0; c < this.m_contacts.length; ++c) { var contact = this.m_contacts[c]; for (var p = 0; p < contact.v_points.length; ++p) { impulse.normalImpulses.push(contact.v_points[p].normalImpulse); impulse.tangentImpulses.push(contact.v_points[p].tangentImpulse); } this.m_world.postSolve(contact, impulse); } }; },{"./Body":2,"./Contact":3,"./Joint":5,"./Settings":7,"./collision/Distance":13,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Vec2":23,"./util/Timer":50,"./util/common":51}],10:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = World; var options = require("./util/options"); var common = require("./util/common"); var Timer = require("./util/Timer"); var Vec2 = require("./common/Vec2"); var BroadPhase = require("./collision/BroadPhase"); var Solver = require("./Solver"); var Body = require("./Body"); var Contact = require("./Contact"); var WorldDef = { gravity: Vec2.zero(), allowSleep: true, warmStarting: true, continuousPhysics: true, subStepping: false, blockSolve: true, velocityIterations: 8, positionIterations: 3 }; function World(def) { if (!(this instanceof World)) { return new World(def); } if (def && Vec2.isValid(def)) { def = { gravity: def }; } def = options(def, WorldDef); this.m_solver = new Solver(this); this.m_broadPhase = new BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_bodyList = null; this.m_bodyCount = 0; this.m_jointList = null; this.m_jointCount = 0; this.m_stepComplete = true; this.m_allowSleep = def.allowSleep; this.m_gravity = Vec2.clone(def.gravity); this.m_clearForces = true; this.m_newFixture = false; this.m_locked = false; this.m_warmStarting = def.warmStarting; this.m_continuousPhysics = def.continuousPhysics; this.m_subStepping = def.subStepping; this.m_blockSolve = def.blockSolve; this.m_velocityIterations = def.velocityIterations; this.m_positionIterations = def.positionIterations; this.m_t = 0; this.m_stepCount = 0; this.addPair = this.createContact.bind(this); } World.prototype.getBodyList = function() { return this.m_bodyList; }; World.prototype.getJointList = function() { return this.m_jointList; }; World.prototype.getContactList = function() { return this.m_contactList; }; World.prototype.getBodyCount = function() { return this.m_bodyCount; }; World.prototype.getJointCount = function() { return this.m_jointCount; }; World.prototype.getContactCount = function() { return this.m_contactCount; }; World.prototype.setGravity = function(gravity) { this.m_gravity = gravity; }; World.prototype.getGravity = function() { return this.m_gravity; }; World.prototype.isLocked = function() { return this.m_locked; }; World.prototype.setAllowSleeping = function(flag) { if (flag == this.m_allowSleep) { return; } this.m_allowSleep = flag; if (this.m_allowSleep == false) { for (var b = this.m_bodyList; b; b = b.m_next) { b.setAwake(true); } } }; World.prototype.getAllowSleeping = function() { return this.m_allowSleep; }; World.prototype.setWarmStarting = function(flag) { this.m_warmStarting = flag; }; World.prototype.getWarmStarting = function() { return this.m_warmStarting; }; World.prototype.setContinuousPhysics = function(flag) { this.m_continuousPhysics = flag; }; World.prototype.getContinuousPhysics = function() { return this.m_continuousPhysics; }; World.prototype.setSubStepping = function(flag) { this.m_subStepping = flag; }; World.prototype.getSubStepping = function() { return this.m_subStepping; }; World.prototype.setAutoClearForces = function(flag) { this.m_clearForces = flag; }; World.prototype.getAutoClearForces = function() { return this.m_clearForces; }; World.prototype.clearForces = function() { for (var body = this.m_bodyList; body; body = body.getNext()) { body.m_force.setZero(); body.m_torque = 0; } }; World.prototype.queryAABB = function(aabb, queryCallback) { ASSERT && common.assert(typeof queryCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.query(aabb, function(proxyId) { var proxy = broadPhase.getUserData(proxyId); return queryCallback(proxy.fixture); }); }; World.prototype.rayCast = function(point1, point2, reportFixtureCallback) { ASSERT && common.assert(typeof reportFixtureCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.rayCast({ maxFraction: 1, p1: point1, p2: point2 }, function(input, proxyId) { var proxy = broadPhase.getUserData(proxyId); var fixture = proxy.fixture; var index = proxy.childIndex; var output = {}; var hit = fixture.rayCast(output, input, index); if (hit) { var fraction = output.fraction; var point = Vec2.add(Vec2.mul(1 - fraction, input.p1), Vec2.mul(fraction, input.p2)); return reportFixtureCallback(fixture, point, output.normal, fraction); } return input.maxFraction; }); }; World.prototype.getProxyCount = function() { return this.m_broadPhase.getProxyCount(); }; World.prototype.getTreeHeight = function() { return this.m_broadPhase.getTreeHeight(); }; World.prototype.getTreeBalance = function() { return this.m_broadPhase.getTreeBalance(); }; World.prototype.getTreeQuality = function() { return this.m_broadPhase.getTreeQuality(); }; World.prototype.shiftOrigin = function(newOrigin) { ASSERT && common.assert(this.m_locked == false); if (this.m_locked) { return; } for (var b = this.m_bodyList; b; b = b.m_next) { b.m_xf.p.sub(newOrigin); b.m_sweep.c0.sub(newOrigin); b.m_sweep.c.sub(newOrigin); } for (var j = this.m_jointList; j; j = j.m_next) { j.shiftOrigin(newOrigin); } this.m_broadPhase.shiftOrigin(newOrigin); }; World.prototype.createBody = function(def, angle) { ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } if (def && Vec2.isValid(def)) { def = { position: def, angle: angle }; } var body = new Body(this, def); body.m_prev = null; body.m_next = this.m_bodyList; if (this.m_bodyList) { this.m_bodyList.m_prev = body; } this.m_bodyList = body; ++this.m_bodyCount; return body; }; World.prototype.createDynamicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "dynamic"; return this.createBody(def); }; World.prototype.createKinematicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "kinematic"; return this.createBody(def); }; World.prototype.destroyBody = function(b) { ASSERT && common.assert(this.m_bodyCount > 0); ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (b.m_destroyed) { return false; } var je = b.m_jointList; while (je) { var je0 = je; je = je.next; this.publish("remove-joint", je0.joint); this.destroyJoint(je0.joint); b.m_jointList = je; } b.m_jointList = null; var ce = b.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.destroyContact(ce0.contact); b.m_contactList = ce; } b.m_contactList = null; var f = b.m_fixtureList; while (f) { var f0 = f; f = f.m_next; this.publish("remove-fixture", f0); f0.destroyProxies(this.m_broadPhase); b.m_fixtureList = f; } b.m_fixtureList = null; if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == this.m_bodyList) { this.m_bodyList = b.m_next; } b.m_destroyed = true; --this.m_bodyCount; return true; }; World.prototype.createJoint = function(joint) { ASSERT && common.assert(!!joint.m_bodyA); ASSERT && common.assert(!!joint.m_bodyB); ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } joint.m_prev = null; joint.m_next = this.m_jointList; if (this.m_jointList) { this.m_jointList.m_prev = joint; } this.m_jointList = joint; ++this.m_jointCount; joint.m_edgeA.joint = joint; joint.m_edgeA.other = joint.m_bodyB; joint.m_edgeA.prev = null; joint.m_edgeA.next = joint.m_bodyA.m_jointList; if (joint.m_bodyA.m_jointList) joint.m_bodyA.m_jointList.prev = joint.m_edgeA; joint.m_bodyA.m_jointList = joint.m_edgeA; joint.m_edgeB.joint = joint; joint.m_edgeB.other = joint.m_bodyA; joint.m_edgeB.prev = null; joint.m_edgeB.next = joint.m_bodyB.m_jointList; if (joint.m_bodyB.m_jointList) joint.m_bodyB.m_jointList.prev = joint.m_edgeB; joint.m_bodyB.m_jointList = joint.m_edgeB; if (joint.m_collideConnected == false) { for (var edge = joint.m_bodyB.getContactList(); edge; edge = edge.next) { if (edge.other == joint.m_bodyA) { edge.contact.flagForFiltering(); } } } return joint; }; World.prototype.destroyJoint = function(joint) { ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (joint.m_prev) { joint.m_prev.m_next = joint.m_next; } if (joint.m_next) { joint.m_next.m_prev = joint.m_prev; } if (joint == this.m_jointList) { this.m_jointList = joint.m_next; } var bodyA = joint.m_bodyA; var bodyB = joint.m_bodyB; bodyA.setAwake(true); bodyB.setAwake(true); if (joint.m_edgeA.prev) { joint.m_edgeA.prev.next = joint.m_edgeA.next; } if (joint.m_edgeA.next) { joint.m_edgeA.next.prev = joint.m_edgeA.prev; } if (joint.m_edgeA == bodyA.m_jointList) { bodyA.m_jointList = joint.m_edgeA.next; } joint.m_edgeA.prev = null; joint.m_edgeA.next = null; if (joint.m_edgeB.prev) { joint.m_edgeB.prev.next = joint.m_edgeB.next; } if (joint.m_edgeB.next) { joint.m_edgeB.next.prev = joint.m_edgeB.prev; } if (joint.m_edgeB == bodyB.m_jointList) { bodyB.m_jointList = joint.m_edgeB.next; } joint.m_edgeB.prev = null; joint.m_edgeB.next = null; ASSERT && common.assert(this.m_jointCount > 0); --this.m_jointCount; if (joint.m_collideConnected == false) { var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { edge.contact.flagForFiltering(); } edge = edge.next; } } this.publish("remove-joint", joint); }; var s_step = new Solver.TimeStep(); World.prototype.step = function(timeStep, velocityIterations, positionIterations) { if ((velocityIterations | 0) !== velocityIterations) { velocityIterations = 0; } velocityIterations = velocityIterations || this.m_velocityIterations; positionIterations = positionIterations || this.m_positionIterations; this.m_stepCount++; if (this.m_newFixture) { this.findNewContacts(); this.m_newFixture = false; } this.m_locked = true; s_step.reset(timeStep); s_step.velocityIterations = velocityIterations; s_step.positionIterations = positionIterations; s_step.warmStarting = this.m_warmStarting; s_step.blockSolve = this.m_blockSolve; this.updateContacts(); if (this.m_stepComplete && timeStep > 0) { this.m_solver.solveWorld(s_step); for (var b = this.m_bodyList; b; b = b.getNext()) { if (b.m_islandFlag == false) { continue; } if (b.isStatic()) { continue; } b.synchronizeFixtures(); } this.findNewContacts(); } if (this.m_continuousPhysics && timeStep > 0) { this.m_solver.solveWorldTOI(s_step); } if (this.m_clearForces) { this.clearForces(); } this.m_locked = false; }; World.prototype.findNewContacts = function() { this.m_broadPhase.updatePairs(this.addPair); }; World.prototype.createContact = function(proxyA, proxyB) { var fixtureA = proxyA.fixture; var fixtureB = proxyB.fixture; var indexA = proxyA.childIndex; var indexB = proxyB.childIndex; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (bodyA == bodyB) { return; } var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { var fA = edge.contact.getFixtureA(); var fB = edge.contact.getFixtureB(); var iA = edge.contact.getChildIndexA(); var iB = edge.contact.getChildIndexB(); if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) { return; } if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) { return; } } edge = edge.next; } if (bodyB.shouldCollide(bodyA) == false) { return; } if (fixtureB.shouldCollide(fixtureA) == false) { return; } var contact = Contact.create(fixtureA, indexA, fixtureB, indexB); if (contact == null) { return; } contact.m_prev = null; if (this.m_contactList != null) { contact.m_next = this.m_contactList; this.m_contactList.m_prev = contact; } this.m_contactList = contact; ++this.m_contactCount; }; World.prototype.updateContacts = function() { var c, next_c = this.m_contactList; while (c = next_c) { next_c = c.getNext(); var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (c.m_filterFlag) { if (bodyB.shouldCollide(bodyA) == false) { this.destroyContact(c); continue; } if (fixtureB.shouldCollide(fixtureA) == false) { this.destroyContact(c); continue; } c.m_filterFlag = false; } var activeA = bodyA.isAwake() && !bodyA.isStatic(); var activeB = bodyB.isAwake() && !bodyB.isStatic(); if (activeA == false && activeB == false) { continue; } var proxyIdA = fixtureA.m_proxies[indexA].proxyId; var proxyIdB = fixtureB.m_proxies[indexB].proxyId; var overlap = this.m_broadPhase.testOverlap(proxyIdA, proxyIdB); if (overlap == false) { this.destroyContact(c); continue; } c.update(this); } }; World.prototype.destroyContact = function(contact) { Contact.destroy(contact, this); if (contact.m_prev) { contact.m_prev.m_next = contact.m_next; } if (contact.m_next) { contact.m_next.m_prev = contact.m_prev; } if (contact == this.m_contactList) { this.m_contactList = contact.m_next; } --this.m_contactCount; }; World.prototype._listeners = null; World.prototype.on = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } if (!this._listeners) { this._listeners = {}; } if (!this._listeners[name]) { this._listeners[name] = []; } this._listeners[name].push(listener); return this; }; World.prototype.off = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return this; } var index = listeners.indexOf(listener); if (index >= 0) { listeners.splice(index, 1); } return this; }; World.prototype.publish = function(name, arg1, arg2, arg3) { var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].call(this, arg1, arg2, arg3); } return listeners.length; }; World.prototype.beginContact = function(contact) { this.publish("begin-contact", contact); }; World.prototype.endContact = function(contact) { this.publish("end-contact", contact); }; World.prototype.preSolve = function(contact, oldManifold) { this.publish("pre-solve", contact, oldManifold); }; World.prototype.postSolve = function(contact, impulse) { this.publish("post-solve", contact, impulse); }; },{"./Body":2,"./Contact":3,"./Solver":9,"./collision/BroadPhase":12,"./common/Vec2":23,"./util/Timer":50,"./util/common":51,"./util/options":53}],11:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); module.exports = AABB; function AABB(lower, upper) { if (!(this instanceof AABB)) { return new AABB(lower, upper); } this.lowerBound = Vec2.zero(); this.upperBound = Vec2.zero(); if (typeof lower === "object") { this.lowerBound.set(lower); } if (typeof upper === "object") { this.upperBound.set(upper); } } AABB.prototype.isValid = function() { return AABB.isValid(this); }; AABB.isValid = function(aabb) { var d = Vec2.sub(aabb.upperBound, aabb.lowerBound); var valid = d.x >= 0 && d.y >= 0 && Vec2.isValid(aabb.lowerBound) && Vec2.isValid(aabb.upperBound); return valid; }; AABB.prototype.getCenter = function() { return Vec2.neo((this.lowerBound.x + this.upperBound.x) * .5, (this.lowerBound.y + this.upperBound.y) * .5); }; AABB.prototype.getExtents = function() { return Vec2.neo((this.upperBound.x - this.lowerBound.x) * .5, (this.upperBound.y - this.lowerBound.y) * .5); }; AABB.prototype.getPerimeter = function() { return 2 * (this.upperBound.x - this.lowerBound.x + this.upperBound.y - this.lowerBound.y); }; AABB.prototype.combine = function(a, b) { b = b || this; this.lowerBound.set(Math.min(a.lowerBound.x, b.lowerBound.x), Math.min(a.lowerBound.y, b.lowerBound.y)); this.upperBound.set(Math.max(a.upperBound.x, b.upperBound.x), Math.max(a.upperBound.y, b.upperBound.y)); }; AABB.prototype.combinePoints = function(a, b) { this.lowerBound.set(Math.min(a.x, b.x), Math.min(a.y, b.y)); this.upperBound.set(Math.max(a.x, b.x), Math.max(a.y, b.y)); }; AABB.prototype.set = function(aabb) { this.lowerBound.set(aabb.lowerBound.x, aabb.lowerBound.y); this.upperBound.set(aabb.upperBound.x, aabb.upperBound.y); }; AABB.prototype.contains = function(aabb) { var result = true; result = result && this.lowerBound.x <= aabb.lowerBound.x; result = result && this.lowerBound.y <= aabb.lowerBound.y; result = result && aabb.upperBound.x <= this.upperBound.x; result = result && aabb.upperBound.y <= this.upperBound.y; return result; }; AABB.prototype.extend = function(value) { AABB.extend(this, value); }; AABB.extend = function(aabb, value) { aabb.lowerBound.x -= value; aabb.lowerBound.y -= value; aabb.upperBound.x += value; aabb.upperBound.y += value; }; AABB.testOverlap = function(a, b) { var d1x = b.lowerBound.x - a.upperBound.x; var d2x = a.lowerBound.x - b.upperBound.x; var d1y = b.lowerBound.y - a.upperBound.y; var d2y = a.lowerBound.y - b.upperBound.y; if (d1x > 0 || d1y > 0 || d2x > 0 || d2y > 0) { return false; } return true; }; AABB.areEqual = function(a, b) { return Vec2.areEqual(a.lowerBound, b.lowerBound) && Vec2.areEqual(a.upperBound, b.upperBound); }; AABB.diff = function(a, b) { var wD = Math.max(0, Math.min(a.upperBound.x, b.upperBound.x) - Math.max(b.lowerBound.x, a.lowerBound.x)); var hD = Math.max(0, Math.min(a.upperBound.y, b.upperBound.y) - Math.max(b.lowerBound.y, a.lowerBound.y)); var wA = a.upperBound.x - a.lowerBound.x; var hA = a.upperBound.y - a.lowerBound.y; var hB = b.upperBound.y - b.lowerBound.y; var hB = b.upperBound.y - b.lowerBound.y; return wA * hA + wB * hB - wD * hD; }; AABB.prototype.rayCast = function(output, input) { var tmin = -Infinity; var tmax = Infinity; var p = input.p1; var d = Vec2.sub(input.p2, input.p1); var absD = Vec2.abs(d); var normal = Vec2.zero(); for (var f = "x"; f !== null; f = f === "x" ? "y" : null) { if (absD.x < Math.EPSILON) { if (p[f] < this.lowerBound[f] || this.upperBound[f] < p[f]) { return false; } } else { var inv_d = 1 / d[f]; var t1 = (this.lowerBound[f] - p[f]) * inv_d; var t2 = (this.upperBound[f] - p[f]) * inv_d; var s = -1; if (t1 > t2) { var temp = t1; t1 = t2, t2 = temp; s = 1; } if (t1 > tmin) { normal.setZero(); normal[f] = s; tmin = t1; } tmax = Math.min(tmax, t2); if (tmin > tmax) { return false; } } } if (tmin < 0 || input.maxFraction < tmin) { return false; } output.fraction = tmin; output.normal = normal; return true; }; AABB.prototype.toString = function() { return JSON.stringify(this); }; },{"../Settings":7,"../common/Math":18,"../common/Vec2":23}],12:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Math = require("../common/Math"); var AABB = require("./AABB"); var DynamicTree = require("./DynamicTree"); module.exports = BroadPhase; function BroadPhase() { this.m_tree = new DynamicTree(); this.m_proxyCount = 0; this.m_moveBuffer = []; this.queryCallback = this.queryCallback.bind(this); } BroadPhase.prototype.getUserData = function(proxyId) { return this.m_tree.getUserData(proxyId); }; BroadPhase.prototype.testOverlap = function(proxyIdA, proxyIdB) { var aabbA = this.m_tree.getFatAABB(proxyIdA); var aabbB = this.m_tree.getFatAABB(proxyIdB); return AABB.testOverlap(aabbA, aabbB); }; BroadPhase.prototype.getFatAABB = function(proxyId) { return this.m_tree.getFatAABB(proxyId); }; BroadPhase.prototype.getProxyCount = function() { return this.m_proxyCount; }; BroadPhase.prototype.getTreeHeight = function() { return this.m_tree.getHeight(); }; BroadPhase.prototype.getTreeBalance = function() { return this.m_tree.getMaxBalance(); }; BroadPhase.prototype.getTreeQuality = function() { return this.m_tree.getAreaRatio(); }; BroadPhase.prototype.query = function(aabb, queryCallback) { this.m_tree.query(aabb, queryCallback); }; BroadPhase.prototype.rayCast = function(input, rayCastCallback) { this.m_tree.rayCast(input, rayCastCallback); }; BroadPhase.prototype.shiftOrigin = function(newOrigin) { this.m_tree.shiftOrigin(newOrigin); }; BroadPhase.prototype.createProxy = function(aabb, userData) { ASSERT && common.assert(AABB.isValid(aabb)); var proxyId = this.m_tree.createProxy(aabb, userData); this.m_proxyCount++; this.bufferMove(proxyId); return proxyId; }; BroadPhase.prototype.destroyProxy = function(proxyId) { this.unbufferMove(proxyId); this.m_proxyCount--; this.m_tree.destroyProxy(proxyId); }; BroadPhase.prototype.moveProxy = function(proxyId, aabb, displacement) { ASSERT && common.assert(AABB.isValid(aabb)); var changed = this.m_tree.moveProxy(proxyId, aabb, displacement); if (changed) { this.bufferMove(proxyId); } }; BroadPhase.prototype.touchProxy = function(proxyId) { this.bufferMove(proxyId); }; BroadPhase.prototype.bufferMove = function(proxyId) { this.m_moveBuffer.push(proxyId); }; BroadPhase.prototype.unbufferMove = function(proxyId) { for (var i = 0; i < this.m_moveBuffer.length; ++i) { if (this.m_moveBuffer[i] == proxyId) { this.m_moveBuffer[i] = null; } } }; BroadPhase.prototype.updatePairs = function(addPairCallback) { ASSERT && common.assert(typeof addPairCallback === "function"); this.m_callback = addPairCallback; while (this.m_moveBuffer.length > 0) { this.m_queryProxyId = this.m_moveBuffer.pop(); if (this.m_queryProxyId === null) { continue; } var fatAABB = this.m_tree.getFatAABB(this.m_queryProxyId); this.m_tree.query(fatAABB, this.queryCallback); } }; BroadPhase.prototype.queryCallback = function(proxyId) { if (proxyId == this.m_queryProxyId) { return true; } var proxyIdA = Math.min(proxyId, this.m_queryProxyId); var proxyIdB = Math.max(proxyId, this.m_queryProxyId); var userDataA = this.m_tree.getUserData(proxyIdA); var userDataB = this.m_tree.getUserData(proxyIdB); this.m_callback(userDataA, userDataB); return true; }; },{"../Settings":7,"../common/Math":18,"../util/common":51,"./AABB":11,"./DynamicTree":14}],13:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Distance; module.exports.Input = DistanceInput; module.exports.Output = DistanceOutput; module.exports.Proxy = DistanceProxy; module.exports.Cache = SimplexCache; var Settings = require("../Settings"); var common = require("../util/common"); var Timer = require("../util/Timer"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); stats.gjkCalls = 0; stats.gjkIters = 0; stats.gjkMaxIters = 0; function DistanceInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.transformA = null; this.transformB = null; this.useRadii = false; } function DistanceOutput() { this.pointA = Vec2.zero(); this.pointB = Vec2.zero(); this.distance; this.iterations; } function SimplexCache() { this.metric = 0; this.indexA = []; this.indexB = []; this.count = 0; } function Distance(output, cache, input) { ++stats.gjkCalls; var proxyA = input.proxyA; var proxyB = input.proxyB; var xfA = input.transformA; var xfB = input.transformB; DEBUG && common.debug("cahce:", cache.metric, cache.count); DEBUG && common.debug("proxyA:", proxyA.m_count); DEBUG && common.debug("proxyB:", proxyB.m_count); DEBUG && common.debug("xfA:", xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s); DEBUG && common.debug("xfB:", xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s); var simplex = new Simplex(); simplex.readCache(cache, proxyA, xfA, proxyB, xfB); DEBUG && common.debug("cache", simplex.print()); var vertices = simplex.m_v; var k_maxIters = Settings.maxDistnceIterations; var saveA = []; var saveB = []; var saveCount = 0; var distanceSqr1 = Infinity; var distanceSqr2 = Infinity; var iter = 0; while (iter < k_maxIters) { saveCount = simplex.m_count; for (var i = 0; i < saveCount; ++i) { saveA[i] = vertices[i].indexA; saveB[i] = vertices[i].indexB; } simplex.solve(); if (simplex.m_count == 3) { break; } var p = simplex.getClosestPoint(); distanceSqr2 = p.lengthSquared(); if (distanceSqr2 >= distanceSqr1) {} distanceSqr1 = distanceSqr2; var d = simplex.getSearchDirection(); if (d.lengthSquared() < Math.EPSILON * Math.EPSILON) { break; } var vertex = vertices[simplex.m_count]; vertex.indexA = proxyA.getSupport(Rot.mulT(xfA.q, Vec2.neg(d))); vertex.wA = Transform.mul(xfA, proxyA.getVertex(vertex.indexA)); vertex.indexB = proxyB.getSupport(Rot.mulT(xfB.q, d)); vertex.wB = Transform.mul(xfB, proxyB.getVertex(vertex.indexB)); vertex.w = Vec2.sub(vertex.wB, vertex.wA); ++iter; ++stats.gjkIters; var duplicate = false; for (var i = 0; i < saveCount; ++i) { if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) { duplicate = true; break; } } if (duplicate) { break; } ++simplex.m_count; } stats.gjkMaxIters = Math.max(stats.gjkMaxIters, iter); simplex.getWitnessPoints(output.pointA, output.pointB); output.distance = Vec2.distance(output.pointA, output.pointB); output.iterations = iter; DEBUG && common.debug("Distance:", output.distance, output.pointA.x, output.pointA.y, output.pointB.x, output.pointB.y); simplex.writeCache(cache); if (input.useRadii) { var rA = proxyA.m_radius; var rB = proxyB.m_radius; if (output.distance > rA + rB && output.distance > Math.EPSILON) { output.distance -= rA + rB; var normal = Vec2.sub(output.pointB, output.pointA); normal.normalize(); output.pointA.wAdd(rA, normal); output.pointB.wSub(rB, normal); } else { var p = Vec2.mid(output.pointA, output.pointB); output.pointA.set(p); output.pointB.set(p); output.distance = 0; } } } function DistanceProxy() { this.m_buffer = []; this.m_vertices = []; this.m_count = 0; this.m_radius = 0; } DistanceProxy.prototype.getVertexCount = function() { return this.m_count; }; DistanceProxy.prototype.getVertex = function(index) { ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; DistanceProxy.prototype.getSupport = function(d) { var bestIndex = 0; var bestValue = Vec2.dot(this.m_vertices[0], d); for (var i = 0; i < this.m_count; ++i) { var value = Vec2.dot(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; }; DistanceProxy.prototype.getSupportVertex = function(d) { return this.m_vertices[this.getSupport(d)]; }; DistanceProxy.prototype.set = function(shape, index) { ASSERT && common.assert(typeof shape.computeDistanceProxy === "function"); shape.computeDistanceProxy(this, index); }; function SimplexVertex() { this.indexA; this.indexB; this.wA = Vec2.zero(); this.wB = Vec2.zero(); this.w = Vec2.zero(); this.a; } SimplexVertex.prototype.set = function(v) { this.indexA = v.indexA; this.indexB = v.indexB; this.wA = Vec2.clone(v.wA); this.wB = Vec2.clone(v.wB); this.w = Vec2.clone(v.w); this.a = v.a; }; function Simplex() { this.m_v1 = new SimplexVertex(); this.m_v2 = new SimplexVertex(); this.m_v3 = new SimplexVertex(); this.m_v = [ this.m_v1, this.m_v2, this.m_v3 ]; this.m_count; } Simplex.prototype.print = function() { if (this.m_count == 3) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y, this.m_v3.a, this.m_v3.wA.x, this.m_v3.wA.y, this.m_v3.wB.x, this.m_v3.wB.y ].toString(); } else if (this.m_count == 2) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y ].toString(); } else if (this.m_count == 1) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y ].toString(); } else { return "+" + this.m_count; } }; Simplex.prototype.readCache = function(cache, proxyA, transformA, proxyB, transformB) { ASSERT && common.assert(cache.count <= 3); this.m_count = cache.count; for (var i = 0; i < this.m_count; ++i) { var v = this.m_v[i]; v.indexA = cache.indexA[i]; v.indexB = cache.indexB[i]; var wALocal = proxyA.getVertex(v.indexA); var wBLocal = proxyB.getVertex(v.indexB); v.wA = Transform.mul(transformA, wALocal); v.wB = Transform.mul(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 0; } if (this.m_count > 1) { var metric1 = cache.metric; var metric2 = this.getMetric(); if (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < Math.EPSILON) { this.m_count = 0; } } if (this.m_count == 0) { var v = this.m_v[0]; v.indexA = 0; v.indexB = 0; var wALocal = proxyA.getVertex(0); var wBLocal = proxyB.getVertex(0); v.wA = Transform.mul(transformA, wALocal); v.wB = Transform.mul(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 1; this.m_count = 1; } }; Simplex.prototype.writeCache = function(cache) { cache.metric = this.getMetric(); cache.count = this.m_count; for (var i = 0; i < this.m_count; ++i) { cache.indexA[i] = this.m_v[i].indexA; cache.indexB[i] = this.m_v[i].indexB; } }; Simplex.prototype.getSearchDirection = function() { switch (this.m_count) { case 1: return Vec2.neg(this.m_v1.w); case 2: { var e12 = Vec2.sub(this.m_v2.w, this.m_v1.w); var sgn = Vec2.cross(e12, Vec2.neg(this.m_v1.w)); if (sgn > 0) { return Vec2.cross(1, e12); } else { return Vec2.cross(e12, 1); } } default: ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getClosestPoint = function() { switch (this.m_count) { case 0: ASSERT && common.assert(false); return Vec2.zero(); case 1: return Vec2.clone(this.m_v1.w); case 2: return Vec2.wAdd(this.m_v1.a, this.m_v1.w, this.m_v2.a, this.m_v2.w); case 3: return Vec2.zero(); default: ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getWitnessPoints = function(pA, pB) { switch (this.m_count) { case 0: ASSERT && common.assert(false); break; case 1: DEBUG && common.debug("case1", this.print()); pA.set(this.m_v1.wA); pB.set(this.m_v1.wB); break; case 2: DEBUG && common.debug("case2", this.print()); pA.wSet(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pB.wSet(this.m_v1.a, this.m_v1.wB, this.m_v2.a, this.m_v2.wB); break; case 3: DEBUG && common.debug("case3", this.print()); pA.wSet(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pA.wAdd(this.m_v3.a, this.m_v3.wA); pB.set(pA); break; default: ASSERT && common.assert(false); break; } }; Simplex.prototype.getMetric = function() { switch (this.m_count) { case 0: ASSERT && common.assert(false); return 0; case 1: return 0; case 2: return Vec2.distance(this.m_v1.w, this.m_v2.w); case 3: return Vec2.cross(Vec2.sub(this.m_v2.w, this.m_v1.w), Vec2.sub(this.m_v3.w, this.m_v1.w)); default: ASSERT && common.assert(false); return 0; } }; Simplex.prototype.solve = function() { switch (this.m_count) { case 1: break; case 2: this.solve2(); break; case 3: this.solve3(); break; default: ASSERT && common.assert(false); } }; Simplex.prototype.solve2 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var e12 = Vec2.sub(w2, w1); var d12_2 = -Vec2.dot(w1, e12); if (d12_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } var d12_1 = Vec2.dot(w2, e12); if (d12_1 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; }; Simplex.prototype.solve3 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var w3 = this.m_v3.w; var e12 = Vec2.sub(w2, w1); var w1e12 = Vec2.dot(w1, e12); var w2e12 = Vec2.dot(w2, e12); var d12_1 = w2e12; var d12_2 = -w1e12; var e13 = Vec2.sub(w3, w1); var w1e13 = Vec2.dot(w1, e13); var w3e13 = Vec2.dot(w3, e13); var d13_1 = w3e13; var d13_2 = -w1e13; var e23 = Vec2.sub(w3, w2); var w2e23 = Vec2.dot(w2, e23); var w3e23 = Vec2.dot(w3, e23); var d23_1 = w3e23; var d23_2 = -w2e23; var n123 = Vec2.cross(e12, e13); var d123_1 = n123 * Vec2.cross(w2, w3); var d123_2 = n123 * Vec2.cross(w3, w1); var d123_3 = n123 * Vec2.cross(w1, w2); if (d12_2 <= 0 && d13_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } if (d12_1 > 0 && d12_2 > 0 && d123_3 <= 0) { var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; return; } if (d13_1 > 0 && d13_2 > 0 && d123_2 <= 0) { var inv_d13 = 1 / (d13_1 + d13_2); this.m_v1.a = d13_1 * inv_d13; this.m_v3.a = d13_2 * inv_d13; this.m_count = 2; this.m_v2.set(this.m_v3); return; } if (d12_1 <= 0 && d23_2 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } if (d13_1 <= 0 && d23_1 <= 0) { this.m_v3.a = 1; this.m_count = 1; this.m_v1.set(this.m_v3); return; } if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) { var inv_d23 = 1 / (d23_1 + d23_2); this.m_v2.a = d23_1 * inv_d23; this.m_v3.a = d23_2 * inv_d23; this.m_count = 2; this.m_v1.set(this.m_v3); return; } var inv_d123 = 1 / (d123_1 + d123_2 + d123_3); this.m_v1.a = d123_1 * inv_d123; this.m_v2.a = d123_2 * inv_d123; this.m_v3.a = d123_3 * inv_d123; this.m_count = 3; }; Distance.testOverlap = function(shapeA, indexA, shapeB, indexB, xfA, xfB) { var input = new DistanceInput(); input.proxyA.set(shapeA, indexA); input.proxyB.set(shapeB, indexB); input.transformA = xfA; input.transformB = xfB; input.useRadii = true; var cache = new SimplexCache(); var output = new DistanceOutput(); Distance(output, cache, input); return output.distance < 10 * Math.EPSILON; }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51}],14:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Pool = require("../util/Pool"); var Vec2 = require("../common/Vec2"); var Math = require("../common/Math"); var AABB = require("./AABB"); module.exports = DynamicTree; function TreeNode(id) { this.id = id; this.aabb = new AABB(); this.userData = null; this.parent = null; this.child1 = null; this.child2 = null; this.height = -1; this.toString = function() { return this.id + ": " + this.userData; }; } TreeNode.prototype.isLeaf = function() { return this.child1 == null; }; function DynamicTree() { this.m_root = null; this.m_nodes = {}; this.m_lastProxyId = 0; this.m_pool = new Pool({ create: function() { return new TreeNode(); } }); } DynamicTree.prototype.getUserData = function(id) { var node = this.m_nodes[id]; ASSERT && common.assert(!!node); return node.userData; }; DynamicTree.prototype.getFatAABB = function(id) { var node = this.m_nodes[id]; ASSERT && common.assert(!!node); return node.aabb; }; DynamicTree.prototype.allocateNode = function() { var node = this.m_pool.allocate(); node.id = ++this.m_lastProxyId; node.userData = null; node.parent = null; node.child1 = null; node.child2 = null; node.height = -1; this.m_nodes[node.id] = node; return node; }; DynamicTree.prototype.freeNode = function(node) { this.m_pool.release(node); node.height = -1; delete this.m_nodes[node.id]; }; DynamicTree.prototype.createProxy = function(aabb, userData) { ASSERT && common.assert(AABB.isValid(aabb)); var node = this.allocateNode(); node.aabb.set(aabb); AABB.extend(node.aabb, Settings.aabbExtension); node.userData = userData; node.height = 0; this.insertLeaf(node); return node.id; }; DynamicTree.prototype.destroyProxy = function(id) { var node = this.m_nodes[id]; ASSERT && common.assert(!!node); ASSERT && common.assert(node.isLeaf()); this.removeLeaf(node); this.freeNode(node); }; DynamicTree.prototype.moveProxy = function(id, aabb, d) { ASSERT && common.assert(AABB.isValid(aabb)); ASSERT && common.assert(!d || Vec2.isValid(d)); var node = this.m_nodes[id]; ASSERT && common.assert(!!node); ASSERT && common.assert(node.isLeaf()); if (node.aabb.contains(aabb)) { return false; } this.removeLeaf(node); node.aabb.set(aabb); aabb = node.aabb; AABB.extend(aabb, Settings.aabbExtension); if (d.x < 0) { aabb.lowerBound.x += d.x * Settings.aabbMultiplier; } else { aabb.upperBound.x += d.x * Settings.aabbMultiplier; } if (d.y < 0) { aabb.lowerBound.y += d.y * Settings.aabbMultiplier; } else { aabb.upperBound.y += d.y * Settings.aabbMultiplier; } this.insertLeaf(node); return true; }; DynamicTree.prototype.insertLeaf = function(leaf) { ASSERT && common.assert(AABB.isValid(leaf.aabb)); if (this.m_root == null) { this.m_root = leaf; this.m_root.parent = null; return; } var leafAABB = leaf.aabb; var index = this.m_root; while (index.isLeaf() == false) { var child1 = index.child1; var child2 = index.child2; var area = index.aabb.getPerimeter(); var combinedAABB = new AABB(); combinedAABB.combine(index.aabb, leafAABB); var combinedArea = combinedAABB.getPerimeter(); var cost = 2 * combinedArea; var inheritanceCost = 2 * (combinedArea - area); var cost1; if (child1.isLeaf()) { var aabb = new AABB(); aabb.combine(leafAABB, child1.aabb); cost1 = aabb.getPerimeter() + inheritanceCost; } else { var aabb = new AABB(); aabb.combine(leafAABB, child1.aabb); var oldArea = child1.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost1 = newArea - oldArea + inheritanceCost; } var cost2; if (child2.isLeaf()) { var aabb = new AABB(); aabb.combine(leafAABB, child2.aabb); cost2 = aabb.getPerimeter() + inheritanceCost; } else { var aabb = new AABB(); aabb.combine(leafAABB, child2.aabb); var oldArea = child2.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost2 = newArea - oldArea + inheritanceCost; } if (cost < cost1 && cost < cost2) { break; } if (cost1 < cost2) { index = child1; } else { index = child2; } } var sibling = index; var oldParent = sibling.parent; var newParent = this.allocateNode(); newParent.parent = oldParent; newParent.userData = null; newParent.aabb.combine(leafAABB, sibling.aabb); newParent.height = sibling.height + 1; if (oldParent != null) { if (oldParent.child1 == sibling) { oldParent.child1 = newParent; } else { oldParent.child2 = newParent; } newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; } else { newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; this.m_root = newParent; } index = leaf.parent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; ASSERT && common.assert(child1 != null); ASSERT && common.assert(child2 != null); index.height = 1 + Math.max(child1.height, child2.height); index.aabb.combine(child1.aabb, child2.aabb); index = index.parent; } }; DynamicTree.prototype.removeLeaf = function(leaf) { if (leaf == this.m_root) { this.m_root = null; return; } var parent = leaf.parent; var grandParent = parent.parent; var sibling; if (parent.child1 == leaf) { sibling = parent.child2; } else { sibling = parent.child1; } if (grandParent != null) { if (grandParent.child1 == parent) { grandParent.child1 = sibling; } else { grandParent.child2 = sibling; } sibling.parent = grandParent; this.freeNode(parent); var index = grandParent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; index.aabb.combine(child1.aabb, child2.aabb); index.height = 1 + Math.max(child1.height, child2.height); index = index.parent; } } else { this.m_root = sibling; sibling.parent = null; this.freeNode(parent); } }; DynamicTree.prototype.balance = function(iA) { ASSERT && common.assert(iA != null); var A = iA; if (A.isLeaf() || A.height < 2) { return iA; } var B = A.child1; var C = A.child2; var balance = C.height - B.height; if (balance > 1) { var F = C.child1; var G = C.child2; C.child1 = A; C.parent = A.parent; A.parent = C; if (C.parent != null) { if (C.parent.child1 == iA) { C.parent.child1 = C; } else { C.parent.child2 = C; } } else { this.m_root = C; } if (F.height > G.height) { C.child2 = F; A.child2 = G; G.parent = A; A.aabb.combine(B.aabb, G.aabb); C.aabb.combine(A.aabb, F.aabb); A.height = 1 + Math.max(B.height, G.height); C.height = 1 + Math.max(A.height, F.height); } else { C.child2 = G; A.child2 = F; F.parent = A; A.aabb.combine(B.aabb, F.aabb); C.aabb.combine(A.aabb, G.aabb); A.height = 1 + Math.max(B.height, F.height); C.height = 1 + Math.max(A.height, G.height); } return C; } if (balance < -1) { var D = B.child1; var E = B.child2; B.child1 = A; B.parent = A.parent; A.parent = B; if (B.parent != null) { if (B.parent.child1 == A) { B.parent.child1 = B; } else { B.parent.child2 = B; } } else { this.m_root = B; } if (D.height > E.height) { B.child2 = D; A.child1 = E; E.parent = A; A.aabb.combine(C.aabb, E.aabb); B.aabb.combine(A.aabb, D.aabb); A.height = 1 + Math.max(C.height, E.height); B.height = 1 + Math.max(A.height, D.height); } else { B.child2 = E; A.child1 = D; D.parent = A; A.aabb.combine(C.aabb, D.aabb); B.aabb.combine(A.aabb, E.aabb); A.height = 1 + Math.max(C.height, D.height); B.height = 1 + Math.max(A.height, E.height); } return B; } return A; }; DynamicTree.prototype.getHeight = function() { if (this.m_root == null) { return 0; } return this.m_root.height; }; DynamicTree.prototype.getAreaRatio = function() { if (this.m_root == null) { return 0; } var root = this.m_root; var rootArea = root.aabb.getPerimeter(); var totalArea = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } totalArea += node.aabb.getPerimeter(); } iteratorPool.release(it); return totalArea / rootArea; }; DynamicTree.prototype.computeHeight = function(id) { var node; if (typeof id !== "undefined") { node = this.m_nodes[id]; } else { node = this.m_root; } if (node.isLeaf()) { return 0; } var height1 = ComputeHeight(node.child1); var height2 = ComputeHeight(node.child2); return 1 + Math.max(height1, height2); }; DynamicTree.prototype.validateStructure = function(node) { if (node == null) { return; } if (node == this.m_root) { ASSERT && common.assert(node.parent == null); } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { ASSERT && common.assert(child1 == null); ASSERT && common.assert(child2 == null); ASSERT && common.assert(node.height == 0); return; } ASSERT && common.assert(child1.parent == node); ASSERT && common.assert(child2.parent == node); this.validateStructure(child1); this.validateStructure(child2); }; DynamicTree.prototype.validateMetrics = function(node) { if (node == null) { return; } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { ASSERT && common.assert(child1 == null); ASSERT && common.assert(child2 == null); ASSERT && common.assert(node.height == 0); return; } var height1 = this.m_nodes[child1].height; var height2 = this.m_nodes[child2].height; var height = 1 + Math.max(height1, height2); ASSERT && common.assert(node.height == height); var aabb = new AABB(); aabb.combine(child1.aabb, child2.aabb); ASSERT && common.assert(AABB.areEqual(aabb, node.aabb)); this.validateMetrics(child1); this.validateMetrics(child2); }; DynamicTree.prototype.validate = function() { ValidateStructure(this.m_root); ValidateMetrics(this.m_root); ASSERT && common.assert(this.getHeight() == this.computeHeight()); }; DynamicTree.prototype.getMaxBalance = function() { var maxBalance = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height <= 1) { continue; } ASSERT && common.assert(node.isLeaf() == false); var balance = Math.abs(node.child2.height - node.child1.height); maxBalance = Math.max(maxBalance, balance); } iteratorPool.release(it); return maxBalance; }; DynamicTree.prototype.rebuildBottomUp = function() { var nodes = []; var count = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } if (node.isLeaf()) { node.parent = null; nodes[count] = node; ++count; } else { this.freeNode(node); } } iteratorPool.release(it); while (count > 1) { var minCost = Infinity; var iMin = -1, jMin = -1; for (var i = 0; i < count; ++i) { var aabbi = nodes[i].aabb; for (var j = i + 1; j < count; ++j) { var aabbj = nodes[j].aabb; var b = new AABB(); b.combine(aabbi, aabbj); var cost = b.getPerimeter(); if (cost < minCost) { iMin = i; jMin = j; minCost = cost; } } } var child1 = nodes[iMin]; var child2 = nodes[jMin]; var parent = this.allocateNode(); parent.child1 = child1; parent.child2 = child2; parent.height = 1 + Math.max(child1.height, child2.height); parent.aabb.combine(child1.aabb, child2.aabb); parent.parent = null; child1.parent = parent; child2.parent = parent; nodes[jMin] = nodes[count - 1]; nodes[iMin] = parent; --count; } this.m_root = nodes[0]; this.validate(); }; DynamicTree.prototype.shiftOrigin = function(newOrigin) { var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { var aabb = node.aabb; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; } iteratorPool.release(it); }; DynamicTree.prototype.query = function(aabb, queryCallback) { ASSERT && common.assert(typeof queryCallback === "function"); var stack = stackPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, aabb)) { if (node.isLeaf()) { var proceed = queryCallback(node.id); if (proceed == false) { return; } } else { stack.push(node.child1); stack.push(node.child2); } } } stackPool.release(stack); }; DynamicTree.prototype.rayCast = function(input, rayCastCallback) { ASSERT && common.assert(typeof rayCastCallback === "function"); var p1 = input.p1; var p2 = input.p2; var r = Vec2.sub(p2, p1); ASSERT && common.assert(r.lengthSquared() > 0); r.normalize(); var v = Vec2.cross(1, r); var abs_v = Vec2.abs(v); var maxFraction = input.maxFraction; var segmentAABB = new AABB(); var t = Vec2.wAdd(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); var stack = stackPool.allocate(); var subInput = inputPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, segmentAABB) == false) { continue; } var c = node.aabb.getCenter(); var h = node.aabb.getExtents(); var separation = Math.abs(Vec2.dot(v, Vec2.sub(p1, c))) - Vec2.dot(abs_v, h); if (separation > 0) { continue; } if (node.isLeaf()) { subInput.p1 = Vec2.clone(input.p1); subInput.p2 = Vec2.clone(input.p2); subInput.maxFraction = maxFraction; var value = rayCastCallback(subInput, node.id); if (value == 0) { return; } if (value > 0) { maxFraction = value; t = Vec2.wAdd(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); } } else { stack.push(node.child1); stack.push(node.child2); } } stackPool.release(stack); inputPool.release(subInput); }; var inputPool = new Pool({ create: function() { return {}; }, release: function(stack) {} }); var stackPool = new Pool({ create: function() { return []; }, release: function(stack) { stack.length = 0; } }); var iteratorPool = new Pool({ create: function() { return new Iterator(); }, release: function(iterator) { iterator.close(); } }); function Iterator() { var parents = []; var states = []; return { preorder: function(root) { parents.length = 0; parents.push(root); states.length = 0; states.push(0); return this; }, next: function() { while (parents.length > 0) { var i = parents.length - 1; var node = parents[i]; if (states[i] === 0) { states[i] = 1; return node; } if (states[i] === 1) { states[i] = 2; if (node.child1) { parents.push(node.child1); states.push(1); return node.child1; } } if (states[i] === 2) { states[i] = 3; if (node.child2) { parents.push(node.child2); states.push(1); return node.child2; } } parents.pop(); states.pop(); } }, close: function() { parents.length = 0; } }; } },{"../Settings":7,"../common/Math":18,"../common/Vec2":23,"../util/Pool":49,"../util/common":51,"./AABB":11}],15:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = TimeOfImpact; module.exports.Input = TOIInput; module.exports.Output = TOIOutput; var Settings = require("../Settings"); var common = require("../util/common"); var Timer = require("../util/Timer"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Distance = require("./Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TOIInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.sweepA = new Sweep(); this.sweepB = new Sweep(); this.tMax; } TOIOutput.e_unknown = 0; TOIOutput.e_failed = 1; TOIOutput.e_overlapped = 2; TOIOutput.e_touching = 3; TOIOutput.e_separated = 4; function TOIOutput() { this.state; this.t; } stats.toiTime = 0; stats.toiMaxTime = 0; stats.toiCalls = 0; stats.toiIters = 0; stats.toiMaxIters = 0; stats.toiRootIters = 0; stats.toiMaxRootIters = 0; function TimeOfImpact(output, input) { var timer = Timer.now(); ++stats.toiCalls; output.state = TOIOutput.e_unknown; output.t = input.tMax; var proxyA = input.proxyA; var proxyB = input.proxyB; var sweepA = input.sweepA; var sweepB = input.sweepB; DEBUG && common.debug("sweepA", sweepA.localCenter.x, sweepA.localCenter.y, sweepA.c.x, sweepA.c.y, sweepA.a, sweepA.alpha0, sweepA.c0.x, sweepA.c0.y, sweepA.a0); DEBUG && common.debug("sweepB", sweepB.localCenter.x, sweepB.localCenter.y, sweepB.c.x, sweepB.c.y, sweepB.a, sweepB.alpha0, sweepB.c0.x, sweepB.c0.y, sweepB.a0); sweepA.normalize(); sweepB.normalize(); var tMax = input.tMax; var totalRadius = proxyA.m_radius + proxyB.m_radius; var target = Math.max(Settings.linearSlop, totalRadius - 3 * Settings.linearSlop); var tolerance = .25 * Settings.linearSlop; ASSERT && common.assert(target > tolerance); var t1 = 0; var k_maxIterations = Settings.maxTOIIterations; var iter = 0; var cache = new SimplexCache(); var distanceInput = new DistanceInput(); distanceInput.proxyA = input.proxyA; distanceInput.proxyB = input.proxyB; distanceInput.useRadii = false; for (;;) { var xfA = Transform.identity(); var xfB = Transform.identity(); sweepA.getTransform(xfA, t1); sweepB.getTransform(xfB, t1); DEBUG && common.debug("xfA:", xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s); DEBUG && common.debug("xfB:", xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s); distanceInput.transformA = xfA; distanceInput.transformB = xfB; var distanceOutput = new DistanceOutput(); Distance(distanceOutput, cache, distanceInput); DEBUG && common.debug("distance:", distanceOutput.distance); if (distanceOutput.distance <= 0) { output.state = TOIOutput.e_overlapped; output.t = 0; break; } if (distanceOutput.distance < target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; break; } var fcn = new SeparationFunction(); fcn.initialize(cache, proxyA, sweepA, proxyB, sweepB, t1); if (false) { var N = 100; var dx = 1 / N; var xs = []; var fs = []; var x = 0; for (var i = 0; i <= N; ++i) { sweepA.getTransform(xfA, x); sweepB.getTransform(xfB, x); var f = fcn.evaluate(xfA, xfB) - target; printf("%g %g\n", x, f); xs[i] = x; fs[i] = f; x += dx; } } var done = false; var t2 = tMax; var pushBackIter = 0; for (;;) { var s2 = fcn.findMinSeparation(t2); var indexA = fcn.indexA; var indexB = fcn.indexB; if (s2 > target + tolerance) { output.state = TOIOutput.e_separated; output.t = tMax; done = true; break; } if (s2 > target - tolerance) { t1 = t2; break; } var s1 = fcn.evaluate(t1); var indexA = fcn.indexA; var indexB = fcn.indexB; DEBUG && common.debug("s1:", s1, target, tolerance, t1); if (s1 < target - tolerance) { output.state = TOIOutput.e_failed; output.t = t1; done = true; break; } if (s1 <= target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; done = true; break; } var rootIterCount = 0; var a1 = t1, a2 = t2; for (;;) { var t; if (rootIterCount & 1) { t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); } else { t = .5 * (a1 + a2); } ++rootIterCount; ++stats.toiRootIters; var s = fcn.evaluate(t); var indexA = fcn.indexA; var indexB = fcn.indexB; if (Math.abs(s - target) < tolerance) { t2 = t; break; } if (s > target) { a1 = t; s1 = s; } else { a2 = t; s2 = s; } if (rootIterCount == 50) { break; } } stats.toiMaxRootIters = Math.max(stats.toiMaxRootIters, rootIterCount); ++pushBackIter; if (pushBackIter == Settings.maxPolygonVertices) { break; } } ++iter; ++stats.toiIters; if (done) { break; } if (iter == k_maxIterations) { output.state = TOIOutput.e_failed; output.t = t1; break; } } stats.toiMaxIters = Math.max(stats.toiMaxIters, iter); var time = Timer.diff(timer); stats.toiMaxTime = Math.max(stats.toiMaxTime, time); stats.toiTime += time; } var e_points = 1; var e_faceA = 2; var e_faceB = 3; function SeparationFunction() { this.m_proxyA = new DistanceProxy(); this.m_proxyB = new DistanceProxy(); this.m_sweepA; this.m_sweepB; this.m_type; this.m_localPoint = Vec2.zero(); this.m_axis = Vec2.zero(); } SeparationFunction.prototype.initialize = function(cache, proxyA, sweepA, proxyB, sweepB, t1) { this.m_proxyA = proxyA; this.m_proxyB = proxyB; var count = cache.count; ASSERT && common.assert(0 < count && count < 3); this.m_sweepA = sweepA; this.m_sweepB = sweepB; var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t1); this.m_sweepB.getTransform(xfB, t1); if (count == 1) { this.m_type = e_points; var localPointA = this.m_proxyA.getVertex(cache.indexA[0]); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointA = Transform.mul(xfA, localPointA); var pointB = Transform.mul(xfB, localPointB); this.m_axis.wSet(1, pointB, -1, pointA); var s = this.m_axis.normalize(); return s; } else if (cache.indexA[0] == cache.indexA[1]) { this.m_type = e_faceB; var localPointB1 = proxyB.getVertex(cache.indexB[0]); var localPointB2 = proxyB.getVertex(cache.indexB[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointB2, localPointB1), 1); this.m_axis.normalize(); var normal = Rot.mul(xfB.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointB1, localPointB2); var pointB = Transform.mul(xfB, this.m_localPoint); var localPointA = proxyA.getVertex(cache.indexA[0]); var pointA = Transform.mul(xfA, localPointA); var s = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } else { this.m_type = e_faceA; var localPointA1 = this.m_proxyA.getVertex(cache.indexA[0]); var localPointA2 = this.m_proxyA.getVertex(cache.indexA[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointA2, localPointA1), 1); this.m_axis.normalize(); var normal = Rot.mul(xfA.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointA1, localPointA2); var pointA = Transform.mul(xfA, this.m_localPoint); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointB = Transform.mul(xfB, localPointB); var s = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } }; SeparationFunction.prototype.compute = function(find, t) { var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t); this.m_sweepB.getTransform(xfB, t); switch (this.m_type) { case e_points: { if (find) { var axisA = Rot.mulT(xfA.q, this.m_axis); var axisB = Rot.mulT(xfB.q, Vec2.neg(this.m_axis)); this.indexA = this.m_proxyA.getSupport(axisA); this.indexB = this.m_proxyB.getSupport(axisB); } var localPointA = this.m_proxyA.getVertex(this.indexA); var localPointB = this.m_proxyB.getVertex(this.indexB); var pointA = Transform.mul(xfA, localPointA); var pointB = Transform.mul(xfB, localPointB); var sep = Vec2.dot(pointB, this.m_axis) - Vec2.dot(pointA, this.m_axis); return sep; } case e_faceA: { var normal = Rot.mul(xfA.q, this.m_axis); var pointA = Transform.mul(xfA, this.m_localPoint); if (find) { var axisB = Rot.mulT(xfB.q, Vec2.neg(normal)); this.indexA = -1; this.indexB = this.m_proxyB.getSupport(axisB); } var localPointB = this.m_proxyB.getVertex(this.indexB); var pointB = Transform.mul(xfB, localPointB); var sep = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); return sep; } case e_faceB: { var normal = Rot.mul(xfB.q, this.m_axis); var pointB = Transform.mul(xfB, this.m_localPoint); if (find) { var axisA = Rot.mulT(xfA.q, Vec2.neg(normal)); this.indexB = -1; this.indexA = this.m_proxyA.getSupport(axisA); } var localPointA = this.m_proxyA.getVertex(this.indexA); var pointA = Transform.mul(xfA, localPointA); var sep = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); return sep; } default: ASSERT && common.assert(false); if (find) { this.indexA = -1; this.indexB = -1; } return 0; } }; SeparationFunction.prototype.findMinSeparation = function(t) { return this.compute(true, t); }; SeparationFunction.prototype.evaluate = function(t) { return this.compute(false, t); }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51,"./Distance":13}],16:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat22; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); function Mat22(a, b, c, d) { if (typeof a === "object" && a !== null) { this.ex = Vec2.clone(a); this.ey = Vec2.clone(b); } else if (typeof a === "number") { this.ex = Vec2.neo(a, c); this.ey = Vec2.neo(b, d); } else { this.ex = Vec2.zero(); this.ey = Vec2.zero(); } } Mat22.prototype.toString = function() { return JSON.stringify(this); }; Mat22.isValid = function(o) { return o && Vec2.isValid(o.ex) && Vec2.isValid(o.ey); }; Mat22.assert = function(o) { if (!ASSERT) return; if (!Mat22.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Mat22!"); } }; Mat22.prototype.set = function(a, b, c, d) { if (typeof a === "number" && typeof b === "number" && typeof c === "number" && typeof d === "number") { this.ex.set(a, c); this.ey.set(b, d); } else if (typeof a === "object" && typeof b === "object") { this.ex.set(a); this.ey.set(b); } else if (typeof a === "object") { ASSERT && Mat22.assert(a); this.ex.set(a.ex); this.ey.set(a.ey); } else { ASSERT && common.assert(false); } }; Mat22.prototype.setIdentity = function() { this.ex.x = 1; this.ey.x = 0; this.ex.y = 0; this.ey.y = 1; }; Mat22.prototype.setZero = function() { this.ex.x = 0; this.ey.x = 0; this.ex.y = 0; this.ey.y = 0; }; Mat22.prototype.getInverse = function() { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var imx = new Mat22(); imx.ex.x = det * d; imx.ey.x = -det * b; imx.ex.y = -det * c; imx.ey.y = det * a; return imx; }; Mat22.prototype.solve = function(v) { ASSERT && Vec2.assert(v); var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var w = Vec2.zero(); w.x = det * (d * v.x - b * v.y); w.y = det * (a * v.y - c * v.x); return w; }; Mat22.mul = function(mx, v) { if (v && "x" in v && "y" in v) { ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return Vec2.neo(x, y); } else if (v && "ex" in v && "ey" in v) { ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); } ASSERT && common.assert(false); }; Mat22.mulT = function(mx, v) { if (v && "x" in v && "y" in v) { ASSERT && Vec2.assert(v); return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey)); } else if (v && "ex" in v && "ey" in v) { ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); } ASSERT && common.assert(false); }; Mat22.abs = function(mx) { ASSERT && Mat22.assert(mx); return new Mat22(Vec2.abs(mx.ex), Vec2.abs(mx.ey)); }; Mat22.add = function(mx1, mx2) { ASSERT && Mat22.assert(mx1); ASSERT && Mat22.assert(mx2); return new Mat22(Vec2.add(mx1.ex + mx2.ex), Vec2.add(mx1.ey + mx2.ey)); }; },{"../util/common":51,"./Math":18,"./Vec2":23}],17:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat33; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Vec3 = require("./Vec3"); function Mat33(a, b, c) { if (typeof a === "object" && a !== null) { this.ex = Vec3.clone(a); this.ey = Vec3.clone(b); this.ez = Vec3.clone(c); } else { this.ex = Vec3(); this.ey = Vec3(); this.ez = Vec3(); } } Mat33.prototype.toString = function() { return JSON.stringify(this); }; Mat33.isValid = function(o) { return o && Vec3.isValid(o.ex) && Vec3.isValid(o.ey) && Vec3.isValid(o.ez); }; Mat33.assert = function(o) { if (!ASSERT) return; if (!Mat33.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Mat33!"); } }; Mat33.prototype.setZero = function() { this.ex.setZero(); this.ey.setZero(); this.ez.setZero(); return this; }; Mat33.prototype.solve33 = function(v) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var r = new Vec3(); r.x = det * Vec3.dot(v, Vec3.cross(this.ey, this.ez)); r.y = det * Vec3.dot(this.ex, Vec3.cross(v, this.ez)); r.z = det * Vec3.dot(this.ex, Vec3.cross(this.ey, v)); return r; }; Mat33.prototype.solve22 = function(v) { var a11 = this.ex.x; var a12 = this.ey.x; var a21 = this.ex.y; var a22 = this.ey.y; var det = a11 * a22 - a12 * a21; if (det != 0) { det = 1 / det; } var r = Vec2.zero(); r.x = det * (a22 * v.x - a12 * v.y); r.y = det * (a11 * v.y - a21 * v.x); return r; }; Mat33.prototype.getInverse22 = function(M) { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } M.ex.x = det * d; M.ey.x = -det * b; M.ex.z = 0; M.ex.y = -det * c; M.ey.y = det * a; M.ey.z = 0; M.ez.x = 0; M.ez.y = 0; M.ez.z = 0; }; Mat33.prototype.getSymInverse33 = function(M) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var a11 = this.ex.x; var a12 = this.ey.x; var a13 = this.ez.x; var a22 = this.ey.y; var a23 = this.ez.y; var a33 = this.ez.z; M.ex.x = det * (a22 * a33 - a23 * a23); M.ex.y = det * (a13 * a23 - a12 * a33); M.ex.z = det * (a12 * a23 - a13 * a22); M.ey.x = M.ex.y; M.ey.y = det * (a11 * a33 - a13 * a13); M.ey.z = det * (a13 * a12 - a11 * a23); M.ez.x = M.ex.z; M.ez.y = M.ey.z; M.ez.z = det * (a11 * a22 - a12 * a12); }; Mat33.mul = function(a, b) { ASSERT && Mat33.assert(a); if (b && "z" in b && "y" in b && "x" in b) { ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); } else if (b && "y" in b && "x" in b) { ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); } ASSERT && common.assert(false); }; Mat33.add = function(a, b) { ASSERT && Mat33.assert(a); ASSERT && Mat33.assert(b); return new Vec3(a.x + b.x, a.y + b.y, a.z + b.z); }; },{"../util/common":51,"./Math":18,"./Vec2":23,"./Vec3":24}],18:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var native = Math; var math = module.exports = create(native); math.EPSILON = 1e-9; math.isFinite = function(x) { return typeof x === "number" && isFinite(x) && !isNaN(x); }; math.assert = function(x) { if (!ASSERT) return; if (!math.isFinite(x)) { DEBUG && common.debug(x); throw new Error("Invalid Number!"); } }; math.invSqrt = function(x) { return 1 / native.sqrt(x); }; math.nextPowerOfTwo = function(x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; }; math.isPowerOfTwo = function(x) { return x > 0 && (x & x - 1) == 0; }; math.mod = function(num, min, max) { if (typeof min === "undefined") { max = 1, min = 0; } else if (typeof max === "undefined") { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; math.clamp = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; math.random = function(min, max) { if (typeof min === "undefined") { max = 1; min = 0; } else if (typeof max === "undefined") { max = min; min = 0; } return min == max ? min : native.random() * (max - min) + min; }; },{"../util/common":51,"../util/create":52}],19:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Position; var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Position() { this.c = Vec2.zero(); this.a = 0; } Position.prototype.getTransform = function(xf, p) { xf.q.set(this.a); xf.p.set(Vec2.sub(this.c, Rot.mul(xf.q, p))); return xf; }; },{"./Rot":20,"./Vec2":23}],20:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Rot; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Math = require("./Math"); function Rot(angle) { if (!(this instanceof Rot)) { return new Rot(angle); } if (typeof angle === "number") { this.setAngle(angle); } else if (typeof angle === "object") { this.set(angle); } else { this.setIdentity(); } } Rot.neo = function(angle) { var obj = Object.create(Rot.prototype); obj.setAngle(angle); return obj; }; Rot.clone = function(rot) { ASSERT && Rot.assert(rot); var obj = Object.create(Rot.prototype); ojb.s = rot.s; ojb.c = rot.c; return ojb; }; Rot.identity = function(rot) { ASSERT && Rot.assert(rot); var obj = Object.create(Rot.prototype); obj.s = 0; obj.c = 1; return obj; }; Rot.isValid = function(o) { return o && Math.isFinite(o.s) && Math.isFinite(o.c); }; Rot.assert = function(o) { if (!ASSERT) return; if (!Rot.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Rot!"); } }; Rot.prototype.setIdentity = function() { this.s = 0; this.c = 1; }; Rot.prototype.set = function(angle) { if (typeof angle === "object") { ASSERT && Rot.assert(angle); this.s = angle.s; this.c = angle.c; } else { ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); } }; Rot.prototype.setAngle = function(angle) { ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); }; Rot.prototype.getAngle = function() { return Math.atan2(this.s, this.c); }; Rot.prototype.getXAxis = function() { return Vec2.neo(this.c, this.s); }; Rot.prototype.getYAxis = function() { return Vec2.neo(-this.s, this.c); }; Rot.mul = function(rot, m) { ASSERT && Rot.assert(rot); if ("c" in m && "s" in m) { ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); } }; Rot.mulSub = function(rot, v, w) { var x = rot.c * (v.x - w.x) - rot.s * (v.y - w.y); var y = rot.s * (v.x - w.y) + rot.c * (v.y - w.y); return Vec2.neo(x, y); }; Rot.mulT = function(rot, m) { if ("c" in m && "s" in m) { ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); } }; },{"../util/common":51,"./Math":18,"./Vec2":23}],21:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Sweep; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); var Transform = require("./Transform"); function Sweep(c, a) { ASSERT && common.assert(typeof c === "undefined"); ASSERT && common.assert(typeof a === "undefined"); this.localCenter = Vec2.zero(); this.c = Vec2.zero(); this.a = 0; this.alpha0 = 0; this.c0 = Vec2.zero(); this.a0 = 0; } Sweep.prototype.setTransform = function(xf) { var c = Transform.mul(xf, this.localCenter); this.c.set(c); this.c0.set(c); this.a = xf.q.getAngle(); this.a0 = xf.q.getAngle(); }; Sweep.prototype.setLocalCenter = function(localCenter, xf) { this.localCenter.set(localCenter); var c = Transform.mul(xf, this.localCenter); this.c.set(c); this.c0.set(c); }; Sweep.prototype.getTransform = function(xf, beta) { beta = typeof beta === "undefined" ? 0 : beta; xf.q.setAngle((1 - beta) * this.a0 + beta * this.a); xf.p.wSet(1 - beta, this.c0, beta, this.c); xf.p.sub(Rot.mul(xf.q, this.localCenter)); }; Sweep.prototype.advance = function(alpha) { ASSERT && common.assert(this.alpha0 < 1); var beta = (alpha - this.alpha0) / (1 - this.alpha0); this.c0.wSet(beta, this.c, 1 - beta, this.c0); this.a0 = beta * this.a + (1 - beta) * this.a0; this.alpha0 = alpha; }; Sweep.prototype.forward = function() { this.a0 = this.a; this.c0.set(this.c); }; Sweep.prototype.normalize = function() { var a0 = Math.mod(this.a0, -Math.PI, +Math.PI); this.a -= this.a0 - a0; this.a0 = a0; }; Sweep.prototype.clone = function() { var clone = new Sweep(); clone.localCenter.set(this.localCenter); clone.alpha0 = this.alpha0; clone.a0 = this.a0; clone.a = this.a; clone.c0.set(this.c0); clone.c.set(this.c); return clone; }; Sweep.prototype.set = function(that) { this.localCenter.set(that.localCenter); this.alpha0 = that.alpha0; this.a0 = that.a0; this.a = that.a; this.c0.set(that.c0); this.c.set(that.c); }; },{"../util/common":51,"./Math":18,"./Rot":20,"./Transform":22,"./Vec2":23}],22:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Transform; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Transform(position, rotation) { if (!(this instanceof Transform)) { return new Transform(position, rotation); } this.p = Vec2.zero(); this.q = Rot.identity(); if (typeof position !== "undefined") { this.p.set(position); } if (typeof rotation !== "undefined") { this.q.set(rotation); } } Transform.clone = function(xf) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(xf.p); obj.q = Rot.clone(xf.q); return obj; }; Transform.neo = function(position, rotation) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(position); obj.q = Rot.clone(rotation); return obj; }; Transform.identity = function() { var obj = Object.create(Transform.prototype); obj.p = Vec2.zero(); obj.q = Rot.identity(); return obj; }; Transform.prototype.setIdentity = function() { this.p.setZero(); this.q.setIdentity(); }; Transform.prototype.set = function(a, b) { if (Transform.isValid(a)) { this.p.set(a.p); this.q.set(a.q); } else { this.p.set(a); this.q.set(b); } }; Transform.isValid = function(o) { return o && Vec2.isValid(o.p) && Rot.isValid(o.q); }; Transform.assert = function(o) { if (!ASSERT) return; if (!Transform.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Transform!"); } }; Transform.mul = function(a, b) { ASSERT && Transform.assert(a); if (Array.isArray(b)) { var arr = []; for (var i = 0; i < b.length; i++) { arr[i] = Transform.mul(a, b[i]); } return arr; } else if ("x" in b && "y" in b) { ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q = Rot.mul(a.q, b.q); xf.p = Vec2.add(Rot.mul(a.q, b.p), a.p); return xf; } }; Transform.mulT = function(a, b) { ASSERT && Transform.assert(a); if ("x" in b && "y" in b) { ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q.set(Rot.mulT(a.q, b.q)); xf.p.set(Rot.mulT(a.q, Vec2.sub(b.p, a.p))); return xf; } }; },{"../util/common":51,"./Rot":20,"./Vec2":23}],23:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec2; var common = require("../util/common"); var Math = require("./Math"); function Vec2(x, y) { if (!(this instanceof Vec2)) { return new Vec2(x, y); } if (typeof x === "undefined") { this.x = 0, this.y = 0; } else if (typeof x === "object") { this.x = x.x, this.y = x.y; } else { this.x = x, this.y = y; } ASSERT && Vec2.assert(this); } Vec2.zero = function() { var obj = Object.create(Vec2.prototype); obj.x = 0; obj.y = 0; return obj; }; Vec2.neo = function(x, y) { var obj = Object.create(Vec2.prototype); obj.x = x; obj.y = y; return obj; }; Vec2.clone = function(v, depricated) { ASSERT && Vec2.assert(v); ASSERT && common.assert(!depricated); return Vec2.neo(v.x, v.y); }; Vec2.prototype.toString = function() { return JSON.stringify(this); }; Vec2.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y); }; Vec2.assert = function(o) { if (!ASSERT) return; if (!Vec2.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Vec2!"); } }; Vec2.prototype.clone = function(depricated) { return Vec2.clone(this, depricated); }; Vec2.prototype.setZero = function() { this.x = 0; this.y = 0; return this; }; Vec2.prototype.set = function(x, y) { if (typeof x === "object") { ASSERT && Vec2.assert(x); this.x = x.x; this.y = x.y; } else { ASSERT && Math.assert(x); ASSERT && Math.assert(y); this.x = x; this.y = y; } return this; }; Vec2.prototype.wSet = function(a, v, b, w) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.y; } this.x = x; this.y = y; return this; }; Vec2.prototype.add = function(w) { ASSERT && Vec2.assert(w); this.x += w.x; this.y += w.y; return this; }; Vec2.prototype.wAdd = function(a, v, b, w) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.y; } this.x += x; this.y += y; return this; }; Vec2.prototype.wSub = function(a, v, b, w) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.y; } this.x -= x; this.y -= y; return this; }; Vec2.prototype.sub = function(w) { ASSERT && Vec2.assert(w); this.x -= w.x; this.y -= w.y; return this; }; Vec2.prototype.mul = function(m) { ASSERT && Math.assert(m); this.x *= m; this.y *= m; return this; }; Vec2.prototype.length = function() { return Vec2.lengthOf(this); }; Vec2.prototype.lengthSquared = function() { return Vec2.lengthSquared(this); }; Vec2.prototype.normalize = function() { var length = this.length(); if (length < Math.EPSILON) { return 0; } var invLength = 1 / length; this.x *= invLength; this.y *= invLength; return length; }; Vec2.lengthOf = function(v) { ASSERT && Vec2.assert(v); return Math.sqrt(v.x * v.x + v.y * v.y); }; Vec2.lengthSquared = function(v) { ASSERT && Vec2.assert(v); return v.x * v.x + v.y * v.y; }; Vec2.distance = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return Math.sqrt(dx * dx + dy * dy); }; Vec2.distanceSquared = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return dx * dx + dy * dy; }; Vec2.areEqual = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return v == w || typeof w === "object" && w !== null && v.x == w.x && v.y == w.y; }; Vec2.skew = function(v) { ASSERT && Vec2.assert(v); return Vec2.neo(-v.y, v.x); }; Vec2.dot = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return v.x * w.x + v.y * w.y; }; Vec2.cross = function(v, w) { if (typeof w === "number") { ASSERT && Vec2.assert(v); ASSERT && Math.assert(w); return Vec2.neo(w * v.y, -w * v.x); } else if (typeof v === "number") { ASSERT && Math.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y, v * w.x); } else { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return v.x * w.y - v.y * w.x; } }; Vec2.addCross = function(a, v, w) { if (typeof w === "number") { ASSERT && Vec2.assert(v); ASSERT && Math.assert(w); return Vec2.neo(w * v.y + a.x, -w * v.x + a.y); } else if (typeof v === "number") { ASSERT && Math.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y + a.x, v * w.x + a.y); } ASSERT && common.assert(false); }; Vec2.add = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(v.x + w.x, v.y + w.y); }; Vec2.wAdd = function(a, v, b, w) { var r = Vec2.zero(); r.wAdd(a, v, b, w); return r; }; Vec2.sub = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(v.x - w.x, v.y - w.y); }; Vec2.mul = function(a, b) { if (typeof a === "object") { ASSERT && Vec2.assert(a); ASSERT && Math.assert(b); return Vec2.neo(a.x * b, a.y * b); } else if (typeof b === "object") { ASSERT && Math.assert(a); ASSERT && Vec2.assert(b); return Vec2.neo(a * b.x, a * b.y); } }; Vec2.prototype.neg = function() { this.x = -this.x; this.y = -this.y; return this; }; Vec2.neg = function(v) { ASSERT && Vec2.assert(v); return Vec2.neo(-v.x, -v.y); }; Vec2.abs = function(v) { ASSERT && Vec2.assert(v); return Vec2.neo(Math.abs(v.x), Math.abs(v.y)); }; Vec2.mid = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo((v.x + w.x) * .5, (v.y + w.y) * .5); }; Vec2.upper = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(Math.max(v.x, w.x), Math.max(v.y, w.y)); }; Vec2.lower = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(Math.min(v.x, w.x), Math.min(v.y, w.y)); }; Vec2.prototype.clamp = function(max) { var lengthSqr = this.x * this.x + this.y * this.y; if (lengthSqr > max * max) { var invLength = Math.invSqrt(lengthSqr); this.x *= invLength * max; this.y *= invLength * max; } return this; }; Vec2.clamp = function(v, max) { v = Vec2.neo(v.x, v.y); v.clamp(max); return v; }; },{"../util/common":51,"./Math":18}],24:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec3; var common = require("../util/common"); var Math = require("./Math"); function Vec3(x, y, z) { if (!(this instanceof Vec3)) { return new Vec3(x, y, z); } if (typeof x === "undefined") { this.x = 0, this.y = 0, this.z = 0; } else if (typeof x === "object") { this.x = x.x, this.y = x.y, this.z = x.z; } else { this.x = x, this.y = y, this.z = z; } ASSERT && Vec3.assert(this); } Vec3.prototype.toString = function() { return JSON.stringify(this); }; Vec3.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y) && Math.isFinite(v.z); }; Vec3.assert = function(o) { if (!ASSERT) return; if (!Vec3.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Vec3!"); } }; Vec3.prototype.setZero = function() { this.x = 0; this.y = 0; this.z = 0; return this; }; Vec3.prototype.set = function(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }; Vec3.prototype.add = function(w) { this.x += w.x; this.y += w.y; this.z += w.z; return this; }; Vec3.prototype.sub = function(w) { this.x -= w.x; this.y -= w.y; this.z -= w.z; return this; }; Vec3.prototype.mul = function(m) { this.x *= m; this.y *= m; this.z *= m; return this; }; Vec3.areEqual = function(v, w) { return v == w || typeof w === "object" && w !== null && v.x == w.x && v.y == w.y && v.z == w.z; }; Vec3.dot = function(v, w) { return v.x * w.x + v.y * w.y + v.z * w.z; }; Vec3.cross = function(v, w) { return new Vec3(v.y * w.z - v.z * w.y, v.z * w.x - v.x * w.z, v.x * w.y - v.y * w.x); }; Vec3.add = function(v, w) { return new Vec3(v.x + w.x, v.y + w.y, v.z + w.z); }; Vec3.sub = function(v, w) { return new Vec3(v.x - w.x, v.y - w.y, v.z - w.z); }; Vec3.mul = function(v, m) { return new Vec3(m * v.x, m * v.y, m * v.z); }; Vec3.prototype.neg = function(m) { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; Vec3.neg = function(v) { return new Vec3(-v.x, -v.y, -v.z); }; },{"../util/common":51,"./Math":18}],25:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Velocity; var Vec2 = require("./Vec2"); function Velocity() { this.v = Vec2.zero(); this.w = 0; } },{"./Vec2":23}],26:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.toString = function(newline) { newline = typeof newline === "string" ? newline : "\n"; var string = ""; for (var name in this) { if (typeof this[name] !== "function" && typeof this[name] !== "object") { string += name + ": " + this[name] + newline; } } return string; }; },{}],27:[function(require,module,exports){ exports.internal = {}; exports.Math = require("./common/Math"); exports.Vec2 = require("./common/Vec2"); exports.Transform = require("./common/Transform"); exports.Rot = require("./common/Rot"); exports.AABB = require("./collision/AABB"); exports.Shape = require("./Shape"); exports.Fixture = require("./Fixture"); exports.Body = require("./Body"); exports.Contact = require("./Contact"); exports.Joint = require("./Joint"); exports.World = require("./World"); exports.Circle = require("./shape/CircleShape"); exports.Edge = require("./shape/EdgeShape"); exports.Polygon = require("./shape/PolygonShape"); exports.Chain = require("./shape/ChainShape"); exports.Box = require("./shape/BoxShape"); require("./shape/CollideCircle"); require("./shape/CollideEdgeCircle"); exports.internal.CollidePolygons = require("./shape/CollidePolygon"); require("./shape/CollideCirclePolygone"); require("./shape/CollideEdgePolygon"); exports.DistanceJoint = require("./joint/DistanceJoint"); exports.FrictionJoint = require("./joint/FrictionJoint"); exports.GearJoint = require("./joint/GearJoint"); exports.MotorJoint = require("./joint/MotorJoint"); exports.MouseJoint = require("./joint/MouseJoint"); exports.PrismaticJoint = require("./joint/PrismaticJoint"); exports.PulleyJoint = require("./joint/PulleyJoint"); exports.RevoluteJoint = require("./joint/RevoluteJoint"); exports.RopeJoint = require("./joint/RopeJoint"); exports.WeldJoint = require("./joint/WeldJoint"); exports.WheelJoint = require("./joint/WheelJoint"); exports.internal.Sweep = require("./common/Sweep"); exports.internal.stats = require("./common/stats"); exports.internal.Manifold = require("./Manifold"); exports.internal.Distance = require("./collision/Distance"); exports.internal.TimeOfImpact = require("./collision/TimeOfImpact"); exports.internal.DynamicTree = require("./collision/DynamicTree"); exports.internal.Settings = require("./Settings"); },{"./Body":2,"./Contact":3,"./Fixture":4,"./Joint":5,"./Manifold":6,"./Settings":7,"./Shape":8,"./World":10,"./collision/AABB":11,"./collision/Distance":13,"./collision/DynamicTree":14,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/stats":26,"./joint/DistanceJoint":28,"./joint/FrictionJoint":29,"./joint/GearJoint":30,"./joint/MotorJoint":31,"./joint/MouseJoint":32,"./joint/PrismaticJoint":33,"./joint/PulleyJoint":34,"./joint/RevoluteJoint":35,"./joint/RopeJoint":36,"./joint/WeldJoint":37,"./joint/WheelJoint":38,"./shape/BoxShape":39,"./shape/ChainShape":40,"./shape/CircleShape":41,"./shape/CollideCircle":42,"./shape/CollideCirclePolygone":43,"./shape/CollideEdgeCircle":44,"./shape/CollideEdgePolygon":45,"./shape/CollidePolygon":46,"./shape/EdgeShape":47,"./shape/PolygonShape":48}],28:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = DistanceJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); DistanceJoint.TYPE = "distance-joint"; DistanceJoint._super = Joint; DistanceJoint.prototype = create(DistanceJoint._super.prototype); var DistanceJointDef = { frequencyHz: 0, dampingRatio: 0 }; function DistanceJoint(def, bodyA, anchorA, bodyB, anchorB) { if (!(this instanceof DistanceJoint)) { return new DistanceJoint(def, bodyA, anchorA, bodyB, anchorB); } def = options(def, DistanceJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = DistanceJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchorA); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchorB); this.m_length = Vec2.distance(anchorB, anchorA); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = 0; this.m_gamma = 0; this.m_bias = 0; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } DistanceJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; DistanceJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; DistanceJoint.prototype.setLength = function(length) { this.m_length = length; }; DistanceJoint.prototype.getLength = function() { return this.m_length; }; DistanceJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; DistanceJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; DistanceJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; DistanceJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; DistanceJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; DistanceJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; DistanceJoint.prototype.getReactionForce = function(inv_dt) { var F = Vec2.mul(inv_dt * this.m_impulse, this.m_u); return F; }; DistanceJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; DistanceJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_u = Vec2.sub(Vec2.add(cB, this.m_rB), Vec2.add(cA, this.m_rA)); var length = this.m_u.length(); if (length > Settings.linearSlop) { this.m_u.mul(1 / length); } else { this.m_u.set(0, 0); } var crAu = Vec2.cross(this.m_rA, this.m_u); var crBu = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crAu * crAu + this.m_invMassB + this.m_invIB * crBu * crBu; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (this.m_frequencyHz > 0) { var C = length - this.m_length; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_mass * this.m_dampingRatio * omega; var k = this.m_mass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invMass += this.m_gamma; this.m_mass = invMass != 0 ? 1 / invMass : 0; } else { this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = Vec2.dot(this.m_u, vpB) - Vec2.dot(this.m_u, vpA); var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse); this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_u); vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solvePositionConstraints = function(step) { if (this.m_frequencyHz > 0) { return true; } var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var length = u.normalize(); var C = length - this.m_length; C = Math.clamp(C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.wSub(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.wAdd(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],29:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = FrictionJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); FrictionJoint.TYPE = "friction-joint"; FrictionJoint._super = Joint; FrictionJoint.prototype = create(FrictionJoint._super.prototype); var FrictionJointDef = { maxForce: 0, maxTorque: 0 }; function FrictionJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof FrictionJoint)) { return new FrictionJoint(def, bodyA, bodyB, anchor); } def = options(def, FrictionJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = FrictionJoint.TYPE; if (anchor) { this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); } else { this.m_localAnchorA = Vec2.zero(); this.m_localAnchorB = Vec2.zero(); } this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } FrictionJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; FrictionJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; FrictionJoint.prototype.setMaxForce = function(force) { ASSERT && common.assert(IsValid(force) && force >= 0); this.m_maxForce = force; }; FrictionJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; FrictionJoint.prototype.setMaxTorque = function(torque) { ASSERT && common.assert(IsValid(torque) && torque >= 0); this.m_maxTorque = torque; }; FrictionJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; FrictionJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; FrictionJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; FrictionJoint.prototype.getReactionForce = function(inv_dt) { return inv_dt * this.m_linearImpulse; }; FrictionJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; FrictionJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; { var Cdot = wB - wA; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, this.m_rB)), Vec2.add(vA, Vec2.cross(wA, this.m_rA))); var impulse = Vec2.neg(Mat22.mul(this.m_linearMass, Cdot)); var oldImpulse = this.m_linearImpulse; this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.lengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.normalize(); this.m_linearImpulse.mul(maxImpulse); } impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],30:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = GearJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var RevoluteJoint = require("./RevoluteJoint"); var PrismaticJoint = require("./PrismaticJoint"); GearJoint.TYPE = "gear-joint"; GearJoint._super = Joint; GearJoint.prototype = create(GearJoint._super.prototype); var GearJointDef = { ratio: 1 }; function GearJoint(def, bodyA, bodyB, joint1, joint2, ratio) { if (!(this instanceof GearJoint)) { return new GearJoint(def, bodyA, bodyB, joint1, joint2, ratio); } def = options(def, GearJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = GearJoint.TYPE; ASSERT && common.assert(joint1.m_type == RevoluteJoint.TYPE || joint1.m_type == PrismaticJoint.TYPE); ASSERT && common.assert(joint2.m_type == RevoluteJoint.TYPE || joint2.m_type == PrismaticJoint.TYPE); this.m_joint1 = joint1; this.m_joint2 = joint2; this.m_type1 = this.m_joint1.getType(); this.m_type2 = this.m_joint2.getType(); var coordinateA, coordinateB; this.m_bodyC = this.m_joint1.getBodyA(); this.m_bodyA = this.m_joint1.getBodyB(); var xfA = this.m_bodyA.m_xf; var aA = this.m_bodyA.m_sweep.a; var xfC = this.m_bodyC.m_xf; var aC = this.m_bodyC.m_sweep.a; if (this.m_type1 == RevoluteJoint.TYPE) { var revolute = joint1; this.m_localAnchorC = revolute.m_localAnchorA; this.m_localAnchorA = revolute.m_localAnchorB; this.m_referenceAngleA = revolute.m_referenceAngle; this.m_localAxisC = Vec2.zero(); coordinateA = aA - aC - this.m_referenceAngleA; } else { var prismatic = joint1; this.m_localAnchorC = prismatic.m_localAnchorA; this.m_localAnchorA = prismatic.m_localAnchorB; this.m_referenceAngleA = prismatic.m_referenceAngle; this.m_localAxisC = prismatic.m_localXAxisA; var pC = this.m_localAnchorC; var pA = Rot.mulT(xfC.q, Vec2.add(Rot.mul(xfA.q, this.m_localAnchorA), Vec2.sub(xfA.p, xfC.p))); coordinateA = Vec2.dot(pA, this.m_localAxisC) - Vec2.dot(pC, this.m_localAxisC); } this.m_bodyD = this.m_joint2.getBodyA(); this.m_bodyB = this.m_joint2.getBodyB(); var xfB = this.m_bodyB.m_xf; var aB = this.m_bodyB.m_sweep.a; var xfD = this.m_bodyD.m_xf; var aD = this.m_bodyD.m_sweep.a; if (this.m_type2 == RevoluteJoint.TYPE) { var revolute = joint2; this.m_localAnchorD = revolute.m_localAnchorA; this.m_localAnchorB = revolute.m_localAnchorB; this.m_referenceAngleB = revolute.m_referenceAngle; this.m_localAxisD = Vec2.zero(); coordinateB = aB - aD - this.m_referenceAngleB; } else { var prismatic = joint2; this.m_localAnchorD = prismatic.m_localAnchorA; this.m_localAnchorB = prismatic.m_localAnchorB; this.m_referenceAngleB = prismatic.m_referenceAngle; this.m_localAxisD = prismatic.m_localXAxisA; var pD = this.m_localAnchorD; var pB = Rot.mulT(xfD.q, Vec2.add(Rot.mul(xfB.q, this.m_localAnchorB), Vec2.sub(xfB.p, xfD.p))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } this.m_ratio = ratio || def.ratio; this.m_constant = coordinateA + this.m_ratio * coordinateB; this.m_impulse = 0; this.m_lcA, this.m_lcB, this.m_lcC, this.m_lcD; this.m_mA, this.m_mB, this.m_mC, this.m_mD; this.m_iA, this.m_iB, this.m_iC, this.m_iD; this.m_JvAC, this.m_JvBD; this.m_JwA, this.m_JwB, this.m_JwC, this.m_JwD; this.m_mass; } GearJoint.prototype.getJoint1 = function() { return this.m_joint1; }; GearJoint.prototype.getJoint2 = function() { return this.m_joint2; }; GearJoint.prototype.setRatio = function(ratio) { ASSERT && common.assert(IsValid(ratio)); this.m_ratio = ratio; }; GearJoint.prototype.setRatio = function() { return this.m_ratio; }; GearJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; GearJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; GearJoint.prototype.getReactionForce = function(inv_dt) { var P = this.m_impulse * this.m_JvAC; return inv_dt * P; }; GearJoint.prototype.getReactionTorque = function(inv_dt) { var L = this.m_impulse * this.m_JwA; return inv_dt * L; }; GearJoint.prototype.initVelocityConstraints = function(step) { this.m_lcA = this.m_bodyA.m_sweep.localCenter; this.m_lcB = this.m_bodyB.m_sweep.localCenter; this.m_lcC = this.m_bodyC.m_sweep.localCenter; this.m_lcD = this.m_bodyD.m_sweep.localCenter; this.m_mA = this.m_bodyA.m_invMass; this.m_mB = this.m_bodyB.m_invMass; this.m_mC = this.m_bodyC.m_invMass; this.m_mD = this.m_bodyD.m_invMass; this.m_iA = this.m_bodyA.m_invI; this.m_iB = this.m_bodyB.m_invI; this.m_iC = this.m_bodyC.m_invI; this.m_iD = this.m_bodyD.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var aC = this.m_bodyC.c_position.a; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var aD = this.m_bodyD.c_position.a; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); this.m_mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { this.m_JvAC = Vec2.zero(); this.m_JwA = 1; this.m_JwC = 1; this.m_mass += this.m_iA + this.m_iC; } else { var u = Rot.mul(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); this.m_JvAC = u; this.m_JwC = Vec2.cross(rC, u); this.m_JwA = Vec2.cross(rA, u); this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA; } if (this.m_type2 == RevoluteJoint.TYPE) { this.m_JvBD = Vec2.zero(); this.m_JwB = this.m_ratio; this.m_JwD = this.m_ratio; this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); } else { var u = Rot.mul(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); this.m_JvBD = Vec2.mul(this.m_ratio, u); this.m_JwD = this.m_ratio * Vec2.cross(rD, u); this.m_JwB = this.m_ratio * Vec2.cross(rB, u); this.m_mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * this.m_JwD * this.m_JwD + this.m_iB * this.m_JwB * this.m_JwB; } this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0; if (step.warmStarting) { vA.wAdd(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; vB.wAdd(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; vC.wSub(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; vD.wSub(this.m_mD * this.m_impulse, this.m_JvBD); wD -= this.m_iD * this.m_impulse * this.m_JwD; } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var Cdot = Vec2.dot(this.m_JvAC, vA) - Vec2.dot(this.m_JvAC, vC) + Vec2.dot(this.m_JvBD, vB) - Vec2.dot(this.m_JvBD, vD); Cdot += this.m_JwA * wA - this.m_JwC * wC + (this.m_JwB * wB - this.m_JwD * wD); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; vA.wAdd(this.m_mA * impulse, this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; vB.wAdd(this.m_mB * impulse, this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; vC.wSub(this.m_mC * impulse, this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; vD.wSub(this.m_mD * impulse, this.m_JvBD); wD -= this.m_iD * impulse * this.m_JwD; this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var cC = this.m_bodyC.c_position.c; var aC = this.m_bodyC.c_position.a; var cD = this.m_bodyD.c_position.c; var aD = this.m_bodyD.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); var linearError = 0; var coordinateA, coordinateB; var JvAC, JvBD; var JwA, JwB, JwC, JwD; var mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { JvAC = Vec2.zero(); JwA = 1; JwC = 1; mass += this.m_iA + this.m_iC; coordinateA = aA - aC - this.m_referenceAngleA; } else { var u = Rot.mul(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); JvAC = u; JwC = Vec2.cross(rC, u); JwA = Vec2.cross(rA, u); mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA; var pC = this.m_localAnchorC - this.m_lcC; var pA = Rot.mulT(qC, Vec2.add(rA, Vec2.sub(cA, cC))); coordinateA = Dot(pA - pC, this.m_localAxisC); } if (this.m_type2 == RevoluteJoint.TYPE) { JvBD = Vec2.zero(); JwB = this.m_ratio; JwD = this.m_ratio; mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); coordinateB = aB - aD - this.m_referenceAngleB; } else { var u = Rot.mul(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); JvBD = Vec2.mul(this.m_ratio, u); JwD = this.m_ratio * Vec2.cross(rD, u); JwB = this.m_ratio * Vec2.cross(rB, u); mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB; var pD = Vec2.sub(this.m_localAnchorD, this.m_lcD); var pB = Rot.mulT(qD, Vec2.add(rB, Vec2.sub(cB, cD))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } var C = coordinateA + this.m_ratio * coordinateB - this.m_constant; var impulse = 0; if (mass > 0) { impulse = -C / mass; } cA.wAdd(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; cB.wAdd(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; cC.wAdd(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; cD.wAdd(this.m_mD * impulse, JvBD); aD -= this.m_iD * impulse * JwD; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; this.m_bodyC.c_position.c.set(cC); this.m_bodyC.c_position.a = aC; this.m_bodyD.c_position.c.set(cD); this.m_bodyD.c_position.a = aD; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53,"./PrismaticJoint":33,"./RevoluteJoint":35}],31:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MotorJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MotorJoint.TYPE = "motor-joint"; MotorJoint._super = Joint; MotorJoint.prototype = create(MotorJoint._super.prototype); var MotorJointDef = { maxForce: 1, maxTorque: 1, correctionFactor: .3 }; function MotorJoint(def, bodyA, bodyB) { if (!(this instanceof MotorJoint)) { return new MotorJoint(def, bodyA, bodyB); } def = options(def, MotorJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = MotorJoint.TYPE; var xB = bodyB.getPosition(); this.m_linearOffset = bodyA.getLocalPoint(xB); var angleA = bodyA.getAngle(); var angleB = bodyB.getAngle(); this.m_angularOffset = angleB - angleA; this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_correctionFactor = def.correctionFactor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_linearError; this.m_angularError; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } MotorJoint.prototype.setMaxForce = function(force) { ASSERT && common.assert(IsValid(force) && force >= 0); this.m_maxForce = force; }; MotorJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; MotorJoint.prototype.setMaxTorque = function(torque) { ASSERT && common.assert(IsValid(torque) && torque >= 0); this.m_maxTorque = torque; }; MotorJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; MotorJoint.prototype.setCorrectionFactor = function(factor) { ASSERT && common.assert(IsValid(factor) && 0 <= factor && factor <= 1); this.m_correctionFactor = factor; }; MotorJoint.prototype.getCorrectionFactor = function() { return this.m_correctionFactor; }; MotorJoint.prototype.setLinearOffset = function(linearOffset) { if (linearOffset.x != this.m_linearOffset.x || linearOffset.y != this.m_linearOffset.y) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_linearOffset = linearOffset; } }; MotorJoint.prototype.getLinearOffset = function() { return this.m_linearOffset; }; MotorJoint.prototype.setAngularOffset = function(angularOffset) { if (angularOffset != this.m_angularOffset) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_angularOffset = angularOffset; } }; MotorJoint.prototype.getAngularOffset = function() { return this.m_angularOffset; }; MotorJoint.prototype.getAnchorA = function() { return this.m_bodyA.getPosition(); }; MotorJoint.prototype.getAnchorB = function() { return this.m_bodyB.getPosition(); }; MotorJoint.prototype.getReactionForce = function(inv_dt) { return inv_dt * this.m_linearImpulse; }; MotorJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; MotorJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.neg(this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.neg(this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } this.m_linearError = Vec2.zero(); this.m_linearError.wAdd(1, cB, 1, this.m_rB); this.m_linearError.wSub(1, cA, 1, this.m_rA); this.m_linearError.sub(Rot.mul(qA, this.m_linearOffset)); this.m_angularError = aB - aA - this.m_angularOffset; if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; var inv_h = step.inv_dt; { var Cdot = wB - wA + inv_h * this.m_correctionFactor * this.m_angularError; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.zero(); Cdot.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); Cdot.wAdd(inv_h * this.m_correctionFactor, this.m_linearError); var impulse = Vec2.neg(Mat22.mul(this.m_linearMass, Cdot)); var oldImpulse = Vec2.clone(this.m_linearImpulse); this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; this.m_linearImpulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],32:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MouseJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MouseJoint.TYPE = "mouse-joint"; MouseJoint._super = Joint; MouseJoint.prototype = create(MouseJoint._super.prototype); var MouseJointDef = { maxForce: 0, frequencyHz: 5, dampingRatio: .7 }; function MouseJoint(def, bodyA, bodyB, target) { if (!(this instanceof MouseJoint)) { return new MouseJoint(def, bodyA, bodyB, target); } def = options(def, MouseJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = MouseJoint.TYPE; ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0); ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0); ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0); this.m_targetA = Vec2.clone(target); this.m_localAnchorB = Transform.mulT(this.m_bodyB.getTransform(), this.m_targetA); this.m_maxForce = def.maxForce; this.m_impulse = Vec2.zero(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_beta = 0; this.m_gamma = 0; this.m_rB = Vec2.zero(); this.m_localCenterB = Vec2.zero(); this.m_invMassB = 0; this.m_invIB = 0; this.mass = new Mat22(); this.m_C = Vec2.zero(); } MouseJoint.prototype.setTarget = function(target) { if (this.m_bodyB.isAwake() == false) { this.m_bodyB.setAwake(true); } this.m_targetA = Vec2.clone(target); }; MouseJoint.prototype.getTarget = function() { return this.m_targetA; }; MouseJoint.prototype.setMaxForce = function(force) { this.m_maxForce = force; }; MouseJoint.getMaxForce = function() { return this.m_maxForce; }; MouseJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; MouseJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; MouseJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; MouseJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; MouseJoint.prototype.getAnchorA = function() { return Vec2.clone(this.m_targetA); }; MouseJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; MouseJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_impulse); }; MouseJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * 0; }; MouseJoint.prototype.shiftOrigin = function(newOrigin) { this.m_targetA.sub(newOrigin); }; MouseJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIB = this.m_bodyB.m_invI; var position = this.m_bodyB.c_position; var velocity = this.m_bodyB.c_velocity; var cB = position.c; var aB = position.a; var vB = velocity.v; var wB = velocity.w; var qB = Rot.neo(aB); var mass = this.m_bodyB.getMass(); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * mass * this.m_dampingRatio * omega; var k = mass * (omega * omega); var h = step.dt; ASSERT && common.assert(d + h * k > Math.EPSILON); this.m_gamma = h * (d + h * k); if (this.m_gamma != 0) { this.m_gamma = 1 / this.m_gamma; } this.m_beta = h * k * this.m_gamma; this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var K = new Mat22(); K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma; K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma; this.m_mass = K.getInverse(); this.m_C.set(cB); this.m_C.wAdd(1, this.m_rB, -1, this.m_targetA); this.m_C.mul(this.m_beta); wB *= .98; if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); vB.wAdd(this.m_invMassB, this.m_impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, this.m_impulse); } else { this.m_impulse.setZero(); } velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solveVelocityConstraints = function(step) { var velocity = this.m_bodyB.c_velocity; var vB = Vec2.clone(velocity.v); var wB = velocity.w; var Cdot = Vec2.cross(wB, this.m_rB); Cdot.add(vB); Cdot.wAdd(1, this.m_C, this.m_gamma, this.m_impulse); Cdot.neg(); var impulse = Mat22.mul(this.m_mass, Cdot); var oldImpulse = Vec2.clone(this.m_impulse); this.m_impulse.add(impulse); var maxImpulse = step.dt * this.m_maxForce; this.m_impulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_impulse, oldImpulse); vB.wAdd(this.m_invMassB, impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, impulse); velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],33:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PrismaticJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; PrismaticJoint.TYPE = "prismatic-joint"; PrismaticJoint._super = Joint; PrismaticJoint.prototype = create(PrismaticJoint._super.prototype); var PrismaticJointDef = { enableLimit: false, lowerTranslation: 0, upperTranslation: 0, enableMotor: false, maxMotorForce: 0, motorSpeed: 0 }; function PrismaticJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof PrismaticJoint)) { return new PrismaticJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, PrismaticJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = PrismaticJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_localXAxisA = def.localAxisA || bodyA.getLocalVector(axis); this.m_localXAxisA.normalize(); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_lowerTranslation = def.lowerTranslation; this.m_upperTranslation = def.upperTranslation; this.m_maxMotorForce = def.maxMotorForce; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_limitState = inactiveLimit; this.m_axis = Vec2.zero(); this.m_perp = Vec2.zero(); this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_axis, this.m_perp; this.m_s1, this.m_s2; this.m_a1, this.m_a2; this.m_K = new Mat33(); this.m_motorMass; } PrismaticJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; PrismaticJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; PrismaticJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; PrismaticJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; PrismaticJoint.prototype.getJointTranslation = function() { var pA = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var pB = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var d = Vec2.sub(pB, pA); var axis = this.m_bodyA.getWorldVector(this.m_localXAxisA); var translation = Vec2.dot(d, axis); return translation; }; PrismaticJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var rA = Mul(bA.m_xf.q, this.m_localAnchorA - bA.m_sweep.localCenter); var rB = Mul(bB.m_xf.q, this.m_localAnchorB - bB.m_sweep.localCenter); var p1 = bA.m_sweep.c + rA; var p2 = bB.m_sweep.c + rB; var d = p2 - p1; var axis = Mul(bA.m_xf.q, this.m_localXAxisA); var vA = bA.m_linearVelocity; var vB = bB.m_linearVelocity; var wA = bA.m_angularVelocity; var wB = bB.m_angularVelocity; var speed = Dot(d, Cross(wA, axis)) + Dot(axis, vB + Cross(wB, rB) - vA - Cross(wA, rA)); return speed; }; PrismaticJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; PrismaticJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.getLowerLimit = function() { return this.m_lowerTranslation; }; PrismaticJoint.prototype.getUpperLimit = function() { return this.m_upperTranslation; }; PrismaticJoint.prototype.setLimits = function(lower, upper) { ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerTranslation || upper != this.m_upperTranslation) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_lowerTranslation = lower; this.m_upperTranslation = upper; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; PrismaticJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; PrismaticJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; PrismaticJoint.prototype.setMaxMotorForce = function(force) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorForce = force; }; PrismaticJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; PrismaticJoint.prototype.getMotorForce = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; PrismaticJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PrismaticJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PrismaticJoint.prototype.getReactionForce = function(inv_dt) { return inv_dt * (this.m_impulse.x * this.m_perp + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis); }; PrismaticJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.y; }; PrismaticJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(1, cA, 1, rA); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; { this.m_axis = Rot.mul(qA, this.m_localXAxisA); this.m_a1 = Vec2.cross(Vec2.add(d, rA), this.m_axis); this.m_a2 = Vec2.cross(rB, this.m_axis); this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } { this.m_perp = Rot.mul(qA, this.m_localYAxisA); this.m_s1 = Vec2.cross(Vec2.add(d, rA), this.m_perp); this.m_s2 = Vec2.cross(rB, this.m_perp); var s1test = Vec2.cross(rA, this.m_perp); var k11 = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2; var k12 = iA * this.m_s1 + iB * this.m_s2; var k13 = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * this.m_a1 + iB * this.m_a2; var k33 = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; this.m_K.ex.set(k11, k12, k13); this.m_K.ey.set(k12, k22, k23); this.m_K.ez.set(k13, k23, k33); } if (this.m_enableLimit) { var jointTranslation = Vec2.dot(this.m_axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * Settings.linearSlop) { this.m_limitState = equalLimits; } else if (jointTranslation <= this.m_lowerTranslation) { if (this.m_limitState != atLowerLimit) { this.m_limitState = atLowerLimit; this.m_impulse.z = 0; } } else if (jointTranslation >= this.m_upperTranslation) { if (this.m_limitState != atUpperLimit) { this.m_limitState = atUpperLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } if (this.m_enableMotor == false) { this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.wAdd(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis); var LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1; var LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_enableMotor && this.m_limitState != equalLimits) { var Cdot = Vec2.dot(this.m_axis, Vec2.sub(vB, vA)) + this.m_a2 * wB - this.m_a1 * wA; var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot); var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorForce; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; var P = Vec2.zero().wSet(impulse, this.m_axis); var LA = impulse * this.m_a1; var LB = impulse * this.m_a2; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } var Cdot1 = Vec2.zero(); Cdot1.x += Vec2.dot(this.m_perp, vB) + this.m_s2 * wB; Cdot1.x -= Vec2.dot(this.m_perp, vA) + this.m_s1 * wA; Cdot1.y = wB - wA; if (this.m_enableLimit && this.m_limitState != inactiveLimit) { var Cdot2 = 0; Cdot2 += Vec2.dot(this.m_axis, vB) + this.m_a2 * wB; Cdot2 -= Vec2.dot(this.m_axis, vA) + this.m_a1 * wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var f1 = Vec3(this.m_impulse); var df = this.m_K.solve33(Vec3.neg(Cdot)); this.m_impulse.add(df); if (this.m_limitState == atLowerLimit) { this.m_impulse.z = Math.max(this.m_impulse.z, 0); } else if (this.m_limitState == atUpperLimit) { this.m_impulse.z = Math.min(this.m_impulse.z, 0); } var b = Vec2.wAdd(-1, Cdot1, -(this.m_impulse.z - f1.z), Vec2.neo(this.m_K.ez.x, this.m_K.ez.y)); var f2r = Vec2.add(this.m_K.solve22(b), Vec2.neo(f1.x, f1.y)); this.m_impulse.x = f2r.x; this.m_impulse.y = f2r.y; df = Vec3.sub(this.m_impulse, f1); var P = Vec2.wAdd(df.x, this.m_perp, df.z, this.m_axis); var LA = df.x * this.m_s1 + df.y + df.z * this.m_a1; var LB = df.x * this.m_s2 + df.y + df.z * this.m_a2; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } else { var df = this.m_K.solve22(Vec2.neg(Cdot1)); this.m_impulse.x += df.x; this.m_impulse.y += df.y; var P = Vec2.zero().wAdd(df.x, this.m_perp); var LA = df.x * this.m_s1 + df.y; var LB = df.x * this.m_s2 + df.y; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var axis = Rot.mul(qA, this.m_localXAxisA); var a1 = Vec2.cross(Vec2.add(d, rA), axis); var a2 = Vec2.cross(rB, axis); var perp = Rot.mul(qA, this.m_localYAxisA); var s1 = Vec2.cross(Vec2.add(d, rA), perp); var s2 = Vec2.cross(rB, perp); var impulse = Vec3(); var C1 = Vec2.zero(); C1.x = Vec2.dot(perp, d); C1.y = aB - aA - this.m_referenceAngle; var linearError = Math.abs(C1.x); var angularError = Math.abs(C1.y); var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var active = false; var C2 = 0; if (this.m_enableLimit) { var translation = Vec2.dot(axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * linearSlop) { C2 = Math.clamp(translation, -maxLinearCorrection, maxLinearCorrection); linearError = Math.max(linearError, Math.abs(translation)); active = true; } else if (translation <= this.m_lowerTranslation) { C2 = Math.clamp(translation - this.m_lowerTranslation + linearSlop, -maxLinearCorrection, 0); linearError = Math.max(linearError, this.m_lowerTranslation - translation); active = true; } else if (translation >= this.m_upperTranslation) { C2 = Math.clamp(translation - this.m_upperTranslation - linearSlop, 0, maxLinearCorrection); linearError = Math.max(linearError, translation - this.m_upperTranslation); active = true; } } if (active) { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k13 = iA * s1 * a1 + iB * s2 * a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * a1 + iB * a2; var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; var K = new Mat33(); K.ex.set(k11, k12, k13); K.ey.set(k12, k22, k23); K.ez.set(k13, k23, k33); var C = Vec3(); C.x = C1.x; C.y = C1.y; C.z = C2; impulse = K.solve33(Vec3.neg(C)); } else { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var K = new Mat22(); K.ex.set(k11, k12); K.ey.set(k12, k22); var impulse1 = K.solve(Vec2.neg(C1)); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; } var P = Vec2.wAdd(impulse.x, perp, impulse.z, axis); var LA = impulse.x * s1 + impulse.y + impulse.z * a1; var LB = impulse.x * s2 + impulse.y + impulse.z * a2; cA.wSub(mA, P); aA -= iA * LA; cB.wAdd(mB, P); aB += iB * LB; this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],34:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PulleyJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); PulleyJoint.TYPE = "pulley-joint"; PulleyJoint.MIN_PULLEY_LENGTH = 2; PulleyJoint._super = Joint; PulleyJoint.prototype = create(PulleyJoint._super.prototype); var PulleyJointDef = { collideConnected: true }; function PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio) { if (!(this instanceof PulleyJoint)) { return new PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio); } def = options(def, PulleyJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = PulleyJoint.TYPE; this.m_groundAnchorA = groundA; this.m_groundAnchorB = groundB; this.m_localAnchorA = bodyA.getLocalPoint(anchorA); this.m_localAnchorB = bodyB.getLocalPoint(anchorB); this.m_lengthA = Vec2.distance(anchorA, groundA); this.m_lengthB = Vec2.distance(anchorB, groundB); this.m_ratio = def.ratio || ratio; ASSERT && common.assert(ratio > Math.EPSILON); this.m_constant = this.m_lengthA + this.m_ratio * this.m_lengthB; this.m_impulse = 0; this.m_uA; this.m_uB; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } PulleyJoint.prototype.getGroundAnchorA = function() { return this.m_groundAnchorA; }; PulleyJoint.prototype.getGroundAnchorB = function() { return this.m_groundAnchorB; }; PulleyJoint.prototype.getLengthA = function() { return this.m_lengthA; }; PulleyJoint.prototype.getLengthB = function() { return this.m_lengthB; }; PulleyJoint.prototype.setRatio = function() { return this.m_ratio; }; PulleyJoint.prototype.getCurrentLengthA = function() { var p = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var s = this.m_groundAnchorA; return Vec2.distance(p, s); }; PulleyJoint.prototype.getCurrentLengthB = function() { var p = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var s = this.m_groundAnchorB; return Vec2.distance(p, s); }; PulleyJoint.prototype.shiftOrigin = function(newOrigin) { this.m_groundAnchorA -= newOrigin; this.m_groundAnchorB -= newOrigin; }; PulleyJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PulleyJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PulleyJoint.prototype.getReactionForce = function(inv_dt) { return Vec3.mul(inv_dt * this.m_impulse, this.m_uB); }; PulleyJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; PulleyJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); this.m_uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = this.m_uA.length(); var lengthB = this.m_uB.length(); if (lengthA > 10 * Settings.linearSlop) { this.m_uA.mul(1 / lengthA); } else { this.m_uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { this.m_uB.mul(1 / lengthB); } else { this.m_uB.setZero(); } var ruA = Vec2.cross(this.m_rA, this.m_uA); var ruB = Vec2.cross(this.m_rB, this.m_uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; this.m_mass = mA + this.m_ratio * this.m_ratio * mB; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var PA = Vec2.mul(-this.m_impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * this.m_impulse, this.m_uB); vA.wAdd(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.wAdd(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = -Vec2.dot(this.m_uA, vpA) - this.m_ratio * Vec2.dot(this.m_uB, vpB); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var PA = Vec2.zero().wSet(-impulse, this.m_uA); var PB = Vec2.zero().wSet(-this.m_ratio * impulse, this.m_uB); vA.wAdd(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.wAdd(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); var uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = uA.length(); var lengthB = uB.length(); if (lengthA > 10 * Settings.linearSlop) { uA.mul(1 / lengthA); } else { uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { uB.mul(1 / lengthB); } else { uB.setZero(); } var ruA = Vec2.cross(rA, uA); var ruB = Vec2.cross(rB, uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; var mass = mA + this.m_ratio * this.m_ratio * mB; if (mass > 0) { mass = 1 / mass; } var C = this.m_constant - lengthA - this.m_ratio * lengthB; var linearError = Math.abs(C); var impulse = -mass * C; var PA = Vec2.zero().wSet(-impulse, uA); var PB = Vec2.zero().wSet(-this.m_ratio * impulse, uB); cA.wAdd(this.m_invMassA, PA); aA += this.m_invIA * Vec2.cross(rA, PA); cB.wAdd(this.m_invMassB, PB); aB += this.m_invIB * Vec2.cross(rB, PB); this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],35:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RevoluteJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RevoluteJoint.TYPE = "revolute-joint"; RevoluteJoint._super = Joint; RevoluteJoint.prototype = create(RevoluteJoint._super.prototype); var RevoluteJointDef = { lowerAngle: 0, upperAngle: 0, maxMotorTorque: 0, motorSpeed: 0, enableLimit: false, enableMotor: false }; function RevoluteJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RevoluteJoint)) { return new RevoluteJoint(def, bodyA, bodyB, anchor); } def = options(def, RevoluteJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = RevoluteJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorImpulse = 0; this.m_lowerAngle = def.lowerAngle; this.m_upperAngle = def.upperAngle; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); this.m_motorMass; this.m_limitState = inactiveLimit; } RevoluteJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RevoluteJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RevoluteJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; RevoluteJoint.prototype.getJointAngle = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle; }; RevoluteJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_angularVelocity - bA.m_angularVelocity; }; RevoluteJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; RevoluteJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; RevoluteJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; RevoluteJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; RevoluteJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; RevoluteJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; RevoluteJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; RevoluteJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; RevoluteJoint.prototype.getLowerLimit = function() { return this.m_lowerAngle; }; RevoluteJoint.prototype.getUpperLimit = function() { return this.m_upperAngle; }; RevoluteJoint.prototype.setLimits = function(lower, upper) { ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerAngle || upper != this.m_upperAngle) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_impulse.z = 0; this.m_lowerAngle = lower; this.m_upperAngle = upper; } }; RevoluteJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RevoluteJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RevoluteJoint.prototype.getReactionForce = function(inv_dt) { var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); return inv_dt * P; }; RevoluteJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; RevoluteJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB == 0; this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; this.m_mass.ex.y = this.m_mass.ey.x; this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; this.m_mass.ex.z = this.m_mass.ez.x; this.m_mass.ey.z = this.m_mass.ez.y; this.m_mass.ez.z = iA + iB; this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } if (this.m_enableMotor == false || fixedRotation) { this.m_motorImpulse = 0; } if (this.m_enableLimit && fixedRotation == false) { var jointAngle = aB - aA - this.m_referenceAngle; if (Math.abs(this.m_upperAngle - this.m_lowerAngle) < 2 * Settings.angularSlop) { this.m_limitState = equalLimits; } else if (jointAngle <= this.m_lowerAngle) { if (this.m_limitState != atLowerLimit) { this.m_impulse.z = 0; } this.m_limitState = atLowerLimit; } else if (jointAngle >= this.m_upperAngle) { if (this.m_limitState != atUpperLimit) { this.m_impulse.z = 0; } this.m_limitState = atUpperLimit; } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z); } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB == 0; if (this.m_enableMotor && this.m_limitState != equalLimits && fixedRotation == false) { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var Cdot1 = Vec2.zero(); Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(this.m_mass.solve33(Cdot)); if (this.m_limitState == equalLimits) { this.m_impulse.add(impulse); } else if (this.m_limitState == atLowerLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse < 0) { var rhs = Vec2.wAdd(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } else if (this.m_limitState == atUpperLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse > 0) { var rhs = Vec2.wAdd(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } var P = Vec2.neo(impulse.x, impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } else { var Cdot = Vec2.zero(); Cdot.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse = this.m_mass.solve22(Vec2.neg(Cdot)); this.m_impulse.x += impulse.x; this.m_impulse.y += impulse.y; vA.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var angularError = 0; var positionError = 0; var fixedRotation = this.m_invIA + this.m_invIB == 0; if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var angle = aB - aA - this.m_referenceAngle; var limitImpulse = 0; if (this.m_limitState == equalLimits) { var C = Math.clamp(angle - this.m_lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; angularError = Math.abs(C); } else if (this.m_limitState == atLowerLimit) { var C = angle - this.m_lowerAngle; angularError = -C; C = Math.clamp(C + Settings.angularSlop, -Settings.maxAngularCorrection, 0); limitImpulse = -this.m_motorMass * C; } else if (this.m_limitState == atUpperLimit) { var C = angle - this.m_upperAngle; angularError = C; C = Math.clamp(C - Settings.angularSlop, 0, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; } aA -= this.m_invIA * limitImpulse; aB += this.m_invIB * limitImpulse; } { qA.set(aA); qB.set(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var C = Vec2.zero(); C.wAdd(1, cB, 1, rB); C.wSub(1, cA, 1, rA); positionError = C.length(); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; var impulse = Vec2.neg(K.solve(C)); cA.wSub(mA, impulse); aA -= iA * Vec2.cross(rA, impulse); cB.wAdd(mB, impulse); aB += iB * Vec2.cross(rB, impulse); } this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],36:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RopeJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RopeJoint.TYPE = "rope-joint"; RopeJoint._super = Joint; RopeJoint.prototype = create(RopeJoint._super.prototype); var RopeJointDef = { maxLength: 0 }; function RopeJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RopeJoint)) { return new RopeJoint(def, bodyA, bodyB, anchor); } def = options(def, RopeJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = RopeJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_maxLength = def.maxLength; this.m_mass = 0; this.m_impulse = 0; this.m_length = 0; this.m_state = inactiveLimit; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } RopeJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RopeJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RopeJoint.prototype.setMaxLength = function(length) { this.m_maxLength = length; }; RopeJoint.prototype.getMaxLength = function() { return this.m_maxLength; }; RopeJoint.prototype.getLimitState = function() { return this.m_state; }; RopeJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RopeJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RopeJoint.prototype.getReactionForce = function(inv_dt) { var F = inv_dt * this.m_impulse * this.m_u; return F; }; RopeJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; RopeJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); this.m_rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); this.m_u = Vec2.zero(); this.m_u.wAdd(1, cB, 1, this.m_rB); this.m_u.wSub(1, cA, 1, this.m_rA); this.m_length = this.m_u.length(); var C = this.m_length - this.m_maxLength; if (C > 0) { this.m_state = atUpperLimit; } else { this.m_state = inactiveLimit; } if (this.m_length > Settings.linearSlop) { this.m_u.mul(1 / this.m_length); } else { this.m_u.setZero(); this.m_mass = 0; this.m_impulse = 0; return; } var crA = Vec2.cross(this.m_rA, this.m_u); var crB = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.addCross(vA, wA, this.m_rA); var vpB = Vec2.addCross(vB, wB, this.m_rB); var C = this.m_length - this.m_maxLength; var Cdot = Vec2.dot(this.m_u, Vec2.sub(vpB, vpA)); if (C < 0) { Cdot += step.inv_dt * C; } var impulse = -this.m_mass * Cdot; var oldImpulse = this.m_impulse; this.m_impulse = Math.min(0, this.m_impulse + impulse); impulse = this.m_impulse - oldImpulse; var P = Vec2.mul(impulse, this.m_u); vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.zero(); u.wAdd(1, cB, 1, rB); u.wSub(1, cA, 1, rA); var length = u.normalize(); var C = length - this.m_maxLength; C = Math.clamp(C, 0, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.wSub(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.wAdd(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return length - this.m_maxLength < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],37:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WeldJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WeldJoint.TYPE = "weld-joint"; WeldJoint._super = Joint; WeldJoint.prototype = create(WeldJoint._super.prototype); var WeldJointDef = { frequencyHz: 0, dampingRatio: 0 }; function WeldJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof WeldJoint)) { return new WeldJoint(def, bodyA, bodyB, anchor); } def = options(def, WeldJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = WeldJoint.TYPE; this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = Vec3(); this.m_bias = 0; this.m_gamma = 0; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); } WeldJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WeldJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WeldJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; WeldJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; WeldJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; WeldJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WeldJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; WeldJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WeldJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WeldJoint.prototype.getReactionForce = function(inv_dt) { var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); return inv_dt * P; }; WeldJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; WeldJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat33(); K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { K.getInverse22(this.m_mass); var invM = iA + iB; var m = invM > 0 ? 1 / invM : 0; var C = aB - aA - this.m_referenceAngle; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * m * this.m_dampingRatio * omega; var k = m * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invM += this.m_gamma; this.m_mass.ez.z = invM != 0 ? 1 / invM : 0; } else if (K.ez.z == 0) { K.getInverse22(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } else { K.getSymInverse33(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_impulse.z); } else { this.m_impulse.setZero(); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_frequencyHz > 0) { var Cdot2 = wB - wA; var impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; var Cdot1 = Vec2.zero(); Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse1 = Vec2.neg(Mat33.mul(this.m_mass, Cdot1)); this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; var P = Vec2.clone(impulse1); vA.wSub(mA, P); wA -= iA * Vec2.cross(this.m_rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(this.m_rB, P); } else { var Cdot1 = Vec2.zero(); Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(Mat33.mul(this.m_mass, Cdot)); this.m_impulse.add(impulse); var P = Vec2.neo(impulse.x, impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var positionError, angularError; var K = new Mat33(); K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { var C1 = Vec2.zero(); C1.wAdd(1, cB, 1, rB); C1.wSub(1, cA, 1, rA); positionError = C1.length(); angularError = 0; var P = Vec2.neg(K.solve22(C1)); cA.wSub(mA, P); aA -= iA * Vec2.cross(rA, P); cB.wAdd(mB, P); aB += iB * Vec2.cross(rB, P); } else { var C1 = Vec2.zero(); C1.wAdd(1, cB, 1, rB); C1.wSub(1, cA, 1, rA); var C2 = aB - aA - this.m_referenceAngle; positionError = C1.length(); angularError = Math.abs(C2); var C = Vec3(C1.x, C1.y, C2); var impulse = Vec3(); if (K.ez.z > 0) { impulse = Vec3.neg(K.solve33(C)); } else { var impulse2 = Vec2.neg(K.solve22(C1)); impulse.set(impulse2.x, impulse2.y, 0); } var P = Vec2.neo(impulse.x, impulse.y); cA.wSub(mA, P); aA -= iA * (Vec2.cross(rA, P) + impulse.z); cB.wAdd(mB, P); aB += iB * (Vec2.cross(rB, P) + impulse.z); } this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],38:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WheelJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WheelJoint.TYPE = "wheel-joint"; WheelJoint._super = Joint; WheelJoint.prototype = create(WheelJoint._super.prototype); var WheelJointDef = { enableMotor: false, maxMotorTorque: 0, motorSpeed: 0, frequencyHz: 2, dampingRatio: .7 }; function WheelJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof WheelJoint)) { return new WheelJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, WheelJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = WheelJoint.TYPE; this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); this.m_localXAxisA = bodyA.getLocalVector(axis || Vec2.neo(1, 0)); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_mass = 0; this.m_impulse = 0; this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_springMass = 0; this.m_springImpulse = 0; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableMotor = def.enableMotor; this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_bias = 0; this.m_gamma = 0; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_ax = Vec2.zero(); this.m_ay = Vec2.zero(); this.m_sAx; this.m_sBx; this.m_sAy; this.m_sBy; } WheelJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WheelJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WheelJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; WheelJoint.prototype.getJointTranslation = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var pA = bA.getWorldPoint(this.m_localAnchorA); var pB = bB.getWorldPoint(this.m_localAnchorB); var d = pB - pA; var axis = bA.getWorldVector(this.m_localXAxisA); var translation = Dot(d, axis); return translation; }; WheelJoint.prototype.getJointSpeed = function() { var wA = this.m_bodyA.m_angularVelocity; var wB = this.m_bodyB.m_angularVelocity; return wB - wA; }; WheelJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; WheelJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; WheelJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; WheelJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; WheelJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; WheelJoint.prototype.getMaxMotorTorque = function() { return this.m_maxMotorTorque; }; WheelJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.setSpringFrequencyHz = function(hz) { this.m_frequencyHz = hz; }; WheelJoint.prototype.getSpringFrequencyHz = function() { return this.m_frequencyHz; }; WheelJoint.prototype.setSpringDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WheelJoint.prototype.getSpringDampingRatio = function() { return this.m_dampingRatio; }; WheelJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WheelJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WheelJoint.prototype.getReactionForce = function(inv_dt) { return inv_dt * (this.m_impulse * this.m_ay + this.m_springImpulse * this.m_ax); }; WheelJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(1, cA, 1, rA); { this.m_ay = Rot.mul(qA, this.m_localYAxisA); this.m_sAy = Vec2.cross(Vec2.add(d, rA), this.m_ay); this.m_sBy = Vec2.cross(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } } this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; if (this.m_frequencyHz > 0) { this.m_ax = Rot.mul(qA, this.m_localXAxisA); this.m_sAx = Vec2.cross(Vec2.add(d, rA), this.m_ax); this.m_sBx = Vec2.cross(rB, this.m_ax); var invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; if (invMass > 0) { this.m_springMass = 1 / invMass; var C = Vec2.dot(d, this.m_ax); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_springMass * this.m_dampingRatio * omega; var k = this.m_springMass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); if (this.m_gamma > 0) { this.m_gamma = 1 / this.m_gamma; } this.m_bias = C * h * k * this.m_gamma; this.m_springMass = invMass + this.m_gamma; if (this.m_springMass > 0) { this.m_springMass = 1 / this.m_springMass; } } } else { this.m_springImpulse = 0; } if (this.m_enableMotor) { this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } else { this.m_motorMass = 0; this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; this.m_springImpulse *= step.dtRatio; this.m_motorImpulse *= step.dtRatio; var P = Vec2.wAdd(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax); var LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; var LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0; this.m_springImpulse = 0; this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solveVelocityConstraints = function(step) { var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; { var Cdot = Vec2.dot(this.m_ax, vB) - Vec2.dot(this.m_ax, vA) + this.m_sBx * wB - this.m_sAx * wA; var impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); this.m_springImpulse += impulse; var P = Vec2.zero().wSet(impulse, this.m_ax); var LA = impulse * this.m_sAx; var LB = impulse * this.m_sBx; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.dot(this.m_ay, vB) - Vec2.dot(this.m_ay, vA) + this.m_sBy * wB - this.m_sAy * wA; var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var P = Vec2.zero().wSet(impulse, this.m_ay); var LA = impulse * this.m_sAy; var LB = impulse * this.m_sBy; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(1, cA, 1, rA); var ay = Rot.mul(qA, this.m_localYAxisA); var sAy = Vec2.cross(Vec2.sub(d, rA), ay); var sBy = Vec2.cross(rB, ay); var C = Vec2.dot(d, ay); var k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy; var impulse; if (k != 0) { impulse = -C / k; } else { impulse = 0; } var P = Vec2.zero().wSet(impulse, ay); var LA = impulse * sAy; var LB = impulse * sBy; cA.wSub(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.wAdd(this.m_invMassB, P); aB += this.m_invIB * LB; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) <= Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],39:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = BoxShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var PolygonShape = require("./PolygonShape"); BoxShape._super = PolygonShape; BoxShape.prototype = create(BoxShape._super.prototype); BoxShape.TYPE = "polygon"; function BoxShape(hx, hy, center, angle) { if (!(this instanceof BoxShape)) { return new BoxShape(hx, hy, center, angle); } BoxShape._super.call(this); this.m_vertices[0] = Vec2.neo(-hx, -hy); this.m_vertices[1] = Vec2.neo(hx, -hy); this.m_vertices[2] = Vec2.neo(hx, hy); this.m_vertices[3] = Vec2.neo(-hx, hy); this.m_normals[0] = Vec2.neo(0, -1); this.m_normals[1] = Vec2.neo(1, 0); this.m_normals[2] = Vec2.neo(0, 1); this.m_normals[3] = Vec2.neo(-1, 0); this.m_count = 4; if (center && "x" in center && "y" in center) { angle = angle || 0; this.m_centroid.set(center); var xf = Transform.identity(); xf.p.set(center); xf.q.set(angle); for (var i = 0; i < this.m_count; ++i) { this.m_vertices[i] = Transform.mul(xf, this.m_vertices[i]); this.m_normals[i] = Rot.mul(xf.q, this.m_normals[i]); } } } },{"../Settings":7,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./PolygonShape":48}],40:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = ChainShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); var EdgeShape = require("./EdgeShape"); ChainShape._super = Shape; ChainShape.prototype = create(ChainShape._super.prototype); ChainShape.TYPE = "chain"; function ChainShape(vertices, loop) { if (!(this instanceof ChainShape)) { return new ChainShape(vertices, loop); } ChainShape._super.call(this); this.m_type = ChainShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertices = []; this.m_count = 0; this.m_prevVertex = null; this.m_nextVertex = null; this.m_hasPrevVertex = false; this.m_hasNextVertex = false; if (vertices && vertices.length) { if (loop) { this._createLoop(vertices); } else { this._createChain(vertices); } } } ChainShape.prototype._createLoop = function(vertices) { ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); ASSERT && common.assert(vertices.length >= 3); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_vertices.length = 0; this.m_count = vertices.length + 1; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_vertices[vertices.length] = vertices[0].clone(); this.m_prevVertex = this.m_vertices[this.m_count - 2]; this.m_nextVertex = this.m_vertices[1]; this.m_hasPrevVertex = true; this.m_hasNextVertex = true; return this; }; ChainShape.prototype._createChain = function(vertices) { ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); ASSERT && common.assert(vertices.length >= 2); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_count = vertices.length; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_hasPrevVertex = false; this.m_hasNextVertex = false; this.m_prevVertex = null; this.m_nextVertex = null; return this; }; ChainShape.prototype._setPrevVertex = function(prevVertex) { this.m_prevVertex = prevVertex; this.m_hasPrevVertex = true; }; ChainShape.prototype._setNextVertex = function(nextVertex) { this.m_nextVertex = nextVertex; this.m_hasNextVertex = true; }; ChainShape.prototype._clone = function() { var clone = new ChainShape(); clone.createChain(this.m_vertices); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_prevVertex = this.m_prevVertex; clone.m_nextVertex = this.m_nextVertex; clone.m_hasPrevVertex = this.m_hasPrevVertex; clone.m_hasNextVertex = this.m_hasNextVertex; return clone; }; ChainShape.prototype.getChildCount = function() { return this.m_count - 1; }; ChainShape.prototype.getChildEdge = function(edge, childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count - 1); edge.m_type = EdgeShape.TYPE; edge.m_radius = this.m_radius; edge.m_vertex1 = this.m_vertices[childIndex]; edge.m_vertex2 = this.m_vertices[childIndex + 1]; if (childIndex > 0) { edge.m_vertex0 = this.m_vertices[childIndex - 1]; edge.m_hasVertex0 = true; } else { edge.m_vertex0 = this.m_prevVertex; edge.m_hasVertex0 = this.m_hasPrevVertex; } if (childIndex < this.m_count - 2) { edge.m_vertex3 = this.m_vertices[childIndex + 2]; edge.m_hasVertex3 = true; } else { edge.m_vertex3 = this.m_nextVertex; edge.m_hasVertex3 = this.m_hasNextVertex; } }; ChainShape.prototype.getVertex = function(index) { ASSERT && common.assert(0 <= index && index <= this.m_count); if (index < this.m_count) { return this.m_vertices[index]; } else { return this.m_vertices[0]; } }; ChainShape.prototype.testPoint = function(xf, p) { return false; }; ChainShape.prototype.rayCast = function(output, input, xf, childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var edgeShape = new EdgeShape(this.getVertex(childIndex), this.getVertex(childIndex + 1)); return edgeShape.rayCast(output, input, xf, 0); }; ChainShape.prototype.computeAABB = function(aabb, xf, childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var v1 = Transform.mul(xf, this.getVertex(childIndex)); var v2 = Transform.mul(xf, this.getVertex(childIndex + 1)); aabb.combinePoints(v1, v2); }; ChainShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center = Vec2.neo(); massData.I = 0; }; ChainShape.prototype.computeDistanceProxy = function(proxy, childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); proxy.m_buffer[0] = this.getVertex(childIndex); proxy.m_buffer[1] = this.getVertex(childIndex + 1); proxy.m_vertices = proxy.m_buffer; proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./EdgeShape":47}],41:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = CircleShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); CircleShape._super = Shape; CircleShape.prototype = create(CircleShape._super.prototype); CircleShape.TYPE = "circle"; function CircleShape(a, b) { if (!(this instanceof CircleShape)) { return new CircleShape(a, b); } CircleShape._super.call(this); this.m_type = CircleShape.TYPE; this.m_p = Vec2.zero(); this.m_radius = 1; if (typeof a === "object" && Vec2.isValid(a)) { this.m_p.set(a); if (typeof b === "number") { this.m_radius = b; } } else if (typeof a === "number") { this.m_radius = a; } } CircleShape.prototype.getRadius = function() { return this.m_radius; }; CircleShape.prototype.getCenter = function() { return this.m_p; }; CircleShape.prototype.getSupportVertex = function(d) { return this.m_p; }; CircleShape.prototype.getVertex = function(index) { ASSERT && common.assert(index == 0); return this.m_p; }; CircleShape.prototype.getVertexCount = function(index) { return 1; }; CircleShape.prototype._clone = function() { var clone = new CircleShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_p = this.m_p.clone(); return clone; }; CircleShape.prototype.getChildCount = function() { return 1; }; CircleShape.prototype.testPoint = function(xf, p) { var center = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); var d = Vec2.sub(p, center); return Vec2.dot(d, d) <= this.m_radius * this.m_radius; }; CircleShape.prototype.rayCast = function(output, input, xf, childIndex) { var position = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); var s = Vec2.sub(input.p1, position); var b = Vec2.dot(s, s) - this.m_radius * this.m_radius; var r = Vec2.sub(input.p2, input.p1); var c = Vec2.dot(s, r); var rr = Vec2.dot(r, r); var sigma = c * c - rr * b; if (sigma < 0 || rr < Math.EPSILON) { return false; } var a = -(c + Math.sqrt(sigma)); if (0 <= a && a <= input.maxFraction * rr) { a /= rr; output.fraction = a; output.normal = Vec2.add(s, Vec2.mul(a, r)); output.normal.normalize(); return true; } return false; }; CircleShape.prototype.computeAABB = function(aabb, xf, childIndex) { var p = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); aabb.lowerBound.set(p.x - this.m_radius, p.y - this.m_radius); aabb.upperBound.set(p.x + this.m_radius, p.y + this.m_radius); }; CircleShape.prototype.computeMass = function(massData, density) { massData.mass = density * Math.PI * this.m_radius * this.m_radius; massData.center = this.m_p; massData.I = massData.mass * (.5 * this.m_radius * this.m_radius + Vec2.dot(this.m_p, this.m_p)); }; CircleShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_p); proxy.m_count = 1; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],42:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var CircleShape = require("./CircleShape"); Contact.addType(CircleShape.TYPE, CircleShape.TYPE, CircleCircleContact); function CircleCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == CircleShape.TYPE); ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollideCircles(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollideCircles(manifold, circleA, xfA, circleB, xfB) { manifold.pointCount = 0; var pA = Transform.mul(xfA, circleA.m_p); var pB = Transform.mul(xfB, circleB.m_p); var distSqr = Vec2.distanceSquared(pB, pA); var rA = circleA.m_radius; var rB = circleB.m_radius; var radius = rA + rB; if (distSqr > radius * radius) { return; } manifold.type = Manifold.e_circles; manifold.localPoint.set(circleA.m_p); manifold.localNormal.setZero(); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } exports.CollideCircles = CollideCircles; },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./CircleShape":41}],43:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var CircleShape = require("./CircleShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(PolygonShape.TYPE, CircleShape.TYPE, PolygonCircleContact); function PolygonCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollidePolygonCircle(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollidePolygonCircle(manifold, polygonA, xfA, circleB, xfB) { manifold.pointCount = 0; var c = Transform.mul(xfB, circleB.m_p); var cLocal = Transform.mulT(xfA, c); var normalIndex = 0; var separation = -Infinity; var radius = polygonA.m_radius + circleB.m_radius; var vertexCount = polygonA.m_count; var vertices = polygonA.m_vertices; var normals = polygonA.m_normals; for (var i = 0; i < vertexCount; ++i) { var s = Vec2.dot(normals[i], Vec2.sub(cLocal, vertices[i])); if (s > radius) { return; } if (s > separation) { separation = s; normalIndex = i; } } var vertIndex1 = normalIndex; var vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; var v1 = vertices[vertIndex1]; var v2 = vertices[vertIndex2]; if (separation < Math.EPSILON) { manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[normalIndex]); manifold.localPoint.wSet(.5, v1, .5, v2); manifold.points[0].localPoint = circleB.m_p; manifold.points[0].id.key = 0; return; } var u1 = Vec2.dot(Vec2.sub(cLocal, v1), Vec2.sub(v2, v1)); var u2 = Vec2.dot(Vec2.sub(cLocal, v2), Vec2.sub(v1, v2)); if (u1 <= 0) { if (Vec2.distanceSquared(cLocal, v1) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.wSet(1, cLocal, -1, v1); manifold.localNormal.normalize(); manifold.localPoint = v1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } else if (u2 <= 0) { if (Vec2.distanceSquared(cLocal, v2) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.wSet(1, cLocal, -1, v2); manifold.localNormal.normalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } else { var faceCenter = Vec2.mid(v1, v2); var separation = Vec2.dot(cLocal, normals[vertIndex1]) - Vec2.dot(faceCenter, normals[vertIndex1]); if (separation > radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[vertIndex1]); manifold.localPoint.set(faceCenter); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./CircleShape":41,"./PolygonShape":48}],44:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var CircleShape = require("./CircleShape"); Contact.addType(EdgeShape.TYPE, CircleShape.TYPE, EdgeCircleContact); Contact.addType(ChainShape.TYPE, CircleShape.TYPE, ChainCircleContact); function EdgeCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == EdgeShape.TYPE); ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function ChainCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == ChainShape.TYPE); ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var chain = fixtureA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); var shapeA = edge; var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function CollideEdgeCircle(manifold, edgeA, xfA, circleB, xfB) { manifold.pointCount = 0; var Q = Transform.mulT(xfA, Transform.mul(xfB, circleB.m_p)); var A = edgeA.m_vertex1; var B = edgeA.m_vertex2; var e = Vec2.sub(B, A); var u = Vec2.dot(e, Vec2.sub(B, Q)); var v = Vec2.dot(e, Vec2.sub(Q, A)); var radius = edgeA.m_radius + circleB.m_radius; if (v <= 0) { var P = Vec2.clone(A); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex0) { var A1 = edgeA.m_vertex0; var B1 = A; var e1 = Vec2.sub(B1, A1); var u1 = Vec2.dot(e1, Vec2.sub(B1, Q)); if (u1 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } if (u <= 0) { var P = Vec2.clone(B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex3) { var B2 = edgeA.m_vertex3; var A2 = B; var e2 = Vec2.sub(B2, A2); var v2 = Vec2.dot(e2, Vec2.sub(Q, A2)); if (v2 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 1; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } var den = Vec2.dot(e, e); ASSERT && common.assert(den > 0); var P = Vec2.wAdd(u / den, A, v / den, B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } var n = Vec2.neo(-e.y, e.x); if (Vec2.dot(n, Vec2.sub(Q, A)) < 0) { n.set(-n.x, -n.y); } n.normalize(); manifold.type = Manifold.e_faceA; manifold.localNormal = n; manifold.localPoint.set(A); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_face; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./CircleShape":41,"./EdgeShape":47}],45:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(EdgeShape.TYPE, PolygonShape.TYPE, EdgePolygonContact); Contact.addType(ChainShape.TYPE, PolygonShape.TYPE, ChainPolygonContact); function EdgePolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { ASSERT && common.assert(fA.getType() == EdgeShape.TYPE); ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); CollideEdgePolygon(manifold, fA.getShape(), xfA, fB.getShape(), xfB); } function ChainPolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { ASSERT && common.assert(fA.getType() == ChainShape.TYPE); ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); var chain = fA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); CollideEdgePolygon(manifold, edge, xfA, fB.getShape(), xfB); } var e_unknown = -1; var e_edgeA = 1; var e_edgeB = 2; var e_isolated = 0; var e_concave = 1; var e_convex = 2; function EPAxis() { this.type; this.index; this.separation; } function TempPolygon() { this.vertices = []; this.normals = []; this.count = 0; } function ReferenceFace() { this.i1, this.i2; this.v1, this.v2; this.normal = Vec2.zero(); this.sideNormal1 = Vec2.zero(); this.sideOffset1; this.sideNormal2 = Vec2.zero(); this.sideOffset2; } var edgeAxis = new EPAxis(); var polygonAxis = new EPAxis(); var polygonBA = new TempPolygon(); var rf = new ReferenceFace(); function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) { DEBUG && common.debug("CollideEdgePolygon"); var m_type1, m_type2; var xf = Transform.mulT(xfA, xfB); var centroidB = Transform.mul(xf, polygonB.m_centroid); var v0 = edgeA.m_vertex0; var v1 = edgeA.m_vertex1; var v2 = edgeA.m_vertex2; var v3 = edgeA.m_vertex3; var hasVertex0 = edgeA.m_hasVertex0; var hasVertex3 = edgeA.m_hasVertex3; var edge1 = Vec2.sub(v2, v1); edge1.normalize(); var normal1 = Vec2.neo(edge1.y, -edge1.x); var offset1 = Vec2.dot(normal1, Vec2.sub(centroidB, v1)); var offset0 = 0; var offset2 = 0; var convex1 = false; var convex2 = false; if (hasVertex0) { var edge0 = Vec2.sub(v1, v0); edge0.normalize(); var normal0 = Vec2.neo(edge0.y, -edge0.x); convex1 = Vec2.cross(edge0, edge1) >= 0; offset0 = Vec2.dot(normal0, centroidB) - Vec2.dot(normal0, v0); } if (hasVertex3) { var edge2 = Vec2.sub(v3, v2); edge2.normalize(); var normal2 = Vec2.neo(edge2.y, -edge2.x); convex2 = Vec2.cross(edge1, edge2) > 0; offset2 = Vec2.dot(normal2, centroidB) - Vec2.dot(normal2, v2); } var front; var normal = Vec2.zero(); var lowerLimit = Vec2.zero(); var upperLimit = Vec2.zero(); if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal2); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-1, normal1); } } else if (convex1) { front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal1); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.wSet(-1, normal1); } } else if (convex2) { front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal2); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-1, normal0); } } else { front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.wSet(-1, normal0); } } } else if (hasVertex0) { if (convex1) { front = offset0 >= 0 || offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.wSet(-1, normal1); } else { normal.wSet(-1, normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal1); } } else { front = offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal1); } else { normal.wSet(-1, normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal0); } } } else if (hasVertex3) { if (convex2) { front = offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal2); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal1); } } else { front = offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal1); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.set(normal1); } } } else { front = offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-1, normal1); } else { normal.wSet(-1, normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } } polygonBA.count = polygonB.m_count; for (var i = 0; i < polygonB.m_count; ++i) { polygonBA.vertices[i] = Transform.mul(xf, polygonB.m_vertices[i]); polygonBA.normals[i] = Rot.mul(xf.q, polygonB.m_normals[i]); } var radius = 2 * Settings.polygonRadius; manifold.pointCount = 0; { edgeAxis.type = e_edgeA; edgeAxis.index = front ? 0 : 1; edgeAxis.separation = Infinity; for (var i = 0; i < polygonBA.count; ++i) { var s = Vec2.dot(normal, Vec2.sub(polygonBA.vertices[i], v1)); if (s < edgeAxis.separation) { edgeAxis.separation = s; } } } if (edgeAxis.type == e_unknown) { return; } if (edgeAxis.separation > radius) { return; } { polygonAxis.type = e_unknown; polygonAxis.index = -1; polygonAxis.separation = -Infinity; var perp = Vec2.neo(-normal.y, normal.x); for (var i = 0; i < polygonBA.count; ++i) { var n = Vec2.neg(polygonBA.normals[i]); var s1 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v1)); var s2 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v2)); var s = Math.min(s1, s2); if (s > radius) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; break; } if (Vec2.dot(n, perp) >= 0) { if (Vec2.dot(Vec2.sub(n, upperLimit), normal) < -Settings.angularSlop) { continue; } } else { if (Vec2.dot(Vec2.sub(n, lowerLimit), normal) < -Settings.angularSlop) { continue; } } if (s > polygonAxis.separation) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; } } } if (polygonAxis.type != e_unknown && polygonAxis.separation > radius) { return; } var k_relativeTol = .98; var k_absoluteTol = .001; var primaryAxis; if (polygonAxis.type == e_unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } var ie = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; if (primaryAxis.type == e_edgeA) { manifold.type = Manifold.e_faceA; var bestIndex = 0; var bestValue = Vec2.dot(normal, polygonBA.normals[0]); for (var i = 1; i < polygonBA.count; ++i) { var value = Vec2.dot(normal, polygonBA.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } var i1 = bestIndex; var i2 = i1 + 1 < polygonBA.count ? i1 + 1 : 0; ie[0].v = polygonBA.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = i1; ie[0].id.cf.typeA = Manifold.e_face; ie[0].id.cf.typeB = Manifold.e_vertex; ie[1].v = polygonBA.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = i2; ie[1].id.cf.typeA = Manifold.e_face; ie[1].id.cf.typeB = Manifold.e_vertex; if (front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = v1; rf.v2 = v2; rf.normal.set(normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = v2; rf.v2 = v1; rf.normal.wSet(-1, normal1); } } else { manifold.type = Manifold.e_faceB; ie[0].v = v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = primaryAxis.index; ie[0].id.cf.typeA = Manifold.e_vertex; ie[0].id.cf.typeB = Manifold.e_face; ie[1].v = v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = primaryAxis.index; ie[1].id.cf.typeA = Manifold.e_vertex; ie[1].id.cf.typeB = Manifold.e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < polygonBA.count ? rf.i1 + 1 : 0; rf.v1 = polygonBA.vertices[rf.i1]; rf.v2 = polygonBA.vertices[rf.i2]; rf.normal.set(polygonBA.normals[rf.i1]); } rf.sideNormal1.set(rf.normal.y, -rf.normal.x); rf.sideNormal2.wSet(-1, rf.sideNormal1); rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2); var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < Settings.maxManifoldPoints) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < Settings.maxManifoldPoints) { return; } if (primaryAxis.type == e_edgeA) { manifold.localNormal = Vec2.clone(rf.normal); manifold.localPoint = Vec2.clone(rf.v1); } else { manifold.localNormal = Vec2.clone(polygonB.m_normals[rf.i1]); manifold.localPoint = Vec2.clone(polygonB.m_vertices[rf.i1]); } var pointCount = 0; for (var i = 0; i < Settings.maxManifoldPoints; ++i) { var separation = Vec2.dot(rf.normal, Vec2.sub(clipPoints2[i].v, rf.v1)); if (separation <= radius) { var cp = manifold.points[pointCount]; if (primaryAxis.type == e_edgeA) { cp.localPoint = Transform.mulT(xf, clipPoints2[i].v); cp.id = clipPoints2[i].id; } else { cp.localPoint = clipPoints2[i].v; cp.id.cf.typeA = clipPoints2[i].id.cf.typeB; cp.id.cf.typeB = clipPoints2[i].id.cf.typeA; cp.id.cf.indexA = clipPoints2[i].id.cf.indexB; cp.id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./EdgeShape":47,"./PolygonShape":48}],46:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var PolygonShape = require("./PolygonShape"); module.exports = CollidePolygons; Contact.addType(PolygonShape.TYPE, PolygonShape.TYPE, PolygonContact); function PolygonContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); ASSERT && common.assert(fixtureB.getType() == PolygonShape.TYPE); CollidePolygons(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function FindMaxSeparation(poly1, xf1, poly2, xf2) { var count1 = poly1.m_count; var count2 = poly2.m_count; var n1s = poly1.m_normals; var v1s = poly1.m_vertices; var v2s = poly2.m_vertices; var xf = Transform.mulT(xf2, xf1); var bestIndex = 0; var maxSeparation = -Infinity; for (var i = 0; i < count1; ++i) { var n = Rot.mul(xf.q, n1s[i]); var v1 = Transform.mul(xf, v1s[i]); var si = Infinity; for (var j = 0; j < count2; ++j) { var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1); if (sij < si) { si = sij; } } if (si > maxSeparation) { maxSeparation = si; bestIndex = i; } } FindMaxSeparation._maxSeparation = maxSeparation; FindMaxSeparation._bestIndex = bestIndex; } function FindIncidentEdge(c, poly1, xf1, edge1, poly2, xf2) { var normals1 = poly1.m_normals; var count2 = poly2.m_count; var vertices2 = poly2.m_vertices; var normals2 = poly2.m_normals; ASSERT && common.assert(0 <= edge1 && edge1 < poly1.m_count); var normal1 = Rot.mulT(xf2.q, Rot.mul(xf1.q, normals1[edge1])); var index = 0; var minDot = Infinity; for (var i = 0; i < count2; ++i) { var dot = Vec2.dot(normal1, normals2[i]); if (dot < minDot) { minDot = dot; index = i; } } var i1 = index; var i2 = i1 + 1 < count2 ? i1 + 1 : 0; c[0].v = Transform.mul(xf2, vertices2[i1]); c[0].id.cf.indexA = edge1; c[0].id.cf.indexB = i1; c[0].id.cf.typeA = Manifold.e_face; c[0].id.cf.typeB = Manifold.e_vertex; c[1].v = Transform.mul(xf2, vertices2[i2]); c[1].id.cf.indexA = edge1; c[1].id.cf.indexB = i2; c[1].id.cf.typeA = Manifold.e_face; c[1].id.cf.typeB = Manifold.e_vertex; } function CollidePolygons(manifold, polyA, xfA, polyB, xfB) { manifold.pointCount = 0; var totalRadius = polyA.m_radius + polyB.m_radius; FindMaxSeparation(polyA, xfA, polyB, xfB); var edgeA = FindMaxSeparation._bestIndex; var separationA = FindMaxSeparation._maxSeparation; if (separationA > totalRadius) return; FindMaxSeparation(polyB, xfB, polyA, xfA); var edgeB = FindMaxSeparation._bestIndex; var separationB = FindMaxSeparation._maxSeparation; if (separationB > totalRadius) return; var poly1; var poly2; var xf1; var xf2; var edge1; var flip; var k_tol = .1 * Settings.linearSlop; if (separationB > separationA + k_tol) { poly1 = polyB; poly2 = polyA; xf1 = xfB; xf2 = xfA; edge1 = edgeB; manifold.type = Manifold.e_faceB; flip = 1; } else { poly1 = polyA; poly2 = polyB; xf1 = xfA; xf2 = xfB; edge1 = edgeA; manifold.type = Manifold.e_faceA; flip = 0; } var incidentEdge = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); var count1 = poly1.m_count; var vertices1 = poly1.m_vertices; var iv1 = edge1; var iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; var v11 = vertices1[iv1]; var v12 = vertices1[iv2]; var localTangent = Vec2.sub(v12, v11); localTangent.normalize(); var localNormal = Vec2.cross(localTangent, 1); var planePoint = Vec2.wAdd(.5, v11, .5, v12); var tangent = Rot.mul(xf1.q, localTangent); var normal = Vec2.cross(tangent, 1); v11 = Transform.mul(xf1, v11); v12 = Transform.mul(xf1, v12); var frontOffset = Vec2.dot(normal, v11); var sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; var sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, incidentEdge, Vec2.neg(tangent), sideOffset1, iv1); if (np < 2) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) { return; } manifold.localNormal = localNormal; manifold.localPoint = planePoint; var pointCount = 0; for (var i = 0; i < clipPoints2.length; ++i) { var separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset; if (separation <= totalRadius) { var cp = manifold.points[pointCount]; cp.localPoint.set(Transform.mulT(xf2, clipPoints2[i].v)); cp.id = clipPoints2[i].id; if (flip) { var cf = cp.id.cf; var indexA = cf.indexA; var indexB = cf.indexB; var typeA = cf.typeA; var typeB = cf.typeB; cf.indexA = indexB; cf.indexB = indexA; cf.typeA = typeB; cf.typeB = typeA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./PolygonShape":48}],47:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = EdgeShape; var create = require("../util/create"); var options = require("../util/options"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); EdgeShape._super = Shape; EdgeShape.prototype = create(EdgeShape._super.prototype); EdgeShape.TYPE = "edge"; function EdgeShape(v1, v2) { if (!(this instanceof EdgeShape)) { return new EdgeShape(v1, v2); } EdgeShape._super.call(this); this.m_type = EdgeShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertex1 = v1 ? Vec2.clone(v1) : Vec2.zero(); this.m_vertex2 = v2 ? Vec2.clone(v2) : Vec2.zero(); this.m_vertex0 = Vec2.zero(); this.m_vertex3 = Vec2.zero(); this.m_hasVertex0 = false; this.m_hasVertex3 = false; } EdgeShape.prototype.setNext = function(v3) { if (v3) { this.m_vertex3.set(v3); this.m_hasVertex3 = true; } else { this.m_vertex3.setZero(); this.m_hasVertex3 = false; } return this; }; EdgeShape.prototype.setPrev = function(v0) { if (v0) { this.m_vertex0.set(v0); this.m_hasVertex0 = true; } else { this.m_vertex0.setZero(); this.m_hasVertex0 = false; } return this; }; EdgeShape.prototype._set = function(v1, v2) { this.m_vertex1.set(v1); this.m_vertex2.set(v2); this.m_hasVertex0 = false; this.m_hasVertex3 = false; return this; }; EdgeShape.prototype._clone = function() { var clone = new EdgeShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_vertex1.set(this.m_vertex1); clone.m_vertex2.set(this.m_vertex2); clone.m_vertex0.set(this.m_vertex0); clone.m_vertex3.set(this.m_vertex3); clone.m_hasVertex0 = this.m_hasVertex0; clone.m_hasVertex3 = this.m_hasVertex3; return clone; }; EdgeShape.prototype.getChildCount = function() { return 1; }; EdgeShape.prototype.testPoint = function(xf, p) { return false; }; EdgeShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulT(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulT(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var v1 = this.m_vertex1; var v2 = this.m_vertex2; var e = Vec2.sub(v2, v1); var normal = Vec2.neo(e.y, -e.x); normal.normalize(); var numerator = Vec2.dot(normal, Vec2.sub(v1, p1)); var denominator = Vec2.dot(normal, d); if (denominator == 0) { return false; } var t = numerator / denominator; if (t < 0 || input.maxFraction < t) { return false; } var q = Vec2.add(p1, Vec2.mul(t, d)); var r = Vec2.sub(v2, v1); var rr = Vec2.dot(r, r); if (rr == 0) { return false; } var s = Vec2.dot(Vec2.sub(q, v1), r) / rr; if (s < 0 || 1 < s) { return false; } output.fraction = t; if (numerator > 0) { output.normal = Rot.mul(xf.q, normal).neg(); } else { output.normal = Rot.mul(xf.q, normal); } return true; }; EdgeShape.prototype.computeAABB = function(aabb, xf, childIndex) { var v1 = Transform.mul(xf, this.m_vertex1); var v2 = Transform.mul(xf, this.m_vertex2); aabb.combinePoints(v1, v2); aabb.extend(this.m_radius); }; EdgeShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center.wSet(.5, this.m_vertex1, .5, this.m_vertex2); massData.I = 0; }; EdgeShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_vertex1); proxy.m_vertices.push(this.m_vertex2); proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/create":52,"../util/options":53}],48:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PolygonShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); PolygonShape._super = Shape; PolygonShape.prototype = create(PolygonShape._super.prototype); PolygonShape.TYPE = "polygon"; function PolygonShape(vertices) { if (!(this instanceof PolygonShape)) { return new PolygonShape(vertices); } PolygonShape._super.call(this); this.m_type = PolygonShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_centroid = Vec2.zero(); this.m_vertices = []; this.m_normals = []; this.m_count = 0; if (vertices && vertices.length) { this._set(vertices); } } PolygonShape.prototype.getVertex = function(index) { ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; PolygonShape.prototype._clone = function() { var clone = new PolygonShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_count = this.m_count; clone.m_centroid.set(this.m_centroid); for (var i = 0; i < this.m_count; i++) { clone.m_vertices.push(this.m_vertices[i].clone()); } for (var i = 0; i < this.m_normals.length; i++) { clone.m_normals.push(this.m_normals[i].clone()); } return clone; }; PolygonShape.prototype.getChildCount = function() { return 1; }; function ComputeCentroid(vs, count) { ASSERT && common.assert(count >= 3); var c = Vec2.zero(); var area = 0; var pRef = Vec2.zero(); if (false) { for (var i = 0; i < count; ++i) { pRef.add(vs[i]); } pRef.mul(1 / count); } var inv3 = 1 / 3; for (var i = 0; i < count; ++i) { var p1 = pRef; var p2 = vs[i]; var p3 = i + 1 < count ? vs[i + 1] : vs[0]; var e1 = Vec2.sub(p2, p1); var e2 = Vec2.sub(p3, p1); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; c.wAdd(triangleArea * inv3, p1); c.wAdd(triangleArea * inv3, p2); c.wAdd(triangleArea * inv3, p3); } ASSERT && common.assert(area > Math.EPSILON); c.mul(1 / area); return c; } PolygonShape.prototype._set = function(vertices) { ASSERT && common.assert(3 <= vertices.length && vertices.length <= Settings.maxPolygonVertices); if (vertices.length < 3) { SetAsBox(1, 1); return; } var n = Math.min(vertices.length, Settings.maxPolygonVertices); var ps = []; var tempCount = 0; for (var i = 0; i < n; ++i) { var v = vertices[i]; var unique = true; for (var j = 0; j < tempCount; ++j) { if (Vec2.distanceSquared(v, ps[j]) < .25 * Settings.linearSlopSquared) { unique = false; break; } } if (unique) { ps[tempCount++] = v; } } n = tempCount; if (n < 3) { ASSERT && common.assert(false); SetAsBox(1, 1); return; } var i0 = 0; var x0 = ps[0].x; for (var i = 1; i < n; ++i) { var x = ps[i].x; if (x > x0 || x == x0 && ps[i].y < ps[i0].y) { i0 = i; x0 = x; } } var hull = []; var m = 0; var ih = i0; for (;;) { hull[m] = ih; var ie = 0; for (var j = 1; j < n; ++j) { if (ie == ih) { ie = j; continue; } var r = Vec2.sub(ps[ie], ps[hull[m]]); var v = Vec2.sub(ps[j], ps[hull[m]]); var c = Vec2.cross(r, v); if (c < 0) { ie = j; } if (c == 0 && v.lengthSquared() > r.lengthSquared()) { ie = j; } } ++m; ih = ie; if (ie == i0) { break; } } if (m < 3) { ASSERT && common.assert(false); SetAsBox(1, 1); return; } this.m_count = m; for (var i = 0; i < m; ++i) { this.m_vertices[i] = ps[hull[i]]; } for (var i = 0; i < m; ++i) { var i1 = i; var i2 = i + 1 < m ? i + 1 : 0; var edge = Vec2.sub(this.m_vertices[i2], this.m_vertices[i1]); ASSERT && common.assert(edge.lengthSquared() > Math.EPSILON * Math.EPSILON); this.m_normals[i] = Vec2.cross(edge, 1); this.m_normals[i].normalize(); } this.m_centroid = ComputeCentroid(this.m_vertices, m); }; PolygonShape.prototype.testPoint = function(xf, p) { var pLocal = Rot.mulT(xf.q, Vec2.sub(p, xf.p)); for (var i = 0; i < this.m_count; ++i) { var dot = Vec2.dot(this.m_normals[i], Vec2.sub(pLocal, this.m_vertices[i])); if (dot > 0) { return false; } } return true; }; PolygonShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulT(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulT(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var lower = 0; var upper = input.maxFraction; var index = -1; for (var i = 0; i < this.m_count; ++i) { var numerator = Vec2.dot(this.m_normals[i], Vec2.sub(this.m_vertices[i], p1)); var denominator = Vec2.dot(this.m_normals[i], d); if (denominator == 0) { if (numerator < 0) { return false; } } else { if (denominator < 0 && numerator < lower * denominator) { lower = numerator / denominator; index = i; } else if (denominator > 0 && numerator < upper * denominator) { upper = numerator / denominator; } } if (upper < lower) { return false; } } ASSERT && common.assert(0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; output.normal = Rot.mul(xf.q, this.m_normals[index]); return true; } return false; }; PolygonShape.prototype.computeAABB = function(aabb, xf, childIndex) { var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < this.m_count; ++i) { var v = Transform.mul(xf, this.m_vertices[i]); minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } aabb.lowerBound.set(minX, minY); aabb.upperBound.set(maxX, maxY); aabb.extend(this.m_radius); }; PolygonShape.prototype.computeMass = function(massData, density) { ASSERT && common.assert(this.m_count >= 3); var center = Vec2.zero(); var area = 0; var I = 0; var s = Vec2.zero(); for (var i = 0; i < this.m_count; ++i) { s.add(this.m_vertices[i]); } s.mul(1 / this.m_count); var k_inv3 = 1 / 3; for (var i = 0; i < this.m_count; ++i) { var e1 = Vec2.sub(this.m_vertices[i], s); var e2 = i + 1 < this.m_count ? Vec2.sub(this.m_vertices[i + 1], s) : Vec2.sub(this.m_vertices[0], s); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; center.wAdd(triangleArea * k_inv3, e1, triangleArea * k_inv3, e2); var ex1 = e1.x; var ey1 = e1.y; var ex2 = e2.x; var ey2 = e2.y; var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += .25 * k_inv3 * D * (intx2 + inty2); } massData.mass = density * area; ASSERT && common.assert(area > Math.EPSILON); center.mul(1 / area); massData.center.wSet(1, center, 1, s); massData.I = density * I; massData.I += massData.mass * (Vec2.dot(massData.center, massData.center) - Vec2.dot(center, center)); }; PolygonShape.prototype.validate = function() { for (var i = 0; i < this.m_count; ++i) { var i1 = i; var i2 = i < this.m_count - 1 ? i1 + 1 : 0; var p = this.m_vertices[i1]; var e = Vec2.sub(this.m_vertices[i2], p); for (var j = 0; j < this.m_count; ++j) { if (j == i1 || j == i2) { continue; } var v = Vec2.sub(this.m_vertices[j], p); var c = Vec2.cross(e, v); if (c < 0) { return false; } } } return true; }; PolygonShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices = this.m_vertices; proxy.m_count = this.m_count; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],49:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Pool; function Pool(opts) { var _list = []; var _max = opts.max || Infinity; var _createFn = opts.create; var _outFn = opts.allocate; var _inFn = opts.release; var _discardFn = opts.discard; var _createCount = 0; var _outCount = 0; var _inCount = 0; var _discardCount = 0; this.max = function(n) { if (typeof n === "number") { _max = n; return this; } return _max; }; this.size = function() { return _list.length; }; this.allocate = function() { var item; if (_list.length > 0) { item = _list.shift(); } else { _createCount++; if (typeof _createFn === "function") { item = _createFn(); } else { item = {}; } } _outCount++; if (typeof _outFn === "function") { _outFn(item); } return item; }; this.release = function(item) { if (_list.length < _max) { _inCount++; if (typeof _inFn === "function") { _inFn(item); } _list.push(item); } else { _discardCount++; if (typeof _discardFn === "function") { item = _discardFn(item); } } }; this.toString = function() { return " +" + _createCount + " >" + _outCount + " <" + _inCount + " -" + _discardCount + " =" + _list.length + "/" + _max; }; } },{}],50:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports.now = function() { return Date.now(); }; module.exports.diff = function(time) { return Date.now() - time; }; },{}],51:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.debug = function() { if (!DEBUG) return; console.log.apply(console, arguments); }; exports.assert = function(statement, err, log) { if (!ASSERT) return; if (statement) return; log && console.log(log); throw new Error(err); }; },{}],52:[function(require,module,exports){ if (typeof Object.create == "function") { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error("Second argument is not supported!"); if (typeof proto !== "object" || proto === null) throw Error("Invalid prototype!"); noop.prototype = proto; return new noop(); }; function noop() {} } },{}],53:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var propIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function(to, from) { if (to === null || typeof to === "undefined") { to = {}; } for (var key in from) { if (from.hasOwnProperty(key) && typeof to[key] === "undefined") { to[key] = from[key]; } } if (typeof Object.getOwnPropertySymbols === "function") { var symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { var symbol = symbols[i]; if (from.propertyIsEnumerable(symbol) && typeof to[key] === "undefined") { to[symbol] = from[symbol]; } } } return to; }; },{}],54:[function(require,module,exports){ function _identity(x) { return x; }; var _cache = {}; var _modes = {}; var _easings = {}; function Easing(token) { if (typeof token === 'function') { return token; } if (typeof token !== 'string') { return _identity; } var fn = _cache[token]; if (fn) { return fn; } var match = /^(\w+)(-(in|out|in-out|out-in))?(\((.*)\))?$/i.exec(token); if (!match || !match.length) { return _identity; } var easing = _easings[match[1]]; var mode = _modes[match[3]]; var params = match[5]; if (easing && easing.fn) { fn = easing.fn; } else if (easing && easing.fc) { fn = easing.fc.apply(easing.fc, params && params.replace(/\s+/, '').split(',')); } else { fn = _identity; } if (mode) { fn = mode.fn(fn); } // TODO: It can be a memory leak with different `params`. _cache[token] = fn; return fn; }; Easing.add = function(data) { // TODO: create a map of all { name-mode : data } var names = (data.name || data.mode).split(/\s+/); for (var i = 0; i < names.length; i++) { var name = names[i]; if (name) { (data.name ? _easings : _modes)[name] = data; } } }; Easing.add({ mode : 'in', fn : function(f) { return f; } }); Easing.add({ mode : 'out', fn : function(f) { return function(t) { return 1 - f(1 - t); }; } }); Easing.add({ mode : 'in-out', fn : function(f) { return function(t) { return (t < 0.5) ? (f(2 * t) / 2) : (1 - f(2 * (1 - t)) / 2); }; } }); Easing.add({ mode : 'out-in', fn : function(f) { return function(t) { return (t < 0.5) ? (1 - f(2 * (1 - t)) / 2) : (f(2 * t) / 2); }; } }); Easing.add({ name : 'linear', fn : function(t) { return t; } }); Easing.add({ name : 'quad', fn : function(t) { return t * t; } }); Easing.add({ name : 'cubic', fn : function(t) { return t * t * t; } }); Easing.add({ name : 'quart', fn : function(t) { return t * t * t * t; } }); Easing.add({ name : 'quint', fn : function(t) { return t * t * t * t * t; } }); Easing.add({ name : 'sin sine', fn : function(t) { return 1 - Math.cos(t * Math.PI / 2); } }); Easing.add({ name : 'exp expo', fn : function(t) { return t == 0 ? 0 : Math.pow(2, 10 * (t - 1)); } }); Easing.add({ name : 'circle circ', fn : function(t) { return 1 - Math.sqrt(1 - t * t); } }); Easing.add({ name : 'bounce', fn : function(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } }); Easing.add({ name : 'poly', fc : function(e) { return function(t) { return Math.pow(t, e); }; } }); Easing.add({ name : 'elastic', fc : function(a, p) { p = p || 0.45; a = a || 1; var s = p / (2 * Math.PI) * Math.asin(1 / a); return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p); }; } }); Easing.add({ name : 'back', fc : function(s) { s = typeof s !== 'undefined' ? s : 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } }); module.exports = Easing; },{}],55:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; require('../core')._load(function(stage, elem) { Mouse.subscribe(stage, elem); }); // TODO: capture mouse Mouse.CLICK = 'click'; Mouse.START = 'touchstart mousedown'; Mouse.MOVE = 'touchmove mousemove'; Mouse.END = 'touchend mouseup'; Mouse.CANCEL = 'touchcancel mousecancel'; Mouse.subscribe = function(stage, elem) { if (stage.mouse) { return; } stage.mouse = new Mouse(stage, elem); // `click` events are synthesized from start/end events on same nodes // `mousecancel` events are synthesized on blur or mouseup outside element elem.addEventListener('touchstart', handleStart); elem.addEventListener('touchend', handleEnd); elem.addEventListener('touchmove', handleMove); elem.addEventListener('touchcancel', handleCancel); elem.addEventListener('mousedown', handleStart); elem.addEventListener('mouseup', handleEnd); elem.addEventListener('mousemove', handleMove); document.addEventListener('mouseup', handleCancel); window.addEventListener("blur", handleCancel); var clicklist = [], cancellist = []; function handleStart(event) { event.preventDefault(); stage.mouse.locate(event); // DEBUG && console.log('Mouse Start: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); stage.mouse.lookup('click', clicklist); stage.mouse.lookup('mousecancel', cancellist); } function handleMove(event) { event.preventDefault(); stage.mouse.locate(event); stage.mouse.publish(event.type, event); } function handleEnd(event) { event.preventDefault(); // up/end location is not available, last one is used instead // DEBUG && console.log('Mouse End: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); if (clicklist.length) { // DEBUG && console.log('Mouse Click: ' + clicklist.length); stage.mouse.publish('click', event, clicklist); } cancellist.length = 0; } function handleCancel(event) { if (cancellist.length) { // DEBUG && console.log('Mouse Cancel: ' + event.type); stage.mouse.publish('mousecancel', event, cancellist); } clicklist.length = 0; } }; function Mouse(stage, elem) { if (!(this instanceof Mouse)) { // old-style mouse subscription return; } var ratio = stage.viewport().ratio || 1; stage.on('viewport', function(size) { ratio = size.ratio || ratio; }); this.x = 0; this.y = 0; this.toString = function() { return (this.x | 0) + 'x' + (this.y | 0); }; this.locate = function(event) { locateElevent(elem, event, this); this.x *= ratio; this.y *= ratio; }; this.lookup = function(type, collect) { this.type = type; this.root = stage; this.event = null; collect.length = 0; this.collect = collect; this.root.visit(this.visitor, this); }; this.publish = function(type, event, targets) { this.type = type; this.root = stage; this.event = event; this.collect = false; this.timeStamp = Date.now(); if (type !== 'mousemove' && type !== 'touchmove') { DEBUG && console.log(this.type + ' ' + this); } if (targets) { while (targets.length) if (this.visitor.end(targets.shift(), this)) break; targets.length = 0; } else { this.root.visit(this.visitor, this); } }; this.visitor = { reverse : true, visible : true, start : function(node, mouse) { return !node._flag(mouse.type); }, end : function(node, mouse) { // mouse: event/collect, type, root rel.raw = mouse.event; rel.type = mouse.type; rel.timeStamp = mouse.timeStamp; rel.abs.x = mouse.x; rel.abs.y = mouse.y; var listeners = node.listeners(mouse.type); if (!listeners) { return; } node.matrix().inverse().map(mouse, rel); if (!(node === mouse.root || node.hitTest(rel))) { return; } if (mouse.collect) { mouse.collect.push(node); } if (mouse.event) { var cancel = false; for (var l = 0; l < listeners.length; l++) { cancel = listeners[l].call(node, rel) ? true : cancel; } return cancel; } } }; }; // TODO: define per mouse object with get-only x and y var rel = {}, abs = {}; defineValue(rel, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(rel, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0) + ' (' + this.abs + ')'; }); defineValue(rel, 'abs', abs); defineValue(abs, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(abs, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0); }); function defineValue(obj, name, value) { Object.defineProperty(obj, name, { value : value }); } function locateElevent(el, ev, loc) { // pageX/Y if available? if (ev.touches && ev.touches.length) { loc.x = ev.touches[0].clientX; loc.y = ev.touches[0].clientY; } else { loc.x = ev.clientX; loc.y = ev.clientY; } var rect = el.getBoundingClientRect(); loc.x -= rect.left; loc.y -= rect.top; loc.x -= el.clientLeft | 0; loc.y -= el.clientTop | 0; return loc; }; module.exports = Mouse; },{"../core":60}],56:[function(require,module,exports){ var Easing = require('./easing'); var Class = require('../core'); var Pin = require('../pin'); Class.prototype.tween = function(duration, delay, append) { if (typeof duration !== 'number') { append = duration, delay = 0, duration = 0; } else if (typeof delay !== 'number') { append = delay, delay = 0; } if (!this._tweens) { this._tweens = []; var ticktime = 0; this.tick(function(elapsed, now, last) { if (!this._tweens.length) { return; } // ignore old elapsed var ignore = ticktime != last; ticktime = now; if (ignore) { return true; } var next = this._tweens[0].tick(this, elapsed, now, last); if (next) { this._tweens.shift(); } if (typeof next === 'object') { this._tweens.unshift(next); } return true; }, true); } this.touch(); if (!append) { this._tweens.length = 0; } var tween = new Tween(this, duration, delay); this._tweens.push(tween); return tween; }; function Tween(owner, duration, delay) { this._end = {}; this._duration = duration || 400; this._delay = delay || 0; this._owner = owner; this._time = 0; }; Tween.prototype.tick = function(node, elapsed, now, last) { this._time += elapsed; if (this._time < this._delay) { return; } var time = this._time - this._delay; if (!this._start) { this._start = {}; for ( var key in this._end) { this._start[key] = this._owner.pin(key); } } var p, over; if (time < this._duration) { p = time / this._duration, over = false; } else { p = 1, over = true; } p = typeof this._easing == 'function' ? this._easing(p) : p; var q = 1 - p; for ( var key in this._end) { this._owner.pin(key, this._start[key] * q + this._end[key] * p); } if (over) { try { this._done && this._done.call(this._owner); } catch (e) { console.log(e); } return this._next || true; } }; Tween.prototype.tween = function(duration, delay) { return this._next = new Tween(this._owner, duration, delay); }; Tween.prototype.duration = function(duration) { this._duration = duration; return this; }; Tween.prototype.delay = function(delay) { this._delay = delay; return this; }; Tween.prototype.ease = function(easing) { this._easing = Easing(easing); return this; }; Tween.prototype.done = function(fn) { this._done = fn; return this; }; Tween.prototype.hide = function() { this.done(function() { this.hide(); }); return this; }; Tween.prototype.remove = function() { this.done(function() { this.remove(); }); return this; }; Tween.prototype.pin = function(a, b) { if (typeof a === 'object') { for ( var attr in a) { pinning(this._owner, this._end, attr, a[attr]); } } else if (typeof b !== 'undefined') { pinning(this._owner, this._end, a, b); } return this; }; function pinning(node, map, key, value) { if (typeof node.pin(key) === 'number') { map[key] = value; } else if (typeof node.pin(key + 'X') === 'number' && typeof node.pin(key + 'Y') === 'number') { map[key + 'X'] = value; map[key + 'Y'] = value; } } Pin._add_shortcuts(Tween); /** * @deprecated Use .done(fn) instead. */ Tween.prototype.then = function(fn) { this.done(fn); return this; }; /** * @deprecated Use .done(fn) instead. */ Tween.prototype.then = function(fn) { this.done(fn); return this; }; /** * @deprecated NOOP */ Tween.prototype.clear = function(forward) { return this; }; module.exports = Tween; },{"../core":60,"../pin":68,"./easing":54}],57:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var math = require('./util/math'); Class.anim = function(frames, fps) { var anim = new Anim(); anim.frames(frames).gotoFrame(0); fps && anim.fps(fps); return anim; }; Anim._super = Class; Anim.prototype = create(Anim._super.prototype); // TODO: replace with atlas fps or texture time Class.Anim = { FPS : 15 }; function Anim() { Anim._super.call(this); this.label('Anim'); this._textures = []; this._fps = Class.Anim.FPS; this._ft = 1000 / this._fps; this._time = -1; this._repeat = 0; this._index = 0; this._frames = []; var lastTime = 0; this.tick(function(t, now, last) { if (this._time < 0 || this._frames.length <= 1) { return; } // ignore old elapsed var ignore = lastTime != last; lastTime = now; if (ignore) { return true; } this._time += t; if (this._time < this._ft) { return true; } var n = this._time / this._ft | 0; this._time -= n * this._ft; this.moveFrame(n); if (this._repeat > 0 && (this._repeat -= n) <= 0) { this.stop(); this._callback && this._callback(); return false; } return true; }, false); }; Anim.prototype.fps = function(fps) { if (typeof fps === 'undefined') { return this._fps; } this._fps = fps > 0 ? fps : Class.Anim.FPS; this._ft = 1000 / this._fps; return this; }; /** * @deprecated Use frames */ Anim.prototype.setFrames = function(a, b, c) { return this.frames(a, b, c); }; Anim.prototype.frames = function(frames) { this._index = 0; this._frames = Class.texture(frames).array(); this.touch(); return this; }; Anim.prototype.length = function() { return this._frames ? this._frames.length : 0; }; Anim.prototype.gotoFrame = function(frame, resize) { this._index = math.rotate(frame, this._frames.length) | 0; resize = resize || !this._textures[0]; this._textures[0] = this._frames[this._index]; if (resize) { this.pin('width', this._textures[0].width); this.pin('height', this._textures[0].height); } this.touch(); return this; }; Anim.prototype.moveFrame = function(move) { return this.gotoFrame(this._index + move); }; Anim.prototype.repeat = function(repeat, callback) { this._repeat = repeat * this._frames.length - 1; this._callback = callback; this.play(); return this; }; Anim.prototype.play = function(frame) { if (typeof frame !== 'undefined') { this.gotoFrame(frame); this._time = 0; } else if (this._time < 0) { this._time = 0; } this.touch(); return this; }; Anim.prototype.stop = function(frame) { this._time = -1; if (typeof frame !== 'undefined') { this.gotoFrame(frame); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/math":78}],58:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('./core'); var Texture = require('./texture'); var extend = require('./util/extend'); var create = require('./util/create'); var is = require('./util/is'); var string = require('./util/string'); // name : atlas var _atlases_map = {}; // [atlas] var _atlases_arr = []; // TODO: print subquery not found error // TODO: index textures Class.atlas = function(def) { var atlas = is.fn(def.draw) ? def : new Atlas(def); if (def.name) { _atlases_map[def.name] = atlas; } _atlases_arr.push(atlas); deprecated(def, 'imagePath'); deprecated(def, 'imageRatio'); var url = def.imagePath; var ratio = def.imageRatio || 1; if (is.string(def.image)) { url = def.image; } else if (is.hash(def.image)) { url = def.image.src || def.image.url; ratio = def.image.ratio || ratio; } url && Class.preload(function(done) { url = Class.resolve(url); DEBUG && console.log('Loading atlas: ' + url); var imageloader = Class.config('image-loader'); imageloader(url, function(image) { DEBUG && console.log('Image loaded: ' + url); atlas.src(image, ratio); done(); }, function(err) { DEBUG && console.log('Error loading atlas: ' + url, err); done(); }); }); return atlas; }; Atlas._super = Texture; Atlas.prototype = create(Atlas._super.prototype); function Atlas(def) { Atlas._super.call(this); var atlas = this; deprecated(def, 'filter'); deprecated(def, 'cutouts'); deprecated(def, 'sprites'); deprecated(def, 'factory'); var map = def.map || def.filter; var ppu = def.ppu || def.ratio || 1; var trim = def.trim || 0; var textures = def.textures; var factory = def.factory; var cutouts = def.cutouts || def.sprites; function make(def) { if (!def || is.fn(def.draw)) { return def; } def = extend({}, def); if (is.fn(map)) { def = map(def); } if (ppu != 1) { def.x *= ppu, def.y *= ppu; def.width *= ppu, def.height *= ppu; def.top *= ppu, def.bottom *= ppu; def.left *= ppu, def.right *= ppu; } if (trim != 0) { def.x += trim, def.y += trim; def.width -= 2 * trim, def.height -= 2 * trim; def.top -= trim, def.bottom -= trim; def.left -= trim, def.right -= trim; } var texture = atlas.pipe(); texture.top = def.top, texture.bottom = def.bottom; texture.left = def.left, texture.right = def.right; texture.src(def.x, def.y, def.width, def.height); return texture; } function find(query) { if (textures) { if (is.fn(textures)) { return textures(query); } else if (is.hash(textures)) { return textures[query]; } } if (cutouts) { // deprecated var result = null, n = 0; for (var i = 0; i < cutouts.length; i++) { if (string.startsWith(cutouts[i].name, query)) { if (n === 0) { result = cutouts[i]; } else if (n === 1) { result = [ result, cutouts[i] ]; } else { result.push(cutouts[i]); } n++; } } if (n === 0 && is.fn(factory)) { result = function(subquery) { return factory(query + (subquery ? subquery : '')); }; } return result; } } this.select = function(query) { if (!query) { // TODO: if `textures` is texture def, map or fn? return new Selection(this.pipe()); } var found = find(query); if (found) { return new Selection(found, find, make); } }; }; var nfTexture = new Texture(); nfTexture.x = nfTexture.y = nfTexture.width = nfTexture.height = 0; nfTexture.pipe = nfTexture.src = nfTexture.dest = function() { return this; }; nfTexture.draw = function() { }; var nfSelection = new Selection(nfTexture); function Selection(result, find, make) { function link(result, subquery) { if (!result) { return nfTexture; } else if (is.fn(result.draw)) { return result; } else if (is.hash(result) && is.number(result.width) && is.number(result.height) && is.fn(make)) { return make(result); } else if (is.hash(result) && is.defined(subquery)) { return link(result[subquery]); } else if (is.fn(result)) { return link(result(subquery)); } else if (is.array(result)) { return link(result[0]); } else if (is.string(result) && is.fn(find)) { return link(find(result)); } } this.one = function(subquery) { return link(result, subquery); }; this.array = function(arr) { var array = is.array(arr) ? arr : []; if (is.array(result)) { for (var i = 0; i < result.length; i++) { array[i] = link(result[i]); } } else { array[0] = link(result); } return array; }; } Class.texture = function(query) { if (!is.string(query)) { return new Selection(query); } var result = null, atlas, i; if ((i = query.indexOf(':')) > 0 && query.length > i + 1) { atlas = _atlases_map[query.slice(0, i)]; result = atlas && atlas.select(query.slice(i + 1)); } if (!result && (atlas = _atlases_map[query])) { result = atlas.select(); } for (i = 0; !result && i < _atlases_arr.length; i++) { result = _atlases_arr[i].select(query); } if (!result) { console.error('Texture not found: ' + query); result = nfSelection; } return result; }; function deprecated(hash, name, msg) { if (name in hash) console.log(msg ? msg.replace('%name', name) : '\'' + name + '\' field of texture atlas is deprecated.'); }; module.exports = Atlas; },{"./core":60,"./texture":71,"./util/create":74,"./util/extend":76,"./util/is":77,"./util/string":81}],59:[function(require,module,exports){ var Class = require('./core'); var Texture = require('./texture'); Class.canvas = function(type, attributes, callback) { if (typeof type === 'string') { if (typeof attributes === 'object') { } else { if (typeof attributes === 'function') { callback = attributes; } attributes = {}; } } else { if (typeof type === 'function') { callback = type; } attributes = {}; type = '2d'; } var canvas = document.createElement('canvas'); var context = canvas.getContext(type, attributes); var texture = new Texture(canvas); texture.context = function() { return context; }; texture.size = function(width, height, ratio) { ratio = ratio || 1; canvas.width = width * ratio; canvas.height = height * ratio; this.src(canvas, ratio); return this; }; texture.canvas = function(fn) { if (typeof fn === 'function') { fn.call(this, context); } else if (typeof fn === 'undefined' && typeof callback === 'function') { callback.call(this, context); } return this; }; if (typeof callback === 'function') { callback.call(texture, context); } return texture; }; },{"./core":60,"./texture":71}],60:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var stats = require('./util/stats'); var extend = require('./util/extend'); var is = require('./util/is'); var _await = require('./util/await'); stats.create = 0; function Class(arg) { if (!(this instanceof Class)) { if (is.fn(arg)) { return Class.app.apply(Class, arguments); } else if (is.object(arg)) { return Class.atlas.apply(Class, arguments); } else { return arg; } } stats.create++; for (var i = 0; i < _init.length; i++) { _init[i].call(this); } } var _init = []; Class._init = function(fn) { _init.push(fn); }; var _load = []; Class._load = function(fn) { _load.push(fn); }; var _config = {}; Class.config = function() { if (arguments.length === 1 && is.string(arguments[0])) { return _config[arguments[0]]; } if (arguments.length === 1 && is.object(arguments[0])) { extend(_config, arguments[0]); } if (arguments.length === 2 && is.string(arguments[0])) { _config[arguments[0], arguments[1]]; } }; var _app_queue = []; var _preload_queue = []; var _stages = []; var _loaded = false; var _paused = false; Class.app = function(app, opts) { if (!_loaded) { _app_queue.push(arguments); return; } DEBUG && console.log('Creating app...'); var loader = Class.config('app-loader'); loader(function(stage, canvas) { DEBUG && console.log('Initing app...'); for (var i = 0; i < _load.length; i++) { _load[i].call(this, stage, canvas); } app(stage, canvas); _stages.push(stage); DEBUG && console.log('Starting app...'); stage.start(); }, opts); }; var loading = _await(); Class.preload = function(load) { if (typeof load === 'string') { var url = Class.resolve(load); if (/\.js($|\?|\#)/.test(url)) { DEBUG && console.log('Loading script: ' + url); load = function(callback) { loadScript(url, callback); }; } } if (typeof load !== 'function') { return; } // if (!_started) { // _preload_queue.push(load); // return; // } load(loading()); }; Class.start = function(config) { DEBUG && console.log('Starting...'); Class.config(config); // DEBUG && console.log('Preloading...'); // _started = true; // while (_preload_queue.length) { // var load = _preload_queue.shift(); // load(loading()); // } loading.then(function() { DEBUG && console.log('Loading apps...'); _loaded = true; while (_app_queue.length) { var args = _app_queue.shift(); Class.app.apply(Class, args); } }); }; Class.pause = function() { if (!_paused) { _paused = true; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].pause(); } } }; Class.resume = function() { if (_paused) { _paused = false; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].resume(); } } }; Class.create = function() { return new Class(); }; Class.resolve = (function() { if (typeof window === 'undefined' || typeof document === 'undefined') { return function(url) { return url; }; } var scripts = document.getElementsByTagName('script'); function getScriptSrc() { // HTML5 if (document.currentScript) { return document.currentScript.src; } // IE>=10 var stack; try { var err = new Error(); if (err.stack) { stack = err.stack; } else { throw err; } } catch (err) { stack = err.stack; } if (typeof stack === 'string') { stack = stack.split('\n'); // Uses the last line, where the call started for (var i = stack.length; i--;) { var url = stack[i].match(/(\w+\:\/\/[^/]*?\/.+?)(:\d+)(:\d+)?/); if (url) { return url[1]; } } } // IE<11 if (scripts.length && 'readyState' in scripts[0]) { for (var i = scripts.length; i--;) { if (scripts[i].readyState === 'interactive') { return scripts[i].src; } } } return location.href; } return function(url) { if (/^\.\//.test(url)) { var src = getScriptSrc(); var base = src.substring(0, src.lastIndexOf('/') + 1); url = base + url.substring(2); // } else if (/^\.\.\//.test(url)) { // url = base + url; } return url; }; })(); module.exports = Class; function loadScript(src, callback) { var el = document.createElement('script'); el.addEventListener('load', function() { callback(); }); el.addEventListener('error', function(err) { callback(err || 'Error loading script: ' + src); }); el.src = src; el.id = 'preload-' + Date.now(); document.body.appendChild(el); }; },{"./util/await":73,"./util/extend":76,"./util/is":77,"./util/stats":80}],61:[function(require,module,exports){ require('./util/event')(require('./core').prototype, function(obj, name, on) { obj._flag(name, on); }); },{"./core":60,"./util/event":75}],62:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var repeat = require('./util/repeat'); var create = require('./util/create'); Class.image = function(image) { var img = new Image(); image && img.image(image); return img; }; Image._super = Class; Image.prototype = create(Image._super.prototype); function Image() { Image._super.call(this); this.label('Image'); this._textures = []; this._image = null; }; /** * @deprecated Use image */ Image.prototype.setImage = function(a, b, c) { return this.image(a, b, c); }; Image.prototype.image = function(image) { this._image = Class.texture(image).one(); this.pin('width', this._image ? this._image.width : 0); this.pin('height', this._image ? this._image.height : 0); this._textures[0] = this._image.pipe(); this._textures.length = 1; return this; }; Image.prototype.tile = function(inner) { this._repeat(false, inner); return this; }; Image.prototype.stretch = function(inner) { this._repeat(true, inner); return this; }; Image.prototype._repeat = function(stretch, inner) { var self = this; this.untick(this._repeatTicker); this.tick(this._repeatTicker = function() { if (this._mo_stretch == this._pin._ts_transform) { return; } this._mo_stretch = this._pin._ts_transform; var width = this.pin('width'); var height = this.pin('height'); this._textures.length = repeat(this._image, width, height, stretch, inner, insert); }); function insert(i, sx, sy, sw, sh, dx, dy, dw, dh) { var repeat = self._textures.length > i ? self._textures[i] : self._textures[i] = self._image.pipe(); repeat.src(sx, sy, sw, sh); repeat.dest(dx, dy, dw, dh); } }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/repeat":79}],63:[function(require,module,exports){ module.exports = require('./core'); module.exports.Matrix = require('./matrix'); module.exports.Texture = require('./texture'); require('./atlas'); require('./tree'); require('./event'); require('./pin'); require('./loop'); require('./root'); },{"./atlas":58,"./core":60,"./event":61,"./loop":66,"./matrix":67,"./pin":68,"./root":69,"./texture":71,"./tree":72}],64:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); Class.row = function(align) { return Class.create().row(align).label('Row'); }; Class.prototype.row = function(align) { this.sequence('row', align); return this; }; Class.column = function(align) { return Class.create().column(align).label('Row'); }; Class.prototype.column = function(align) { this.sequence('column', align); return this; }; Class.sequence = function(type, align) { return Class.create().sequence(type, align).label('Sequence'); }; Class.prototype.sequence = function(type, align) { this._padding = this._padding || 0; this._spacing = this._spacing || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_seq == this._ts_touch) { return; } this._mo_seq = this._ts_touch; var alignChildren = (this._mo_seqAlign != this._ts_children); this._mo_seqAlign = this._ts_children; var width = 0, height = 0; var child, next = this.first(true); var first = true; while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); if (type == 'column') { !first && (height += this._spacing); child.pin('offsetY') != height && child.pin('offsetY', height); width = Math.max(width, w); height = height + h; alignChildren && child.pin('alignX', align); } else if (type == 'row') { !first && (width += this._spacing); child.pin('offsetX') != width && child.pin('offsetX', width); width = width + w; height = Math.max(height, h); alignChildren && child.pin('alignY', align); } first = false; } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.box = function() { return Class.create().box().label('Box'); }; Class.prototype.box = function() { this._padding = this._padding || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_box == this._ts_touch) { return; } this._mo_box = this._ts_touch; var width = 0, height = 0; var child, next = this.first(true); while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); width = Math.max(width, w); height = Math.max(height, h); } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.layer = function() { return Class.create().layer().label('Layer'); }; Class.prototype.layer = function() { this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { var parent = this.parent(); if (parent) { var width = parent.pin('width'); if (this.pin('width') != width) { this.pin('width', width); } var height = parent.pin('height'); if (this.pin('height') != height) { this.pin('height', height); } } }, true); return this; }; // TODO: move padding to pin Class.prototype.padding = function(pad) { this._padding = pad; return this; }; Class.prototype.spacing = function(space) { this._spacing = space; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74}],65:[function(require,module,exports){ /** * Default loader for web. */ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('../core'); Class._supported = (function() { var elem = document.createElement('canvas'); return (elem.getContext && elem.getContext('2d')) ? true : false; })(); window.addEventListener('load', function() { DEBUG && console.log('On load.'); if (Class._supported) { Class.start(); } // TODO if not supported }, false); Class.config({ 'app-loader' : AppLoader, 'image-loader' : ImageLoader }); function AppLoader(app, configs) { configs = configs || {}; var canvas = configs.canvas, context = null, full = false; var width = 0, height = 0, ratio = 1; if (typeof canvas === 'string') { canvas = document.getElementById(canvas); } if (!canvas) { canvas = document.getElementById('cutjs') || document.getElementById('stage'); } if (!canvas) { full = true; DEBUG && console.log('Creating Canvas...'); canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = '0'; canvas.style.left = '0'; var body = document.body; body.insertBefore(canvas, body.firstChild); } context = canvas.getContext('2d'); var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; ratio = devicePixelRatio / backingStoreRatio; var requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; DEBUG && console.log('Creating stage...'); var root = Class.root(requestAnimationFrame, render); function render() { context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, width, height); root.render(context); } root.background = function(color) { canvas.style.backgroundColor = color; return this; }; app(root, canvas); resize(); window.addEventListener('resize', resize, false); window.addEventListener('orientationchange', resize, false); function resize() { if (full) { // screen.availWidth/Height? width = (window.innerWidth > 0 ? window.innerWidth : screen.width); height = (window.innerHeight > 0 ? window.innerHeight : screen.height); canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; } else { width = canvas.clientWidth; height = canvas.clientHeight; } width *= ratio; height *= ratio; if (canvas.width === width && canvas.height === height) { return; } canvas.width = width; canvas.height = height; DEBUG && console.log('Resize: ' + width + ' x ' + height + ' / ' + ratio); root.viewport(width, height, ratio); render(); } } function ImageLoader(src, success, error) { DEBUG && console.log('Loading image: ' + src); var image = new Image(); image.onload = function() { success(image); }; image.onerror = error; image.src = src; } },{"../core":60}],66:[function(require,module,exports){ var Class = require('./core'); require('./pin'); var stats = require('./util/stats'); Class.prototype._textures = null; Class.prototype._alpha = 1; Class.prototype.render = function(context) { if (!this._visible) { return; } stats.node++; var m = this.matrix(); context.setTransform(m.a, m.b, m.c, m.d, m.e, m.f); // move this elsewhere! this._alpha = this._pin._alpha * (this._parent ? this._parent._alpha : 1); var alpha = this._pin._textureAlpha * this._alpha; if (context.globalAlpha != alpha) { context.globalAlpha = alpha; } if (this._textures !== null) { for (var i = 0, n = this._textures.length; i < n; i++) { this._textures[i].draw(context); } } if (context.globalAlpha != this._alpha) { context.globalAlpha = this._alpha; } var child, next = this._first; while (child = next) { next = child._next; child.render(context); } }; Class.prototype._tickBefore = null; Class.prototype._tickAfter = null; Class.prototype.MAX_ELAPSE = Infinity; Class.prototype._tick = function(elapsed, now, last) { if (!this._visible) { return; } if (elapsed > this.MAX_ELAPSE) { elapsed = this.MAX_ELAPSE; } var ticked = false; if (this._tickBefore !== null) { for (var i = 0, n = this._tickBefore.length; i < n; i++) { stats.tick++; ticked = this._tickBefore[i].call(this, elapsed, now, last) === true || ticked; } } var child, next = this._first; while (child = next) { next = child._next; if (child._flag('_tick')) { ticked = child._tick(elapsed, now, last) === true ? true : ticked; } } if (this._tickAfter !== null) { for (var i = 0, n = this._tickAfter.length; i < n; i++) { stats.tick++; ticked = this._tickAfter[i].call(this, elapsed, now, last) === true || ticked; } } return ticked; }; Class.prototype.tick = function(ticker, before) { if (typeof ticker !== 'function') { return; } if (before) { if (this._tickBefore === null) { this._tickBefore = []; } this._tickBefore.push(ticker); } else { if (this._tickAfter === null) { this._tickAfter = []; } this._tickAfter.push(ticker); } this._flag('_tick', this._tickAfter !== null && this._tickAfter.length > 0 || this._tickBefore !== null && this._tickBefore.length > 0); }; Class.prototype.untick = function(ticker) { if (typeof ticker !== 'function') { return; } var i; if (this._tickBefore !== null && (i = this._tickBefore.indexOf(ticker)) >= 0) { this._tickBefore.splice(i, 1); } if (this._tickAfter !== null && (i = this._tickAfter.indexOf(ticker)) >= 0) { this._tickAfter.splice(i, 1); } }; Class.prototype.timeout = function(fn, time) { this.tick(function timer(t) { if ((time -= t) < 0) { this.untick(timer); fn.call(this); } else { return true; } }); }; },{"./core":60,"./pin":68,"./util/stats":80}],67:[function(require,module,exports){ function Matrix(a, b, c, d, e, f) { this.reset(a, b, c, d, e, f); }; Matrix.prototype.toString = function() { return '[' + this.a + ', ' + this.b + ', ' + this.c + ', ' + this.d + ', ' + this.e + ', ' + this.f + ']'; }; Matrix.prototype.clone = function() { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; Matrix.prototype.reset = function(a, b, c, d, e, f) { this._dirty = true; if (typeof a === 'object') { this.a = a.a, this.d = a.d; this.b = a.b, this.c = a.c; this.e = a.e, this.f = a.f; } else { this.a = a || 1, this.d = d || 1; this.b = b || 0, this.c = c || 0; this.e = e || 0, this.f = f || 0; } return this; }; Matrix.prototype.identity = function() { this._dirty = true; this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.e = 0; this.f = 0; return this; }; Matrix.prototype.rotate = function(angle) { if (!angle) { return this; } this._dirty = true; var u = angle ? Math.cos(angle) : 1; // android bug may give bad 0 values var v = angle ? Math.sin(angle) : 0; var a = u * this.a - v * this.b; var b = u * this.b + v * this.a; var c = u * this.c - v * this.d; var d = u * this.d + v * this.c; var e = u * this.e - v * this.f; var f = u * this.f + v * this.e; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.translate = function(x, y) { if (!x && !y) { return this; } this._dirty = true; this.e += x; this.f += y; return this; }; Matrix.prototype.scale = function(x, y) { if (!(x - 1) && !(y - 1)) { return this; } this._dirty = true; this.a *= x; this.b *= y; this.c *= x; this.d *= y; this.e *= x; this.f *= y; return this; }; Matrix.prototype.skew = function(x, y) { if (!x && !y) { return this; } this._dirty = true; var a = this.a + this.b * x; var b = this.b + this.a * y; var c = this.c + this.d * x; var d = this.d + this.c * y; var e = this.e + this.f * x; var f = this.f + this.e * y; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.concat = function(m) { this._dirty = true; var n = this; var a = n.a * m.a + n.b * m.c; var b = n.b * m.d + n.a * m.b; var c = n.c * m.a + n.d * m.c; var d = n.d * m.d + n.c * m.b; var e = n.e * m.a + m.e + n.f * m.c; var f = n.f * m.d + m.f + n.e * m.b; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.inverse = Matrix.prototype.reverse = function() { if (this._dirty) { this._dirty = false; this.inversed = this.inversed || new Matrix(); var z = this.a * this.d - this.b * this.c; this.inversed.a = this.d / z; this.inversed.b = -this.b / z; this.inversed.c = -this.c / z; this.inversed.d = this.a / z; this.inversed.e = (this.c * this.f - this.e * this.d) / z; this.inversed.f = (this.e * this.b - this.a * this.f) / z; } return this.inversed; }; Matrix.prototype.map = function(p, q) { q = q || {}; q.x = this.a * p.x + this.c * p.y + this.e; q.y = this.b * p.x + this.d * p.y + this.f; return q; }; Matrix.prototype.mapX = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.a * x + this.c * y + this.e; }; Matrix.prototype.mapY = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.b * x + this.d * y + this.f; }; module.exports = Matrix; },{}],68:[function(require,module,exports){ var Class = require('./core'); var Matrix = require('./matrix'); var iid = 0; Class._init(function() { this._pin = new Pin(this); }); Class.prototype.matrix = function(relative) { if (relative === true) { return this._pin.relativeMatrix(); } return this._pin.absoluteMatrix(); }; Class.prototype.pin = function(a, b) { if (typeof a === 'object') { this._pin.set(a); return this; } else if (typeof a === 'string') { if (typeof b === 'undefined') { return this._pin.get(a); } else { this._pin.set(a, b); return this; } } else if (typeof a === 'undefined') { return this._pin; } }; function Pin(owner) { this._owner = owner; this._parent = null; // relative to parent this._relativeMatrix = new Matrix(); // relative to stage this._absoluteMatrix = new Matrix(); this.reset(); }; Pin.prototype.reset = function() { this._textureAlpha = 1; this._alpha = 1; this._width = 0; this._height = 0; this._scaleX = 1; this._scaleY = 1; this._skewX = 0; this._skewY = 0; this._rotation = 0; // scale/skew/rotate center this._pivoted = false; this._pivotX = null; this._pivotY = null; // self pin point this._handled = false; this._handleX = 0; this._handleY = 0; // parent pin point this._aligned = false; this._alignX = 0; this._alignY = 0; // as seen by parent px this._offsetX = 0; this._offsetY = 0; this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; // TODO: also set for owner this._ts_translate = ++iid; this._ts_transform = ++iid; this._ts_matrix = ++iid; }; Pin.prototype._update = function() { this._parent = this._owner._parent && this._owner._parent._pin; // if handled and transformed then be translated if (this._handled && this._mo_handle != this._ts_transform) { this._mo_handle = this._ts_transform; this._ts_translate = ++iid; } if (this._aligned && this._parent && this._mo_align != this._parent._ts_transform) { this._mo_align = this._parent._ts_transform; this._ts_translate = ++iid; } return this; }; Pin.prototype.toString = function() { return this._owner + ' (' + (this._parent ? this._parent._owner : null) + ')'; }; // TODO: ts fields require refactoring Pin.prototype.absoluteMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_matrix : 0); if (this._mo_abs == ts) { return this._absoluteMatrix; } this._mo_abs = ts; var abs = this._absoluteMatrix; abs.reset(this.relativeMatrix()); this._parent && abs.concat(this._parent._absoluteMatrix); this._ts_matrix = ++iid; return abs; }; Pin.prototype.relativeMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_transform : 0); if (this._mo_rel == ts) { return this._relativeMatrix; } this._mo_rel = ts; var rel = this._relativeMatrix; rel.identity(); if (this._pivoted) { rel.translate(-this._pivotX * this._width, -this._pivotY * this._height); } rel.scale(this._scaleX, this._scaleY); rel.skew(this._skewX, this._skewY); rel.rotate(this._rotation); if (this._pivoted) { rel.translate(this._pivotX * this._width, this._pivotY * this._height); } // calculate effective box if (this._pivoted) { // origin this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; } else { // aabb var p, q; if (rel.a > 0 && rel.c > 0 || rel.a < 0 && rel.c < 0) { p = 0, q = rel.a * this._width + rel.c * this._height; } else { p = rel.a * this._width, q = rel.c * this._height; } if (p > q) { this._boxX = q; this._boxWidth = p - q; } else { this._boxX = p; this._boxWidth = q - p; } if (rel.b > 0 && rel.d > 0 || rel.b < 0 && rel.d < 0) { p = 0, q = rel.b * this._width + rel.d * this._height; } else { p = rel.b * this._width, q = rel.d * this._height; } if (p > q) { this._boxY = q; this._boxHeight = p - q; } else { this._boxY = p; this._boxHeight = q - p; } } this._x = this._offsetX; this._y = this._offsetY; this._x -= this._boxX + this._handleX * this._boxWidth; this._y -= this._boxY + this._handleY * this._boxHeight; if (this._aligned && this._parent) { this._parent.relativeMatrix(); this._x += this._alignX * this._parent._width; this._y += this._alignY * this._parent._height; } rel.translate(this._x, this._y); return this._relativeMatrix; }; Pin.prototype.get = function(key) { if (typeof getters[key] === 'function') { return getters[key](this); } }; // TODO: Use defineProperty instead? What about multi-field pinning? Pin.prototype.set = function(a, b) { if (typeof a === 'string') { if (typeof setters[a] === 'function' && typeof b !== 'undefined') { setters[a](this, b); } } else if (typeof a === 'object') { for (b in a) { if (typeof setters[b] === 'function' && typeof a[b] !== 'undefined') { setters[b](this, a[b], a); } } } if (this._owner) { this._owner._ts_pin = ++iid; this._owner.touch(); } return this; }; var getters = { alpha : function(pin) { return pin._alpha; }, textureAlpha : function(pin) { return pin._textureAlpha; }, width : function(pin) { return pin._width; }, height : function(pin) { return pin._height; }, boxWidth : function(pin) { return pin._boxWidth; }, boxHeight : function(pin) { return pin._boxHeight; }, // scale : function(pin) { // }, scaleX : function(pin) { return pin._scaleX; }, scaleY : function(pin) { return pin._scaleY; }, // skew : function(pin) { // }, skewX : function(pin) { return pin._skewX; }, skewY : function(pin) { return pin._skewY; }, rotation : function(pin) { return pin._rotation; }, // pivot : function(pin) { // }, pivotX : function(pin) { return pin._pivotX; }, pivotY : function(pin) { return pin._pivotY; }, // offset : function(pin) { // }, offsetX : function(pin) { return pin._offsetX; }, offsetY : function(pin) { return pin._offsetY; }, // align : function(pin) { // }, alignX : function(pin) { return pin._alignX; }, alignY : function(pin) { return pin._alignY; }, // handle : function(pin) { // }, handleX : function(pin) { return pin._handleX; }, handleY : function(pin) { return pin._handleY; } }; var setters = { alpha : function(pin, value) { pin._alpha = value; }, textureAlpha : function(pin, value) { pin._textureAlpha = value; }, width : function(pin, value) { pin._width_ = value; pin._width = value; pin._ts_transform = ++iid; }, height : function(pin, value) { pin._height_ = value; pin._height = value; pin._ts_transform = ++iid; }, scale : function(pin, value) { pin._scaleX = value; pin._scaleY = value; pin._ts_transform = ++iid; }, scaleX : function(pin, value) { pin._scaleX = value; pin._ts_transform = ++iid; }, scaleY : function(pin, value) { pin._scaleY = value; pin._ts_transform = ++iid; }, skew : function(pin, value) { pin._skewX = value; pin._skewY = value; pin._ts_transform = ++iid; }, skewX : function(pin, value) { pin._skewX = value; pin._ts_transform = ++iid; }, skewY : function(pin, value) { pin._skewY = value; pin._ts_transform = ++iid; }, rotation : function(pin, value) { pin._rotation = value; pin._ts_transform = ++iid; }, pivot : function(pin, value) { pin._pivotX = value; pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotX : function(pin, value) { pin._pivotX = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotY : function(pin, value) { pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, offset : function(pin, value) { pin._offsetX = value; pin._offsetY = value; pin._ts_translate = ++iid; }, offsetX : function(pin, value) { pin._offsetX = value; pin._ts_translate = ++iid; }, offsetY : function(pin, value) { pin._offsetY = value; pin._ts_translate = ++iid; }, align : function(pin, value) { this.alignX(pin, value); this.alignY(pin, value); }, alignX : function(pin, value) { pin._alignX = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleX(pin, value); }, alignY : function(pin, value) { pin._alignY = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleY(pin, value); }, handle : function(pin, value) { this.handleX(pin, value); this.handleY(pin, value); }, handleX : function(pin, value) { pin._handleX = value; pin._handled = true; pin._ts_translate = ++iid; }, handleY : function(pin, value) { pin._handleY = value; pin._handled = true; pin._ts_translate = ++iid; }, resizeMode : function(pin, value, all) { if (all) { if (value == 'in') { value = 'in-pad'; } else if (value == 'out') { value = 'out-crop'; } scaleTo(pin, all.resizeWidth, all.resizeHeight, value); } }, resizeWidth : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, value, null); } }, resizeHeight : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, null, value); } }, scaleMode : function(pin, value, all) { if (all) { scaleTo(pin, all.scaleWidth, all.scaleHeight, value); } }, scaleWidth : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, value, null); } }, scaleHeight : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, null, value); } }, matrix : function(pin, value) { this.scaleX(pin, value.a); this.skewX(pin, value.c / value.d); this.skewY(pin, value.b / value.a); this.scaleY(pin, value.d); this.offsetX(pin, value.e); this.offsetY(pin, value.f); this.rotation(pin, 0); } }; function scaleTo(pin, width, height, mode) { var w = typeof width === 'number'; var h = typeof height === 'number'; var m = typeof mode === 'string'; pin._ts_transform = ++iid; if (w) { pin._scaleX = width / pin._width_; pin._width = pin._width_; } if (h) { pin._scaleY = height / pin._height_; pin._height = pin._height_; } if (w && h && m) { if (mode == 'out' || mode == 'out-crop') { pin._scaleX = pin._scaleY = Math.max(pin._scaleX, pin._scaleY); } else if (mode == 'in' || mode == 'in-pad') { pin._scaleX = pin._scaleY = Math.min(pin._scaleX, pin._scaleY); } if (mode == 'out-crop' || mode == 'in-pad') { pin._width = width / pin._scaleX; pin._height = height / pin._scaleY; } } }; Class.prototype.scaleTo = function(a, b, c) { if (typeof a === 'object') c = b, b = a.y, a = a.x; scaleTo(this._pin, a, b, c); return this; }; // Used by Tween class Pin._add_shortcuts = function(Class) { Class.prototype.size = function(w, h) { this.pin('width', w); this.pin('height', h); return this; }; Class.prototype.width = function(w) { if (typeof w === 'undefined') { return this.pin('width'); } this.pin('width', w); return this; }; Class.prototype.height = function(h) { if (typeof h === 'undefined') { return this.pin('height'); } this.pin('height', h); return this; }; Class.prototype.offset = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; this.pin('offsetX', a); this.pin('offsetY', b); return this; }; Class.prototype.rotate = function(a) { this.pin('rotation', a); return this; }; Class.prototype.skew = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('skewX', a); this.pin('skewY', b); return this; }; Class.prototype.scale = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('scaleX', a); this.pin('scaleY', b); return this; }; Class.prototype.alpha = function(a, ta) { this.pin('alpha', a); if (typeof ta !== 'undefined') { this.pin('textureAlpha', ta); } return this; }; }; Pin._add_shortcuts(Class); module.exports = Pin; },{"./core":60,"./matrix":67}],69:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var stats = require('./util/stats'); var create = require('./util/create'); var extend = require('./util/extend'); Root._super = Class; Root.prototype = create(Root._super.prototype); Class.root = function(request, render) { return new Root(request, render); }; function Root(request, render) { Root._super.call(this); this.label('Root'); var paused = true; var self = this; var lastTime = 0; var loop = function(now) { if (paused === true) { return; } stats.tick = stats.node = stats.draw = 0; var last = lastTime || now; var elapsed = now - last; lastTime = now; var ticked = self._tick(elapsed, now, last); if (self._mo_touch != self._ts_touch) { self._mo_touch = self._ts_touch; render(self); request(loop); } else if (ticked) { request(loop); } else { paused = true; } stats.fps = elapsed ? 1000 / elapsed : 0; }; this.start = function() { return this.resume(); }; this.resume = function() { if (paused) { this.publish('resume'); paused = false; request(loop); } return this; }; this.pause = function() { if (!paused) { this.publish('pause'); } paused = true; return this; }; this.touch_root = this.touch; this.touch = function() { this.resume(); return this.touch_root(); }; }; Root.prototype.background = function(color) { // to be implemented by loaders return this; }; Root.prototype.viewport = function(width, height, ratio) { if (typeof width === 'undefined') { return extend({}, this._viewport); } this._viewport = { width : width, height : height, ratio : ratio || 1 }; this.viewbox(); var data = extend({}, this._viewport); this.visit({ start : function(node) { if (!node._flag('viewport')) { return true; } node.publish('viewport', [ data ]); } }); return this; }; // TODO: static/fixed viewbox Root.prototype.viewbox = function(width, height, mode) { if (typeof width === 'number' && typeof height === 'number') { this._viewbox = { width : width, height : height, mode : /^(in|out|in-pad|out-crop)$/.test(mode) ? mode : 'in-pad' }; } var box = this._viewbox; var size = this._viewport; if (size && box) { this.pin({ width : box.width, height : box.height }); this.scaleTo(size.width, size.height, box.mode); } else if (size) { this.pin({ width : size.width, height : size.height }); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/extend":76,"./util/stats":80}],70:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var is = require('./util/is'); Class.string = function(frames) { return new Str().frames(frames); }; Str._super = Class; Str.prototype = create(Str._super.prototype); function Str() { Str._super.call(this); this.label('String'); this._textures = []; }; /** * @deprecated Use frames */ Str.prototype.setFont = function(a, b, c) { return this.frames(a, b, c); }; Str.prototype.frames = function(frames) { this._textures = []; if (typeof frames == 'string') { frames = Class.texture(frames); this._item = function(value) { return frames.one(value); }; } else if (typeof frames === 'object') { this._item = function(value) { return frames[value]; }; } else if (typeof frames === 'function') { this._item = frames; } return this; }; /** * @deprecated Use value */ Str.prototype.setValue = function(a, b, c) { return this.value(a, b, c); }; Str.prototype.value = function(value) { if (typeof value === 'undefined') { return this._value; } if (this._value === value) { return this; } this._value = value; if (value === null) { value = ''; } else if (typeof value !== 'string' && !is.array(value)) { value = value.toString(); } this._spacing = this._spacing || 0; var width = 0, height = 0; for (var i = 0; i < value.length; i++) { var image = this._textures[i] = this._item(value[i]); width += i > 0 ? this._spacing : 0; image.dest(width, 0); width = width + image.width; height = Math.max(height, image.height); } this.pin('width', width); this.pin('height', height); this._textures.length = value.length; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/is":77}],71:[function(require,module,exports){ var stats = require('./util/stats'); var math = require('./util/math'); function Texture(image, ratio) { if (typeof image === 'object') { this.src(image, ratio); } } Texture.prototype.pipe = function() { return new Texture(this); }; /** * Signatures: (image), (x, y, w, h), (w, h) */ Texture.prototype.src = function(x, y, w, h) { if (typeof x === 'object') { var image = x, ratio = y || 1; this._image = image; this._sx = this._dx = 0; this._sy = this._dy = 0; this._sw = this._dw = image.width / ratio; this._sh = this._dh = image.height / ratio; this.width = image.width / ratio; this.height = image.height / ratio; this.ratio = ratio; } else { if (typeof w === 'undefined') { w = x, h = y; } else { this._sx = x, this._sy = y; } this._sw = this._dw = w; this._sh = this._dh = h; this.width = w; this.height = h; } return this; }; /** * Signatures: (x, y, w, h), (x, y) */ Texture.prototype.dest = function(x, y, w, h) { this._dx = x, this._dy = y; this._dx = x, this._dy = y; if (typeof w !== 'undefined') { this._dw = w, this._dh = h; this.width = w, this.height = h; } return this; }; Texture.prototype.draw = function(context, x1, y1, x2, y2, x3, y3, x4, y4) { var image = this._image; if (image === null || typeof image !== 'object') { return; } var sx = this._sx, sy = this._sy; var sw = this._sw, sh = this._sh; var dx = this._dx, dy = this._dy; var dw = this._dw, dh = this._dh; if (typeof x3 !== 'undefined') { x1 = math.limit(x1, 0, this._sw), x2 = math.limit(x2, 0, this._sw - x1); y1 = math.limit(y1, 0, this._sh), y2 = math.limit(y2, 0, this._sh - y1); sx += x1, sy += y1, sw = x2, sh = y2; dx = x3, dy = y3, dw = x4, dh = y4; } else if (typeof x2 !== 'undefined') { dx = x1, dy = y1, dw = x2, dh = y2; } else if (typeof x1 !== 'undefined') { dw = x1, dh = y1; } var ratio = this.ratio || 1; sx *= ratio, sy *= ratio, sw *= ratio, sh *= ratio; try { if (typeof image.draw === 'function') { image.draw(context, sx, sy, sw, sh, dx, dy, dw, dh); } else { stats.draw++; context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh); } } catch (ex) { if (!image._draw_failed) { console.log('Unable to draw: ', image); console.log(ex); image._draw_failed = true; } } }; module.exports = Texture; },{"./util/math":78,"./util/stats":80}],72:[function(require,module,exports){ var Class = require('./core'); var is = require('./util/is'); var iid = 0; // TODO: do not clear next/prev/parent on remove Class.prototype._label = ''; Class.prototype._visible = true; Class.prototype._parent = null; Class.prototype._next = null; Class.prototype._prev = null; Class.prototype._first = null; Class.prototype._last = null; Class.prototype._attrs = null; Class.prototype._flags = null; Class.prototype.toString = function() { return '[' + this._label + ']'; }; /** * @deprecated Use label() */ Class.prototype.id = function(id) { return this.label(id); }; Class.prototype.label = function(label) { if (typeof label === 'undefined') { return this._label; } this._label = label; return this; }; Class.prototype.attr = function(name, value) { if (typeof value === 'undefined') { return this._attrs !== null ? this._attrs[name] : undefined; } (this._attrs !== null ? this._attrs : this._attrs = {})[name] = value; return this; }; Class.prototype.visible = function(visible) { if (typeof visible === 'undefined') { return this._visible; } this._visible = visible; this._parent && (this._parent._ts_children = ++iid); this._ts_pin = ++iid; this.touch(); return this; }; Class.prototype.hide = function() { return this.visible(false); }; Class.prototype.show = function() { return this.visible(true); }; Class.prototype.parent = function() { return this._parent; }; Class.prototype.next = function(visible) { var next = this._next; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.prev = function(visible) { var prev = this._prev; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.first = function(visible) { var next = this._first; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.last = function(visible) { var prev = this._last; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.visit = function(visitor, data) { var reverse = visitor.reverse; var visible = visitor.visible; if (visitor.start && visitor.start(this, data)) { return; } var child, next = reverse ? this.last(visible) : this.first(visible); while (child = next) { next = reverse ? child.prev(visible) : child.next(visible); if (child.visit(visitor, data)) { return true; } } return visitor.end && visitor.end(this, data); }; Class.prototype.append = function(child, more) { if (is.array(child)) for (var i = 0; i < child.length; i++) append(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) append(this, arguments[i]); else if (typeof child !== 'undefined') append(this, child); return this; }; Class.prototype.prepend = function(child, more) { if (is.array(child)) for (var i = child.length - 1; i >= 0; i--) prepend(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) prepend(this, arguments[i]); else if (typeof child !== 'undefined') prepend(this, child); return this; }; Class.prototype.appendTo = function(parent) { append(parent, this); return this; }; Class.prototype.prependTo = function(parent) { prepend(parent, this); return this; }; Class.prototype.insertNext = function(sibling, more) { if (is.array(sibling)) for (var i = 0; i < sibling.length; i++) insertAfter(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) insertAfter(arguments[i], this); else if (typeof sibling !== 'undefined') insertAfter(sibling, this); return this; }; Class.prototype.insertPrev = function(sibling, more) { if (is.array(sibling)) for (var i = sibling.length - 1; i >= 0; i--) insertBefore(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) insertBefore(arguments[i], this); else if (typeof sibling !== 'undefined') insertBefore(sibling, this); return this; }; Class.prototype.insertAfter = function(prev) { insertAfter(this, prev); return this; }; Class.prototype.insertBefore = function(next) { insertBefore(this, next); return this; }; function append(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._last) { parent._last._next = child; child._prev = parent._last; } child._parent = parent; parent._last = child; if (!parent._first) { parent._first = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); } function prepend(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._first) { parent._first._prev = child; child._next = parent._first; } child._parent = parent; parent._first = child; if (!parent._last) { parent._last = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); }; function insertBefore(self, next) { _ensure(self); _ensure(next); self.remove(); var parent = next._parent; var prev = next._prev; next._prev = self; prev && (prev._next = self) || parent && (parent._first = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; function insertAfter(self, prev) { _ensure(self); _ensure(prev); self.remove(); var parent = prev._parent; var next = prev._next; prev._next = self; next && (next._prev = self) || parent && (parent._last = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; Class.prototype.remove = function(child, more) { if (typeof child !== 'undefined') { if (is.array(child)) { for (var i = 0; i < child.length; i++) _ensure(child[i]).remove(); } else if (typeof more !== 'undefined') { for (var i = 0; i < arguments.length; i++) _ensure(arguments[i]).remove(); } else { _ensure(child).remove(); } return this; } if (this._prev) { this._prev._next = this._next; } if (this._next) { this._next._prev = this._prev; } if (this._parent) { if (this._parent._first === this) { this._parent._first = this._next; } if (this._parent._last === this) { this._parent._last = this._prev; } this._parent._flag(this, false); this._parent._ts_children = ++iid; this._parent.touch(); } this._prev = this._next = this._parent = null; this._ts_parent = ++iid; // this._parent.touch(); return this; }; Class.prototype.empty = function() { var child, next = this._first; while (child = next) { next = child._next; child._prev = child._next = child._parent = null; this._flag(child, false); } this._first = this._last = null; this._ts_children = ++iid; this.touch(); return this; }; Class.prototype.touch = function() { this._ts_touch = ++iid; this._parent && this._parent.touch(); return this; }; /** * Deep flags used for optimizing event distribution. */ Class.prototype._flag = function(obj, name) { if (typeof name === 'undefined') { return this._flags !== null && this._flags[obj] || 0; } if (typeof obj === 'string') { if (name) { this._flags = this._flags || {}; if (!this._flags[obj] && this._parent) { this._parent._flag(obj, true); } this._flags[obj] = (this._flags[obj] || 0) + 1; } else if (this._flags && this._flags[obj] > 0) { if (this._flags[obj] == 1 && this._parent) { this._parent._flag(obj, false); } this._flags[obj] = this._flags[obj] - 1; } } if (typeof obj === 'object') { if (obj._flags) { for ( var type in obj._flags) { if (obj._flags[type] > 0) { this._flag(type, name); } } } } return this; }; /** * @private */ Class.prototype.hitTest = function(hit) { if (this.attr('spy')) { return true; } return hit.x >= 0 && hit.x <= this._pin._width && hit.y >= 0 && hit.y <= this._pin._height; }; function _ensure(obj) { if (obj && obj instanceof Class) { return obj; } throw 'Invalid node: ' + obj; }; module.exports = Class; },{"./core":60,"./util/is":77}],73:[function(require,module,exports){ module.exports = function() { var count = 0; function fork(fn, n) { count += n = (typeof n === 'number' && n >= 1 ? n : 1); return function() { fn && fn.apply(this, arguments); if (n > 0) { n--, count--, call(); } }; } var then = []; function call() { if (count === 0) { while (then.length) { setTimeout(then.shift(), 0); } } } fork.then = function(fn) { if (count === 0) { setTimeout(fn, 0); } else { then.push(fn); } }; return fork; }; },{}],74:[function(require,module,exports){ if (typeof Object.create == 'function') { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error('Second argument is not supported!'); if (typeof proto !== 'object' || proto === null) throw Error('Invalid prototype!'); noop.prototype = proto; return new noop; }; function noop() { } } },{}],75:[function(require,module,exports){ module.exports = function(prototype, callback) { prototype._listeners = null; prototype.on = prototype.listen = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { this._listeners = {}; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i]; this._listeners[type] = this._listeners[type] || []; this._listeners[type].push(listener); if (typeof callback === 'function') { callback(this, type, true); } } } return this; }; prototype.off = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { return this; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i], all = this._listeners[type], index; if (all && (index = all.indexOf(listener)) >= 0) { all.splice(index, 1); if (!all.length) { delete this._listeners[type]; } if (typeof callback === 'function') { callback(this, type, false); } } } } return this; }; prototype.listeners = function(type) { return this._listeners && this._listeners[type]; }; prototype.publish = function(name, args) { var listeners = this.listeners(name); if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].apply(this, args); } return listeners.length; }; prototype.trigger = function(name, args) { this.publish(name, args); return this; }; }; },{}],76:[function(require,module,exports){ module.exports = function(base) { for (var i = 1; i < arguments.length; i++) { var obj = arguments[i]; for ( var key in obj) { if (obj.hasOwnProperty(key)) { base[key] = obj[key]; } } } return base; }; },{}],77:[function(require,module,exports){ /** * ! is the definitive JavaScript type testing library * * @copyright 2013-2014 Enrico Marino / Jordan Harband * @license MIT */ var objProto = Object.prototype; var owns = objProto.hasOwnProperty; var toStr = objProto.toString; var NON_HOST_TYPES = { 'boolean' : 1, 'number' : 1, 'string' : 1, 'undefined' : 1 }; var hexRegex = /^[A-Fa-f0-9]+$/; var is = module.exports = {}; is.a = is.an = is.type = function(value, type) { return typeof value === type; }; is.defined = function(value) { return typeof value !== 'undefined'; }; is.empty = function(value) { var type = toStr.call(value); var key; if ('[object Array]' === type || '[object Arguments]' === type || '[object String]' === type) { return value.length === 0; } if ('[object Object]' === type) { for (key in value) { if (owns.call(value, key)) { return false; } } return true; } return !value; }; is.equal = function(value, other) { if (value === other) { return true; } var type = toStr.call(value); var key; if (type !== toStr.call(other)) { return false; } if ('[object Object]' === type) { for (key in value) { if (!is.equal(value[key], other[key]) || !(key in other)) { return false; } } for (key in other) { if (!is.equal(value[key], other[key]) || !(key in value)) { return false; } } return true; } if ('[object Array]' === type) { key = value.length; if (key !== other.length) { return false; } while (--key) { if (!is.equal(value[key], other[key])) { return false; } } return true; } if ('[object Function]' === type) { return value.prototype === other.prototype; } if ('[object Date]' === type) { return value.getTime() === other.getTime(); } return false; }; is.instance = function(value, constructor) { return value instanceof constructor; }; is.nil = function(value) { return value === null; }; is.undef = function(value) { return typeof value === 'undefined'; }; is.array = function(value) { return '[object Array]' === toStr.call(value); }; is.emptyarray = function(value) { return is.array(value) && value.length === 0; }; is.arraylike = function(value) { return !!value && !is.boolean(value) && owns.call(value, 'length') && isFinite(value.length) && is.number(value.length) && value.length >= 0; }; is.boolean = function(value) { return '[object Boolean]' === toStr.call(value); }; is.element = function(value) { return value !== undefined && typeof HTMLElement !== 'undefined' && value instanceof HTMLElement && value.nodeType === 1; }; is.fn = function(value) { return '[object Function]' === toStr.call(value); }; is.number = function(value) { return '[object Number]' === toStr.call(value); }; is.nan = function(value) { return !is.number(value) || value !== value; }; is.object = function(value) { return '[object Object]' === toStr.call(value); }; is.hash = function(value) { return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval; }; is.regexp = function(value) { return '[object RegExp]' === toStr.call(value); }; is.string = function(value) { return '[object String]' === toStr.call(value); }; is.hex = function(value) { return is.string(value) && (!value.length || hexRegex.test(value)); }; },{}],78:[function(require,module,exports){ var create = require('./create'); var native = Math; module.exports = create(Math); module.exports.random = function(min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } return min == max ? min : native.random() * (max - min) + min; }; module.exports.rotate = function(num, min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; module.exports.limit = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; module.exports.length = function(x, y) { return native.sqrt(x * x + y * y); }; },{"./create":74}],79:[function(require,module,exports){ module.exports = function(img, owidth, oheight, stretch, inner, insert) { var width = img.width; var height = img.height; var left = img.left; var right = img.right; var top = img.top; var bottom = img.bottom; left = typeof left === 'number' && left === left ? left : 0; right = typeof right === 'number' && right === right ? right : 0; top = typeof top === 'number' && top === top ? top : 0; bottom = typeof bottom === 'number' && bottom === bottom ? bottom : 0; width = width - left - right; height = height - top - bottom; if (!inner) { owidth = Math.max(owidth - left - right, 0); oheight = Math.max(oheight - top - bottom, 0); } var i = 0; if (top > 0 && left > 0) insert(i++, 0, 0, left, top, 0, 0, left, top); if (bottom > 0 && left > 0) insert(i++, 0, height + top, left, bottom, 0, oheight + top, left, bottom); if (top > 0 && right > 0) insert(i++, width + left, 0, right, top, owidth + left, 0, right, top); if (bottom > 0 && right > 0) insert(i++, width + left, height + top, right, bottom, owidth + left, oheight + top, right, bottom); if (stretch) { if (top > 0) insert(i++, left, 0, width, top, left, 0, owidth, top); if (bottom > 0) insert(i++, left, height + top, width, bottom, left, oheight + top, owidth, bottom); if (left > 0) insert(i++, 0, top, left, height, 0, top, left, oheight); if (right > 0) insert(i++, width + left, top, right, height, owidth + left, top, right, oheight); // center insert(i++, left, top, width, height, left, top, owidth, oheight); } else { // tile var l = left, r = owidth, w; while (r > 0) { w = Math.min(width, r), r -= width; var t = top, b = oheight, h; while (b > 0) { h = Math.min(height, b), b -= height; insert(i++, left, top, w, h, l, t, w, h); if (r <= 0) { if (left) insert(i++, 0, top, left, h, 0, t, left, h); if (right) insert(i++, width + left, top, right, h, l + w, t, right, h); } t += h; } if (top) insert(i++, left, 0, w, top, l, 0, w, top); if (bottom) insert(i++, left, height + top, w, bottom, l, t, w, bottom); l += w; } } return i; }; },{}],80:[function(require,module,exports){ module.exports = {}; },{}],81:[function(require,module,exports){ module.exports.startsWith = function(str, sub) { return typeof str === 'string' && typeof sub === 'string' && str.substring(0, sub.length) == sub; }; },{}],82:[function(require,module,exports){ module.exports = require('../lib/'); require('../lib/canvas'); require('../lib/image'); require('../lib/anim'); require('../lib/str'); require('../lib/layout'); require('../lib/addon/tween'); module.exports.Mouse = require('../lib/addon/mouse'); module.exports.Math = require('../lib/util/math'); module.exports._extend = require('../lib/util/extend'); module.exports._create = require('../lib/util/create'); require('../lib/loader/web'); },{"../lib/":63,"../lib/addon/mouse":55,"../lib/addon/tween":56,"../lib/anim":57,"../lib/canvas":59,"../lib/image":62,"../lib/layout":64,"../lib/loader/web":65,"../lib/str":70,"../lib/util/create":74,"../lib/util/extend":76,"../lib/util/math":78}]},{},[1])(1) });
PeterDaveHello/jsdelivr
files/planck/0.1.34/planck-with-testbed.js
JavaScript
mit
464,606
module.exports = function isString (value) { return Object.prototype.toString.call(value) === '[object String]' }
chrisdavidmills/express-local-library
node_modules/helmet-csp/lib/is-string.js
JavaScript
mit
116
// Generated by CoffeeScript 1.4.0 (function() { var RoomIO; RoomIO = require('./room').RoomIO; exports.RequestIO = (function() { function RequestIO(socket, request, io) { this.socket = socket; this.request = request; this.manager = io; } RequestIO.prototype.broadcast = function(event, message) { return this.socket.broadcast.emit(event, message); }; RequestIO.prototype.emit = function(event, message) { return this.socket.emit(event, message); }; RequestIO.prototype.room = function(room) { return new RoomIO(room, this.socket); }; RequestIO.prototype.join = function(room) { return this.socket.join(room); }; RequestIO.prototype.route = function(route) { return this.manager.route(route, this.request, { trigger: true }); }; RequestIO.prototype.leave = function(room) { return this.socket.leave(room); }; RequestIO.prototype.on = function() { var args; args = Array.prototype.slice.call(arguments, 0); return this.sockets.on.apply(this.socket, args); }; RequestIO.prototype.disconnect = function(callback) { return this.socket.disconnect(callback); }; return RequestIO; })(); }).call(this);
mekinney/transparica
webapp/node_modules/express.io/compiled/request.js
JavaScript
gpl-2.0
1,285
// Inspired from https://github.com/tsi/inlineDisqussions (function () { 'use strict'; var website = openerp.website, qweb = openerp.qweb; website.blog_discussion = openerp.Class.extend({ init: function(options) { var self = this ; self.discus_identifier; var defaults = { position: 'right', post_id: $('#blog_post_name').attr('data-blog-id'), content : false, public_user: false, }; self.settings = $.extend({}, defaults, options); // TODO: bundlify qweb templates website.add_template_file('/website_blog/static/src/xml/website_blog.inline.discussion.xml').then(function () { self.do_render(self); }); }, do_render: function(data) { var self = this; if ($('#discussions_wrapper').length === 0 && self.settings.content.length > 0) { $('<div id="discussions_wrapper"></div>').insertAfter($('#blog_content')); } // Attach a discussion to each paragraph. self.discussions_handler(self.settings.content); // Hide the discussion. $('html').click(function(event) { if($(event.target).parents('#discussions_wrapper, .main-discussion-link-wrp').length === 0) { self.hide_discussion(); } if(!$(event.target).hasClass('discussion-link') && !$(event.target).parents('.popover').length){ if($('.move_discuss').length){ $('[enable_chatter_discuss=True]').removeClass('move_discuss'); $('[enable_chatter_discuss=True]').animate({ 'marginLeft': "+=40%" }); $('#discussions_wrapper').animate({ 'marginLeft': "+=250px" }); } } }); }, prepare_data : function(identifier, comment_count) { var self = this; return openerp.jsonRpc("/blogpost/get_discussion/", 'call', { 'post_id': self.settings.post_id, 'path': identifier, 'count': comment_count, //if true only get length of total comment, display on discussion thread. }) }, prepare_multi_data : function(identifiers, comment_count) { var self = this; return openerp.jsonRpc("/blogpost/get_discussions/", 'call', { 'post_id': self.settings.post_id, 'paths': identifiers, 'count': comment_count, //if true only get length of total comment, display on discussion thread. }) }, discussions_handler: function() { var self = this; var node_by_id = {}; $(self.settings.content).each(function(i) { var node = $(this); var identifier = node.attr('data-chatter-id'); if (identifier) { node_by_id[identifier] = node; } }); self.prepare_multi_data(_.keys(node_by_id), true).then( function (multi_data) { _.forEach(multi_data, function(data) { self.prepare_discuss_link(data.val, data.path, node_by_id[data.path]); }); }); }, prepare_discuss_link : function(data, identifier, node) { var self = this; var cls = data > 0 ? 'discussion-link has-comments' : 'discussion-link'; var a = $('<a class="'+ cls +' css_editable_mode_hidden" />') .attr('data-discus-identifier', identifier) .attr('data-discus-position', self.settings.position) .text(data > 0 ? data : '+') .attr('data-contentwrapper', '.mycontent') .wrap('<div class="discussion" />') .parent() .appendTo('#discussions_wrapper'); a.css({ 'top': node.offset().top, 'left': self.settings.position == 'right' ? node.outerWidth() + node.offset().left: node.offset().left - a.outerWidth() }); // node.attr('data-discus-identifier', identifier) node.mouseover(function() { a.addClass("hovered"); }).mouseout(function() { a.removeClass("hovered"); }); a.delegate('a.discussion-link', "click", function(e) { e.preventDefault(); if(!$('.move_discuss').length){ $('[enable_chatter_discuss=True]').addClass('move_discuss'); $('[enable_chatter_discuss=True]').animate({ 'marginLeft': "-=40%" }); $('#discussions_wrapper').animate({ 'marginLeft': "-=250px" }); } if ($(this).is('.active')) { e.stopPropagation(); self.hide_discussion(); } else { self.get_discussion($(this), function(source) {}); } }); }, get_discussion : function(source, callback) { var self = this; var identifier = source.attr('data-discus-identifier'); self.hide_discussion(); self.discus_identifier = identifier; var elt = $('a[data-discus-identifier="'+identifier+'"]'); elt.append(qweb.render("website.blog_discussion.popover", {'identifier': identifier , 'options': self.settings})); var comment = ''; self.prepare_data(identifier,false).then(function(data){ _.each(data, function(res){ comment += qweb.render("website.blog_discussion.comment", {'res': res}); }); $('.discussion_history').html('<ul class="media-list">'+comment+'</ul>'); self.create_popover(elt, identifier); // Add 'active' class. $('a.discussion-link, a.main-discussion-link').removeClass('active').filter(source).addClass('active'); elt.popover('hide').filter(source).popover('show'); callback(source); }); }, create_popover : function(elt, identifier) { var self = this; elt.popover({ placement:'right', trigger:'manual', html:true, content:function(){ return $($(this).data('contentwrapper')).html(); } }).parent().delegate(self).on('click','button#comment_post',function(e) { e.stopImmediatePropagation(); self.post_discussion(identifier); }); }, validate : function(public_user){ var comment = $(".popover textarea#inline_comment").val(); if (public_user){ var author_name = $('.popover input#author_name').val(); var author_email = $('.popover input#author_email').val(); if(!comment || !author_name || !author_email){ if (!author_name) $('div#author_name').addClass('has-error'); else $('div#author_name').removeClass('has-error'); if (!author_email) $('div#author_email').addClass('has-error'); else $('div#author_email').removeClass('has-error'); if(!comment) $('div#inline_comment').addClass('has-error'); else $('div#inline_comment').removeClass('has-error'); return false } } else if(!comment) { $('div#inline_comment').addClass('has-error'); return false } $("div#inline_comment").removeClass('has-error'); $('div#author_name').removeClass('has-error'); $('div#author_email').removeClass('has-error'); $(".popover textarea#inline_comment").val(''); $('.popover input#author_name').val(''); $('.popover input#author_email').val(''); return [comment, author_name, author_email] }, post_discussion : function(identifier) { var self = this; var val = self.validate(self.settings.public_user) if(!val) return openerp.jsonRpc("/blogpost/post_discussion", 'call', { 'blog_post_id': self.settings.post_id, 'path': self.discus_identifier, 'comment': val[0], 'name' : val[1], 'email': val[2], }).then(function(res){ $(".popover ul.media-list").prepend(qweb.render("website.blog_discussion.comment", {'res': res[0]})) var ele = $('a[data-discus-identifier="'+ self.discus_identifier +'"]'); ele.text(_.isNaN(parseInt(ele.text())) ? 1 : parseInt(ele.text())+1) ele.addClass('has-comments'); }); }, hide_discussion : function() { var self = this; $('a[data-discus-identifier="'+ self.discus_identifier+'"]').popover('destroy'); $('a.discussion-link').removeClass('active'); } }); })();
jjscarafia/odoo
addons/website_blog/static/src/js/website_blog.inline.discussion.js
JavaScript
agpl-3.0
9,713
/* @flow */ function a(x: {[key: string]: ?string}, y: string): string { if (x[y]) { return x[y]; } return ""; } function b(x: {y: {[key: string]: ?string}}, z: string): string { if (x.y[z]) { return x.y[z]; } return ""; } function c(x: {[key: string]: ?string}, y: {z: string}): string { if (x[y.z]) { return x[y.z]; } return ""; } function d(x: {y: {[key: string]: ?string}}, a: {b: string}): string { if (x.y[a.b]) { return x.y[a.b]; } return ""; } function a_array(x: Array<?string>, y: number): string { if (x[y]) { return x[y]; } return ""; } function b_array(x: {y: Array<?string>}, z: number): string { if (x.y[z]) { return x.y[z]; } return ""; } function c_array(x: Array<?string>, y: {z: number}): string { if (x[y.z]) { return x[y.z]; } return ""; } function d_array(x: {y: Array<?string>}, a: {b: number}): string { if (x.y[a.b]) { return x.y[a.b]; } return ""; } // --- name-sensitive havoc --- function c2(x: {[key: string]: ?string}, y: {z: string}): string { if (x[y.z]) { y.z = "HEY"; return x[y.z]; // error } return ""; } function c3(x: {[key: string]: ?string}, y: {z: string, a: string}): string { if (x[y.z]) { y.a = "HEY"; return x[y.z]; // ok } return ""; }
JohnyDays/flow
tests/refinements/property.js
JavaScript
bsd-3-clause
1,303
//################################################################################################################## // #TOOLBAR# /* global CMS */ (function ($) { 'use strict'; // CMS.$ will be passed for $ $(document).ready(function () { /*! * Toolbar * Handles all features related to the toolbar */ CMS.Toolbar = new CMS.Class({ implement: [CMS.API.Helpers], options: { preventSwitch: false, preventSwitchMessage: 'Switching is disabled.', messageDelay: 2000 }, initialize: function (options) { this.container = $('#cms-toolbar'); this.options = $.extend(true, {}, this.options, options); this.config = CMS.config; this.settings = CMS.settings; // elements this.body = $('html'); this.toolbar = this.container.find('.cms-toolbar').hide(); this.toolbarTrigger = this.container.find('.cms-toolbar-trigger'); this.navigations = this.container.find('.cms-toolbar-item-navigation'); this.buttons = this.container.find('.cms-toolbar-item-buttons'); this.switcher = this.container.find('.cms-toolbar-item-switch'); this.messages = this.container.find('.cms-messages'); this.screenBlock = this.container.find('.cms-screenblock'); // states this.click = 'click.cms'; this.timer = function () {}; this.lockToolbar = false; // setup initial stuff this._setup(); // setup events this._events(); }, // initial methods _setup: function () { // setup toolbar visibility, we need to reverse the options to set the correct state (this.settings.toolbar === 'expanded') ? this._showToolbar(0, true) : this._hideToolbar(0, true); // hide publish button var publishBtn = $('.cms-btn-publish').parent(); publishBtn.hide(); if ($('.cms-btn-publish-active').length) { publishBtn.show(); } // check if debug is true if (CMS.config.debug) { this._debug(); } // check if there are messages and display them if (CMS.config.messages) { this.openMessage(CMS.config.messages); } // check if there are error messages and display them if (CMS.config.error) { this.showError(CMS.config.error); } // enforce open state if user is not logged in but requests the toolbar if (!CMS.config.auth || CMS.config.settings.version !== this.settings.version) { this.toggleToolbar(true); this.settings = this.setSettings(CMS.config.settings); } // should switcher indicate that there is an unpublished page? if (CMS.config.publisher) { this.openMessage(CMS.config.publisher, 'right'); setInterval(function () { CMS.$('.cms-toolbar-item-switch').toggleClass('cms-toolbar-item-switch-highlight'); }, this.options.messageDelay); } // open sideframe if it was previously opened if (this.settings.sideframe.url) { var sideframe = new CMS.Sideframe(); sideframe.open(this.settings.sideframe.url, false); } // if there is a screenblock, do some resize magic if (this.screenBlock.length) { this._screenBlock(); } // add toolbar ready class to body and fire event this.body.addClass('cms-ready'); $(document).trigger('cms-ready'); }, _events: function () { var that = this; // attach event to the trigger handler this.toolbarTrigger.bind(this.click, function (e) { e.preventDefault(); that.toggleToolbar(); }); // attach event to the navigation elements this.navigations.each(function () { var item = $(this); var lists = item.find('li'); var root = 'cms-toolbar-item-navigation'; var hover = 'cms-toolbar-item-navigation-hover'; var disabled = 'cms-toolbar-item-navigation-disabled'; var children = 'cms-toolbar-item-navigation-children'; // remove events from first level item.find('a').bind(that.click, function (e) { e.preventDefault(); if ($(this).attr('href') !== '' && $(this).attr('href') !== '#' && !$(this).parent().hasClass(disabled) && !$(this).parent().hasClass(disabled)) { that._delegate($(this)); reset(); return false; } }); // handle click states lists.bind(that.click, function (e) { e.stopPropagation(); var el = $(this); // close if el is first item if (el.parent().hasClass(root) && el.hasClass(hover) || el.hasClass(disabled)) { reset(); return false; } else { reset(); el.addClass(hover); } // activate hover selection item.find('> li').bind('mouseenter', function () { // cancel if item is already active if ($(this).hasClass(hover)) { return false; } $(this).trigger(that.click); }); // create the document event $(document).bind(that.click, reset); }); // attach hover lists.find('li').bind('mouseenter mouseleave', function () { var el = $(this); var parent = el.closest('.cms-toolbar-item-navigation-children') .add(el.parents('.cms-toolbar-item-navigation-children')); var hasChildren = el.hasClass(children) || parent.length; // do not attach hover effect if disabled // cancel event if element has already hover class if (el.hasClass(disabled) || el.hasClass(hover)) { return false; } // reset lists.find('li').removeClass(hover); // add hover effect el.addClass(hover); // handle children elements if (hasChildren) { el.find('> ul').show(); // add parent class parent.addClass(hover); } else { lists.find('ul ul').hide(); } // Remove stale submenus el.siblings().find('> ul').hide(); }); // fix leave event lists.find('> ul').bind('mouseleave', function () { lists.find('li').removeClass(hover); }); // removes classes and events function reset() { lists.removeClass(hover); lists.find('ul ul').hide(); item.find('> li').unbind('mouseenter'); $(document).unbind(that.click); } }); // attach event to the switcher elements this.switcher.each(function () { $(this).bind(that.click, function (e) { e.preventDefault(); that._setSwitcher($(e.currentTarget)); }); }); // attach event for first page publish this.buttons.each(function () { var btn = $(this); // in case the button has a data-rel attribute if (btn.find('a').attr('data-rel')) { btn.on('click', function (e) { e.preventDefault(); that._delegate($(this).find('a')); }); } // in case of the publish button btn.find('.cms-publish-page').bind(that.click, function (e) { if (!confirm(that.config.lang.publish)) { e.preventDefault(); } }); btn.find('.cms-btn-publish').bind(that.click, function (e) { e.preventDefault(); // send post request to prevent xss attacks $.ajax({ 'type': 'post', 'url': $(this).prop('href'), 'data': { 'csrfmiddlewaretoken': CMS.config.csrf }, 'success': function () { CMS.API.Helpers.reloadBrowser(); }, 'error': function (request) { throw new Error(request); } }); }); }); }, // public methods toggleToolbar: function (show) { // overwrite state when provided if (show) { this.settings.toolbar = 'collapsed'; } // toggle bar (this.settings.toolbar === 'collapsed') ? this._showToolbar(200) : this._hideToolbar(200); }, openMessage: function (msg, dir, delay, error) { // set toolbar freeze this._lock(true); // add content to element this.messages.find('.cms-messages-inner').html(msg); // clear timeout clearTimeout(this.timer); // determine width var that = this; var width = 320; var height = this.messages.outerHeight(true); var top = this.toolbar.outerHeight(true); var close = this.messages.find('.cms-messages-close'); close.hide(); close.bind(this.click, function () { that.closeMessage(); }); // set top to 0 if toolbar is collapsed if (this.settings.toolbar === 'collapsed') { top = 0; } // do we need to add debug styles? if (this.config.debug) { top = top + 5; } // set correct position and show this.messages.css('top', -height).show(); // error handling this.messages.removeClass('cms-messages-error'); if (error) { this.messages.addClass('cms-messages-error'); } // dir should be left, center, right dir = dir || 'center'; // set correct direction and animation switch (dir) { case 'left': this.messages.css({ 'top': top, 'left': -width, 'right': 'auto', 'margin-left': 0 }); this.messages.animate({ 'left': 0 }); break; case 'right': this.messages.css({ 'top': top, 'right': -width, 'left': 'auto', 'margin-left': 0 }); this.messages.animate({ 'right': 0 }); break; default: this.messages.css({ 'left': '50%', 'right': 'auto', 'margin-left': -(width / 2) }); this.messages.animate({ 'top': top }); } // cancel autohide if delay is 0 if (delay === 0) { close.show(); return false; } // add delay to hide this.timer = setTimeout(function () { that.closeMessage(); }, delay || this.options.messageDelay); }, closeMessage: function () { this.messages.fadeOut(300); // unlock toolbar this._lock(false); }, openAjax: function (url, post, text, callback, onSuccess) { var that = this; // check if we have a confirmation text var question = (text) ? confirm(text) : true; // cancel if question has been denied if (!question) { return false; } // set loader this._loader(true); $.ajax({ 'type': 'POST', 'url': url, 'data': (post) ? JSON.parse(post) : {}, 'success': function (response) { CMS.API.locked = false; if (callback) { callback(that, response); that._loader(false); } else if (onSuccess) { CMS.API.Helpers.reloadBrowser(onSuccess, false, true); } else { // reload CMS.API.Helpers.reloadBrowser(false, false, true); } }, 'error': function (jqXHR) { CMS.API.locked = false; that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText); } }); }, showError: function (msg, reload) { this.openMessage(msg, 'center', 0, true); // force reload if param is passed if (reload) { CMS.API.Helpers.reloadBrowser(false, this.options.messageDelay); } }, // private methods _showToolbar: function (speed, init) { this.toolbarTrigger.addClass('cms-toolbar-trigger-expanded'); this.toolbar.slideDown(speed); // animate html this.body.animate({ 'margin-top': (this.config.debug) ? 35 : 30 }, (init) ? 0 : speed, function () { $(this).addClass('cms-toolbar-expanded'); }); // set messages top to toolbar height this.messages.css('top', 31); // set new settings this.settings.toolbar = 'expanded'; if (!init) { this.settings = this.setSettings(this.settings); } }, _hideToolbar: function (speed, init) { // cancel if sideframe is active if (this.lockToolbar) { return false; } this.toolbarTrigger.removeClass('cms-toolbar-trigger-expanded'); this.toolbar.slideUp(speed); // animate html this.body.removeClass('cms-toolbar-expanded') .animate({ 'margin-top': (this.config.debug) ? 5 : 0 }, speed); // set messages top to 0 this.messages.css('top', 0); // set new settings this.settings.toolbar = 'collapsed'; if (!init) { this.settings = this.setSettings(this.settings); } }, _setSwitcher: function (el) { // save local vars var active = el.hasClass('cms-toolbar-item-switch-active'); var anchor = el.find('a'); var knob = el.find('.cms-toolbar-item-switch-knob'); var duration = 300; // prevent if switchopstion is passed if (this.options.preventSwitch) { this.openMessage(this.options.preventSwitchMessage, 'right'); return false; } // determin what to trigger if (active) { knob.animate({ 'right': anchor.outerWidth(true) - (knob.outerWidth(true) + 2) }, duration); // move anchor behind the knob anchor.css('z-index', 1).animate({ 'padding-top': 6, 'padding-right': 14, 'padding-bottom': 4, 'padding-left': 28 }, duration); } else { knob.animate({ 'left': anchor.outerWidth(true) - (knob.outerWidth(true) + 2) }, duration); // move anchor behind the knob anchor.css('z-index', 1).animate({ 'padding-top': 6, 'padding-right': 28, 'padding-bottom': 4, 'padding-left': 14 }, duration); } // reload setTimeout(function () { window.location.href = anchor.attr('href'); }, duration); }, _delegate: function (el) { // save local vars var target = el.data('rel'); switch (target) { case 'modal': var modal = new CMS.Modal({'onClose': el.data('on-close')}); modal.open(el.attr('href'), el.data('name')); break; case 'message': this.openMessage(el.data('text')); break; case 'sideframe': var sideframe = new CMS.Sideframe({'onClose': el.data('on-close')}); sideframe.open(el.attr('href'), true); break; case 'ajax': this.openAjax(el.attr('href'), JSON.stringify( el.data('post')), el.data('text'), null, el.data('on-success') ); break; default: window.location.href = el.attr('href'); } }, _lock: function (lock) { if (lock) { this.lockToolbar = true; // make button look disabled this.toolbarTrigger.css('opacity', 0.2); } else { this.lockToolbar = false; // make button look disabled this.toolbarTrigger.css('opacity', 1); } }, _loader: function (loader) { if (loader) { this.toolbarTrigger.addClass('cms-toolbar-loader'); } else { this.toolbarTrigger.removeClass('cms-toolbar-loader'); } }, _debug: function () { var that = this; var timeout = 1000; var timer = function () {}; // bind message event var debug = this.container.find('.cms-debug-bar'); debug.bind('mouseenter mouseleave', function (e) { clearTimeout(timer); if (e.type === 'mouseenter') { timer = setTimeout(function () { that.openMessage(that.config.lang.debug); }, timeout); } }); }, _screenBlock: function () { var interval = 20; var blocker = this.screenBlock; var sideframe = $('.cms-sideframe'); // automatically resize screenblock window according to given attributes $(window).on('resize.cms.screenblock', function () { var width = $(this).width() - sideframe.width(); blocker.css({ 'width': width, 'height': $(window).height() }); }).trigger('resize'); // set update interval setInterval(function () { $(window).trigger('resize.cms.screenblock'); }, interval); } }); }); })(CMS.$);
josjevv/django-cms
cms/static/cms/js/modules/cms.toolbar.js
JavaScript
bsd-3-clause
22,476
import foo from "foo"; import {default as foo2} from "foo";
hawkrives/6to5
test/fixtures/transformation/es6-modules-umd/imports-default/actual.js
JavaScript
mit
60
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-onclickoutside"), require("moment")); else if(typeof define === 'function' && define.amd) define(["react", "react-onclickoutside", "moment"], factory); else if(typeof exports === 'object') exports["DatePicker"] = factory(require("react"), require("react-onclickoutside"), require("moment")); else root["DatePicker"] = factory(root["React"], root["onClickOutside"], root["moment"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_11__, __WEBPACK_EXTERNAL_MODULE_13__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _calendar = __webpack_require__(1); var _calendar2 = _interopRequireDefault(_calendar); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _popper_component = __webpack_require__(21); var _popper_component2 = _interopRequireDefault(_popper_component); var _classnames2 = __webpack_require__(10); var _classnames3 = _interopRequireDefault(_classnames2); var _date_utils = __webpack_require__(12); var _reactOnclickoutside = __webpack_require__(11); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var outsideClickIgnoreClass = 'react-datepicker-ignore-onclickoutside'; var WrappedCalendar = (0, _reactOnclickoutside2.default)(_calendar2.default); /** * General datepicker component. */ var DatePicker = function (_React$Component) { _inherits(DatePicker, _React$Component); _createClass(DatePicker, null, [{ key: 'defaultProps', get: function get() { return { allowSameDay: false, dateFormat: 'L', dateFormatCalendar: 'MMMM YYYY', onChange: function onChange() {}, disabled: false, disabledKeyboardNavigation: false, dropdownMode: 'scroll', onFocus: function onFocus() {}, onBlur: function onBlur() {}, onKeyDown: function onKeyDown() {}, onSelect: function onSelect() {}, onClickOutside: function onClickOutside() {}, onMonthChange: function onMonthChange() {}, monthsShown: 1, withPortal: false, shouldCloseOnSelect: true, showTimeSelect: false, timeIntervals: 30 }; } }]); function DatePicker(props) { _classCallCheck(this, DatePicker); var _this = _possibleConstructorReturn(this, (DatePicker.__proto__ || Object.getPrototypeOf(DatePicker)).call(this, props)); _this.getPreSelection = function () { return _this.props.openToDate ? (0, _date_utils.newDate)(_this.props.openToDate) : _this.props.selectsEnd && _this.props.startDate ? (0, _date_utils.newDate)(_this.props.startDate) : _this.props.selectsStart && _this.props.endDate ? (0, _date_utils.newDate)(_this.props.endDate) : (0, _date_utils.now)(_this.props.utcOffset); }; _this.calcInitialState = function () { var defaultPreSelection = _this.getPreSelection(); var minDate = (0, _date_utils.getEffectiveMinDate)(_this.props); var maxDate = (0, _date_utils.getEffectiveMaxDate)(_this.props); var boundedPreSelection = minDate && (0, _date_utils.isBefore)(defaultPreSelection, minDate) ? minDate : maxDate && (0, _date_utils.isAfter)(defaultPreSelection, maxDate) ? maxDate : defaultPreSelection; return { open: _this.props.startOpen || false, preventFocus: false, preSelection: _this.props.selected ? (0, _date_utils.newDate)(_this.props.selected) : boundedPreSelection }; }; _this.clearPreventFocusTimeout = function () { if (_this.preventFocusTimeout) { clearTimeout(_this.preventFocusTimeout); } }; _this.setFocus = function () { _this.input.focus(); }; _this.setOpen = function (open) { _this.setState({ open: open, preSelection: open && _this.state.open ? _this.state.preSelection : _this.calcInitialState().preSelection }); }; _this.handleFocus = function (event) { if (!_this.state.preventFocus) { _this.props.onFocus(event); _this.setOpen(true); } }; _this.cancelFocusInput = function () { clearTimeout(_this.inputFocusTimeout); _this.inputFocusTimeout = null; }; _this.deferFocusInput = function () { _this.cancelFocusInput(); _this.inputFocusTimeout = setTimeout(function () { return _this.setFocus(); }, 1); }; _this.handleDropdownFocus = function () { _this.cancelFocusInput(); }; _this.handleBlur = function (event) { if (_this.state.open) { _this.deferFocusInput(); } else { _this.props.onBlur(event); } }; _this.handleCalendarClickOutside = function (event) { if (!_this.props.inline) { _this.setOpen(false); } _this.props.onClickOutside(event); if (_this.props.withPortal) { event.preventDefault(); } }; _this.handleChange = function (event) { if (_this.props.onChangeRaw) { _this.props.onChangeRaw(event); if (event.isDefaultPrevented()) { return; } } _this.setState({ inputValue: event.target.value }); var date = (0, _date_utils.parseDate)(event.target.value, _this.props); if (date || !event.target.value) { _this.setSelected(date, event, true); } }; _this.handleSelect = function (date, event) { // Preventing onFocus event to fix issue // https://github.com/Hacker0x01/react-datepicker/issues/628 _this.setState({ preventFocus: true }, function () { _this.preventFocusTimeout = setTimeout(function () { return _this.setState({ preventFocus: false }); }, 50); return _this.preventFocusTimeout; }); _this.setSelected(date, event); if (!_this.props.shouldCloseOnSelect) { _this.setPreSelection(date); } else if (!_this.props.inline) { _this.setOpen(false); } }; _this.setSelected = function (date, event, keepInput) { var changedDate = date; if (changedDate !== null && (0, _date_utils.isDayDisabled)(changedDate, _this.props)) { return; } if (!(0, _date_utils.isSameDay)(_this.props.selected, changedDate) || _this.props.allowSameDay) { if (changedDate !== null) { if (_this.props.selected) { changedDate = (0, _date_utils.setTime)((0, _date_utils.newDate)(changedDate), { hour: (0, _date_utils.getHour)(_this.props.selected), minute: (0, _date_utils.getMinute)(_this.props.selected), second: (0, _date_utils.getSecond)(_this.props.selected) }); } _this.setState({ preSelection: changedDate }); } _this.props.onChange(changedDate, event); } _this.props.onSelect(changedDate, event); if (!keepInput) { _this.setState({ inputValue: null }); } }; _this.setPreSelection = function (date) { var isDateRangePresent = typeof _this.props.minDate !== 'undefined' && typeof _this.props.maxDate !== 'undefined'; var isValidDateSelection = isDateRangePresent && date ? (0, _date_utils.isDayInRange)(date, _this.props.minDate, _this.props.maxDate) : true; if (isValidDateSelection) { _this.setState({ preSelection: date }); } }; _this.handleTimeChange = function (time) { var selected = _this.props.selected ? _this.props.selected : _this.getPreSelection(); var changedDate = (0, _date_utils.setTime)((0, _date_utils.cloneDate)(selected), { hour: (0, _date_utils.getHour)(time), minute: (0, _date_utils.getMinute)(time) }); _this.setState({ preSelection: changedDate }); _this.props.onChange(changedDate); }; _this.onInputClick = function () { if (!_this.props.disabled) { _this.setOpen(true); } }; _this.onInputKeyDown = function (event) { _this.props.onKeyDown(event); var eventKey = event.key; if (!_this.state.open && !_this.props.inline) { if (eventKey !== 'Enter' && eventKey !== 'Escape' && eventKey !== 'Tab') { _this.onInputClick(); } return; } var copy = (0, _date_utils.newDate)(_this.state.preSelection); if (eventKey === 'Enter') { event.preventDefault(); if ((0, _date_utils.isMoment)(_this.state.preSelection) || (0, _date_utils.isDate)(_this.state.preSelection)) { _this.handleSelect(copy, event); !_this.props.shouldCloseOnSelect && _this.setPreSelection(copy); } else { _this.setOpen(false); } } else if (eventKey === 'Escape') { event.preventDefault(); _this.setOpen(false); } else if (eventKey === 'Tab') { _this.setOpen(false); } else if (!_this.props.disabledKeyboardNavigation) { var newSelection = void 0; switch (eventKey) { case 'ArrowLeft': event.preventDefault(); newSelection = (0, _date_utils.subtractDays)(copy, 1); break; case 'ArrowRight': event.preventDefault(); newSelection = (0, _date_utils.addDays)(copy, 1); break; case 'ArrowUp': event.preventDefault(); newSelection = (0, _date_utils.subtractWeeks)(copy, 1); break; case 'ArrowDown': event.preventDefault(); newSelection = (0, _date_utils.addWeeks)(copy, 1); break; case 'PageUp': event.preventDefault(); newSelection = (0, _date_utils.subtractMonths)(copy, 1); break; case 'PageDown': event.preventDefault(); newSelection = (0, _date_utils.addMonths)(copy, 1); break; case 'Home': event.preventDefault(); newSelection = (0, _date_utils.subtractYears)(copy, 1); break; case 'End': event.preventDefault(); newSelection = (0, _date_utils.addYears)(copy, 1); break; } _this.setPreSelection(newSelection); } }; _this.onClearClick = function (event) { event.preventDefault(); _this.props.onChange(null, event); _this.setState({ inputValue: null }); }; _this.renderCalendar = function () { if (!_this.props.inline && (!_this.state.open || _this.props.disabled)) { return null; } return _react2.default.createElement( WrappedCalendar, { ref: function ref(elem) { _this.calendar = elem; }, locale: _this.props.locale, dateFormat: _this.props.dateFormatCalendar, useWeekdaysShort: _this.props.useWeekdaysShort, dropdownMode: _this.props.dropdownMode, selected: _this.props.selected, preSelection: _this.state.preSelection, onSelect: _this.handleSelect, onWeekSelect: _this.props.onWeekSelect, openToDate: _this.props.openToDate, minDate: _this.props.minDate, maxDate: _this.props.maxDate, selectsStart: _this.props.selectsStart, selectsEnd: _this.props.selectsEnd, startDate: _this.props.startDate, endDate: _this.props.endDate, excludeDates: _this.props.excludeDates, filterDate: _this.props.filterDate, onClickOutside: _this.handleCalendarClickOutside, formatWeekNumber: _this.props.formatWeekNumber, highlightDates: _this.props.highlightDates, includeDates: _this.props.includeDates, inline: _this.props.inline, peekNextMonth: _this.props.peekNextMonth, showMonthDropdown: _this.props.showMonthDropdown, showWeekNumbers: _this.props.showWeekNumbers, showYearDropdown: _this.props.showYearDropdown, withPortal: _this.props.withPortal, forceShowMonthNavigation: _this.props.forceShowMonthNavigation, scrollableYearDropdown: _this.props.scrollableYearDropdown, todayButton: _this.props.todayButton, weekLabel: _this.props.weekLabel, utcOffset: _this.props.utcOffset, outsideClickIgnoreClass: outsideClickIgnoreClass, fixedHeight: _this.props.fixedHeight, monthsShown: _this.props.monthsShown, onDropdownFocus: _this.handleDropdownFocus, onMonthChange: _this.props.onMonthChange, dayClassName: _this.props.dayClassName, showTimeSelect: _this.props.showTimeSelect, onTimeChange: _this.handleTimeChange, timeFormat: _this.props.timeFormat, timeIntervals: _this.props.timeIntervals, minTime: _this.props.minTime, maxTime: _this.props.maxTime, excludeTimes: _this.props.excludeTimes, className: _this.props.calendarClassName, yearDropdownItemNumber: _this.props.yearDropdownItemNumber }, _this.props.children ); }; _this.renderDateInput = function () { var className = (0, _classnames3.default)(_this.props.className, _defineProperty({}, outsideClickIgnoreClass, _this.state.open)); var customInput = _this.props.customInput || _react2.default.createElement('input', { type: 'text' }); var inputValue = typeof _this.props.value === 'string' ? _this.props.value : typeof _this.state.inputValue === 'string' ? _this.state.inputValue : (0, _date_utils.safeDateFormat)(_this.props.selected, _this.props); return _react2.default.cloneElement(customInput, { ref: function ref(input) { _this.input = input; }, value: inputValue, onBlur: _this.handleBlur, onChange: _this.handleChange, onClick: _this.onInputClick, onFocus: _this.handleFocus, onKeyDown: _this.onInputKeyDown, id: _this.props.id, name: _this.props.name, autoFocus: _this.props.autoFocus, placeholder: _this.props.placeholderText, disabled: _this.props.disabled, autoComplete: _this.props.autoComplete, className: className, title: _this.props.title, readOnly: _this.props.readOnly, required: _this.props.required, tabIndex: _this.props.tabIndex }); }; _this.renderClearButton = function () { if (_this.props.isClearable && _this.props.selected != null) { return _react2.default.createElement('a', { className: 'react-datepicker__close-icon', href: '#', onClick: _this.onClearClick }); } else { return null; } }; _this.state = _this.calcInitialState(); return _this; } _createClass(DatePicker, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var currentMonth = this.props.selected && (0, _date_utils.getMonth)(this.props.selected); var nextMonth = nextProps.selected && (0, _date_utils.getMonth)(nextProps.selected); if (this.props.inline && currentMonth !== nextMonth) { this.setPreSelection(nextProps.selected); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearPreventFocusTimeout(); } }, { key: 'render', value: function render() { var calendar = this.renderCalendar(); if (this.props.inline && !this.props.withPortal) { return calendar; } if (this.props.withPortal) { return _react2.default.createElement( 'div', null, !this.props.inline ? _react2.default.createElement( 'div', { className: 'react-datepicker__input-container' }, this.renderDateInput(), this.renderClearButton() ) : null, this.state.open || this.props.inline ? _react2.default.createElement( 'div', { className: 'react-datepicker__portal' }, calendar ) : null ); } return _react2.default.createElement(_popper_component2.default, { className: this.props.popperClassName, hidePopper: !this.state.open || this.props.disabled, popperModifiers: this.props.popperModifiers, targetComponent: _react2.default.createElement( 'div', { className: 'react-datepicker__input-container' }, this.renderDateInput(), this.renderClearButton() ), popperContainer: this.props.popperContainer, popperComponent: calendar, popperPlacement: this.props.popperPlacement }); } }]); return DatePicker; }(_react2.default.Component); DatePicker.propTypes = { allowSameDay: _propTypes2.default.bool, autoComplete: _propTypes2.default.string, autoFocus: _propTypes2.default.bool, calendarClassName: _propTypes2.default.string, children: _propTypes2.default.node, className: _propTypes2.default.string, customInput: _propTypes2.default.element, dateFormat: _propTypes2.default.oneOfType([// eslint-disable-line react/no-unused-prop-types _propTypes2.default.string, _propTypes2.default.array]), dateFormatCalendar: _propTypes2.default.string, dayClassName: _propTypes2.default.func, disabled: _propTypes2.default.bool, disabledKeyboardNavigation: _propTypes2.default.bool, dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired, endDate: _propTypes2.default.object, excludeDates: _propTypes2.default.array, filterDate: _propTypes2.default.func, fixedHeight: _propTypes2.default.bool, formatWeekNumber: _propTypes2.default.func, highlightDates: _propTypes2.default.array, id: _propTypes2.default.string, includeDates: _propTypes2.default.array, inline: _propTypes2.default.bool, isClearable: _propTypes2.default.bool, locale: _propTypes2.default.string, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, monthsShown: _propTypes2.default.number, name: _propTypes2.default.string, onBlur: _propTypes2.default.func, onChange: _propTypes2.default.func.isRequired, onSelect: _propTypes2.default.func, onWeekSelect: _propTypes2.default.func, onClickOutside: _propTypes2.default.func, onChangeRaw: _propTypes2.default.func, onFocus: _propTypes2.default.func, onKeyDown: _propTypes2.default.func, onMonthChange: _propTypes2.default.func, openToDate: _propTypes2.default.object, peekNextMonth: _propTypes2.default.bool, placeholderText: _propTypes2.default.string, popperContainer: _propTypes2.default.func, popperClassName: _propTypes2.default.string, // <PopperComponent/> props popperModifiers: _propTypes2.default.object, // <PopperComponent/> props popperPlacement: _propTypes2.default.oneOf(_popper_component.popperPlacementPositions), // <PopperComponent/> props readOnly: _propTypes2.default.bool, required: _propTypes2.default.bool, scrollableYearDropdown: _propTypes2.default.bool, selected: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, showMonthDropdown: _propTypes2.default.bool, showWeekNumbers: _propTypes2.default.bool, showYearDropdown: _propTypes2.default.bool, forceShowMonthNavigation: _propTypes2.default.bool, startDate: _propTypes2.default.object, startOpen: _propTypes2.default.bool, tabIndex: _propTypes2.default.number, title: _propTypes2.default.string, todayButton: _propTypes2.default.string, useWeekdaysShort: _propTypes2.default.bool, utcOffset: _propTypes2.default.number, value: _propTypes2.default.string, weekLabel: _propTypes2.default.string, withPortal: _propTypes2.default.bool, yearDropdownItemNumber: _propTypes2.default.number, shouldCloseOnSelect: _propTypes2.default.bool, showTimeSelect: _propTypes2.default.bool, timeFormat: _propTypes2.default.string, timeIntervals: _propTypes2.default.number, minTime: _propTypes2.default.object, maxTime: _propTypes2.default.object, excludeTimes: _propTypes2.default.array }; exports.default = DatePicker; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _year_dropdown = __webpack_require__(2); var _year_dropdown2 = _interopRequireDefault(_year_dropdown); var _month_dropdown = __webpack_require__(14); var _month_dropdown2 = _interopRequireDefault(_month_dropdown); var _month = __webpack_require__(16); var _month2 = _interopRequireDefault(_month); var _time = __webpack_require__(20); var _time2 = _interopRequireDefault(_time); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _date_utils = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var DROPDOWN_FOCUS_CLASSNAMES = ['react-datepicker__year-select', 'react-datepicker__month-select']; var isDropdownSelect = function isDropdownSelect() { var element = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var classNames = (element.className || '').split(/\s+/); return DROPDOWN_FOCUS_CLASSNAMES.some(function (testClassname) { return classNames.indexOf(testClassname) >= 0; }); }; var Calendar = function (_React$Component) { _inherits(Calendar, _React$Component); _createClass(Calendar, null, [{ key: 'defaultProps', get: function get() { return { onDropdownFocus: function onDropdownFocus() {}, monthsShown: 1, forceShowMonthNavigation: false }; } }]); function Calendar(props) { _classCallCheck(this, Calendar); var _this = _possibleConstructorReturn(this, (Calendar.__proto__ || Object.getPrototypeOf(Calendar)).call(this, props)); _this.handleClickOutside = function (event) { _this.props.onClickOutside(event); }; _this.handleDropdownFocus = function (event) { if (isDropdownSelect(event.target)) { _this.props.onDropdownFocus(); } }; _this.getDateInView = function () { var _this$props = _this.props, preSelection = _this$props.preSelection, selected = _this$props.selected, openToDate = _this$props.openToDate, utcOffset = _this$props.utcOffset; var minDate = (0, _date_utils.getEffectiveMinDate)(_this.props); var maxDate = (0, _date_utils.getEffectiveMaxDate)(_this.props); var current = (0, _date_utils.now)(utcOffset); var initialDate = openToDate || selected || preSelection; if (initialDate) { return initialDate; } else { if (minDate && (0, _date_utils.isBefore)(current, minDate)) { return minDate; } else if (maxDate && (0, _date_utils.isAfter)(current, maxDate)) { return maxDate; } } return current; }; _this.localizeDate = function (date) { return (0, _date_utils.localizeDate)(date, _this.props.locale); }; _this.increaseMonth = function () { _this.setState({ date: (0, _date_utils.addMonths)((0, _date_utils.cloneDate)(_this.state.date), 1) }, function () { return _this.handleMonthChange(_this.state.date); }); }; _this.decreaseMonth = function () { _this.setState({ date: (0, _date_utils.subtractMonths)((0, _date_utils.cloneDate)(_this.state.date), 1) }, function () { return _this.handleMonthChange(_this.state.date); }); }; _this.handleDayClick = function (day, event) { return _this.props.onSelect(day, event); }; _this.handleDayMouseEnter = function (day) { return _this.setState({ selectingDate: day }); }; _this.handleMonthMouseLeave = function () { return _this.setState({ selectingDate: null }); }; _this.handleMonthChange = function (date) { if (_this.props.onMonthChange) { _this.props.onMonthChange(date); } }; _this.changeYear = function (year) { _this.setState({ date: (0, _date_utils.setYear)((0, _date_utils.cloneDate)(_this.state.date), year) }); }; _this.changeMonth = function (month) { _this.setState({ date: (0, _date_utils.setMonth)((0, _date_utils.cloneDate)(_this.state.date), month) }, function () { return _this.handleMonthChange(_this.state.date); }); }; _this.header = function () { var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.state.date; var startOfWeek = (0, _date_utils.getStartOfWeek)((0, _date_utils.cloneDate)(date)); var dayNames = []; if (_this.props.showWeekNumbers) { dayNames.push(_react2.default.createElement( 'div', { key: 'W', className: 'react-datepicker__day-name' }, _this.props.weekLabel || '#' )); } return dayNames.concat([0, 1, 2, 3, 4, 5, 6].map(function (offset) { var day = (0, _date_utils.addDays)((0, _date_utils.cloneDate)(startOfWeek), offset); var localeData = (0, _date_utils.getLocaleData)(day); var weekDayName = _this.props.useWeekdaysShort ? (0, _date_utils.getWeekdayShortInLocale)(localeData, day) : (0, _date_utils.getWeekdayMinInLocale)(localeData, day); return _react2.default.createElement( 'div', { key: offset, className: 'react-datepicker__day-name' }, weekDayName ); })); }; _this.renderPreviousMonthButton = function () { if (!_this.props.forceShowMonthNavigation && (0, _date_utils.allDaysDisabledBefore)(_this.state.date, 'month', _this.props)) { return; } return _react2.default.createElement('a', { className: 'react-datepicker__navigation react-datepicker__navigation--previous', onClick: _this.decreaseMonth }); }; _this.renderNextMonthButton = function () { if (!_this.props.forceShowMonthNavigation && (0, _date_utils.allDaysDisabledAfter)(_this.state.date, 'month', _this.props)) { return; } var classes = ['react-datepicker__navigation', 'react-datepicker__navigation--next']; if (_this.props.showTimeSelect) { classes.push('react-datepicker__navigation--next--with-time'); } if (_this.props.todayButton) { classes.push('react-datepicker__navigation--next--with-today-button'); } return _react2.default.createElement('a', { className: classes.join(' '), onClick: _this.increaseMonth }); }; _this.renderCurrentMonth = function () { var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.state.date; var classes = ['react-datepicker__current-month']; if (_this.props.showYearDropdown) { classes.push('react-datepicker__current-month--hasYearDropdown'); } if (_this.props.showMonthDropdown) { classes.push('react-datepicker__current-month--hasMonthDropdown'); } return _react2.default.createElement( 'div', { className: classes.join(' ') }, (0, _date_utils.formatDate)(date, _this.props.dateFormat) ); }; _this.renderYearDropdown = function () { var overrideHide = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (!_this.props.showYearDropdown || overrideHide) { return; } return _react2.default.createElement(_year_dropdown2.default, { dropdownMode: _this.props.dropdownMode, onChange: _this.changeYear, minDate: _this.props.minDate, maxDate: _this.props.maxDate, year: (0, _date_utils.getYear)(_this.state.date), scrollableYearDropdown: _this.props.scrollableYearDropdown, yearDropdownItemNumber: _this.props.yearDropdownItemNumber }); }; _this.renderMonthDropdown = function () { var overrideHide = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (!_this.props.showMonthDropdown) { return; } return _react2.default.createElement(_month_dropdown2.default, { dropdownMode: _this.props.dropdownMode, locale: _this.props.locale, dateFormat: _this.props.dateFormat, onChange: _this.changeMonth, month: (0, _date_utils.getMonth)(_this.state.date) }); }; _this.renderTodayButton = function () { if (!_this.props.todayButton) { return; } return _react2.default.createElement( 'div', { className: 'react-datepicker__today-button', onClick: function onClick(e) { return _this.props.onSelect((0, _date_utils.getStartOfDate)((0, _date_utils.now)(_this.props.utcOffset)), e); } }, _this.props.todayButton ); }; _this.renderMonths = function () { var monthList = []; for (var i = 0; i < _this.props.monthsShown; ++i) { var monthDate = (0, _date_utils.addMonths)((0, _date_utils.cloneDate)(_this.state.date), i); var monthKey = 'month-' + i; monthList.push(_react2.default.createElement( 'div', { key: monthKey, ref: function ref(div) { _this.monthContainer = div; }, className: 'react-datepicker__month-container' }, _react2.default.createElement( 'div', { className: 'react-datepicker__header' }, _this.renderCurrentMonth(monthDate), _react2.default.createElement( 'div', { className: 'react-datepicker__header__dropdown react-datepicker__header__dropdown--' + _this.props.dropdownMode, onFocus: _this.handleDropdownFocus }, _this.renderMonthDropdown(i !== 0), _this.renderYearDropdown(i !== 0) ), _react2.default.createElement( 'div', { className: 'react-datepicker__day-names' }, _this.header(monthDate) ) ), _react2.default.createElement(_month2.default, { day: monthDate, dayClassName: _this.props.dayClassName, onDayClick: _this.handleDayClick, onDayMouseEnter: _this.handleDayMouseEnter, onMouseLeave: _this.handleMonthMouseLeave, onWeekSelect: _this.props.onWeekSelect, formatWeekNumber: _this.props.formatWeekNumber, minDate: _this.props.minDate, maxDate: _this.props.maxDate, excludeDates: _this.props.excludeDates, highlightDates: _this.props.highlightDates, selectingDate: _this.state.selectingDate, includeDates: _this.props.includeDates, inline: _this.props.inline, fixedHeight: _this.props.fixedHeight, filterDate: _this.props.filterDate, preSelection: _this.props.preSelection, selected: _this.props.selected, selectsStart: _this.props.selectsStart, selectsEnd: _this.props.selectsEnd, showWeekNumbers: _this.props.showWeekNumbers, startDate: _this.props.startDate, endDate: _this.props.endDate, peekNextMonth: _this.props.peekNextMonth, utcOffset: _this.props.utcOffset }) )); } return monthList; }; _this.renderTimeSection = function () { if (_this.props.showTimeSelect) { return _react2.default.createElement(_time2.default, { selected: _this.props.selected, onChange: _this.props.onTimeChange, format: _this.props.timeFormat, intervals: _this.props.timeIntervals, minTime: _this.props.minTime, maxTime: _this.props.maxTime, excludeTimes: _this.props.excludeTimes, todayButton: _this.props.todayButton, showMonthDropdown: _this.props.showMonthDropdown, showYearDropdown: _this.props.showYearDropdown, withPortal: _this.props.withPortal, monthRef: _this.state.monthContainer }); } else { return; } }; _this.state = { date: _this.localizeDate(_this.getDateInView()), selectingDate: null, monthContainer: _this.monthContainer }; return _this; } _createClass(Calendar, [{ key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; /* monthContainer height is needed in time component to determine the height for the ul in the time component. setState here so height is given after final component layout is rendered */ if (this.props.showTimeSelect) { this.assignMonthContainer = function () { _this2.setState({ monthContainer: _this2.monthContainer }); }(); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.preSelection && !(0, _date_utils.isSameDay)(nextProps.preSelection, this.props.preSelection)) { this.setState({ date: this.localizeDate(nextProps.preSelection) }); } else if (nextProps.openToDate && !(0, _date_utils.isSameDay)(nextProps.openToDate, this.props.openToDate)) { this.setState({ date: this.localizeDate(nextProps.openToDate) }); } } }, { key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: (0, _classnames2.default)('react-datepicker', this.props.className) }, _react2.default.createElement('div', { className: 'react-datepicker__triangle' }), this.renderPreviousMonthButton(), this.renderNextMonthButton(), this.renderMonths(), this.renderTodayButton(), this.renderTimeSection(), this.props.children ); } }]); return Calendar; }(_react2.default.Component); Calendar.propTypes = { className: _propTypes2.default.string, children: _propTypes2.default.node, dateFormat: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.array]).isRequired, dayClassName: _propTypes2.default.func, dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired, endDate: _propTypes2.default.object, excludeDates: _propTypes2.default.array, filterDate: _propTypes2.default.func, fixedHeight: _propTypes2.default.bool, formatWeekNumber: _propTypes2.default.func, highlightDates: _propTypes2.default.array, includeDates: _propTypes2.default.array, inline: _propTypes2.default.bool, locale: _propTypes2.default.string, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, monthsShown: _propTypes2.default.number, onClickOutside: _propTypes2.default.func.isRequired, onMonthChange: _propTypes2.default.func, forceShowMonthNavigation: _propTypes2.default.bool, onDropdownFocus: _propTypes2.default.func, onSelect: _propTypes2.default.func.isRequired, onWeekSelect: _propTypes2.default.func, showTimeSelect: _propTypes2.default.bool, timeFormat: _propTypes2.default.string, timeIntervals: _propTypes2.default.number, onTimeChange: _propTypes2.default.func, minTime: _propTypes2.default.object, maxTime: _propTypes2.default.object, excludeTimes: _propTypes2.default.array, openToDate: _propTypes2.default.object, peekNextMonth: _propTypes2.default.bool, scrollableYearDropdown: _propTypes2.default.bool, preSelection: _propTypes2.default.object, selected: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, showMonthDropdown: _propTypes2.default.bool, showWeekNumbers: _propTypes2.default.bool, showYearDropdown: _propTypes2.default.bool, startDate: _propTypes2.default.object, todayButton: _propTypes2.default.string, useWeekdaysShort: _propTypes2.default.bool, withPortal: _propTypes2.default.bool, utcOffset: _propTypes2.default.number, weekLabel: _propTypes2.default.string, yearDropdownItemNumber: _propTypes2.default.number }; exports.default = Calendar; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _year_dropdown_options = __webpack_require__(9); var _year_dropdown_options2 = _interopRequireDefault(_year_dropdown_options); var _reactOnclickoutside = __webpack_require__(11); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); var _date_utils = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var WrappedYearDropdownOptions = (0, _reactOnclickoutside2.default)(_year_dropdown_options2.default); var YearDropdown = function (_React$Component) { _inherits(YearDropdown, _React$Component); function YearDropdown() { var _ref; var _temp, _this, _ret; _classCallCheck(this, YearDropdown); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = YearDropdown.__proto__ || Object.getPrototypeOf(YearDropdown)).call.apply(_ref, [this].concat(args))), _this), _this.state = { dropdownVisible: false }, _this.renderSelectOptions = function () { var minYear = _this.props.minDate ? (0, _date_utils.getYear)(_this.props.minDate) : 1900; var maxYear = _this.props.maxDate ? (0, _date_utils.getYear)(_this.props.maxDate) : 2100; var options = []; for (var i = minYear; i <= maxYear; i++) { options.push(_react2.default.createElement( 'option', { key: i, value: i }, i )); } return options; }, _this.onSelectChange = function (e) { _this.onChange(e.target.value); }, _this.renderSelectMode = function () { return _react2.default.createElement( 'select', { value: _this.props.year, className: 'react-datepicker__year-select', onChange: _this.onSelectChange }, _this.renderSelectOptions() ); }, _this.renderReadView = function (visible) { return _react2.default.createElement( 'div', { key: 'read', style: { visibility: visible ? 'visible' : 'hidden' }, className: 'react-datepicker__year-read-view', onClick: _this.toggleDropdown }, _react2.default.createElement('span', { className: 'react-datepicker__year-read-view--down-arrow' }), _react2.default.createElement( 'span', { className: 'react-datepicker__year-read-view--selected-year' }, _this.props.year ) ); }, _this.renderDropdown = function () { return _react2.default.createElement(WrappedYearDropdownOptions, { key: 'dropdown', ref: 'options', year: _this.props.year, onChange: _this.onChange, onCancel: _this.toggleDropdown, minDate: _this.props.minDate, maxDate: _this.props.maxDate, scrollableYearDropdown: _this.props.scrollableYearDropdown, yearDropdownItemNumber: _this.props.yearDropdownItemNumber }); }, _this.renderScrollMode = function () { var dropdownVisible = _this.state.dropdownVisible; var result = [_this.renderReadView(!dropdownVisible)]; if (dropdownVisible) { result.unshift(_this.renderDropdown()); } return result; }, _this.onChange = function (year) { _this.toggleDropdown(); if (year === _this.props.year) return; _this.props.onChange(year); }, _this.toggleDropdown = function () { _this.setState({ dropdownVisible: !_this.state.dropdownVisible }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(YearDropdown, [{ key: 'render', value: function render() { var renderedDropdown = void 0; switch (this.props.dropdownMode) { case 'scroll': renderedDropdown = this.renderScrollMode(); break; case 'select': renderedDropdown = this.renderSelectMode(); break; } return _react2.default.createElement( 'div', { className: 'react-datepicker__year-dropdown-container react-datepicker__year-dropdown-container--' + this.props.dropdownMode }, renderedDropdown ); } }]); return YearDropdown; }(_react2.default.Component); YearDropdown.propTypes = { dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, onChange: _propTypes2.default.func.isRequired, scrollableYearDropdown: _propTypes2.default.bool, year: _propTypes2.default.number.isRequired, yearDropdownItemNumber: _propTypes2.default.number }; exports.default = YearDropdown; /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ if (false) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(5)(); } /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(6); var invariant = __webpack_require__(7); var ReactPropTypesSecret = __webpack_require__(8); module.exports = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); }; shim.isRequired = shim; function getShim() { return shim; }; // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 6 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (false) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }), /* 8 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function generateYears(year, noOfYear, minDate, maxDate) { var list = []; for (var i = 0; i < 2 * noOfYear + 1; i++) { var newYear = year + noOfYear - i; var isInRange = true; if (minDate) { isInRange = minDate.year() <= newYear; } if (maxDate && isInRange) { isInRange = maxDate.year() >= newYear; } if (isInRange) { list.push(newYear); } } return list; } var YearDropdownOptions = function (_React$Component) { _inherits(YearDropdownOptions, _React$Component); function YearDropdownOptions(props) { _classCallCheck(this, YearDropdownOptions); var _this = _possibleConstructorReturn(this, (YearDropdownOptions.__proto__ || Object.getPrototypeOf(YearDropdownOptions)).call(this, props)); _this.renderOptions = function () { var selectedYear = _this.props.year; var options = _this.state.yearsList.map(function (year) { return _react2.default.createElement( 'div', { className: 'react-datepicker__year-option', key: year, ref: year, onClick: _this.onChange.bind(_this, year) }, selectedYear === year ? _react2.default.createElement( 'span', { className: 'react-datepicker__year-option--selected' }, '\u2713' ) : '', year ); }); var minYear = _this.props.minDate ? _this.props.minDate.year() : null; var maxYear = _this.props.maxDate ? _this.props.maxDate.year() : null; if (!maxYear || !_this.state.yearsList.find(function (year) { return year === maxYear; })) { options.unshift(_react2.default.createElement( 'div', { className: 'react-datepicker__year-option', ref: 'upcoming', key: 'upcoming', onClick: _this.incrementYears }, _react2.default.createElement('a', { className: 'react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-upcoming' }) )); } if (!minYear || !_this.state.yearsList.find(function (year) { return year === minYear; })) { options.push(_react2.default.createElement( 'div', { className: 'react-datepicker__year-option', ref: 'previous', key: 'previous', onClick: _this.decrementYears }, _react2.default.createElement('a', { className: 'react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-previous' }) )); } return options; }; _this.onChange = function (year) { _this.props.onChange(year); }; _this.handleClickOutside = function () { _this.props.onCancel(); }; _this.shiftYears = function (amount) { var years = _this.state.yearsList.map(function (year) { return year + amount; }); _this.setState({ yearsList: years }); }; _this.incrementYears = function () { return _this.shiftYears(1); }; _this.decrementYears = function () { return _this.shiftYears(-1); }; var yearDropdownItemNumber = props.yearDropdownItemNumber, scrollableYearDropdown = props.scrollableYearDropdown; var noOfYear = yearDropdownItemNumber || (scrollableYearDropdown ? 10 : 5); _this.state = { yearsList: generateYears(_this.props.year, noOfYear, _this.props.minDate, _this.props.maxDate) }; return _this; } _createClass(YearDropdownOptions, [{ key: 'render', value: function render() { var dropdownClass = (0, _classnames2.default)({ 'react-datepicker__year-dropdown': true, 'react-datepicker__year-dropdown--scrollable': this.props.scrollableYearDropdown }); return _react2.default.createElement( 'div', { className: dropdownClass }, this.renderOptions() ); } }]); return YearDropdownOptions; }(_react2.default.Component); YearDropdownOptions.propTypes = { minDate: _propTypes2.default.object, maxDate: _propTypes2.default.object, onCancel: _propTypes2.default.func.isRequired, onChange: _propTypes2.default.func.isRequired, scrollableYearDropdown: _propTypes2.default.bool, year: _propTypes2.default.number.isRequired, yearDropdownItemNumber: _propTypes2.default.number }; exports.default = YearDropdownOptions; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }), /* 11 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_11__; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.newDate = newDate; exports.newDateWithOffset = newDateWithOffset; exports.now = now; exports.cloneDate = cloneDate; exports.parseDate = parseDate; exports.isMoment = isMoment; exports.isDate = isDate; exports.formatDate = formatDate; exports.safeDateFormat = safeDateFormat; exports.setTime = setTime; exports.setMonth = setMonth; exports.setYear = setYear; exports.setUTCOffset = setUTCOffset; exports.getSecond = getSecond; exports.getMinute = getMinute; exports.getHour = getHour; exports.getDay = getDay; exports.getWeek = getWeek; exports.getMonth = getMonth; exports.getYear = getYear; exports.getDate = getDate; exports.getUTCOffset = getUTCOffset; exports.getDayOfWeekCode = getDayOfWeekCode; exports.getStartOfDay = getStartOfDay; exports.getStartOfWeek = getStartOfWeek; exports.getStartOfMonth = getStartOfMonth; exports.getStartOfDate = getStartOfDate; exports.getEndOfWeek = getEndOfWeek; exports.getEndOfMonth = getEndOfMonth; exports.addMinutes = addMinutes; exports.addDays = addDays; exports.addWeeks = addWeeks; exports.addMonths = addMonths; exports.addYears = addYears; exports.subtractDays = subtractDays; exports.subtractWeeks = subtractWeeks; exports.subtractMonths = subtractMonths; exports.subtractYears = subtractYears; exports.isBefore = isBefore; exports.isAfter = isAfter; exports.equals = equals; exports.isSameMonth = isSameMonth; exports.isSameDay = isSameDay; exports.isSameUtcOffset = isSameUtcOffset; exports.isDayInRange = isDayInRange; exports.getDaysDiff = getDaysDiff; exports.localizeDate = localizeDate; exports.getDefaultLocale = getDefaultLocale; exports.getDefaultLocaleData = getDefaultLocaleData; exports.registerLocale = registerLocale; exports.getLocaleData = getLocaleData; exports.getLocaleDataForLocale = getLocaleDataForLocale; exports.getWeekdayMinInLocale = getWeekdayMinInLocale; exports.getWeekdayShortInLocale = getWeekdayShortInLocale; exports.getMonthInLocale = getMonthInLocale; exports.isDayDisabled = isDayDisabled; exports.isTimeDisabled = isTimeDisabled; exports.isTimeInDisabledRange = isTimeInDisabledRange; exports.allDaysDisabledBefore = allDaysDisabledBefore; exports.allDaysDisabledAfter = allDaysDisabledAfter; exports.getEffectiveMinDate = getEffectiveMinDate; exports.getEffectiveMaxDate = getEffectiveMaxDate; var _moment = __webpack_require__(13); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var dayOfWeekCodes = { 1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5: 'fri', 6: 'sat', 7: 'sun' // These functions are not exported so // that we avoid magic strings like 'days' };function set(date, unit, to) { return date.set(unit, to); } function add(date, amount, unit) { return date.add(amount, unit); } function subtract(date, amount, unit) { return date.subtract(amount, unit); } function get(date, unit) { return date.get(unit); } function getStartOf(date, unit) { return date.startOf(unit); } function getEndOf(date, unit) { return date.endOf(unit); } function getDiff(date1, date2, unit) { return date1.diff(date2, unit); } function isSame(date1, date2, unit) { return date1.isSame(date2, unit); } // ** Date Constructors ** function newDate(point) { return (0, _moment2.default)(point); } function newDateWithOffset(utcOffset) { return (0, _moment2.default)().utc().utcOffset(utcOffset); } function now(maybeFixedUtcOffset) { if (maybeFixedUtcOffset == null) { return newDate(); } return newDateWithOffset(maybeFixedUtcOffset); } function cloneDate(date) { return date.clone(); } function parseDate(value, _ref) { var dateFormat = _ref.dateFormat, locale = _ref.locale; var m = (0, _moment2.default)(value, dateFormat, locale || _moment2.default.locale(), true); return m.isValid() ? m : null; } // ** Date "Reflection" ** function isMoment(date) { return _moment2.default.isMoment(date); } function isDate(date) { return _moment2.default.isDate(date); } // ** Date Formatting ** function formatDate(date, format) { return date.format(format); } function safeDateFormat(date, _ref2) { var dateFormat = _ref2.dateFormat, locale = _ref2.locale; return date && date.clone().locale(locale || _moment2.default.locale()).format(Array.isArray(dateFormat) ? dateFormat[0] : dateFormat) || ''; } // ** Date Setters ** function setTime(date, _ref3) { var hour = _ref3.hour, minute = _ref3.minute, second = _ref3.second; date.set({ hour: hour, minute: minute, second: second }); return date; } function setMonth(date, month) { return set(date, 'month', month); } function setYear(date, year) { return set(date, 'year', year); } function setUTCOffset(date, offset) { return date.utcOffset(offset); } // ** Date Getters ** function getSecond(date) { return get(date, 'second'); } function getMinute(date) { return get(date, 'minute'); } function getHour(date) { return get(date, 'hour'); } // Returns day of week function getDay(date) { return get(date, 'day'); } function getWeek(date) { return get(date, 'week'); } function getMonth(date) { return get(date, 'month'); } function getYear(date) { return get(date, 'year'); } // Returns day of month function getDate(date) { return get(date, 'date'); } function getUTCOffset() { return (0, _moment2.default)().utcOffset(); } function getDayOfWeekCode(day) { return dayOfWeekCodes[day.isoWeekday()]; } // *** Start of *** function getStartOfDay(date) { return getStartOf(date, 'day'); } function getStartOfWeek(date) { return getStartOf(date, 'week'); } function getStartOfMonth(date) { return getStartOf(date, 'month'); } function getStartOfDate(date) { return getStartOf(date, 'date'); } // *** End of *** function getEndOfWeek(date) { return getEndOf(date, 'week'); } function getEndOfMonth(date) { return getEndOf(date, 'month'); } // ** Date Math ** // *** Addition *** function addMinutes(date, amount) { return add(date, amount, 'minutes'); } function addDays(date, amount) { return add(date, amount, 'days'); } function addWeeks(date, amount) { return add(date, amount, 'weeks'); } function addMonths(date, amount) { return add(date, amount, 'months'); } function addYears(date, amount) { return add(date, amount, 'years'); } // *** Subtraction *** function subtractDays(date, amount) { return subtract(date, amount, 'days'); } function subtractWeeks(date, amount) { return subtract(date, amount, 'weeks'); } function subtractMonths(date, amount) { return subtract(date, amount, 'months'); } function subtractYears(date, amount) { return subtract(date, amount, 'years'); } // ** Date Comparison ** function isBefore(date1, date2) { return date1.isBefore(date2); } function isAfter(date1, date2) { return date1.isAfter(date2); } function equals(date1, date2) { return date1.isSame(date2); } function isSameMonth(date1, date2) { return isSame(date1, date2, 'month'); } function isSameDay(moment1, moment2) { if (moment1 && moment2) { return moment1.isSame(moment2, 'day'); } else { return !moment1 && !moment2; } } function isSameUtcOffset(moment1, moment2) { if (moment1 && moment2) { return moment1.utcOffset() === moment2.utcOffset(); } else { return !moment1 && !moment2; } } function isDayInRange(day, startDate, endDate) { var before = startDate.clone().startOf('day').subtract(1, 'seconds'); var after = endDate.clone().startOf('day').add(1, 'seconds'); return day.clone().startOf('day').isBetween(before, after); } // *** Diffing *** function getDaysDiff(date1, date2) { return getDiff(date1, date2, 'days'); } // ** Date Localization ** function localizeDate(date, locale) { return date.clone().locale(locale || _moment2.default.locale()); } function getDefaultLocale() { return _moment2.default.locale(); } function getDefaultLocaleData() { return _moment2.default.localeData(); } function registerLocale(localeName, localeData) { _moment2.default.defineLocale(localeName, localeData); } function getLocaleData(date) { return date.localeData(); } function getLocaleDataForLocale(locale) { return _moment2.default.localeData(locale); } function getWeekdayMinInLocale(locale, date) { return locale.weekdaysMin(date); } function getWeekdayShortInLocale(locale, date) { return locale.weekdaysShort(date); } // TODO what is this format exactly? function getMonthInLocale(locale, date, format) { return locale.months(date, format); } // ** Utils for some components ** function isDayDisabled(day) { var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, minDate = _ref4.minDate, maxDate = _ref4.maxDate, excludeDates = _ref4.excludeDates, includeDates = _ref4.includeDates, filterDate = _ref4.filterDate; return minDate && day.isBefore(minDate, 'day') || maxDate && day.isAfter(maxDate, 'day') || excludeDates && excludeDates.some(function (excludeDate) { return isSameDay(day, excludeDate); }) || includeDates && !includeDates.some(function (includeDate) { return isSameDay(day, includeDate); }) || filterDate && !filterDate(day.clone()) || false; } function isTimeDisabled(time, disabledTimes) { var l = disabledTimes.length; for (var i = 0; i < l; i++) { if (disabledTimes[i].get('hours') === time.get('hours') && disabledTimes[i].get('minutes') === time.get('minutes')) { return true; } } return false; } function isTimeInDisabledRange(time, _ref5) { var minTime = _ref5.minTime, maxTime = _ref5.maxTime; if (!minTime || !maxTime) { throw new Error('Both minTime and maxTime props required'); } var base = (0, _moment2.default)().hours(0).minutes(0).seconds(0); var baseTime = base.clone().hours(time.get('hours')).minutes(time.get('minutes')); var min = base.clone().hours(minTime.get('hours')).minutes(minTime.get('minutes')); var max = base.clone().hours(maxTime.get('hours')).minutes(maxTime.get('minutes')); return !(baseTime.isSameOrAfter(min) && baseTime.isSameOrBefore(max)); } function allDaysDisabledBefore(day, unit) { var _ref6 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, minDate = _ref6.minDate, includeDates = _ref6.includeDates; var dateBefore = day.clone().subtract(1, unit); return minDate && dateBefore.isBefore(minDate, unit) || includeDates && includeDates.every(function (includeDate) { return dateBefore.isBefore(includeDate, unit); }) || false; } function allDaysDisabledAfter(day, unit) { var _ref7 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, maxDate = _ref7.maxDate, includeDates = _ref7.includeDates; var dateAfter = day.clone().add(1, unit); return maxDate && dateAfter.isAfter(maxDate, unit) || includeDates && includeDates.every(function (includeDate) { return dateAfter.isAfter(includeDate, unit); }) || false; } function getEffectiveMinDate(_ref8) { var minDate = _ref8.minDate, includeDates = _ref8.includeDates; if (includeDates && minDate) { return _moment2.default.min(includeDates.filter(function (includeDate) { return minDate.isSameOrBefore(includeDate, 'day'); })); } else if (includeDates) { return _moment2.default.min(includeDates); } else { return minDate; } } function getEffectiveMaxDate(_ref9) { var maxDate = _ref9.maxDate, includeDates = _ref9.includeDates; if (includeDates && maxDate) { return _moment2.default.max(includeDates.filter(function (includeDate) { return maxDate.isSameOrAfter(includeDate, 'day'); })); } else if (includeDates) { return _moment2.default.max(includeDates); } else { return maxDate; } } /***/ }), /* 13 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_13__; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _month_dropdown_options = __webpack_require__(15); var _month_dropdown_options2 = _interopRequireDefault(_month_dropdown_options); var _reactOnclickoutside = __webpack_require__(11); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); var _date_utils = __webpack_require__(12); var utils = _interopRequireWildcard(_date_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var WrappedMonthDropdownOptions = (0, _reactOnclickoutside2.default)(_month_dropdown_options2.default); var MonthDropdown = function (_React$Component) { _inherits(MonthDropdown, _React$Component); function MonthDropdown() { var _ref; var _temp, _this, _ret; _classCallCheck(this, MonthDropdown); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MonthDropdown.__proto__ || Object.getPrototypeOf(MonthDropdown)).call.apply(_ref, [this].concat(args))), _this), _this.state = { dropdownVisible: false }, _this.renderSelectOptions = function (monthNames) { return monthNames.map(function (M, i) { return _react2.default.createElement( 'option', { key: i, value: i }, M ); }); }, _this.renderSelectMode = function (monthNames) { return _react2.default.createElement( 'select', { value: _this.props.month, className: 'react-datepicker__month-select', onChange: function onChange(e) { return _this.onChange(e.target.value); } }, _this.renderSelectOptions(monthNames) ); }, _this.renderReadView = function (visible, monthNames) { return _react2.default.createElement( 'div', { key: 'read', style: { visibility: visible ? 'visible' : 'hidden' }, className: 'react-datepicker__month-read-view', onClick: _this.toggleDropdown }, _react2.default.createElement( 'span', { className: 'react-datepicker__month-read-view--selected-month' }, monthNames[_this.props.month] ), _react2.default.createElement('span', { className: 'react-datepicker__month-read-view--down-arrow' }) ); }, _this.renderDropdown = function (monthNames) { return _react2.default.createElement(WrappedMonthDropdownOptions, { key: 'dropdown', ref: 'options', month: _this.props.month, monthNames: monthNames, onChange: _this.onChange, onCancel: _this.toggleDropdown }); }, _this.renderScrollMode = function (monthNames) { var dropdownVisible = _this.state.dropdownVisible; var result = [_this.renderReadView(!dropdownVisible, monthNames)]; if (dropdownVisible) { result.unshift(_this.renderDropdown(monthNames)); } return result; }, _this.onChange = function (month) { _this.toggleDropdown(); if (month !== _this.props.month) { _this.props.onChange(month); } }, _this.toggleDropdown = function () { return _this.setState({ dropdownVisible: !_this.state.dropdownVisible }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(MonthDropdown, [{ key: 'render', value: function render() { var _this2 = this; var localeData = utils.getLocaleDataForLocale(this.props.locale); var monthNames = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(function (M) { return utils.getMonthInLocale(localeData, utils.newDate({ M: M }), _this2.props.dateFormat); }); var renderedDropdown = void 0; switch (this.props.dropdownMode) { case 'scroll': renderedDropdown = this.renderScrollMode(monthNames); break; case 'select': renderedDropdown = this.renderSelectMode(monthNames); break; } return _react2.default.createElement( 'div', { className: 'react-datepicker__month-dropdown-container react-datepicker__month-dropdown-container--' + this.props.dropdownMode }, renderedDropdown ); } }]); return MonthDropdown; }(_react2.default.Component); MonthDropdown.propTypes = { dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired, locale: _propTypes2.default.string, dateFormat: _propTypes2.default.string.isRequired, month: _propTypes2.default.number.isRequired, onChange: _propTypes2.default.func.isRequired }; exports.default = MonthDropdown; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var MonthDropdownOptions = function (_React$Component) { _inherits(MonthDropdownOptions, _React$Component); function MonthDropdownOptions() { var _ref; var _temp, _this, _ret; _classCallCheck(this, MonthDropdownOptions); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MonthDropdownOptions.__proto__ || Object.getPrototypeOf(MonthDropdownOptions)).call.apply(_ref, [this].concat(args))), _this), _this.renderOptions = function () { return _this.props.monthNames.map(function (month, i) { return _react2.default.createElement( 'div', { className: 'react-datepicker__month-option', key: month, ref: month, onClick: _this.onChange.bind(_this, i) }, _this.props.month === i ? _react2.default.createElement( 'span', { className: 'react-datepicker__month-option--selected' }, '\u2713' ) : '', month ); }); }, _this.onChange = function (month) { return _this.props.onChange(month); }, _this.handleClickOutside = function () { return _this.props.onCancel(); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(MonthDropdownOptions, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: 'react-datepicker__month-dropdown' }, this.renderOptions() ); } }]); return MonthDropdownOptions; }(_react2.default.Component); MonthDropdownOptions.propTypes = { onCancel: _propTypes2.default.func.isRequired, onChange: _propTypes2.default.func.isRequired, month: _propTypes2.default.number.isRequired, monthNames: _propTypes2.default.arrayOf(_propTypes2.default.string.isRequired).isRequired }; exports.default = MonthDropdownOptions; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _week = __webpack_require__(17); var _week2 = _interopRequireDefault(_week); var _date_utils = __webpack_require__(12); var utils = _interopRequireWildcard(_date_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var FIXED_HEIGHT_STANDARD_WEEK_COUNT = 6; var Month = function (_React$Component) { _inherits(Month, _React$Component); function Month() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Month); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Month.__proto__ || Object.getPrototypeOf(Month)).call.apply(_ref, [this].concat(args))), _this), _this.handleDayClick = function (day, event) { if (_this.props.onDayClick) { _this.props.onDayClick(day, event); } }, _this.handleDayMouseEnter = function (day) { if (_this.props.onDayMouseEnter) { _this.props.onDayMouseEnter(day); } }, _this.handleMouseLeave = function () { if (_this.props.onMouseLeave) { _this.props.onMouseLeave(); } }, _this.isWeekInMonth = function (startOfWeek) { var day = _this.props.day; var endOfWeek = utils.addDays(utils.cloneDate(startOfWeek), 6); return utils.isSameMonth(startOfWeek, day) || utils.isSameMonth(endOfWeek, day); }, _this.renderWeeks = function () { var weeks = []; var isFixedHeight = _this.props.fixedHeight; var currentWeekStart = utils.getStartOfWeek(utils.getStartOfMonth(utils.cloneDate(_this.props.day))); var i = 0; var breakAfterNextPush = false; while (true) { weeks.push(_react2.default.createElement(_week2.default, { key: i, day: currentWeekStart, month: utils.getMonth(_this.props.day), onDayClick: _this.handleDayClick, onDayMouseEnter: _this.handleDayMouseEnter, onWeekSelect: _this.props.onWeekSelect, formatWeekNumber: _this.props.formatWeekNumber, minDate: _this.props.minDate, maxDate: _this.props.maxDate, excludeDates: _this.props.excludeDates, includeDates: _this.props.includeDates, inline: _this.props.inline, highlightDates: _this.props.highlightDates, selectingDate: _this.props.selectingDate, filterDate: _this.props.filterDate, preSelection: _this.props.preSelection, selected: _this.props.selected, selectsStart: _this.props.selectsStart, selectsEnd: _this.props.selectsEnd, showWeekNumber: _this.props.showWeekNumbers, startDate: _this.props.startDate, endDate: _this.props.endDate, dayClassName: _this.props.dayClassName, utcOffset: _this.props.utcOffset })); if (breakAfterNextPush) break; i++; currentWeekStart = utils.addWeeks(utils.cloneDate(currentWeekStart), 1); // If one of these conditions is true, we will either break on this week // or break on the next week var isFixedAndFinalWeek = isFixedHeight && i >= FIXED_HEIGHT_STANDARD_WEEK_COUNT; var isNonFixedAndOutOfMonth = !isFixedHeight && !_this.isWeekInMonth(currentWeekStart); if (isFixedAndFinalWeek || isNonFixedAndOutOfMonth) { if (_this.props.peekNextMonth) { breakAfterNextPush = true; } else { break; } } } return weeks; }, _this.getClassNames = function () { var _this$props = _this.props, selectingDate = _this$props.selectingDate, selectsStart = _this$props.selectsStart, selectsEnd = _this$props.selectsEnd; return (0, _classnames2.default)('react-datepicker__month', { 'react-datepicker__month--selecting-range': selectingDate && (selectsStart || selectsEnd) }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Month, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: this.getClassNames(), onMouseLeave: this.handleMouseLeave, role: 'listbox' }, this.renderWeeks() ); } }]); return Month; }(_react2.default.Component); Month.propTypes = { day: _propTypes2.default.object.isRequired, dayClassName: _propTypes2.default.func, endDate: _propTypes2.default.object, excludeDates: _propTypes2.default.array, filterDate: _propTypes2.default.func, fixedHeight: _propTypes2.default.bool, formatWeekNumber: _propTypes2.default.func, highlightDates: _propTypes2.default.array, includeDates: _propTypes2.default.array, inline: _propTypes2.default.bool, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, onDayClick: _propTypes2.default.func, onDayMouseEnter: _propTypes2.default.func, onMouseLeave: _propTypes2.default.func, onWeekSelect: _propTypes2.default.func, peekNextMonth: _propTypes2.default.bool, preSelection: _propTypes2.default.object, selected: _propTypes2.default.object, selectingDate: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, showWeekNumbers: _propTypes2.default.bool, startDate: _propTypes2.default.object, utcOffset: _propTypes2.default.number }; exports.default = Month; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _day = __webpack_require__(18); var _day2 = _interopRequireDefault(_day); var _week_number = __webpack_require__(19); var _week_number2 = _interopRequireDefault(_week_number); var _date_utils = __webpack_require__(12); var utils = _interopRequireWildcard(_date_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Week = function (_React$Component) { _inherits(Week, _React$Component); function Week() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Week); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Week.__proto__ || Object.getPrototypeOf(Week)).call.apply(_ref, [this].concat(args))), _this), _this.handleDayClick = function (day, event) { if (_this.props.onDayClick) { _this.props.onDayClick(day, event); } }, _this.handleDayMouseEnter = function (day) { if (_this.props.onDayMouseEnter) { _this.props.onDayMouseEnter(day); } }, _this.handleWeekClick = function (day, weekNumber, event) { if (typeof _this.props.onWeekSelect === 'function') { _this.props.onWeekSelect(day, weekNumber, event); } }, _this.formatWeekNumber = function (startOfWeek) { if (_this.props.formatWeekNumber) { return _this.props.formatWeekNumber(startOfWeek); } return utils.getWeek(startOfWeek); }, _this.renderDays = function () { var startOfWeek = utils.getStartOfWeek(utils.cloneDate(_this.props.day)); var days = []; var weekNumber = _this.formatWeekNumber(startOfWeek); if (_this.props.showWeekNumber) { var onClickAction = _this.props.onWeekSelect ? _this.handleWeekClick.bind(_this, startOfWeek, weekNumber) : undefined; days.push(_react2.default.createElement(_week_number2.default, { key: 'W', weekNumber: weekNumber, onClick: onClickAction })); } return days.concat([0, 1, 2, 3, 4, 5, 6].map(function (offset) { var day = utils.addDays(utils.cloneDate(startOfWeek), offset); return _react2.default.createElement(_day2.default, { key: offset, day: day, month: _this.props.month, onClick: _this.handleDayClick.bind(_this, day), onMouseEnter: _this.handleDayMouseEnter.bind(_this, day), minDate: _this.props.minDate, maxDate: _this.props.maxDate, excludeDates: _this.props.excludeDates, includeDates: _this.props.includeDates, inline: _this.props.inline, highlightDates: _this.props.highlightDates, selectingDate: _this.props.selectingDate, filterDate: _this.props.filterDate, preSelection: _this.props.preSelection, selected: _this.props.selected, selectsStart: _this.props.selectsStart, selectsEnd: _this.props.selectsEnd, startDate: _this.props.startDate, endDate: _this.props.endDate, dayClassName: _this.props.dayClassName, utcOffset: _this.props.utcOffset }); })); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Week, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: 'react-datepicker__week' }, this.renderDays() ); } }]); return Week; }(_react2.default.Component); Week.propTypes = { day: _propTypes2.default.object.isRequired, dayClassName: _propTypes2.default.func, endDate: _propTypes2.default.object, excludeDates: _propTypes2.default.array, filterDate: _propTypes2.default.func, formatWeekNumber: _propTypes2.default.func, highlightDates: _propTypes2.default.array, includeDates: _propTypes2.default.array, inline: _propTypes2.default.bool, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, month: _propTypes2.default.number, onDayClick: _propTypes2.default.func, onDayMouseEnter: _propTypes2.default.func, onWeekSelect: _propTypes2.default.func, preSelection: _propTypes2.default.object, selected: _propTypes2.default.object, selectingDate: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, showWeekNumber: _propTypes2.default.bool, startDate: _propTypes2.default.object, utcOffset: _propTypes2.default.number }; exports.default = Week; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _date_utils = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Day = function (_React$Component) { _inherits(Day, _React$Component); function Day() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Day); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Day.__proto__ || Object.getPrototypeOf(Day)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (event) { if (!_this.isDisabled() && _this.props.onClick) { _this.props.onClick(event); } }, _this.handleMouseEnter = function (event) { if (!_this.isDisabled() && _this.props.onMouseEnter) { _this.props.onMouseEnter(event); } }, _this.isSameDay = function (other) { return (0, _date_utils.isSameDay)(_this.props.day, other); }, _this.isKeyboardSelected = function () { return !_this.props.inline && !_this.isSameDay(_this.props.selected) && _this.isSameDay(_this.props.preSelection); }, _this.isDisabled = function () { return (0, _date_utils.isDayDisabled)(_this.props.day, _this.props); }, _this.getHighLightedClass = function (defaultClassName) { var _this$props = _this.props, day = _this$props.day, highlightDates = _this$props.highlightDates; if (!highlightDates) { return _defineProperty({}, defaultClassName, false); } var classNames = {}; for (var i = 0, len = highlightDates.length; i < len; i++) { var obj = highlightDates[i]; if ((0, _date_utils.isMoment)(obj)) { if ((0, _date_utils.isSameDay)(day, obj)) { classNames[defaultClassName] = true; } } else if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object') { var keys = Object.keys(obj); var arr = obj[keys[0]]; if (typeof keys[0] === 'string' && arr.constructor === Array) { for (var k = 0, _len2 = arr.length; k < _len2; k++) { if ((0, _date_utils.isSameDay)(day, arr[k])) { classNames[keys[0]] = true; } } } } } return classNames; }, _this.isInRange = function () { var _this$props2 = _this.props, day = _this$props2.day, startDate = _this$props2.startDate, endDate = _this$props2.endDate; if (!startDate || !endDate) { return false; } return (0, _date_utils.isDayInRange)(day, startDate, endDate); }, _this.isInSelectingRange = function () { var _this$props3 = _this.props, day = _this$props3.day, selectsStart = _this$props3.selectsStart, selectsEnd = _this$props3.selectsEnd, selectingDate = _this$props3.selectingDate, startDate = _this$props3.startDate, endDate = _this$props3.endDate; if (!(selectsStart || selectsEnd) || !selectingDate || _this.isDisabled()) { return false; } if (selectsStart && endDate && selectingDate.isSameOrBefore(endDate)) { return (0, _date_utils.isDayInRange)(day, selectingDate, endDate); } if (selectsEnd && startDate && selectingDate.isSameOrAfter(startDate)) { return (0, _date_utils.isDayInRange)(day, startDate, selectingDate); } return false; }, _this.isSelectingRangeStart = function () { if (!_this.isInSelectingRange()) { return false; } var _this$props4 = _this.props, day = _this$props4.day, selectingDate = _this$props4.selectingDate, startDate = _this$props4.startDate, selectsStart = _this$props4.selectsStart; if (selectsStart) { return (0, _date_utils.isSameDay)(day, selectingDate); } else { return (0, _date_utils.isSameDay)(day, startDate); } }, _this.isSelectingRangeEnd = function () { if (!_this.isInSelectingRange()) { return false; } var _this$props5 = _this.props, day = _this$props5.day, selectingDate = _this$props5.selectingDate, endDate = _this$props5.endDate, selectsEnd = _this$props5.selectsEnd; if (selectsEnd) { return (0, _date_utils.isSameDay)(day, selectingDate); } else { return (0, _date_utils.isSameDay)(day, endDate); } }, _this.isRangeStart = function () { var _this$props6 = _this.props, day = _this$props6.day, startDate = _this$props6.startDate, endDate = _this$props6.endDate; if (!startDate || !endDate) { return false; } return (0, _date_utils.isSameDay)(startDate, day); }, _this.isRangeEnd = function () { var _this$props7 = _this.props, day = _this$props7.day, startDate = _this$props7.startDate, endDate = _this$props7.endDate; if (!startDate || !endDate) { return false; } return (0, _date_utils.isSameDay)(endDate, day); }, _this.isWeekend = function () { var weekday = (0, _date_utils.getDay)(_this.props.day); return weekday === 0 || weekday === 6; }, _this.isOutsideMonth = function () { return _this.props.month !== undefined && _this.props.month !== (0, _date_utils.getMonth)(_this.props.day); }, _this.getClassNames = function (date) { var dayClassName = _this.props.dayClassName ? _this.props.dayClassName(date) : undefined; return (0, _classnames2.default)('react-datepicker__day', dayClassName, 'react-datepicker__day--' + (0, _date_utils.getDayOfWeekCode)(_this.props.day), { 'react-datepicker__day--disabled': _this.isDisabled(), 'react-datepicker__day--selected': _this.isSameDay(_this.props.selected), 'react-datepicker__day--keyboard-selected': _this.isKeyboardSelected(), 'react-datepicker__day--range-start': _this.isRangeStart(), 'react-datepicker__day--range-end': _this.isRangeEnd(), 'react-datepicker__day--in-range': _this.isInRange(), 'react-datepicker__day--in-selecting-range': _this.isInSelectingRange(), 'react-datepicker__day--selecting-range-start': _this.isSelectingRangeStart(), 'react-datepicker__day--selecting-range-end': _this.isSelectingRangeEnd(), 'react-datepicker__day--today': _this.isSameDay((0, _date_utils.now)(_this.props.utcOffset)), 'react-datepicker__day--weekend': _this.isWeekend(), 'react-datepicker__day--outside-month': _this.isOutsideMonth() }, _this.getHighLightedClass('react-datepicker__day--highlighted')); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Day, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: this.getClassNames(this.props.day), onClick: this.handleClick, onMouseEnter: this.handleMouseEnter, 'aria-label': 'day-' + (0, _date_utils.getDate)(this.props.day), role: 'option' }, (0, _date_utils.getDate)(this.props.day) ); } }]); return Day; }(_react2.default.Component); Day.propTypes = { day: _propTypes2.default.object.isRequired, dayClassName: _propTypes2.default.func, endDate: _propTypes2.default.object, highlightDates: _propTypes2.default.array, inline: _propTypes2.default.bool, month: _propTypes2.default.number, onClick: _propTypes2.default.func, onMouseEnter: _propTypes2.default.func, preSelection: _propTypes2.default.object, selected: _propTypes2.default.object, selectingDate: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, startDate: _propTypes2.default.object, utcOffset: _propTypes2.default.number }; exports.default = Day; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var WeekNumber = function (_React$Component) { _inherits(WeekNumber, _React$Component); function WeekNumber() { var _ref; var _temp, _this, _ret; _classCallCheck(this, WeekNumber); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = WeekNumber.__proto__ || Object.getPrototypeOf(WeekNumber)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (event) { if (_this.props.onClick) { _this.props.onClick(event); } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(WeekNumber, [{ key: 'render', value: function render() { var weekNumberClasses = { 'react-datepicker__week-number': true, 'react-datepicker__week-number--clickable': !!this.props.onClick }; return _react2.default.createElement( 'div', { className: (0, _classnames2.default)(weekNumberClasses), 'aria-label': 'week-' + this.props.weekNumber, onClick: this.handleClick }, this.props.weekNumber ); } }]); return WeekNumber; }(_react2.default.Component); WeekNumber.propTypes = { weekNumber: _propTypes2.default.number.isRequired, onClick: _propTypes2.default.func }; exports.default = WeekNumber; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _date_utils = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Time = function (_React$Component) { _inherits(Time, _React$Component); function Time() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Time); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Time.__proto__ || Object.getPrototypeOf(Time)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (time) { if ((_this.props.minTime || _this.props.maxTime) && (0, _date_utils.isTimeInDisabledRange)(time, _this.props) || _this.props.excludeTimes && (0, _date_utils.isTimeDisabled)(time, _this.props.excludeTimes)) { return; } _this.props.onChange(time); }, _this.liClasses = function (time, currH, currM) { var classes = ['react-datepicker__time-list-item']; if (currH === (0, _date_utils.getHour)(time) && currM === (0, _date_utils.getMinute)(time)) { classes.push('react-datepicker__time-list-item--selected'); } if ((_this.props.minTime || _this.props.maxTime) && (0, _date_utils.isTimeInDisabledRange)(time, _this.props) || _this.props.excludeTimes && (0, _date_utils.isTimeDisabled)(time, _this.props.excludeTimes)) { classes.push('react-datepicker__time-list-item--disabled'); } return classes.join(' '); }, _this.renderTimes = function () { var times = []; var format = _this.props.format ? _this.props.format : 'hh:mm A'; var intervals = _this.props.intervals; var activeTime = _this.props.selected ? _this.props.selected : (0, _date_utils.newDate)(); var currH = (0, _date_utils.getHour)(activeTime); var currM = (0, _date_utils.getMinute)(activeTime); var base = (0, _date_utils.getStartOfDay)((0, _date_utils.newDate)()); var multiplier = 1440 / intervals; for (var i = 0; i < multiplier; i++) { times.push((0, _date_utils.addMinutes)((0, _date_utils.cloneDate)(base), i * intervals)); } return times.map(function (time, i) { return _react2.default.createElement( 'li', { key: i, onClick: _this.handleClick.bind(_this, time), className: _this.liClasses(time, currH, currM) }, (0, _date_utils.formatDate)(time, format) ); }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Time, [{ key: 'componentDidMount', value: function componentDidMount() { // code to ensure selected time will always be in focus within time window when it first appears var multiplier = 60 / this.props.intervals; var currH = this.props.selected ? (0, _date_utils.getHour)(this.props.selected) : (0, _date_utils.getHour)((0, _date_utils.newDate)()); this.list.scrollTop = 30 * (multiplier * currH); } }, { key: 'render', value: function render() { var _this2 = this; var height = null; if (this.props.monthRef) { height = this.props.monthRef.clientHeight - 39; } return _react2.default.createElement( 'div', { className: 'react-datepicker__time-container ' + (this.props.todayButton ? 'react-datepicker__time-container--with-today-button' : '') }, _react2.default.createElement( 'div', { className: 'react-datepicker__header react-datepicker__header--time' }, _react2.default.createElement( 'div', { className: 'react-datepicker-time__header' }, 'Time' ) ), _react2.default.createElement( 'div', { className: 'react-datepicker__time' }, _react2.default.createElement( 'div', { className: 'react-datepicker__time-box' }, _react2.default.createElement( 'ul', { className: 'react-datepicker__time-list', ref: function ref(list) { _this2.list = list; }, style: height ? { height: height } : {} }, this.renderTimes.bind(this)() ) ) ) ); } }], [{ key: 'defaultProps', get: function get() { return { intervals: 30, onTimeChange: function onTimeChange() {}, todayButton: null }; } }]); return Time; }(_react2.default.Component); Time.propTypes = { format: _propTypes2.default.string, intervals: _propTypes2.default.number, selected: _propTypes2.default.object, onChange: _propTypes2.default.func, todayButton: _propTypes2.default.string, minTime: _propTypes2.default.object, maxTime: _propTypes2.default.object, excludeTimes: _propTypes2.default.array, monthRef: _propTypes2.default.object }; exports.default = Time; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.popperPlacementPositions = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactPopper = __webpack_require__(22); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var popperPlacementPositions = exports.popperPlacementPositions = ['auto', 'auto-left', 'auto-right', 'bottom', 'bottom-end', 'bottom-start', 'left', 'left-end', 'left-start', 'right', 'right-end', 'right-start', 'top', 'top-end', 'top-start']; var PopperComponent = function (_React$Component) { _inherits(PopperComponent, _React$Component); function PopperComponent() { _classCallCheck(this, PopperComponent); return _possibleConstructorReturn(this, (PopperComponent.__proto__ || Object.getPrototypeOf(PopperComponent)).apply(this, arguments)); } _createClass(PopperComponent, [{ key: 'render', value: function render() { var _props = this.props, className = _props.className, hidePopper = _props.hidePopper, popperComponent = _props.popperComponent, popperModifiers = _props.popperModifiers, popperPlacement = _props.popperPlacement, targetComponent = _props.targetComponent; var popper = void 0; if (!hidePopper) { var classes = (0, _classnames2.default)('react-datepicker-popper', className); popper = _react2.default.createElement( _reactPopper.Popper, { className: classes, modifiers: popperModifiers, placement: popperPlacement }, popperComponent ); } if (this.props.popperContainer) { popper = _react2.default.createElement(this.props.popperContainer, {}, popper); } return _react2.default.createElement( _reactPopper.Manager, null, _react2.default.createElement( _reactPopper.Target, { className: 'react-datepicker-wrapper' }, targetComponent ), popper ); } }], [{ key: 'defaultProps', get: function get() { return { hidePopper: true, popperModifiers: { preventOverflow: { enabled: true, escapeWithReference: true, boundariesElement: 'viewport' } }, popperPlacement: 'bottom-start' }; } }]); return PopperComponent; }(_react2.default.Component); PopperComponent.propTypes = { className: _propTypes2.default.string, hidePopper: _propTypes2.default.bool, popperComponent: _propTypes2.default.element, popperModifiers: _propTypes2.default.object, // <datepicker/> props popperPlacement: _propTypes2.default.oneOf(popperPlacementPositions), // <datepicker/> props popperContainer: _propTypes2.default.func, targetComponent: _propTypes2.default.element }; exports.default = PopperComponent; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Arrow = exports.Popper = exports.Target = exports.Manager = undefined; var _Manager2 = __webpack_require__(23); var _Manager3 = _interopRequireDefault(_Manager2); var _Target2 = __webpack_require__(24); var _Target3 = _interopRequireDefault(_Target2); var _Popper2 = __webpack_require__(25); var _Popper3 = _interopRequireDefault(_Popper2); var _Arrow2 = __webpack_require__(27); var _Arrow3 = _interopRequireDefault(_Arrow2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.Manager = _Manager3.default; exports.Target = _Target3.default; exports.Popper = _Popper3.default; exports.Arrow = _Arrow3.default; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Manager = function (_Component) { _inherits(Manager, _Component); function Manager() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Manager); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Manager.__proto__ || Object.getPrototypeOf(Manager)).call.apply(_ref, [this].concat(args))), _this), _this._setTargetNode = function (node) { _this._targetNode = node; }, _this._getTargetNode = function () { return _this._targetNode; }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Manager, [{ key: 'getChildContext', value: function getChildContext() { return { popperManager: { setTargetNode: this._setTargetNode, getTargetNode: this._getTargetNode } }; } }, { key: 'render', value: function render() { var _props = this.props, tag = _props.tag, children = _props.children, restProps = _objectWithoutProperties(_props, ['tag', 'children']); if (tag !== false) { return (0, _react.createElement)(tag, restProps, children); } else { return children; } } }]); return Manager; }(_react.Component); Manager.childContextTypes = { popperManager: _propTypes2.default.object.isRequired }; Manager.propTypes = { tag: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.bool]) }; Manager.defaultProps = { tag: 'div' }; exports.default = Manager; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var Target = function Target(props, context) { var _props$component = props.component, component = _props$component === undefined ? 'div' : _props$component, innerRef = props.innerRef, children = props.children, restProps = _objectWithoutProperties(props, ['component', 'innerRef', 'children']); var popperManager = context.popperManager; var targetRef = function targetRef(node) { popperManager.setTargetNode(node); if (typeof innerRef === 'function') { innerRef(node); } }; if (typeof children === 'function') { var targetProps = { ref: targetRef }; return children({ targetProps: targetProps, restProps: restProps }); } var componentProps = _extends({}, restProps); if (typeof component === 'string') { componentProps.ref = targetRef; } else { componentProps.innerRef = targetRef; } return (0, _react.createElement)(component, componentProps, children); }; Target.contextTypes = { popperManager: _propTypes2.default.object.isRequired }; Target.propTypes = { component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]), innerRef: _propTypes2.default.func, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; exports.default = Target; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _popper = __webpack_require__(26); var _popper2 = _interopRequireDefault(_popper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var noop = function noop() { return null; }; var Popper = function (_Component) { _inherits(Popper, _Component); function Popper() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Popper); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Popper.__proto__ || Object.getPrototypeOf(Popper)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this._setArrowNode = function (node) { _this._arrowNode = node; }, _this._getTargetNode = function () { return _this.context.popperManager.getTargetNode(); }, _this._getOffsets = function (data) { return Object.keys(data.offsets).map(function (key) { return data.offsets[key]; }); }, _this._isDataDirty = function (data) { if (_this.state.data) { return JSON.stringify(_this._getOffsets(_this.state.data)) !== JSON.stringify(_this._getOffsets(data)); } else { return true; } }, _this._updateStateModifier = { enabled: true, order: 900, fn: function fn(data) { if (_this._isDataDirty(data)) { _this.setState({ data: data }); } return data; } }, _this._getPopperStyle = function () { var data = _this.state.data; // If Popper isn't instantiated, hide the popperElement // to avoid flash of unstyled content if (!_this._popper || !data) { return { position: 'absolute', pointerEvents: 'none', opacity: 0 }; } var _data$offsets$popper = data.offsets.popper, top = _data$offsets$popper.top, left = _data$offsets$popper.left, position = _data$offsets$popper.position; return _extends({ position: position }, data.styles); }, _this._getPopperPlacement = function () { return !!_this.state.data ? _this.state.data.placement : undefined; }, _this._getPopperHide = function () { return !!_this.state.data && _this.state.data.hide ? '' : undefined; }, _this._getArrowStyle = function () { if (!_this.state.data || !_this.state.data.offsets.arrow) { return {}; } else { var _this$state$data$offs = _this.state.data.offsets.arrow, top = _this$state$data$offs.top, left = _this$state$data$offs.left; return { top: top, left: left }; } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Popper, [{ key: 'getChildContext', value: function getChildContext() { return { popper: { setArrowNode: this._setArrowNode, getArrowStyle: this._getArrowStyle } }; } }, { key: 'componentDidMount', value: function componentDidMount() { this._updatePopper(); } }, { key: 'componentDidUpdate', value: function componentDidUpdate(lastProps) { if (lastProps.placement !== this.props.placement || lastProps.eventsEnabled !== this.props.eventsEnabled) { this._updatePopper(); } if (this._popper && lastProps.children !== this.props.children) { this._popper.scheduleUpdate(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this._destroyPopper(); } }, { key: '_updatePopper', value: function _updatePopper() { this._destroyPopper(); if (this._node) { this._createPopper(); } } }, { key: '_createPopper', value: function _createPopper() { var _props = this.props, placement = _props.placement, eventsEnabled = _props.eventsEnabled; var modifiers = _extends({}, this.props.modifiers, { applyStyle: { enabled: false }, updateState: this._updateStateModifier }); if (this._arrowNode) { modifiers.arrow = { element: this._arrowNode }; } this._popper = new _popper2.default(this._getTargetNode(), this._node, { placement: placement, eventsEnabled: eventsEnabled, modifiers: modifiers }); // schedule an update to make sure everything gets positioned correct // after being instantiated this._popper.scheduleUpdate(); } }, { key: '_destroyPopper', value: function _destroyPopper() { if (this._popper) { this._popper.destroy(); } } }, { key: 'render', value: function render() { var _this2 = this; var _props2 = this.props, component = _props2.component, innerRef = _props2.innerRef, placement = _props2.placement, eventsEnabled = _props2.eventsEnabled, modifiers = _props2.modifiers, children = _props2.children, restProps = _objectWithoutProperties(_props2, ['component', 'innerRef', 'placement', 'eventsEnabled', 'modifiers', 'children']); var popperRef = function popperRef(node) { _this2._node = node; if (typeof innerRef === 'function') { innerRef(node); } }; var popperStyle = this._getPopperStyle(); var popperPlacement = this._getPopperPlacement(); var popperHide = this._getPopperHide(); if (typeof children === 'function') { var _popperProps; var popperProps = (_popperProps = { ref: popperRef, style: popperStyle }, _defineProperty(_popperProps, 'data-placement', popperPlacement), _defineProperty(_popperProps, 'data-x-out-of-boundaries', popperHide), _popperProps); return children({ popperProps: popperProps, restProps: restProps, scheduleUpdate: this._popper && this._popper.scheduleUpdate }); } var componentProps = _extends({}, restProps, { style: _extends({}, restProps.style, popperStyle), 'data-placement': popperPlacement, 'data-x-out-of-boundaries': popperHide }); if (typeof component === 'string') { componentProps.ref = popperRef; } else { componentProps.innerRef = popperRef; } return (0, _react.createElement)(component, componentProps, children); } }]); return Popper; }(_react.Component); Popper.contextTypes = { popperManager: _propTypes2.default.object.isRequired }; Popper.childContextTypes = { popper: _propTypes2.default.object.isRequired }; Popper.propTypes = { component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]), innerRef: _propTypes2.default.func, placement: _propTypes2.default.oneOf(_popper2.default.placements), eventsEnabled: _propTypes2.default.bool, modifiers: _propTypes2.default.object, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; Popper.defaultProps = { component: 'div', placement: 'bottom', eventsEnabled: true, modifiers: {} }; exports.default = Popper; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/**! * @fileOverview Kickass library to create and place poppers near their reference elements. * @version 1.12.6 * @license * Copyright (c) 2016 Federico Zivolo and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Popper = factory()); }(this, (function () { 'use strict'; var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined'; var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; var timeoutDuration = 0; for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) { if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { timeoutDuration = 1; break; } } function microtaskDebounce(fn) { var called = false; return function () { if (called) { return; } called = true; Promise.resolve().then(function () { called = false; fn(); }); }; } function taskDebounce(fn) { var scheduled = false; return function () { if (!scheduled) { scheduled = true; setTimeout(function () { scheduled = false; fn(); }, timeoutDuration); } }; } var supportsMicroTasks = isBrowser && window.Promise; /** * Create a debounced version of a method, that's asynchronously deferred * but called in the minimum time possible. * * @method * @memberof Popper.Utils * @argument {Function} fn * @returns {Function} */ var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce; /** * Check if the given variable is a function * @method * @memberof Popper.Utils * @argument {Any} functionToCheck - variable to check * @returns {Boolean} answer to: is a function? */ function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /** * Get CSS computed property of the given element * @method * @memberof Popper.Utils * @argument {Eement} element * @argument {String} property */ function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here var css = window.getComputedStyle(element, null); return property ? css[property] : css; } /** * Returns the parentNode or the host of the element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} parent */ function getParentNode(element) { if (element.nodeName === 'HTML') { return element; } return element.parentNode || element.host; } /** * Returns the scrolling parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} scroll parent */ function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element) { return window.document.body; } switch (element.nodeName) { case 'HTML': case 'BODY': return element.ownerDocument.body; case '#document': return element.body; } // Firefox want us to check `-x` and `-y` variations as well var _getStyleComputedProp = getStyleComputedProperty(element), overflow = _getStyleComputedProp.overflow, overflowX = _getStyleComputedProp.overflowX, overflowY = _getStyleComputedProp.overflowY; if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); } /** * Returns the offset parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} offset parent */ function getOffsetParent(element) { // NOTE: 1 DOM access here var offsetParent = element && element.offsetParent; var nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { if (element) { return element.ownerDocument.documentElement; } return window.document.documentElement; } // .offsetParent will return the closest TD or TABLE in case // no offsetParent is present, I hate this job... if (['TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { return getOffsetParent(offsetParent); } return offsetParent; } function isOffsetContainer(element) { var nodeName = element.nodeName; if (nodeName === 'BODY') { return false; } return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element; } /** * Finds the root node (document, shadowDOM root) of the given element * @method * @memberof Popper.Utils * @argument {Element} node * @returns {Element} root node */ function getRoot(node) { if (node.parentNode !== null) { return getRoot(node.parentNode); } return node; } /** * Finds the offset parent common to the two provided nodes * @method * @memberof Popper.Utils * @argument {Element} element1 * @argument {Element} element2 * @returns {Element} common offset parent */ function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return window.document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; var start = order ? element1 : element2; var end = order ? element2 : element1; // Get common ancestor container var range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); var commonAncestorContainer = range.commonAncestorContainer; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one var element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } } /** * Gets the scroll value of the given element in the given side (top and left) * @method * @memberof Popper.Utils * @argument {Element} element * @argument {String} side `top` or `left` * @returns {number} amount of scrolled pixels */ function getScroll(element) { var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top'; var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft'; var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { var html = element.ownerDocument.documentElement; var scrollingElement = element.ownerDocument.scrollingElement || html; return scrollingElement[upperSide]; } return element[upperSide]; } /* * Sum or subtract the element scroll values (left and top) from a given rect object * @method * @memberof Popper.Utils * @param {Object} rect - Rect object you want to change * @param {HTMLElement} element - The element from the function reads the scroll values * @param {Boolean} subtract - set to true if you want to subtract the scroll values * @return {Object} rect - The modifier rect object */ function includeScroll(rect, element) { var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); var modifier = subtract ? -1 : 1; rect.top += scrollTop * modifier; rect.bottom += scrollTop * modifier; rect.left += scrollLeft * modifier; rect.right += scrollLeft * modifier; return rect; } /* * Helper to detect borders of a given element * @method * @memberof Popper.Utils * @param {CSSStyleDeclaration} styles * Result of `getStyleComputedProperty` on the given element * @param {String} axis - `x` or `y` * @return {number} borders - The borders size of the given axis */ function getBordersSize(styles, axis) { var sideA = axis === 'x' ? 'Left' : 'Top'; var sideB = sideA === 'Left' ? 'Right' : 'Bottom'; return +styles['border' + sideA + 'Width'].split('px')[0] + +styles['border' + sideB + 'Width'].split('px')[0]; } /** * Tells if you are running Internet Explorer 10 * @method * @memberof Popper.Utils * @returns {Boolean} isIE10 */ var isIE10 = undefined; var isIE10$1 = function () { if (isIE10 === undefined) { isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1; } return isIE10; }; function getSize(axis, body, html, computedStyle) { return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE10$1() ? html['offset' + axis] + computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')] + computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')] : 0); } function getWindowSizes() { var body = window.document.body; var html = window.document.documentElement; var computedStyle = isIE10$1() && window.getComputedStyle(html); return { height: getSize('Height', body, html, computedStyle), width: getSize('Width', body, html, computedStyle) }; } var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Given element offsets, generate an output similar to getBoundingClientRect * @method * @memberof Popper.Utils * @argument {Object} offsets * @returns {Object} ClientRect like output */ function getClientRect(offsets) { return _extends({}, offsets, { right: offsets.left + offsets.width, bottom: offsets.top + offsets.height }); } /** * Get bounding client rect of given element * @method * @memberof Popper.Utils * @param {HTMLElement} element * @return {Object} client rect */ function getBoundingClientRect(element) { var rect = {}; // IE10 10 FIX: Please, don't ask, the element isn't // considered in DOM in some circumstances... // This isn't reproducible in IE10 compatibility mode of IE11 if (isIE10$1()) { try { rect = element.getBoundingClientRect(); var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); rect.top += scrollTop; rect.left += scrollLeft; rect.bottom += scrollTop; rect.right += scrollLeft; } catch (err) {} } else { rect = element.getBoundingClientRect(); } var result = { left: rect.left, top: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; // subtract scrollbar size from sizes var sizes = element.nodeName === 'HTML' ? getWindowSizes() : {}; var width = sizes.width || element.clientWidth || result.right - result.left; var height = sizes.height || element.clientHeight || result.bottom - result.top; var horizScrollbar = element.offsetWidth - width; var vertScrollbar = element.offsetHeight - height; // if an hypothetical scrollbar is detected, we must be sure it's not a `border` // we make this check conditional for performance reasons if (horizScrollbar || vertScrollbar) { var styles = getStyleComputedProperty(element); horizScrollbar -= getBordersSize(styles, 'x'); vertScrollbar -= getBordersSize(styles, 'y'); result.width -= horizScrollbar; result.height -= vertScrollbar; } return getClientRect(result); } function getOffsetRectRelativeToArbitraryNode(children, parent) { var isIE10 = isIE10$1(); var isHTML = parent.nodeName === 'HTML'; var childrenRect = getBoundingClientRect(children); var parentRect = getBoundingClientRect(parent); var scrollParent = getScrollParent(children); var styles = getStyleComputedProperty(parent); var borderTopWidth = +styles.borderTopWidth.split('px')[0]; var borderLeftWidth = +styles.borderLeftWidth.split('px')[0]; var offsets = getClientRect({ top: childrenRect.top - parentRect.top - borderTopWidth, left: childrenRect.left - parentRect.left - borderLeftWidth, width: childrenRect.width, height: childrenRect.height }); offsets.marginTop = 0; offsets.marginLeft = 0; // Subtract margins of documentElement in case it's being used as parent // we do this only on HTML because it's the only element that behaves // differently when margins are applied to it. The margins are included in // the box of the documentElement, in the other cases not. if (!isIE10 && isHTML) { var marginTop = +styles.marginTop.split('px')[0]; var marginLeft = +styles.marginLeft.split('px')[0]; offsets.top -= borderTopWidth - marginTop; offsets.bottom -= borderTopWidth - marginTop; offsets.left -= borderLeftWidth - marginLeft; offsets.right -= borderLeftWidth - marginLeft; // Attach marginTop and marginLeft because in some circumstances we may need them offsets.marginTop = marginTop; offsets.marginLeft = marginLeft; } if (isIE10 ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') { offsets = includeScroll(offsets, parent); } return offsets; } function getViewportOffsetRectRelativeToArtbitraryNode(element) { var html = element.ownerDocument.documentElement; var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html); var width = Math.max(html.clientWidth, window.innerWidth || 0); var height = Math.max(html.clientHeight, window.innerHeight || 0); var scrollTop = getScroll(html); var scrollLeft = getScroll(html, 'left'); var offset = { top: scrollTop - relativeOffset.top + relativeOffset.marginTop, left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft, width: width, height: height }; return getClientRect(offset); } /** * Check if the given element is fixed or is inside a fixed parent * @method * @memberof Popper.Utils * @argument {Element} element * @argument {Element} customContainer * @returns {Boolean} answer to "isFixed?" */ function isFixed(element) { var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { return false; } if (getStyleComputedProperty(element, 'position') === 'fixed') { return true; } return isFixed(getParentNode(element)); } /** * Computed the boundaries limits and return them * @method * @memberof Popper.Utils * @param {HTMLElement} popper * @param {HTMLElement} reference * @param {number} padding * @param {HTMLElement} boundariesElement - Element used to define the boundaries * @returns {Object} Coordinates of the boundaries */ function getBoundaries(popper, reference, padding, boundariesElement) { // NOTE: 1 DOM access here var boundaries = { top: 0, left: 0 }; var offsetParent = findCommonOffsetParent(popper, reference); // Handle viewport case if (boundariesElement === 'viewport') { boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent); } else { // Handle other cases based on DOM element used as boundaries var boundariesNode = void 0; if (boundariesElement === 'scrollParent') { boundariesNode = getScrollParent(getParentNode(popper)); if (boundariesNode.nodeName === 'BODY') { boundariesNode = popper.ownerDocument.documentElement; } } else if (boundariesElement === 'window') { boundariesNode = popper.ownerDocument.documentElement; } else { boundariesNode = boundariesElement; } var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent); // In case of HTML, we need a different computation if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) { var _getWindowSizes = getWindowSizes(), height = _getWindowSizes.height, width = _getWindowSizes.width; boundaries.top += offsets.top - offsets.marginTop; boundaries.bottom = height + offsets.top; boundaries.left += offsets.left - offsets.marginLeft; boundaries.right = width + offsets.left; } else { // for all the other DOM elements, this one is good boundaries = offsets; } } // Add paddings boundaries.left += padding; boundaries.top += padding; boundaries.right -= padding; boundaries.bottom -= padding; return boundaries; } function getArea(_ref) { var width = _ref.width, height = _ref.height; return width * height; } /** * Utility used to transform the `auto` placement to the placement with more * available space. * @method * @memberof Popper.Utils * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) { var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; if (placement.indexOf('auto') === -1) { return placement; } var boundaries = getBoundaries(popper, reference, padding, boundariesElement); var rects = { top: { width: boundaries.width, height: refRect.top - boundaries.top }, right: { width: boundaries.right - refRect.right, height: boundaries.height }, bottom: { width: boundaries.width, height: boundaries.bottom - refRect.bottom }, left: { width: refRect.left - boundaries.left, height: boundaries.height } }; var sortedAreas = Object.keys(rects).map(function (key) { return _extends({ key: key }, rects[key], { area: getArea(rects[key]) }); }).sort(function (a, b) { return b.area - a.area; }); var filteredAreas = sortedAreas.filter(function (_ref2) { var width = _ref2.width, height = _ref2.height; return width >= popper.clientWidth && height >= popper.clientHeight; }); var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; var variation = placement.split('-')[1]; return computedPlacement + (variation ? '-' + variation : ''); } /** * Get offsets to the reference element * @method * @memberof Popper.Utils * @param {Object} state * @param {Element} popper - the popper element * @param {Element} reference - the reference element (the popper will be relative to this) * @returns {Object} An object containing the offsets which will be applied to the popper */ function getReferenceOffsets(state, popper, reference) { var commonOffsetParent = findCommonOffsetParent(popper, reference); return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent); } /** * Get the outer sizes of the given element (offset size + margins) * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Object} object containing width and height properties */ function getOuterSizes(element) { var styles = window.getComputedStyle(element); var x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom); var y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight); var result = { width: element.offsetWidth + y, height: element.offsetHeight + x }; return result; } /** * Get the opposite placement of the given one * @method * @memberof Popper.Utils * @argument {String} placement * @returns {String} flipped placement */ function getOppositePlacement(placement) { var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, function (matched) { return hash[matched]; }); } /** * Get offsets to the popper * @method * @memberof Popper.Utils * @param {Object} position - CSS position the Popper will get applied * @param {HTMLElement} popper - the popper element * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) * @param {String} placement - one of the valid placement options * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper */ function getPopperOffsets(popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes var popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object var popperOffsets = { width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently var isHoriz = ['right', 'left'].indexOf(placement) !== -1; var mainSide = isHoriz ? 'top' : 'left'; var secondarySide = isHoriz ? 'left' : 'top'; var measurement = isHoriz ? 'height' : 'width'; var secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; } /** * Mimics the `find` method of Array * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function find(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; } /** * Return the index of the matching object * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function findIndex(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(function (cur) { return cur[prop] === value; }); } // use `find` + `indexOf` if `findIndex` isn't supported var match = find(arr, function (obj) { return obj[prop] === value; }); return arr.indexOf(match); } /** * Loop trough the list of modifiers and run them in order, * each of them will then edit the data object. * @method * @memberof Popper.Utils * @param {dataObject} data * @param {Array} modifiers * @param {String} ends - Optional modifier name used as stopper * @returns {dataObject} */ function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier['function']) { // eslint-disable-line dot-notation console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation if (modifier.enabled && isFunction(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; } /** * Updates the position of the popper, computing the new offsets and applying * the new style.<br /> * Prefer `scheduleUpdate` over `update` because of performance reasons. * @method * @memberof Popper */ function update() { // if popper is destroyed, don't perform any further update if (this.state.isDestroyed) { return; } var data = { instance: this, styles: {}, arrowStyles: {}, attributes: {}, flipped: false, offsets: {} }; // compute reference element offsets data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding); // store the computed placement inside `originalPlacement` data.originalPlacement = data.placement; // compute the popper offsets data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement); data.offsets.popper.position = 'absolute'; // run the modifiers data = runModifiers(this.modifiers, data); // the first `update` will call `onCreate` callback // the other ones will call `onUpdate` callback if (!this.state.isCreated) { this.state.isCreated = true; this.options.onCreate(data); } else { this.options.onUpdate(data); } } /** * Helper used to know if the given modifier is enabled. * @method * @memberof Popper.Utils * @returns {Boolean} */ function isModifierEnabled(modifiers, modifierName) { return modifiers.some(function (_ref) { var name = _ref.name, enabled = _ref.enabled; return enabled && name === modifierName; }); } /** * Get the prefixed supported property name * @method * @memberof Popper.Utils * @argument {String} property (camelCase) * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix) */ function getSupportedPropertyName(property) { var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; var upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (var i = 0; i < prefixes.length - 1; i++) { var prefix = prefixes[i]; var toCheck = prefix ? '' + prefix + upperProp : property; if (typeof window.document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; } /** * Destroy the popper * @method * @memberof Popper */ function destroy() { this.state.isDestroyed = true; // touch DOM only if `applyStyle` modifier is enabled if (isModifierEnabled(this.modifiers, 'applyStyle')) { this.popper.removeAttribute('x-placement'); this.popper.style.left = ''; this.popper.style.position = ''; this.popper.style.top = ''; this.popper.style[getSupportedPropertyName('transform')] = ''; } this.disableEventListeners(); // remove the popper if user explicity asked for the deletion on destroy // do not use `remove` because IE11 doesn't support it if (this.options.removeOnDestroy) { this.popper.parentNode.removeChild(this.popper); } return this; } /** * Get the window associated with the element * @argument {Element} element * @returns {Window} */ function getWindow(element) { var ownerDocument = element.ownerDocument; return ownerDocument ? ownerDocument.defaultView : window; } function attachToScrollParents(scrollParent, event, callback, scrollParents) { var isBody = scrollParent.nodeName === 'BODY'; var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent; target.addEventListener(event, callback, { passive: true }); if (!isBody) { attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents); } scrollParents.push(target); } /** * Setup needed event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; getWindow(reference).addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents var scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; } /** * It will add resize/scroll events and start recalculating * position of the popper element when they are triggered. * @method * @memberof Popper */ function enableEventListeners() { if (!this.state.eventsEnabled) { this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate); } } /** * Remove event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function removeEventListeners(reference, state) { // Remove resize event listener on window getWindow(reference).removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(function (target) { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; } /** * It will remove resize/scroll events and won't recalculate popper position * when they are triggered. It also won't trigger onUpdate callback anymore, * unless you call `update` method manually. * @method * @memberof Popper */ function disableEventListeners() { if (this.state.eventsEnabled) { window.cancelAnimationFrame(this.scheduleUpdate); this.state = removeEventListeners(this.reference, this.state); } } /** * Tells if a given input is a number * @method * @memberof Popper.Utils * @param {*} input to check * @return {Boolean} */ function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); } /** * Set the style to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the style to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); } /** * Set the attributes to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the attributes to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} data.styles - List of style properties - values to apply to popper element * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element * @argument {Object} options - Modifiers configuration and options * @returns {Object} The same data object */ function applyStyle(data) { // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! setStyles(data.instance.popper, data.styles); // any property present in `data.attributes` will be applied to the popper, // they will be set as HTML attributes of the element setAttributes(data.instance.popper, data.attributes); // if arrowElement is defined and arrowStyles has some properties if (data.arrowElement && Object.keys(data.arrowStyles).length) { setStyles(data.arrowElement, data.arrowStyles); } return data; } /** * Set the x-placement attribute before everything else because it could be used * to add margins to the popper margins needs to be calculated to get the * correct popper offsets. * @method * @memberof Popper.modifiers * @param {HTMLElement} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper. * @param {Object} options - Popper.js options */ function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets var referenceOffsets = getReferenceOffsets(state, popper, reference); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: 'absolute' }); return options; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeStyle(data, options) { var x = options.x, y = options.y; var popper = data.offsets.popper; // Remove this legacy support in Popper.js v2 var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) { return modifier.name === 'applyStyle'; }).gpuAcceleration; if (legacyGpuAccelerationOption !== undefined) { console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!'); } var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration; var offsetParent = getOffsetParent(data.instance.popper); var offsetParentRect = getBoundingClientRect(offsetParent); // Styles var styles = { position: popper.position }; // floor sides to avoid blurry text var offsets = { left: Math.floor(popper.left), top: Math.floor(popper.top), bottom: Math.floor(popper.bottom), right: Math.floor(popper.right) }; var sideA = x === 'bottom' ? 'top' : 'bottom'; var sideB = y === 'right' ? 'left' : 'right'; // if gpuAcceleration is set to `true` and transform is supported, // we use `translate3d` to apply the position to the popper we // automatically use the supported prefixed version if needed var prefixedProperty = getSupportedPropertyName('transform'); // now, let's make a step back and look at this code closely (wtf?) // If the content of the popper grows once it's been positioned, it // may happen that the popper gets misplaced because of the new content // overflowing its reference element // To avoid this problem, we provide two options (x and y), which allow // the consumer to define the offset origin. // If we position a popper on top of a reference element, we can set // `x` to `top` to make the popper grow towards its top instead of // its bottom. var left = void 0, top = void 0; if (sideA === 'bottom') { top = -offsetParentRect.height + offsets.bottom; } else { top = offsets.top; } if (sideB === 'right') { left = -offsetParentRect.width + offsets.right; } else { left = offsets.left; } if (gpuAcceleration && prefixedProperty) { styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)'; styles[sideA] = 0; styles[sideB] = 0; styles.willChange = 'transform'; } else { // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties var invertTop = sideA === 'bottom' ? -1 : 1; var invertLeft = sideB === 'right' ? -1 : 1; styles[sideA] = top * invertTop; styles[sideB] = left * invertLeft; styles.willChange = sideA + ', ' + sideB; } // Attributes var attributes = { 'x-placement': data.placement }; // Update `data` attributes, styles and arrowStyles data.attributes = _extends({}, attributes, data.attributes); data.styles = _extends({}, styles, data.styles); data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles); return data; } /** * Helper used to know if the given modifier depends from another one.<br /> * It checks if the needed modifier is listed and enabled. * @method * @memberof Popper.Utils * @param {Array} modifiers - list of modifiers * @param {String} requestingName - name of requesting modifier * @param {String} requestedName - name of requested modifier * @returns {Boolean} */ function isModifierRequired(modifiers, requestingName, requestedName) { var requesting = find(modifiers, function (_ref) { var name = _ref.name; return name === requestingName; }); var isRequired = !!requesting && modifiers.some(function (modifier) { return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; }); if (!isRequired) { var _requesting = '`' + requestingName + '`'; var requested = '`' + requestedName + '`'; console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!'); } return isRequired; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function arrow(data, options) { // arrow depends on keepTogether in order to work if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { return data; } var arrowElement = options.element; // if arrowElement is a string, suppose it's a CSS selector if (typeof arrowElement === 'string') { arrowElement = data.instance.popper.querySelector(arrowElement); // if arrowElement is not found, don't run the modifier if (!arrowElement) { return data; } } else { // if the arrowElement isn't a query selector we must check that the // provided DOM node is child of its popper node if (!data.instance.popper.contains(arrowElement)) { console.warn('WARNING: `arrow.element` must be child of its popper element!'); return data; } } var placement = data.placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isVertical = ['left', 'right'].indexOf(placement) !== -1; var len = isVertical ? 'height' : 'width'; var sideCapitalized = isVertical ? 'Top' : 'Left'; var side = sideCapitalized.toLowerCase(); var altSide = isVertical ? 'left' : 'top'; var opSide = isVertical ? 'bottom' : 'right'; var arrowElementSize = getOuterSizes(arrowElement)[len]; // // extends keepTogether behavior making sure the popper and its // reference have enough pixels in conjuction // // top/left side if (reference[opSide] - arrowElementSize < popper[side]) { data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize); } // bottom/right side if (reference[side] + arrowElementSize > popper[opSide]) { data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide]; } // compute center of the popper var center = reference[side] + reference[len] / 2 - arrowElementSize / 2; // Compute the sideValue using the updated popper offsets // take popper margin in account because we don't have this info available var popperMarginSide = getStyleComputedProperty(data.instance.popper, 'margin' + sideCapitalized).replace('px', ''); var sideValue = center - getClientRect(data.offsets.popper)[side] - popperMarginSide; // prevent arrowElement from being placed not contiguously to its popper sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0); data.arrowElement = arrowElement; data.offsets.arrow = {}; data.offsets.arrow[side] = Math.round(sideValue); data.offsets.arrow[altSide] = ''; // make sure to unset any eventual altSide value from the DOM node return data; } /** * Get the opposite placement variation of the given one * @method * @memberof Popper.Utils * @argument {String} placement variation * @returns {String} flipped placement variation */ function getOppositeVariation(variation) { if (variation === 'end') { return 'start'; } else if (variation === 'start') { return 'end'; } return variation; } /** * List of accepted placements to use as values of the `placement` option.<br /> * Valid placements are: * - `auto` * - `top` * - `right` * - `bottom` * - `left` * * Each placement can have a variation from this list: * - `-start` * - `-end` * * Variations are interpreted easily if you think of them as the left to right * written languages. Horizontally (`top` and `bottom`), `start` is left and `end` * is right.<br /> * Vertically (`left` and `right`), `start` is top and `end` is bottom. * * Some valid examples are: * - `top-end` (on top of reference, right aligned) * - `right-start` (on right of reference, top aligned) * - `bottom` (on bottom, centered) * - `auto-right` (on the side with more space available, alignment depends by placement) * * @static * @type {Array} * @enum {String} * @readonly * @method placements * @memberof Popper */ var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']; // Get rid of `auto` `auto-start` and `auto-end` var validPlacements = placements.slice(3); /** * Given an initial placement, returns all the subsequent placements * clockwise (or counter-clockwise). * * @method * @memberof Popper.Utils * @argument {String} placement - A valid placement (it accepts variations) * @argument {Boolean} counter - Set to true to walk the placements counterclockwise * @returns {Array} placements including their variations */ function clockwise(placement) { var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var index = validPlacements.indexOf(placement); var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index)); return counter ? arr.reverse() : arr; } var BEHAVIORS = { FLIP: 'flip', CLOCKWISE: 'clockwise', COUNTERCLOCKWISE: 'counterclockwise' }; /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function flip(data, options) { // if `inner` modifier is enabled, we can't use the `flip` modifier if (isModifierEnabled(data.instance.modifiers, 'inner')) { return data; } if (data.flipped && data.placement === data.originalPlacement) { // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides return data; } var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement); var placement = data.placement.split('-')[0]; var placementOpposite = getOppositePlacement(placement); var variation = data.placement.split('-')[1] || ''; var flipOrder = []; switch (options.behavior) { case BEHAVIORS.FLIP: flipOrder = [placement, placementOpposite]; break; case BEHAVIORS.CLOCKWISE: flipOrder = clockwise(placement); break; case BEHAVIORS.COUNTERCLOCKWISE: flipOrder = clockwise(placement, true); break; default: flipOrder = options.behavior; } flipOrder.forEach(function (step, index) { if (placement !== step || flipOrder.length === index + 1) { return data; } placement = data.placement.split('-')[0]; placementOpposite = getOppositePlacement(placement); var popperOffsets = data.offsets.popper; var refOffsets = data.offsets.reference; // using floor because the reference offsets may contain decimals we are not going to consider here var floor = Math.floor; var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom); var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left); var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right); var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top); var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom); var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom; // flip the variation if required var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom); if (overlapsRef || overflowsBoundaries || flippedVariation) { // this boolean to detect any flip loop data.flipped = true; if (overlapsRef || overflowsBoundaries) { placement = flipOrder[index + 1]; } if (flippedVariation) { variation = getOppositeVariation(variation); } data.placement = placement + (variation ? '-' + variation : ''); // this object contains `position`, we want to preserve it along with // any additional property we may add in the future data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement)); data = runModifiers(data.instance.modifiers, data, 'flip'); } }); return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function keepTogether(data) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var placement = data.placement.split('-')[0]; var floor = Math.floor; var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var side = isVertical ? 'right' : 'bottom'; var opSide = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; if (popper[side] < floor(reference[opSide])) { data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement]; } if (popper[opSide] > floor(reference[side])) { data.offsets.popper[opSide] = floor(reference[side]); } return data; } /** * Converts a string containing value + unit into a px value number * @function * @memberof {modifiers~offset} * @private * @argument {String} str - Value + unit string * @argument {String} measurement - `height` or `width` * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @returns {Number|String} * Value in pixels, or original string if no values were extracted */ function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = popperOffsets; break; case '%': case '%r': default: element = referenceOffsets; } var rect = getClientRect(element); return rect[measurement] / 100 * value; } else if (unit === 'vh' || unit === 'vw') { // if is a vh or vw, we calculate the size based on the viewport var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } else { // if is an explicit pixel unit, we get rid of the unit and keep the value // if is an implicit unit, it's px, and we return just the value return value; } } /** * Parse an `offset` string to extrapolate `x` and `y` numeric offsets. * @function * @memberof {modifiers~offset} * @private * @argument {String} offset * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @argument {String} basePlacement * @returns {Array} a two cells array with x and y offsets in numbers */ function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { var offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) var fragments = offset.split(/(\+|\-)/).map(function (frag) { return frag.trim(); }); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space var divider = fragments.indexOf(find(fragments, function (frag) { return frag.search(/,|\s/) !== -1; })); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. var splitRegex = /\s*,\s*|\s+/; var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map(function (op, index) { // Most of the units rely on the orientation of the popper var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; var mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce(function (a, b) { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(function (str) { return toValue(str, measurement, popperOffsets, referenceOffsets); }); }); // Loop trough the offsets arrays and execute the operations ops.forEach(function (op, index) { op.forEach(function (frag, index2) { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @argument {Number|String} options.offset=0 * The offset value as described in the modifier description * @returns {Object} The data object, properly modified */ function offset(data, _ref) { var offset = _ref.offset; var placement = data.placement, _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var basePlacement = placement.split('-')[0]; var offsets = void 0; if (isNumeric(+offset)) { offsets = [+offset, 0]; } else { offsets = parseOffset(offset, popper, reference, basePlacement); } if (basePlacement === 'left') { popper.top += offsets[0]; popper.left -= offsets[1]; } else if (basePlacement === 'right') { popper.top += offsets[0]; popper.left += offsets[1]; } else if (basePlacement === 'top') { popper.left += offsets[0]; popper.top -= offsets[1]; } else if (basePlacement === 'bottom') { popper.left += offsets[0]; popper.top += offsets[1]; } data.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function preventOverflow(data, options) { var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper); // If offsetParent is the reference element, we really want to // go one step up and use the next offsetParent as reference to // avoid to make this modifier completely useless and look like broken if (data.instance.reference === boundariesElement) { boundariesElement = getOffsetParent(boundariesElement); } var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement); options.boundaries = boundaries; var order = options.priority; var popper = data.offsets.popper; var check = { primary: function primary(placement) { var value = popper[placement]; if (popper[placement] < boundaries[placement] && !options.escapeWithReference) { value = Math.max(popper[placement], boundaries[placement]); } return defineProperty({}, placement, value); }, secondary: function secondary(placement) { var mainSide = placement === 'right' ? 'left' : 'top'; var value = popper[mainSide]; if (popper[placement] > boundaries[placement] && !options.escapeWithReference) { value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height)); } return defineProperty({}, mainSide, value); } }; order.forEach(function (placement) { var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary'; popper = _extends({}, popper, check[side](placement)); }); data.offsets.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function shift(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var shiftvariation = placement.split('-')[1]; // if shift shiftvariation is specified, run the modifier if (shiftvariation) { var _data$offsets = data.offsets, reference = _data$offsets.reference, popper = _data$offsets.popper; var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1; var side = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; var shiftOffsets = { start: defineProperty({}, side, reference[side]), end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement]) }; data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]); } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function hide(data) { if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) { return data; } var refRect = data.offsets.reference; var bound = find(data.instance.modifiers, function (modifier) { return modifier.name === 'preventOverflow'; }).boundaries; if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === true) { return data; } data.hide = true; data.attributes['x-out-of-boundaries'] = ''; } else { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === false) { return data; } data.hide = false; data.attributes['x-out-of-boundaries'] = false; } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function inner(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1; var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1; popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0); data.placement = getOppositePlacement(placement); data.offsets.popper = getClientRect(popper); return data; } /** * Modifier function, each modifier can have a function of this type assigned * to its `fn` property.<br /> * These functions will be called on each update, this means that you must * make sure they are performant enough to avoid performance bottlenecks. * * @function ModifierFn * @argument {dataObject} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {dataObject} The data object, properly modified */ /** * Modifiers are plugins used to alter the behavior of your poppers.<br /> * Popper.js uses a set of 9 modifiers to provide all the basic functionalities * needed by the library. * * Usually you don't want to override the `order`, `fn` and `onLoad` props. * All the other properties are configurations that could be tweaked. * @namespace modifiers */ var modifiers = { /** * Modifier used to shift the popper on the start or end of its reference * element.<br /> * It will read the variation of the `placement` property.<br /> * It can be one either `-end` or `-start`. * @memberof modifiers * @inner */ shift: { /** @prop {number} order=100 - Index used to define the order of execution */ order: 100, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: shift }, /** * The `offset` modifier can shift your popper on both its axis. * * It accepts the following units: * - `px` or unitless, interpreted as pixels * - `%` or `%r`, percentage relative to the length of the reference element * - `%p`, percentage relative to the length of the popper element * - `vw`, CSS viewport width unit * - `vh`, CSS viewport height unit * * For length is intended the main axis relative to the placement of the popper.<br /> * This means that if the placement is `top` or `bottom`, the length will be the * `width`. In case of `left` or `right`, it will be the height. * * You can provide a single value (as `Number` or `String`), or a pair of values * as `String` divided by a comma or one (or more) white spaces.<br /> * The latter is a deprecated method because it leads to confusion and will be * removed in v2.<br /> * Additionally, it accepts additions and subtractions between different units. * Note that multiplications and divisions aren't supported. * * Valid examples are: * ``` * 10 * '10%' * '10, 10' * '10%, 10' * '10 + 10%' * '10 - 5vh + 3%' * '-10px + 5vh, 5px - 6%' * ``` * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap * > with their reference element, unfortunately, you will have to disable the `flip` modifier. * > More on this [reading this issue](https://github.com/FezVrasta/popper.js/issues/373) * * @memberof modifiers * @inner */ offset: { /** @prop {number} order=200 - Index used to define the order of execution */ order: 200, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: offset, /** @prop {Number|String} offset=0 * The offset value as described in the modifier description */ offset: 0 }, /** * Modifier used to prevent the popper from being positioned outside the boundary. * * An scenario exists where the reference itself is not within the boundaries.<br /> * We can say it has "escaped the boundaries" — or just "escaped".<br /> * In this case we need to decide whether the popper should either: * * - detach from the reference and remain "trapped" in the boundaries, or * - if it should ignore the boundary and "escape with its reference" * * When `escapeWithReference` is set to`true` and reference is completely * outside its boundaries, the popper will overflow (or completely leave) * the boundaries in order to remain attached to the edge of the reference. * * @memberof modifiers * @inner */ preventOverflow: { /** @prop {number} order=300 - Index used to define the order of execution */ order: 300, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: preventOverflow, /** * @prop {Array} [priority=['left','right','top','bottom']] * Popper will try to prevent overflow following these priorities by default, * then, it could overflow on the left and on top of the `boundariesElement` */ priority: ['left', 'right', 'top', 'bottom'], /** * @prop {number} padding=5 * Amount of pixel used to define a minimum distance between the boundaries * and the popper this makes sure the popper has always a little padding * between the edges of its container */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='scrollParent' * Boundaries used by the modifier, can be `scrollParent`, `window`, * `viewport` or any DOM element. */ boundariesElement: 'scrollParent' }, /** * Modifier used to make sure the reference and its popper stay near eachothers * without leaving any gap between the two. Expecially useful when the arrow is * enabled and you want to assure it to point to its reference element. * It cares only about the first axis, you can still have poppers with margin * between the popper and its reference element. * @memberof modifiers * @inner */ keepTogether: { /** @prop {number} order=400 - Index used to define the order of execution */ order: 400, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: keepTogether }, /** * This modifier is used to move the `arrowElement` of the popper to make * sure it is positioned between the reference element and its popper element. * It will read the outer size of the `arrowElement` node to detect how many * pixels of conjuction are needed. * * It has no effect if no `arrowElement` is provided. * @memberof modifiers * @inner */ arrow: { /** @prop {number} order=500 - Index used to define the order of execution */ order: 500, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: arrow, /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */ element: '[x-arrow]' }, /** * Modifier used to flip the popper's placement when it starts to overlap its * reference element. * * Requires the `preventOverflow` modifier before it in order to work. * * **NOTE:** this modifier will interrupt the current update cycle and will * restart it if it detects the need to flip the placement. * @memberof modifiers * @inner */ flip: { /** @prop {number} order=600 - Index used to define the order of execution */ order: 600, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: flip, /** * @prop {String|Array} behavior='flip' * The behavior used to change the popper's placement. It can be one of * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid * placements (with optional variations). */ behavior: 'flip', /** * @prop {number} padding=5 * The popper will flip if it hits the edges of the `boundariesElement` */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='viewport' * The element which will define the boundaries of the popper position, * the popper will never be placed outside of the defined boundaries * (except if keepTogether is enabled) */ boundariesElement: 'viewport' }, /** * Modifier used to make the popper flow toward the inner of the reference element. * By default, when this modifier is disabled, the popper will be placed outside * the reference element. * @memberof modifiers * @inner */ inner: { /** @prop {number} order=700 - Index used to define the order of execution */ order: 700, /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */ enabled: false, /** @prop {ModifierFn} */ fn: inner }, /** * Modifier used to hide the popper when its reference element is outside of the * popper boundaries. It will set a `x-out-of-boundaries` attribute which can * be used to hide with a CSS selector the popper when its reference is * out of boundaries. * * Requires the `preventOverflow` modifier before it in order to work. * @memberof modifiers * @inner */ hide: { /** @prop {number} order=800 - Index used to define the order of execution */ order: 800, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: hide }, /** * Computes the style that will be applied to the popper element to gets * properly positioned. * * Note that this modifier will not touch the DOM, it just prepares the styles * so that `applyStyle` modifier can apply it. This separation is useful * in case you need to replace `applyStyle` with a custom implementation. * * This modifier has `850` as `order` value to maintain backward compatibility * with previous versions of Popper.js. Expect the modifiers ordering method * to change in future major versions of the library. * * @memberof modifiers * @inner */ computeStyle: { /** @prop {number} order=850 - Index used to define the order of execution */ order: 850, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: computeStyle, /** * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3d transformation to position the popper. * Otherwise, it will use the `top` and `left` properties. */ gpuAcceleration: true, /** * @prop {string} [x='bottom'] * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin. * Change this if your popper should grow in a direction different from `bottom` */ x: 'bottom', /** * @prop {string} [x='left'] * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin. * Change this if your popper should grow in a direction different from `right` */ y: 'right' }, /** * Applies the computed styles to the popper element. * * All the DOM manipulations are limited to this modifier. This is useful in case * you want to integrate Popper.js inside a framework or view library and you * want to delegate all the DOM manipulations to it. * * Note that if you disable this modifier, you must make sure the popper element * has its position set to `absolute` before Popper.js can do its work! * * Just disable this modifier and define you own to achieve the desired effect. * * @memberof modifiers * @inner */ applyStyle: { /** @prop {number} order=900 - Index used to define the order of execution */ order: 900, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: applyStyle, /** @prop {Function} */ onLoad: applyStyleOnLoad, /** * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3d transformation to position the popper. * Otherwise, it will use the `top` and `left` properties. */ gpuAcceleration: undefined } }; /** * The `dataObject` is an object containing all the informations used by Popper.js * this object get passed to modifiers and to the `onCreate` and `onUpdate` callbacks. * @name dataObject * @property {Object} data.instance The Popper.js instance * @property {String} data.placement Placement applied to popper * @property {String} data.originalPlacement Placement originally defined on init * @property {Boolean} data.flipped True if popper has been flipped by flip modifier * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper. * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier * @property {Object} data.styles Any CSS property defined here will be applied to the popper, it expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow, it expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.boundaries Offsets of the popper boundaries * @property {Object} data.offsets The measurements of popper, reference and arrow elements. * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0 */ /** * Default options provided to Popper.js constructor.<br /> * These can be overriden using the `options` argument of Popper.js.<br /> * To override an option, simply pass as 3rd argument an object with the same * structure of this object, example: * ``` * new Popper(ref, pop, { * modifiers: { * preventOverflow: { enabled: false } * } * }) * ``` * @type {Object} * @static * @memberof Popper */ var Defaults = { /** * Popper's placement * @prop {Popper.placements} placement='bottom' */ placement: 'bottom', /** * Whether events (resize, scroll) are initially enabled * @prop {Boolean} eventsEnabled=true */ eventsEnabled: true, /** * Set to true if you want to automatically remove the popper when * you call the `destroy` method. * @prop {Boolean} removeOnDestroy=false */ removeOnDestroy: false, /** * Callback called when the popper is created.<br /> * By default, is set to no-op.<br /> * Access Popper.js instance with `data.instance`. * @prop {onCreate} */ onCreate: function onCreate() {}, /** * Callback called when the popper is updated, this callback is not called * on the initialization/creation of the popper, but only on subsequent * updates.<br /> * By default, is set to no-op.<br /> * Access Popper.js instance with `data.instance`. * @prop {onUpdate} */ onUpdate: function onUpdate() {}, /** * List of modifiers used to modify the offsets before they are applied to the popper. * They provide most of the functionalities of Popper.js * @prop {modifiers} */ modifiers: modifiers }; /** * @callback onCreate * @param {dataObject} data */ /** * @callback onUpdate * @param {dataObject} data */ // Utils // Methods var Popper = function () { /** * Create a new Popper.js instance * @class Popper * @param {HTMLElement|referenceObject} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper. * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) * @return {Object} instance - The generated Popper.js instance */ function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference && reference.jquery ? reference[0] : reference; this.popper = popper && popper.jquery ? popper[0] : popper; // Deep merge modifiers options this.options.modifiers = {}; Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; } // We can't use class properties because they don't get listed in the // class prototype and break stuff like Sinon stubs createClass(Popper, [{ key: 'update', value: function update$$1() { return update.call(this); } }, { key: 'destroy', value: function destroy$$1() { return destroy.call(this); } }, { key: 'enableEventListeners', value: function enableEventListeners$$1() { return enableEventListeners.call(this); } }, { key: 'disableEventListeners', value: function disableEventListeners$$1() { return disableEventListeners.call(this); } /** * Schedule an update, it will run on the next UI update available * @method scheduleUpdate * @memberof Popper */ /** * Collection of utilities useful when writing custom modifiers. * Starting from version 1.7, this method is available only if you * include `popper-utils.js` before `popper.js`. * * **DEPRECATION**: This way to access PopperUtils is deprecated * and will be removed in v2! Use the PopperUtils module directly instead. * Due to the high instability of the methods contained in Utils, we can't * guarantee them to follow semver. Use them at your own risk! * @static * @private * @type {Object} * @deprecated since version 1.8 * @member Utils * @memberof Popper */ }]); return Popper; }(); /** * The `referenceObject` is an object that provides an interface compatible with Popper.js * and lets you use it as replacement of a real DOM node.<br /> * You can use this method to position a popper relatively to a set of coordinates * in case you don't have a DOM node to use as reference. * * ``` * new Popper(referenceObject, popperNode); * ``` * * NB: This feature isn't supported in Internet Explorer 10 * @name referenceObject * @property {Function} data.getBoundingClientRect * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method. * @property {number} data.clientWidth * An ES6 getter that will return the width of the virtual reference element. * @property {number} data.clientHeight * An ES6 getter that will return the height of the virtual reference element. */ Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils; Popper.placements = placements; Popper.Defaults = Defaults; return Popper; }))); //# sourceMappingURL=popper.js.map /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var Arrow = function Arrow(props, context) { var _props$component = props.component, component = _props$component === undefined ? 'span' : _props$component, innerRef = props.innerRef, children = props.children, restProps = _objectWithoutProperties(props, ['component', 'innerRef', 'children']); var popper = context.popper; var arrowRef = function arrowRef(node) { popper.setArrowNode(node); if (typeof innerRef === 'function') { innerRef(node); } }; var arrowStyle = popper.getArrowStyle(); if (typeof children === 'function') { var arrowProps = { ref: arrowRef, style: arrowStyle }; return children({ arrowProps: arrowProps, restProps: restProps }); } var componentProps = _extends({}, restProps, { style: _extends({}, arrowStyle, restProps.style) }); if (typeof component === 'string') { componentProps.ref = arrowRef; } else { componentProps.innerRef = arrowRef; } return (0, _react.createElement)(component, componentProps, children); }; Arrow.contextTypes = { popper: _propTypes2.default.object.isRequired }; Arrow.propTypes = { component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]), innerRef: _propTypes2.default.func, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; exports.default = Arrow; /***/ }) /******/ ]) }); ;
tholu/cdnjs
ajax/libs/react-datepicker/0.59.0/react-datepicker.js
JavaScript
mit
229,566
function getElements(className) { return Array.from(document.getElementsByClassName(className)); } window.onload = function() { // Force a reflow before any changes. document.body.clientWidth; getElements('remove').forEach(function(e) { e.remove(); }); getElements('remove-after').forEach(function(e) { e.parentNode.removeChild(e.nextSibling); }); };
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/css/css-ruby/support/ruby-dynamic-removal.js
JavaScript
bsd-3-clause
374
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ 'use strict'; ( function() { var template = '<img alt="" src="" />', templateBlock = new CKEDITOR.template( '<figure class="{captionedClass}">' + template + '<figcaption>{captionPlaceholder}</figcaption>' + '</figure>' ), alignmentsObj = { left: 0, center: 1, right: 2 }, regexPercent = /^\s*(\d+\%)\s*$/i; CKEDITOR.plugins.add( 'image2', { // jscs:disable maximumLineLength lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE% // jscs:enable maximumLineLength requires: 'widget,dialog', icons: 'image', hidpi: true, onLoad: function() { CKEDITOR.addCss( '.cke_image_nocaption{' + // This is to remove unwanted space so resize // wrapper is displayed property. 'line-height:0' + '}' + '.cke_editable.cke_image_sw, .cke_editable.cke_image_sw *{cursor:sw-resize !important}' + '.cke_editable.cke_image_se, .cke_editable.cke_image_se *{cursor:se-resize !important}' + '.cke_image_resizer{' + 'display:none;' + 'position:absolute;' + 'width:10px;' + 'height:10px;' + 'bottom:-5px;' + 'right:-5px;' + 'background:#000;' + 'outline:1px solid #fff;' + // Prevent drag handler from being misplaced (#11207). 'line-height:0;' + 'cursor:se-resize;' + '}' + '.cke_image_resizer_wrapper{' + 'position:relative;' + 'display:inline-block;' + 'line-height:0;' + '}' + // Bottom-left corner style of the resizer. '.cke_image_resizer.cke_image_resizer_left{' + 'right:auto;' + 'left:-5px;' + 'cursor:sw-resize;' + '}' + '.cke_widget_wrapper:hover .cke_image_resizer,' + '.cke_image_resizer.cke_image_resizing{' + 'display:block' + '}' + // Expand widget wrapper when linked inline image. '.cke_widget_wrapper>a{' + 'display:inline-block' + '}' ); }, init: function( editor ) { // Adapts configuration from original image plugin. Should be removed // when we'll rename image2 to image. var config = editor.config, lang = editor.lang.image2, image = widgetDef( editor ); // Since filebrowser plugin discovers config properties by dialog (plugin?) // names (sic!), this hack will be necessary as long as Image2 is not named // Image. And since Image2 will never be Image, for sure some filebrowser logic // got to be refined. config.filebrowserImage2BrowseUrl = config.filebrowserImageBrowseUrl; config.filebrowserImage2UploadUrl = config.filebrowserImageUploadUrl; // Add custom elementspath names to widget definition. image.pathName = lang.pathName; image.editables.caption.pathName = lang.pathNameCaption; // Register the widget. editor.widgets.add( 'image', image ); // Add toolbar button for this plugin. editor.ui.addButton && editor.ui.addButton( 'Image', { label: editor.lang.common.image, command: 'image', toolbar: 'insert,10' } ); // Register context menu option for editing widget. if ( editor.contextMenu ) { editor.addMenuGroup( 'image', 10 ); editor.addMenuItem( 'image', { label: lang.menu, command: 'image', group: 'image' } ); } CKEDITOR.dialog.add( 'image2', this.path + 'dialogs/image2.js' ); }, afterInit: function( editor ) { // Integrate with align commands (justify plugin). var align = { left: 1, right: 1, center: 1, block: 1 }, integrate = alignCommandIntegrator( editor ); for ( var value in align ) integrate( value ); // Integrate with link commands (link plugin). linkCommandIntegrator( editor ); } } ); // Wiget states (forms) depending on alignment and configuration. // // Non-captioned widget (inline styles) // ┌──────┬───────────────────────────────┬─────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │none │<wrapper> │<img /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │left │<wrapper style=”float:left”> │<img style=”float:left” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │center│<wrapper> │<p style=”text-align:center”>│ // │ │ <p style=”text-align:center”> │ <img /> │ // │ │ <img /> │</p> │ // │ │ </p> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │right │<wrapper style=”float:right”> │<img style=”float:right” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // └──────┴───────────────────────────────┴─────────────────────────────┘ // // Non-captioned widget (config.image2_alignClasses defined) // ┌──────┬───────────────────────────────┬─────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │none │<wrapper> │<img /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │left │<wrapper class=”left”> │<img class=”left” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │center│<wrapper> │<p class=”center”> │ // │ │ <p class=”center”> │ <img /> │ // │ │ <img /> │</p> │ // │ │ </p> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │right │<wrapper class=”right”> │<img class=”right” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // └──────┴───────────────────────────────┴─────────────────────────────┘ // // Captioned widget (inline styles) // ┌──────┬────────────────────────────────────────┬────────────────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │none │<wrapper> │<figure /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │left │<wrapper style=”float:left”> │<figure style=”float:left” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │center│<wrapper style=”text-align:center”> │<div style=”text-align:center”> │ // │ │ <figure style=”display:inline-block” />│ <figure style=”display:inline-block” />│ // │ │</wrapper> │</p> │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │right │<wrapper style=”float:right”> │<figure style=”float:right” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // └──────┴────────────────────────────────────────┴────────────────────────────────────────┘ // // Captioned widget (config.image2_alignClasses defined) // ┌──────┬────────────────────────────────────────┬────────────────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │none │<wrapper> │<figure /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │left │<wrapper class=”left”> │<figure class=”left” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │center│<wrapper class=”center”> │<div class=”center”> │ // │ │ <figure /> │ <figure /> │ // │ │</wrapper> │</p> │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │right │<wrapper class=”right”> │<figure class=”right” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // └──────┴────────────────────────────────────────┴────────────────────────────────────────┘ // // @param {CKEDITOR.editor} // @returns {Object} function widgetDef( editor ) { var alignClasses = editor.config.image2_alignClasses, captionedClass = editor.config.image2_captionedClass; function deflate() { if ( this.deflated ) return; // Remember whether widget was focused before destroyed. if ( editor.widgets.focused == this.widget ) this.focused = true; editor.widgets.destroy( this.widget ); // Mark widget was destroyed. this.deflated = true; } function inflate() { var editable = editor.editable(), doc = editor.document; // Create a new widget. This widget will be either captioned // non-captioned, block or inline according to what is the // new state of the widget. if ( this.deflated ) { this.widget = editor.widgets.initOn( this.element, 'image', this.widget.data ); // Once widget was re-created, it may become an inline element without // block wrapper (i.e. when unaligned, end not captioned). Let's do some // sort of autoparagraphing here (#10853). if ( this.widget.inline && !( new CKEDITOR.dom.elementPath( this.widget.wrapper, editable ).block ) ) { var block = doc.createElement( editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ); block.replace( this.widget.wrapper ); this.widget.wrapper.move( block ); } // The focus must be transferred from the old one (destroyed) // to the new one (just created). if ( this.focused ) { this.widget.focus(); delete this.focused; } delete this.deflated; } // If now widget was destroyed just update wrapper's alignment. // According to the new state. else { setWrapperAlign( this.widget, alignClasses ); } } return { allowedContent: getWidgetAllowedContent( editor ), requiredContent: 'img[src,alt]', features: getWidgetFeatures( editor ), styleableElements: 'img figure', // This widget converts style-driven dimensions to attributes. contentTransformations: [ [ 'img[width]: sizeToAttribute' ] ], // This widget has an editable caption. editables: { caption: { selector: 'figcaption', allowedContent: 'br em strong sub sup u s; a[!href]' } }, parts: { image: 'img', caption: 'figcaption' // parts#link defined in widget#init }, // The name of this widget's dialog. dialog: 'image2', // Template of the widget: plain image. template: template, data: function() { var features = this.features; // Image can't be captioned when figcaption is disallowed (#11004). if ( this.data.hasCaption && !editor.filter.checkFeature( features.caption ) ) this.data.hasCaption = false; // Image can't be aligned when floating is disallowed (#11004). if ( this.data.align != 'none' && !editor.filter.checkFeature( features.align ) ) this.data.align = 'none'; // Convert the internal form of the widget from the old state to the new one. this.shiftState( { widget: this, element: this.element, oldData: this.oldData, newData: this.data, deflate: deflate, inflate: inflate } ); // Update widget.parts.link since it will not auto-update unless widget // is destroyed and re-inited. if ( !this.data.link ) { if ( this.parts.link ) delete this.parts.link; } else { if ( !this.parts.link ) this.parts.link = this.parts.image.getParent(); } this.parts.image.setAttributes( { src: this.data.src, // This internal is required by the editor. 'data-cke-saved-src': this.data.src, alt: this.data.alt } ); // If shifting non-captioned -> captioned, remove classes // related to styles from <img/>. if ( this.oldData && !this.oldData.hasCaption && this.data.hasCaption ) { for ( var c in this.data.classes ) this.parts.image.removeClass( c ); } // Set dimensions of the image according to gathered data. // Do it only when the attributes are allowed (#11004). if ( editor.filter.checkFeature( features.dimension ) ) setDimensions( this ); // Cache current data. this.oldData = CKEDITOR.tools.extend( {}, this.data ); }, init: function() { var helpers = CKEDITOR.plugins.image2, image = this.parts.image, data = { hasCaption: !!this.parts.caption, src: image.getAttribute( 'src' ), alt: image.getAttribute( 'alt' ) || '', width: image.getAttribute( 'width' ) || '', height: image.getAttribute( 'height' ) || '', // Lock ratio is on by default (#10833). lock: this.ready ? helpers.checkHasNaturalRatio( image ) : true }; // If we used 'a' in widget#parts definition, it could happen that // selected element is a child of widget.parts#caption. Since there's no clever // way to solve it with CSS selectors, it's done like that. (#11783). var link = image.getAscendant( 'a' ); if ( link && this.wrapper.contains( link ) ) this.parts.link = link; // Depending on configuration, read style/class from element and // then remove it. Removed style/class will be set on wrapper in #data listener. // Note: Center alignment is detected during upcast, so only left/right cases // are checked below. if ( !data.align ) { var alignElement = data.hasCaption ? this.element : image; // Read the initial left/right alignment from the class set on element. if ( alignClasses ) { if ( alignElement.hasClass( alignClasses[ 0 ] ) ) { data.align = 'left'; } else if ( alignElement.hasClass( alignClasses[ 2 ] ) ) { data.align = 'right'; } if ( data.align ) { alignElement.removeClass( alignClasses[ alignmentsObj[ data.align ] ] ); } else { data.align = 'none'; } } // Read initial float style from figure/image and then remove it. else { data.align = alignElement.getStyle( 'float' ) || 'none'; alignElement.removeStyle( 'float' ); } } // Update data.link object with attributes if the link has been discovered. if ( editor.plugins.link && this.parts.link ) { data.link = CKEDITOR.plugins.link.parseLinkAttributes( editor, this.parts.link ); // Get rid of cke_widget_* classes in data. Otherwise // they might appear in link dialog. var advanced = data.link.advanced; if ( advanced && advanced.advCSSClasses ) { advanced.advCSSClasses = CKEDITOR.tools.trim( advanced.advCSSClasses.replace( /cke_\S+/, '' ) ); } } // Get rid of extra vertical space when there's no caption. // It will improve the look of the resizer. this.wrapper[ ( data.hasCaption ? 'remove' : 'add' ) + 'Class' ]( 'cke_image_nocaption' ); this.setData( data ); // Setup dynamic image resizing with mouse. // Don't initialize resizer when dimensions are disallowed (#11004). if ( editor.filter.checkFeature( this.features.dimension ) && editor.config.image2_disableResizer !== true ) setupResizer( this ); this.shiftState = helpers.stateShifter( this.editor ); // Add widget editing option to its context menu. this.on( 'contextMenu', function( evt ) { evt.data.image = CKEDITOR.TRISTATE_OFF; // Integrate context menu items for link. // Note that widget may be wrapped in a link, which // does not belong to that widget (#11814). if ( this.parts.link || this.wrapper.getAscendant( 'a' ) ) evt.data.link = evt.data.unlink = CKEDITOR.TRISTATE_OFF; } ); // Pass the reference to this widget to the dialog. this.on( 'dialog', function( evt ) { evt.data.widget = this; }, this ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#addClass addClass: function( className ) { getStyleableElement( this ).addClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#hasClass hasClass: function( className ) { return getStyleableElement( this ).hasClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#removeClass removeClass: function( className ) { getStyleableElement( this ).removeClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#getClasses getClasses: ( function() { var classRegex = new RegExp( '^(' + [].concat( captionedClass, alignClasses ).join( '|' ) + ')$' ); return function() { var classes = this.repository.parseElementClasses( getStyleableElement( this ).getAttribute( 'class' ) ); // Neither config.image2_captionedClass nor config.image2_alignClasses // do not belong to style classes. for ( var c in classes ) { if ( classRegex.test( c ) ) delete classes[ c ]; } return classes; }; } )(), upcast: upcastWidgetElement( editor ), downcast: downcastWidgetElement( editor ) }; } CKEDITOR.plugins.image2 = { stateShifter: function( editor ) { // Tag name used for centering non-captioned widgets. var doc = editor.document, alignClasses = editor.config.image2_alignClasses, captionedClass = editor.config.image2_captionedClass, editable = editor.editable(), // The order that stateActions get executed. It matters! shiftables = [ 'hasCaption', 'align', 'link' ]; // Atomic procedures, one per state variable. var stateActions = { align: function( shift, oldValue, newValue ) { var el = shift.element; // Alignment changed. if ( shift.changed.align ) { // No caption in the new state. if ( !shift.newData.hasCaption ) { // Changed to "center" (non-captioned). if ( newValue == 'center' ) { shift.deflate(); shift.element = wrapInCentering( editor, el ); } // Changed to "non-center" from "center" while caption removed. if ( !shift.changed.hasCaption && oldValue == 'center' && newValue != 'center' ) { shift.deflate(); shift.element = unwrapFromCentering( el ); } } } // Alignment remains and "center" removed caption. else if ( newValue == 'center' && shift.changed.hasCaption && !shift.newData.hasCaption ) { shift.deflate(); shift.element = wrapInCentering( editor, el ); } // Finally set display for figure. if ( !alignClasses && el.is( 'figure' ) ) { if ( newValue == 'center' ) el.setStyle( 'display', 'inline-block' ); else el.removeStyle( 'display' ); } }, hasCaption: function( shift, oldValue, newValue ) { // This action is for real state change only. if ( !shift.changed.hasCaption ) return; // Get <img/> or <a><img/></a> from widget. Note that widget element might itself // be what we're looking for. Also element can be <p style="text-align:center"><a>...</a></p>. var imageOrLink; if ( shift.element.is( { img: 1, a: 1 } ) ) imageOrLink = shift.element; else imageOrLink = shift.element.findOne( 'a,img' ); // Switching hasCaption always destroys the widget. shift.deflate(); // There was no caption, but the caption is to be added. if ( newValue ) { // Create new <figure> from widget template. var figure = CKEDITOR.dom.element.createFromHtml( templateBlock.output( { captionedClass: captionedClass, captionPlaceholder: editor.lang.image2.captionPlaceholder } ), doc ); // Replace element with <figure>. replaceSafely( figure, shift.element ); // Use old <img/> or <a><img/></a> instead of the one from the template, // so we won't lose additional attributes. imageOrLink.replace( figure.findOne( 'img' ) ); // Update widget's element. shift.element = figure; } // The caption was present, but now it's to be removed. else { // Unwrap <img/> or <a><img/></a> from figure. imageOrLink.replace( shift.element ); // Update widget's element. shift.element = imageOrLink; } }, link: function( shift, oldValue, newValue ) { if ( shift.changed.link ) { var img = shift.element.is( 'img' ) ? shift.element : shift.element.findOne( 'img' ), link = shift.element.is( 'a' ) ? shift.element : shift.element.findOne( 'a' ), // Why deflate: // If element is <img/>, it will be wrapped into <a>, // which becomes a new widget.element. // If element is <a><img/></a>, it will be unlinked // so <img/> becomes a new widget.element. needsDeflate = ( shift.element.is( 'a' ) && !newValue ) || ( shift.element.is( 'img' ) && newValue ), newEl; if ( needsDeflate ) shift.deflate(); // If unlinked the image, returned element is <img>. if ( !newValue ) newEl = unwrapFromLink( link ); else { // If linked the image, returned element is <a>. if ( !oldValue ) newEl = wrapInLink( img, shift.newData.link ); // Set and remove all attributes associated with this state. var attributes = CKEDITOR.plugins.link.getLinkAttributes( editor, newValue ); if ( !CKEDITOR.tools.isEmpty( attributes.set ) ) ( newEl || link ).setAttributes( attributes.set ); if ( attributes.removed.length ) ( newEl || link ).removeAttributes( attributes.removed ); } if ( needsDeflate ) shift.element = newEl; } } }; function wrapInCentering( editor, element ) { var attribsAndStyles = {}; if ( alignClasses ) attribsAndStyles.attributes = { 'class': alignClasses[ 1 ] }; else attribsAndStyles.styles = { 'text-align': 'center' }; // There's no gentle way to center inline element with CSS, so create p/div // that wraps widget contents and does the trick either with style or class. var center = doc.createElement( editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div', attribsAndStyles ); // Replace element with centering wrapper. replaceSafely( center, element ); element.move( center ); return center; } function unwrapFromCentering( element ) { var imageOrLink = element.findOne( 'a,img' ); imageOrLink.replace( element ); return imageOrLink; } // Wraps <img/> -> <a><img/></a>. // Returns reference to <a>. // // @param {CKEDITOR.dom.element} img // @param {Object} linkData // @returns {CKEDITOR.dom.element} function wrapInLink( img, linkData ) { var link = doc.createElement( 'a', { attributes: { href: linkData.url } } ); link.replace( img ); img.move( link ); return link; } // De-wraps <a><img/></a> -> <img/>. // Returns the reference to <img/> // // @param {CKEDITOR.dom.element} link // @returns {CKEDITOR.dom.element} function unwrapFromLink( link ) { var img = link.findOne( 'img' ); img.replace( link ); return img; } function replaceSafely( replacing, replaced ) { if ( replaced.getParent() ) { var range = editor.createRange(); range.moveToPosition( replaced, CKEDITOR.POSITION_BEFORE_START ); // Remove old element. Do it before insertion to avoid a case when // element is moved from 'replaced' element before it, what creates // a tricky case which insertElementIntorRange does not handle. replaced.remove(); editable.insertElementIntoRange( replacing, range ); } else { replacing.replace( replaced ); } } return function( shift ) { var name, i; shift.changed = {}; for ( i = 0; i < shiftables.length; i++ ) { name = shiftables[ i ]; shift.changed[ name ] = shift.oldData ? shift.oldData[ name ] !== shift.newData[ name ] : false; } // Iterate over possible state variables. for ( i = 0; i < shiftables.length; i++ ) { name = shiftables[ i ]; stateActions[ name ]( shift, shift.oldData ? shift.oldData[ name ] : null, shift.newData[ name ] ); } shift.inflate(); }; }, // Checks whether current ratio of the image match the natural one. // by comparing dimensions. // @param {CKEDITOR.dom.element} image // @returns {Boolean} checkHasNaturalRatio: function( image ) { var $ = image.$, natural = this.getNatural( image ); // The reason for two alternative comparisons is that the rounding can come from // both dimensions, e.g. there are two cases: // 1. height is computed as a rounded relation of the real height and the value of width, // 2. width is computed as a rounded relation of the real width and the value of heigh. return Math.round( $.clientWidth / natural.width * natural.height ) == $.clientHeight || Math.round( $.clientHeight / natural.height * natural.width ) == $.clientWidth; }, // Returns natural dimensions of the image. For modern browsers // it uses natural(Width|Height) for old ones (IE8), creates // a new image and reads dimensions. // @param {CKEDITOR.dom.element} image // @returns {Object} getNatural: function( image ) { var dimensions; if ( image.$.naturalWidth ) { dimensions = { width: image.$.naturalWidth, height: image.$.naturalHeight }; } else { var img = new Image(); img.src = image.getAttribute( 'src' ); dimensions = { width: img.width, height: img.height }; } return dimensions; } }; function setWrapperAlign( widget, alignClasses ) { var wrapper = widget.wrapper, align = widget.data.align, hasCaption = widget.data.hasCaption; if ( alignClasses ) { // Remove all align classes first. for ( var i = 3; i--; ) wrapper.removeClass( alignClasses[ i ] ); if ( align == 'center' ) { // Avoid touching non-captioned, centered widgets because // they have the class set on the element instead of wrapper: // // <div class="cke_widget_wrapper"> // <p class="center-class"> // <img /> // </p> // </div> if ( hasCaption ) { wrapper.addClass( alignClasses[ 1 ] ); } } else if ( align != 'none' ) { wrapper.addClass( alignClasses[ alignmentsObj[ align ] ] ); } } else { if ( align == 'center' ) { if ( hasCaption ) wrapper.setStyle( 'text-align', 'center' ); else wrapper.removeStyle( 'text-align' ); wrapper.removeStyle( 'float' ); } else { if ( align == 'none' ) wrapper.removeStyle( 'float' ); else wrapper.setStyle( 'float', align ); wrapper.removeStyle( 'text-align' ); } } } // Returns a function that creates widgets from all <img> and // <figure class="{config.image2_captionedClass}"> elements. // // @param {CKEDITOR.editor} editor // @returns {Function} function upcastWidgetElement( editor ) { var isCenterWrapper = centerWrapperChecker( editor ), captionedClass = editor.config.image2_captionedClass; // @param {CKEDITOR.htmlParser.element} el // @param {Object} data return function( el, data ) { var dimensions = { width: 1, height: 1 }, name = el.name, image; // #11110 Don't initialize on pasted fake objects. if ( el.attributes[ 'data-cke-realelement' ] ) return; // If a center wrapper is found, there are 3 possible cases: // // 1. <div style="text-align:center"><figure>...</figure></div>. // In this case centering is done with a class set on widget.wrapper. // Simply replace centering wrapper with figure (it's no longer necessary). // // 2. <p style="text-align:center"><img/></p>. // Nothing to do here: <p> remains for styling purposes. // // 3. <div style="text-align:center"><img/></div>. // Nothing to do here (2.) but that case is only possible in enterMode different // than ENTER_P. if ( isCenterWrapper( el ) ) { if ( name == 'div' ) { var figure = el.getFirst( 'figure' ); // Case #1. if ( figure ) { el.replaceWith( figure ); el = figure; } } // Cases #2 and #3 (handled transparently) // If there's a centering wrapper, save it in data. data.align = 'center'; // Image can be wrapped in link <a><img/></a>. image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' ); } // No center wrapper has been found. else if ( name == 'figure' && el.hasClass( captionedClass ) ) { image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' ); // Upcast linked image like <a><img/></a>. } else if ( isLinkedOrStandaloneImage( el ) ) { image = el.name == 'a' ? el.children[ 0 ] : el; } if ( !image ) return; // If there's an image, then cool, we got a widget. // Now just remove dimension attributes expressed with %. for ( var d in dimensions ) { var dimension = image.attributes[ d ]; if ( dimension && dimension.match( regexPercent ) ) delete image.attributes[ d ]; } return el; }; } // Returns a function which transforms the widget to the external format // according to the current configuration. // // @param {CKEDITOR.editor} function downcastWidgetElement( editor ) { var alignClasses = editor.config.image2_alignClasses; // @param {CKEDITOR.htmlParser.element} el return function( el ) { // In case of <a><img/></a>, <img/> is the element to hold // inline styles or classes (image2_alignClasses). var attrsHolder = el.name == 'a' ? el.getFirst() : el, attrs = attrsHolder.attributes, align = this.data.align; // De-wrap the image from resize handle wrapper. // Only block widgets have one. if ( !this.inline ) { var resizeWrapper = el.getFirst( 'span' ); if ( resizeWrapper ) resizeWrapper.replaceWith( resizeWrapper.getFirst( { img: 1, a: 1 } ) ); } if ( align && align != 'none' ) { var styles = CKEDITOR.tools.parseCssText( attrs.style || '' ); // When the widget is captioned (<figure>) and internally centering is done // with widget's wrapper style/class, in the external data representation, // <figure> must be wrapped with an element holding an style/class: // // <div style="text-align:center"> // <figure class="image" style="display:inline-block">...</figure> // </div> // or // <div class="some-center-class"> // <figure class="image">...</figure> // </div> // if ( align == 'center' && el.name == 'figure' ) { el = el.wrapWith( new CKEDITOR.htmlParser.element( 'div', alignClasses ? { 'class': alignClasses[ 1 ] } : { style: 'text-align:center' } ) ); } // If left/right, add float style to the downcasted element. else if ( align in { left: 1, right: 1 } ) { if ( alignClasses ) attrsHolder.addClass( alignClasses[ alignmentsObj[ align ] ] ); else styles[ 'float' ] = align; } // Update element styles. if ( !alignClasses && !CKEDITOR.tools.isEmpty( styles ) ) attrs.style = CKEDITOR.tools.writeCssText( styles ); } return el; }; } // Returns a function that checks if an element is a centering wrapper. // // @param {CKEDITOR.editor} editor // @returns {Function} function centerWrapperChecker( editor ) { var captionedClass = editor.config.image2_captionedClass, alignClasses = editor.config.image2_alignClasses, validChildren = { figure: 1, a: 1, img: 1 }; return function( el ) { // Wrapper must be either <div> or <p>. if ( !( el.name in { div: 1, p: 1 } ) ) return false; var children = el.children; // Centering wrapper can have only one child. if ( children.length !== 1 ) return false; var child = children[ 0 ]; // Only <figure> or <img /> can be first (only) child of centering wrapper, // regardless of its type. if ( !( child.name in validChildren ) ) return false; // If centering wrapper is <p>, only <img /> can be the child. // <p style="text-align:center"><img /></p> if ( el.name == 'p' ) { if ( !isLinkedOrStandaloneImage( child ) ) return false; } // Centering <div> can hold <img/> or <figure>, depending on enterMode. else { // If a <figure> is the first (only) child, it must have a class. // <div style="text-align:center"><figure>...</figure><div> if ( child.name == 'figure' ) { if ( !child.hasClass( captionedClass ) ) return false; } else { // Centering <div> can hold <img/> or <a><img/></a> only when enterMode // is ENTER_(BR|DIV). // <div style="text-align:center"><img /></div> // <div style="text-align:center"><a><img /></a></div> if ( editor.enterMode == CKEDITOR.ENTER_P ) return false; // Regardless of enterMode, a child which is not <figure> must be // either <img/> or <a><img/></a>. if ( !isLinkedOrStandaloneImage( child ) ) return false; } } // Centering wrapper got to be... centering. If image2_alignClasses are defined, // check for centering class. Otherwise, check the style. if ( alignClasses ? el.hasClass( alignClasses[ 1 ] ) : CKEDITOR.tools.parseCssText( el.attributes.style || '', true )[ 'text-align' ] == 'center' ) return true; return false; }; } // Checks whether element is <img/> or <a><img/></a>. // // @param {CKEDITOR.htmlParser.element} function isLinkedOrStandaloneImage( el ) { if ( el.name == 'img' ) return true; else if ( el.name == 'a' ) return el.children.length == 1 && el.getFirst( 'img' ); return false; } // Sets width and height of the widget image according to current widget data. // // @param {CKEDITOR.plugins.widget} widget function setDimensions( widget ) { var data = widget.data, dimensions = { width: data.width, height: data.height }, image = widget.parts.image; for ( var d in dimensions ) { if ( dimensions[ d ] ) image.setAttribute( d, dimensions[ d ] ); else image.removeAttribute( d ); } } // Defines all features related to drag-driven image resizing. // // @param {CKEDITOR.plugins.widget} widget function setupResizer( widget ) { var editor = widget.editor, editable = editor.editable(), doc = editor.document, // Store the resizer in a widget for testing (#11004). resizer = widget.resizer = doc.createElement( 'span' ); resizer.addClass( 'cke_image_resizer' ); resizer.setAttribute( 'title', editor.lang.image2.resizer ); resizer.append( new CKEDITOR.dom.text( '\u200b', doc ) ); // Inline widgets don't need a resizer wrapper as an image spans the entire widget. if ( !widget.inline ) { var imageOrLink = widget.parts.link || widget.parts.image, oldResizeWrapper = imageOrLink.getParent(), resizeWrapper = doc.createElement( 'span' ); resizeWrapper.addClass( 'cke_image_resizer_wrapper' ); resizeWrapper.append( imageOrLink ); resizeWrapper.append( resizer ); widget.element.append( resizeWrapper, true ); // Remove the old wrapper which could came from e.g. pasted HTML // and which could be corrupted (e.g. resizer span has been lost). if ( oldResizeWrapper.is( 'span' ) ) oldResizeWrapper.remove(); } else { widget.wrapper.append( resizer ); } // Calculate values of size variables and mouse offsets. resizer.on( 'mousedown', function( evt ) { var image = widget.parts.image, // "factor" can be either 1 or -1. I.e.: For right-aligned images, we need to // subtract the difference to get proper width, etc. Without "factor", // resizer starts working the opposite way. factor = widget.data.align == 'right' ? -1 : 1, // The x-coordinate of the mouse relative to the screen // when button gets pressed. startX = evt.data.$.screenX, startY = evt.data.$.screenY, // The initial dimensions and aspect ratio of the image. startWidth = image.$.clientWidth, startHeight = image.$.clientHeight, ratio = startWidth / startHeight, listeners = [], // A class applied to editable during resizing. cursorClass = 'cke_image_s' + ( !~factor ? 'w' : 'e' ), nativeEvt, newWidth, newHeight, updateData, moveDiffX, moveDiffY, moveRatio; // Save the undo snapshot first: before resizing. editor.fire( 'saveSnapshot' ); // Mousemove listeners are removed on mouseup. attachToDocuments( 'mousemove', onMouseMove, listeners ); // Clean up the mousemove listener. Update widget data if valid. attachToDocuments( 'mouseup', onMouseUp, listeners ); // The entire editable will have the special cursor while resizing goes on. editable.addClass( cursorClass ); // This is to always keep the resizer element visible while resizing. resizer.addClass( 'cke_image_resizing' ); // Attaches an event to a global document if inline editor. // Additionally, if classic (`iframe`-based) editor, also attaches the same event to `iframe`'s document. function attachToDocuments( name, callback, collection ) { var globalDoc = CKEDITOR.document, listeners = []; if ( !doc.equals( globalDoc ) ) listeners.push( globalDoc.on( name, callback ) ); listeners.push( doc.on( name, callback ) ); if ( collection ) { for ( var i = listeners.length; i--; ) collection.push( listeners.pop() ); } } // Calculate with first, and then adjust height, preserving ratio. function adjustToX() { newWidth = startWidth + factor * moveDiffX; newHeight = Math.round( newWidth / ratio ); } // Calculate height first, and then adjust width, preserving ratio. function adjustToY() { newHeight = startHeight - moveDiffY; newWidth = Math.round( newHeight * ratio ); } // This is how variables refer to the geometry. // Note: x corresponds to moveOffset, this is the position of mouse // Note: o corresponds to [startX, startY]. // // +--------------+--------------+ // | | | // | I | II | // | | | // +------------- o -------------+ _ _ _ // | | | ^ // | VI | III | | moveDiffY // | | x _ _ _ _ _ v // +--------------+---------|----+ // | | // <-------> // moveDiffX function onMouseMove( evt ) { nativeEvt = evt.data.$; // This is how far the mouse is from the point the button was pressed. moveDiffX = nativeEvt.screenX - startX; moveDiffY = startY - nativeEvt.screenY; // This is the aspect ratio of the move difference. moveRatio = Math.abs( moveDiffX / moveDiffY ); // Left, center or none-aligned widget. if ( factor == 1 ) { if ( moveDiffX <= 0 ) { // Case: IV. if ( moveDiffY <= 0 ) adjustToX(); // Case: I. else { if ( moveRatio >= ratio ) adjustToX(); else adjustToY(); } } else { // Case: III. if ( moveDiffY <= 0 ) { if ( moveRatio >= ratio ) adjustToY(); else adjustToX(); } // Case: II. else { adjustToY(); } } } // Right-aligned widget. It mirrors behaviours, so I becomes II, // IV becomes III and vice-versa. else { if ( moveDiffX <= 0 ) { // Case: IV. if ( moveDiffY <= 0 ) { if ( moveRatio >= ratio ) adjustToY(); else adjustToX(); } // Case: I. else { adjustToY(); } } else { // Case: III. if ( moveDiffY <= 0 ) adjustToX(); // Case: II. else { if ( moveRatio >= ratio ) { adjustToX(); } else { adjustToY(); } } } } // Don't update attributes if less than 10. // This is to prevent images to visually disappear. if ( newWidth >= 15 && newHeight >= 15 ) { image.setAttributes( { width: newWidth, height: newHeight } ); updateData = true; } else { updateData = false; } } function onMouseUp() { var l; while ( ( l = listeners.pop() ) ) l.removeListener(); // Restore default cursor by removing special class. editable.removeClass( cursorClass ); // This is to bring back the regular behaviour of the resizer. resizer.removeClass( 'cke_image_resizing' ); if ( updateData ) { widget.setData( { width: newWidth, height: newHeight } ); // Save another undo snapshot: after resizing. editor.fire( 'saveSnapshot' ); } // Don't update data twice or more. updateData = false; } } ); // Change the position of the widget resizer when data changes. widget.on( 'data', function() { resizer[ widget.data.align == 'right' ? 'addClass' : 'removeClass' ]( 'cke_image_resizer_left' ); } ); } // Integrates widget alignment setting with justify // plugin's commands (execution and refreshment). // @param {CKEDITOR.editor} editor // @param {String} value 'left', 'right', 'center' or 'block' function alignCommandIntegrator( editor ) { var execCallbacks = [], enabled; return function( value ) { var command = editor.getCommand( 'justify' + value ); // Most likely, the justify plugin isn't loaded. if ( !command ) return; // This command will be manually refreshed along with // other commands after exec. execCallbacks.push( function() { command.refresh( editor, editor.elementPath() ); } ); if ( value in { right: 1, left: 1, center: 1 } ) { command.on( 'exec', function( evt ) { var widget = getFocusedWidget( editor ); if ( widget ) { widget.setData( 'align', value ); // Once the widget changed its align, all the align commands // must be refreshed: the event is to be cancelled. for ( var i = execCallbacks.length; i--; ) execCallbacks[ i ](); evt.cancel(); } } ); } command.on( 'refresh', function( evt ) { var widget = getFocusedWidget( editor ), allowed = { right: 1, left: 1, center: 1 }; if ( !widget ) return; // Cache "enabled" on first use. This is because filter#checkFeature may // not be available during plugin's afterInit in the future — a moment when // alignCommandIntegrator is called. if ( enabled === undefined ) enabled = editor.filter.checkFeature( editor.widgets.registered.image.features.align ); // Don't allow justify commands when widget alignment is disabled (#11004). if ( !enabled ) this.setState( CKEDITOR.TRISTATE_DISABLED ); else { this.setState( ( widget.data.align == value ) ? ( CKEDITOR.TRISTATE_ON ) : ( ( value in allowed ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ) ); } evt.cancel(); } ); }; } function linkCommandIntegrator( editor ) { // Nothing to integrate with if link is not loaded. if ( !editor.plugins.link ) return; CKEDITOR.on( 'dialogDefinition', function( evt ) { var dialog = evt.data; if ( dialog.name == 'link' ) { var def = dialog.definition; var onShow = def.onShow, onOk = def.onOk; def.onShow = function() { var widget = getFocusedWidget( editor ); // Widget cannot be enclosed in a link, i.e. // <a>foo<inline widget/>bar</a> if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) this.setupContent( widget.data.link || {} ); else onShow.apply( this, arguments ); }; // Set widget data if linking the widget using // link dialog (instead of default action). // State shifter handles data change and takes // care of internal DOM structure of linked widget. def.onOk = function() { var widget = getFocusedWidget( editor ); // Widget cannot be enclosed in a link, i.e. // <a>foo<inline widget/>bar</a> if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) { var data = {}; // Collect data from fields. this.commitContent( data ); // Set collected data to widget. widget.setData( 'link', data ); } else { onOk.apply( this, arguments ); } }; } } ); // Overwrite default behaviour of unlink command. editor.getCommand( 'unlink' ).on( 'exec', function( evt ) { var widget = getFocusedWidget( editor ); // Override unlink only when link truly belongs to the widget. // If wrapped inline widget in a link, let default unlink work (#11814). if ( !widget || !widget.parts.link ) return; widget.setData( 'link', null ); // Selection (which is fake) may not change if unlinked image in focused widget, // i.e. if captioned image. Let's refresh command state manually here. this.refresh( editor, editor.elementPath() ); evt.cancel(); } ); // Overwrite default refresh of unlink command. editor.getCommand( 'unlink' ).on( 'refresh', function( evt ) { var widget = getFocusedWidget( editor ); if ( !widget ) return; // Note that widget may be wrapped in a link, which // does not belong to that widget (#11814). this.setState( widget.data.link || widget.wrapper.getAscendant( 'a' ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ); evt.cancel(); } ); } // Returns the focused widget, if of the type specific for this plugin. // If no widget is focused, `null` is returned. // // @param {CKEDITOR.editor} // @returns {CKEDITOR.plugins.widget} function getFocusedWidget( editor ) { var widget = editor.widgets.focused; if ( widget && widget.name == 'image' ) return widget; return null; } // Returns a set of widget allowedContent rules, depending // on configurations like config#image2_alignClasses or // config#image2_captionedClass. // // @param {CKEDITOR.editor} // @returns {Object} function getWidgetAllowedContent( editor ) { var alignClasses = editor.config.image2_alignClasses, rules = { // Widget may need <div> or <p> centering wrapper. div: { match: centerWrapperChecker( editor ) }, p: { match: centerWrapperChecker( editor ) }, img: { attributes: '!src,alt,width,height' }, figure: { classes: '!' + editor.config.image2_captionedClass }, figcaption: true }; if ( alignClasses ) { // Centering class from the config. rules.div.classes = alignClasses[ 1 ]; rules.p.classes = rules.div.classes; // Left/right classes from the config. rules.img.classes = alignClasses[ 0 ] + ',' + alignClasses[ 2 ]; rules.figure.classes += ',' + rules.img.classes; } else { // Centering with text-align. rules.div.styles = 'text-align'; rules.p.styles = 'text-align'; rules.img.styles = 'float'; rules.figure.styles = 'float,display'; } return rules; } // Returns a set of widget feature rules, depending // on editor configuration. Note that the following may not cover // all the possible cases since requiredContent supports a single // tag only. // // @param {CKEDITOR.editor} // @returns {Object} function getWidgetFeatures( editor ) { var alignClasses = editor.config.image2_alignClasses, features = { dimension: { requiredContent: 'img[width,height]' }, align: { requiredContent: 'img' + ( alignClasses ? '(' + alignClasses[ 0 ] + ')' : '{float}' ) }, caption: { requiredContent: 'figcaption' } }; return features; } // Returns element which is styled, considering current // state of the widget. // // @see CKEDITOR.plugins.widget#applyStyle // @param {CKEDITOR.plugins.widget} widget // @returns {CKEDITOR.dom.element} function getStyleableElement( widget ) { return widget.data.hasCaption ? widget.element : widget.parts.image; } } )(); /** * A CSS class applied to the `<figure>` element of a captioned image. * * // Changes the class to "captionedImage". * config.image2_captionedClass = 'captionedImage'; * * @cfg {String} [image2_captionedClass='image'] * @member CKEDITOR.config */ CKEDITOR.config.image2_captionedClass = 'image'; /** * Determines whether dimension inputs should be automatically filled when the image URL changes in the Enhanced Image * plugin dialog window. * * config.image2_prefillDimensions = false; * * @since 4.5 * @cfg {Boolean} [image2_prefillDimensions=true] * @member CKEDITOR.config */ /** * Disables the image resizer. By default the resizer is enabled. * * config.image2_disableResizer = true; * * @since 4.5 * @cfg {Boolean} [image2_disableResizer=false] * @member CKEDITOR.config */ /** * CSS classes applied to aligned images. Useful to take control over the way * the images are aligned, i.e. to customize output HTML and integrate external stylesheets. * * Classes should be defined in an array of three elements, containing left, center, and right * alignment classes, respectively. For example: * * config.image2_alignClasses = [ 'align-left', 'align-center', 'align-right' ]; * * **Note**: Once this configuration option is set, the plugin will no longer produce inline * styles for alignment. It means that e.g. the following HTML will be produced: * * <img alt="My image" class="custom-center-class" src="foo.png" /> * * instead of: * * <img alt="My image" style="float:left" src="foo.png" /> * * **Note**: Once this configuration option is set, corresponding style definitions * must be supplied to the editor: * * * For [classic editor](#!/guide/dev_framed) it can be done by defining additional * styles in the {@link CKEDITOR.config#contentsCss stylesheets loaded by the editor}. The same * styles must be provided on the target page where the content will be loaded. * * For [inline editor](#!/guide/dev_inline) the styles can be defined directly * with `<style> ... <style>` or `<link href="..." rel="stylesheet">`, i.e. within the `<head>` * of the page. * * For example, considering the following configuration: * * config.image2_alignClasses = [ 'align-left', 'align-center', 'align-right' ]; * * CSS rules can be defined as follows: * * .align-left { * float: left; * } * * .align-right { * float: right; * } * * .align-center { * text-align: center; * } * * .align-center > figure { * display: inline-block; * } * * @since 4.4 * @cfg {String[]} [image2_alignClasses=null] * @member CKEDITOR.config */
quepasso/dashboard
web/bundles/ivoryckeditor/plugins/image2/plugin.js
JavaScript
mit
58,206
/** * Modules in this bundle * @license * * opentype.js: * license: MIT (http://opensource.org/licenses/MIT) * author: Frederik De Bleser <frederik@debleser.be> * version: 0.6.7 * * tiny-inflate: * license: MIT (http://opensource.org/licenses/MIT) * author: Devon Govett <devongovett@gmail.com> * maintainers: devongovett <devongovett@gmail.com> * homepage: https://github.com/devongovett/tiny-inflate * version: 1.0.2 * * This header is generated by licensify (https://github.com/twada/licensify) */ (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.opentype = 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(require,module,exports){ var TINF_OK = 0; var TINF_DATA_ERROR = -3; function Tree() { this.table = new Uint16Array(16); /* table of code length counts */ this.trans = new Uint16Array(288); /* code -> symbol translation table */ } function Data(source, dest) { this.source = source; this.sourceIndex = 0; this.tag = 0; this.bitcount = 0; this.dest = dest; this.destLen = 0; this.ltree = new Tree(); /* dynamic length/symbol tree */ this.dtree = new Tree(); /* dynamic distance tree */ } /* --------------------------------------------------- * * -- uninitialized global data (static structures) -- * * --------------------------------------------------- */ var sltree = new Tree(); var sdtree = new Tree(); /* extra bits and base tables for length codes */ var length_bits = new Uint8Array(30); var length_base = new Uint16Array(30); /* extra bits and base tables for distance codes */ var dist_bits = new Uint8Array(30); var dist_base = new Uint16Array(30); /* special ordering of code length codes */ var clcidx = new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]); /* used by tinf_decode_trees, avoids allocations every call */ var code_tree = new Tree(); var lengths = new Uint8Array(288 + 32); /* ----------------------- * * -- utility functions -- * * ----------------------- */ /* build extra bits and base tables */ function tinf_build_bits_base(bits, base, delta, first) { var i, sum; /* build bits table */ for (i = 0; i < delta; ++i) bits[i] = 0; for (i = 0; i < 30 - delta; ++i) bits[i + delta] = i / delta | 0; /* build base table */ for (sum = first, i = 0; i < 30; ++i) { base[i] = sum; sum += 1 << bits[i]; } } /* build the fixed huffman trees */ function tinf_build_fixed_trees(lt, dt) { var i; /* build fixed length tree */ for (i = 0; i < 7; ++i) lt.table[i] = 0; lt.table[7] = 24; lt.table[8] = 152; lt.table[9] = 112; for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i; for (i = 0; i < 144; ++i) lt.trans[24 + i] = i; for (i = 0; i < 8; ++i) lt.trans[24 + 144 + i] = 280 + i; for (i = 0; i < 112; ++i) lt.trans[24 + 144 + 8 + i] = 144 + i; /* build fixed distance tree */ for (i = 0; i < 5; ++i) dt.table[i] = 0; dt.table[5] = 32; for (i = 0; i < 32; ++i) dt.trans[i] = i; } /* given an array of code lengths, build a tree */ var offs = new Uint16Array(16); function tinf_build_tree(t, lengths, off, num) { var i, sum; /* clear code length count table */ for (i = 0; i < 16; ++i) t.table[i] = 0; /* scan symbol lengths, and sum code length counts */ for (i = 0; i < num; ++i) t.table[lengths[off + i]]++; t.table[0] = 0; /* compute offset table for distribution sort */ for (sum = 0, i = 0; i < 16; ++i) { offs[i] = sum; sum += t.table[i]; } /* create code->symbol translation table (symbols sorted by code) */ for (i = 0; i < num; ++i) { if (lengths[off + i]) t.trans[offs[lengths[off + i]]++] = i; } } /* ---------------------- * * -- decode functions -- * * ---------------------- */ /* get one bit from source stream */ function tinf_getbit(d) { /* check if tag is empty */ if (!d.bitcount--) { /* load next tag */ d.tag = d.source[d.sourceIndex++]; d.bitcount = 7; } /* shift bit out of tag */ var bit = d.tag & 1; d.tag >>>= 1; return bit; } /* read a num bit value from a stream and add base */ function tinf_read_bits(d, num, base) { if (!num) return base; while (d.bitcount < 24) { d.tag |= d.source[d.sourceIndex++] << d.bitcount; d.bitcount += 8; } var val = d.tag & (0xffff >>> (16 - num)); d.tag >>>= num; d.bitcount -= num; return val + base; } /* given a data stream and a tree, decode a symbol */ function tinf_decode_symbol(d, t) { while (d.bitcount < 24) { d.tag |= d.source[d.sourceIndex++] << d.bitcount; d.bitcount += 8; } var sum = 0, cur = 0, len = 0; var tag = d.tag; /* get more bits while code value is above sum */ do { cur = 2 * cur + (tag & 1); tag >>>= 1; ++len; sum += t.table[len]; cur -= t.table[len]; } while (cur >= 0); d.tag = tag; d.bitcount -= len; return t.trans[sum + cur]; } /* given a data stream, decode dynamic trees from it */ function tinf_decode_trees(d, lt, dt) { var hlit, hdist, hclen; var i, num, length; /* get 5 bits HLIT (257-286) */ hlit = tinf_read_bits(d, 5, 257); /* get 5 bits HDIST (1-32) */ hdist = tinf_read_bits(d, 5, 1); /* get 4 bits HCLEN (4-19) */ hclen = tinf_read_bits(d, 4, 4); for (i = 0; i < 19; ++i) lengths[i] = 0; /* read code lengths for code length alphabet */ for (i = 0; i < hclen; ++i) { /* get 3 bits code length (0-7) */ var clen = tinf_read_bits(d, 3, 0); lengths[clcidx[i]] = clen; } /* build code length tree */ tinf_build_tree(code_tree, lengths, 0, 19); /* decode code lengths for the dynamic trees */ for (num = 0; num < hlit + hdist;) { var sym = tinf_decode_symbol(d, code_tree); switch (sym) { case 16: /* copy previous code length 3-6 times (read 2 bits) */ var prev = lengths[num - 1]; for (length = tinf_read_bits(d, 2, 3); length; --length) { lengths[num++] = prev; } break; case 17: /* repeat code length 0 for 3-10 times (read 3 bits) */ for (length = tinf_read_bits(d, 3, 3); length; --length) { lengths[num++] = 0; } break; case 18: /* repeat code length 0 for 11-138 times (read 7 bits) */ for (length = tinf_read_bits(d, 7, 11); length; --length) { lengths[num++] = 0; } break; default: /* values 0-15 represent the actual code lengths */ lengths[num++] = sym; break; } } /* build dynamic trees */ tinf_build_tree(lt, lengths, 0, hlit); tinf_build_tree(dt, lengths, hlit, hdist); } /* ----------------------------- * * -- block inflate functions -- * * ----------------------------- */ /* given a stream and two trees, inflate a block of data */ function tinf_inflate_block_data(d, lt, dt) { while (1) { var sym = tinf_decode_symbol(d, lt); /* check for end of block */ if (sym === 256) { return TINF_OK; } if (sym < 256) { d.dest[d.destLen++] = sym; } else { var length, dist, offs; var i; sym -= 257; /* possibly get more bits from length code */ length = tinf_read_bits(d, length_bits[sym], length_base[sym]); dist = tinf_decode_symbol(d, dt); /* possibly get more bits from distance code */ offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]); /* copy match */ for (i = offs; i < offs + length; ++i) { d.dest[d.destLen++] = d.dest[i]; } } } } /* inflate an uncompressed block of data */ function tinf_inflate_uncompressed_block(d) { var length, invlength; var i; /* unread from bitbuffer */ while (d.bitcount > 8) { d.sourceIndex--; d.bitcount -= 8; } /* get length */ length = d.source[d.sourceIndex + 1]; length = 256 * length + d.source[d.sourceIndex]; /* get one's complement of length */ invlength = d.source[d.sourceIndex + 3]; invlength = 256 * invlength + d.source[d.sourceIndex + 2]; /* check length */ if (length !== (~invlength & 0x0000ffff)) return TINF_DATA_ERROR; d.sourceIndex += 4; /* copy block */ for (i = length; i; --i) d.dest[d.destLen++] = d.source[d.sourceIndex++]; /* make sure we start next block on a byte boundary */ d.bitcount = 0; return TINF_OK; } /* inflate stream from source to dest */ function tinf_uncompress(source, dest) { var d = new Data(source, dest); var bfinal, btype, res; do { /* read final block flag */ bfinal = tinf_getbit(d); /* read block type (2 bits) */ btype = tinf_read_bits(d, 2, 0); /* decompress block */ switch (btype) { case 0: /* decompress uncompressed block */ res = tinf_inflate_uncompressed_block(d); break; case 1: /* decompress block with fixed huffman trees */ res = tinf_inflate_block_data(d, sltree, sdtree); break; case 2: /* decompress block with dynamic huffman trees */ tinf_decode_trees(d, d.ltree, d.dtree); res = tinf_inflate_block_data(d, d.ltree, d.dtree); break; default: res = TINF_DATA_ERROR; } if (res !== TINF_OK) throw new Error('Data error'); } while (!bfinal); if (d.destLen < d.dest.length) { if (typeof d.dest.slice === 'function') return d.dest.slice(0, d.destLen); else return d.dest.subarray(0, d.destLen); } return d.dest; } /* -------------------- * * -- initialization -- * * -------------------- */ /* build fixed huffman trees */ tinf_build_fixed_trees(sltree, sdtree); /* build extra bits and base tables */ tinf_build_bits_base(length_bits, length_base, 4, 3); tinf_build_bits_base(dist_bits, dist_base, 2, 1); /* fix a special case */ length_bits[28] = 0; length_base[28] = 258; module.exports = tinf_uncompress; },{}],2:[function(require,module,exports){ // Run-time checking of preconditions. 'use strict'; exports.fail = function(message) { throw new Error(message); }; // Precondition function that checks if the given predicate is true. // If not, it will throw an error. exports.argument = function(predicate, message) { if (!predicate) { exports.fail(message); } }; // Precondition function that checks if the given assertion is true. // If not, it will throw an error. exports.assert = exports.argument; },{}],3:[function(require,module,exports){ // Drawing utility functions. 'use strict'; // Draw a line on the given context from point `x1,y1` to point `x2,y2`. function line(ctx, x1, y1, x2, y2) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } exports.line = line; },{}],4:[function(require,module,exports){ // Glyph encoding 'use strict'; var cffStandardStrings = [ '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold']; var cffStandardEncoding = [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls']; var cffExpertEncoding = [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall']; var standardNames = [ '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat']; /** * This is the encoding used for fonts created from scratch. * It loops through all glyphs and finds the appropriate unicode value. * Since it's linear time, other encodings will be faster. * @exports opentype.DefaultEncoding * @class * @constructor * @param {opentype.Font} */ function DefaultEncoding(font) { this.font = font; } DefaultEncoding.prototype.charToGlyphIndex = function(c) { var code = c.charCodeAt(0); var glyphs = this.font.glyphs; if (glyphs) { for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); for (var j = 0; j < glyph.unicodes.length; j += 1) { if (glyph.unicodes[j] === code) { return i; } } } } else { return null; } }; /** * @exports opentype.CmapEncoding * @class * @constructor * @param {Object} cmap - a object with the cmap encoded data */ function CmapEncoding(cmap) { this.cmap = cmap; } /** * @param {string} c - the character * @return {number} The glyph index. */ CmapEncoding.prototype.charToGlyphIndex = function(c) { return this.cmap.glyphIndexMap[c.charCodeAt(0)] || 0; }; /** * @exports opentype.CffEncoding * @class * @constructor * @param {string} encoding - The encoding * @param {Array} charset - The charcater set. */ function CffEncoding(encoding, charset) { this.encoding = encoding; this.charset = charset; } /** * @param {string} s - The character * @return {number} The index. */ CffEncoding.prototype.charToGlyphIndex = function(s) { var code = s.charCodeAt(0); var charName = this.encoding[code]; return this.charset.indexOf(charName); }; /** * @exports opentype.GlyphNames * @class * @constructor * @param {Object} post */ function GlyphNames(post) { var i; switch (post.version) { case 1: this.names = exports.standardNames.slice(); break; case 2: this.names = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { if (post.glyphNameIndex[i] < exports.standardNames.length) { this.names[i] = exports.standardNames[post.glyphNameIndex[i]]; } else { this.names[i] = post.names[post.glyphNameIndex[i] - exports.standardNames.length]; } } break; case 2.5: this.names = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { this.names[i] = exports.standardNames[i + post.glyphNameIndex[i]]; } break; case 3: this.names = []; break; } } /** * Gets the index of a glyph by name. * @param {string} name - The glyph name * @return {number} The index */ GlyphNames.prototype.nameToGlyphIndex = function(name) { return this.names.indexOf(name); }; /** * @param {number} gid * @return {string} */ GlyphNames.prototype.glyphIndexToName = function(gid) { return this.names[gid]; }; /** * @alias opentype.addGlyphNames * @param {opentype.Font} */ function addGlyphNames(font) { var glyph; var glyphIndexMap = font.tables.cmap.glyphIndexMap; var charCodes = Object.keys(glyphIndexMap); for (var i = 0; i < charCodes.length; i += 1) { var c = charCodes[i]; var glyphIndex = glyphIndexMap[c]; glyph = font.glyphs.get(glyphIndex); glyph.addUnicode(parseInt(c)); } for (i = 0; i < font.glyphs.length; i += 1) { glyph = font.glyphs.get(i); if (font.cffEncoding) { glyph.name = font.cffEncoding.charset[i]; } else if (font.glyphNames.names) { glyph.name = font.glyphNames.glyphIndexToName(i); } } } exports.cffStandardStrings = cffStandardStrings; exports.cffStandardEncoding = cffStandardEncoding; exports.cffExpertEncoding = cffExpertEncoding; exports.standardNames = standardNames; exports.DefaultEncoding = DefaultEncoding; exports.CmapEncoding = CmapEncoding; exports.CffEncoding = CffEncoding; exports.GlyphNames = GlyphNames; exports.addGlyphNames = addGlyphNames; },{}],5:[function(require,module,exports){ // The Font object 'use strict'; var path = require('./path'); var sfnt = require('./tables/sfnt'); var encoding = require('./encoding'); var glyphset = require('./glyphset'); var Substitution = require('./substitution'); var util = require('./util'); /** * @typedef FontOptions * @type Object * @property {Boolean} empty - whether to create a new empty font * @property {string} familyName * @property {string} styleName * @property {string=} fullName * @property {string=} postScriptName * @property {string=} designer * @property {string=} designerURL * @property {string=} manufacturer * @property {string=} manufacturerURL * @property {string=} license * @property {string=} licenseURL * @property {string=} version * @property {string=} description * @property {string=} copyright * @property {string=} trademark * @property {Number} unitsPerEm * @property {Number} ascender * @property {Number} descender * @property {Number} createdTimestamp * @property {string=} weightClass * @property {string=} widthClass * @property {string=} fsSelection */ /** * A Font represents a loaded OpenType font file. * It contains a set of glyphs and methods to draw text on a drawing context, * or to get a path representing the text. * @exports opentype.Font * @class * @param {FontOptions} * @constructor */ function Font(options) { options = options || {}; if (!options.empty) { // Check that we've provided the minimum set of names. util.checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); util.checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); util.checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); util.checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); util.checkArgument(options.descender, 'When creating a new Font object, descender is required.'); util.checkArgument(options.descender < 0, 'Descender should be negative (e.g. -512).'); // OS X will complain if the names are empty, so we put a single space everywhere by default. this.names = { fontFamily: {en: options.familyName || ' '}, fontSubfamily: {en: options.styleName || ' '}, fullName: {en: options.fullName || options.familyName + ' ' + options.styleName}, postScriptName: {en: options.postScriptName || options.familyName + options.styleName}, designer: {en: options.designer || ' '}, designerURL: {en: options.designerURL || ' '}, manufacturer: {en: options.manufacturer || ' '}, manufacturerURL: {en: options.manufacturerURL || ' '}, license: {en: options.license || ' '}, licenseURL: {en: options.licenseURL || ' '}, version: {en: options.version || 'Version 0.1'}, description: {en: options.description || ' '}, copyright: {en: options.copyright || ' '}, trademark: {en: options.trademark || ' '} }; this.unitsPerEm = options.unitsPerEm || 1000; this.ascender = options.ascender; this.descender = options.descender; this.createdTimestamp = options.createdTimestamp; this.tables = { os2: { usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR } }; } this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); this.encoding = new encoding.DefaultEncoding(this); this.substitution = new Substitution(this); this.tables = this.tables || {}; } /** * Check if the font has a glyph for the given character. * @param {string} * @return {Boolean} */ Font.prototype.hasChar = function(c) { return this.encoding.charToGlyphIndex(c) !== null; }; /** * Convert the given character to a single glyph index. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {Number} */ Font.prototype.charToGlyphIndex = function(s) { return this.encoding.charToGlyphIndex(s); }; /** * Convert the given character to a single Glyph object. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {opentype.Glyph} */ Font.prototype.charToGlyph = function(c) { var glyphIndex = this.charToGlyphIndex(c); var glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * Convert the given text to a list of Glyph objects. * Note that there is no strict one-to-one mapping between characters and * glyphs, so the list of returned glyphs can be larger or smaller than the * length of the given string. * @param {string} * @return {opentype.Glyph[]} */ Font.prototype.stringToGlyphs = function(s) { var glyphs = []; for (var i = 0; i < s.length; i += 1) { var c = s[i]; glyphs.push(this.charToGlyph(c)); } return glyphs; }; /** * @param {string} * @return {Number} */ Font.prototype.nameToGlyphIndex = function(name) { return this.glyphNames.nameToGlyphIndex(name); }; /** * @param {string} * @return {opentype.Glyph} */ Font.prototype.nameToGlyph = function(name) { var glyphIndex = this.nameToGlyphIndex(name); var glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * @param {Number} * @return {String} */ Font.prototype.glyphIndexToName = function(gid) { if (!this.glyphNames.glyphIndexToName) { return ''; } return this.glyphNames.glyphIndexToName(gid); }; /** * Retrieve the value of the kerning pair between the left glyph (or its index) * and the right glyph (or its index). If no kerning pair is found, return 0. * The kerning value gets added to the advance width when calculating the spacing * between glyphs. * @param {opentype.Glyph} leftGlyph * @param {opentype.Glyph} rightGlyph * @return {Number} */ Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { leftGlyph = leftGlyph.index || leftGlyph; rightGlyph = rightGlyph.index || rightGlyph; var gposKerning = this.getGposKerningValue; return gposKerning ? gposKerning(leftGlyph, rightGlyph) : (this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0); }; /** * @typedef GlyphRenderOptions * @type Object * @property {boolean} [kerning] - whether to include kerning values */ /** * Helper function that invokes the given callback for each glyph in the given text. * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text * @param {string} text - The text to apply. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @param {Function} callback */ Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 72; options = options || {}; var kerning = options.kerning === undefined ? true : options.kerning; var fontScale = 1 / this.unitsPerEm * fontSize; var glyphs = this.stringToGlyphs(text); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs[i]; callback(glyph, x, y, fontSize, options); if (glyph.advanceWidth) { x += glyph.advanceWidth * fontScale; } if (kerning && i < glyphs.length - 1) { var kerningValue = this.getKerningValue(glyph, glyphs[i + 1]); x += kerningValue * fontScale; } if (options.letterSpacing) { x += options.letterSpacing * fontSize; } else if (options.tracking) { x += (options.tracking / 1000) * fontSize; } } }; /** * Create a Path object that represents the given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path} */ Font.prototype.getPath = function(text, x, y, fontSize, options) { var fullPath = new path.Path(); this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var glyphPath = glyph.getPath(gX, gY, gFontSize); fullPath.extend(glyphPath); }); return fullPath; }; /** * Create an array of Path objects that represent the glyps of a given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path[]} */ Font.prototype.getPaths = function(text, x, y, fontSize, options) { var glyphPaths = []; this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var glyphPath = glyph.getPath(gX, gY, gFontSize); glyphPaths.push(glyphPath); }); return glyphPaths; }; /** * Draw the text on the given drawing context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { this.getPath(text, x, y, fontSize, options).draw(ctx); }; /** * Draw the points of all glyphs in the text. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawPoints(ctx, gX, gY, gFontSize); }); }; /** * Draw lines indicating important font measurements for all glyphs in the text. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawMetrics(ctx, gX, gY, gFontSize); }); }; /** * @param {string} * @return {string} */ Font.prototype.getEnglishName = function(name) { var translations = this.names[name]; if (translations) { return translations.en; } }; /** * Validate */ Font.prototype.validate = function() { var warnings = []; var _this = this; function assert(predicate, message) { if (!predicate) { warnings.push(message); } } function assertNamePresent(name) { var englishName = _this.getEnglishName(name); assert(englishName && englishName.trim().length > 0, 'No English ' + name + ' specified.'); } // Identification information assertNamePresent('fontFamily'); assertNamePresent('weightName'); assertNamePresent('manufacturer'); assertNamePresent('copyright'); assertNamePresent('version'); // Dimension information assert(this.unitsPerEm > 0, 'No unitsPerEm specified.'); }; /** * Convert the font object to a SFNT data structure. * This structure contains all the necessary tables and metadata to create a binary OTF file. * @return {opentype.Table} */ Font.prototype.toTables = function() { return sfnt.fontToTable(this); }; /** * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. */ Font.prototype.toBuffer = function() { console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); return this.toArrayBuffer(); }; /** * Converts a `opentype.Font` into an `ArrayBuffer` * @return {ArrayBuffer} */ Font.prototype.toArrayBuffer = function() { var sfntTable = this.toTables(); var bytes = sfntTable.encode(); var buffer = new ArrayBuffer(bytes.length); var intArray = new Uint8Array(buffer); for (var i = 0; i < bytes.length; i++) { intArray[i] = bytes[i]; } return buffer; }; /** * Initiate a download of the OpenType font. */ Font.prototype.download = function(fileName) { var familyName = this.getEnglishName('fontFamily'); var styleName = this.getEnglishName('fontSubfamily'); fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; var arrayBuffer = this.toArrayBuffer(); if (util.isBrowser()) { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, arrayBuffer.byteLength, function(fs) { fs.root.getFile(fileName, {create: true}, function(fileEntry) { fileEntry.createWriter(function(writer) { var dataView = new DataView(arrayBuffer); var blob = new Blob([dataView], {type: 'font/opentype'}); writer.write(blob); writer.addEventListener('writeend', function() { // Navigating to the file will download it. location.href = fileEntry.toURL(); }, false); }); }); }, function(err) { throw new Error(err.name + ': ' + err.message); }); } else { var fs = require('fs'); var buffer = util.arrayBufferToNodeBuffer(arrayBuffer); fs.writeFileSync(fileName, buffer); } }; /** * @private */ Font.prototype.fsSelectionValues = { ITALIC: 0x001, //1 UNDERSCORE: 0x002, //2 NEGATIVE: 0x004, //4 OUTLINED: 0x008, //8 STRIKEOUT: 0x010, //16 BOLD: 0x020, //32 REGULAR: 0x040, //64 USER_TYPO_METRICS: 0x080, //128 WWS: 0x100, //256 OBLIQUE: 0x200 //512 }; /** * @private */ Font.prototype.usWidthClasses = { ULTRA_CONDENSED: 1, EXTRA_CONDENSED: 2, CONDENSED: 3, SEMI_CONDENSED: 4, MEDIUM: 5, SEMI_EXPANDED: 6, EXPANDED: 7, EXTRA_EXPANDED: 8, ULTRA_EXPANDED: 9 }; /** * @private */ Font.prototype.usWeightClasses = { THIN: 100, EXTRA_LIGHT: 200, LIGHT: 300, NORMAL: 400, MEDIUM: 500, SEMI_BOLD: 600, BOLD: 700, EXTRA_BOLD: 800, BLACK: 900 }; exports.Font = Font; },{"./encoding":4,"./glyphset":7,"./path":11,"./substitution":12,"./tables/sfnt":31,"./util":33,"fs":undefined}],6:[function(require,module,exports){ // The Glyph object 'use strict'; var check = require('./check'); var draw = require('./draw'); var path = require('./path'); function getPathDefinition(glyph, path) { var _path = path || { commands: [] }; return { configurable: true, get: function() { if (typeof _path === 'function') { _path = _path(); } return _path; }, set: function(p) { _path = p; } }; } /** * @typedef GlyphOptions * @type Object * @property {string} [name] - The glyph name * @property {number} [unicode] * @property {Array} [unicodes] * @property {number} [xMin] * @property {number} [yMin] * @property {number} [xMax] * @property {number} [yMax] * @property {number} [advanceWidth] */ // A Glyph is an individual mark that often corresponds to a character. // Some glyphs, such as ligatures, are a combination of many characters. // Glyphs are the basic building blocks of a font. // // The `Glyph` class contains utility methods for drawing the path and its points. /** * @exports opentype.Glyph * @class * @param {GlyphOptions} * @constructor */ function Glyph(options) { // By putting all the code on a prototype function (which is only declared once) // we reduce the memory requirements for larger fonts by some 2% this.bindConstructorValues(options); } /** * @param {GlyphOptions} */ Glyph.prototype.bindConstructorValues = function(options) { this.index = options.index || 0; // These three values cannnot be deferred for memory optimization: this.name = options.name || null; this.unicode = options.unicode || undefined; this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; // But by binding these values only when necessary, we reduce can // the memory requirements by almost 3% for larger fonts. if (options.xMin) { this.xMin = options.xMin; } if (options.yMin) { this.yMin = options.yMin; } if (options.xMax) { this.xMax = options.xMax; } if (options.yMax) { this.yMax = options.yMax; } if (options.advanceWidth) { this.advanceWidth = options.advanceWidth; } // The path for a glyph is the most memory intensive, and is bound as a value // with a getter/setter to ensure we actually do path parsing only once the // path is actually needed by anything. Object.defineProperty(this, 'path', getPathDefinition(this, options.path)); }; /** * @param {number} */ Glyph.prototype.addUnicode = function(unicode) { if (this.unicodes.length === 0) { this.unicode = unicode; } this.unicodes.push(unicode); }; /** * Convert the glyph to a Path we can draw on a drawing context. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {Object=} options - xScale, yScale to strech the glyph. * @return {opentype.Path} */ Glyph.prototype.getPath = function(x, y, fontSize, options) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; options = options !== undefined ? options : {xScale: 1.0, yScale: 1.0}; fontSize = fontSize !== undefined ? fontSize : 72; var scale = 1 / this.path.unitsPerEm * fontSize; var xScale = options.xScale * scale; var yScale = options.yScale * scale; var p = new path.Path(); var commands = this.path.commands; for (var i = 0; i < commands.length; i += 1) { var cmd = commands[i]; if (cmd.type === 'M') { p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'L') { p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'Q') { p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'C') { p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale), x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'Z') { p.closePath(); } } return p; }; /** * Split the glyph into contours. * This function is here for backwards compatibility, and to * provide raw access to the TrueType glyph outlines. * @return {Array} */ Glyph.prototype.getContours = function() { if (this.points === undefined) { return []; } var contours = []; var currentContour = []; for (var i = 0; i < this.points.length; i += 1) { var pt = this.points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); return contours; }; /** * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph. * @return {Object} */ Glyph.prototype.getMetrics = function() { var commands = this.path.commands; var xCoords = []; var yCoords = []; for (var i = 0; i < commands.length; i += 1) { var cmd = commands[i]; if (cmd.type !== 'Z') { xCoords.push(cmd.x); yCoords.push(cmd.y); } if (cmd.type === 'Q' || cmd.type === 'C') { xCoords.push(cmd.x1); yCoords.push(cmd.y1); } if (cmd.type === 'C') { xCoords.push(cmd.x2); yCoords.push(cmd.y2); } } var metrics = { xMin: Math.min.apply(null, xCoords), yMin: Math.min.apply(null, yCoords), xMax: Math.max.apply(null, xCoords), yMax: Math.max.apply(null, yCoords), leftSideBearing: this.leftSideBearing }; if (!isFinite(metrics.xMin)) { metrics.xMin = 0; } if (!isFinite(metrics.xMax)) { metrics.xMax = this.advanceWidth; } if (!isFinite(metrics.yMin)) { metrics.yMin = 0; } if (!isFinite(metrics.yMax)) { metrics.yMax = 0; } metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); return metrics; }; /** * Draw the glyph on the given context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {Object=} options - xScale, yScale to strech the glyph. */ Glyph.prototype.draw = function(ctx, x, y, fontSize, options) { this.getPath(x, y, fontSize, options).draw(ctx); }; /** * Draw the points of the glyph. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. */ Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) { function drawCircles(l, x, y, scale) { var PI_SQ = Math.PI * 2; ctx.beginPath(); for (var j = 0; j < l.length; j += 1) { ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale)); ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, PI_SQ, false); } ctx.closePath(); ctx.fill(); } x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 24; var scale = 1 / this.path.unitsPerEm * fontSize; var blueCircles = []; var redCircles = []; var path = this.path; for (var i = 0; i < path.commands.length; i += 1) { var cmd = path.commands[i]; if (cmd.x !== undefined) { blueCircles.push({x: cmd.x, y: -cmd.y}); } if (cmd.x1 !== undefined) { redCircles.push({x: cmd.x1, y: -cmd.y1}); } if (cmd.x2 !== undefined) { redCircles.push({x: cmd.x2, y: -cmd.y2}); } } ctx.fillStyle = 'blue'; drawCircles(blueCircles, x, y, scale); ctx.fillStyle = 'red'; drawCircles(redCircles, x, y, scale); }; /** * Draw lines indicating important font measurements. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. */ Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) { var scale; x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 24; scale = 1 / this.path.unitsPerEm * fontSize; ctx.lineWidth = 1; // Draw the origin ctx.strokeStyle = 'black'; draw.line(ctx, x, -10000, x, 10000); draw.line(ctx, -10000, y, 10000, y); // This code is here due to memory optimization: by not using // defaults in the constructor, we save a notable amount of memory. var xMin = this.xMin || 0; var yMin = this.yMin || 0; var xMax = this.xMax || 0; var yMax = this.yMax || 0; var advanceWidth = this.advanceWidth || 0; // Draw the glyph box ctx.strokeStyle = 'blue'; draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000); draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000); draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale)); draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale)); // Draw the advance width ctx.strokeStyle = 'green'; draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000); }; exports.Glyph = Glyph; },{"./check":2,"./draw":3,"./path":11}],7:[function(require,module,exports){ // The GlyphSet object 'use strict'; var _glyph = require('./glyph'); // Define a property on the glyph that depends on the path being loaded. function defineDependentProperty(glyph, externalName, internalName) { Object.defineProperty(glyph, externalName, { get: function() { // Request the path property to make sure the path is loaded. glyph.path; // jshint ignore:line return glyph[internalName]; }, set: function(newValue) { glyph[internalName] = newValue; }, enumerable: true, configurable: true }); } /** * A GlyphSet represents all glyphs available in the font, but modelled using * a deferred glyph loader, for retrieving glyphs only once they are absolutely * necessary, to keep the memory footprint down. * @exports opentype.GlyphSet * @class * @param {opentype.Font} * @param {Array} */ function GlyphSet(font, glyphs) { this.font = font; this.glyphs = {}; if (Array.isArray(glyphs)) { for (var i = 0; i < glyphs.length; i++) { this.glyphs[i] = glyphs[i]; } } this.length = (glyphs && glyphs.length) || 0; } /** * @param {number} index * @return {opentype.Glyph} */ GlyphSet.prototype.get = function(index) { if (typeof this.glyphs[index] === 'function') { this.glyphs[index] = this.glyphs[index](); } return this.glyphs[index]; }; /** * @param {number} index * @param {Object} */ GlyphSet.prototype.push = function(index, loader) { this.glyphs[index] = loader; this.length++; }; /** * @alias opentype.glyphLoader * @param {opentype.Font} font * @param {number} index * @return {opentype.Glyph} */ function glyphLoader(font, index) { return new _glyph.Glyph({index: index, font: font}); } /** * Generate a stub glyph that can be filled with all metadata *except* * the "points" and "path" properties, which must be loaded only once * the glyph's path is actually requested for text shaping. * @alias opentype.ttfGlyphLoader * @param {opentype.Font} font * @param {number} index * @param {Function} parseGlyph * @param {Object} data * @param {number} position * @param {Function} buildPath * @return {opentype.Glyph} */ function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) { return function() { var glyph = new _glyph.Glyph({index: index, font: font}); glyph.path = function() { parseGlyph(glyph, data, position); var path = buildPath(font.glyphs, glyph); path.unitsPerEm = font.unitsPerEm; return path; }; defineDependentProperty(glyph, 'xMin', '_xMin'); defineDependentProperty(glyph, 'xMax', '_xMax'); defineDependentProperty(glyph, 'yMin', '_yMin'); defineDependentProperty(glyph, 'yMax', '_yMax'); return glyph; }; } /** * @alias opentype.cffGlyphLoader * @param {opentype.Font} font * @param {number} index * @param {Function} parseCFFCharstring * @param {string} charstring * @return {opentype.Glyph} */ function cffGlyphLoader(font, index, parseCFFCharstring, charstring) { return function() { var glyph = new _glyph.Glyph({index: index, font: font}); glyph.path = function() { var path = parseCFFCharstring(font, glyph, charstring); path.unitsPerEm = font.unitsPerEm; return path; }; return glyph; }; } exports.GlyphSet = GlyphSet; exports.glyphLoader = glyphLoader; exports.ttfGlyphLoader = ttfGlyphLoader; exports.cffGlyphLoader = cffGlyphLoader; },{"./glyph":6}],8:[function(require,module,exports){ // The Layout object is the prototype of Substition objects, and provides utility methods to manipulate // common layout tables (GPOS, GSUB, GDEF...) 'use strict'; var check = require('./check'); function searchTag(arr, tag) { /* jshint bitwise: false */ var imin = 0; var imax = arr.length - 1; while (imin <= imax) { var imid = (imin + imax) >>> 1; var val = arr[imid].tag; if (val === tag) { return imid; } else if (val < tag) { imin = imid + 1; } else { imax = imid - 1; } } // Not found: return -1-insertion point return -imin - 1; } function binSearch(arr, value) { /* jshint bitwise: false */ var imin = 0; var imax = arr.length - 1; while (imin <= imax) { var imid = (imin + imax) >>> 1; var val = arr[imid]; if (val === value) { return imid; } else if (val < value) { imin = imid + 1; } else { imax = imid - 1; } } // Not found: return -1-insertion point return -imin - 1; } /** * @exports opentype.Layout * @class */ var Layout = { /** * Binary search an object by "tag" property * @instance * @function searchTag * @memberof opentype.Layout * @param {Array} arr * @param {string} tag * @return {number} */ searchTag: searchTag, /** * Binary search in a list of numbers * @instance * @function binSearch * @memberof opentype.Layout * @param {Array} arr * @param {number} value * @return {number} */ binSearch: binSearch, /** * Returns all scripts in the substitution table. * @instance * @return {Array} */ getScriptNames: function() { var gsub = this.getGsubTable(); if (!gsub) { return []; } return gsub.scripts.map(function(script) { return script.tag; }); }, /** * Returns all LangSysRecords in the given script. * @instance * @param {string} script - Use 'DFLT' for default script * @param {boolean} create - forces the creation of this script table if it doesn't exist. * @return {Object} An object with tag and script properties. */ getScriptTable: function(script, create) { var gsub = this.getGsubTable(create); if (gsub) { var scripts = gsub.scripts; var pos = searchTag(gsub.scripts, script); if (pos >= 0) { return scripts[pos].script; } else { var scr = { tag: script, script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }, langSysRecords: [] } }; scripts.splice(-1 - pos, 0, scr.script); return scr; } } }, /** * Returns a language system table * @instance * @param {string} script - Use 'DFLT' for default script * @param {string} language - Use 'DFLT' for default language * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. * @return {Object} */ getLangSysTable: function(script, language, create) { var scriptTable = this.getScriptTable(script, create); if (scriptTable) { if (language === 'DFLT') { return scriptTable.defaultLangSys; } var pos = searchTag(scriptTable.langSysRecords, language); if (pos >= 0) { return scriptTable.langSysRecords[pos].langSys; } else if (create) { var langSysRecord = { tag: language, langSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] } }; scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); return langSysRecord.langSys; } } }, /** * Get a specific feature table. * @instance * @param {string} script - Use 'DFLT' for default script * @param {string} language - Use 'DFLT' for default language * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm * @param {boolean} create - forces the creation of the feature table if it doesn't exist. * @return {Object} */ getFeatureTable: function(script, language, feature, create) { var langSysTable = this.getLangSysTable(script, language, create); if (langSysTable) { var featureRecord; var featIndexes = langSysTable.featureIndexes; var allFeatures = this.font.tables.gsub.features; // The FeatureIndex array of indices is in arbitrary order, // even if allFeatures is sorted alphabetically by feature tag. for (var i = 0; i < featIndexes.length; i++) { featureRecord = allFeatures[featIndexes[i]]; if (featureRecord.tag === feature) { return featureRecord.feature; } } if (create) { var index = allFeatures.length; // Automatic ordering of features would require to shift feature indexes in the script list. check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.'); featureRecord = { tag: feature, feature: { params: 0, lookupListIndexes: [] } }; allFeatures.push(featureRecord); featIndexes.push(index); return featureRecord.feature; } } }, /** * Get the first lookup table of a given type for a script/language/feature. * @instance * @param {string} script - Use 'DFLT' for default script * @param {string} language - Use 'DFLT' for default language * @param {string} feature - 4-letter feature code * @param {number} lookupType - 1 to 8 * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. * @return {Object} */ getLookupTable: function(script, language, feature, lookupType, create) { var featureTable = this.getFeatureTable(script, language, feature, create); if (featureTable) { var lookupTable; var lookupListIndexes = featureTable.lookupListIndexes; var allLookups = this.font.tables.gsub.lookups; // lookupListIndexes are in no particular order, so use naïve search. for (var i = 0; i < lookupListIndexes.length; i++) { lookupTable = allLookups[lookupListIndexes[i]]; if (lookupTable.lookupType === lookupType) { return lookupTable; } } if (create) { lookupTable = { lookupType: lookupType, lookupFlag: 0, subtables: [], markFilteringSet: undefined }; var index = allLookups.length; allLookups.push(lookupTable); lookupListIndexes.push(index); return lookupTable; } } }, /** * Returns the list of glyph indexes of a coverage table. * Format 1: the list is stored raw * Format 2: compact list as range records. * @instance * @param {Object} coverageTable * @return {Array} */ expandCoverage: function(coverageTable) { if (coverageTable.format === 1) { return coverageTable.glyphs; } else { var glyphs = []; var ranges = coverageTable.ranges; for (var i = 0; i < ranges; i++) { var range = ranges[i]; var start = range.start; var end = range.end; for (var j = start; j <= end; j++) { glyphs.push(j); } } return glyphs; } } }; module.exports = Layout; },{"./check":2}],9:[function(require,module,exports){ // opentype.js // https://github.com/nodebox/opentype.js // (c) 2015 Frederik De Bleser // opentype.js may be freely distributed under the MIT license. /* global DataView, Uint8Array, XMLHttpRequest */ 'use strict'; var inflate = require('tiny-inflate'); var encoding = require('./encoding'); var _font = require('./font'); var glyph = require('./glyph'); var parse = require('./parse'); var path = require('./path'); var util = require('./util'); var cmap = require('./tables/cmap'); var cff = require('./tables/cff'); var fvar = require('./tables/fvar'); var glyf = require('./tables/glyf'); var gpos = require('./tables/gpos'); var gsub = require('./tables/gsub'); var head = require('./tables/head'); var hhea = require('./tables/hhea'); var hmtx = require('./tables/hmtx'); var kern = require('./tables/kern'); var ltag = require('./tables/ltag'); var loca = require('./tables/loca'); var maxp = require('./tables/maxp'); var _name = require('./tables/name'); var os2 = require('./tables/os2'); var post = require('./tables/post'); var meta = require('./tables/meta'); /** * The opentype library. * @namespace opentype */ // File loaders ///////////////////////////////////////////////////////// /** * Loads a font from a file. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} path - The path of the file * @param {Function} callback - The function to call when the font load completes */ function loadFromFile(path, callback) { var fs = require('fs'); fs.readFile(path, function(err, buffer) { if (err) { return callback(err.message); } callback(null, util.nodeBufferToArrayBuffer(buffer)); }); } /** * Loads a font from a URL. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} url - The URL of the font file. * @param {Function} callback - The function to call when the font load completes */ function loadFromUrl(url, callback) { var request = new XMLHttpRequest(); request.open('get', url, true); request.responseType = 'arraybuffer'; request.onload = function() { if (request.status !== 200) { return callback('Font could not be loaded: ' + request.statusText); } return callback(null, request.response); }; request.send(); } // Table Directory Entries ////////////////////////////////////////////// /** * Parses OpenType table entries. * @param {DataView} * @param {Number} * @return {Object[]} */ function parseOpenTypeTableEntries(data, numTables) { var tableEntries = []; var p = 12; for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var checksum = parse.getULong(data, p + 4); var offset = parse.getULong(data, p + 8); var length = parse.getULong(data, p + 12); tableEntries.push({tag: tag, checksum: checksum, offset: offset, length: length, compression: false}); p += 16; } return tableEntries; } /** * Parses WOFF table entries. * @param {DataView} * @param {Number} * @return {Object[]} */ function parseWOFFTableEntries(data, numTables) { var tableEntries = []; var p = 44; // offset to the first table directory entry. for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var offset = parse.getULong(data, p + 4); var compLength = parse.getULong(data, p + 8); var origLength = parse.getULong(data, p + 12); var compression; if (compLength < origLength) { compression = 'WOFF'; } else { compression = false; } tableEntries.push({tag: tag, offset: offset, compression: compression, compressedLength: compLength, originalLength: origLength}); p += 20; } return tableEntries; } /** * @typedef TableData * @type Object * @property {DataView} data - The DataView * @property {number} offset - The data offset. */ /** * @param {DataView} * @param {Object} * @return {TableData} */ function uncompressTable(data, tableEntry) { if (tableEntry.compression === 'WOFF') { var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2); var outBuffer = new Uint8Array(tableEntry.originalLength); inflate(inBuffer, outBuffer); if (outBuffer.byteLength !== tableEntry.originalLength) { throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length'); } var view = new DataView(outBuffer.buffer, 0); return {data: view, offset: 0}; } else { return {data: data, offset: tableEntry.offset}; } } // Public API /////////////////////////////////////////////////////////// /** * Parse the OpenType file data (as an ArrayBuffer) and return a Font object. * Throws an error if the font could not be parsed. * @param {ArrayBuffer} * @return {opentype.Font} */ function parseBuffer(buffer) { var indexToLocFormat; var ltagTable; // Since the constructor can also be called to create new fonts from scratch, we indicate this // should be an empty font that we'll fill with our own data. var font = new _font.Font({empty: true}); // OpenType fonts use big endian byte ordering. // We can't rely on typed array view types, because they operate with the endianness of the host computer. // Instead we use DataViews where we can specify endianness. var data = new DataView(buffer, 0); var numTables; var tableEntries = []; var signature = parse.getTag(data, 0); if (signature === String.fromCharCode(0, 1, 0, 0)) { font.outlinesFormat = 'truetype'; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === 'OTTO') { font.outlinesFormat = 'cff'; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === 'wOFF') { var flavor = parse.getTag(data, 4); if (flavor === String.fromCharCode(0, 1, 0, 0)) { font.outlinesFormat = 'truetype'; } else if (flavor === 'OTTO') { font.outlinesFormat = 'cff'; } else { throw new Error('Unsupported OpenType flavor ' + signature); } numTables = parse.getUShort(data, 12); tableEntries = parseWOFFTableEntries(data, numTables); } else { throw new Error('Unsupported OpenType signature ' + signature); } var cffTableEntry; var fvarTableEntry; var glyfTableEntry; var gposTableEntry; var gsubTableEntry; var hmtxTableEntry; var kernTableEntry; var locaTableEntry; var nameTableEntry; var metaTableEntry; for (var i = 0; i < numTables; i += 1) { var tableEntry = tableEntries[i]; var table; switch (tableEntry.tag) { case 'cmap': table = uncompressTable(data, tableEntry); font.tables.cmap = cmap.parse(table.data, table.offset); font.encoding = new encoding.CmapEncoding(font.tables.cmap); break; case 'fvar': fvarTableEntry = tableEntry; break; case 'head': table = uncompressTable(data, tableEntry); font.tables.head = head.parse(table.data, table.offset); font.unitsPerEm = font.tables.head.unitsPerEm; indexToLocFormat = font.tables.head.indexToLocFormat; break; case 'hhea': table = uncompressTable(data, tableEntry); font.tables.hhea = hhea.parse(table.data, table.offset); font.ascender = font.tables.hhea.ascender; font.descender = font.tables.hhea.descender; font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics; break; case 'hmtx': hmtxTableEntry = tableEntry; break; case 'ltag': table = uncompressTable(data, tableEntry); ltagTable = ltag.parse(table.data, table.offset); break; case 'maxp': table = uncompressTable(data, tableEntry); font.tables.maxp = maxp.parse(table.data, table.offset); font.numGlyphs = font.tables.maxp.numGlyphs; break; case 'name': nameTableEntry = tableEntry; break; case 'OS/2': table = uncompressTable(data, tableEntry); font.tables.os2 = os2.parse(table.data, table.offset); break; case 'post': table = uncompressTable(data, tableEntry); font.tables.post = post.parse(table.data, table.offset); font.glyphNames = new encoding.GlyphNames(font.tables.post); break; case 'glyf': glyfTableEntry = tableEntry; break; case 'loca': locaTableEntry = tableEntry; break; case 'CFF ': cffTableEntry = tableEntry; break; case 'kern': kernTableEntry = tableEntry; break; case 'GPOS': gposTableEntry = tableEntry; break; case 'GSUB': gsubTableEntry = tableEntry; break; case 'meta': metaTableEntry = tableEntry; break; } } var nameTable = uncompressTable(data, nameTableEntry); font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable); font.names = font.tables.name; if (glyfTableEntry && locaTableEntry) { var shortVersion = indexToLocFormat === 0; var locaTable = uncompressTable(data, locaTableEntry); var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion); var glyfTable = uncompressTable(data, glyfTableEntry); font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font); } else if (cffTableEntry) { var cffTable = uncompressTable(data, cffTableEntry); cff.parse(cffTable.data, cffTable.offset, font); } else { throw new Error('Font doesn\'t contain TrueType or CFF outlines.'); } var hmtxTable = uncompressTable(data, hmtxTableEntry); hmtx.parse(hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs); encoding.addGlyphNames(font); if (kernTableEntry) { var kernTable = uncompressTable(data, kernTableEntry); font.kerningPairs = kern.parse(kernTable.data, kernTable.offset); } else { font.kerningPairs = {}; } if (gposTableEntry) { var gposTable = uncompressTable(data, gposTableEntry); gpos.parse(gposTable.data, gposTable.offset, font); } if (gsubTableEntry) { var gsubTable = uncompressTable(data, gsubTableEntry); font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset); } if (fvarTableEntry) { var fvarTable = uncompressTable(data, fvarTableEntry); font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names); } if (metaTableEntry) { var metaTable = uncompressTable(data, metaTableEntry); font.tables.meta = meta.parse(metaTable.data, metaTable.offset); font.metas = font.tables.meta; } return font; } /** * Asynchronously load the font from a URL or a filesystem. When done, call the callback * with two arguments `(err, font)`. The `err` will be null on success, * the `font` is a Font object. * We use the node.js callback convention so that * opentype.js can integrate with frameworks like async.js. * @alias opentype.load * @param {string} url - The URL of the font to load. * @param {Function} callback - The callback. */ function load(url, callback) { var isNode = typeof window === 'undefined'; var loadFn = isNode ? loadFromFile : loadFromUrl; loadFn(url, function(err, arrayBuffer) { if (err) { return callback(err); } var font; try { font = parseBuffer(arrayBuffer); } catch (e) { return callback(e, null); } return callback(null, font); }); } /** * Synchronously load the font from a URL or file. * When done, returns the font object or throws an error. * @alias opentype.loadSync * @param {string} url - The URL of the font to load. * @return {opentype.Font} */ function loadSync(url) { var fs = require('fs'); var buffer = fs.readFileSync(url); return parseBuffer(util.nodeBufferToArrayBuffer(buffer)); } exports._parse = parse; exports.Font = _font.Font; exports.Glyph = glyph.Glyph; exports.Path = path.Path; exports.parse = parseBuffer; exports.load = load; exports.loadSync = loadSync; },{"./encoding":4,"./font":5,"./glyph":6,"./parse":10,"./path":11,"./tables/cff":14,"./tables/cmap":15,"./tables/fvar":16,"./tables/glyf":17,"./tables/gpos":18,"./tables/gsub":19,"./tables/head":20,"./tables/hhea":21,"./tables/hmtx":22,"./tables/kern":23,"./tables/loca":24,"./tables/ltag":25,"./tables/maxp":26,"./tables/meta":27,"./tables/name":28,"./tables/os2":29,"./tables/post":30,"./util":33,"fs":undefined,"tiny-inflate":1}],10:[function(require,module,exports){ // Parsing utility functions 'use strict'; var check = require('./check'); // Retrieve an unsigned byte from the DataView. exports.getByte = function getByte(dataView, offset) { return dataView.getUint8(offset); }; exports.getCard8 = exports.getByte; // Retrieve an unsigned 16-bit short from the DataView. // The value is stored in big endian. function getUShort(dataView, offset) { return dataView.getUint16(offset, false); } exports.getUShort = exports.getCard16 = getUShort; // Retrieve a signed 16-bit short from the DataView. // The value is stored in big endian. exports.getShort = function(dataView, offset) { return dataView.getInt16(offset, false); }; // Retrieve an unsigned 32-bit long from the DataView. // The value is stored in big endian. exports.getULong = function(dataView, offset) { return dataView.getUint32(offset, false); }; // Retrieve a 32-bit signed fixed-point number (16.16) from the DataView. // The value is stored in big endian. exports.getFixed = function(dataView, offset) { var decimal = dataView.getInt16(offset, false); var fraction = dataView.getUint16(offset + 2, false); return decimal + fraction / 65535; }; // Retrieve a 4-character tag from the DataView. // Tags are used to identify tables. exports.getTag = function(dataView, offset) { var tag = ''; for (var i = offset; i < offset + 4; i += 1) { tag += String.fromCharCode(dataView.getInt8(i)); } return tag; }; // Retrieve an offset from the DataView. // Offsets are 1 to 4 bytes in length, depending on the offSize argument. exports.getOffset = function(dataView, offset, offSize) { var v = 0; for (var i = 0; i < offSize; i += 1) { v <<= 8; v += dataView.getUint8(offset + i); } return v; }; // Retrieve a number of bytes from start offset to the end offset from the DataView. exports.getBytes = function(dataView, startOffset, endOffset) { var bytes = []; for (var i = startOffset; i < endOffset; i += 1) { bytes.push(dataView.getUint8(i)); } return bytes; }; // Convert the list of bytes to a string. exports.bytesToString = function(bytes) { var s = ''; for (var i = 0; i < bytes.length; i += 1) { s += String.fromCharCode(bytes[i]); } return s; }; var typeOffsets = { byte: 1, uShort: 2, short: 2, uLong: 4, fixed: 4, longDateTime: 8, tag: 4 }; // A stateful parser that changes the offset whenever a value is retrieved. // The data is a DataView. function Parser(data, offset) { this.data = data; this.offset = offset; this.relativeOffset = 0; } Parser.prototype.parseByte = function() { var v = this.data.getUint8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseChar = function() { var v = this.data.getInt8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseCard8 = Parser.prototype.parseByte; Parser.prototype.parseUShort = function() { var v = this.data.getUint16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseCard16 = Parser.prototype.parseUShort; Parser.prototype.parseSID = Parser.prototype.parseUShort; Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; Parser.prototype.parseShort = function() { var v = this.data.getInt16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseF2Dot14 = function() { var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; this.relativeOffset += 2; return v; }; Parser.prototype.parseULong = function() { var v = exports.getULong(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.parseFixed = function() { var v = exports.getFixed(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.parseString = function(length) { var dataView = this.data; var offset = this.offset + this.relativeOffset; var string = ''; this.relativeOffset += length; for (var i = 0; i < length; i++) { string += String.fromCharCode(dataView.getUint8(offset + i)); } return string; }; Parser.prototype.parseTag = function() { return this.parseString(4); }; // LONGDATETIME is a 64-bit integer. // JavaScript and unix timestamps traditionally use 32 bits, so we // only take the last 32 bits. // + Since until 2038 those bits will be filled by zeros we can ignore them. Parser.prototype.parseLongDateTime = function() { var v = exports.getULong(this.data, this.offset + this.relativeOffset + 4); // Subtract seconds between 01/01/1904 and 01/01/1970 // to convert Apple Mac timstamp to Standard Unix timestamp v -= 2082844800; this.relativeOffset += 8; return v; }; Parser.prototype.parseVersion = function() { var major = getUShort(this.data, this.offset + this.relativeOffset); // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1 // This returns the correct number if minor = 0xN000 where N is 0-9 var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); this.relativeOffset += 4; return major + minor / 0x1000 / 10; }; Parser.prototype.skip = function(type, amount) { if (amount === undefined) { amount = 1; } this.relativeOffset += typeOffsets[type] * amount; }; ///// Parsing lists and records /////////////////////////////// // Parse a list of 16 bit integers. The length of the list can be read on the stream // or provided as an argument. Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(count) { if (count === undefined) { count = this.parseUShort(); } var offsets = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) { offsets[i] = dataView.getUint16(offset); offset += 2; } this.relativeOffset += count * 2; return offsets; }; /** * Parse a list of items. * Record count is optional, if omitted it is read from the stream. * itemCallback is one of the Parser methods. */ Parser.prototype.parseList = function(count, itemCallback) { if (!itemCallback) { itemCallback = count; count = this.parseUShort(); } var list = new Array(count); for (var i = 0; i < count; i++) { list[i] = itemCallback.call(this); } return list; }; /** * Parse a list of records. * Record count is optional, if omitted it is read from the stream. * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } */ Parser.prototype.parseRecordList = function(count, recordDescription) { // If the count argument is absent, read it in the stream. if (!recordDescription) { recordDescription = count; count = this.parseUShort(); } var records = new Array(count); var fields = Object.keys(recordDescription); for (var i = 0; i < count; i++) { var rec = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = recordDescription[fieldName]; rec[fieldName] = fieldType.call(this); } records[i] = rec; } return records; }; // Parse a data structure into an object // Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } Parser.prototype.parseStruct = function(description) { if (typeof description === 'function') { return description.call(this); } else { var fields = Object.keys(description); var struct = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = description[fieldName]; struct[fieldName] = fieldType.call(this); } return struct; } }; Parser.prototype.parsePointer = function(description) { var structOffset = this.parseOffset16(); if (structOffset > 0) { // NULL offset => return indefined return new Parser(this.data, this.offset + structOffset).parseStruct(description); } }; /** * Parse a list of offsets to lists of 16-bit integers, * or a list of offsets to lists of offsets to any kind of items. * If itemCallback is not provided, a list of list of UShort is assumed. * If provided, itemCallback is called on each item and must parse the item. * See examples in tables/gsub.js */ Parser.prototype.parseListOfLists = function(itemCallback) { var offsets = this.parseOffset16List(); var count = offsets.length; var relativeOffset = this.relativeOffset; var list = new Array(count); for (var i = 0; i < count; i++) { var start = offsets[i]; if (start === 0) { // NULL offset list[i] = undefined; // Add i as owned property to list. Convenient with assert. continue; } this.relativeOffset = start; if (itemCallback) { var subOffsets = this.parseOffset16List(); var subList = new Array(subOffsets.length); for (var j = 0; j < subOffsets.length; j++) { this.relativeOffset = start + subOffsets[j]; subList[j] = itemCallback.call(this); } list[i] = subList; } else { list[i] = this.parseUShortList(); } } this.relativeOffset = relativeOffset; return list; }; ///// Complex tables parsing ////////////////////////////////// // Parse a coverage table in a GSUB, GPOS or GDEF table. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm // parser.offset must point to the start of the table containing the coverage. Parser.prototype.parseCoverage = function() { var startOffset = this.offset + this.relativeOffset; var format = this.parseUShort(); var count = this.parseUShort(); if (format === 1) { return { format: 1, glyphs: this.parseUShortList(count) }; } else if (format === 2) { var ranges = new Array(count); for (var i = 0; i < count; i++) { ranges[i] = { start: this.parseUShort(), end: this.parseUShort(), index: this.parseUShort() }; } return { format: 2, ranges: ranges }; } check.assert(false, '0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.'); }; // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Parser.prototype.parseClassDef = function() { var startOffset = this.offset + this.relativeOffset; var format = this.parseUShort(); if (format === 1) { return { format: 1, startGlyph: this.parseUShort(), classes: this.parseUShortList() }; } else if (format === 2) { return { format: 2, ranges: this.parseRecordList({ start: Parser.uShort, end: Parser.uShort, classId: Parser.uShort }) }; } check.assert(false, '0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'); }; ///// Static methods /////////////////////////////////// // These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance. Parser.list = function(count, itemCallback) { return function() { return this.parseList(count, itemCallback); }; }; Parser.recordList = function(count, recordDescription) { return function() { return this.parseRecordList(count, recordDescription); }; }; Parser.pointer = function(description) { return function() { return this.parsePointer(description); }; }; Parser.tag = Parser.prototype.parseTag; Parser.byte = Parser.prototype.parseByte; Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; Parser.uShortList = Parser.prototype.parseUShortList; Parser.struct = Parser.prototype.parseStruct; Parser.coverage = Parser.prototype.parseCoverage; Parser.classDef = Parser.prototype.parseClassDef; ///// Script, Feature, Lookup lists /////////////////////////////////////////////// // https://www.microsoft.com/typography/OTSPEC/chapter2.htm var langSysTable = { reserved: Parser.uShort, reqFeatureIndex: Parser.uShort, featureIndexes: Parser.uShortList }; Parser.prototype.parseScriptList = function() { return this.parsePointer(Parser.recordList({ tag: Parser.tag, script: Parser.pointer({ defaultLangSys: Parser.pointer(langSysTable), langSysRecords: Parser.recordList({ tag: Parser.tag, langSys: Parser.pointer(langSysTable) }) }) })); }; Parser.prototype.parseFeatureList = function() { return this.parsePointer(Parser.recordList({ tag: Parser.tag, feature: Parser.pointer({ featureParams: Parser.offset16, lookupListIndexes: Parser.uShortList }) })); }; Parser.prototype.parseLookupList = function(lookupTableParsers) { return this.parsePointer(Parser.list(Parser.pointer(function() { var lookupType = this.parseUShort(); check.argument(1 <= lookupType && lookupType <= 8, 'GSUB lookup type ' + lookupType + ' unknown.'); var lookupFlag = this.parseUShort(); var useMarkFilteringSet = lookupFlag & 0x10; return { lookupType: lookupType, lookupFlag: lookupFlag, subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined }; }))); }; exports.Parser = Parser; },{"./check":2}],11:[function(require,module,exports){ // Geometric objects 'use strict'; /** * A bézier path containing a set of path commands similar to a SVG path. * Paths can be drawn on a context using `draw`. * @exports opentype.Path * @class * @constructor */ function Path() { this.commands = []; this.fill = 'black'; this.stroke = null; this.strokeWidth = 1; } /** * @param {number} x * @param {number} y */ Path.prototype.moveTo = function(x, y) { this.commands.push({ type: 'M', x: x, y: y }); }; /** * @param {number} x * @param {number} y */ Path.prototype.lineTo = function(x, y) { this.commands.push({ type: 'L', x: x, y: y }); }; /** * Draws cubic curve * @function * curveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control 1 * @param {number} y1 - y of control 1 * @param {number} x2 - x of control 2 * @param {number} y2 - y of control 2 * @param {number} x - x of path point * @param {number} y - y of path point */ /** * Draws cubic curve * @function * bezierCurveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control 1 * @param {number} y1 - y of control 1 * @param {number} x2 - x of control 2 * @param {number} y2 - y of control 2 * @param {number} x - x of path point * @param {number} y - y of path point * @see curveTo */ Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) { this.commands.push({ type: 'C', x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }); }; /** * Draws quadratic curve * @function * quadraticCurveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control * @param {number} y1 - y of control * @param {number} x - x of path point * @param {number} y - y of path point */ /** * Draws quadratic curve * @function * quadTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control * @param {number} y1 - y of control * @param {number} x - x of path point * @param {number} y - y of path point */ Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) { this.commands.push({ type: 'Q', x1: x1, y1: y1, x: x, y: y }); }; /** * Closes the path * @function closePath * @memberof opentype.Path.prototype */ /** * Close the path * @function close * @memberof opentype.Path.prototype */ Path.prototype.close = Path.prototype.closePath = function() { this.commands.push({ type: 'Z' }); }; /** * Add the given path or list of commands to the commands of this path. * @param {Array} */ Path.prototype.extend = function(pathOrCommands) { if (pathOrCommands.commands) { pathOrCommands = pathOrCommands.commands; } Array.prototype.push.apply(this.commands, pathOrCommands); }; /** * Draw the path to a 2D context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context. */ Path.prototype.draw = function(ctx) { ctx.beginPath(); for (var i = 0; i < this.commands.length; i += 1) { var cmd = this.commands[i]; if (cmd.type === 'M') { ctx.moveTo(cmd.x, cmd.y); } else if (cmd.type === 'L') { ctx.lineTo(cmd.x, cmd.y); } else if (cmd.type === 'C') { ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { ctx.closePath(); } } if (this.fill) { ctx.fillStyle = this.fill; ctx.fill(); } if (this.stroke) { ctx.strokeStyle = this.stroke; ctx.lineWidth = this.strokeWidth; ctx.stroke(); } }; /** * Convert the Path to a string of path data instructions * See http://www.w3.org/TR/SVG/paths.html#PathData * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {string} */ Path.prototype.toPathData = function(decimalPlaces) { decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; function floatToString(v) { if (Math.round(v) === v) { return '' + Math.round(v); } else { return v.toFixed(decimalPlaces); } } function packValues() { var s = ''; for (var i = 0; i < arguments.length; i += 1) { var v = arguments[i]; if (v >= 0 && i > 0) { s += ' '; } s += floatToString(v); } return s; } var d = ''; for (var i = 0; i < this.commands.length; i += 1) { var cmd = this.commands[i]; if (cmd.type === 'M') { d += 'M' + packValues(cmd.x, cmd.y); } else if (cmd.type === 'L') { d += 'L' + packValues(cmd.x, cmd.y); } else if (cmd.type === 'C') { d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { d += 'Z'; } } return d; }; /** * Convert the path to an SVG <path> element, as a string. * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {string} */ Path.prototype.toSVG = function(decimalPlaces) { var svg = '<path d="'; svg += this.toPathData(decimalPlaces); svg += '"'; if (this.fill && this.fill !== 'black') { if (this.fill === null) { svg += ' fill="none"'; } else { svg += ' fill="' + this.fill + '"'; } } if (this.stroke) { svg += ' stroke="' + this.stroke + '" stroke-width="' + this.strokeWidth + '"'; } svg += '/>'; return svg; }; exports.Path = Path; },{}],12:[function(require,module,exports){ // The Substitution object provides utility methods to manipulate // the GSUB substitution table. 'use strict'; var check = require('./check'); var Layout = require('./layout'); /** * @exports opentype.Substitution * @class * @extends opentype.Layout * @param {opentype.Font} * @constructor */ var Substitution = function(font) { this.font = font; }; // Check if 2 arrays of primitives are equal. function arraysEqual(ar1, ar2) { var n = ar1.length; if (n !== ar2.length) { return false; } for (var i = 0; i < n; i++) { if (ar1[i] !== ar2[i]) { return false; } } return true; } // Find the first subtable of a lookup table in a particular format. function getSubstFormat(lookupTable, format, defaultSubtable) { var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; if (subtable.substFormat === format) { return subtable; } } if (defaultSubtable) { subtables.push(defaultSubtable); return defaultSubtable; } } Substitution.prototype = Layout; /** * Get or create the GSUB table. * @param {boolean} create - Whether to create a new one. * @return {Object} gsub - The GSUB table. */ Substitution.prototype.getGsubTable = function(create) { var gsub = this.font.tables.gsub; if (!gsub && create) { // Generate a default empty GSUB table with just a DFLT script and dflt lang sys. this.font.tables.gsub = gsub = { version: 1, scripts: [{ tag: 'DFLT', script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }, langSysRecords: [] } }], features: [], lookups: [] }; } return gsub; }; /** * List all single substitutions (lookup type 1) for a given script, language, and feature. * @param {string} script * @param {string} language * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...) * @return {Array} substitutions - The list of substitutions. */ Substitution.prototype.getSingle = function(feature, script, language) { var substitutions = []; var lookupTable = this.getLookupTable(script, language, feature, 1); if (!lookupTable) { return substitutions; } var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; var glyphs = this.expandCoverage(subtable.coverage); var j; if (subtable.substFormat === 1) { var delta = subtable.deltaGlyphId; for (j = 0; j < glyphs.length; j++) { var glyph = glyphs[j]; substitutions.push({ sub: glyph, by: glyph + delta }); } } else { var substitute = subtable.substitute; for (j = 0; j < glyphs.length; j++) { substitutions.push({ sub: glyphs[j], by: substitute[j] }); } } } return substitutions; }; /** * List all alternates (lookup type 3) for a given script, language, and feature. * @param {string} script * @param {string} language * @param {string} feature - 4-character feature name ('aalt', 'salt'...) * @return {Array} alternates - The list of alternates */ Substitution.prototype.getAlternates = function(feature, script, language) { var alternates = []; var lookupTable = this.getLookupTable(script, language, feature, 3); if (!lookupTable) { return alternates; } var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; var glyphs = this.expandCoverage(subtable.coverage); var alternateSets = subtable.alternateSets; for (var j = 0; j < glyphs.length; j++) { alternates.push({ sub: glyphs[j], by: alternateSets[j] }); } } return alternates; }; /** * List all ligatures (lookup type 4) for a given script, language, and feature. * The result is an array of ligature objects like { sub: [ids], by: id } * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {string} script * @param {string} language * @return {Array} ligatures - The list of ligatures. */ Substitution.prototype.getLigatures = function(feature, script, language) { var ligatures = []; var lookupTable = this.getLookupTable(script, language, feature, 4); if (!lookupTable) { return []; } var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; var glyphs = this.expandCoverage(subtable.coverage); var ligatureSets = subtable.ligatureSets; for (var j = 0; j < glyphs.length; j++) { var startGlyph = glyphs[j]; var ligSet = ligatureSets[j]; for (var k = 0; k < ligSet.length; k++) { var lig = ligSet[k]; ligatures.push({ sub: [startGlyph].concat(lig.components), by: lig.ligGlyph }); } } } return ligatures; }; /** * Add or modify a single substitution (lookup type 1) * Format 2, more flexible, is always used. * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} substitution - { sub: id, delta: number } for format 1 or { sub: id, by: id } for format 2. * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] */ Substitution.prototype.addSingle = function(feature, substitution, script, language) { var lookupTable = this.getLookupTable(script, language, feature, 1, true); var subtable = getSubstFormat(lookupTable, 2, { // lookup type 1 subtable, format 2, coverage format 1 substFormat: 2, coverage: { format: 1, glyphs: [] }, substitute: [] }); check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); var coverageGlyph = substitution.sub; var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); if (pos < 0) { pos = -1 - pos; subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); subtable.substitute.splice(pos, 0, 0); } subtable.substitute[pos] = substitution.by; }; /** * Add or modify an alternate substitution (lookup type 1) * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} substitution - { sub: id, by: [ids] } * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] */ Substitution.prototype.addAlternate = function(feature, substitution, script, language) { var lookupTable = this.getLookupTable(script, language, feature, 3, true); var subtable = getSubstFormat(lookupTable, 1, { // lookup type 3 subtable, format 1, coverage format 1 substFormat: 1, coverage: { format: 1, glyphs: [] }, alternateSets: [] }); check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); var coverageGlyph = substitution.sub; var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); if (pos < 0) { pos = -1 - pos; subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); subtable.alternateSets.splice(pos, 0, 0); } subtable.alternateSets[pos] = substitution.by; }; /** * Add a ligature (lookup type 4) * Ligatures with more components must be stored ahead of those with fewer components in order to be found * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} ligature - { sub: [ids], by: id } * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] */ Substitution.prototype.addLigature = function(feature, ligature, script, language) { script = script || 'DFLT'; language = language || 'DFLT'; var lookupTable = this.getLookupTable(script, language, feature, 4, true); var subtable = lookupTable.subtables[0]; if (!subtable) { subtable = { // lookup type 4 subtable, format 1, coverage format 1 substFormat: 1, coverage: { format: 1, glyphs: [] }, ligatureSets: [] }; lookupTable.subtables[0] = subtable; } check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); var coverageGlyph = ligature.sub[0]; var ligComponents = ligature.sub.slice(1); var ligatureTable = { ligGlyph: ligature.by, components: ligComponents }; var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); if (pos >= 0) { // ligatureSet already exists var ligatureSet = subtable.ligatureSets[pos]; for (var i = 0; i < ligatureSet.length; i++) { // If ligature already exists, return. if (arraysEqual(ligatureSet[i].components, ligComponents)) { return; } } // ligature does not exist: add it. ligatureSet.push(ligatureTable); } else { // Create a new ligatureSet and add coverage for the first glyph. pos = -1 - pos; subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); subtable.ligatureSets.splice(pos, 0, [ligatureTable]); } }; /** * List all feature data for a given script and language. * @param {string} feature - 4-letter feature name * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] * @return {Array} substitutions - The list of substitutions. */ Substitution.prototype.getFeature = function(feature, script, language) { script = script || 'DFLT'; language = language || 'DFLT'; if (/ss\d\d/.test(feature)) { // ss01 - ss20 return this.getSingle(feature, script, language); } switch (feature) { case 'aalt': case 'salt': return this.getSingle(feature, script, language) .concat(this.getAlternates(feature, script, language)); case 'dlig': case 'liga': case 'rlig': return this.getLigatures(feature, script, language); } }; /** * Add a substitution to a feature for a given script and language. * @param {string} feature - 4-letter feature name * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] }) * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] */ Substitution.prototype.add = function(feature, sub, script, language) { script = script || 'DFLT'; language = language || 'DFLT'; if (/ss\d\d/.test(feature)) { // ss01 - ss20 return this.addSingle(feature, sub, script, language); } switch (feature) { case 'aalt': case 'salt': if (typeof sub.by === 'number') { return this.addSingle(feature, sub, script, language); } return this.addAlternate(feature, sub, script, language); case 'dlig': case 'liga': case 'rlig': return this.addLigature(feature, sub, script, language); } }; module.exports = Substitution; },{"./check":2,"./layout":8}],13:[function(require,module,exports){ // Table metadata 'use strict'; var check = require('./check'); var encode = require('./types').encode; var sizeOf = require('./types').sizeOf; /** * @exports opentype.Table * @class * @param {string} tableName * @param {Array} fields * @param {Object} options * @constructor */ function Table(tableName, fields, options) { var i; for (i = 0; i < fields.length; i += 1) { var field = fields[i]; this[field.name] = field.value; } this.tableName = tableName; this.fields = fields; if (options) { var optionKeys = Object.keys(options); for (i = 0; i < optionKeys.length; i += 1) { var k = optionKeys[i]; var v = options[k]; if (this[k] !== undefined) { this[k] = v; } } } } /** * Encodes the table and returns an array of bytes * @return {Array} */ Table.prototype.encode = function() { return encode.TABLE(this); }; /** * Get the size of the table. * @return {number} */ Table.prototype.sizeOf = function() { return sizeOf.TABLE(this); }; /** * @private */ function ushortList(itemName, list, count) { if (count === undefined) { count = list.length; } var fields = new Array(list.length + 1); fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < list.length; i++) { fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]}; } return fields; } /** * @private */ function tableList(itemName, records, itemCallback) { var count = records.length; var fields = new Array(count + 1); fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < count; i++) { fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)}; } return fields; } /** * @private */ function recordList(itemName, records, itemCallback) { var count = records.length; var fields = []; fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < count; i++) { fields = fields.concat(itemCallback(records[i], i)); } return fields; } // Common Layout Tables /** * @exports opentype.Coverage * @class * @param {opentype.Table} * @constructor * @extends opentype.Table */ function Coverage(coverageTable) { if (coverageTable.format === 1) { Table.call(this, 'coverageTable', [{name: 'coverageFormat', type: 'USHORT', value: 1}] .concat(ushortList('glyph', coverageTable.glyphs)) ); } else { check.assert(false, 'Can\'t create coverage table format 2 yet.'); } } Coverage.prototype = Object.create(Table.prototype); Coverage.prototype.constructor = Coverage; function ScriptList(scriptListTable) { Table.call(this, 'scriptListTable', recordList('scriptRecord', scriptListTable, function(scriptRecord, i) { var script = scriptRecord.script; var defaultLangSys = script.defaultLangSys; check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.'); return [ {name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag}, {name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [ {name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [ {name: 'lookupOrder', type: 'USHORT', value: 0}, {name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}] .concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))} ].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) { var langSys = langSysRecord.langSys; return [ {name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag}, {name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [ {name: 'lookupOrder', type: 'USHORT', value: 0}, {name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex} ].concat(ushortList('featureIndex', langSys.featureIndexes)))} ]; })))} ]; }) ); } ScriptList.prototype = Object.create(Table.prototype); ScriptList.prototype.constructor = ScriptList; /** * @exports opentype.FeatureList * @class * @param {opentype.Table} * @constructor * @extends opentype.Table */ function FeatureList(featureListTable) { Table.call(this, 'featureListTable', recordList('featureRecord', featureListTable, function(featureRecord, i) { var feature = featureRecord.feature; return [ {name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag}, {name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [ {name: 'featureParams', type: 'USHORT', value: feature.featureParams}, ].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))} ]; }) ); } FeatureList.prototype = Object.create(Table.prototype); FeatureList.prototype.constructor = FeatureList; /** * @exports opentype.LookupList * @class * @param {opentype.Table} * @param {Object} * @constructor * @extends opentype.Table */ function LookupList(lookupListTable, subtableMakers) { Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) { var subtableCallback = subtableMakers[lookupTable.lookupType]; check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.'); return new Table('lookupTable', [ {name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType}, {name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag} ].concat(tableList('subtable', lookupTable.subtables, subtableCallback))); })); } LookupList.prototype = Object.create(Table.prototype); LookupList.prototype.constructor = LookupList; // Record = same as Table, but inlined (a Table has an offset and its data is further in the stream) // Don't use offsets inside Records (probable bug), only in Tables. exports.Record = exports.Table = Table; exports.Coverage = Coverage; exports.ScriptList = ScriptList; exports.FeatureList = FeatureList; exports.LookupList = LookupList; exports.ushortList = ushortList; exports.tableList = tableList; exports.recordList = recordList; },{"./check":2,"./types":32}],14:[function(require,module,exports){ // The `CFF` table contains the glyph outlines in PostScript format. // https://www.microsoft.com/typography/OTSPEC/cff.htm // http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/cff.pdf // http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/type2.pdf 'use strict'; var encoding = require('../encoding'); var glyphset = require('../glyphset'); var parse = require('../parse'); var path = require('../path'); var table = require('../table'); // Custom equals function that can also check lists. function equals(a, b) { if (a === b) { return true; } else if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return false; } for (var i = 0; i < a.length; i += 1) { if (!equals(a[i], b[i])) { return false; } } return true; } else { return false; } } // Parse a `CFF` INDEX array. // An index array consists of a list of offsets, then a list of objects at those offsets. function parseCFFIndex(data, start, conversionFn) { //var i, objectOffset, endOffset; var offsets = []; var objects = []; var count = parse.getCard16(data, start); var i; var objectOffset; var endOffset; if (count !== 0) { var offsetSize = parse.getByte(data, start + 2); objectOffset = start + ((count + 1) * offsetSize) + 2; var pos = start + 3; for (i = 0; i < count + 1; i += 1) { offsets.push(parse.getOffset(data, pos, offsetSize)); pos += offsetSize; } // The total size of the index array is 4 header bytes + the value of the last offset. endOffset = objectOffset + offsets[count]; } else { endOffset = start + 2; } for (i = 0; i < offsets.length - 1; i += 1) { var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]); if (conversionFn) { value = conversionFn(value); } objects.push(value); } return {objects: objects, startOffset: start, endOffset: endOffset}; } // Parse a `CFF` DICT real value. function parseFloatOperand(parser) { var s = ''; var eof = 15; var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-']; while (true) { var b = parser.parseByte(); var n1 = b >> 4; var n2 = b & 15; if (n1 === eof) { break; } s += lookup[n1]; if (n2 === eof) { break; } s += lookup[n2]; } return parseFloat(s); } // Parse a `CFF` DICT operand. function parseOperand(parser, b0) { var b1; var b2; var b3; var b4; if (b0 === 28) { b1 = parser.parseByte(); b2 = parser.parseByte(); return b1 << 8 | b2; } if (b0 === 29) { b1 = parser.parseByte(); b2 = parser.parseByte(); b3 = parser.parseByte(); b4 = parser.parseByte(); return b1 << 24 | b2 << 16 | b3 << 8 | b4; } if (b0 === 30) { return parseFloatOperand(parser); } if (b0 >= 32 && b0 <= 246) { return b0 - 139; } if (b0 >= 247 && b0 <= 250) { b1 = parser.parseByte(); return (b0 - 247) * 256 + b1 + 108; } if (b0 >= 251 && b0 <= 254) { b1 = parser.parseByte(); return -(b0 - 251) * 256 - b1 - 108; } throw new Error('Invalid b0 ' + b0); } // Convert the entries returned by `parseDict` to a proper dictionary. // If a value is a list of one, it is unpacked. function entriesToObject(entries) { var o = {}; for (var i = 0; i < entries.length; i += 1) { var key = entries[i][0]; var values = entries[i][1]; var value; if (values.length === 1) { value = values[0]; } else { value = values; } if (o.hasOwnProperty(key)) { throw new Error('Object ' + o + ' already has key ' + key); } o[key] = value; } return o; } // Parse a `CFF` DICT object. // A dictionary contains key-value pairs in a compact tokenized format. function parseCFFDict(data, start, size) { start = start !== undefined ? start : 0; var parser = new parse.Parser(data, start); var entries = []; var operands = []; size = size !== undefined ? size : data.length; while (parser.relativeOffset < size) { var op = parser.parseByte(); // The first byte for each dict item distinguishes between operator (key) and operand (value). // Values <= 21 are operators. if (op <= 21) { // Two-byte operators have an initial escape byte of 12. if (op === 12) { op = 1200 + parser.parseByte(); } entries.push([op, operands]); operands = []; } else { // Since the operands (values) come before the operators (keys), we store all operands in a list // until we encounter an operator. operands.push(parseOperand(parser, op)); } } return entriesToObject(entries); } // Given a String Index (SID), return the value of the string. // Strings below index 392 are standard CFF strings and are not encoded in the font. function getCFFString(strings, index) { if (index <= 390) { index = encoding.cffStandardStrings[index]; } else { index = strings[index - 391]; } return index; } // Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. // This function takes `meta` which is a list of objects containing `operand`, `name` and `default`. function interpretDict(dict, meta, strings) { var newDict = {}; // Because we also want to include missing values, we start out from the meta list // and lookup values in the dict. for (var i = 0; i < meta.length; i += 1) { var m = meta[i]; var value = dict[m.op]; if (value === undefined) { value = m.value !== undefined ? m.value : null; } if (m.type === 'SID') { value = getCFFString(strings, value); } newDict[m.name] = value; } return newDict; } // Parse the CFF header. function parseCFFHeader(data, start) { var header = {}; header.formatMajor = parse.getCard8(data, start); header.formatMinor = parse.getCard8(data, start + 1); header.size = parse.getCard8(data, start + 2); header.offsetSize = parse.getCard8(data, start + 3); header.startOffset = start; header.endOffset = start + 4; return header; } var TOP_DICT_META = [ {name: 'version', op: 0, type: 'SID'}, {name: 'notice', op: 1, type: 'SID'}, {name: 'copyright', op: 1200, type: 'SID'}, {name: 'fullName', op: 2, type: 'SID'}, {name: 'familyName', op: 3, type: 'SID'}, {name: 'weight', op: 4, type: 'SID'}, {name: 'isFixedPitch', op: 1201, type: 'number', value: 0}, {name: 'italicAngle', op: 1202, type: 'number', value: 0}, {name: 'underlinePosition', op: 1203, type: 'number', value: -100}, {name: 'underlineThickness', op: 1204, type: 'number', value: 50}, {name: 'paintType', op: 1205, type: 'number', value: 0}, {name: 'charstringType', op: 1206, type: 'number', value: 2}, {name: 'fontMatrix', op: 1207, type: ['real', 'real', 'real', 'real', 'real', 'real'], value: [0.001, 0, 0, 0.001, 0, 0]}, {name: 'uniqueId', op: 13, type: 'number'}, {name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]}, {name: 'strokeWidth', op: 1208, type: 'number', value: 0}, {name: 'xuid', op: 14, type: [], value: null}, {name: 'charset', op: 15, type: 'offset', value: 0}, {name: 'encoding', op: 16, type: 'offset', value: 0}, {name: 'charStrings', op: 17, type: 'offset', value: 0}, {name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]} ]; var PRIVATE_DICT_META = [ {name: 'subrs', op: 19, type: 'offset', value: 0}, {name: 'defaultWidthX', op: 20, type: 'number', value: 0}, {name: 'nominalWidthX', op: 21, type: 'number', value: 0} ]; // Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. // The top dictionary contains the essential metadata for the font, together with the private dictionary. function parseCFFTopDict(data, strings) { var dict = parseCFFDict(data, 0, data.byteLength); return interpretDict(dict, TOP_DICT_META, strings); } // Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need. function parseCFFPrivateDict(data, start, size, strings) { var dict = parseCFFDict(data, start, size); return interpretDict(dict, PRIVATE_DICT_META, strings); } // Parse the CFF charset table, which contains internal names for all the glyphs. // This function will return a list of glyph names. // See Adobe TN #5176 chapter 13, "Charsets". function parseCFFCharset(data, start, nGlyphs, strings) { var i; var sid; var count; var parser = new parse.Parser(data, start); // The .notdef glyph is not included, so subtract 1. nGlyphs -= 1; var charset = ['.notdef']; var format = parser.parseCard8(); if (format === 0) { for (i = 0; i < nGlyphs; i += 1) { sid = parser.parseSID(); charset.push(getCFFString(strings, sid)); } } else if (format === 1) { while (charset.length <= nGlyphs) { sid = parser.parseSID(); count = parser.parseCard8(); for (i = 0; i <= count; i += 1) { charset.push(getCFFString(strings, sid)); sid += 1; } } } else if (format === 2) { while (charset.length <= nGlyphs) { sid = parser.parseSID(); count = parser.parseCard16(); for (i = 0; i <= count; i += 1) { charset.push(getCFFString(strings, sid)); sid += 1; } } } else { throw new Error('Unknown charset format ' + format); } return charset; } // Parse the CFF encoding data. Only one encoding can be specified per font. // See Adobe TN #5176 chapter 12, "Encodings". function parseCFFEncoding(data, start, charset) { var i; var code; var enc = {}; var parser = new parse.Parser(data, start); var format = parser.parseCard8(); if (format === 0) { var nCodes = parser.parseCard8(); for (i = 0; i < nCodes; i += 1) { code = parser.parseCard8(); enc[code] = i; } } else if (format === 1) { var nRanges = parser.parseCard8(); code = 1; for (i = 0; i < nRanges; i += 1) { var first = parser.parseCard8(); var nLeft = parser.parseCard8(); for (var j = first; j <= first + nLeft; j += 1) { enc[j] = code; code += 1; } } } else { throw new Error('Unknown encoding format ' + format); } return new encoding.CffEncoding(enc, charset); } // Take in charstring code and return a Glyph object. // The encoding is described in the Type 2 Charstring Format // https://www.microsoft.com/typography/OTSPEC/charstr2.htm function parseCFFCharstring(font, glyph, code) { var c1x; var c1y; var c2x; var c2y; var p = new path.Path(); var stack = []; var nStems = 0; var haveWidth = false; var width = font.defaultWidthX; var open = false; var x = 0; var y = 0; function newContour(x, y) { if (open) { p.closePath(); } p.moveTo(x, y); open = true; } function parseStems() { var hasWidthArg; // The number of stem operators on the stack is always even. // If the value is uneven, that means a width is specified. hasWidthArg = stack.length % 2 !== 0; if (hasWidthArg && !haveWidth) { width = stack.shift() + font.nominalWidthX; } nStems += stack.length >> 1; stack.length = 0; haveWidth = true; } function parse(code) { var b1; var b2; var b3; var b4; var codeIndex; var subrCode; var jpx; var jpy; var c3x; var c3y; var c4x; var c4y; var i = 0; while (i < code.length) { var v = code[i]; i += 1; switch (v) { case 1: // hstem parseStems(); break; case 3: // vstem parseStems(); break; case 4: // vmoveto if (stack.length > 1 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } y += stack.pop(); newContour(x, y); break; case 5: // rlineto while (stack.length > 0) { x += stack.shift(); y += stack.shift(); p.lineTo(x, y); } break; case 6: // hlineto while (stack.length > 0) { x += stack.shift(); p.lineTo(x, y); if (stack.length === 0) { break; } y += stack.shift(); p.lineTo(x, y); } break; case 7: // vlineto while (stack.length > 0) { y += stack.shift(); p.lineTo(x, y); if (stack.length === 0) { break; } x += stack.shift(); p.lineTo(x, y); } break; case 8: // rrcurveto while (stack.length > 0) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 10: // callsubr codeIndex = stack.pop() + font.subrsBias; subrCode = font.subrs[codeIndex]; if (subrCode) { parse(subrCode); } break; case 11: // return return; case 12: // flex operators v = code[i]; i += 1; switch (v) { case 35: // flex // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y + stack.shift(); // dy3 c3x = jpx + stack.shift(); // dx4 c3y = jpy + stack.shift(); // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 x = c4x + stack.shift(); // dx6 y = c4y + stack.shift(); // dy6 stack.shift(); // flex depth p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 34: // hflex // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- c1x = x + stack.shift(); // dx1 c1y = y; // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y; // dy3 c3x = jpx + stack.shift(); // dx4 c3y = c2y; // dy4 c4x = c3x + stack.shift(); // dx5 c4y = y; // dy5 x = c4x + stack.shift(); // dx6 p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 36: // hflex1 // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y; // dy3 c3x = jpx + stack.shift(); // dx4 c3y = c2y; // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 x = c4x + stack.shift(); // dx6 p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 37: // flex1 // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y + stack.shift(); // dy3 c3x = jpx + stack.shift(); // dx4 c3y = jpy + stack.shift(); // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 if (Math.abs(c4x - x) > Math.abs(c4y - y)) { x = c4x + stack.shift(); } else { y = c4y + stack.shift(); } p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; default: console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v); stack.length = 0; } break; case 14: // endchar if (stack.length > 0 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } if (open) { p.closePath(); open = false; } break; case 18: // hstemhm parseStems(); break; case 19: // hintmask case 20: // cntrmask parseStems(); i += (nStems + 7) >> 3; break; case 21: // rmoveto if (stack.length > 2 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } y += stack.pop(); x += stack.pop(); newContour(x, y); break; case 22: // hmoveto if (stack.length > 1 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } x += stack.pop(); newContour(x, y); break; case 23: // vstemhm parseStems(); break; case 24: // rcurveline while (stack.length > 2) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } x += stack.shift(); y += stack.shift(); p.lineTo(x, y); break; case 25: // rlinecurve while (stack.length > 6) { x += stack.shift(); y += stack.shift(); p.lineTo(x, y); } c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); break; case 26: // vvcurveto if (stack.length % 2) { x += stack.shift(); } while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x; y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 27: // hhcurveto if (stack.length % 2) { y += stack.shift(); } while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y; p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 28: // shortint b1 = code[i]; b2 = code[i + 1]; stack.push(((b1 << 24) | (b2 << 16)) >> 16); i += 2; break; case 29: // callgsubr codeIndex = stack.pop() + font.gsubrsBias; subrCode = font.gsubrs[codeIndex]; if (subrCode) { parse(subrCode); } break; case 30: // vhcurveto while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 31: // hvcurveto while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; default: if (v < 32) { console.log('Glyph ' + glyph.index + ': unknown operator ' + v); } else if (v < 247) { stack.push(v - 139); } else if (v < 251) { b1 = code[i]; i += 1; stack.push((v - 247) * 256 + b1 + 108); } else if (v < 255) { b1 = code[i]; i += 1; stack.push(-(v - 251) * 256 - b1 - 108); } else { b1 = code[i]; b2 = code[i + 1]; b3 = code[i + 2]; b4 = code[i + 3]; i += 4; stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536); } } } } parse(code); glyph.advanceWidth = width; return p; } // Subroutines are encoded using the negative half of the number space. // See type 2 chapter 4.7 "Subroutine operators". function calcCFFSubroutineBias(subrs) { var bias; if (subrs.length < 1240) { bias = 107; } else if (subrs.length < 33900) { bias = 1131; } else { bias = 32768; } return bias; } // Parse the `CFF` table, which contains the glyph outlines in PostScript format. function parseCFFTable(data, start, font) { font.tables.cff = {}; var header = parseCFFHeader(data, start); var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString); var topDictIndex = parseCFFIndex(data, nameIndex.endOffset); var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString); var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset); font.gsubrs = globalSubrIndex.objects; font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); var topDictData = new DataView(new Uint8Array(topDictIndex.objects[0]).buffer); var topDict = parseCFFTopDict(topDictData, stringIndex.objects); font.tables.cff.topDict = topDict; var privateDictOffset = start + topDict['private'][1]; var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict['private'][0], stringIndex.objects); font.defaultWidthX = privateDict.defaultWidthX; font.nominalWidthX = privateDict.nominalWidthX; if (privateDict.subrs !== 0) { var subrOffset = privateDictOffset + privateDict.subrs; var subrIndex = parseCFFIndex(data, subrOffset); font.subrs = subrIndex.objects; font.subrsBias = calcCFFSubroutineBias(font.subrs); } else { font.subrs = []; font.subrsBias = 0; } // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset. var charStringsIndex = parseCFFIndex(data, start + topDict.charStrings); font.nGlyphs = charStringsIndex.objects.length; var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects); if (topDict.encoding === 0) { // Standard encoding font.cffEncoding = new encoding.CffEncoding(encoding.cffStandardEncoding, charset); } else if (topDict.encoding === 1) { // Expert encoding font.cffEncoding = new encoding.CffEncoding(encoding.cffExpertEncoding, charset); } else { font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset); } // Prefer the CMAP encoding to the CFF encoding. font.encoding = font.encoding || font.cffEncoding; font.glyphs = new glyphset.GlyphSet(font); for (var i = 0; i < font.nGlyphs; i += 1) { var charString = charStringsIndex.objects[i]; font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); } } // Convert a string to a String ID (SID). // The list of strings is modified in place. function encodeString(s, strings) { var sid; // Is the string in the CFF standard strings? var i = encoding.cffStandardStrings.indexOf(s); if (i >= 0) { sid = i; } // Is the string already in the string index? i = strings.indexOf(s); if (i >= 0) { sid = i + encoding.cffStandardStrings.length; } else { sid = encoding.cffStandardStrings.length + strings.length; strings.push(s); } return sid; } function makeHeader() { return new table.Record('Header', [ {name: 'major', type: 'Card8', value: 1}, {name: 'minor', type: 'Card8', value: 0}, {name: 'hdrSize', type: 'Card8', value: 4}, {name: 'major', type: 'Card8', value: 1} ]); } function makeNameIndex(fontNames) { var t = new table.Record('Name INDEX', [ {name: 'names', type: 'INDEX', value: []} ]); t.names = []; for (var i = 0; i < fontNames.length; i += 1) { t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]}); } return t; } // Given a dictionary's metadata, create a DICT structure. function makeDict(meta, attrs, strings) { var m = {}; for (var i = 0; i < meta.length; i += 1) { var entry = meta[i]; var value = attrs[entry.name]; if (value !== undefined && !equals(value, entry.value)) { if (entry.type === 'SID') { value = encodeString(value, strings); } m[entry.op] = {name: entry.name, type: entry.type, value: value}; } } return m; } // The Top DICT houses the global font attributes. function makeTopDict(attrs, strings) { var t = new table.Record('Top DICT', [ {name: 'dict', type: 'DICT', value: {}} ]); t.dict = makeDict(TOP_DICT_META, attrs, strings); return t; } function makeTopDictIndex(topDict) { var t = new table.Record('Top DICT INDEX', [ {name: 'topDicts', type: 'INDEX', value: []} ]); t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}]; return t; } function makeStringIndex(strings) { var t = new table.Record('String INDEX', [ {name: 'strings', type: 'INDEX', value: []} ]); t.strings = []; for (var i = 0; i < strings.length; i += 1) { t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]}); } return t; } function makeGlobalSubrIndex() { // Currently we don't use subroutines. return new table.Record('Global Subr INDEX', [ {name: 'subrs', type: 'INDEX', value: []} ]); } function makeCharsets(glyphNames, strings) { var t = new table.Record('Charsets', [ {name: 'format', type: 'Card8', value: 0} ]); for (var i = 0; i < glyphNames.length; i += 1) { var glyphName = glyphNames[i]; var glyphSID = encodeString(glyphName, strings); t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID}); } return t; } function glyphToOps(glyph) { var ops = []; var path = glyph.path; ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth}); var x = 0; var y = 0; for (var i = 0; i < path.commands.length; i += 1) { var dx; var dy; var cmd = path.commands[i]; if (cmd.type === 'Q') { // CFF only supports bézier curves, so convert the quad to a bézier. var _13 = 1 / 3; var _23 = 2 / 3; // We're going to create a new command so we don't change the original path. cmd = { type: 'C', x: cmd.x, y: cmd.y, x1: _13 * x + _23 * cmd.x1, y1: _13 * y + _23 * cmd.y1, x2: _13 * cmd.x + _23 * cmd.x1, y2: _13 * cmd.y + _23 * cmd.y1 }; } if (cmd.type === 'M') { dx = Math.round(cmd.x - x); dy = Math.round(cmd.y - y); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rmoveto', type: 'OP', value: 21}); x = Math.round(cmd.x); y = Math.round(cmd.y); } else if (cmd.type === 'L') { dx = Math.round(cmd.x - x); dy = Math.round(cmd.y - y); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rlineto', type: 'OP', value: 5}); x = Math.round(cmd.x); y = Math.round(cmd.y); } else if (cmd.type === 'C') { var dx1 = Math.round(cmd.x1 - x); var dy1 = Math.round(cmd.y1 - y); var dx2 = Math.round(cmd.x2 - cmd.x1); var dy2 = Math.round(cmd.y2 - cmd.y1); dx = Math.round(cmd.x - cmd.x2); dy = Math.round(cmd.y - cmd.y2); ops.push({name: 'dx1', type: 'NUMBER', value: dx1}); ops.push({name: 'dy1', type: 'NUMBER', value: dy1}); ops.push({name: 'dx2', type: 'NUMBER', value: dx2}); ops.push({name: 'dy2', type: 'NUMBER', value: dy2}); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rrcurveto', type: 'OP', value: 8}); x = Math.round(cmd.x); y = Math.round(cmd.y); } // Contours are closed automatically. } ops.push({name: 'endchar', type: 'OP', value: 14}); return ops; } function makeCharStringsIndex(glyphs) { var t = new table.Record('CharStrings INDEX', [ {name: 'charStrings', type: 'INDEX', value: []} ]); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); var ops = glyphToOps(glyph); t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops}); } return t; } function makePrivateDict(attrs, strings) { var t = new table.Record('Private DICT', [ {name: 'dict', type: 'DICT', value: {}} ]); t.dict = makeDict(PRIVATE_DICT_META, attrs, strings); return t; } function makeCFFTable(glyphs, options) { var t = new table.Table('CFF ', [ {name: 'header', type: 'RECORD'}, {name: 'nameIndex', type: 'RECORD'}, {name: 'topDictIndex', type: 'RECORD'}, {name: 'stringIndex', type: 'RECORD'}, {name: 'globalSubrIndex', type: 'RECORD'}, {name: 'charsets', type: 'RECORD'}, {name: 'charStringsIndex', type: 'RECORD'}, {name: 'privateDict', type: 'RECORD'} ]); var fontScale = 1 / options.unitsPerEm; // We use non-zero values for the offsets so that the DICT encodes them. // This is important because the size of the Top DICT plays a role in offset calculation, // and the size shouldn't change after we've written correct offsets. var attrs = { version: options.version, fullName: options.fullName, familyName: options.familyName, weight: options.weightName, fontBBox: options.fontBBox || [0, 0, 0, 0], fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], charset: 999, encoding: 0, charStrings: 999, private: [0, 999] }; var privateAttrs = {}; var glyphNames = []; var glyph; // Skip first glyph (.notdef) for (var i = 1; i < glyphs.length; i += 1) { glyph = glyphs.get(i); glyphNames.push(glyph.name); } var strings = []; t.header = makeHeader(); t.nameIndex = makeNameIndex([options.postScriptName]); var topDict = makeTopDict(attrs, strings); t.topDictIndex = makeTopDictIndex(topDict); t.globalSubrIndex = makeGlobalSubrIndex(); t.charsets = makeCharsets(glyphNames, strings); t.charStringsIndex = makeCharStringsIndex(glyphs); t.privateDict = makePrivateDict(privateAttrs, strings); // Needs to come at the end, to encode all custom strings used in the font. t.stringIndex = makeStringIndex(strings); var startOffset = t.header.sizeOf() + t.nameIndex.sizeOf() + t.topDictIndex.sizeOf() + t.stringIndex.sizeOf() + t.globalSubrIndex.sizeOf(); attrs.charset = startOffset; // We use the CFF standard encoding; proper encoding will be handled in cmap. attrs.encoding = 0; attrs.charStrings = attrs.charset + t.charsets.sizeOf(); attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf(); // Recreate the Top DICT INDEX with the correct offsets. topDict = makeTopDict(attrs, strings); t.topDictIndex = makeTopDictIndex(topDict); return t; } exports.parse = parseCFFTable; exports.make = makeCFFTable; },{"../encoding":4,"../glyphset":7,"../parse":10,"../path":11,"../table":13}],15:[function(require,module,exports){ // The `cmap` table stores the mappings from characters to glyphs. // https://www.microsoft.com/typography/OTSPEC/cmap.htm 'use strict'; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); function parseCmapTableFormat12(cmap, p) { var i; //Skip reserved. p.parseUShort(); // Length in bytes of the sub-tables. cmap.length = p.parseULong(); cmap.language = p.parseULong(); var groupCount; cmap.groupCount = groupCount = p.parseULong(); cmap.glyphIndexMap = {}; for (i = 0; i < groupCount; i += 1) { var startCharCode = p.parseULong(); var endCharCode = p.parseULong(); var startGlyphId = p.parseULong(); for (var c = startCharCode; c <= endCharCode; c += 1) { cmap.glyphIndexMap[c] = startGlyphId; startGlyphId++; } } } function parseCmapTableFormat4(cmap, p, data, start, offset) { var i; // Length in bytes of the sub-tables. cmap.length = p.parseUShort(); cmap.language = p.parseUShort(); // segCount is stored x 2. var segCount; cmap.segCount = segCount = p.parseUShort() >> 1; // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); // The "unrolled" mapping from character codes to glyph indices. cmap.glyphIndexMap = {}; var endCountParser = new parse.Parser(data, start + offset + 14); var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2); var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4); var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6); var glyphIndexOffset = start + offset + 16 + segCount * 8; for (i = 0; i < segCount - 1; i += 1) { var glyphIndex; var endCount = endCountParser.parseUShort(); var startCount = startCountParser.parseUShort(); var idDelta = idDeltaParser.parseShort(); var idRangeOffset = idRangeOffsetParser.parseUShort(); for (var c = startCount; c <= endCount; c += 1) { if (idRangeOffset !== 0) { // The idRangeOffset is relative to the current position in the idRangeOffset array. // Take the current offset in the idRangeOffset array. glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2); // Add the value of the idRangeOffset, which will move us into the glyphIndex array. glyphIndexOffset += idRangeOffset; // Then add the character index of the current segment, multiplied by 2 for USHORTs. glyphIndexOffset += (c - startCount) * 2; glyphIndex = parse.getUShort(data, glyphIndexOffset); if (glyphIndex !== 0) { glyphIndex = (glyphIndex + idDelta) & 0xFFFF; } } else { glyphIndex = (c + idDelta) & 0xFFFF; } cmap.glyphIndexMap[c] = glyphIndex; } } } // Parse the `cmap` table. This table stores the mappings from characters to glyphs. // There are many available formats, but we only support the Windows format 4 and 12. // This function returns a `CmapEncoding` object or null if no supported format could be found. function parseCmapTable(data, start) { var i; var cmap = {}; cmap.version = parse.getUShort(data, start); check.argument(cmap.version === 0, 'cmap table version should be 0.'); // The cmap table can contain many sub-tables, each with their own format. // We're only interested in a "platform 3" table. This is a Windows format. cmap.numTables = parse.getUShort(data, start + 2); var offset = -1; for (i = cmap.numTables - 1; i >= 0; i -= 1) { var platformId = parse.getUShort(data, start + 4 + (i * 8)); var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2); if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) { offset = parse.getULong(data, start + 4 + (i * 8) + 4); break; } } if (offset === -1) { // There is no cmap table in the font that we support, so return null. // This font will be marked as unsupported. return null; } var p = new parse.Parser(data, start + offset); cmap.format = p.parseUShort(); if (cmap.format === 12) { parseCmapTableFormat12(cmap, p); } else if (cmap.format === 4) { parseCmapTableFormat4(cmap, p, data, start, offset); } else { throw new Error('Only format 4 and 12 cmap tables are supported.'); } return cmap; } function addSegment(t, code, glyphIndex) { t.segments.push({ end: code, start: code, delta: -(code - glyphIndex), offset: 0 }); } function addTerminatorSegment(t) { t.segments.push({ end: 0xFFFF, start: 0xFFFF, delta: 1, offset: 0 }); } function makeCmapTable(glyphs) { var i; var t = new table.Table('cmap', [ {name: 'version', type: 'USHORT', value: 0}, {name: 'numTables', type: 'USHORT', value: 1}, {name: 'platformID', type: 'USHORT', value: 3}, {name: 'encodingID', type: 'USHORT', value: 1}, {name: 'offset', type: 'ULONG', value: 12}, {name: 'format', type: 'USHORT', value: 4}, {name: 'length', type: 'USHORT', value: 0}, {name: 'language', type: 'USHORT', value: 0}, {name: 'segCountX2', type: 'USHORT', value: 0}, {name: 'searchRange', type: 'USHORT', value: 0}, {name: 'entrySelector', type: 'USHORT', value: 0}, {name: 'rangeShift', type: 'USHORT', value: 0} ]); t.segments = []; for (i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); for (var j = 0; j < glyph.unicodes.length; j += 1) { addSegment(t, glyph.unicodes[j], i); } t.segments = t.segments.sort(function(a, b) { return a.start - b.start; }); } addTerminatorSegment(t); var segCount; segCount = t.segments.length; t.segCountX2 = segCount * 2; t.searchRange = Math.pow(2, Math.floor(Math.log(segCount) / Math.log(2))) * 2; t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2); t.rangeShift = t.segCountX2 - t.searchRange; // Set up parallel segment arrays. var endCounts = []; var startCounts = []; var idDeltas = []; var idRangeOffsets = []; var glyphIds = []; for (i = 0; i < segCount; i += 1) { var segment = t.segments[i]; endCounts = endCounts.concat({name: 'end_' + i, type: 'USHORT', value: segment.end}); startCounts = startCounts.concat({name: 'start_' + i, type: 'USHORT', value: segment.start}); idDeltas = idDeltas.concat({name: 'idDelta_' + i, type: 'SHORT', value: segment.delta}); idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i, type: 'USHORT', value: segment.offset}); if (segment.glyphId !== undefined) { glyphIds = glyphIds.concat({name: 'glyph_' + i, type: 'USHORT', value: segment.glyphId}); } } t.fields = t.fields.concat(endCounts); t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0}); t.fields = t.fields.concat(startCounts); t.fields = t.fields.concat(idDeltas); t.fields = t.fields.concat(idRangeOffsets); t.fields = t.fields.concat(glyphIds); t.length = 14 + // Subtable header endCounts.length * 2 + 2 + // reservedPad startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2; return t; } exports.parse = parseCmapTable; exports.make = makeCmapTable; },{"../check":2,"../parse":10,"../table":13}],16:[function(require,module,exports){ // The `fvar` table stores font variation axes and instances. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html 'use strict'; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); function addName(name, names) { var nameString = JSON.stringify(name); var nameID = 256; for (var nameKey in names) { var n = parseInt(nameKey); if (!n || n < 256) { continue; } if (JSON.stringify(names[nameKey]) === nameString) { return n; } if (nameID <= n) { nameID = n + 1; } } names[nameID] = name; return nameID; } function makeFvarAxis(n, axis, names) { var nameID = addName(axis.name, names); return [ {name: 'tag_' + n, type: 'TAG', value: axis.tag}, {name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16}, {name: 'defaultValue_' + n, type: 'FIXED', value: axis.defaultValue << 16}, {name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16}, {name: 'flags_' + n, type: 'USHORT', value: 0}, {name: 'nameID_' + n, type: 'USHORT', value: nameID} ]; } function parseFvarAxis(data, start, names) { var axis = {}; var p = new parse.Parser(data, start); axis.tag = p.parseTag(); axis.minValue = p.parseFixed(); axis.defaultValue = p.parseFixed(); axis.maxValue = p.parseFixed(); p.skip('uShort', 1); // reserved for flags; no values defined axis.name = names[p.parseUShort()] || {}; return axis; } function makeFvarInstance(n, inst, axes, names) { var nameID = addName(inst.name, names); var fields = [ {name: 'nameID_' + n, type: 'USHORT', value: nameID}, {name: 'flags_' + n, type: 'USHORT', value: 0} ]; for (var i = 0; i < axes.length; ++i) { var axisTag = axes[i].tag; fields.push({ name: 'axis_' + n + ' ' + axisTag, type: 'FIXED', value: inst.coordinates[axisTag] << 16 }); } return fields; } function parseFvarInstance(data, start, axes, names) { var inst = {}; var p = new parse.Parser(data, start); inst.name = names[p.parseUShort()] || {}; p.skip('uShort', 1); // reserved for flags; no values defined inst.coordinates = {}; for (var i = 0; i < axes.length; ++i) { inst.coordinates[axes[i].tag] = p.parseFixed(); } return inst; } function makeFvarTable(fvar, names) { var result = new table.Table('fvar', [ {name: 'version', type: 'ULONG', value: 0x10000}, {name: 'offsetToData', type: 'USHORT', value: 0}, {name: 'countSizePairs', type: 'USHORT', value: 2}, {name: 'axisCount', type: 'USHORT', value: fvar.axes.length}, {name: 'axisSize', type: 'USHORT', value: 20}, {name: 'instanceCount', type: 'USHORT', value: fvar.instances.length}, {name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4} ]); result.offsetToData = result.sizeOf(); for (var i = 0; i < fvar.axes.length; i++) { result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names)); } for (var j = 0; j < fvar.instances.length; j++) { result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names)); } return result; } function parseFvarTable(data, start, names) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 0x00010000, 'Unsupported fvar table version.'); var offsetToData = p.parseOffset16(); // Skip countSizePairs. p.skip('uShort', 1); var axisCount = p.parseUShort(); var axisSize = p.parseUShort(); var instanceCount = p.parseUShort(); var instanceSize = p.parseUShort(); var axes = []; for (var i = 0; i < axisCount; i++) { axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names)); } var instances = []; var instanceStart = start + offsetToData + axisCount * axisSize; for (var j = 0; j < instanceCount; j++) { instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names)); } return {axes: axes, instances: instances}; } exports.make = makeFvarTable; exports.parse = parseFvarTable; },{"../check":2,"../parse":10,"../table":13}],17:[function(require,module,exports){ // The `glyf` table describes the glyphs in TrueType outline format. // http://www.microsoft.com/typography/otspec/glyf.htm 'use strict'; var check = require('../check'); var glyphset = require('../glyphset'); var parse = require('../parse'); var path = require('../path'); // Parse the coordinate data for a glyph. function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { var v; if ((flag & shortVectorBitMask) > 0) { // The coordinate is 1 byte long. v = p.parseByte(); // The `same` bit is re-used for short values to signify the sign of the value. if ((flag & sameBitMask) === 0) { v = -v; } v = previousValue + v; } else { // The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if ((flag & sameBitMask) > 0) { v = previousValue; } else { // Parse the coordinate as a signed 16-bit delta value. v = previousValue + p.parseShort(); } } return v; } // Parse a TrueType glyph. function parseGlyph(glyph, data, start) { var p = new parse.Parser(data, start); glyph.numberOfContours = p.parseShort(); glyph._xMin = p.parseShort(); glyph._yMin = p.parseShort(); glyph._xMax = p.parseShort(); glyph._yMax = p.parseShort(); var flags; var flag; if (glyph.numberOfContours > 0) { var i; // This glyph is not a composite. var endPointIndices = glyph.endPointIndices = []; for (i = 0; i < glyph.numberOfContours; i += 1) { endPointIndices.push(p.parseUShort()); } glyph.instructionLength = p.parseUShort(); glyph.instructions = []; for (i = 0; i < glyph.instructionLength; i += 1) { glyph.instructions.push(p.parseByte()); } var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; flags = []; for (i = 0; i < numberOfCoordinates; i += 1) { flag = p.parseByte(); flags.push(flag); // If bit 3 is set, we repeat this flag n times, where n is the next byte. if ((flag & 8) > 0) { var repeatCount = p.parseByte(); for (var j = 0; j < repeatCount; j += 1) { flags.push(flag); i += 1; } } } check.argument(flags.length === numberOfCoordinates, 'Bad flags.'); if (endPointIndices.length > 0) { var points = []; var point; // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. if (numberOfCoordinates > 0) { for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = {}; point.onCurve = !!(flag & 1); point.lastPointOfContour = endPointIndices.indexOf(i) >= 0; points.push(point); } var px = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.x = parseGlyphCoordinate(p, flag, px, 2, 16); px = point.x; } var py = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.y = parseGlyphCoordinate(p, flag, py, 4, 32); py = point.y; } } glyph.points = points; } else { glyph.points = []; } } else if (glyph.numberOfContours === 0) { glyph.points = []; } else { glyph.isComposite = true; glyph.points = []; glyph.components = []; var moreComponents = true; while (moreComponents) { flags = p.parseUShort(); var component = { glyphIndex: p.parseUShort(), xScale: 1, scale01: 0, scale10: 0, yScale: 1, dx: 0, dy: 0 }; if ((flags & 1) > 0) { // The arguments are words if ((flags & 2) > 0) { // values are offset component.dx = p.parseShort(); component.dy = p.parseShort(); } else { // values are matched points component.matchedPoints = [p.parseUShort(), p.parseUShort()]; } } else { // The arguments are bytes if ((flags & 2) > 0) { // values are offset component.dx = p.parseChar(); component.dy = p.parseChar(); } else { // values are matched points component.matchedPoints = [p.parseByte(), p.parseByte()]; } } if ((flags & 8) > 0) { // We have a scale component.xScale = component.yScale = p.parseF2Dot14(); } else if ((flags & 64) > 0) { // We have an X / Y scale component.xScale = p.parseF2Dot14(); component.yScale = p.parseF2Dot14(); } else if ((flags & 128) > 0) { // We have a 2x2 transformation component.xScale = p.parseF2Dot14(); component.scale01 = p.parseF2Dot14(); component.scale10 = p.parseF2Dot14(); component.yScale = p.parseF2Dot14(); } glyph.components.push(component); moreComponents = !!(flags & 32); } } } // Transform an array of points and return a new array. function transformPoints(points, transform) { var newPoints = []; for (var i = 0; i < points.length; i += 1) { var pt = points[i]; var newPt = { x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; } function getContours(points) { var contours = []; var currentContour = []; for (var i = 0; i < points.length; i += 1) { var pt = points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); return contours; } // Convert the TrueType glyph outline to a Path. function getPath(points) { var p = new path.Path(); if (!points) { return p; } var contours = getContours(points); for (var i = 0; i < contours.length; i += 1) { var contour = contours[i]; var firstPt = contour[0]; var lastPt = contour[contour.length - 1]; var curvePt; var realFirstPoint; if (firstPt.onCurve) { curvePt = null; // The first point will be consumed by the moveTo command, // so skip it in the loop. realFirstPoint = true; } else { if (lastPt.onCurve) { // If the first point is off-curve and the last point is on-curve, // start at the last point. firstPt = lastPt; } else { // If both first and last points are off-curve, start at their middle. firstPt = { x: (firstPt.x + lastPt.x) / 2, y: (firstPt.y + lastPt.y) / 2 }; } curvePt = firstPt; // The first point is synthesized, so don't skip the real first point. realFirstPoint = false; } p.moveTo(firstPt.x, firstPt.y); for (var j = realFirstPoint ? 1 : 0; j < contour.length; j += 1) { var pt = contour[j]; var prevPt = j === 0 ? firstPt : contour[j - 1]; if (prevPt.onCurve && pt.onCurve) { // This is a straight line. p.lineTo(pt.x, pt.y); } else if (prevPt.onCurve && !pt.onCurve) { curvePt = pt; } else if (!prevPt.onCurve && !pt.onCurve) { var midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; p.quadraticCurveTo(prevPt.x, prevPt.y, midPt.x, midPt.y); curvePt = pt; } else if (!prevPt.onCurve && pt.onCurve) { // Previous point off-curve, this point on-curve. p.quadraticCurveTo(curvePt.x, curvePt.y, pt.x, pt.y); curvePt = null; } else { throw new Error('Invalid state.'); } } if (firstPt !== lastPt) { // Connect the last and first points if (curvePt) { p.quadraticCurveTo(curvePt.x, curvePt.y, firstPt.x, firstPt.y); } else { p.lineTo(firstPt.x, firstPt.y); } } } p.closePath(); return p; } function buildPath(glyphs, glyph) { if (glyph.isComposite) { for (var j = 0; j < glyph.components.length; j += 1) { var component = glyph.components[j]; var componentGlyph = glyphs.get(component.glyphIndex); // Force the ttfGlyphLoader to parse the glyph. componentGlyph.getPath(); if (componentGlyph.points) { var transformedPoints; if (component.matchedPoints === undefined) { // component positioned by offset transformedPoints = transformPoints(componentGlyph.points, component); } else { // component positioned by matched points if ((component.matchedPoints[0] > glyph.points.length - 1) || (component.matchedPoints[1] > componentGlyph.points.length - 1)) { throw Error('Matched points out of range in ' + glyph.name); } var firstPt = glyph.points[component.matchedPoints[0]]; var secondPt = componentGlyph.points[component.matchedPoints[1]]; var transform = { xScale: component.xScale, scale01: component.scale01, scale10: component.scale10, yScale: component.yScale, dx: 0, dy: 0 }; secondPt = transformPoints([secondPt], transform)[0]; transform.dx = firstPt.x - secondPt.x; transform.dy = firstPt.y - secondPt.y; transformedPoints = transformPoints(componentGlyph.points, transform); } glyph.points = glyph.points.concat(transformedPoints); } } } return getPath(glyph.points); } // Parse all the glyphs according to the offsets from the `loca` table. function parseGlyfTable(data, start, loca, font) { var glyphs = new glyphset.GlyphSet(font); var i; // The last element of the loca table is invalid. for (i = 0; i < loca.length - 1; i += 1) { var offset = loca[i]; var nextOffset = loca[i + 1]; if (offset !== nextOffset) { glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); } else { glyphs.push(i, glyphset.glyphLoader(font, i)); } } return glyphs; } exports.parse = parseGlyfTable; },{"../check":2,"../glyphset":7,"../parse":10,"../path":11}],18:[function(require,module,exports){ // The `GPOS` table contains kerning pairs, among other things. // https://www.microsoft.com/typography/OTSPEC/gpos.htm 'use strict'; var check = require('../check'); var parse = require('../parse'); // Parse ScriptList and FeatureList tables of GPOS, GSUB, GDEF, BASE, JSTF tables. // These lists are unused by now, this function is just the basis for a real parsing. function parseTaggedListTable(data, start) { var p = new parse.Parser(data, start); var n = p.parseUShort(); var list = []; for (var i = 0; i < n; i++) { list[p.parseTag()] = { offset: p.parseUShort() }; } return list; } // Parse a coverage table in a GSUB, GPOS or GDEF table. // Format 1 is a simple list of glyph ids, // Format 2 is a list of ranges. It is expanded in a list of glyphs, maybe not the best idea. function parseCoverageTable(data, start) { var p = new parse.Parser(data, start); var format = p.parseUShort(); var count = p.parseUShort(); if (format === 1) { return p.parseUShortList(count); } else if (format === 2) { var coverage = []; for (; count--;) { var begin = p.parseUShort(); var end = p.parseUShort(); var index = p.parseUShort(); for (var i = begin; i <= end; i++) { coverage[index++] = i; } } return coverage; } } // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. // Returns a function that gets a class value from a glyph ID. function parseClassDefTable(data, start) { var p = new parse.Parser(data, start); var format = p.parseUShort(); if (format === 1) { // Format 1 specifies a range of consecutive glyph indices, one class per glyph ID. var startGlyph = p.parseUShort(); var glyphCount = p.parseUShort(); var classes = p.parseUShortList(glyphCount); return function(glyphID) { return classes[glyphID - startGlyph] || 0; }; } else if (format === 2) { // Format 2 defines multiple groups of glyph indices that belong to the same class. var rangeCount = p.parseUShort(); var startGlyphs = []; var endGlyphs = []; var classValues = []; for (var i = 0; i < rangeCount; i++) { startGlyphs[i] = p.parseUShort(); endGlyphs[i] = p.parseUShort(); classValues[i] = p.parseUShort(); } return function(glyphID) { var l = 0; var r = startGlyphs.length - 1; while (l < r) { var c = (l + r + 1) >> 1; if (glyphID < startGlyphs[c]) { r = c - 1; } else { l = c; } } if (startGlyphs[l] <= glyphID && glyphID <= endGlyphs[l]) { return classValues[l] || 0; } return 0; }; } } // Parse a pair adjustment positioning subtable, format 1 or format 2 // The subtable is returned in the form of a lookup function. function parsePairPosSubTable(data, start) { var p = new parse.Parser(data, start); // This part is common to format 1 and format 2 subtables var format = p.parseUShort(); var coverageOffset = p.parseUShort(); var coverage = parseCoverageTable(data, start + coverageOffset); // valueFormat 4: XAdvance only, 1: XPlacement only, 0: no ValueRecord for second glyph // Only valueFormat1=4 and valueFormat2=0 is supported. var valueFormat1 = p.parseUShort(); var valueFormat2 = p.parseUShort(); var value1; var value2; if (valueFormat1 !== 4 || valueFormat2 !== 0) return; var sharedPairSets = {}; if (format === 1) { // Pair Positioning Adjustment: Format 1 var pairSetCount = p.parseUShort(); var pairSet = []; // Array of offsets to PairSet tables-from beginning of PairPos subtable-ordered by Coverage Index var pairSetOffsets = p.parseOffset16List(pairSetCount); for (var firstGlyph = 0; firstGlyph < pairSetCount; firstGlyph++) { var pairSetOffset = pairSetOffsets[firstGlyph]; var sharedPairSet = sharedPairSets[pairSetOffset]; if (!sharedPairSet) { // Parse a pairset table in a pair adjustment subtable format 1 sharedPairSet = {}; p.relativeOffset = pairSetOffset; var pairValueCount = p.parseUShort(); for (; pairValueCount--;) { var secondGlyph = p.parseUShort(); if (valueFormat1) value1 = p.parseShort(); if (valueFormat2) value2 = p.parseShort(); // We only support valueFormat1 = 4 and valueFormat2 = 0, // so value1 is the XAdvance and value2 is empty. sharedPairSet[secondGlyph] = value1; } } pairSet[coverage[firstGlyph]] = sharedPairSet; } return function(leftGlyph, rightGlyph) { var pairs = pairSet[leftGlyph]; if (pairs) return pairs[rightGlyph]; }; } else if (format === 2) { // Pair Positioning Adjustment: Format 2 var classDef1Offset = p.parseUShort(); var classDef2Offset = p.parseUShort(); var class1Count = p.parseUShort(); var class2Count = p.parseUShort(); var getClass1 = parseClassDefTable(data, start + classDef1Offset); var getClass2 = parseClassDefTable(data, start + classDef2Offset); // Parse kerning values by class pair. var kerningMatrix = []; for (var i = 0; i < class1Count; i++) { var kerningRow = kerningMatrix[i] = []; for (var j = 0; j < class2Count; j++) { if (valueFormat1) value1 = p.parseShort(); if (valueFormat2) value2 = p.parseShort(); // We only support valueFormat1 = 4 and valueFormat2 = 0, // so value1 is the XAdvance and value2 is empty. kerningRow[j] = value1; } } // Convert coverage list to a hash var covered = {}; for (i = 0; i < coverage.length; i++) covered[coverage[i]] = 1; // Get the kerning value for a specific glyph pair. return function(leftGlyph, rightGlyph) { if (!covered[leftGlyph]) return; var class1 = getClass1(leftGlyph); var class2 = getClass2(rightGlyph); var kerningRow = kerningMatrix[class1]; if (kerningRow) { return kerningRow[class2]; } }; } } // Parse a LookupTable (present in of GPOS, GSUB, GDEF, BASE, JSTF tables). function parseLookupTable(data, start) { var p = new parse.Parser(data, start); var lookupType = p.parseUShort(); var lookupFlag = p.parseUShort(); var useMarkFilteringSet = lookupFlag & 0x10; var subTableCount = p.parseUShort(); var subTableOffsets = p.parseOffset16List(subTableCount); var table = { lookupType: lookupType, lookupFlag: lookupFlag, markFilteringSet: useMarkFilteringSet ? p.parseUShort() : -1 }; // LookupType 2, Pair adjustment if (lookupType === 2) { var subtables = []; for (var i = 0; i < subTableCount; i++) { subtables.push(parsePairPosSubTable(data, start + subTableOffsets[i])); } // Return a function which finds the kerning values in the subtables. table.getKerningValue = function(leftGlyph, rightGlyph) { for (var i = subtables.length; i--;) { var value = subtables[i](leftGlyph, rightGlyph); if (value !== undefined) return value; } return 0; }; } return table; } // Parse the `GPOS` table which contains, among other things, kerning pairs. // https://www.microsoft.com/typography/OTSPEC/gpos.htm function parseGposTable(data, start, font) { var p = new parse.Parser(data, start); var tableVersion = p.parseFixed(); check.argument(tableVersion === 1, 'Unsupported GPOS table version.'); // ScriptList and FeatureList - ignored for now parseTaggedListTable(data, start + p.parseUShort()); // 'kern' is the feature we are looking for. parseTaggedListTable(data, start + p.parseUShort()); // LookupList var lookupListOffset = p.parseUShort(); p.relativeOffset = lookupListOffset; var lookupCount = p.parseUShort(); var lookupTableOffsets = p.parseOffset16List(lookupCount); var lookupListAbsoluteOffset = start + lookupListOffset; for (var i = 0; i < lookupCount; i++) { var table = parseLookupTable(data, lookupListAbsoluteOffset + lookupTableOffsets[i]); if (table.lookupType === 2 && !font.getGposKerningValue) font.getGposKerningValue = table.getKerningValue; } } exports.parse = parseGposTable; },{"../check":2,"../parse":10}],19:[function(require,module,exports){ // The `GSUB` table contains ligatures, among other things. // https://www.microsoft.com/typography/OTSPEC/gsub.htm 'use strict'; var check = require('../check'); var Parser = require('../parse').Parser; var subtableParsers = new Array(9); // subtableParsers[0] is unused var table = require('../table'); // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS subtableParsers[1] = function parseLookup1() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: 1, coverage: this.parsePointer(Parser.coverage), deltaGlyphId: this.parseUShort() }; } else if (substFormat === 2) { return { substFormat: 2, coverage: this.parsePointer(Parser.coverage), substitute: this.parseOffset16List() }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS subtableParsers[2] = function parseLookup2() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), sequences: this.parseListOfLists() }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS subtableParsers[3] = function parseLookup3() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), alternateSets: this.parseListOfLists() }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS subtableParsers[4] = function parseLookup4() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), ligatureSets: this.parseListOfLists(function() { return { ligGlyph: this.parseUShort(), components: this.parseUShortList(this.parseUShort() - 1) }; }) }; }; var lookupRecordDesc = { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF subtableParsers[5] = function parseLookup5() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), ruleSets: this.parseListOfLists(function() { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { input: this.parseUShortList(glyphCount - 1), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; }) }; } else if (substFormat === 2) { return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), classDef: this.parsePointer(Parser.classDef), classSets: this.parseListOfLists(function() { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { classes: this.parseUShortList(glyphCount - 1), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; }) }; } else if (substFormat === 3) { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { substFormat: substFormat, coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC subtableParsers[6] = function parseLookup6() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: 1, coverage: this.parsePointer(Parser.coverage), chainRuleSets: this.parseListOfLists(function() { return { backtrack: this.parseUShortList(), input: this.parseUShortList(this.parseShort() - 1), lookahead: this.parseUShortList(), lookupRecords: this.parseRecordList(lookupRecordDesc) }; }) }; } else if (substFormat === 2) { return { substFormat: 2, coverage: this.parsePointer(Parser.coverage), backtrackClassDef: this.parsePointer(Parser.classDef), inputClassDef: this.parsePointer(Parser.classDef), lookaheadClassDef: this.parsePointer(Parser.classDef), chainClassSet: this.parseListOfLists(function() { return { backtrack: this.parseUShortList(), input: this.parseUShortList(this.parseShort() - 1), lookahead: this.parseUShortList(), lookupRecords: this.parseRecordList(lookupRecordDesc) }; }) }; } else if (substFormat === 3) { return { substFormat: 3, backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookupRecords: this.parseRecordList(lookupRecordDesc) }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES subtableParsers[7] = function parseLookup7() { // Extension Substitution subtable var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1'); var extensionLookupType = this.parseUShort(); var extensionParser = new Parser(this.data, this.offset + this.parseULong()); return { substFormat: 1, lookupType: extensionLookupType, extension: subtableParsers[extensionLookupType].call(extensionParser) }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS subtableParsers[8] = function parseLookup8() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), substitutes: this.parseUShortList() }; }; // https://www.microsoft.com/typography/OTSPEC/gsub.htm function parseGsubTable(data, start) { start = start || 0; var p = new Parser(data, start); var tableVersion = p.parseVersion(); check.argument(tableVersion === 1, 'Unsupported GSUB table version.'); return { version: tableVersion, scripts: p.parseScriptList(), features: p.parseFeatureList(), lookups: p.parseLookupList(subtableParsers) }; } // GSUB Writing ////////////////////////////////////////////// var subtableMakers = new Array(9); subtableMakers[1] = function makeLookup1(subtable) { if (subtable.substFormat === 1) { return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}, {name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId} ]); } else { return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 2}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.ushortList('substitute', subtable.substitute))); } check.fail('Lookup type 1 substFormat must be 1 or 2.'); }; subtableMakers[3] = function makeLookup3(subtable) { check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.'); return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) { return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet)); }))); }; subtableMakers[4] = function makeLookup4(subtable) { check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.'); return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) { return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) { return new table.Table('ligatureTable', [{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}] .concat(table.ushortList('component', ligature.components, ligature.components.length + 1)) ); })); }))); }; function makeGsubTable(gsub) { return new table.Table('GSUB', [ {name: 'version', type: 'ULONG', value: 0x10000}, {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)}, {name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)}, {name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)} ]); } exports.parse = parseGsubTable; exports.make = makeGsubTable; },{"../check":2,"../parse":10,"../table":13}],20:[function(require,module,exports){ // The `head` table contains global information about the font. // https://www.microsoft.com/typography/OTSPEC/head.htm 'use strict'; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); // Parse the header `head` table function parseHeadTable(data, start) { var head = {}; var p = new parse.Parser(data, start); head.version = p.parseVersion(); head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; head.checkSumAdjustment = p.parseULong(); head.magicNumber = p.parseULong(); check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.'); head.flags = p.parseUShort(); head.unitsPerEm = p.parseUShort(); head.created = p.parseLongDateTime(); head.modified = p.parseLongDateTime(); head.xMin = p.parseShort(); head.yMin = p.parseShort(); head.xMax = p.parseShort(); head.yMax = p.parseShort(); head.macStyle = p.parseUShort(); head.lowestRecPPEM = p.parseUShort(); head.fontDirectionHint = p.parseShort(); head.indexToLocFormat = p.parseShort(); head.glyphDataFormat = p.parseShort(); return head; } function makeHeadTable(options) { // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970 var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; var createdTimestamp = timestamp; if (options.createdTimestamp) { createdTimestamp = options.createdTimestamp + 2082844800; } return new table.Table('head', [ {name: 'version', type: 'FIXED', value: 0x00010000}, {name: 'fontRevision', type: 'FIXED', value: 0x00010000}, {name: 'checkSumAdjustment', type: 'ULONG', value: 0}, {name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5}, {name: 'flags', type: 'USHORT', value: 0}, {name: 'unitsPerEm', type: 'USHORT', value: 1000}, {name: 'created', type: 'LONGDATETIME', value: createdTimestamp}, {name: 'modified', type: 'LONGDATETIME', value: timestamp}, {name: 'xMin', type: 'SHORT', value: 0}, {name: 'yMin', type: 'SHORT', value: 0}, {name: 'xMax', type: 'SHORT', value: 0}, {name: 'yMax', type: 'SHORT', value: 0}, {name: 'macStyle', type: 'USHORT', value: 0}, {name: 'lowestRecPPEM', type: 'USHORT', value: 0}, {name: 'fontDirectionHint', type: 'SHORT', value: 2}, {name: 'indexToLocFormat', type: 'SHORT', value: 0}, {name: 'glyphDataFormat', type: 'SHORT', value: 0} ], options); } exports.parse = parseHeadTable; exports.make = makeHeadTable; },{"../check":2,"../parse":10,"../table":13}],21:[function(require,module,exports){ // The `hhea` table contains information for horizontal layout. // https://www.microsoft.com/typography/OTSPEC/hhea.htm 'use strict'; var parse = require('../parse'); var table = require('../table'); // Parse the horizontal header `hhea` table function parseHheaTable(data, start) { var hhea = {}; var p = new parse.Parser(data, start); hhea.version = p.parseVersion(); hhea.ascender = p.parseShort(); hhea.descender = p.parseShort(); hhea.lineGap = p.parseShort(); hhea.advanceWidthMax = p.parseUShort(); hhea.minLeftSideBearing = p.parseShort(); hhea.minRightSideBearing = p.parseShort(); hhea.xMaxExtent = p.parseShort(); hhea.caretSlopeRise = p.parseShort(); hhea.caretSlopeRun = p.parseShort(); hhea.caretOffset = p.parseShort(); p.relativeOffset += 8; hhea.metricDataFormat = p.parseShort(); hhea.numberOfHMetrics = p.parseUShort(); return hhea; } function makeHheaTable(options) { return new table.Table('hhea', [ {name: 'version', type: 'FIXED', value: 0x00010000}, {name: 'ascender', type: 'FWORD', value: 0}, {name: 'descender', type: 'FWORD', value: 0}, {name: 'lineGap', type: 'FWORD', value: 0}, {name: 'advanceWidthMax', type: 'UFWORD', value: 0}, {name: 'minLeftSideBearing', type: 'FWORD', value: 0}, {name: 'minRightSideBearing', type: 'FWORD', value: 0}, {name: 'xMaxExtent', type: 'FWORD', value: 0}, {name: 'caretSlopeRise', type: 'SHORT', value: 1}, {name: 'caretSlopeRun', type: 'SHORT', value: 0}, {name: 'caretOffset', type: 'SHORT', value: 0}, {name: 'reserved1', type: 'SHORT', value: 0}, {name: 'reserved2', type: 'SHORT', value: 0}, {name: 'reserved3', type: 'SHORT', value: 0}, {name: 'reserved4', type: 'SHORT', value: 0}, {name: 'metricDataFormat', type: 'SHORT', value: 0}, {name: 'numberOfHMetrics', type: 'USHORT', value: 0} ], options); } exports.parse = parseHheaTable; exports.make = makeHheaTable; },{"../parse":10,"../table":13}],22:[function(require,module,exports){ // The `hmtx` table contains the horizontal metrics for all glyphs. // https://www.microsoft.com/typography/OTSPEC/hmtx.htm 'use strict'; var parse = require('../parse'); var table = require('../table'); // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) { var advanceWidth; var leftSideBearing; var p = new parse.Parser(data, start); for (var i = 0; i < numGlyphs; i += 1) { // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. if (i < numMetrics) { advanceWidth = p.parseUShort(); leftSideBearing = p.parseShort(); } var glyph = glyphs.get(i); glyph.advanceWidth = advanceWidth; glyph.leftSideBearing = leftSideBearing; } } function makeHmtxTable(glyphs) { var t = new table.Table('hmtx', []); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); var advanceWidth = glyph.advanceWidth || 0; var leftSideBearing = glyph.leftSideBearing || 0; t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth}); t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing}); } return t; } exports.parse = parseHmtxTable; exports.make = makeHmtxTable; },{"../parse":10,"../table":13}],23:[function(require,module,exports){ // The `kern` table contains kerning pairs. // Note that some fonts use the GPOS OpenType layout table to specify kerning. // https://www.microsoft.com/typography/OTSPEC/kern.htm 'use strict'; var check = require('../check'); var parse = require('../parse'); function parseWindowsKernTable(p) { var pairs = {}; // Skip nTables. p.skip('uShort'); var subtableVersion = p.parseUShort(); check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.'); // Skip subtableLength, subtableCoverage p.skip('uShort', 2); var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } return pairs; } function parseMacKernTable(p) { var pairs = {}; // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits. // Skip the rest. p.skip('uShort'); var nTables = p.parseULong(); //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').'); if (nTables > 1) { console.warn('Only the first kern subtable is supported.'); } p.skip('uLong'); var coverage = p.parseUShort(); var subtableVersion = coverage & 0xFF; p.skip('uShort'); if (subtableVersion === 0) { var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } } return pairs; } // Parse the `kern` table which contains kerning pairs. function parseKernTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseUShort(); if (tableVersion === 0) { return parseWindowsKernTable(p); } else if (tableVersion === 1) { return parseMacKernTable(p); } else { throw new Error('Unsupported kern table version (' + tableVersion + ').'); } } exports.parse = parseKernTable; },{"../check":2,"../parse":10}],24:[function(require,module,exports){ // The `loca` table stores the offsets to the locations of the glyphs in the font. // https://www.microsoft.com/typography/OTSPEC/loca.htm 'use strict'; var parse = require('../parse'); // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, // relative to the beginning of the glyphData table. // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) // The loca table has two versions: a short version where offsets are stored as uShorts, and a long // version where offsets are stored as uLongs. The `head` table specifies which version to use // (under indexToLocFormat). function parseLocaTable(data, start, numGlyphs, shortVersion) { var p = new parse.Parser(data, start); var parseFn = shortVersion ? p.parseUShort : p.parseULong; // There is an extra entry after the last index element to compute the length of the last glyph. // That's why we use numGlyphs + 1. var glyphOffsets = []; for (var i = 0; i < numGlyphs + 1; i += 1) { var glyphOffset = parseFn.call(p); if (shortVersion) { // The short table version stores the actual offset divided by 2. glyphOffset *= 2; } glyphOffsets.push(glyphOffset); } return glyphOffsets; } exports.parse = parseLocaTable; },{"../parse":10}],25:[function(require,module,exports){ // The `ltag` table stores IETF BCP-47 language tags. It allows supporting // languages for which TrueType does not assign a numeric code. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html // http://www.w3.org/International/articles/language-tags/ // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry 'use strict'; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); function makeLtagTable(tags) { var result = new table.Table('ltag', [ {name: 'version', type: 'ULONG', value: 1}, {name: 'flags', type: 'ULONG', value: 0}, {name: 'numTags', type: 'ULONG', value: tags.length} ]); var stringPool = ''; var stringPoolOffset = 12 + tags.length * 4; for (var i = 0; i < tags.length; ++i) { var pos = stringPool.indexOf(tags[i]); if (pos < 0) { pos = stringPool.length; stringPool += tags[i]; } result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos}); result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length}); } result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); return result; } function parseLtagTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 1, 'Unsupported ltag table version.'); // The 'ltag' specification does not define any flags; skip the field. p.skip('uLong', 1); var numTags = p.parseULong(); var tags = []; for (var i = 0; i < numTags; i++) { var tag = ''; var offset = start + p.parseUShort(); var length = p.parseUShort(); for (var j = offset; j < offset + length; ++j) { tag += String.fromCharCode(data.getInt8(j)); } tags.push(tag); } return tags; } exports.make = makeLtagTable; exports.parse = parseLtagTable; },{"../check":2,"../parse":10,"../table":13}],26:[function(require,module,exports){ // The `maxp` table establishes the memory requirements for the font. // We need it just to get the number of glyphs in the font. // https://www.microsoft.com/typography/OTSPEC/maxp.htm 'use strict'; var parse = require('../parse'); var table = require('../table'); // Parse the maximum profile `maxp` table. function parseMaxpTable(data, start) { var maxp = {}; var p = new parse.Parser(data, start); maxp.version = p.parseVersion(); maxp.numGlyphs = p.parseUShort(); if (maxp.version === 1.0) { maxp.maxPoints = p.parseUShort(); maxp.maxContours = p.parseUShort(); maxp.maxCompositePoints = p.parseUShort(); maxp.maxCompositeContours = p.parseUShort(); maxp.maxZones = p.parseUShort(); maxp.maxTwilightPoints = p.parseUShort(); maxp.maxStorage = p.parseUShort(); maxp.maxFunctionDefs = p.parseUShort(); maxp.maxInstructionDefs = p.parseUShort(); maxp.maxStackElements = p.parseUShort(); maxp.maxSizeOfInstructions = p.parseUShort(); maxp.maxComponentElements = p.parseUShort(); maxp.maxComponentDepth = p.parseUShort(); } return maxp; } function makeMaxpTable(numGlyphs) { return new table.Table('maxp', [ {name: 'version', type: 'FIXED', value: 0x00005000}, {name: 'numGlyphs', type: 'USHORT', value: numGlyphs} ]); } exports.parse = parseMaxpTable; exports.make = makeMaxpTable; },{"../parse":10,"../table":13}],27:[function(require,module,exports){ // The `GPOS` table contains kerning pairs, among other things. // https://www.microsoft.com/typography/OTSPEC/gpos.htm 'use strict'; var types = require('../types'); var decode = types.decode; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); // Parse the metadata `meta` table. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html function parseMetaTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 1, 'Unsupported META table version.'); p.parseULong(); // flags - currently unused and set to 0 p.parseULong(); // tableOffset var numDataMaps = p.parseULong(); var tags = {}; for (var i = 0; i < numDataMaps; i++) { var tag = p.parseTag(); var dataOffset = p.parseULong(); var dataLength = p.parseULong(); var text = decode.UTF8(data, start + dataOffset, dataLength); tags[tag] = text; } return tags; } function makeMetaTable(tags) { var numTags = Object.keys(tags).length; var stringPool = ''; var stringPoolOffset = 16 + numTags * 12; var result = new table.Table('meta', [ {name: 'version', type: 'ULONG', value: 1}, {name: 'flags', type: 'ULONG', value: 0}, {name: 'offset', type: 'ULONG', value: stringPoolOffset}, {name: 'numTags', type: 'ULONG', value: numTags} ]); for (var tag in tags) { var pos = stringPool.length; stringPool += tags[tag]; result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag}); result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos}); result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length}); } result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); return result; } exports.parse = parseMetaTable; exports.make = makeMetaTable; },{"../check":2,"../parse":10,"../table":13,"../types":32}],28:[function(require,module,exports){ // The `name` naming table. // https://www.microsoft.com/typography/OTSPEC/name.htm 'use strict'; var types = require('../types'); var decode = types.decode; var encode = types.encode; var parse = require('../parse'); var table = require('../table'); // NameIDs for the name table. var nameTableNames = [ 'copyright', // 0 'fontFamily', // 1 'fontSubfamily', // 2 'uniqueID', // 3 'fullName', // 4 'version', // 5 'postScriptName', // 6 'trademark', // 7 'manufacturer', // 8 'designer', // 9 'description', // 10 'manufacturerURL', // 11 'designerURL', // 12 'license', // 13 'licenseURL', // 14 'reserved', // 15 'preferredFamily', // 16 'preferredSubfamily', // 17 'compatibleFullName', // 18 'sampleText', // 19 'postScriptFindFontName', // 20 'wwsFamily', // 21 'wwsSubfamily' // 22 ]; var macLanguages = { 0: 'en', 1: 'fr', 2: 'de', 3: 'it', 4: 'nl', 5: 'sv', 6: 'es', 7: 'da', 8: 'pt', 9: 'no', 10: 'he', 11: 'ja', 12: 'ar', 13: 'fi', 14: 'el', 15: 'is', 16: 'mt', 17: 'tr', 18: 'hr', 19: 'zh-Hant', 20: 'ur', 21: 'hi', 22: 'th', 23: 'ko', 24: 'lt', 25: 'pl', 26: 'hu', 27: 'es', 28: 'lv', 29: 'se', 30: 'fo', 31: 'fa', 32: 'ru', 33: 'zh', 34: 'nl-BE', 35: 'ga', 36: 'sq', 37: 'ro', 38: 'cz', 39: 'sk', 40: 'si', 41: 'yi', 42: 'sr', 43: 'mk', 44: 'bg', 45: 'uk', 46: 'be', 47: 'uz', 48: 'kk', 49: 'az-Cyrl', 50: 'az-Arab', 51: 'hy', 52: 'ka', 53: 'mo', 54: 'ky', 55: 'tg', 56: 'tk', 57: 'mn-CN', 58: 'mn', 59: 'ps', 60: 'ks', 61: 'ku', 62: 'sd', 63: 'bo', 64: 'ne', 65: 'sa', 66: 'mr', 67: 'bn', 68: 'as', 69: 'gu', 70: 'pa', 71: 'or', 72: 'ml', 73: 'kn', 74: 'ta', 75: 'te', 76: 'si', 77: 'my', 78: 'km', 79: 'lo', 80: 'vi', 81: 'id', 82: 'tl', 83: 'ms', 84: 'ms-Arab', 85: 'am', 86: 'ti', 87: 'om', 88: 'so', 89: 'sw', 90: 'rw', 91: 'rn', 92: 'ny', 93: 'mg', 94: 'eo', 128: 'cy', 129: 'eu', 130: 'ca', 131: 'la', 132: 'qu', 133: 'gn', 134: 'ay', 135: 'tt', 136: 'ug', 137: 'dz', 138: 'jv', 139: 'su', 140: 'gl', 141: 'af', 142: 'br', 143: 'iu', 144: 'gd', 145: 'gv', 146: 'ga', 147: 'to', 148: 'el-polyton', 149: 'kl', 150: 'az', 151: 'nn' }; // MacOS language ID → MacOS script ID // // Note that the script ID is not sufficient to determine what encoding // to use in TrueType files. For some languages, MacOS used a modification // of a mainstream script. For example, an Icelandic name would be stored // with smRoman in the TrueType naming table, but the actual encoding // is a special Icelandic version of the normal Macintosh Roman encoding. // As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal // Syllables but MacOS had run out of available script codes, so this was // done as a (pretty radical) "modification" of Ethiopic. // // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt var macLanguageToScript = { 0: 0, // langEnglish → smRoman 1: 0, // langFrench → smRoman 2: 0, // langGerman → smRoman 3: 0, // langItalian → smRoman 4: 0, // langDutch → smRoman 5: 0, // langSwedish → smRoman 6: 0, // langSpanish → smRoman 7: 0, // langDanish → smRoman 8: 0, // langPortuguese → smRoman 9: 0, // langNorwegian → smRoman 10: 5, // langHebrew → smHebrew 11: 1, // langJapanese → smJapanese 12: 4, // langArabic → smArabic 13: 0, // langFinnish → smRoman 14: 6, // langGreek → smGreek 15: 0, // langIcelandic → smRoman (modified) 16: 0, // langMaltese → smRoman 17: 0, // langTurkish → smRoman (modified) 18: 0, // langCroatian → smRoman (modified) 19: 2, // langTradChinese → smTradChinese 20: 4, // langUrdu → smArabic 21: 9, // langHindi → smDevanagari 22: 21, // langThai → smThai 23: 3, // langKorean → smKorean 24: 29, // langLithuanian → smCentralEuroRoman 25: 29, // langPolish → smCentralEuroRoman 26: 29, // langHungarian → smCentralEuroRoman 27: 29, // langEstonian → smCentralEuroRoman 28: 29, // langLatvian → smCentralEuroRoman 29: 0, // langSami → smRoman 30: 0, // langFaroese → smRoman (modified) 31: 4, // langFarsi → smArabic (modified) 32: 7, // langRussian → smCyrillic 33: 25, // langSimpChinese → smSimpChinese 34: 0, // langFlemish → smRoman 35: 0, // langIrishGaelic → smRoman (modified) 36: 0, // langAlbanian → smRoman 37: 0, // langRomanian → smRoman (modified) 38: 29, // langCzech → smCentralEuroRoman 39: 29, // langSlovak → smCentralEuroRoman 40: 0, // langSlovenian → smRoman (modified) 41: 5, // langYiddish → smHebrew 42: 7, // langSerbian → smCyrillic 43: 7, // langMacedonian → smCyrillic 44: 7, // langBulgarian → smCyrillic 45: 7, // langUkrainian → smCyrillic (modified) 46: 7, // langByelorussian → smCyrillic 47: 7, // langUzbek → smCyrillic 48: 7, // langKazakh → smCyrillic 49: 7, // langAzerbaijani → smCyrillic 50: 4, // langAzerbaijanAr → smArabic 51: 24, // langArmenian → smArmenian 52: 23, // langGeorgian → smGeorgian 53: 7, // langMoldavian → smCyrillic 54: 7, // langKirghiz → smCyrillic 55: 7, // langTajiki → smCyrillic 56: 7, // langTurkmen → smCyrillic 57: 27, // langMongolian → smMongolian 58: 7, // langMongolianCyr → smCyrillic 59: 4, // langPashto → smArabic 60: 4, // langKurdish → smArabic 61: 4, // langKashmiri → smArabic 62: 4, // langSindhi → smArabic 63: 26, // langTibetan → smTibetan 64: 9, // langNepali → smDevanagari 65: 9, // langSanskrit → smDevanagari 66: 9, // langMarathi → smDevanagari 67: 13, // langBengali → smBengali 68: 13, // langAssamese → smBengali 69: 11, // langGujarati → smGujarati 70: 10, // langPunjabi → smGurmukhi 71: 12, // langOriya → smOriya 72: 17, // langMalayalam → smMalayalam 73: 16, // langKannada → smKannada 74: 14, // langTamil → smTamil 75: 15, // langTelugu → smTelugu 76: 18, // langSinhalese → smSinhalese 77: 19, // langBurmese → smBurmese 78: 20, // langKhmer → smKhmer 79: 22, // langLao → smLao 80: 30, // langVietnamese → smVietnamese 81: 0, // langIndonesian → smRoman 82: 0, // langTagalog → smRoman 83: 0, // langMalayRoman → smRoman 84: 4, // langMalayArabic → smArabic 85: 28, // langAmharic → smEthiopic 86: 28, // langTigrinya → smEthiopic 87: 28, // langOromo → smEthiopic 88: 0, // langSomali → smRoman 89: 0, // langSwahili → smRoman 90: 0, // langKinyarwanda → smRoman 91: 0, // langRundi → smRoman 92: 0, // langNyanja → smRoman 93: 0, // langMalagasy → smRoman 94: 0, // langEsperanto → smRoman 128: 0, // langWelsh → smRoman (modified) 129: 0, // langBasque → smRoman 130: 0, // langCatalan → smRoman 131: 0, // langLatin → smRoman 132: 0, // langQuechua → smRoman 133: 0, // langGuarani → smRoman 134: 0, // langAymara → smRoman 135: 7, // langTatar → smCyrillic 136: 4, // langUighur → smArabic 137: 26, // langDzongkha → smTibetan 138: 0, // langJavaneseRom → smRoman 139: 0, // langSundaneseRom → smRoman 140: 0, // langGalician → smRoman 141: 0, // langAfrikaans → smRoman 142: 0, // langBreton → smRoman (modified) 143: 28, // langInuktitut → smEthiopic (modified) 144: 0, // langScottishGaelic → smRoman (modified) 145: 0, // langManxGaelic → smRoman (modified) 146: 0, // langIrishGaelicScript → smRoman (modified) 147: 0, // langTongan → smRoman 148: 6, // langGreekAncient → smRoman 149: 0, // langGreenlandic → smRoman 150: 0, // langAzerbaijanRoman → smRoman 151: 0 // langNynorsk → smRoman }; // While Microsoft indicates a region/country for all its language // IDs, we omit the region code if it's equal to the "most likely // region subtag" according to Unicode CLDR. For scripts, we omit // the subtag if it is equal to the Suppress-Script entry in the // IANA language subtag registry for IETF BCP 47. // // For example, Microsoft states that its language code 0x041A is // Croatian in Croatia. We transform this to the BCP 47 language code 'hr' // and not 'hr-HR' because Croatia is the default country for Croatian, // according to Unicode CLDR. As another example, Microsoft states // that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform // this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script // for the Croatian language, according to IANA. // // http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry var windowsLanguages = { 0x0436: 'af', 0x041C: 'sq', 0x0484: 'gsw', 0x045E: 'am', 0x1401: 'ar-DZ', 0x3C01: 'ar-BH', 0x0C01: 'ar', 0x0801: 'ar-IQ', 0x2C01: 'ar-JO', 0x3401: 'ar-KW', 0x3001: 'ar-LB', 0x1001: 'ar-LY', 0x1801: 'ary', 0x2001: 'ar-OM', 0x4001: 'ar-QA', 0x0401: 'ar-SA', 0x2801: 'ar-SY', 0x1C01: 'aeb', 0x3801: 'ar-AE', 0x2401: 'ar-YE', 0x042B: 'hy', 0x044D: 'as', 0x082C: 'az-Cyrl', 0x042C: 'az', 0x046D: 'ba', 0x042D: 'eu', 0x0423: 'be', 0x0845: 'bn', 0x0445: 'bn-IN', 0x201A: 'bs-Cyrl', 0x141A: 'bs', 0x047E: 'br', 0x0402: 'bg', 0x0403: 'ca', 0x0C04: 'zh-HK', 0x1404: 'zh-MO', 0x0804: 'zh', 0x1004: 'zh-SG', 0x0404: 'zh-TW', 0x0483: 'co', 0x041A: 'hr', 0x101A: 'hr-BA', 0x0405: 'cs', 0x0406: 'da', 0x048C: 'prs', 0x0465: 'dv', 0x0813: 'nl-BE', 0x0413: 'nl', 0x0C09: 'en-AU', 0x2809: 'en-BZ', 0x1009: 'en-CA', 0x2409: 'en-029', 0x4009: 'en-IN', 0x1809: 'en-IE', 0x2009: 'en-JM', 0x4409: 'en-MY', 0x1409: 'en-NZ', 0x3409: 'en-PH', 0x4809: 'en-SG', 0x1C09: 'en-ZA', 0x2C09: 'en-TT', 0x0809: 'en-GB', 0x0409: 'en', 0x3009: 'en-ZW', 0x0425: 'et', 0x0438: 'fo', 0x0464: 'fil', 0x040B: 'fi', 0x080C: 'fr-BE', 0x0C0C: 'fr-CA', 0x040C: 'fr', 0x140C: 'fr-LU', 0x180C: 'fr-MC', 0x100C: 'fr-CH', 0x0462: 'fy', 0x0456: 'gl', 0x0437: 'ka', 0x0C07: 'de-AT', 0x0407: 'de', 0x1407: 'de-LI', 0x1007: 'de-LU', 0x0807: 'de-CH', 0x0408: 'el', 0x046F: 'kl', 0x0447: 'gu', 0x0468: 'ha', 0x040D: 'he', 0x0439: 'hi', 0x040E: 'hu', 0x040F: 'is', 0x0470: 'ig', 0x0421: 'id', 0x045D: 'iu', 0x085D: 'iu-Latn', 0x083C: 'ga', 0x0434: 'xh', 0x0435: 'zu', 0x0410: 'it', 0x0810: 'it-CH', 0x0411: 'ja', 0x044B: 'kn', 0x043F: 'kk', 0x0453: 'km', 0x0486: 'quc', 0x0487: 'rw', 0x0441: 'sw', 0x0457: 'kok', 0x0412: 'ko', 0x0440: 'ky', 0x0454: 'lo', 0x0426: 'lv', 0x0427: 'lt', 0x082E: 'dsb', 0x046E: 'lb', 0x042F: 'mk', 0x083E: 'ms-BN', 0x043E: 'ms', 0x044C: 'ml', 0x043A: 'mt', 0x0481: 'mi', 0x047A: 'arn', 0x044E: 'mr', 0x047C: 'moh', 0x0450: 'mn', 0x0850: 'mn-CN', 0x0461: 'ne', 0x0414: 'nb', 0x0814: 'nn', 0x0482: 'oc', 0x0448: 'or', 0x0463: 'ps', 0x0415: 'pl', 0x0416: 'pt', 0x0816: 'pt-PT', 0x0446: 'pa', 0x046B: 'qu-BO', 0x086B: 'qu-EC', 0x0C6B: 'qu', 0x0418: 'ro', 0x0417: 'rm', 0x0419: 'ru', 0x243B: 'smn', 0x103B: 'smj-NO', 0x143B: 'smj', 0x0C3B: 'se-FI', 0x043B: 'se', 0x083B: 'se-SE', 0x203B: 'sms', 0x183B: 'sma-NO', 0x1C3B: 'sms', 0x044F: 'sa', 0x1C1A: 'sr-Cyrl-BA', 0x0C1A: 'sr', 0x181A: 'sr-Latn-BA', 0x081A: 'sr-Latn', 0x046C: 'nso', 0x0432: 'tn', 0x045B: 'si', 0x041B: 'sk', 0x0424: 'sl', 0x2C0A: 'es-AR', 0x400A: 'es-BO', 0x340A: 'es-CL', 0x240A: 'es-CO', 0x140A: 'es-CR', 0x1C0A: 'es-DO', 0x300A: 'es-EC', 0x440A: 'es-SV', 0x100A: 'es-GT', 0x480A: 'es-HN', 0x080A: 'es-MX', 0x4C0A: 'es-NI', 0x180A: 'es-PA', 0x3C0A: 'es-PY', 0x280A: 'es-PE', 0x500A: 'es-PR', // Microsoft has defined two different language codes for // “Spanish with modern sorting” and “Spanish with traditional // sorting”. This makes sense for collation APIs, and it would be // possible to express this in BCP 47 language tags via Unicode // extensions (eg., es-u-co-trad is Spanish with traditional // sorting). However, for storing names in fonts, the distinction // does not make sense, so we give “es” in both cases. 0x0C0A: 'es', 0x040A: 'es', 0x540A: 'es-US', 0x380A: 'es-UY', 0x200A: 'es-VE', 0x081D: 'sv-FI', 0x041D: 'sv', 0x045A: 'syr', 0x0428: 'tg', 0x085F: 'tzm', 0x0449: 'ta', 0x0444: 'tt', 0x044A: 'te', 0x041E: 'th', 0x0451: 'bo', 0x041F: 'tr', 0x0442: 'tk', 0x0480: 'ug', 0x0422: 'uk', 0x042E: 'hsb', 0x0420: 'ur', 0x0843: 'uz-Cyrl', 0x0443: 'uz', 0x042A: 'vi', 0x0452: 'cy', 0x0488: 'wo', 0x0485: 'sah', 0x0478: 'ii', 0x046A: 'yo' }; // Returns a IETF BCP 47 language code, for example 'zh-Hant' // for 'Chinese in the traditional script'. function getLanguageCode(platformID, languageID, ltag) { switch (platformID) { case 0: // Unicode if (languageID === 0xFFFF) { return 'und'; } else if (ltag) { return ltag[languageID]; } break; case 1: // Macintosh return macLanguages[languageID]; case 3: // Windows return windowsLanguages[languageID]; } return undefined; } var utf16 = 'utf-16'; // MacOS script ID → encoding. This table stores the default case, // which can be overridden by macLanguageEncodings. var macScriptEncodings = { 0: 'macintosh', // smRoman 1: 'x-mac-japanese', // smJapanese 2: 'x-mac-chinesetrad', // smTradChinese 3: 'x-mac-korean', // smKorean 6: 'x-mac-greek', // smGreek 7: 'x-mac-cyrillic', // smCyrillic 9: 'x-mac-devanagai', // smDevanagari 10: 'x-mac-gurmukhi', // smGurmukhi 11: 'x-mac-gujarati', // smGujarati 12: 'x-mac-oriya', // smOriya 13: 'x-mac-bengali', // smBengali 14: 'x-mac-tamil', // smTamil 15: 'x-mac-telugu', // smTelugu 16: 'x-mac-kannada', // smKannada 17: 'x-mac-malayalam', // smMalayalam 18: 'x-mac-sinhalese', // smSinhalese 19: 'x-mac-burmese', // smBurmese 20: 'x-mac-khmer', // smKhmer 21: 'x-mac-thai', // smThai 22: 'x-mac-lao', // smLao 23: 'x-mac-georgian', // smGeorgian 24: 'x-mac-armenian', // smArmenian 25: 'x-mac-chinesesimp', // smSimpChinese 26: 'x-mac-tibetan', // smTibetan 27: 'x-mac-mongolian', // smMongolian 28: 'x-mac-ethiopic', // smEthiopic 29: 'x-mac-ce', // smCentralEuroRoman 30: 'x-mac-vietnamese', // smVietnamese 31: 'x-mac-extarabic' // smExtArabic }; // MacOS language ID → encoding. This table stores the exceptional // cases, which override macScriptEncodings. For writing MacOS naming // tables, we need to emit a MacOS script ID. Therefore, we cannot // merge macScriptEncodings into macLanguageEncodings. // // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt var macLanguageEncodings = { 15: 'x-mac-icelandic', // langIcelandic 17: 'x-mac-turkish', // langTurkish 18: 'x-mac-croatian', // langCroatian 24: 'x-mac-ce', // langLithuanian 25: 'x-mac-ce', // langPolish 26: 'x-mac-ce', // langHungarian 27: 'x-mac-ce', // langEstonian 28: 'x-mac-ce', // langLatvian 30: 'x-mac-icelandic', // langFaroese 37: 'x-mac-romanian', // langRomanian 38: 'x-mac-ce', // langCzech 39: 'x-mac-ce', // langSlovak 40: 'x-mac-ce', // langSlovenian 143: 'x-mac-inuit', // langInuktitut 146: 'x-mac-gaelic' // langIrishGaelicScript }; function getEncoding(platformID, encodingID, languageID) { switch (platformID) { case 0: // Unicode return utf16; case 1: // Apple Macintosh return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; case 3: // Microsoft Windows if (encodingID === 1 || encodingID === 10) { return utf16; } break; } return undefined; } // Parse the naming `name` table. // FIXME: Format 1 additional fields are not supported yet. // ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904']. function parseNameTable(data, start, ltag) { var name = {}; var p = new parse.Parser(data, start); var format = p.parseUShort(); var count = p.parseUShort(); var stringOffset = p.offset + p.parseUShort(); for (var i = 0; i < count; i++) { var platformID = p.parseUShort(); var encodingID = p.parseUShort(); var languageID = p.parseUShort(); var nameID = p.parseUShort(); var property = nameTableNames[nameID] || nameID; var byteLength = p.parseUShort(); var offset = p.parseUShort(); var language = getLanguageCode(platformID, languageID, ltag); var encoding = getEncoding(platformID, encodingID, languageID); if (encoding !== undefined && language !== undefined) { var text; if (encoding === utf16) { text = decode.UTF16(data, stringOffset + offset, byteLength); } else { text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding); } if (text) { var translations = name[property]; if (translations === undefined) { translations = name[property] = {}; } translations[language] = text; } } } var langTagCount = 0; if (format === 1) { // FIXME: Also handle Microsoft's 'name' table 1. langTagCount = p.parseUShort(); } return name; } // {23: 'foo'} → {'foo': 23} // ['bar', 'baz'] → {'bar': 0, 'baz': 1} function reverseDict(dict) { var result = {}; for (var key in dict) { result[dict[key]] = parseInt(key); } return result; } function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) { return new table.Record('NameRecord', [ {name: 'platformID', type: 'USHORT', value: platformID}, {name: 'encodingID', type: 'USHORT', value: encodingID}, {name: 'languageID', type: 'USHORT', value: languageID}, {name: 'nameID', type: 'USHORT', value: nameID}, {name: 'length', type: 'USHORT', value: length}, {name: 'offset', type: 'USHORT', value: offset} ]); } // Finds the position of needle in haystack, or -1 if not there. // Like String.indexOf(), but for arrays. function findSubArray(needle, haystack) { var needleLength = needle.length; var limit = haystack.length - needleLength + 1; loop: for (var pos = 0; pos < limit; pos++) { for (; pos < limit; pos++) { for (var k = 0; k < needleLength; k++) { if (haystack[pos + k] !== needle[k]) { continue loop; } } return pos; } } return -1; } function addStringToPool(s, pool) { var offset = findSubArray(s, pool); if (offset < 0) { offset = pool.length; for (var i = 0, len = s.length; i < len; ++i) { pool.push(s[i]); } } return offset; } function makeNameTable(names, ltag) { var nameID; var nameIDs = []; var namesWithNumericKeys = {}; var nameTableIds = reverseDict(nameTableNames); for (var key in names) { var id = nameTableIds[key]; if (id === undefined) { id = key; } nameID = parseInt(id); if (isNaN(nameID)) { throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.'); } namesWithNumericKeys[nameID] = names[key]; nameIDs.push(nameID); } var macLanguageIds = reverseDict(macLanguages); var windowsLanguageIds = reverseDict(windowsLanguages); var nameRecords = []; var stringPool = []; for (var i = 0; i < nameIDs.length; i++) { nameID = nameIDs[i]; var translations = namesWithNumericKeys[nameID]; for (var lang in translations) { var text = translations[lang]; // For MacOS, we try to emit the name in the form that was introduced // in the initial version of the TrueType spec (in the late 1980s). // However, this can fail for various reasons: the requested BCP 47 // language code might not have an old-style Mac equivalent; // we might not have a codec for the needed character encoding; // or the name might contain characters that cannot be expressed // in the old-style Macintosh encoding. In case of failure, we emit // the name in a more modern fashion (Unicode encoding with BCP 47 // language tags) that is recognized by MacOS 10.5, released in 2009. // If fonts were only read by operating systems, we could simply // emit all names in the modern form; this would be much easier. // However, there are many applications and libraries that read // 'name' tables directly, and these will usually only recognize // the ancient form (silently skipping the unrecognized names). var macPlatform = 1; // Macintosh var macLanguage = macLanguageIds[lang]; var macScript = macLanguageToScript[macLanguage]; var macEncoding = getEncoding(macPlatform, macScript, macLanguage); var macName = encode.MACSTRING(text, macEncoding); if (macName === undefined) { macPlatform = 0; // Unicode macLanguage = ltag.indexOf(lang); if (macLanguage < 0) { macLanguage = ltag.length; ltag.push(lang); } macScript = 4; // Unicode 2.0 and later macName = encode.UTF16(text); } var macNameOffset = addStringToPool(macName, stringPool); nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, nameID, macName.length, macNameOffset)); var winLanguage = windowsLanguageIds[lang]; if (winLanguage !== undefined) { var winName = encode.UTF16(text); var winNameOffset = addStringToPool(winName, stringPool); nameRecords.push(makeNameRecord(3, 1, winLanguage, nameID, winName.length, winNameOffset)); } } } nameRecords.sort(function(a, b) { return ((a.platformID - b.platformID) || (a.encodingID - b.encodingID) || (a.languageID - b.languageID) || (a.nameID - b.nameID)); }); var t = new table.Table('name', [ {name: 'format', type: 'USHORT', value: 0}, {name: 'count', type: 'USHORT', value: nameRecords.length}, {name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12} ]); for (var r = 0; r < nameRecords.length; r++) { t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]}); } t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool}); return t; } exports.parse = parseNameTable; exports.make = makeNameTable; },{"../parse":10,"../table":13,"../types":32}],29:[function(require,module,exports){ // The `OS/2` table contains metrics required in OpenType fonts. // https://www.microsoft.com/typography/OTSPEC/os2.htm 'use strict'; var parse = require('../parse'); var table = require('../table'); var unicodeRanges = [ {begin: 0x0000, end: 0x007F}, // Basic Latin {begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement {begin: 0x0100, end: 0x017F}, // Latin Extended-A {begin: 0x0180, end: 0x024F}, // Latin Extended-B {begin: 0x0250, end: 0x02AF}, // IPA Extensions {begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters {begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks {begin: 0x0370, end: 0x03FF}, // Greek and Coptic {begin: 0x2C80, end: 0x2CFF}, // Coptic {begin: 0x0400, end: 0x04FF}, // Cyrillic {begin: 0x0530, end: 0x058F}, // Armenian {begin: 0x0590, end: 0x05FF}, // Hebrew {begin: 0xA500, end: 0xA63F}, // Vai {begin: 0x0600, end: 0x06FF}, // Arabic {begin: 0x07C0, end: 0x07FF}, // NKo {begin: 0x0900, end: 0x097F}, // Devanagari {begin: 0x0980, end: 0x09FF}, // Bengali {begin: 0x0A00, end: 0x0A7F}, // Gurmukhi {begin: 0x0A80, end: 0x0AFF}, // Gujarati {begin: 0x0B00, end: 0x0B7F}, // Oriya {begin: 0x0B80, end: 0x0BFF}, // Tamil {begin: 0x0C00, end: 0x0C7F}, // Telugu {begin: 0x0C80, end: 0x0CFF}, // Kannada {begin: 0x0D00, end: 0x0D7F}, // Malayalam {begin: 0x0E00, end: 0x0E7F}, // Thai {begin: 0x0E80, end: 0x0EFF}, // Lao {begin: 0x10A0, end: 0x10FF}, // Georgian {begin: 0x1B00, end: 0x1B7F}, // Balinese {begin: 0x1100, end: 0x11FF}, // Hangul Jamo {begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional {begin: 0x1F00, end: 0x1FFF}, // Greek Extended {begin: 0x2000, end: 0x206F}, // General Punctuation {begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts {begin: 0x20A0, end: 0x20CF}, // Currency Symbol {begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols {begin: 0x2100, end: 0x214F}, // Letterlike Symbols {begin: 0x2150, end: 0x218F}, // Number Forms {begin: 0x2190, end: 0x21FF}, // Arrows {begin: 0x2200, end: 0x22FF}, // Mathematical Operators {begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical {begin: 0x2400, end: 0x243F}, // Control Pictures {begin: 0x2440, end: 0x245F}, // Optical Character Recognition {begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics {begin: 0x2500, end: 0x257F}, // Box Drawing {begin: 0x2580, end: 0x259F}, // Block Elements {begin: 0x25A0, end: 0x25FF}, // Geometric Shapes {begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols {begin: 0x2700, end: 0x27BF}, // Dingbats {begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation {begin: 0x3040, end: 0x309F}, // Hiragana {begin: 0x30A0, end: 0x30FF}, // Katakana {begin: 0x3100, end: 0x312F}, // Bopomofo {begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo {begin: 0xA840, end: 0xA87F}, // Phags-pa {begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months {begin: 0x3300, end: 0x33FF}, // CJK Compatibility {begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables {begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 * {begin: 0x10900, end: 0x1091F}, // Phoenicia {begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs {begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0) {begin: 0x31C0, end: 0x31EF}, // CJK Strokes {begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms {begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A {begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks {begin: 0xFE10, end: 0xFE1F}, // Vertical Forms {begin: 0xFE50, end: 0xFE6F}, // Small Form Variants {begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B {begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms {begin: 0xFFF0, end: 0xFFFF}, // Specials {begin: 0x0F00, end: 0x0FFF}, // Tibetan {begin: 0x0700, end: 0x074F}, // Syriac {begin: 0x0780, end: 0x07BF}, // Thaana {begin: 0x0D80, end: 0x0DFF}, // Sinhala {begin: 0x1000, end: 0x109F}, // Myanmar {begin: 0x1200, end: 0x137F}, // Ethiopic {begin: 0x13A0, end: 0x13FF}, // Cherokee {begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics {begin: 0x1680, end: 0x169F}, // Ogham {begin: 0x16A0, end: 0x16FF}, // Runic {begin: 0x1780, end: 0x17FF}, // Khmer {begin: 0x1800, end: 0x18AF}, // Mongolian {begin: 0x2800, end: 0x28FF}, // Braille Patterns {begin: 0xA000, end: 0xA48F}, // Yi Syllables {begin: 0x1700, end: 0x171F}, // Tagalog {begin: 0x10300, end: 0x1032F}, // Old Italic {begin: 0x10330, end: 0x1034F}, // Gothic {begin: 0x10400, end: 0x1044F}, // Deseret {begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols {begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols {begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15) {begin: 0xFE00, end: 0xFE0F}, // Variation Selectors {begin: 0xE0000, end: 0xE007F}, // Tags {begin: 0x1900, end: 0x194F}, // Limbu {begin: 0x1950, end: 0x197F}, // Tai Le {begin: 0x1980, end: 0x19DF}, // New Tai Lue {begin: 0x1A00, end: 0x1A1F}, // Buginese {begin: 0x2C00, end: 0x2C5F}, // Glagolitic {begin: 0x2D30, end: 0x2D7F}, // Tifinagh {begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols {begin: 0xA800, end: 0xA82F}, // Syloti Nagri {begin: 0x10000, end: 0x1007F}, // Linear B Syllabary {begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers {begin: 0x10380, end: 0x1039F}, // Ugaritic {begin: 0x103A0, end: 0x103DF}, // Old Persian {begin: 0x10450, end: 0x1047F}, // Shavian {begin: 0x10480, end: 0x104AF}, // Osmanya {begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary {begin: 0x10A00, end: 0x10A5F}, // Kharoshthi {begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols {begin: 0x12000, end: 0x123FF}, // Cuneiform {begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals {begin: 0x1B80, end: 0x1BBF}, // Sundanese {begin: 0x1C00, end: 0x1C4F}, // Lepcha {begin: 0x1C50, end: 0x1C7F}, // Ol Chiki {begin: 0xA880, end: 0xA8DF}, // Saurashtra {begin: 0xA900, end: 0xA92F}, // Kayah Li {begin: 0xA930, end: 0xA95F}, // Rejang {begin: 0xAA00, end: 0xAA5F}, // Cham {begin: 0x10190, end: 0x101CF}, // Ancient Symbols {begin: 0x101D0, end: 0x101FF}, // Phaistos Disc {begin: 0x102A0, end: 0x102DF}, // Carian {begin: 0x1F030, end: 0x1F09F} // Domino Tiles ]; function getUnicodeRange(unicode) { for (var i = 0; i < unicodeRanges.length; i += 1) { var range = unicodeRanges[i]; if (unicode >= range.begin && unicode < range.end) { return i; } } return -1; } // Parse the OS/2 and Windows metrics `OS/2` table function parseOS2Table(data, start) { var os2 = {}; var p = new parse.Parser(data, start); os2.version = p.parseUShort(); os2.xAvgCharWidth = p.parseShort(); os2.usWeightClass = p.parseUShort(); os2.usWidthClass = p.parseUShort(); os2.fsType = p.parseUShort(); os2.ySubscriptXSize = p.parseShort(); os2.ySubscriptYSize = p.parseShort(); os2.ySubscriptXOffset = p.parseShort(); os2.ySubscriptYOffset = p.parseShort(); os2.ySuperscriptXSize = p.parseShort(); os2.ySuperscriptYSize = p.parseShort(); os2.ySuperscriptXOffset = p.parseShort(); os2.ySuperscriptYOffset = p.parseShort(); os2.yStrikeoutSize = p.parseShort(); os2.yStrikeoutPosition = p.parseShort(); os2.sFamilyClass = p.parseShort(); os2.panose = []; for (var i = 0; i < 10; i++) { os2.panose[i] = p.parseByte(); } os2.ulUnicodeRange1 = p.parseULong(); os2.ulUnicodeRange2 = p.parseULong(); os2.ulUnicodeRange3 = p.parseULong(); os2.ulUnicodeRange4 = p.parseULong(); os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); os2.fsSelection = p.parseUShort(); os2.usFirstCharIndex = p.parseUShort(); os2.usLastCharIndex = p.parseUShort(); os2.sTypoAscender = p.parseShort(); os2.sTypoDescender = p.parseShort(); os2.sTypoLineGap = p.parseShort(); os2.usWinAscent = p.parseUShort(); os2.usWinDescent = p.parseUShort(); if (os2.version >= 1) { os2.ulCodePageRange1 = p.parseULong(); os2.ulCodePageRange2 = p.parseULong(); } if (os2.version >= 2) { os2.sxHeight = p.parseShort(); os2.sCapHeight = p.parseShort(); os2.usDefaultChar = p.parseUShort(); os2.usBreakChar = p.parseUShort(); os2.usMaxContent = p.parseUShort(); } return os2; } function makeOS2Table(options) { return new table.Table('OS/2', [ {name: 'version', type: 'USHORT', value: 0x0003}, {name: 'xAvgCharWidth', type: 'SHORT', value: 0}, {name: 'usWeightClass', type: 'USHORT', value: 0}, {name: 'usWidthClass', type: 'USHORT', value: 0}, {name: 'fsType', type: 'USHORT', value: 0}, {name: 'ySubscriptXSize', type: 'SHORT', value: 650}, {name: 'ySubscriptYSize', type: 'SHORT', value: 699}, {name: 'ySubscriptXOffset', type: 'SHORT', value: 0}, {name: 'ySubscriptYOffset', type: 'SHORT', value: 140}, {name: 'ySuperscriptXSize', type: 'SHORT', value: 650}, {name: 'ySuperscriptYSize', type: 'SHORT', value: 699}, {name: 'ySuperscriptXOffset', type: 'SHORT', value: 0}, {name: 'ySuperscriptYOffset', type: 'SHORT', value: 479}, {name: 'yStrikeoutSize', type: 'SHORT', value: 49}, {name: 'yStrikeoutPosition', type: 'SHORT', value: 258}, {name: 'sFamilyClass', type: 'SHORT', value: 0}, {name: 'bFamilyType', type: 'BYTE', value: 0}, {name: 'bSerifStyle', type: 'BYTE', value: 0}, {name: 'bWeight', type: 'BYTE', value: 0}, {name: 'bProportion', type: 'BYTE', value: 0}, {name: 'bContrast', type: 'BYTE', value: 0}, {name: 'bStrokeVariation', type: 'BYTE', value: 0}, {name: 'bArmStyle', type: 'BYTE', value: 0}, {name: 'bLetterform', type: 'BYTE', value: 0}, {name: 'bMidline', type: 'BYTE', value: 0}, {name: 'bXHeight', type: 'BYTE', value: 0}, {name: 'ulUnicodeRange1', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange2', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange3', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange4', type: 'ULONG', value: 0}, {name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'}, {name: 'fsSelection', type: 'USHORT', value: 0}, {name: 'usFirstCharIndex', type: 'USHORT', value: 0}, {name: 'usLastCharIndex', type: 'USHORT', value: 0}, {name: 'sTypoAscender', type: 'SHORT', value: 0}, {name: 'sTypoDescender', type: 'SHORT', value: 0}, {name: 'sTypoLineGap', type: 'SHORT', value: 0}, {name: 'usWinAscent', type: 'USHORT', value: 0}, {name: 'usWinDescent', type: 'USHORT', value: 0}, {name: 'ulCodePageRange1', type: 'ULONG', value: 0}, {name: 'ulCodePageRange2', type: 'ULONG', value: 0}, {name: 'sxHeight', type: 'SHORT', value: 0}, {name: 'sCapHeight', type: 'SHORT', value: 0}, {name: 'usDefaultChar', type: 'USHORT', value: 0}, {name: 'usBreakChar', type: 'USHORT', value: 0}, {name: 'usMaxContext', type: 'USHORT', value: 0} ], options); } exports.unicodeRanges = unicodeRanges; exports.getUnicodeRange = getUnicodeRange; exports.parse = parseOS2Table; exports.make = makeOS2Table; },{"../parse":10,"../table":13}],30:[function(require,module,exports){ // The `post` table stores additional PostScript information, such as glyph names. // https://www.microsoft.com/typography/OTSPEC/post.htm 'use strict'; var encoding = require('../encoding'); var parse = require('../parse'); var table = require('../table'); // Parse the PostScript `post` table function parsePostTable(data, start) { var post = {}; var p = new parse.Parser(data, start); var i; post.version = p.parseVersion(); post.italicAngle = p.parseFixed(); post.underlinePosition = p.parseShort(); post.underlineThickness = p.parseShort(); post.isFixedPitch = p.parseULong(); post.minMemType42 = p.parseULong(); post.maxMemType42 = p.parseULong(); post.minMemType1 = p.parseULong(); post.maxMemType1 = p.parseULong(); switch (post.version) { case 1: post.names = encoding.standardNames.slice(); break; case 2: post.numberOfGlyphs = p.parseUShort(); post.glyphNameIndex = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { post.glyphNameIndex[i] = p.parseUShort(); } post.names = []; for (i = 0; i < post.numberOfGlyphs; i++) { if (post.glyphNameIndex[i] >= encoding.standardNames.length) { var nameLength = p.parseChar(); post.names.push(p.parseString(nameLength)); } } break; case 2.5: post.numberOfGlyphs = p.parseUShort(); post.offset = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { post.offset[i] = p.parseChar(); } break; } return post; } function makePostTable() { return new table.Table('post', [ {name: 'version', type: 'FIXED', value: 0x00030000}, {name: 'italicAngle', type: 'FIXED', value: 0}, {name: 'underlinePosition', type: 'FWORD', value: 0}, {name: 'underlineThickness', type: 'FWORD', value: 0}, {name: 'isFixedPitch', type: 'ULONG', value: 0}, {name: 'minMemType42', type: 'ULONG', value: 0}, {name: 'maxMemType42', type: 'ULONG', value: 0}, {name: 'minMemType1', type: 'ULONG', value: 0}, {name: 'maxMemType1', type: 'ULONG', value: 0} ]); } exports.parse = parsePostTable; exports.make = makePostTable; },{"../encoding":4,"../parse":10,"../table":13}],31:[function(require,module,exports){ // The `sfnt` wrapper provides organization for the tables in the font. // It is the top-level data structure in a font. // https://www.microsoft.com/typography/OTSPEC/otff.htm // Recommendations for creating OpenType Fonts: // http://www.microsoft.com/typography/otspec140/recom.htm 'use strict'; var check = require('../check'); var table = require('../table'); var cmap = require('./cmap'); var cff = require('./cff'); var head = require('./head'); var hhea = require('./hhea'); var hmtx = require('./hmtx'); var ltag = require('./ltag'); var maxp = require('./maxp'); var _name = require('./name'); var os2 = require('./os2'); var post = require('./post'); var gsub = require('./gsub'); var meta = require('./meta'); function log2(v) { return Math.log(v) / Math.log(2) | 0; } function computeCheckSum(bytes) { while (bytes.length % 4 !== 0) { bytes.push(0); } var sum = 0; for (var i = 0; i < bytes.length; i += 4) { sum += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + (bytes[i + 3]); } sum %= Math.pow(2, 32); return sum; } function makeTableRecord(tag, checkSum, offset, length) { return new table.Record('Table Record', [ {name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''}, {name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0}, {name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0}, {name: 'length', type: 'ULONG', value: length !== undefined ? length : 0} ]); } function makeSfntTable(tables) { var sfnt = new table.Table('sfnt', [ {name: 'version', type: 'TAG', value: 'OTTO'}, {name: 'numTables', type: 'USHORT', value: 0}, {name: 'searchRange', type: 'USHORT', value: 0}, {name: 'entrySelector', type: 'USHORT', value: 0}, {name: 'rangeShift', type: 'USHORT', value: 0} ]); sfnt.tables = tables; sfnt.numTables = tables.length; var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); sfnt.searchRange = 16 * highestPowerOf2; sfnt.entrySelector = log2(highestPowerOf2); sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; var recordFields = []; var tableFields = []; var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables); while (offset % 4 !== 0) { offset += 1; tableFields.push({name: 'padding', type: 'BYTE', value: 0}); } for (var i = 0; i < tables.length; i += 1) { var t = tables[i]; check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.'); var tableLength = t.sizeOf(); var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength); recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord}); tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t}); offset += tableLength; check.argument(!isNaN(offset), 'Something went wrong calculating the offset.'); while (offset % 4 !== 0) { offset += 1; tableFields.push({name: 'padding', type: 'BYTE', value: 0}); } } // Table records need to be sorted alphabetically. recordFields.sort(function(r1, r2) { if (r1.value.tag > r2.value.tag) { return 1; } else { return -1; } }); sfnt.fields = sfnt.fields.concat(recordFields); sfnt.fields = sfnt.fields.concat(tableFields); return sfnt; } // Get the metrics for a character. If the string has more than one character // this function returns metrics for the first available character. // You can provide optional fallback metrics if no characters are available. function metricsForChar(font, chars, notFoundMetrics) { for (var i = 0; i < chars.length; i += 1) { var glyphIndex = font.charToGlyphIndex(chars[i]); if (glyphIndex > 0) { var glyph = font.glyphs.get(glyphIndex); return glyph.getMetrics(); } } return notFoundMetrics; } function average(vs) { var sum = 0; for (var i = 0; i < vs.length; i += 1) { sum += vs[i]; } return sum / vs.length; } // Convert the font object to a SFNT data structure. // This structure contains all the necessary tables and metadata to create a binary OTF file. function fontToSfntTable(font) { var xMins = []; var yMins = []; var xMaxs = []; var yMaxs = []; var advanceWidths = []; var leftSideBearings = []; var rightSideBearings = []; var firstCharIndex; var lastCharIndex = 0; var ulUnicodeRange1 = 0; var ulUnicodeRange2 = 0; var ulUnicodeRange3 = 0; var ulUnicodeRange4 = 0; for (var i = 0; i < font.glyphs.length; i += 1) { var glyph = font.glyphs.get(i); var unicode = glyph.unicode | 0; if (isNaN(glyph.advanceWidth)) { throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'); } if (firstCharIndex > unicode || firstCharIndex === undefined) { // ignore .notdef char if (unicode > 0) { firstCharIndex = unicode; } } if (lastCharIndex < unicode) { lastCharIndex = unicode; } var position = os2.getUnicodeRange(unicode); if (position < 32) { ulUnicodeRange1 |= 1 << position; } else if (position < 64) { ulUnicodeRange2 |= 1 << position - 32; } else if (position < 96) { ulUnicodeRange3 |= 1 << position - 64; } else if (position < 123) { ulUnicodeRange4 |= 1 << position - 96; } else { throw new Error('Unicode ranges bits > 123 are reserved for internal usage'); } // Skip non-important characters. if (glyph.name === '.notdef') continue; var metrics = glyph.getMetrics(); xMins.push(metrics.xMin); yMins.push(metrics.yMin); xMaxs.push(metrics.xMax); yMaxs.push(metrics.yMax); leftSideBearings.push(metrics.leftSideBearing); rightSideBearings.push(metrics.rightSideBearing); advanceWidths.push(glyph.advanceWidth); } var globals = { xMin: Math.min.apply(null, xMins), yMin: Math.min.apply(null, yMins), xMax: Math.max.apply(null, xMaxs), yMax: Math.max.apply(null, yMaxs), advanceWidthMax: Math.max.apply(null, advanceWidths), advanceWidthAvg: average(advanceWidths), minLeftSideBearing: Math.min.apply(null, leftSideBearings), maxLeftSideBearing: Math.max.apply(null, leftSideBearings), minRightSideBearing: Math.min.apply(null, rightSideBearings) }; globals.ascender = font.ascender; globals.descender = font.descender; var headTable = head.make({ flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0) unitsPerEm: font.unitsPerEm, xMin: globals.xMin, yMin: globals.yMin, xMax: globals.xMax, yMax: globals.yMax, lowestRecPPEM: 3, createdTimestamp: font.createdTimestamp }); var hheaTable = hhea.make({ ascender: globals.ascender, descender: globals.descender, advanceWidthMax: globals.advanceWidthMax, minLeftSideBearing: globals.minLeftSideBearing, minRightSideBearing: globals.minRightSideBearing, xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), numberOfHMetrics: font.glyphs.length }); var maxpTable = maxp.make(font.glyphs.length); var os2Table = os2.make({ xAvgCharWidth: Math.round(globals.advanceWidthAvg), usWeightClass: font.tables.os2.usWeightClass, usWidthClass: font.tables.os2.usWidthClass, usFirstCharIndex: firstCharIndex, usLastCharIndex: lastCharIndex, ulUnicodeRange1: ulUnicodeRange1, ulUnicodeRange2: ulUnicodeRange2, ulUnicodeRange3: ulUnicodeRange3, ulUnicodeRange4: ulUnicodeRange4, fsSelection: font.tables.os2.fsSelection, // REGULAR // See http://typophile.com/node/13081 for more info on vertical metrics. // We get metrics for typical characters (such as "x" for xHeight). // We provide some fallback characters if characters are unavailable: their // ordering was chosen experimentally. sTypoAscender: globals.ascender, sTypoDescender: globals.descender, sTypoLineGap: 0, usWinAscent: globals.yMax, usWinDescent: Math.abs(globals.yMin), ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax, sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax, usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available. usBreakChar: font.hasChar(' ') ? 32 : 0 // Use space as the break character, if available. }); var hmtxTable = hmtx.make(font.glyphs); var cmapTable = cmap.make(font.glyphs); var englishFamilyName = font.getEnglishName('fontFamily'); var englishStyleName = font.getEnglishName('fontSubfamily'); var englishFullName = englishFamilyName + ' ' + englishStyleName; var postScriptName = font.getEnglishName('postScriptName'); if (!postScriptName) { postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName; } var names = {}; for (var n in font.names) { names[n] = font.names[n]; } if (!names.uniqueID) { names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName}; } if (!names.postScriptName) { names.postScriptName = {en: postScriptName}; } if (!names.preferredFamily) { names.preferredFamily = font.names.fontFamily; } if (!names.preferredSubfamily) { names.preferredSubfamily = font.names.fontSubfamily; } var languageTags = []; var nameTable = _name.make(names, languageTags); var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined); var postTable = post.make(); var cffTable = cff.make(font.glyphs, { version: font.getEnglishName('version'), fullName: englishFullName, familyName: englishFamilyName, weightName: englishStyleName, postScriptName: postScriptName, unitsPerEm: font.unitsPerEm, fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] }); var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined; // The order does not matter because makeSfntTable() will sort them. var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; if (ltagTable) { tables.push(ltagTable); } // Optional tables if (font.tables.gsub) { tables.push(gsub.make(font.tables.gsub)); } if (metaTable) { tables.push(metaTable); } var sfntTable = makeSfntTable(tables); // Compute the font's checkSum and store it in head.checkSumAdjustment. var bytes = sfntTable.encode(); var checkSum = computeCheckSum(bytes); var tableFields = sfntTable.fields; var checkSumAdjusted = false; for (i = 0; i < tableFields.length; i += 1) { if (tableFields[i].name === 'head table') { tableFields[i].value.checkSumAdjustment = 0xB1B0AFBA - checkSum; checkSumAdjusted = true; break; } } if (!checkSumAdjusted) { throw new Error('Could not find head table with checkSum to adjust.'); } return sfntTable; } exports.computeCheckSum = computeCheckSum; exports.make = makeSfntTable; exports.fontToTable = fontToSfntTable; },{"../check":2,"../table":13,"./cff":14,"./cmap":15,"./gsub":19,"./head":20,"./hhea":21,"./hmtx":22,"./ltag":25,"./maxp":26,"./meta":27,"./name":28,"./os2":29,"./post":30}],32:[function(require,module,exports){ // Data types used in the OpenType font file. // All OpenType fonts use Motorola-style byte ordering (Big Endian) /* global WeakMap */ 'use strict'; var check = require('./check'); var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15 var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31 /** * @exports opentype.decode * @class */ var decode = {}; /** * @exports opentype.encode * @class */ var encode = {}; /** * @exports opentype.sizeOf * @class */ var sizeOf = {}; // Return a function that always returns the same value. function constant(v) { return function() { return v; }; } // OpenType data types ////////////////////////////////////////////////////// /** * Convert an 8-bit unsigned integer to a list of 1 byte. * @param {number} * @returns {Array} */ encode.BYTE = function(v) { check.argument(v >= 0 && v <= 255, 'Byte value should be between 0 and 255.'); return [v]; }; /** * @constant * @type {number} */ sizeOf.BYTE = constant(1); /** * Convert a 8-bit signed integer to a list of 1 byte. * @param {string} * @returns {Array} */ encode.CHAR = function(v) { return [v.charCodeAt(0)]; }; /** * @constant * @type {number} */ sizeOf.CHAR = constant(1); /** * Convert an ASCII string to a list of bytes. * @param {string} * @returns {Array} */ encode.CHARARRAY = function(v) { var b = []; for (var i = 0; i < v.length; i += 1) { b[i] = v.charCodeAt(i); } return b; }; /** * @param {Array} * @returns {number} */ sizeOf.CHARARRAY = function(v) { return v.length; }; /** * Convert a 16-bit unsigned integer to a list of 2 bytes. * @param {number} * @returns {Array} */ encode.USHORT = function(v) { return [(v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.USHORT = constant(2); /** * Convert a 16-bit signed integer to a list of 2 bytes. * @param {number} * @returns {Array} */ encode.SHORT = function(v) { // Two's complement if (v >= LIMIT16) { v = -(2 * LIMIT16 - v); } return [(v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.SHORT = constant(2); /** * Convert a 24-bit unsigned integer to a list of 3 bytes. * @param {number} * @returns {Array} */ encode.UINT24 = function(v) { return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.UINT24 = constant(3); /** * Convert a 32-bit unsigned integer to a list of 4 bytes. * @param {number} * @returns {Array} */ encode.ULONG = function(v) { return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.ULONG = constant(4); /** * Convert a 32-bit unsigned integer to a list of 4 bytes. * @param {number} * @returns {Array} */ encode.LONG = function(v) { // Two's complement if (v >= LIMIT32) { v = -(2 * LIMIT32 - v); } return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.LONG = constant(4); encode.FIXED = encode.ULONG; sizeOf.FIXED = sizeOf.ULONG; encode.FWORD = encode.SHORT; sizeOf.FWORD = sizeOf.SHORT; encode.UFWORD = encode.USHORT; sizeOf.UFWORD = sizeOf.USHORT; /** * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp. * @param {number} * @returns {Array} */ encode.LONGDATETIME = function(v) { return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.LONGDATETIME = constant(8); /** * Convert a 4-char tag to a list of 4 bytes. * @param {string} * @returns {Array} */ encode.TAG = function(v) { check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.'); return [v.charCodeAt(0), v.charCodeAt(1), v.charCodeAt(2), v.charCodeAt(3)]; }; /** * @constant * @type {number} */ sizeOf.TAG = constant(4); // CFF data types /////////////////////////////////////////////////////////// encode.Card8 = encode.BYTE; sizeOf.Card8 = sizeOf.BYTE; encode.Card16 = encode.USHORT; sizeOf.Card16 = sizeOf.USHORT; encode.OffSize = encode.BYTE; sizeOf.OffSize = sizeOf.BYTE; encode.SID = encode.USHORT; sizeOf.SID = sizeOf.USHORT; // Convert a numeric operand or charstring number to a variable-size list of bytes. /** * Convert a numeric operand or charstring number to a variable-size list of bytes. * @param {number} * @returns {Array} */ encode.NUMBER = function(v) { if (v >= -107 && v <= 107) { return [v + 139]; } else if (v >= 108 && v <= 1131) { v = v - 108; return [(v >> 8) + 247, v & 0xFF]; } else if (v >= -1131 && v <= -108) { v = -v - 108; return [(v >> 8) + 251, v & 0xFF]; } else if (v >= -32768 && v <= 32767) { return encode.NUMBER16(v); } else { return encode.NUMBER32(v); } }; /** * @param {number} * @returns {number} */ sizeOf.NUMBER = function(v) { return encode.NUMBER(v).length; }; /** * Convert a signed number between -32768 and +32767 to a three-byte value. * This ensures we always use three bytes, but is not the most compact format. * @param {number} * @returns {Array} */ encode.NUMBER16 = function(v) { return [28, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.NUMBER16 = constant(3); /** * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value. * This is useful if you want to be sure you always use four bytes, * at the expense of wasting a few bytes for smaller numbers. * @param {number} * @returns {Array} */ encode.NUMBER32 = function(v) { return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.NUMBER32 = constant(5); /** * @param {number} * @returns {Array} */ encode.REAL = function(v) { var value = v.toString(); // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7) // This code converts it back to a number without the epsilon. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); if (m) { var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length)); value = (Math.round(v * epsilon) / epsilon).toString(); } var nibbles = ''; var i; var ii; for (i = 0, ii = value.length; i < ii; i += 1) { var c = value[i]; if (c === 'e') { nibbles += value[++i] === '-' ? 'c' : 'b'; } else if (c === '.') { nibbles += 'a'; } else if (c === '-') { nibbles += 'e'; } else { nibbles += c; } } nibbles += (nibbles.length & 1) ? 'f' : 'ff'; var out = [30]; for (i = 0, ii = nibbles.length; i < ii; i += 2) { out.push(parseInt(nibbles.substr(i, 2), 16)); } return out; }; /** * @param {number} * @returns {number} */ sizeOf.REAL = function(v) { return encode.REAL(v).length; }; encode.NAME = encode.CHARARRAY; sizeOf.NAME = sizeOf.CHARARRAY; encode.STRING = encode.CHARARRAY; sizeOf.STRING = sizeOf.CHARARRAY; /** * @param {DataView} data * @param {number} offset * @param {number} numBytes * @returns {string} */ decode.UTF8 = function(data, offset, numBytes) { var codePoints = []; var numChars = numBytes; for (var j = 0; j < numChars; j++, offset += 1) { codePoints[j] = data.getUint8(offset); } return String.fromCharCode.apply(null, codePoints); }; /** * @param {DataView} data * @param {number} offset * @param {number} numBytes * @returns {string} */ decode.UTF16 = function(data, offset, numBytes) { var codePoints = []; var numChars = numBytes / 2; for (var j = 0; j < numChars; j++, offset += 2) { codePoints[j] = data.getUint16(offset); } return String.fromCharCode.apply(null, codePoints); }; /** * Convert a JavaScript string to UTF16-BE. * @param {string} * @returns {Array} */ encode.UTF16 = function(v) { var b = []; for (var i = 0; i < v.length; i += 1) { var codepoint = v.charCodeAt(i); b[b.length] = (codepoint >> 8) & 0xFF; b[b.length] = codepoint & 0xFF; } return b; }; /** * @param {string} * @returns {number} */ sizeOf.UTF16 = function(v) { return v.length * 2; }; // Data for converting old eight-bit Macintosh encodings to Unicode. // This representation is optimized for decoding; encoding is slower // and needs more memory. The assumption is that all opentype.js users // want to open fonts, but saving a font will be comperatively rare // so it can be more expensive. Keyed by IANA character set name. // // Python script for generating these strings: // // s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)]) // print(s.encode('utf-8')) /** * @private */ var eightBitMacEncodings = { 'x-mac-croatian': // Python: 'mac_croatian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' + '¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', 'x-mac-cyrillic': // Python: 'mac_cyrillic' 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' + 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю', 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' + 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', 'x-mac-greek': // Python: 'mac_greek' 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' + 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD', 'x-mac-icelandic': // Python: 'mac_iceland' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' + 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', 'x-mac-ce': // Python: 'mac_latin2' 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' + 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', macintosh: // Python: 'mac_roman' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-romanian': // Python: 'mac_romanian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-turkish': // Python: 'mac_turkish' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' }; /** * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript * string, or 'undefined' if the encoding is unsupported. For example, we do * not support Chinese, Japanese or Korean because these would need large * mapping tables. * @param {DataView} dataView * @param {number} offset * @param {number} dataLength * @param {string} encoding * @returns {string} */ decode.MACSTRING = function(dataView, offset, dataLength, encoding) { var table = eightBitMacEncodings[encoding]; if (table === undefined) { return undefined; } var result = ''; for (var i = 0; i < dataLength; i++) { var c = dataView.getUint8(offset + i); // In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if (c <= 0x7F) { result += String.fromCharCode(c); } else { result += table[c & 0x7F]; } } return result; }; // Helper function for encode.MACSTRING. Returns a dictionary for mapping // Unicode character codes to their 8-bit MacOS equivalent. This table // is not exactly a super cheap data structure, but we do not care because // encoding Macintosh strings is only rarely needed in typical applications. var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap(); var macEncodingCacheKeys; var getMacEncodingTable = function(encoding) { // Since we use encoding as a cache key for WeakMap, it has to be // a String object and not a literal. And at least on NodeJS 2.10.1, // WeakMap requires that the same String instance is passed for cache hits. if (!macEncodingCacheKeys) { macEncodingCacheKeys = {}; for (var e in eightBitMacEncodings) { /*jshint -W053 */ // Suppress "Do not use String as a constructor." macEncodingCacheKeys[e] = new String(e); } } var cacheKey = macEncodingCacheKeys[encoding]; if (cacheKey === undefined) { return undefined; } // We can't do "if (cache.has(key)) {return cache.get(key)}" here: // since garbage collection may run at any time, it could also kick in // between the calls to cache.has() and cache.get(). In that case, // we would return 'undefined' even though we do support the encoding. if (macEncodingTableCache) { var cachedTable = macEncodingTableCache.get(cacheKey); if (cachedTable !== undefined) { return cachedTable; } } var decodingTable = eightBitMacEncodings[encoding]; if (decodingTable === undefined) { return undefined; } var encodingTable = {}; for (var i = 0; i < decodingTable.length; i++) { encodingTable[decodingTable.charCodeAt(i)] = i + 0x80; } if (macEncodingTableCache) { macEncodingTableCache.set(cacheKey, encodingTable); } return encodingTable; }; /** * Encodes an old-style Macintosh string. Returns a byte array upon success. * If the requested encoding is unsupported, or if the input string contains * a character that cannot be expressed in the encoding, the function returns * 'undefined'. * @param {string} str * @param {string} encoding * @returns {Array} */ encode.MACSTRING = function(str, encoding) { var table = getMacEncodingTable(encoding); if (table === undefined) { return undefined; } var result = []; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); // In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if (c >= 0x80) { c = table[c]; if (c === undefined) { // str contains a Unicode character that cannot be encoded // in the requested encoding. return undefined; } } result[i] = c; // result.push(c); } return result; }; /** * @param {string} str * @param {string} encoding * @returns {number} */ sizeOf.MACSTRING = function(str, encoding) { var b = encode.MACSTRING(str, encoding); if (b !== undefined) { return b.length; } else { return 0; } }; // Convert a list of values to a CFF INDEX structure. // The values should be objects containing name / type / value. /** * @param {Array} l * @returns {Array} */ encode.INDEX = function(l) { var i; //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data, // i, v; // Because we have to know which data type to use to encode the offsets, // we have to go through the values twice: once to encode the data and // calculate the offets, then again to encode the offsets using the fitting data type. var offset = 1; // First offset is always 1. var offsets = [offset]; var data = []; for (i = 0; i < l.length; i += 1) { var v = encode.OBJECT(l[i]); Array.prototype.push.apply(data, v); offset += v.length; offsets.push(offset); } if (data.length === 0) { return [0, 0]; } var encodedOffsets = []; var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0; var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; for (i = 0; i < offsets.length; i += 1) { var encodedOffset = offsetEncoder(offsets[i]); Array.prototype.push.apply(encodedOffsets, encodedOffset); } return Array.prototype.concat(encode.Card16(l.length), encode.OffSize(offSize), encodedOffsets, data); }; /** * @param {Array} * @returns {number} */ sizeOf.INDEX = function(v) { return encode.INDEX(v).length; }; /** * Convert an object to a CFF DICT structure. * The keys should be numeric. * The values should be objects containing name / type / value. * @param {Object} m * @returns {Array} */ encode.DICT = function(m) { var d = []; var keys = Object.keys(m); var length = keys.length; for (var i = 0; i < length; i += 1) { // Object.keys() return string keys, but our keys are always numeric. var k = parseInt(keys[i], 0); var v = m[k]; // Value comes before the key. d = d.concat(encode.OPERAND(v.value, v.type)); d = d.concat(encode.OPERATOR(k)); } return d; }; /** * @param {Object} * @returns {number} */ sizeOf.DICT = function(m) { return encode.DICT(m).length; }; /** * @param {number} * @returns {Array} */ encode.OPERATOR = function(v) { if (v < 1200) { return [v]; } else { return [12, v - 1200]; } }; /** * @param {Array} v * @param {string} * @returns {Array} */ encode.OPERAND = function(v, type) { var d = []; if (Array.isArray(type)) { for (var i = 0; i < type.length; i += 1) { check.argument(v.length === type.length, 'Not enough arguments given for type' + type); d = d.concat(encode.OPERAND(v[i], type[i])); } } else { if (type === 'SID') { d = d.concat(encode.NUMBER(v)); } else if (type === 'offset') { // We make it easy for ourselves and always encode offsets as // 4 bytes. This makes offset calculation for the top dict easier. d = d.concat(encode.NUMBER32(v)); } else if (type === 'number') { d = d.concat(encode.NUMBER(v)); } else if (type === 'real') { d = d.concat(encode.REAL(v)); } else { throw new Error('Unknown operand type ' + type); // FIXME Add support for booleans } } return d; }; encode.OP = encode.BYTE; sizeOf.OP = sizeOf.BYTE; // memoize charstring encoding using WeakMap if available var wmm = typeof WeakMap === 'function' && new WeakMap(); /** * Convert a list of CharString operations to bytes. * @param {Array} * @returns {Array} */ encode.CHARSTRING = function(ops) { // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))". if (wmm) { var cachedValue = wmm.get(ops); if (cachedValue !== undefined) { return cachedValue; } } var d = []; var length = ops.length; for (var i = 0; i < length; i += 1) { var op = ops[i]; d = d.concat(encode[op.type](op.value)); } if (wmm) { wmm.set(ops, d); } return d; }; /** * @param {Array} * @returns {number} */ sizeOf.CHARSTRING = function(ops) { return encode.CHARSTRING(ops).length; }; // Utility functions //////////////////////////////////////////////////////// /** * Convert an object containing name / type / value to bytes. * @param {Object} * @returns {Array} */ encode.OBJECT = function(v) { var encodingFunction = encode[v.type]; check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type); return encodingFunction(v.value); }; /** * @param {Object} * @returns {number} */ sizeOf.OBJECT = function(v) { var sizeOfFunction = sizeOf[v.type]; check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type); return sizeOfFunction(v.value); }; /** * Convert a table object to bytes. * A table contains a list of fields containing the metadata (name, type and default value). * The table itself has the field values set as attributes. * @param {opentype.Table} * @returns {Array} */ encode.TABLE = function(table) { var d = []; var length = table.fields.length; var subtables = []; var subtableOffsets = []; var i; for (i = 0; i < length; i += 1) { var field = table.fields[i]; var encodingFunction = encode[field.type]; check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')'); var value = table[field.name]; if (value === undefined) { value = field.value; } var bytes = encodingFunction(value); if (field.type === 'TABLE') { subtableOffsets.push(d.length); d = d.concat([0, 0]); subtables.push(bytes); } else { d = d.concat(bytes); } } for (i = 0; i < subtables.length; i += 1) { var o = subtableOffsets[i]; var offset = d.length; check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.'); d[o] = offset >> 8; d[o + 1] = offset & 0xff; d = d.concat(subtables[i]); } return d; }; /** * @param {opentype.Table} * @returns {number} */ sizeOf.TABLE = function(table) { var numBytes = 0; var length = table.fields.length; for (var i = 0; i < length; i += 1) { var field = table.fields[i]; var sizeOfFunction = sizeOf[field.type]; check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')'); var value = table[field.name]; if (value === undefined) { value = field.value; } numBytes += sizeOfFunction(value); // Subtables take 2 more bytes for offsets. if (field.type === 'TABLE') { numBytes += 2; } } return numBytes; }; encode.RECORD = encode.TABLE; sizeOf.RECORD = sizeOf.TABLE; // Merge in a list of bytes. encode.LITERAL = function(v) { return v; }; sizeOf.LITERAL = function(v) { return v.length; }; exports.decode = decode; exports.encode = encode; exports.sizeOf = sizeOf; },{"./check":2}],33:[function(require,module,exports){ 'use strict'; exports.isBrowser = function() { return typeof window !== 'undefined'; }; exports.isNode = function() { return typeof window === 'undefined'; }; exports.nodeBufferToArrayBuffer = function(buffer) { var ab = new ArrayBuffer(buffer.length); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { view[i] = buffer[i]; } return ab; }; exports.arrayBufferToNodeBuffer = function(ab) { var buffer = new Buffer(ab.byteLength); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } return buffer; }; exports.checkArgument = function(expression, message) { if (!expression) { throw message; } }; },{}]},{},[9])(9) });
joeyparrish/cdnjs
ajax/libs/opentype.js/0.6.7/opentype.js
JavaScript
mit
295,992
import { onBlur } from "../display/focus" import { setGuttersForLineNumbers, updateGutters } from "../display/gutters" import { alignHorizontally } from "../display/line_numbers" import { loadMode, resetModeState } from "../display/mode_state" import { initScrollbars, updateScrollbars } from "../display/scrollbars" import { updateSelection } from "../display/selection" import { regChange } from "../display/view_tracking" import { getKeyMap } from "../input/keymap" import { defaultSpecialCharPlaceholder } from "../line/line_data" import { Pos } from "../line/pos" import { findMaxLine } from "../line/spans" import { clearCaches, compensateForHScroll, estimateLineHeights } from "../measurement/position_measurement" import { replaceRange } from "../model/changes" import { mobile, windows } from "../util/browser" import { addClass, rmClass } from "../util/dom" import { off, on } from "../util/event" import { themeChanged } from "./utils" export let Init = {toString: function(){return "CodeMirror.Init"}} export let defaults = {} export let optionHandlers = {} export function defineOptions(CodeMirror) { let optionHandlers = CodeMirror.optionHandlers function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt if (handle) optionHandlers[name] = notOnInit ? (cm, val, old) => {if (old != Init) handle(cm, val, old)} : handle } CodeMirror.defineOption = option // Passed to option handlers when there is no old value. CodeMirror.Init = Init // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", (cm, val) => cm.setValue(val), true) option("mode", null, (cm, val) => { cm.doc.modeOption = val loadMode(cm) }, true) option("indentUnit", 2, loadMode, true) option("indentWithTabs", false) option("smartIndent", true) option("tabSize", 4, cm => { resetModeState(cm) clearCaches(cm) regChange(cm) }, true) option("lineSeparator", null, (cm, val) => { cm.doc.lineSep = val if (!val) return let newBreaks = [], lineNo = cm.doc.first cm.doc.iter(line => { for (let pos = 0;;) { let found = line.text.indexOf(val, pos) if (found == -1) break pos = found + val.length newBreaks.push(Pos(lineNo, found)) } lineNo++ }) for (let i = newBreaks.length - 1; i >= 0; i--) replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }) option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, (cm, val, old) => { cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g") if (old != Init) cm.refresh() }) option("specialCharPlaceholder", defaultSpecialCharPlaceholder, cm => cm.refresh(), true) option("electricChars", true) option("inputStyle", mobile ? "contenteditable" : "textarea", () => { throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME }, true) option("spellcheck", false, (cm, val) => cm.getInputField().spellcheck = val, true) option("rtlMoveVisually", !windows) option("wholeLineUpdateBefore", true) option("theme", "default", cm => { themeChanged(cm) guttersChanged(cm) }, true) option("keyMap", "default", (cm, val, old) => { let next = getKeyMap(val) let prev = old != Init && getKeyMap(old) if (prev && prev.detach) prev.detach(cm, next) if (next.attach) next.attach(cm, prev || null) }) option("extraKeys", null) option("configureMouse", null) option("lineWrapping", false, wrappingChanged, true) option("gutters", [], cm => { setGuttersForLineNumbers(cm.options) guttersChanged(cm) }, true) option("fixedGutter", true, (cm, val) => { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0" cm.refresh() }, true) option("coverGutterNextToScrollbar", false, cm => updateScrollbars(cm), true) option("scrollbarStyle", "native", cm => { initScrollbars(cm) updateScrollbars(cm) cm.display.scrollbars.setScrollTop(cm.doc.scrollTop) cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft) }, true) option("lineNumbers", false, cm => { setGuttersForLineNumbers(cm.options) guttersChanged(cm) }, true) option("firstLineNumber", 1, guttersChanged, true) option("lineNumberFormatter", integer => integer, guttersChanged, true) option("showCursorWhenSelecting", false, updateSelection, true) option("resetSelectionOnContextMenu", true) option("lineWiseCopyCut", true) option("pasteLinesPerSelection", true) option("readOnly", false, (cm, val) => { if (val == "nocursor") { onBlur(cm) cm.display.input.blur() } cm.display.input.readOnlyChanged(val) }) option("disableInput", false, (cm, val) => {if (!val) cm.display.input.reset()}, true) option("dragDrop", true, dragDropChanged) option("allowDropFileTypes", null) option("cursorBlinkRate", 530) option("cursorScrollMargin", 0) option("cursorHeight", 1, updateSelection, true) option("singleCursorHeightPerLine", true, updateSelection, true) option("workTime", 100) option("workDelay", 100) option("flattenSpans", true, resetModeState, true) option("addModeClass", false, resetModeState, true) option("pollInterval", 100) option("undoDepth", 200, (cm, val) => cm.doc.history.undoDepth = val) option("historyEventDelay", 1250) option("viewportMargin", 10, cm => cm.refresh(), true) option("maxHighlightLength", 10000, resetModeState, true) option("moveInputWithCursor", true, (cm, val) => { if (!val) cm.display.input.resetPosition() }) option("tabindex", null, (cm, val) => cm.display.input.getField().tabIndex = val || "") option("autofocus", null) option("direction", "ltr", (cm, val) => cm.doc.setDirection(val), true) } function guttersChanged(cm) { updateGutters(cm) regChange(cm) alignHorizontally(cm) } function dragDropChanged(cm, value, old) { let wasOn = old && old != Init if (!value != !wasOn) { let funcs = cm.display.dragFunctions let toggle = value ? on : off toggle(cm.display.scroller, "dragstart", funcs.start) toggle(cm.display.scroller, "dragenter", funcs.enter) toggle(cm.display.scroller, "dragover", funcs.over) toggle(cm.display.scroller, "dragleave", funcs.leave) toggle(cm.display.scroller, "drop", funcs.drop) } } function wrappingChanged(cm) { if (cm.options.lineWrapping) { addClass(cm.display.wrapper, "CodeMirror-wrap") cm.display.sizer.style.minWidth = "" cm.display.sizerWidth = null } else { rmClass(cm.display.wrapper, "CodeMirror-wrap") findMaxLine(cm) } estimateLineHeights(cm) regChange(cm) clearCaches(cm) setTimeout(() => updateScrollbars(cm), 100) }
AfrikaBurn/Main
web/libraries/codemirror/src/edit/options.js
JavaScript
gpl-2.0
6,874
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Serbian (Cyrillic) language. */ /**#@+ @type String @example */ /** * Contains the dictionary of language entries. * @namespace */ CKEDITOR.lang[ 'sr' ] = { // ARIA description. editor: 'Rich Text Editor', // MISSING editorPanel: 'Rich Text Editor panel', // MISSING // Common messages and labels. common: { // Screenreader titles. Please note that screenreaders are not always capable // of reading non-English words. So be careful while translating it. editorHelp: 'Press ALT 0 for help', // MISSING browseServer: 'Претражи сервер', url: 'УРЛ', protocol: 'Протокол', upload: 'Пошаљи', uploadSubmit: 'Пошаљи на сервер', image: 'Слика', flash: 'Флеш елемент', form: 'Форма', checkbox: 'Поље за потврду', radio: 'Радио-дугме', textField: 'Текстуално поље', textarea: 'Зона текста', hiddenField: 'Скривено поље', button: 'Дугме', select: 'Изборно поље', imageButton: 'Дугме са сликом', notSet: '<није постављено>', id: 'Ид', name: 'Назив', langDir: 'Смер језика', langDirLtr: 'С лева на десно (LTR)', langDirRtl: 'С десна на лево (RTL)', langCode: 'Kôд језика', longDescr: 'Пун опис УРЛ', cssClass: 'Stylesheet класе', advisoryTitle: 'Advisory наслов', cssStyle: 'Стил', ok: 'OK', cancel: 'Oткажи', close: 'Затвори', preview: 'Изглед странице', resize: 'Resize', // MISSING generalTab: 'Опште', advancedTab: 'Напредни тагови', validateNumberFailed: 'Ова вредност није цигра.', confirmNewPage: 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING confirmCancel: 'You have changed some options. Are you sure you want to close the dialog window?', // MISSING options: 'Опције', target: 'Meтa', targetNew: 'New Window (_blank)', // MISSING targetTop: 'Topmost Window (_top)', // MISSING targetSelf: 'Same Window (_self)', // MISSING targetParent: 'Parent Window (_parent)', // MISSING langDirLTR: 'С лева на десно (LTR)', langDirRTL: 'С десна на лево (RTL)', styles: 'Стил', cssClasses: 'Stylesheet класе', width: 'Ширина', height: 'Висина', align: 'Равнање', alignLeft: 'Лево', alignRight: 'Десно', alignCenter: 'Средина', alignJustify: 'Обострано равнање', alignTop: 'Врх', alignMiddle: 'Средина', alignBottom: 'Доле', alignNone: 'None', // MISSING invalidValue : 'Invalid value.', // MISSING invalidHeight: 'Height must be a number.', // MISSING invalidWidth: 'Width must be a number.', // MISSING invalidCssLength: 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING invalidHtmlLength: 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING invalidInlineStyle: 'Value specified for the inline style must consist of one or more tuples with the format of "name : value", separated by semi-colons.', // MISSING cssLengthTooltip: 'Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING // Put the voice-only part of the label in the span. unavailable: '%1<span class="cke_accessibility">, unavailable</span>' // MISSING } };
noskill/Firesoft
src/main/webapp/ckeditor/lang/sr.js
JavaScript
gpl-3.0
3,935
/* * DarkTooltip v0.4.0 * Simple customizable tooltip with confirm option and 3d effects * (c)2014 Rubén Torres - rubentdlh@gmail.com * Released under the MIT license */ (function($) { function DarkTooltip(element, options){ this.bearer = element; this.options = options; this.hideEvent; this.mouseOverMode=(this.options.trigger == "hover" || this.options.trigger == "mouseover" || this.options.trigger == "onmouseover"); } DarkTooltip.prototype = { show: function(){ var dt = this; if(this.options.modal){ this.modalLayer.css('display', 'block'); } //Close all other tooltips this.tooltip.css('display', 'block'); //Set event to prevent tooltip from closig when mouse is over the tooltip if(dt.mouseOverMode){ this.tooltip.mouseover( function(){ clearTimeout(dt.hideEvent); }); this.tooltip.mouseout( function(){ clearTimeout(dt.hideEvent); dt.hide(); }); } }, hide: function(){ var dt=this; this.hideEvent = setTimeout( function(){ dt.tooltip.hide(); }, 100); if(dt.options.modal){ dt.modalLayer.hide(); } this.options.onClose(); }, toggle: function(){ if(this.tooltip.is(":visible")){ this.hide(); }else{ this.show(); } }, addAnimation: function(){ switch(this.options.animation){ case 'none': break; case 'fadeIn': this.tooltip.addClass('animated'); this.tooltip.addClass('fadeIn'); break; case 'flipIn': this.tooltip.addClass('animated'); this.tooltip.addClass('flipIn'); break; } }, setContent: function(){ $(this.bearer).css('cursor', 'pointer'); //Get tooltip content if(this.options.content){ this.content = this.options.content; }else if(this.bearer.attr("data-tooltip")){ this.content = this.bearer.attr("data-tooltip"); }else{ // console.log("No content for tooltip: " + this.bearer.selector); return; } if(this.content.charAt(0) == '#'){ if (this.options.delete_content){ var content = $(this.content).html(); $(this.content).html(''); this.content = content; delete content; } else{ $(this.content).hide(); this.content = $(this.content).html(); } this.contentType='html'; }else{ this.contentType='text'; } tooltipId = ""; if(this.bearer.attr("id") != ""){ tooltipId = "id='darktooltip-" + this.bearer.attr("id") + "'"; } //Create modal layer this.modalLayer = $("<ins class='darktooltip-modal-layer'></ins>"); //Create tooltip container this.tooltip = $("<ins " + tooltipId + " class = 'dark-tooltip " + this.options.theme + " " + this.options.size + " " + this.options.gravity + "'><div>" + this.content + "</div><div class = 'tip'></div></ins>"); this.tip = this.tooltip.find(".tip"); $("body").append(this.modalLayer); $("body").append(this.tooltip); //Adjust size for html tooltip if(this.contentType == 'html'){ this.tooltip.css('max-width','none'); } this.tooltip.css('opacity', this.options.opacity); this.addAnimation(); if(this.options.confirm){ this.addConfirm(); } }, setPositions: function(){ var leftPos = this.bearer.offset().left; var topPos = this.bearer.offset().top; switch(this.options.gravity){ case 'south': leftPos += this.bearer.outerWidth()/2 - this.tooltip.outerWidth()/2; topPos += -this.tooltip.outerHeight() - this.tip.outerHeight()/2; break; case 'west': leftPos += this.bearer.outerWidth() + this.tip.outerWidth()/2; topPos += this.bearer.outerHeight()/2 - (this.tooltip.outerHeight()/2); break; case 'north': leftPos += this.bearer.outerWidth()/2 - (this.tooltip.outerWidth()/2); topPos += this.bearer.outerHeight() + this.tip.outerHeight()/2; break; case 'east': leftPos += -this.tooltip.outerWidth() - this.tip.outerWidth()/2; topPos += this.bearer.outerHeight()/2 - this.tooltip.outerHeight()/2; break; } if(this.options.autoLeft){ this.tooltip.css('left', leftPos); } if(this.options.autoTop){ this.tooltip.css('top', topPos); } }, setEvents: function(){ var dt = this; var delay = dt.options.hoverDelay; var setTimeoutConst; if(dt.mouseOverMode){ this.bearer.mouseenter( function(){ //Timeout for hover mouse delay setTimeoutConst = setTimeout( function(){ dt.setPositions(); dt.show(); }, delay); }).mouseleave( function(){ clearTimeout(setTimeoutConst ); dt.hide(); }); }else if(this.options.trigger == "click" || this.options.trigger == "onclik"){ this.tooltip.click( function(e){ e.stopPropagation(); }); this.bearer.click( function(e){ e.preventDefault(); dt.setPositions(); dt.toggle(); e.stopPropagation(); }); $('html').click(function(){ dt.hide(); }) } }, activate: function(){ this.setContent(); if(this.content){ this.setEvents(); } }, addConfirm: function(){ this.tooltip.append("<ul class = 'confirm'><li class = 'darktooltip-yes'>" + this.options.yes +"</li><li class = 'darktooltip-no'>"+ this.options.no +"</li></ul>"); this.setConfirmEvents(); }, setConfirmEvents: function(){ var dt = this; this.tooltip.find('li.darktooltip-yes').click( function(e){ dt.onYes(); e.stopPropagation(); }); this.tooltip.find('li.darktooltip-no').click( function(e){ dt.onNo(); e.stopPropagation(); }); }, finalMessage: function(){ if(this.options.finalMessage){ var dt = this; dt.tooltip.find('div:first').html(this.options.finalMessage); dt.tooltip.find('ul').remove(); dt.setPositions(); setTimeout( function(){ dt.hide(); dt.setContent(); }, dt.options.finalMessageDuration); }else{ this.hide(); } }, onYes: function(){ this.options.onYes(this.bearer); this.finalMessage(); }, onNo: function(){ this.options.onNo(this.bearer); this.hide(); } } $.fn.darkTooltip = function(options) { return this.each(function(){ options = $.extend({}, $.fn.darkTooltip.defaults, options); var tooltip = new DarkTooltip($(this), options); tooltip.activate(); }); } $.fn.darkTooltip.defaults = { animation: 'none', confirm: false, content:'', finalMessage: '', finalMessageDuration: 1000, gravity: 'south', hoverDelay: 0, modal: false, no: 'No', onNo: function(){}, onYes: function(){}, opacity: 0.9, size: 'medium', theme: 'dark', trigger: 'hover', yes: 'Yes', autoTop: true, autoLeft: true, onClose: function(){} }; })(jQuery);
gtison/kf
src/main/resources/static/js/jquery.darktooltip.js
JavaScript
apache-2.0
6,675
module.exports = function(client, test) { test.ok(typeof client == 'object'); this.testPageAction = function() { return this; }; };
miguelangel6/nightwatchbamboo
tests/extra/pageobjects/SimplePageFn.js
JavaScript
mit
142
// Copyright JS Foundation and other contributors, http://js.foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var a = 20; var b = a >> "2"; assert(b == 5)
slaff/jerryscript
tests/jerry-test-suite/11/11.07/11.07.02/11.07.02-003.js
JavaScript
apache-2.0
674
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesRvHookup = (props) => ( <SvgIcon {...props}> <path d="M20 17v-6c0-1.1-.9-2-2-2H7V7l-3 3 3 3v-2h4v3H4v3c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h8v-2h-2zm-9 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h4v3zM17 2v2H9v2h8v2l3-3z"/> </SvgIcon> ); PlacesRvHookup = pure(PlacesRvHookup); PlacesRvHookup.displayName = 'PlacesRvHookup'; PlacesRvHookup.muiName = 'SvgIcon'; export default PlacesRvHookup;
ichiohta/material-ui
src/svg-icons/places/rv-hookup.js
JavaScript
mit
534
/** * @abstract * @class Ext.chart.series.Cartesian * @extends Ext.chart.series.Series * * Common base class for series implementations which plot values using x/y coordinates. * * @constructor */ Ext.define('Ext.chart.series.Cartesian', { extend: 'Ext.chart.series.Series', config: { /** * The field used to access the x axis value from the items from the data * source. * * @cfg {String} xField */ xField: null, /** * The field used to access the y-axis value from the items from the data * source. * * @cfg {String} yField */ yField: null, /** * @cfg {Ext.chart.axis.Axis} xAxis The chart axis bound to the series on the x-axis. */ xAxis: null, /** * @cfg {Ext.chart.axis.Axis} yAxis The chart axis bound to the series on the y-axis. */ yAxis: null }, directions: ['X', 'Y'], fieldCategoryX: ['X'], fieldCategoryY: ['Y'], updateXAxis: function (axis) { axis.processData(this); }, updateYAxis: function (axis) { axis.processData(this); }, coordinateX: function () { return this.coordinate('X', 0, 2); }, coordinateY: function () { return this.coordinate('Y', 1, 2); }, getItemForPoint: function (x, y) { if (this.getSprites()) { var me = this, sprite = me.getSprites()[0], store = me.getStore(), item; if(me.getHidden()) { return null; } if (sprite) { var index = sprite.getIndexNearPoint(x, y); if (index !== -1) { item = { series: this, category: this.getItemInstancing() ? 'items' : 'markers', index: index, record: store.getData().items[index], field: this.getYField(), sprite: sprite }; return item; } } } }, createSprite: function () { var sprite = this.callSuper(), xAxis = this.getXAxis(); sprite.setFlipXY(this.getChart().getFlipXY()); if (sprite.setAggregator && xAxis && xAxis.getAggregator) { if (xAxis.getAggregator) { sprite.setAggregator({strategy: xAxis.getAggregator()}); } else { sprite.setAggregator({}); } } return sprite; }, getSprites: function () { var me = this, chart = this.getChart(), animation = chart && chart.getAnimate(), itemInstancing = me.getItemInstancing(), sprites = me.sprites, sprite; if (!chart) { return []; } if (!sprites.length) { sprite = me.createSprite(); } else { sprite = sprites[0]; } if (animation) { me.getLabel().getTemplate().fx.setConfig(animation); if (itemInstancing) { sprite.itemsMarker.getTemplate().fx.setConfig(animation); } sprite.fx.setConfig(animation); } return sprites; }, provideLegendInfo: function (target) { var style = this.getStyle(); target.push({ name: this.getTitle() || this.getYField() || this.getId(), mark: style.fillStyle || style.strokeStyle || 'black', disabled: false, series: this.getId(), index: 0 }); }, getXRange: function () { return [this.dataRange[0], this.dataRange[2]]; }, getYRange: function () { return [this.dataRange[1], this.dataRange[3]]; } }) ;
DawidMyslak/native-vs-html5_android-performance
www/TakePhoto/touch/src/chart/series/Cartesian.js
JavaScript
mit
3,929
'use strict'; var grunt = require('grunt'); exports.concat_sourcemap = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(2); var actual = grunt.file.read('tmp/default_options.js'); var expected = grunt.file.read('test/expected/default_options.js'); test.equal(actual, expected, 'should join files with default separator.'); var actualMap = grunt.file.read('tmp/default_options.js.map'); var expectedMap = grunt.file.read('test/expected/default_options.js.map'); test.equal(actualMap, expectedMap, 'should write a source map file.'); test.done(); }, options_with_sourceRoot: function(test) { test.expect(2); var actual = grunt.file.read('tmp/options_with_sourceRoot.js'); var expected = grunt.file.read('test/expected/options_with_sourceRoot.js'); test.equal(actual, expected, 'should not affect a output joined file.'); var actualMap = grunt.file.read('tmp/options_with_sourceRoot.js.map'); var expectedMap = grunt.file.read('test/expected/options_with_sourceRoot.js.map'); test.equal(actualMap, expectedMap, 'should write a source map file including `sourceRoot` property.'); test.done(); }, options_with_sourcesContent: function(test) { test.expect(2); var actual = grunt.file.read('tmp/options_with_sourcesContent.js'); var expected = grunt.file.read('test/expected/options_with_sourcesContent.js'); test.equal(actual, expected, 'should not affect a output joined file.'); var actualMap = grunt.file.read('tmp/options_with_sourcesContent.js.map'); var expectedMap = grunt.file.read('test/expected/options_with_sourcesContent.js.map'); test.equal(actualMap, expectedMap, 'should write a source map file including `sourcesContent` property.'); test.done(); }, options_with_process: function(test) { test.expect(1); var actual = grunt.file.read('tmp/options_with_process.js'); var expected = grunt.file.read('test/expected/options_with_process.js'); test.equal(actual, expected, 'should use process function to modify concatenated file'); test.done(); }, with_coffee: function(test) { test.expect(1); var actualMap = grunt.file.read('tmp/with_coffee.js.map'); var expectedMap = grunt.file.read('test/expected/with_coffee.js.map'); test.equal(actualMap, expectedMap, 'should resolve combined source map.'); test.done(); }, css_files: function(test) { var actualContent, expectedContent, actualMap, expectedMap; test.expect(2); actualContent = grunt.file.read('tmp/css_files.css'); expectedContent = grunt.file.read('test/expected/css_files.css'); test.equal(actualContent, expectedContent, 'should output linking line as `/*# sourceMappingURL=<URL> */`.'); actualMap = grunt.file.read('tmp/css_files.css.map'); expectedMap = grunt.file.read('test/expected/css_files.css.map'); test.equal(actualMap, expectedMap, 'should write a source map.'); test.done(); }, css_files_with_sass_generated: function(test) { var actualContent, expectedContent, actualMap, expectedMap; test.expect(2); actualContent = grunt.file.read('tmp/css_files_with_sass_generated.css'); expectedContent = grunt.file.read('test/expected/css_files_with_sass_generated.css'); test.equal(actualContent, expectedContent, 'should concatenate contents except for linking lines.'); actualMap = grunt.file.read('tmp/css_files_with_sass_generated.css.map'); expectedMap = grunt.file.read('test/expected/css_files_with_sass_generated.css.map'); test.equal(actualMap, expectedMap, 'should write a source map resolving combined source map.'); test.done(); }, file_with_linking: function(test) { var actualContent, expectedContent, actualMap, expectedMap; test.expect(2); actualContent = grunt.file.read('tmp/file_with_linking.js'); expectedContent = grunt.file.read('test/expected/file_with_linking.js'); test.equal(actualContent, expectedContent, 'should concatenate contents and resolve the linking.'); actualMap = grunt.file.read('tmp/file_with_linking.js.map'); expectedMap = grunt.file.read('test/expected/file_with_linking.js.map'); test.equal(actualMap, expectedMap, 'should concatenate contents and resolve the linking.'); test.done(); }, file_with_old_linking: function(test) { var actualContent, expectedContent, actualMap, expectedMap; test.expect(2); actualContent = grunt.file.read('tmp/file_with_old_linking.js'); expectedContent = grunt.file.read('test/expected/file_with_old_linking.js'); test.equal(actualContent, expectedContent, 'should concatenate contents and resolve the old linking.'); actualMap = grunt.file.read('tmp/file_with_old_linking.js.map'); expectedMap = grunt.file.read('test/expected/file_with_old_linking.js.map'); test.equal(actualMap, expectedMap, 'should concatenate contents and resolve the old linking.'); test.done(); }, };
alexsmander/alexmattorr
wp-content/themes/portfolio/node_modules/grunt-concat-sourcemap/test/concat_sourcemap_test.js
JavaScript
gpl-2.0
5,041
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Usage instructions: Create a single array variable named 'activity'. This // represents explanatory text and one or more questions to present to the // student. Each element in the array should itself be either // // -- a string containing a set of complete HTML elements. That is, if the // string contains an open HTML tag (such as <form>), it must also have the // corresponding close tag (such as </form>). You put the actual question // text in a string. // // -- a JavaScript object representing the answer information for a question. // That is, the object contains properties such as the type of question, a // regular expression indicating the correct answer, a string to show in // case of either correct or incorrect answers or to show when the student // asks for help. For more information on how to specify the object, please // see http://code.google.com/p/course-builder/wiki/CreateActivities. var activity = [ '<table border="1"><tr><td><b>Search Tips:</b><p><ul><li>In the last video you learned how to select effective keywords. Remember to think about the words you think will be in your desired results page.<p> <li>Determine the most important words in your search as well as potential synonyms.</ul><p> </tr></td></table>', 'You received this letter from a friend. <p><font style="font-style:italic;">Hi, I am a chef and a food blogger. Recently, I wanted to write about this really yummy French sandwich with tuna and peppers and anchovies and stuff called a Pom Mignon, or something like that. For the life of me, I don’t know precisely what it is called. I spent half an hour last night typing every possible spelling I could think of into Google, but could not find it. What do I do now? <p>Thank you,<br>L.</font><p>Given what you know about this problem, what query would you use to solve it?<p>', { questionType: 'freetext', showAnswerPrompt: 'Compare with Expert', showAnswerOutput: 'Our expert says: Different people have different styles for searching for information. Here is how I identified the sandwich--though it is not the only way to arrive at an answer.\n\nI searched for [french sandwich tuna peppers anchovies]. \n\nRemember how Dan talked about thinking about what you want to find? What words will be on the kind of page you want to appear? \n\nSo, ask yourself what kind of page is likely to:\n\n1. Give the name of this sandwich?\n2. Be a common resource on the web?\n3. Make use of the other information you have about the sandwich--since the name was obviously a dead-end?\n\nI thought of a recipe! A recipe lists all of the ingredients. In this case, the chef knew several of the ingredients, but did not connect the fact that she knew them to the idea that she could use them in a basic web search.\n\nScroll down to continue. ', outputHeight: '300px' }, '<br><br>Can you find the name of the sandwich in the results below?<br>', '<br><img src="assets/img/Image10.1.png"<p>', '<br>What\'s the name of the sandwich?<br>', { questionType: 'freetext', showAnswerPrompt: 'Check Answer', showAnswerOutput: 'Pan Bagnat!'}, ];
esacosta/u-mooc
edu-courses/assets/js/activity-1.4.js
JavaScript
apache-2.0
3,756
//// [noImplicitReturnsWithoutReturnExpression.ts] function isMissingReturnExpression(): number { return; } function isMissingReturnExpression2(): any { return; } function isMissingReturnExpression3(): number|void { return; } function isMissingReturnExpression4(): void { return; } function isMissingReturnExpression5(x) { if (x) { return 0; } else { return; } } //// [noImplicitReturnsWithoutReturnExpression.js] function isMissingReturnExpression() { return; } function isMissingReturnExpression2() { return; } function isMissingReturnExpression3() { return; } function isMissingReturnExpression4() { return; } function isMissingReturnExpression5(x) { if (x) { return 0; } else { return; } }
plantain-00/TypeScript
tests/baselines/reference/noImplicitReturnsWithoutReturnExpression.js
JavaScript
apache-2.0
820
/** * @author TristanVALCKE / https://github.com/Itee */ /* global QUnit */ import { PointLightHelper } from '../../../../src/helpers/PointLightHelper'; export default QUnit.module( 'Helpers', () => { QUnit.module( 'PointLightHelper', () => { // INHERITANCE QUnit.todo( "Extending", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); // INSTANCING QUnit.todo( "Instancing", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); // PUBLIC STUFF QUnit.todo( "dispose", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); QUnit.todo( "update", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); } ); } );
Aldrien-/three.js
test/unit/src/helpers/PointLightHelper.tests.js
JavaScript
mit
745
'use strict'; var fs = require('fs'); var path = require('path'); var readdirp = require('readdirp'); var handlebars = require('handlebars'); var async = require('./async'); /** * Regex pattern for layout directive. {{!< layout }} */ var layoutPattern = /{{!<\s+([A-Za-z0-9\._\-\/]+)\s*}}/; /** * Constructor */ var ExpressHbs = function() { this.handlebars = handlebars.create(); this.SafeString = this.handlebars.SafeString; this.Utils = this.handlebars.Utils; this.beautify = null; this.beautifyrc = null; }; /** * Defines a block into which content is inserted via `content`. * * @example * In layout.hbs * * {{{block "pageStylesheets"}}} */ ExpressHbs.prototype.block = function(name) { var val = (this.blocks[name] || []).join('\n'); // free mem this.blocks[name] = null; return val; }; /** * Defines content for a named block declared in layout. * * @example * * {{#contentFor "pageStylesheets"}} * <link rel="stylesheet" href='{{{URL "css/style.css"}}}' /> * {{/contentFor}} */ ExpressHbs.prototype.content = function(name, options, context) { var block = this.blocks[name] || (this.blocks[name] = []); block.push(options.fn(context)); }; /** * Returns the layout filepath given the template filename and layout used. * Backward compatible with specifying layouts in locals like 'layouts/foo', * but if you have specified a layoutsDir you can specify layouts in locals with just the layout name. * * @param {String} filename Path to template file. * @param {String} layout Layout path. */ ExpressHbs.prototype.layoutPath = function(filename, layout) { var layoutPath; if (layout[0] === '.') { layoutPath = path.resolve(path.dirname(filename), layout); } else if (this.layoutsDir) { layoutPath = path.resolve(this.layoutsDir, layout); } else { layoutPath = path.resolve(this.viewsDir, layout); } return layoutPath; } /** * Find the path of the declared layout in `str`, if any * * @param {String} str The template string to parse * @param {String} filename Path to template * @returns {String|undefined} Returns the path to layout. */ ExpressHbs.prototype.declaredLayoutFile = function(str, filename) { var matches = str.match(layoutPattern); if (matches) { var layout = matches[1]; // behave like `require`, if '.' then relative, else look in // usual location (layoutsDir) if (this.layoutsDir && layout[0] !== '.') { layout = path.resolve(this.layoutsDir, layout); } return path.resolve(path.dirname(filename), layout); } }; /** * Compiles a layout file. * * The function checks whether the layout file declares a parent layout. * If it does, the parent layout is loaded recursively and checked as well * for a parent layout, and so on, until the top layout is reached. * All layouts are then returned as a stack to the caller via the callback. * * @param {String} layoutFile The path to the layout file to compile * @param {Boolean} useCache Cache the compiled layout? * @param {Function} cb Callback called with layouts stack */ ExpressHbs.prototype.cacheLayout = function(layoutFile, useCache, cb) { var self = this; // assume hbs extension if (path.extname(layoutFile) === '') layoutFile += this._options.extname; // path is relative in directive, make it absolute var layoutTemplates = this.cache[layoutFile]; if (layoutTemplates) return cb(null, layoutTemplates); fs.readFile(layoutFile, 'utf8', function(err, str) { if (err) return cb(err); // File path of eventual declared parent layout var parentLayoutFile = self.declaredLayoutFile(str, layoutFile); // This function returns the current layout stack to the caller var _returnLayouts = function(layouts) { var currentLayout; layouts = layouts.slice(0); currentLayout = self.compile(str, layoutFile); layouts.push(currentLayout); if (useCache) { self.cache[layoutFile] = layouts.slice(0); } cb(null, layouts); }; if (parentLayoutFile) { // Recursively compile/cache parent layouts self.cacheLayout(parentLayoutFile, useCache, function(err, parentLayouts) { if (err) return cb(err); _returnLayouts(parentLayouts); }); } else { // No parent layout: return current layout with an empty stack _returnLayouts([]); } }); }; /** * Cache partial templates found under directories configure in partialsDir. */ ExpressHbs.prototype.cachePartials = function(cb) { var self = this; if (!(this.partialsDir instanceof Array)) { this.partialsDir = [this.partialsDir]; } // Use to iterate all folder in series var count = 0; function readNext() { readdirp({ root: self.partialsDir[count], fileFilter: '*.*' }) .on('warn', function(err) { console.warn('Non-fatal error in express-hbs cachePartials.', err); }) .on('error', function(err) { console.error('Fatal error in express-hbs cachePartials', err); return cb(err); }) .on('data', function(entry) { if (!entry) return; var source = fs.readFileSync(entry.fullPath, 'utf8'); var dirname = path.dirname(entry.path); dirname = dirname === '.' ? '' : dirname + '/'; var name = dirname + path.basename(entry.name, path.extname(entry.name)); self.registerPartial(name, source); }) .on('end', function() { count += 1; // If all directories aren't read, read the next directory if (count < self.partialsDir.length) { readNext() } else { self.isPartialCachingComplete = true; cb && cb(null, true); } }); } readNext(); }; /** * Express 3.x template engine compliance. * * @param {Object} options = { * handlebars: "override handlebars", * defaultLayout: "path to default layout", * partialsDir: "absolute path to partials (one path or an array of paths)", * layoutsDir: "absolute path to the layouts", * extname: "extension to use", * contentHelperName: "contentFor", * blockHelperName: "block", * beautify: "{Boolean} whether to pretty print HTML" * } * */ ExpressHbs.prototype.express3 = function(options) { var self = this; // Set defaults if (!options) options = {}; if (!options.extname) options.extname = '.hbs'; if (!options.contentHelperName) options.contentHelperName = 'contentFor'; if (!options.blockHelperName) options.blockHelperName = 'block'; if (!options.templateOptions) options.templateOptions = {}; if (options.handlebars) this.handlebars = options.handlebars; this._options = options; if (this._options.handlebars) this.handlebars = this._options.handlebars; if (options.i18n) { var i18n = options.i18n; this.handlebars.registerHelper('__', function() { return i18n.__.apply(this, arguments); }); this.handlebars.registerHelper('__n', function() { return i18n.__n.apply(this, arguments); }); } this.handlebars.registerHelper(this._options.blockHelperName, function(name, options) { var val = self.block(name); if (val == '' && (typeof options.fn === 'function')) { val = options.fn(this); } // blocks may have async helpers if (val.indexOf('__aSyNcId_') >= 0) { if (self.asyncValues) { Object.keys(self.asyncValues).forEach(function (id) { val = val.replace(id, self.asyncValues[id]); val = val.replace(self.Utils.escapeExpression(id), self.Utils.escapeExpression(self.asyncValues[id])); }); } } return val; }); // Pass 'this' as context of helper function to don't lose context call of helpers. this.handlebars.registerHelper(this._options.contentHelperName, function(name, options) { return self.content(name, options, this); }); // Absolute path to partials directory. this.partialsDir = this._options.partialsDir; // Absolute path to the layouts directory this.layoutsDir = this._options.layoutsDir; // express passes this through _express3 func, gulp pass in an option this.viewsDir = null this.viewsDirOpt = this._options.viewsDir; // Cache for templates, express 3.x doesn't do this for us this.cache = {}; // Blocks for layouts. Is this safe? What happens if the same block is used on multiple connections? // Isn't there a chance block and content are not in sync. The template and layout are processed asynchronously. this.blocks = {}; // Holds the default compiled layout if specified in options configuration. this.defaultLayoutTemplates = null; // Keep track of if partials have been cached already or not. this.isPartialCachingComplete = false; return _express3.bind(this); }; /** * Tries to load the default layout. * * @param {Boolean} useCache Whether to cache. */ ExpressHbs.prototype.loadDefaultLayout = function(useCache, cb) { var self = this; if (!this._options.defaultLayout) return cb(); if (useCache && this.defaultLayoutTemplates) return cb(null, this.defaultLayoutTemplates); this.cacheLayout(this._options.defaultLayout, useCache, function(err, templates) { if (err) return cb(err); self.defaultLayoutTemplates = templates.slice(0); return cb(null, templates); }); }; /** * express 3.x template engine compliance * * @param {String} filename Full path to template. * @param {Object} options Is the context or locals for templates. { * {Object} settings - subset of Express settings, `settings.views` is * the views directory * } * @param {Function} cb The callback expecting the rendered template as a string. * * @example * * Example options from express * * { * settings: { * 'x-powered-by': true, * env: 'production', * views: '/home/coder/barc/code/express-hbs/example/views', * 'jsonp callback name': 'callback', * 'view cache': true, * 'view engine': 'hbs' * }, * cache: true, * * // the rest are app-defined locals * title: 'My favorite veggies', * layout: 'layout/veggie' * } */ function _express3(filename, source, options, cb) { // console.log('filename', filename); // console.log('options', options); // support running as a gulp/grunt filter outside of express if (arguments.length === 3) { cb = options; options = source; source = null; } this.viewsDir = options.settings.views || this.viewsDirOpt; var self = this; /** * Allow a layout to be declared as a handlebars comment to remain spec * compatible with handlebars. * * Valid directives * * {{!< foo}} # foo.hbs in same directory as template * {{!< ../layouts/default}} # default.hbs in parent layout directory * {{!< ../layouts/default.html}} # default.html in parent layout directory */ function parseLayout(str, filename, cb) { var layoutFile = self.declaredLayoutFile(str, filename); if (layoutFile) { self.cacheLayout(layoutFile, options.cache, cb); } else { cb(null, null); } } /** * Renders `template` with given `locals` and calls `cb` with the * resulting HTML string. * * @param template * @param locals * @param cb */ function renderTemplate(template, locals, cb) { var res; try { res = template(locals, self._options.templateOptions); } catch (err) { if (err.message) { err.message = '[' + template.__filename + '] ' + err.message; } else if (typeof err === 'string') { err = '[' + template.__filename + '] ' + err; } return cb(err, null); } // Wait for async helpers async.done(function (values) { // Save for layout. Block helpers are called within layout, not in the // current template. self.asyncValues = values; Object.keys(values).forEach(function (id) { res = res.replace(id, values[id]); res = res.replace(self.Utils.escapeExpression(id), self.Utils.escapeExpression(values[id])); }); cb(null, res); }); } /** * Renders `template` with an optional set of nested `layoutTemplates` using * data in `locals`. */ function render(template, locals, layoutTemplates, cb) { if (layoutTemplates == undefined) layoutTemplates = []; // We'll render templates from bottom to top of the stack, each template // being passed the rendered string of the previous ones as `body` var i = layoutTemplates.length - 1; var _stackRenderer = function(err, htmlStr) { if (err) return cb(err); if (i >= 0) { locals.body = htmlStr; renderTemplate(layoutTemplates[i--], locals, _stackRenderer); } else { cb(null, htmlStr); } }; // Start the rendering with the innermost page template renderTemplate(template, locals, _stackRenderer); } /** * Lazy loads js-beautify, which shouldn't be used in production env. */ function loadBeautify() { if (!self.beautify) { self.beautify = require('js-beautify').html; var rc = path.join(process.cwd(), '.jsbeautifyrc'); if (fs.existsSync(rc)) { self.beautifyrc = JSON.parse(fs.readFileSync(rc, 'utf8')); } } } /** * Compiles a file into a template and a layoutTemplate, then renders it above. */ function compileFile(locals, cb) { var source, info, template; if (options.cache) { info = self.cache[filename]; if (info) { source = info.source; template = info.template; } } if (!info) { source = fs.readFileSync(filename, 'utf8'); template = self.compile(source, filename); if (options.cache) { self.cache[filename] = { source: source, template: template }; } } // Try to get the layout parseLayout(source, filename, function (err, layoutTemplates) { if (err) return cb(err); function renderIt(layoutTemplates) { if (self._options.beautify) { return render(template, locals, layoutTemplates, function(err, html) { if (err) return cb(err); loadBeautify(); return cb(null, self.beautify(html, self.beautifyrc)); }); } else { return render(template, locals, layoutTemplates, cb); } } // Determine which layout to use // If options.layout is falsy, behave as if no layout should be used - suppress defaults if ((typeof (options.layout) !== 'undefined') && !options.layout) { renderIt(null); } else { // 1. Layout specified in template if (layoutTemplates) { renderIt(layoutTemplates); } // 2. Layout specified by options from render else if ((typeof (options.layout) !== 'undefined') && options.layout) { var layoutFile = self.layoutPath(filename, options.layout); self.cacheLayout(layoutFile, options.cache, function (err, layoutTemplates) { if (err) return cb(err); renderIt(layoutTemplates); }); } // 3. Default layout specified when middleware was configured. else if (self.defaultLayoutTemplates) { renderIt(self.defaultLayoutTemplates); } // render without a template else renderIt(null); } }); } // kick it off by loading default template (if any) this.loadDefaultLayout(options.cache, function(err) { if (err) return cb(err); // Force reloading of all partials if caching is not used. Inefficient but there // is no loading partial event. if (self.partialsDir && (!options.cache || !self.isPartialCachingComplete)) { return self.cachePartials(function(err) { if (err) return cb(err); return compileFile(options, cb); }); } return compileFile(options, cb); }); } /** * Expose useful methods. */ ExpressHbs.prototype.registerHelper = function(name, fn) { this.handlebars.registerHelper(name, fn); }; /** * Registers a partial. * * @param {String} name The name of the partial as used in a template. * @param {String} source String source of the partial. */ ExpressHbs.prototype.registerPartial = function(name, source) { this.handlebars.registerPartial(name, this.compile(source)); }; /** * Compiles a string. * * @param {String} source The source to compile. * @param {String} filename The path used to embed into __filename for errors. */ ExpressHbs.prototype.compile = function(source, filename) { // Handlebars has a bug with comment only partial causes errors. This must // be a string so the block below can add a space. if (typeof source !== 'string') { throw new Error('registerPartial must be a string for empty comment workaround'); } if (source.indexOf('}}') === source.length - 2) { source += ' '; } var compiled = this.handlebars.compile(source); if (filename) { // track for error message compiled.__filename = path.relative(this.viewsDir, filename).replace(path.sep, '/'); } return compiled; } /** * Registers an asynchronous helper. * * @param {String} name The name of the partial as used in a template. * @param {String} fn The `function(options, cb)` */ ExpressHbs.prototype.registerAsyncHelper = function(name, fn) { this.handlebars.registerHelper(name, function(context) { return async.resolve(fn.bind(this), context); }); }; ExpressHbs.prototype.updateTemplateOptions = function(templateOptions) { this._options.templateOptions = templateOptions; }; /** * Creates a new instance of ExpressHbs. */ ExpressHbs.prototype.create = function() { return new ExpressHbs(); }; module.exports = new ExpressHbs();
vietpn/ghost-nodejs
node_modules/express-hbs/lib/hbs.js
JavaScript
mit
17,800
var baz = "baz"; export default baz;
EliteScientist/webpack
test/statsCases/import-context-filter/templates/baz.noimport.js
JavaScript
mit
38
define( [ "js/views/baseview", "underscore", "js/models/metadata", "js/views/abstract_editor", "js/models/uploads", "js/views/uploads", "js/models/license", "js/views/license", "js/views/video/transcripts/metadata_videolist", "js/views/video/translations_editor" ], function(BaseView, _, MetadataModel, AbstractEditor, FileUpload, UploadDialog, LicenseModel, LicenseView, VideoList, VideoTranslations) { var Metadata = {}; Metadata.Editor = BaseView.extend({ // Model is CMS.Models.MetadataCollection, initialize : function() { var self = this, counter = 0, locator = self.$el.closest('[data-locator]').data('locator'), courseKey = self.$el.closest('[data-course-key]').data('course-key'); this.template = this.loadTemplate('metadata-editor'); this.$el.html(this.template({numEntries: this.collection.length})); this.collection.each( function (model) { var data = { el: self.$el.find('.metadata_entry')[counter++], courseKey: courseKey, locator: locator, model: model }, conversions = { 'Select': 'Option', 'Float': 'Number', 'Integer': 'Number' }, type = model.getType(); if (conversions[type]) { type = conversions[type]; } if (_.isFunction(Metadata[type])) { new Metadata[type](data); } else { // Everything else is treated as GENERIC_TYPE, which uses String editor. new Metadata.String(data); } }); }, /** * Returns just the modified metadata values, in the format used to persist to the server. */ getModifiedMetadataValues: function () { var modified_values = {}; this.collection.each( function (model) { if (model.isModified()) { modified_values[model.getFieldName()] = model.getValue(); } } ); return modified_values; }, /** * Returns a display name for the component related to this metadata. This method looks to see * if there is a metadata entry called 'display_name', and if so, it returns its value. If there * is no such entry, or if display_name does not have a value set, it returns an empty string. */ getDisplayName: function () { var displayName = ''; this.collection.each( function (model) { if (model.get('field_name') === 'display_name') { var displayNameValue = model.get('value'); // It is possible that there is no display name value set. In that case, return empty string. displayName = displayNameValue ? displayNameValue : ''; } } ); return displayName; } }); Metadata.VideoList = VideoList; Metadata.VideoTranslations = VideoTranslations; Metadata.String = AbstractEditor.extend({ events : { "change input" : "updateModel", "keypress .setting-input" : "showClearButton", "click .setting-clear" : "clear" }, templateName: "metadata-string-entry", render: function () { AbstractEditor.prototype.render.apply(this); // If the model has property `non editable` equals `true`, // the field is disabled, but user is able to clear it. if (this.model.get('non_editable')) { this.$el.find('#' + this.uniqueId) .prop('readonly', true) .addClass('is-disabled') .attr('aria-disabled', true); } }, getValueFromEditor : function () { return this.$el.find('#' + this.uniqueId).val(); }, setValueInEditor : function (value) { this.$el.find('input').val(value); } }); Metadata.Number = AbstractEditor.extend({ events : { "change input" : "updateModel", "keypress .setting-input" : "keyPressed", "change .setting-input" : "changed", "click .setting-clear" : "clear" }, render: function () { AbstractEditor.prototype.render.apply(this); if (!this.initialized) { var numToString = function (val) { return val.toFixed(4); }; var min = "min"; var max = "max"; var step = "step"; var options = this.model.getOptions(); if (options.hasOwnProperty(min)) { this.min = Number(options[min]); this.$el.find('input').attr(min, numToString(this.min)); } if (options.hasOwnProperty(max)) { this.max = Number(options[max]); this.$el.find('input').attr(max, numToString(this.max)); } var stepValue = undefined; if (options.hasOwnProperty(step)) { // Parse step and convert to String. Polyfill doesn't like float values like ".1" (expects "0.1"). stepValue = numToString(Number(options[step])); } else if (this.isIntegerField()) { stepValue = "1"; } if (stepValue !== undefined) { this.$el.find('input').attr(step, stepValue); } // Manually runs polyfill for input number types to correct for Firefox non-support. // inputNumber will be undefined when unit test is running. if ($.fn.inputNumber) { this.$el.find('.setting-input-number').inputNumber(); } this.initialized = true; } return this; }, templateName: "metadata-number-entry", getValueFromEditor : function () { return this.$el.find('#' + this.uniqueId).val(); }, setValueInEditor : function (value) { this.$el.find('input').val(value); }, /** * Returns true if this view is restricted to integers, as opposed to floating points values. */ isIntegerField : function () { return this.model.getType() === 'Integer'; }, keyPressed: function (e) { this.showClearButton(); // This first filtering if statement is take from polyfill to prevent // non-numeric input (for browsers that don't use polyfill because they DO have a number input type). var _ref, _ref1; if (((_ref = e.keyCode) !== 8 && _ref !== 9 && _ref !== 35 && _ref !== 36 && _ref !== 37 && _ref !== 39) && ((_ref1 = e.which) !== 45 && _ref1 !== 46 && _ref1 !== 48 && _ref1 !== 49 && _ref1 !== 50 && _ref1 !== 51 && _ref1 !== 52 && _ref1 !== 53 && _ref1 !== 54 && _ref1 !== 55 && _ref1 !== 56 && _ref1 !== 57)) { e.preventDefault(); } // For integers, prevent decimal points. if (this.isIntegerField() && e.keyCode === 46) { e.preventDefault(); } }, changed: function () { // Limit value to the range specified by min and max (necessary for browsers that aren't using polyfill). // Prevent integer/float fields value to be empty (set them to their defaults) var value = this.getValueFromEditor(); if (value) { if ((this.max !== undefined) && value > this.max) { value = this.max; } else if ((this.min != undefined) && value < this.min) { value = this.min; } this.setValueInEditor(value); this.updateModel(); } else { this.clear(); } } }); Metadata.Option = AbstractEditor.extend({ events : { "change select" : "updateModel", "click .setting-clear" : "clear" }, templateName: "metadata-option-entry", getValueFromEditor : function () { var selectedText = this.$el.find('#' + this.uniqueId).find(":selected").text(); var selectedValue; _.each(this.model.getOptions(), function (modelValue) { if (modelValue === selectedText) { selectedValue = modelValue; } else if (modelValue['display_name'] === selectedText) { selectedValue = modelValue['value']; } }); return selectedValue; }, setValueInEditor : function (value) { // Value here is the json value as used by the field. The choice may instead be showing display names. // Find the display name matching the value passed in. _.each(this.model.getOptions(), function (modelValue) { if (modelValue['value'] === value) { value = modelValue['display_name']; } }); this.$el.find('#' + this.uniqueId + " option").filter(function() { return $(this).text() === value; }).prop('selected', true); } }); Metadata.List = AbstractEditor.extend({ events : { "click .setting-clear" : "clear", "keypress .setting-input" : "showClearButton", "change input" : "updateModel", "input input" : "enableAdd", "click .create-setting" : "addEntry", "click .remove-setting" : "removeEntry" }, templateName: "metadata-list-entry", getValueFromEditor: function () { return _.map( this.$el.find('li input'), function (ele) { return ele.value.trim(); } ).filter(_.identity); }, setValueInEditor: function (value) { var list = this.$el.find('ol'); list.empty(); _.each(value, function(ele, index) { var template = _.template( '<li class="list-settings-item">' + '<input type="text" class="input" value="<%= ele %>">' + '<a href="#" class="remove-action remove-setting" data-index="<%= index %>"><i class="icon fa fa-times-circle" aria-hidden="true"></i><span class="sr">Remove</span></a>' + '</li>' ); list.append($(template({'ele': ele, 'index': index}))); }); }, addEntry: function(event) { event.preventDefault(); // We don't call updateModel here since it's bound to the // change event var list = this.model.get('value') || []; this.setValueInEditor(list.concat([''])); this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true); }, removeEntry: function(event) { event.preventDefault(); var entry = $(event.currentTarget).siblings().val(); this.setValueInEditor(_.without(this.model.get('value'), entry)); this.updateModel(); this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, enableAdd: function() { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, clear: function() { AbstractEditor.prototype.clear.apply(this, arguments); if (_.isNull(this.model.getValue())) { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); } } }); Metadata.RelativeTime = AbstractEditor.extend({ defaultValue: '00:00:00', // By default max value of RelativeTime field on Backend is 23:59:59, // that is 86399 seconds. maxTimeInSeconds: 86399, events: { "focus input" : "addSelection", "mouseup input" : "mouseUpHandler", "change input" : "updateModel", "keypress .setting-input" : "showClearButton" , "click .setting-clear" : "clear" }, templateName: "metadata-string-entry", getValueFromEditor: function () { var $input = this.$el.find('#' + this.uniqueId); return $input.val(); }, updateModel: function () { var value = this.getValueFromEditor(), time = this.parseRelativeTime(value); this.model.setValue(time); // Sometimes, `parseRelativeTime` method returns the same value for // the different inputs. In this case, model will not be // updated (it already has the same value) and we should // call `render` method manually. // Examples: // value => 23:59:59; parseRelativeTime => 23:59:59 // value => 44:59:59; parseRelativeTime => 23:59:59 if (value !== time && !this.model.hasChanged('value')) { this.render(); } }, parseRelativeTime: function (value) { // This function ensure you have two-digits var pad = function (number) { return (number < 10) ? "0" + number : number; }, // Removes all white-spaces and splits by `:`. list = value.replace(/\s+/g, '').split(':'), seconds, date; list = _.map(list, function(num) { return Math.max(0, parseInt(num, 10) || 0); }).reverse(); seconds = _.reduce(list, function(memo, num, index) { return memo + num * Math.pow(60, index); }, 0); // multiply by 1000 because Date() requires milliseconds date = new Date(Math.min(seconds, this.maxTimeInSeconds) * 1000); return [ pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()) ].join(':'); }, setValueInEditor: function (value) { if (!value) { value = this.defaultValue; } this.$el.find('input').val(value); }, addSelection: function (event) { $(event.currentTarget).select(); }, mouseUpHandler: function (event) { // Prevents default behavior to make works selection in WebKit // browsers event.preventDefault(); } }); Metadata.Dict = AbstractEditor.extend({ events: { "click .setting-clear" : "clear", "keypress .setting-input" : "showClearButton", "change input" : "updateModel", "input input" : "enableAdd", "click .create-setting" : "addEntry", "click .remove-setting" : "removeEntry" }, templateName: "metadata-dict-entry", getValueFromEditor: function () { var dict = {}; _.each(this.$el.find('li'), function(li, index) { var key = $(li).find('.input-key').val().trim(), value = $(li).find('.input-value').val().trim(); // Keys should be unique, so if our keys are duplicated and // second key is empty or key and value are empty just do // nothing. Otherwise, it'll be overwritten by the new value. if (value === '') { if (key === '' || key in dict) { return false; } } dict[key] = value; }); return dict; }, setValueInEditor: function (value) { var list = this.$el.find('ol'), frag = document.createDocumentFragment(); _.each(value, function(value, key) { var template = _.template( '<li class="list-settings-item">' + '<input type="text" class="input input-key" value="<%= key %>">' + '<input type="text" class="input input-value" value="<%= value %>">' + '<a href="#" class="remove-action remove-setting" data-value="<%= value %>"><i class="icon fa fa-times-circle" aria-hidden="true"></i><span class="sr">Remove</span></a>' + '</li>' ); frag.appendChild($(template({'key': key, 'value': value}))[0]); }); list.html([frag]); }, addEntry: function(event) { event.preventDefault(); // We don't call updateModel here since it's bound to the // change event var dict = $.extend(true, {}, this.model.get('value')) || {}; dict[''] = ''; this.setValueInEditor(dict); this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true); }, removeEntry: function(event) { event.preventDefault(); var entry = $(event.currentTarget).siblings('.input-key').val(); this.setValueInEditor(_.omit(this.model.get('value'), entry)); this.updateModel(); this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, enableAdd: function() { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, clear: function() { AbstractEditor.prototype.clear.apply(this, arguments); if (_.isNull(this.model.getValue())) { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); } } }); /** * Provides convenient way to upload/download files in component edit. * The editor uploads files directly to course assets and stores link * to uploaded file. */ Metadata.FileUploader = AbstractEditor.extend({ events : { "click .upload-setting" : "upload", "click .setting-clear" : "clear" }, templateName: "metadata-file-uploader-entry", templateButtonsName: "metadata-file-uploader-item", initialize: function () { this.buttonTemplate = this.loadTemplate(this.templateButtonsName); AbstractEditor.prototype.initialize.apply(this); }, getValueFromEditor: function () { return this.$('#' + this.uniqueId).val(); }, setValueInEditor: function (value) { var html = this.buttonTemplate({ model: this.model, uniqueId: this.uniqueId }); this.$('#' + this.uniqueId).val(value); this.$('.wrapper-uploader-actions').html(html); }, upload: function (event) { var self = this, target = $(event.currentTarget), url = '/assets/' + this.options.courseKey + '/', model = new FileUpload({ title: gettext('Upload File'), }), view = new UploadDialog({ model: model, url: url, parentElement: target.closest('.xblock-editor'), onSuccess: function (response) { if (response['asset'] && response['asset']['url']) { self.model.setValue(response['asset']['url']); } } }).show(); event.preventDefault(); } }); Metadata.License = AbstractEditor.extend({ initialize: function(options) { this.licenseModel = new LicenseModel({"asString": this.model.getValue()}); this.licenseView = new LicenseView({model: this.licenseModel}); // Rerender when the license model changes this.listenTo(this.licenseModel, 'change', this.setLicense); this.render(); }, render: function() { this.licenseView.render().$el.css("display", "inline"); this.licenseView.undelegateEvents(); this.$el.empty().append(this.licenseView.el); // restore event bindings this.licenseView.delegateEvents(); return this; }, setLicense: function() { this.model.setValue(this.licenseModel.toString()); this.render() } }); return Metadata; });
MakeHer/edx-platform
cms/static/js/views/metadata.js
JavaScript
agpl-3.0
21,517
/** * Copyright (c) 2016 hustcc * License: MIT * https://github.com/hustcc/timeago.js **/ /* jshint expr: true */ !function (root, factory) { if (typeof module === 'object' && module.exports) module.exports = factory(root); else root.timeago = factory(root); }(typeof window !== 'undefined' ? window : this, function () { var cnt = 0, // the timer counter, for timer key indexMapEn = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year'], indexMapZh = ['秒', '分钟', '小时', '天', '周', '月', '年'], // build-in locales: en & zh_CN locales = { 'en': function(number, index) { if (index === 0) return ['just now', 'a while']; else { var unit = indexMapEn[parseInt(index / 2)]; if (number > 1) unit += 's'; return [number + ' ' + unit + ' ago', 'in ' + number + ' ' + unit]; } }, 'zh_CN': function(number, index) { if (index === 0) return ['刚刚', '片刻后']; else { var unit = indexMapZh[parseInt(index / 2)]; return [number + unit + '前', number + unit + '后']; } } }, // second, minute, hour, day, week, month, year(365 days) SEC_ARRAY = [60, 60, 24, 7, 365/7/12, 12], SEC_ARRAY_LEN = 6, ATTR_DATETIME = 'datetime'; /** * timeago: the function to get `timeago` instance. * - nowDate: the relative date, default is new Date(). * - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you. * * How to use it? * var timeagoLib = require('timeago.js'); * var timeago = timeagoLib(); // all use default. * var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago. * var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`. * var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前. **/ function timeago(nowDate, defaultLocale) { var timers = {}; // real-time render timers // if do not set the defaultLocale, set it with `en` if (! defaultLocale) defaultLocale = 'en'; // use default build-in locale // calculate the diff second between date to be formated an now date. function diffSec(date) { var now = new Date(); if (nowDate) now = toDate(nowDate); return (now - toDate(date)) / 1000; } // format the diff second to *** time ago, with setting locale function formatDiff(diff, locale) { if (! locales[locale]) locale = defaultLocale; var i = 0; agoin = diff < 0 ? 1 : 0, // timein or timeago diff = Math.abs(diff); for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) { diff /= SEC_ARRAY[i]; } diff = toInt(diff); i *= 2; if (diff > (i === 0 ? 9 : 1)) i += 1; return locales[locale](diff, i)[agoin].replace('%s', diff); } /** * format: format the date to *** time ago, with setting or default locale * - date: the date / string / timestamp to be formated * - locale: the formated string's locale name, e.g. en / zh_CN * * How to use it? * var timeago = require('timeago.js')(); * timeago.format(new Date(), 'pl'); // Date instance * timeago.format('2016-09-10', 'fr'); // formated date string * timeago.format(1473473400269); // timestamp with ms **/ this.format = function(date, locale) { return formatDiff(diffSec(date), locale); }; // format Date / string / timestamp to Date instance. function toDate(input) { if (input instanceof Date) { return input; } else if (!isNaN(input)) { return new Date(toInt(input)); } else if (/^\d+$/.test(input)) { return new Date(toInt(input, 10)); } else { var s = (input || '').trim(); s = s.replace(/\.\d+/, '') // remove milliseconds .replace(/-/, '/').replace(/-/, '/') .replace(/T/, ' ').replace(/Z/, ' UTC') .replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2'); // -04:00 -> -0400 return new Date(s); } } // change f into int, remove Decimal. just for code compression function toInt(f) { return parseInt(f); } // function leftSec(diff, unit) { // diff = diff % unit; // diff = diff ? unit - diff : unit; // return Math.ceil(diff); // } /** * nextInterval: calculate the next interval time. * - diff: the diff sec between now and date to be formated. * * What's the meaning? * diff = 61 then return 59 * diff = 3601 (an hour + 1 second), then return 3599 * make the interval with high performace. **/ // this.nextInterval = function(diff) { // for dev test function nextInterval(diff) { var rst = 1, i = 0, d = diff; for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) { diff /= SEC_ARRAY[i]; rst *= SEC_ARRAY[i]; } // return leftSec(d, rst); d = d % rst; d = d ? rst - d : rst; return Math.ceil(d); // }; // for dev test } // what the timer will do function doRender(node, date, locale, cnt) { var diff = diffSec(date); node.innerHTML = formatDiff(diff, locale); // waiting %s seconds, do the next render timers['k' + cnt] = setTimeout(function() { doRender(node, date, locale, cnt); }, nextInterval(diff) * 1000); } // get the datetime attribute, jQuery and DOM function getDateAttr(node) { if (node.getAttribute) return node.getAttribute(ATTR_DATETIME); if(node.attr) return node.attr(ATTR_DATETIME); } /** * render: render the DOM real-time. * - nodes: which nodes will be rendered. * - locale: the locale name used to format date. * * How to use it? * var timeago = new require('timeago.js')(); * // 1. javascript selector * timeago.render(document.querySelectorAll('.need_to_be_rendered')); * // 2. use jQuery selector * timeago.render($('.need_to_be_rendered'), 'pl'); * * Notice: please be sure the dom has attribute `datetime`. **/ this.render = function(nodes, locale) { if (nodes.length === undefined) nodes = [nodes]; for (var i = 0; i < nodes.length; i++) { doRender(nodes[i], getDateAttr(nodes[i]), locale, ++ cnt); // render item } }; /** * cancel: cancel all the timers which are doing real-time render. * * How to use it? * var timeago = new require('timeago.js')(); * timeago.render(document.querySelectorAll('.need_to_be_rendered')); * timeago.cancel(); // will stop all the timer, stop render in real time. **/ this.cancel = function() { for (var key in timers) { clearTimeout(timers[key]); } timers = {}; }; /** * setLocale: set the default locale name. * * How to use it? * var timeago = require('timeago.js'); * timeago = new timeago(); * timeago.setLocale('fr'); **/ this.setLocale = function(locale) { defaultLocale = locale; }; return this; } /** * timeago: the function to get `timeago` instance. * - nowDate: the relative date, default is new Date(). * - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you. * * How to use it? * var timeagoLib = require('timeago.js'); * var timeago = timeagoLib(); // all use default. * var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago. * var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`. * var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前. **/ function timeagoFactory(nowDate, defaultLocale) { return new timeago(nowDate, defaultLocale); } /** * register: register a new language locale * - locale: locale name, e.g. en / zh_CN, notice the standard. * - localeFunc: the locale process function * * How to use it? * var timeagoLib = require('timeago.js'); * * timeagoLib.register('the locale name', the_locale_func); * // or * timeagoLib.register('pl', require('timeago.js/locales/pl')); **/ timeagoFactory.register = function(locale, localeFunc) { locales[locale] = localeFunc; }; return timeagoFactory; });
froala/cdnjs
ajax/libs/timeago.js/2.0.0/timeago.js
JavaScript
mit
8,824
import { Subscriber } from '../Subscriber'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; /** * Compares all values of two observables in sequence using an optional comparor function * and returns an observable of a single boolean value representing whether or not the two sequences * are equal. * * <span class="informal">Checks to see of all values emitted by both observables are equal, in order.</span> * * <img src="./img/sequenceEqual.png" width="100%"> * * `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the * observables completes, the operator will wait for the other observable to complete; If the other * observable emits before completing, the returned observable will emit `false` and complete. If one observable never * completes or emits after the other complets, the returned observable will never complete. * * @example <caption>figure out if the Konami code matches</caption> * var code = Rx.Observable.from([ * "ArrowUp", * "ArrowUp", * "ArrowDown", * "ArrowDown", * "ArrowLeft", * "ArrowRight", * "ArrowLeft", * "ArrowRight", * "KeyB", * "KeyA", * "Enter" // no start key, clearly. * ]); * * var keys = Rx.Observable.fromEvent(document, 'keyup') * .map(e => e.code); * var matches = keys.bufferCount(11, 1) * .mergeMap( * last11 => * Rx.Observable.from(last11) * .sequenceEqual(code) * ); * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched)); * * @see {@link combineLatest} * @see {@link zip} * @see {@link withLatestFrom} * * @param {Observable} compareTo The observable sequence to compare the source sequence to. * @param {function} [comparor] An optional function to compare each value pair * @return {Observable} An Observable of a single boolean value representing whether or not * the values emitted by both observables were equal in sequence. * @method sequenceEqual * @owner Observable */ export function sequenceEqual(compareTo, comparor) { return (source) => source.lift(new SequenceEqualOperator(compareTo, comparor)); } export class SequenceEqualOperator { constructor(compareTo, comparor) { this.compareTo = compareTo; this.comparor = comparor; } call(subscriber, source) { return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor)); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export class SequenceEqualSubscriber extends Subscriber { constructor(destination, compareTo, comparor) { super(destination); this.compareTo = compareTo; this.comparor = comparor; this._a = []; this._b = []; this._oneComplete = false; this.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this))); } _next(value) { if (this._oneComplete && this._b.length === 0) { this.emit(false); } else { this._a.push(value); this.checkValues(); } } _complete() { if (this._oneComplete) { this.emit(this._a.length === 0 && this._b.length === 0); } else { this._oneComplete = true; } } checkValues() { const { _a, _b, comparor } = this; while (_a.length > 0 && _b.length > 0) { let a = _a.shift(); let b = _b.shift(); let areEqual = false; if (comparor) { areEqual = tryCatch(comparor)(a, b); if (areEqual === errorObject) { this.destination.error(errorObject.e); } } else { areEqual = a === b; } if (!areEqual) { this.emit(false); } } } emit(value) { const { destination } = this; destination.next(value); destination.complete(); } nextB(value) { if (this._oneComplete && this._a.length === 0) { this.emit(false); } else { this._b.push(value); this.checkValues(); } } } class SequenceEqualCompareToSubscriber extends Subscriber { constructor(destination, parent) { super(destination); this.parent = parent; } _next(value) { this.parent.nextB(value); } _error(err) { this.parent.error(err); } _complete() { this.parent._complete(); } } //# sourceMappingURL=sequenceEqual.js.map
rospilot/rospilot
share/web_assets/nodejs_deps/node_modules/rxjs/_esm2015/operators/sequenceEqual.js
JavaScript
apache-2.0
4,896
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // var mocha = require('mocha'); var should = require('should'); var sinon = require('sinon'); var _ = require('underscore'); // Test includes var testutil = require('../util/util'); // Lib includes var util = testutil.libRequire('util/utils'); var GetCommand = require('./util-GetCommand.js'); describe('HDInsight list command (under unit test)', function() { after(function (done) { done(); }); // NOTE: To Do, we should actually create new accounts for our tests // So that we can work on any existing subscription. before (function (done) { done(); }); it('should call startProgress with the correct statement', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({}, _); command.user.startProgress.firstCall.args[0].should.be.equal('Getting HDInsight servers'); done(); }); it('should call listClusters with the supplied subscriptionId (when none is supplied)', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({}, _); command.processor.listClusters.firstCall.should.not.equal(null); (command.processor.listClusters.firstCall.args[0] === undefined).should.equal(true); done(); }); it('should call listClusters with the supplied subscriptionId (when one is supplied)', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({ subscription: 'test1' }, _); command.processor.listClusters.firstCall.should.not.equal(null); command.processor.listClusters.firstCall.args[0].should.not.equal(null); command.processor.listClusters.firstCall.args[0].should.be.equal('test1'); done(); }); });
Nepomuceno/azure-xplat-cli
test/hdinsight/unit-list-command.js
JavaScript
apache-2.0
2,528
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint globalstrict: false */ /* umdutils ignore */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define('pdfjs-dist/build/pdf', ['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.pdfjsDistBuildPdf = {})); } }(this, function (exports) { // Use strict in our context only - users might not want it 'use strict'; var pdfjsVersion = '1.3.177'; var pdfjsBuild = '51b59bc'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { (function (root, factory) { { factory((root.pdfjsSharedGlobal = {})); } }(this, function (exports) { var globalScope = (typeof window !== 'undefined') ? window : (typeof global !== 'undefined') ? global : (typeof self !== 'undefined') ? self : this; var isWorker = (typeof window === 'undefined'); // The global PDFJS object exposes the API // In production, it will be declared outside a global wrapper // In development, it will be declared here if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } if (typeof pdfjsVersion !== 'undefined') { globalScope.PDFJS.version = pdfjsVersion; } if (typeof pdfjsVersion !== 'undefined') { globalScope.PDFJS.build = pdfjsBuild; } globalScope.PDFJS.pdfBug = false; exports.globalScope = globalScope; exports.isWorker = isWorker; exports.PDFJS = globalScope.PDFJS; })); (function (root, factory) { { factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedGlobal); } }(this, function (exports, sharedGlobal) { var PDFJS = sharedGlobal.PDFJS; /** * Optimised CSS custom property getter/setter. * @class */ var CustomStyle = (function CustomStyleClosure() { // As noted on: http://www.zachstronaut.com/posts/2009/02/17/ // animate-css-transforms-firefox-webkit.html // in some versions of IE9 it is critical that ms appear in this list // before Moz var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var _cache = {}; function CustomStyle() {} CustomStyle.getProp = function get(propName, element) { // check cache only when no element is given if (arguments.length === 1 && typeof _cache[propName] === 'string') { return _cache[propName]; } element = element || document.documentElement; var style = element.style, prefixed, uPropName; // test standard property first if (typeof style[propName] === 'string') { return (_cache[propName] = propName); } // capitalize uPropName = propName.charAt(0).toUpperCase() + propName.slice(1); // test vendor specific properties for (var i = 0, l = prefixes.length; i < l; i++) { prefixed = prefixes[i] + uPropName; if (typeof style[prefixed] === 'string') { return (_cache[propName] = prefixed); } } //if all fails then set to undefined return (_cache[propName] = 'undefined'); }; CustomStyle.setProp = function set(propName, element, str) { var prop = this.getProp(propName); if (prop !== 'undefined') { element.style[prop] = str; } }; return CustomStyle; })(); PDFJS.CustomStyle = CustomStyle; exports.CustomStyle = CustomStyle; })); (function (root, factory) { { factory((root.pdfjsSharedUtil = {}), root.pdfjsSharedGlobal); } }(this, function (exports, sharedGlobal) { var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { TEXT: 1, LINK: 2, FREETEXT: 3, LINE: 4, SQUARE: 5, CIRCLE: 6, POLYGON: 7, POLYLINE: 8, HIGHLIGHT: 9, UNDERLINE: 10, SQUIGGLY: 11, STRIKEOUT: 12, STAMP: 13, CARET: 14, INK: 15, POPUP: 16, FILEATTACHMENT: 17, SOUND: 18, MOVIE: 19, WIDGET: 20, SCREEN: 21, PRINTERMARK: 22, TRAPNET: 23, WATERMARK: 24, THREED: 25, REDACT: 26 }; var AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, PRINT: 0x04, NOZOOM: 0x08, NOROTATE: 0x10, NOVIEW: 0x20, READONLY: 0x40, LOCKED: 0x80, TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; var AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, BEVELED: 3, INSET: 4, UNDERLINE: 5 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; PDFJS.VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = PDFJS.OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Deprecated API function -- treated as warnings. function deprecated(details) { warn('Deprecated API usage: ' + details); } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; // Combines two URLs. The baseUrl shall be absolute URL. If the url is an // absolute URL, it will be returned as is. function combineUrl(baseUrl, url) { if (!url) { return baseUrl; } if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) { return url; } var i; if (url.charAt(0) === '/') { // absolute path i = baseUrl.indexOf('://'); if (url.charAt(1) === '/') { ++i; } else { i = baseUrl.indexOf('/', i + 3); } return baseUrl.substring(0, i) + url; } else { // relative path var pathLength = baseUrl.length; i = baseUrl.lastIndexOf('#'); pathLength = i >= 0 ? i : pathLength; i = baseUrl.lastIndexOf('?', pathLength); pathLength = i >= 0 ? i : pathLength; var prefixLength = baseUrl.lastIndexOf('/', pathLength); return baseUrl.substring(0, prefixLength + 1) + url; } } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url) { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': case 'tel': return true; default: return false; } } PDFJS.isValidUrl = isValidUrl; function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } PDFJS.shadow = shadow; var LinkTarget = PDFJS.LinkTarget = { NONE: 0, // Default value. SELF: 1, BLANK: 2, PARENT: 3, TOP: 4, }; var LinkTargetStringMap = [ '', '_self', '_blank', '_parent', '_top' ]; function isExternalLinkTargetSet() { if (PDFJS.openExternalLinksInNewWindow) { deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'); if (PDFJS.externalLinkTarget === LinkTarget.NONE) { PDFJS.externalLinkTarget = LinkTarget.BLANK; } // Reset the deprecated parameter, to suppress further warnings. PDFJS.openExternalLinksInNewWindow = false; } switch (PDFJS.externalLinkTarget) { case LinkTarget.NONE: return false; case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return true; } warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget); // Reset the external link target, to suppress further warnings. PDFJS.externalLinkTarget = LinkTarget.NONE; return false; } PDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet; var PasswordResponses = PDFJS.PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); PDFJS.PasswordException = PasswordException; var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); PDFJS.UnknownErrorException = UnknownErrorException; var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); PDFJS.InvalidPDFException = InvalidPDFException; var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); PDFJS.MissingPDFException = MissingPDFException; var UnexpectedResponseException = (function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; })(); PDFJS.UnexpectedResponseException = UnexpectedResponseException; var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); var NullCharactersRegExp = /\x00/g; function removeNullCharacters(str) { if (typeof str !== 'string') { warn('The argument for removeNullCharacters must be a string.'); return str; } return str.replace(NullCharactersRegExp, ''); } PDFJS.removeNullCharacters = removeNullCharacters; function bytesToString(bytes) { assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return (data[start] << 24) >> 24; } function readUint16(data, offset) { return (data[offset] << 8) | data[offset + 1]; } function readUint32(data, offset) { return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { return shadow(PDFJS, 'isLittleEndian', isLittleEndian()); } }); // Lazy test if the userAgent support CanvasTypedArrays function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays()); } }); var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); exports.Uint32ArrayView = Uint32ArrayView; var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = PDFJS.Util = (function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); /** * PDF page viewport created based on scale, rotation and offset. * @class * @alias PDFJS.PageViewport */ var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() { /** * @constructor * @private * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. * @param scale {number} scale of the viewport. * @param rotation {number} rotations of the viewport in degrees. * @param offsetX {number} offset X * @param offsetY {number} offset Y * @param dontFlip {boolean} if true, axis Y will not be flipped. */ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ { /** * Clones viewport with additional properties. * @param args {Object} (optional) If specified, may contain the 'scale' or * 'rotation' properties to override the corresponding properties in * the cloned viewport. * @returns {PDFJS.PageViewport} Cloned viewport. */ clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, /** * Converts PDF rectangle to the viewport coordinates. * @param rect {Array} xMin, yMin, xMax and yMax coordinates. * @returns {Array} Contains corresponding coordinates of the rectangle * in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isInt(v) { return typeof v === 'number' && ((v | 0) === v); } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isArray(v) { return v instanceof Array; } function isArrayBuffer(v) { return typeof v === 'object' && v !== null && v.byteLength !== undefined; } /** * Promise Capability object. * * @typedef {Object} PromiseCapability * @property {Promise} promise - A promise object. * @property {function} resolve - Fullfills the promise. * @property {function} reject - Rejects the promise. */ /** * Creates a promise capability object. * @alias PDFJS.createPromiseCapability * * @return {PromiseCapability} A capability object contains: * - a Promise, resolve and reject methods. */ function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } PDFJS.createPromiseCapability = createPromiseCapability; /** * Polyfill for Promises: * The following promise implementation tries to generally implement the * Promise/A+ spec. Some notable differences from other promise libaries are: * - There currently isn't a seperate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (value) { return new globalScope.Promise(function (resolve) { resolve(value); }); }; } if (typeof globalScope.Promise.reject !== 'function') { globalScope.Promise.reject = function (reason) { return new globalScope.Promise(function (resolve, reject) { reject(reason); }); }; } if (typeof globalScope.Promise.prototype.catch !== 'function') { globalScope.Promise.prototype.catch = function (onReject) { return globalScope.Promise.prototype.then(undefined, onReject); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status === STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof handler.onResolve === 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof handler.onReject === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; try { resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } catch (e) { this._reject(e); } } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} array of data and/or promises to wait for. * @return {Promise} New dependant promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if value is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param value resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(value) { return new Promise(function (resolve) { resolve(value); }); }; /** * Creates rejected promise * @param reason rejection value * @returns {Promise} */ Promise.reject = function Promise_reject(reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status === STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = resolve; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; }, catch: function Promise_catch(onReject) { return this.then(undefined, onReject); } }; globalScope.Promise = Promise; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = {}; this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); PDFJS.createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } // Blob builder is deprecated in FF14 and removed in FF18. var bb = new MozBlobBuilder(); bb.append(data); return bb.getBlob(contentType); }; PDFJS.createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType) { if (!PDFJS.disableCreateObjectURL && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = PDFJS.createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(sourceName, targetName, comObj) { this.sourceName = sourceName; this.targetName = targetName; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacksCapabilities = this.callbacksCapabilities = {}; var ah = this.actionHandler = {}; this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.targetName !== this.sourceName) { return; } if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(data.error); } else { callback.resolve(data.data); } } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var sourceName = this.sourceName; var targetName = data.sourceName; Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { if (reason instanceof Error) { // Serialize error to avoid "DataCloneError" reason = reason + ''; } comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, error: reason }); }); } else { action[0].call(action[1], data.data); } } else { error('Unknown action from worker: ' + data.action); } }.bind(this); comObj.addEventListener('message', this._onComObjOnMessage); } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, transfers) { var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data }; this.postMessage(message, transfers); }, /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that other side will callback with the response. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) { var callbackId = this.callbackIndex++; var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, /** * Sends raw message to the comObj. * @private * @param message {Object} Raw message. * @param transfers List of transfers/ArrayBuffers, or undefined. */ postMessage: function (message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } }, destroy: function () { this.comObj.removeEventListener('message', this._onComObjOnMessage); } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.onerror = (function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }); img.src = imageUrl; } exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; exports.IDENTITY_MATRIX = IDENTITY_MATRIX; exports.OPS = OPS; exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES; exports.AnnotationBorderStyleType = AnnotationBorderStyleType; exports.AnnotationFlag = AnnotationFlag; exports.AnnotationType = AnnotationType; exports.FontType = FontType; exports.ImageKind = ImageKind; exports.InvalidPDFException = InvalidPDFException; exports.LinkTarget = LinkTarget; exports.LinkTargetStringMap = LinkTargetStringMap; exports.MessageHandler = MessageHandler; exports.MissingDataException = MissingDataException; exports.MissingPDFException = MissingPDFException; exports.NotImplementedException = NotImplementedException; exports.PasswordException = PasswordException; exports.PasswordResponses = PasswordResponses; exports.StatTimer = StatTimer; exports.StreamType = StreamType; exports.TextRenderingMode = TextRenderingMode; exports.UnexpectedResponseException = UnexpectedResponseException; exports.UnknownErrorException = UnknownErrorException; exports.Util = Util; exports.XRefParseException = XRefParseException; exports.assert = assert; exports.bytesToString = bytesToString; exports.combineUrl = combineUrl; exports.createPromiseCapability = createPromiseCapability; exports.deprecated = deprecated; exports.error = error; exports.info = info; exports.isArray = isArray; exports.isArrayBuffer = isArrayBuffer; exports.isBool = isBool; exports.isEmptyObj = isEmptyObj; exports.isExternalLinkTargetSet = isExternalLinkTargetSet; exports.isInt = isInt; exports.isNum = isNum; exports.isString = isString; exports.isValidUrl = isValidUrl; exports.loadJpegStream = loadJpegStream; exports.log2 = log2; exports.readInt8 = readInt8; exports.readUint16 = readUint16; exports.readUint32 = readUint32; exports.removeNullCharacters = removeNullCharacters; exports.shadow = shadow; exports.string32 = string32; exports.stringToBytes = stringToBytes; exports.stringToPDFString = stringToPDFString; exports.stringToUTF8String = stringToUTF8String; exports.utf8StringToString = utf8StringToString; exports.warn = warn; })); (function (root, factory) { { factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType; var AnnotationType = sharedUtil.AnnotationType; var Util = sharedUtil.Util; var isExternalLinkTargetSet = sharedUtil.isExternalLinkTargetSet; var LinkTargetStringMap = sharedUtil.LinkTargetStringMap; var removeNullCharacters = sharedUtil.removeNullCharacters; var warn = sharedUtil.warn; var CustomStyle = displayDOMUtils.CustomStyle; /** * @typedef {Object} AnnotationElementParameters * @property {Object} data * @property {HTMLDivElement} layer * @property {PDFPage} page * @property {PageViewport} viewport * @property {IPDFLinkService} linkService */ /** * @class * @alias AnnotationElementFactory */ function AnnotationElementFactory() {} AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */ { /** * @param {AnnotationElementParameters} parameters * @returns {AnnotationElement} */ create: function AnnotationElementFactory_create(parameters) { var subtype = parameters.data.annotationType; switch (subtype) { case AnnotationType.LINK: return new LinkAnnotationElement(parameters); case AnnotationType.TEXT: return new TextAnnotationElement(parameters); case AnnotationType.WIDGET: return new WidgetAnnotationElement(parameters); case AnnotationType.POPUP: return new PopupAnnotationElement(parameters); case AnnotationType.HIGHLIGHT: return new HighlightAnnotationElement(parameters); case AnnotationType.UNDERLINE: return new UnderlineAnnotationElement(parameters); case AnnotationType.SQUIGGLY: return new SquigglyAnnotationElement(parameters); case AnnotationType.STRIKEOUT: return new StrikeOutAnnotationElement(parameters); default: throw new Error('Unimplemented annotation type "' + subtype + '"'); } } }; /** * @class * @alias AnnotationElement */ var AnnotationElement = (function AnnotationElementClosure() { function AnnotationElement(parameters) { this.data = parameters.data; this.layer = parameters.layer; this.page = parameters.page; this.viewport = parameters.viewport; this.linkService = parameters.linkService; this.container = this._createContainer(); } AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ { /** * Create an empty container for the annotation's HTML element. * * @private * @memberof AnnotationElement * @returns {HTMLSectionElement} */ _createContainer: function AnnotationElement_createContainer() { var data = this.data, page = this.page, viewport = this.viewport; var container = document.createElement('section'); var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; container.setAttribute('data-annotation-id', data.id); // Do *not* modify `data.rect`, since that will corrupt the annotation // position on subsequent calls to `_createContainer` (see issue 6804). var rect = Util.normalizeRect([ data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1] ]); CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')'); CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px'); if (data.borderStyle.width > 0) { container.style.borderWidth = data.borderStyle.width + 'px'; if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) { // Underline styles only have a bottom border, so we do not need // to adjust for all borders. This yields a similar result as // Adobe Acrobat/Reader. width = width - 2 * data.borderStyle.width; height = height - 2 * data.borderStyle.width; } var horizontalRadius = data.borderStyle.horizontalCornerRadius; var verticalRadius = data.borderStyle.verticalCornerRadius; if (horizontalRadius > 0 || verticalRadius > 0) { var radius = horizontalRadius + 'px / ' + verticalRadius + 'px'; CustomStyle.setProp('borderRadius', container, radius); } switch (data.borderStyle.style) { case AnnotationBorderStyleType.SOLID: container.style.borderStyle = 'solid'; break; case AnnotationBorderStyleType.DASHED: container.style.borderStyle = 'dashed'; break; case AnnotationBorderStyleType.BEVELED: warn('Unimplemented border style: beveled'); break; case AnnotationBorderStyleType.INSET: warn('Unimplemented border style: inset'); break; case AnnotationBorderStyleType.UNDERLINE: container.style.borderBottomStyle = 'solid'; break; default: break; } if (data.color) { container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); } else { // Transparent (invisible) border, so do not draw it at all. container.style.borderWidth = 0; } } container.style.left = rect[0] + 'px'; container.style.top = rect[1] + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; return container; }, /** * Render the annotation's HTML element in the empty container. * * @public * @memberof AnnotationElement */ render: function AnnotationElement_render() { throw new Error('Abstract method AnnotationElement.render called'); } }; return AnnotationElement; })(); /** * @class * @alias LinkAnnotationElement */ var LinkAnnotationElement = (function LinkAnnotationElementClosure() { function LinkAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(LinkAnnotationElement, AnnotationElement, { /** * Render the link annotation's HTML element in the empty container. * * @public * @memberof LinkAnnotationElement * @returns {HTMLSectionElement} */ render: function LinkAnnotationElement_render() { this.container.className = 'linkAnnotation'; var link = document.createElement('a'); link.href = link.title = (this.data.url ? removeNullCharacters(this.data.url) : ''); if (this.data.url && isExternalLinkTargetSet()) { link.target = LinkTargetStringMap[PDFJS.externalLinkTarget]; } // Strip referrer from the URL. if (this.data.url) { link.rel = PDFJS.externalLinkRel; } if (!this.data.url) { if (this.data.action) { this._bindNamedAction(link, this.data.action); } else { this._bindLink(link, ('dest' in this.data) ? this.data.dest : null); } } this.container.appendChild(link); return this.container; }, /** * Bind internal links to the link element. * * @private * @param {Object} link * @param {Object} destination * @memberof LinkAnnotationElement */ _bindLink: function LinkAnnotationElement_bindLink(link, destination) { var self = this; link.href = this.linkService.getDestinationHash(destination); link.onclick = function() { if (destination) { self.linkService.navigateTo(destination); } return false; }; if (destination) { link.className = 'internalLink'; } }, /** * Bind named actions to the link element. * * @private * @param {Object} link * @param {Object} action * @memberof LinkAnnotationElement */ _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) { var self = this; link.href = this.linkService.getAnchorUrl(''); link.onclick = function() { self.linkService.executeNamedAction(action); return false; }; link.className = 'internalLink'; } }); return LinkAnnotationElement; })(); /** * @class * @alias TextAnnotationElement */ var TextAnnotationElement = (function TextAnnotationElementClosure() { function TextAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(TextAnnotationElement, AnnotationElement, { /** * Render the text annotation's HTML element in the empty container. * * @public * @memberof TextAnnotationElement * @returns {HTMLSectionElement} */ render: function TextAnnotationElement_render() { this.container.className = 'textAnnotation'; var image = document.createElement('img'); image.style.height = this.container.style.height; image.style.width = this.container.style.width; image.src = PDFJS.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: this.data.name}); if (!this.data.hasPopup) { var popupElement = new PopupElement({ container: this.container, trigger: image, color: this.data.color, title: this.data.title, contents: this.data.contents, hideWrapper: true }); var popup = popupElement.render(); // Position the popup next to the Text annotation's container. popup.style.left = image.style.width; this.container.appendChild(popup); } this.container.appendChild(image); return this.container; } }); return TextAnnotationElement; })(); /** * @class * @alias WidgetAnnotationElement */ var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() { function WidgetAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(WidgetAnnotationElement, AnnotationElement, { /** * Render the widget annotation's HTML element in the empty container. * * @public * @memberof WidgetAnnotationElement * @returns {HTMLSectionElement} */ render: function WidgetAnnotationElement_render() { var content = document.createElement('div'); content.textContent = this.data.fieldValue; var textAlignment = this.data.textAlignment; content.style.textAlign = ['left', 'center', 'right'][textAlignment]; content.style.verticalAlign = 'middle'; content.style.display = 'table-cell'; var font = (this.data.fontRefName ? this.page.commonObjs.getData(this.data.fontRefName) : null); this._setTextStyle(content, font); this.container.appendChild(content); return this.container; }, /** * Apply text styles to the text in the element. * * @private * @param {HTMLDivElement} element * @param {Object} font * @memberof WidgetAnnotationElement */ _setTextStyle: function WidgetAnnotationElement_setTextStyle(element, font) { // TODO: This duplicates some of the logic in CanvasGraphics.setFont(). var style = element.style; style.fontSize = this.data.fontSize + 'px'; style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr'); if (!font) { return; } style.fontWeight = (font.black ? (font.bold ? '900' : 'bold') : (font.bold ? 'bold' : 'normal')); style.fontStyle = (font.italic ? 'italic' : 'normal'); // Use a reasonable default font if the font doesn't specify a fallback. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : ''; var fallbackName = font.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } }); return WidgetAnnotationElement; })(); /** * @class * @alias PopupAnnotationElement */ var PopupAnnotationElement = (function PopupAnnotationElementClosure() { function PopupAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(PopupAnnotationElement, AnnotationElement, { /** * Render the popup annotation's HTML element in the empty container. * * @public * @memberof PopupAnnotationElement * @returns {HTMLSectionElement} */ render: function PopupAnnotationElement_render() { this.container.className = 'popupAnnotation'; var selector = '[data-annotation-id="' + this.data.parentId + '"]'; var parentElement = this.layer.querySelector(selector); if (!parentElement) { return this.container; } var popup = new PopupElement({ container: this.container, trigger: parentElement, color: this.data.color, title: this.data.title, contents: this.data.contents }); // Position the popup next to the parent annotation's container. // PDF viewers ignore a popup annotation's rectangle. var parentLeft = parseFloat(parentElement.style.left); var parentWidth = parseFloat(parentElement.style.width); CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top); this.container.style.left = (parentLeft + parentWidth) + 'px'; this.container.appendChild(popup.render()); return this.container; } }); return PopupAnnotationElement; })(); /** * @class * @alias PopupElement */ var PopupElement = (function PopupElementClosure() { var BACKGROUND_ENLIGHT = 0.7; function PopupElement(parameters) { this.container = parameters.container; this.trigger = parameters.trigger; this.color = parameters.color; this.title = parameters.title; this.contents = parameters.contents; this.hideWrapper = parameters.hideWrapper || false; this.pinned = false; } PopupElement.prototype = /** @lends PopupElement.prototype */ { /** * Render the popup's HTML element. * * @public * @memberof PopupElement * @returns {HTMLSectionElement} */ render: function PopupElement_render() { var wrapper = document.createElement('div'); wrapper.className = 'popupWrapper'; // For Popup annotations we hide the entire section because it contains // only the popup. However, for Text annotations without a separate Popup // annotation, we cannot hide the entire container as the image would // disappear too. In that special case, hiding the wrapper suffices. this.hideElement = (this.hideWrapper ? wrapper : this.container); this.hideElement.setAttribute('hidden', true); var popup = document.createElement('div'); popup.className = 'popup'; var color = this.color; if (color) { // Enlighten the color. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0); } var contents = this._formatContents(this.contents); var title = document.createElement('h1'); title.textContent = this.title; // Attach the event listeners to the trigger element. this.trigger.addEventListener('click', this._toggle.bind(this)); this.trigger.addEventListener('mouseover', this._show.bind(this, false)); this.trigger.addEventListener('mouseout', this._hide.bind(this, false)); popup.addEventListener('click', this._hide.bind(this, true)); popup.appendChild(title); popup.appendChild(contents); wrapper.appendChild(popup); return wrapper; }, /** * Format the contents of the popup by adding newlines where necessary. * * @private * @param {string} contents * @memberof PopupElement * @returns {HTMLParagraphElement} */ _formatContents: function PopupElement_formatContents(contents) { var p = document.createElement('p'); var lines = contents.split(/(?:\r\n?|\n)/); for (var i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; p.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { p.appendChild(document.createElement('br')); } } return p; }, /** * Toggle the visibility of the popup. * * @private * @memberof PopupElement */ _toggle: function PopupElement_toggle() { if (this.pinned) { this._hide(true); } else { this._show(true); } }, /** * Show the popup. * * @private * @param {boolean} pin * @memberof PopupElement */ _show: function PopupElement_show(pin) { if (pin) { this.pinned = true; } if (this.hideElement.hasAttribute('hidden')) { this.hideElement.removeAttribute('hidden'); this.container.style.zIndex += 1; } }, /** * Hide the popup. * * @private * @param {boolean} unpin * @memberof PopupElement */ _hide: function PopupElement_hide(unpin) { if (unpin) { this.pinned = false; } if (!this.hideElement.hasAttribute('hidden') && !this.pinned) { this.hideElement.setAttribute('hidden', true); this.container.style.zIndex -= 1; } } }; return PopupElement; })(); /** * @class * @alias HighlightAnnotationElement */ var HighlightAnnotationElement = ( function HighlightAnnotationElementClosure() { function HighlightAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(HighlightAnnotationElement, AnnotationElement, { /** * Render the highlight annotation's HTML element in the empty container. * * @public * @memberof HighlightAnnotationElement * @returns {HTMLSectionElement} */ render: function HighlightAnnotationElement_render() { this.container.className = 'highlightAnnotation'; return this.container; } }); return HighlightAnnotationElement; })(); /** * @class * @alias UnderlineAnnotationElement */ var UnderlineAnnotationElement = ( function UnderlineAnnotationElementClosure() { function UnderlineAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(UnderlineAnnotationElement, AnnotationElement, { /** * Render the underline annotation's HTML element in the empty container. * * @public * @memberof UnderlineAnnotationElement * @returns {HTMLSectionElement} */ render: function UnderlineAnnotationElement_render() { this.container.className = 'underlineAnnotation'; return this.container; } }); return UnderlineAnnotationElement; })(); /** * @class * @alias SquigglyAnnotationElement */ var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() { function SquigglyAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(SquigglyAnnotationElement, AnnotationElement, { /** * Render the squiggly annotation's HTML element in the empty container. * * @public * @memberof SquigglyAnnotationElement * @returns {HTMLSectionElement} */ render: function SquigglyAnnotationElement_render() { this.container.className = 'squigglyAnnotation'; return this.container; } }); return SquigglyAnnotationElement; })(); /** * @class * @alias StrikeOutAnnotationElement */ var StrikeOutAnnotationElement = ( function StrikeOutAnnotationElementClosure() { function StrikeOutAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(StrikeOutAnnotationElement, AnnotationElement, { /** * Render the strikeout annotation's HTML element in the empty container. * * @public * @memberof StrikeOutAnnotationElement * @returns {HTMLSectionElement} */ render: function StrikeOutAnnotationElement_render() { this.container.className = 'strikeoutAnnotation'; return this.container; } }); return StrikeOutAnnotationElement; })(); /** * @typedef {Object} AnnotationLayerParameters * @property {PageViewport} viewport * @property {HTMLDivElement} div * @property {Array} annotations * @property {PDFPage} page * @property {IPDFLinkService} linkService */ /** * @class * @alias AnnotationLayer */ var AnnotationLayer = (function AnnotationLayerClosure() { return { /** * Render a new annotation layer with all annotation elements. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ render: function AnnotationLayer_render(parameters) { var annotationElementFactory = new AnnotationElementFactory(); for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; if (!data || !data.hasHtml) { continue; } var properties = { data: data, layer: parameters.div, page: parameters.page, viewport: parameters.viewport, linkService: parameters.linkService }; var element = annotationElementFactory.create(properties); parameters.div.appendChild(element.render()); } }, /** * Update the annotation elements on existing annotation layer. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ update: function AnnotationLayer_update(parameters) { for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; var element = parameters.div.querySelector( '[data-annotation-id="' + data.id + '"]'); if (element) { CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')'); } } parameters.div.removeAttribute('hidden'); } }; })(); PDFJS.AnnotationLayer = AnnotationLayer; exports.AnnotationLayer = AnnotationLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, sharedGlobal) { var assert = sharedUtil.assert; var bytesToString = sharedUtil.bytesToString; var string32 = sharedUtil.string32; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var isWorker = sharedGlobal.isWorker; function FontLoader(docId) { this.docId = docId; this.styleElement = null; this.nativeFontFaces = []; this.loadTestFontId = 0; this.loadingContext = { requests: [], nextRequestId: 0 }; } FontLoader.prototype = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = this.styleElement; if (!styleElement) { styleElement = this.styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = this.styleElement; if (styleElement) { styleElement.parentNode.removeChild(styleElement); styleElement = this.styleElement = null; } this.nativeFontFaces.forEach(function(nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }, bind: function fontLoaderBind(fonts, callback) { assert(!isWorker, 'bind() shall be called from main thread'); var rules = []; var fontsToLoad = []; var fontLoadPromises = []; var getNativeFontPromise = function(nativeFontFace) { // Return a promise that is always fulfilled, even when the font fails to // load. return nativeFontFace.loaded.catch(function(e) { warn('Failed to load font "' + nativeFontFace.family + '": ' + e); }); }; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; if (FontLoader.isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { this.addNativeFontFace(nativeFontFace); fontLoadPromises.push(getNativeFontPromise(nativeFontFace)); } } else { var rule = font.createFontFaceRule(); if (rule) { this.insertRule(rule); rules.push(rule); fontsToLoad.push(font); } } } var request = this.queueLoadingCallback(callback); if (FontLoader.isFontLoadingAPISupported) { Promise.all(fontLoadPromises).then(function() { request.complete(); }); } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) { this.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = this.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; this.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; FontLoader.isFontLoadingAPISupported = (!isWorker && typeof document !== 'undefined' && !!document.fonts); Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', { get: function () { var supported = false; // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var userAgent = window.navigator.userAgent; var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent); if (m && m[1] >= 14) { supported = true; } // TODO other browsers if (userAgent === 'node') { supported = true; } return shadow(FontLoader, 'isSyncFontLoadingSupported', supported); }, enumerable: true, configurable: true }); var FontFaceObject = (function FontFaceObjectClosure() { function FontFaceObject(translatedData) { this.compiledGlyphs = {}; // importing translated data for (var i in translatedData) { this[i] = translatedData[i]; } } Object.defineProperty(FontFaceObject, 'isEvalSupported', { get: function () { var evalSupport = false; if (PDFJS.isEvalSupported) { try { /* jshint evil: true */ new Function(''); evalSupport = true; } catch (e) {} } return shadow(this, 'isEvalSupported', evalSupport); }, enumerable: true, configurable: true }); FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this); } return nativeFontFace; }, createFontFaceRule: function FontFaceObject_createFontFaceRule() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + window.btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this, url); } return rule; }, getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var cmds = objs.get(this.loadedName + '_path_' + character); var current, i, len; // If we can, compile cmds into JS for MAXIMUM SPEED if (FontFaceObject.isEvalSupported) { var args, js = ''; for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.args !== undefined) { args = current.args.join(','); } else { args = ''; } js += 'c.' + current.cmd + '(' + args + ');\n'; } /* jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } else { // But fall back on using Function.prototype.apply() if we're // blocked from using eval() for whatever reason (like CSP policies) this.compiledGlyphs[character] = function(c, size) { for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.cmd === 'scale') { current.args = [size, -size]; } c[current.cmd].apply(c, current.args); } }; } } return this.compiledGlyphs[character]; } }; return FontFaceObject; })(); exports.FontFaceObject = FontFaceObject; exports.FontLoader = FontLoader; })); (function (root, factory) { { factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var error = sharedUtil.error; var Metadata = PDFJS.Metadata = (function MetadataClosure() { function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = {}; this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; return Metadata; })(); exports.Metadata = Metadata; })); (function (root, factory) { { factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var Util = sharedUtil.Util; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var warn = sharedUtil.warn; var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = (function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); } else { c = (c >> 1) & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = (crc >>> 8) ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } function encode(imgData, kind) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = (width + 7) >> 3; break; case ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } // prefix every row with predictor 0 var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; // no prediction literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === ImageKind.GRAYSCALE_1BPP) { // inverting for B/W offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; // skipping predictor for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([ width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, // bit depth colorType, // color type 0x00, // compression method 0x00, // filter method 0x00 // interlace method ]); var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; // compression method and flags idat[pi++] = 0x9c; // flags var pos = 0; while (len > maxBlockLength) { // writing non-final DEFLATE blocks type 0 and length of 65535 idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } // writing non-final DEFLATE blocks type 0 idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = (~len & 0xffff) & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); // checksum idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; // PNG will consists: header, IHDR+data, IDAT+data, and IEND. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return PDFJS.createObjectURL(data, 'image/png'); } return function convertImgDataToPng(imgData) { var kind = (imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind); return encode(imgData, kind); }; })(); var SVGExtraState = (function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; // Default foreground and background colors this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; // Clipping this.clipId = ''; this.pendingClip = false; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; })(); var SVGGraphics = (function SVGGraphicsClosure() { function createScratchSVG(width, height) { var NS = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(NS, 'svg:svg'); svg.setAttributeNS(null, 'version', '1.1'); svg.setAttributeNS(null, 'width', width + 'px'); svg.setAttributeNS(null, 'height', height + 'px'); svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height); return svg; } function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({'fnId': 92, 'fn': 'group', 'items': []}); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if(opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } /** * Formats float number. * @param value {number} number to format. * @returns {string} */ function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } /** * Formats transform matrix. The standard rotation, scale and translate * matrices are replaced by their shorter forms, and for identity matrix * returns empty string to save the memory. * @param m {Array} matrix to format. * @returns {string} */ function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs) { this.current = new SVGExtraState(); this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = {}; this.cssStyle = null; } var NS = 'http://www.w3.org/2000/svg'; var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.pgrp.appendChild(this.tgrp); }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; var self = this; for (var i = 0; i < fnArrayLen; i++) { if (OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function(resolve) { self.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function(resolve) { self.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = PDFJS.Util.transform(this.transformMatrix, transformMatrix); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { this.svg = createScratchSVG(viewport.width, viewport.height); this.viewport = viewport; return this.loadDependencies(operatorList).then(function () { this.transformMatrix = IDENTITY_MATRIX; this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform)); this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.defs = document.createElementNS(NS, 'svg:defs'); this.pgrp.appendChild(this.defs); this.pgrp.appendChild(this.tgrp); this.svg.appendChild(this.pgrp); var opTree = this.convertOpList(operatorList); this.executeOpTree(opTree); return this.svg; }.bind(this)); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in OPS) { REVOPS[OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]}); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for(var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case OPS.beginText: this.beginText(); break; case OPS.setLeading: this.setLeading(args); break; case OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case OPS.setFont: this.setFont(args); break; case OPS.showText: this.showText(args[0]); break; case OPS.showSpacedText: this.showText(args[0]); break; case OPS.endText: this.endText(); break; case OPS.moveText: this.moveText(args[0], args[1]); break; case OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case OPS.setHScale: this.setHScale(args[0]); break; case OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setLineWidth: this.setLineWidth(args[0]); break; case OPS.setLineJoin: this.setLineJoin(args[0]); break; case OPS.setLineCap: this.setLineCap(args[0]); break; case OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case OPS.setDash: this.setDash(args[0], args[1]); break; case OPS.setGState: this.setGState(args[0]); break; case OPS.fill: this.fill(); break; case OPS.eoFill: this.eoFill(); break; case OPS.stroke: this.stroke(); break; case OPS.fillStroke: this.fillStroke(); break; case OPS.eoFillStroke: this.eoFillStroke(); break; case OPS.clip: this.clip('nonzero'); break; case OPS.eoClip: this.clip('evenodd'); break; case OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case OPS.closePath: this.closePath(); break; case OPS.closeStroke: this.closeStroke(); break; case OPS.closeFillStroke: this.closeFillStroke(); break; case OPS.nextLine: this.nextLine(); break; case OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.constructPath: this.constructPath(args[0], args[1]); break; case OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: warn('Unimplemented method '+ fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = document.createElementNS(NS, 'svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = IDENTITY_MATRIX; this.current.lineMatrix = IDENTITY_MATRIX; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.txtElement = document.createElementNS(NS, 'svg:text'); this.current.txtgrp = document.createElementNS(NS, 'svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } current.xcoords.push(current.x + x * textHScale); var width = glyph.width; var character = glyph.fontChar; var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; current.tspan.textContent += character; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)' ); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this.tgrp.appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = document.createElementNS(NS, 'svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() { if (this.current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, // Path properties setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = document.createElementNS(NS, 'svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x) , pf(y)); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.path.setAttributeNS(null, 'fill', 'none'); this.tgrp.appendChild(current.path); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } // Saving a reference in current.element so that it can be addressed // in 'fill' and 'stroke' current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { var current = this.current; if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, clip: function SVGGraphics_clip(type) { var current = this.current; // Add current path to clipping path current.clipId = 'clippath' + clipCount; clipCount++; this.clippath = document.createElementNS(NS, 'svg:clipPath'); this.clippath.setAttributeNS(null, 'id', current.clipId); var clipElement = current.element.cloneNode(); if (type === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.clippath.appendChild(clipElement); this.defs.appendChild(this.clippath); // Create a new group with that attribute current.pendingClip = true; this.cgrp = document.createElementNS(NS, 'svg:g'); this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')'); this.pgrp.appendChild(this.cgrp); }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': break; case 'FL': break; case 'Font': this.setFont(value); break; case 'CA': break; case 'ca': break; case 'BM': break; case 'SMask': break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); }, fillStroke: function SVGGraphics_fillStroke() { // Order is important since stroke wants fill to be none. // First stroke, then if fill needed, it will be overwritten. this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this.tgrp.appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var current = this.current; var imgObj = this.objs.get(objId); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', imgObj.width + 'px'); imgEl.setAttributeNS(null, 'height', imgObj.height + 'px'); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this.tgrp.appendChild(imgEl); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var current = this.current; var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData); var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); current.element = cliprect; this.clip('nonzero'); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this.tgrp.appendChild(imgEl); } if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = document.createElementNS(NS, 'svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')'); this.defs.appendChild(mask); this.tgrp.appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); if (isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() { this.restore(); } }; return SVGGraphics; })(); PDFJS.SVGGraphics = SVGGraphics; exports.SVGGraphics = SVGGraphics; })); (function (root, factory) { { factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, displayDOMUtils, sharedGlobal) { var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var CustomStyle = displayDOMUtils.CustomStyle; var PDFJS = sharedGlobal.PDFJS; /** * Text layer render parameters. * * @typedef {Object} TextLayerRenderParameters * @property {TextContent} textContent - Text content to render (the object is * returned by the page's getTextContent() method). * @property {HTMLElement} container - HTML element that will contain text runs. * @property {PDFJS.PageViewport} viewport - The target viewport to properly * layout the text runs. * @property {Array} textDivs - (optional) HTML elements that are correspond * the text items of the textContent input. This is output and shall be * initially be set to empty array. * @property {number} timeout - (optional) Delay in milliseconds before * rendering of the text runs occurs. */ var renderTextLayer = (function renderTextLayerClosure() { var MAX_TEXT_DIVS_TO_RENDER = 100000; var NonWhitespaceRegexp = /\S/; function isAllWhitespace(str) { return !NonWhitespaceRegexp.test(str); } function appendText(textDivs, viewport, geom, styles) { var style = styles[geom.fontName]; var textDiv = document.createElement('div'); textDivs.push(textDiv); if (isAllWhitespace(geom.str)) { textDiv.dataset.isWhitespace = true; return; } var tx = Util.transform(viewport.transform, geom.transform); var angle = Math.atan2(tx[1], tx[0]); if (style.vertical) { angle += Math.PI / 2; } var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3])); var fontAscent = fontHeight; if (style.ascent) { fontAscent = style.ascent * fontAscent; } else if (style.descent) { fontAscent = (1 + style.descent) * fontAscent; } var left; var top; if (angle === 0) { left = tx[4]; top = tx[5] - fontAscent; } else { left = tx[4] + (fontAscent * Math.sin(angle)); top = tx[5] - (fontAscent * Math.cos(angle)); } textDiv.style.left = left + 'px'; textDiv.style.top = top + 'px'; textDiv.style.fontSize = fontHeight + 'px'; textDiv.style.fontFamily = style.fontFamily; textDiv.textContent = geom.str; // |fontName| is only used by the Font Inspector. This test will succeed // when e.g. the Font Inspector is off but the Stepper is on, but it's // not worth the effort to do a more accurate test. if (PDFJS.pdfBug) { textDiv.dataset.fontName = geom.fontName; } // Storing into dataset will convert number into string. if (angle !== 0) { textDiv.dataset.angle = angle * (180 / Math.PI); } // We don't bother scaling single-char text divs, because it has very // little effect on text highlighting. This makes scrolling on docs with // lots of such divs a lot faster. if (geom.str.length > 1) { if (style.vertical) { textDiv.dataset.canvasWidth = geom.height * viewport.scale; } else { textDiv.dataset.canvasWidth = geom.width * viewport.scale; } } } function render(task) { if (task._canceled) { return; } var textLayerFrag = task._container; var textDivs = task._textDivs; var capability = task._capability; var textDivsLength = textDivs.length; // No point in rendering many divs as it would make the browser // unusable even after the divs are rendered. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { capability.resolve(); return; } var canvas = document.createElement('canvas'); canvas.mozOpaque = true; var ctx = canvas.getContext('2d', {alpha: false}); var lastFontSize; var lastFontFamily; for (var i = 0; i < textDivsLength; i++) { var textDiv = textDivs[i]; if (textDiv.dataset.isWhitespace !== undefined) { continue; } var fontSize = textDiv.style.fontSize; var fontFamily = textDiv.style.fontFamily; // Only build font string and set to context if different from last. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) { ctx.font = fontSize + ' ' + fontFamily; lastFontSize = fontSize; lastFontFamily = fontFamily; } var width = ctx.measureText(textDiv.textContent).width; if (width > 0) { textLayerFrag.appendChild(textDiv); var transform; if (textDiv.dataset.canvasWidth !== undefined) { // Dataset values come of type string. var textScale = textDiv.dataset.canvasWidth / width; transform = 'scaleX(' + textScale + ')'; } else { transform = ''; } var rotation = textDiv.dataset.angle; if (rotation) { transform = 'rotate(' + rotation + 'deg) ' + transform; } if (transform) { CustomStyle.setProp('transform' , textDiv, transform); } } } capability.resolve(); } /** * Text layer rendering task. * * @param {TextContent} textContent * @param {HTMLElement} container * @param {PDFJS.PageViewport} viewport * @param {Array} textDivs * @private */ function TextLayerRenderTask(textContent, container, viewport, textDivs) { this._textContent = textContent; this._container = container; this._viewport = viewport; textDivs = textDivs || []; this._textDivs = textDivs; this._canceled = false; this._capability = createPromiseCapability(); this._renderTimer = null; } TextLayerRenderTask.prototype = { get promise() { return this._capability.promise; }, cancel: function TextLayer_cancel() { this._canceled = true; if (this._renderTimer !== null) { clearTimeout(this._renderTimer); this._renderTimer = null; } this._capability.reject('canceled'); }, _render: function TextLayer_render(timeout) { var textItems = this._textContent.items; var styles = this._textContent.styles; var textDivs = this._textDivs; var viewport = this._viewport; for (var i = 0, len = textItems.length; i < len; i++) { appendText(textDivs, viewport, textItems[i], styles); } if (!timeout) { // Render right away render(this); } else { // Schedule var self = this; this._renderTimer = setTimeout(function() { render(self); self._renderTimer = null; }, timeout); } } }; /** * Starts rendering of the text layer. * * @param {TextLayerRenderParameters} renderParameters * @returns {TextLayerRenderTask} */ function renderTextLayer(renderParameters) { var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs); task._render(renderParameters.timeout); return task; } return renderTextLayer; })(); PDFJS.renderTextLayer = renderTextLayer; exports.renderTextLayer = renderTextLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var shadow = sharedUtil.shadow; var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[j]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if (PDFJS.disableWebGL) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); exports.WebGLUtils = WebGLUtils; })); (function (root, factory) { { factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayWebGL) { var Util = sharedUtil.Util; var info = sharedUtil.info; var isArray = sharedUtil.isArray; var error = sharedUtil.error; var WebGLUtils = displayWebGL.WebGLUtils; var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); tmpCanvas.context.drawImage(canvas, 0, 0); canvas = tmpCanvas.canvas; } else { tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, 0, 0); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { //var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; //var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { // Obtain scale from matrix and current transformation matrix. scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.canvasGraphicsFactory = canvasGraphicsFactory; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var canvasGraphicsFactory = this.canvasGraphicsFactory; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); exports.getShadingPatternFromIR = getShadingPatternFromIR; exports.TilingPattern = TilingPattern; })); (function (root, factory) { { factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayPatternHelper, displayWebGL) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var TextRenderingMode = sharedUtil.TextRenderingMode; var Uint32ArrayView = sharedUtil.Uint32ArrayView; var Util = sharedUtil.Util; var assert = sharedUtil.assert; var info = sharedUtil.info; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var error = sharedUtil.error; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; var TilingPattern = displayPatternHelper.TilingPattern; var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR; var WebGLUtils = displayWebGL.WebGLUtils; // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; // Maximum font size that would be used during canvas fillText operations. var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; // Heuristic value used when enforcing minimum line widths. var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based one. if (!ctx.mozCurrentTransform) { ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { function CachedCanvases() { this.cache = Object.create(null); } CachedCanvases.prototype = { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (this.cache[id] !== undefined) { canvasEntry = this.cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } this.cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { for (var id in this.cache) { var canvasEntry = this.cache[id]; // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. canvasEntry.canvas.width = 0; canvasEntry.canvas.height = 0; delete this.cache[id]; } } }; return CachedCanvases; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; // Defines the number of steps before checking the execution time var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; this.cachedCanvases = new CachedCanvases(); if (canvasCtx) { // NOTE: if mozCurrentTransform is polyfilled, then the current state of // the transformation must already be set in canvasCtx._transformMatrix. addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var srcLength = src.byteLength; var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } else if (sourceCtx.mozDashOffset !== undefined) { destCtx.mozDash = sourceCtx.mozDash; destCtx.mozDashOffset = sourceCtx.mozDashOffset; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8; } } } function composeSMaskAlpha(maskData, layerData, transferMap) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; layerData[i] = (layerData[i] * alpha * scale) | 0; } } function composeSMaskLuminosity(maskData, layerData, transferMap) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskData[i - 2] * 152) + // * 0.59 .... (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = transferMap ? (layerData[i] * transferMap[y >> 8]) >> 8 : (layerData[i] * y) >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data, transferMap); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (!smask.transferMap && WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, creating temporary // transparent canvas when we have blend modes. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); if (transparency) { var transparentCanvas = this.cachedCanvases.getCanvas( 'transparent', width, height, true); this.compositeCtx = this.ctx; this.transparentCanvas = transparentCanvas.canvas; this.ctx = transparentCanvas.context; this.ctx.save(); // The transform can be applied before rendering, transferring it to // the new canvas. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); } this.ctx.save(); if (transform) { this.ctx.transform.apply(this.ctx, transform); } this.ctx.transform.apply(this.ctx, viewport.transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen === i) { return i; } var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'); var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i === argsArrayLen) { return i; } // If the execution took longer then a certain amount of time and // `continueCallback` is specified, interrupt the execution. if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { this.ctx.restore(); if (this.transparentCanvas) { this.ctx = this.compositeCtx; this.ctx.drawImage(this.transparentCanvas, 0, 0); this.transparentCanvas = null; } this.cachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { this.endSMaskGroup(); } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); copyCtxState(groupCtx, this.ctx); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.activeSMask = null; }, restore: function CanvasGraphics_restore() { if (this.stateStack.length !== 0) { if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.current = this.stateStack.pop(); this.ctx.restore(); // Ensure that the clipping path is reset (fixes issue6413.pdf). this.pendingClip = null; this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, // Path constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; // Prevent drawing too thin lines by enforcing a minimum line width. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); if (this.baseTransform) { ctx.setTransform.apply(ctx, this.baseTransform); } ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.fill(); ctx.mozFillRule = 'nonzero'; } else { ctx.fill('evenodd'); } this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var spacingDir = vertical ? 1 : -1; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (current.patternFill) { // TODO: Some shading patterns are not applied correctly to text, // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf. ctx.fillStyle = current.fillColor.getPattern(ctx, this); } if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (isNum(glyph)) { x += spacingDir * glyph * fontSize / 1000; continue; } var restoreNeeded = false; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0) { // Some standard fonts may not have the exact width: rescale per // character if measured width is greater than expected glyph width // and subpixel-aa is enabled, otherwise just center the glyph. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; if (width < measuredWidth && this.isFontSubpixelAAEnabled) { var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } else if (width !== measuredWidth) { scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; } } if (simpleFillText && !accent) { // common case ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } var charWidth = width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { // Type3 fonts - each glyph is a "mini-PDF" var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var spacingDir = font.vertical ? 1 : -1; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width, spacingLength; if (isTextInvisible || fontSize === 0) { return; } this.cachedGetSinglePixelWidth = null; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (isNum(glyph)) { spacingLength = spacingDir * glyph * fontSize / 1000; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { warn('Type3 character \"' + glyph.operatorListId + '\" is not available'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + spacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); var self = this; var canvasGraphicsFactory = { createCanvasGraphics: function (ctx) { return new CanvasGraphics(ctx, self.commonObjs, self.objs); } }; pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (isArray(matrix) && 6 === matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (isArray(bbox) && 4 === bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implmenting: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, transferMap: group.smask.transferMap || null }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); if (this.baseTransform) { this.ctx.setTransform.apply(this.ctx, this.baseTransform); } }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (isArray(rect) && 4 === rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, paintXObject: function CanvasGraphics_paintXObject() { warn('Unsupported \'paintXObject\' command.'); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.clip(); ctx.mozFillRule = 'nonzero'; } else { ctx.clip('evenodd'); } } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { var inverse = this.ctx.mozCurrentTransformInverse; // max of the current horizontal and vertical scale this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); exports.CanvasGraphics = CanvasGraphics; exports.createScratchCanvas = createScratchCanvas; })); (function (root, factory) { { factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, sharedGlobal, amdRequire) { var InvalidPDFException = sharedUtil.InvalidPDFException; var MessageHandler = sharedUtil.MessageHandler; var MissingPDFException = sharedUtil.MissingPDFException; var PasswordResponses = sharedUtil.PasswordResponses; var PasswordException = sharedUtil.PasswordException; var StatTimer = sharedUtil.StatTimer; var UnexpectedResponseException = sharedUtil.UnexpectedResponseException; var UnknownErrorException = sharedUtil.UnknownErrorException; var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var combineUrl = sharedUtil.combineUrl; var error = sharedUtil.error; var deprecated = sharedUtil.deprecated; var info = sharedUtil.info; var isArrayBuffer = sharedUtil.isArrayBuffer; var loadJpegStream = sharedUtil.loadJpegStream; var stringToBytes = sharedUtil.stringToBytes; var warn = sharedUtil.warn; var FontFaceObject = displayFontLoader.FontFaceObject; var FontLoader = displayFontLoader.FontLoader; var CanvasGraphics = displayCanvas.CanvasGraphics; var createScratchCanvas = displayCanvas.createScratchCanvas; var Metadata = displayMetadata.Metadata; var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536 var useRequireEnsure = false; if (typeof module !== 'undefined' && module.require) { // node.js - disable worker and set require.ensure. PDFJS.disableWorker = true; if (typeof require.ensure === 'undefined') { require.ensure = require('node-ensure'); } useRequireEnsure = true; } if (typeof __webpack_require__ !== 'undefined') { // Webpack - get/bundle pdf.worker.js as additional file. PDFJS.workerSrc = require('entry?name=[hash]-worker.js!./pdf.worker.js'); useRequireEnsure = true; } if (typeof requirejs !== 'undefined' && requirejs.toUrl) { PDFJS.workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js'); } var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) { require.ensure([], function () { require('./pdf.worker.js'); callback(); }); }) : (typeof requirejs !== 'undefined') ? (function (callback) { requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) { callback(); }); }) : null; /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /** * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font renderer * that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will happen * automatically if the browser doesn't support workers or sending typed arrays * to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled in * development mode. If unspecified in the production build, the worker will be * loaded based on the location of the pdf.js file. It is recommended that * the workerSrc is set in a custom application to prevent issues caused by * third-party frameworks and libraries. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable streaming of PDF file data. By default PDF.js attempts to load PDF * in chunks. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableStream = (PDFJS.disableStream === undefined ? false : PDFJS.disableStream); /** * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js * will automatically keep fetching more data even if it isn't needed to display * the current page. This default behavior can be disabled. * * NOTE: It is also necessary to disable streaming, see above, * in order for disabling of pre-fetching to work correctly. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Disables fullscreen support, and by extension Presentation Mode, * in browsers which support the fullscreen API. * @var {boolean} */ PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen); /** * Enables CSS only zooming. * @var {boolean} */ PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom); /** * Controls the logging level. * The constants from PDFJS.VERBOSITY_LEVELS should be used: * - errors * - warnings [default] * - infos * @var {number} */ PDFJS.verbosity = (PDFJS.verbosity === undefined ? PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity); /** * The maximum supported canvas size in total pixels e.g. width * height. * The default value is 4096 * 4096. Use -1 for no limit. * @var {number} */ PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels); /** * (Deprecated) Opens external links in a new window if enabled. * The default behavior opens external links in the PDF.js window. * * NOTE: This property has been deprecated, please use * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead. * @var {boolean} */ PDFJS.openExternalLinksInNewWindow = ( PDFJS.openExternalLinksInNewWindow === undefined ? false : PDFJS.openExternalLinksInNewWindow); /** * Specifies the |target| attribute for external links. * The constants from PDFJS.LinkTarget should be used: * - NONE [default] * - SELF * - BLANK * - PARENT * - TOP * @var {number} */ PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ? PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget); /** * Specifies the |rel| attribute for external links. Defaults to stripping * the referrer. * @var {string} */ PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel); /** * Determines if we can eval strings as JS. Primarily used to improve * performance for font rendering. * @var {boolean} */ PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported); /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded, * use atob() to convert it to a binary string first. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. * @property {number} length - The PDF file length. It's used for progress * reports and range requests operations. * @property {PDFDataRangeTransport} range * @property {number} rangeChunkSize - Optional parameter to specify * maximum number of bytes fetched per range request. The default value is * 2^16 = 65536. * @property {PDFWorker} worker - The worker that will be used for the loading * and parsing of the PDF data. */ /** * @typedef {Object} PDFDocumentStats * @property {Array} streamTypes - Used stream types in the document (an item * is set to true if specific stream ID was used in the document). * @property {Array} fontTypes - Used font type in the document (an item is set * to true if specific font ID was used in the document). */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src * Can be a url to where a PDF is located, a typed array (Uint8Array) * already populated with data or parameter object. * * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used * if you want to manually serve range requests for data in the PDF. * * @param {function} passwordCallback (deprecated) It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @param {function} progressCallback (deprecated) It is used to be able to * monitor the loading progress of the PDF file (necessary to implement e.g. * a loading bar). The callback receives an {Object} with the properties: * {number} loaded and {number} total. * * @return {PDFDocumentLoadingTask} */ PDFJS.getDocument = function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { var task = new PDFDocumentLoadingTask(); // Support of the obsolete arguments (for compatibility with API v1.0) if (arguments.length > 1) { deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument'); } if (pdfDataRangeTransport) { if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { // Not a PDFDataRangeTransport instance, trying to add missing properties. pdfDataRangeTransport = Object.create(pdfDataRangeTransport); pdfDataRangeTransport.length = src.length; pdfDataRangeTransport.initialData = src.initialData; if (!pdfDataRangeTransport.abort) { pdfDataRangeTransport.abort = function () {}; } } src = Object.create(src); src.range = pdfDataRangeTransport; } task.onPassword = passwordCallback || null; task.onProgress = progressCallback || null; var source; if (typeof src === 'string') { source = { url: src }; } else if (isArrayBuffer(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if (typeof src !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!src.url && !src.data && !src.range) { error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; var rangeTransport = null; var worker = null; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { // The full path is required in the 'url' field. params[key] = combineUrl(window.location.href, source[key]); continue; } else if (key === 'range') { rangeTransport = source[key]; continue; } else if (key === 'worker') { worker = source[key]; continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { // Converting string or array-like data to Uint8Array. var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = stringToBytes(pdfBytes); } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else if (isArrayBuffer(pdfBytes)) { params[key] = new Uint8Array(pdfBytes); } else { error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.'); } continue; } params[key] = source[key]; } params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; if (!worker) { // Worker was not provided -- creating and owning our own. worker = new PDFWorker(); task._worker = worker; } var docId = task.docId; worker.promise.then(function () { if (task.destroyed) { throw new Error('Loading aborted'); } return _fetchDocument(worker, params, rangeTransport, docId).then( function (workerId) { if (task.destroyed) { throw new Error('Loading aborted'); } var messageHandler = new MessageHandler(docId, workerId, worker.port); messageHandler.send('Ready', null); var transport = new WorkerTransport(messageHandler, task, rangeTransport); task._transport = transport; }); }).catch(task._capability.reject); return task; }; /** * Starts fetching of specified PDF document/data. * @param {PDFWorker} worker * @param {Object} source * @param {PDFDataRangeTransport} pdfDataRangeTransport * @param {string} docId Unique document id, used as MessageHandler id. * @returns {Promise} The promise, which is resolved when worker id of * MessageHandler is known. * @private */ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { if (worker.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } source.disableAutoFetch = PDFJS.disableAutoFetch; source.disableStream = PDFJS.disableStream; source.chunkedViewerLoading = !!pdfDataRangeTransport; if (pdfDataRangeTransport) { source.length = pdfDataRangeTransport.length; source.initialData = pdfDataRangeTransport.initialData; } return worker.messageHandler.sendWithPromise('GetDocRequest', { docId: docId, source: source, disableRange: PDFJS.disableRange, maxImageSize: PDFJS.maxImageSize, cMapUrl: PDFJS.cMapUrl, cMapPacked: PDFJS.cMapPacked, disableFontFace: PDFJS.disableFontFace, disableCreateObjectURL: PDFJS.disableCreateObjectURL, verbosity: PDFJS.verbosity }).then(function (workerId) { if (worker.destroyed) { throw new Error('Worker was destroyed'); } return workerId; }); } /** * PDF document loading operation. * @class * @alias PDFDocumentLoadingTask */ var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { var nextDocumentId = 0; /** @constructs PDFDocumentLoadingTask */ function PDFDocumentLoadingTask() { this._capability = createPromiseCapability(); this._transport = null; this._worker = null; /** * Unique document loading task id -- used in MessageHandlers. * @type {string} */ this.docId = 'd' + (nextDocumentId++); /** * Shows if loading task is destroyed. * @type {boolean} */ this.destroyed = false; /** * Callback to request a password if wrong or no password was provided. * The callback receives two parameters: function that needs to be called * with new password and reason (see {PasswordResponses}). */ this.onPassword = null; /** * Callback to be able to monitor the loading progress of the PDF file * (necessary to implement e.g. a loading bar). The callback receives * an {Object} with the properties: {number} loaded and {number} total. */ this.onProgress = null; /** * Callback to when unsupported feature is used. The callback receives * an {PDFJS.UNSUPPORTED_FEATURES} argument. */ this.onUnsupportedFeature = null; } PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */ { /** * @return {Promise} */ get promise() { return this._capability.promise; }, /** * Aborts all network requests and destroys worker. * @return {Promise} A promise that is resolved after destruction activity * is completed. */ destroy: function () { this.destroyed = true; var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); return transportDestroyed.then(function () { this._transport = null; if (this._worker) { this._worker.destroy(); this._worker = null; } }.bind(this)); }, /** * Registers callbacks to indicate the document loading completion. * * @param {function} onFulfilled The callback for the loading completion. * @param {function} onRejected The callback for the loading failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; })(); /** * Abstract class to support range requests file loading. * @class * @alias PDFJS.PDFDataRangeTransport * @param {number} length * @param {Uint8Array} initialData */ var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() { function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = createPromiseCapability(); } PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */ { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { this._readyCapability.promise.then(function () { var listeners = this._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }.bind(this)); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { this._readyCapability.promise.then(function () { var listeners = this._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }.bind(this)); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); }, abort: function PDFDataRangeTransport_abort() { } }; return PDFDataRangeTransport; })(); PDFJS.PDFDataRangeTransport = PDFDataRangeTransport; /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class * @alias PDFDocumentProxy */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport, loadingTask) { this.pdfInfo = pdfInfo; this.transport = transport; this.loadingTask = loadingTask; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. * * This can be slow for large documents: use getDestination instead */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @param {string} id The named destination to get. * @return {Promise} A promise that is resolved with all information * of the given named destination. */ getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named attachments to their content. */ getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { return this.transport.getJavaScript(); }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb array, * dest: dest obj, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, /** * @return {Promise} A promise this is resolved with current stats about * document structures (see {@link PDFDocumentStats}). */ getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { return this.loadingTask.destroy(); } }; return PDFDocumentProxy; })(); /** * Page getTextContent parameters. * * @typedef {Object} getTextContentParameters * @param {boolean} normalizeWhitespace - replaces all occurrences of * whitespace with standard spaces (0x20). The default value is `false`. */ /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page annotation parameters. * * @typedef {Object} GetAnnotationsParameters * @param {string} intent - Determines the annotations that will be fetched, * can be either 'display' (viewable annotations) or 'print' * (printable annotations). * If the parameter is omitted, all annotations are fetched. */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {Array} transform - (optional) Additional transform, applied * just before viewport transform. * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (deprecated) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * PDF page operator list. * * @typedef {Object} PDFOperatorList * @property {Array} fnArray - Array containing the operator functions. * @property {Array} argsArray - Array containing the arguments of the * functions. */ /** * Proxy to a PDFPage in the worker thread. * @class * @alias PDFPageProxy */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = !!globalScope.PDFJS.enableStats; this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingCleanup = false; this.intentStates = {}; this.destroyed = false; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0); }, /** * @param {GetAnnotationsParameters} params - Annotation parameters. * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations(params) { var intent = (params && params.intent) || null; if (!this.annotationsPromise || this.annotationsIntent !== intent) { this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent); this.annotationsIntent = intent; } return this.annotationsPromise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingCleanup = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { deprecated('render is used with continueCallback parameter'); renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingCleanup) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingCleanup = true; } self._tryCleanup(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} A promise resolved with an {@link PDFOperatorList} * object that represents page's operator list. */ getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; if (!intentState.opListReadCapability) { var opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = createPromiseCapability(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, /** * @param {getTextContentParameters} params - getTextContent parameters. * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent(params) { var normalizeWhitespace = (params && params.normalizeWhitespace) || false; return this.transport.messageHandler.sendWithPromise('GetTextContent', { pageIndex: this.pageNumber - 1, normalizeWhitespace: normalizeWhitespace, }); }, /** * Destroys page object. */ _destroy: function PDFPageProxy_destroy() { this.destroyed = true; this.transport.pageCache[this.pageIndex] = null; var waitOn = []; Object.keys(this.intentStates).forEach(function(intent) { var intentState = this.intentStates[intent]; intentState.renderTasks.forEach(function(renderTask) { var renderCompleted = renderTask.capability.promise. catch(function () {}); // ignoring failures waitOn.push(renderCompleted); renderTask.cancel(); }); }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; return Promise.all(waitOn); }, /** * Cleans up resources allocated by the page. (deprecated) */ destroy: function() { deprecated('page destroy method, use cleanup() instead'); this.cleanup(); }, /** * Cleans up resources allocated by the page. */ cleanup: function PDFPageProxy_cleanup() { this.pendingCleanup = true; this._tryCleanup(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryCleanup: function PDFPageProxy_tryCleanup() { if (!this.pendingCleanup || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; // TODO Refactor RenderPageRequest to separate rendering // and operator list logic if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryCleanup(); } } }; return PDFPageProxy; })(); /** * PDF.js web worker abstraction, it controls instantiation of PDF documents and * WorkerTransport for them. If creation of a web worker is not possible, * a "fake" worker will be used instead. * @class */ var PDFWorker = (function PDFWorkerClosure() { var nextFakeWorkerId = 0; function getWorkerSrc() { if (PDFJS.workerSrc) { return PDFJS.workerSrc; } if (pdfjsFilePath) { return pdfjsFilePath.replace(/\.js$/i, '.worker.js'); } error('No PDFJS.workerSrc specified'); } // Loads worker code into main thread. function setupFakeWorkerGlobal() { if (!PDFJS.fakeWorkerFilesLoadedCapability) { PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. var loader = fakeWorkerFilesLoader || function (callback) { Util.loadScript(getWorkerSrc(), callback); }; loader(function () { PDFJS.fakeWorkerFilesLoadedCapability.resolve(); }); } return PDFJS.fakeWorkerFilesLoadedCapability.promise; } function PDFWorker(name) { this.name = name; this.destroyed = false; this._readyCapability = createPromiseCapability(); this._port = null; this._webWorker = null; this._messageHandler = null; this._initialize(); } PDFWorker.prototype = /** @lends PDFWorker.prototype */ { get promise() { return this._readyCapability.promise; }, get port() { return this._port; }, get messageHandler() { return this._messageHandler; }, _initialize: function PDFWorker_initialize() { // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fullfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an // Uint8Array as it arrives on the worker. (Chrome added this with v.15.) if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { var workerSrc = getWorkerSrc(); try { // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', 'worker', worker); messageHandler.on('test', function PDFWorker_test(data) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); messageHandler.destroy(); worker.terminate(); return; // worker was destroyed } var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this._messageHandler = messageHandler; this._port = worker; this._webWorker = worker; if (!data.supportTransfers) { PDFJS.postMessageTransfers = false; } this._readyCapability.resolve(); } else { this._setupFakeWorker(); messageHandler.destroy(); worker.terminate(); } }.bind(this)); messageHandler.on('console_log', function (data) { console.log.apply(console, data); }); messageHandler.on('console_error', function (data) { console.error.apply(console, data); }); messageHandler.on('ready', function (data) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); messageHandler.destroy(); worker.terminate(); return; // worker was destroyed } try { sendTest(); } catch (e) { // We need fallback to a faked worker. this._setupFakeWorker(); } }.bind(this)); var sendTest = function () { var testObj = new Uint8Array( [PDFJS.postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } }; // It might take time for worker to initialize (especially when AMD // loader is used). We will try to send test immediately, and then // when 'ready' message will arrive. The worker shall process only // first received 'test'. sendTest(); return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. this._setupFakeWorker(); }, _setupFakeWorker: function PDFWorker_setupFakeWorker() { if (!globalScope.PDFJS.disableWorker) { warn('Setting up fake worker.'); globalScope.PDFJS.disableWorker = true; } setupFakeWorkerGlobal().then(function () { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); return; } // If we don't use a worker, just post/sendMessage to the main thread. var port = { _listeners: [], postMessage: function (obj) { var e = {data: obj}; this._listeners.forEach(function (listener) { listener.call(this, e); }, this); }, addEventListener: function (name, listener) { this._listeners.push(listener); }, removeEventListener: function (name, listener) { var i = this._listeners.indexOf(listener); this._listeners.splice(i, 1); }, terminate: function () {} }; this._port = port; // All fake workers use the same port, making id unique. var id = 'fake' + (nextFakeWorkerId++); // If the main thread is our worker, setup the handling for the // messages -- the main thread sends to it self. var workerHandler = new MessageHandler(id + '_worker', id, port); PDFJS.WorkerMessageHandler.setup(workerHandler, port); var messageHandler = new MessageHandler(id, id + '_worker', port); this._messageHandler = messageHandler; this._readyCapability.resolve(); }.bind(this)); }, /** * Destroys the worker instance. */ destroy: function PDFWorker_destroy() { this.destroyed = true; if (this._webWorker) { // We need to terminate only web worker created resource. this._webWorker.terminate(); this._webWorker = null; } this._port = null; if (this._messageHandler) { this._messageHandler.destroy(); this._messageHandler = null; } } }; return PDFWorker; })(); PDFJS.PDFWorker = PDFWorker; /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) { this.messageHandler = messageHandler; this.loadingTask = loadingTask; this.pdfDataRangeTransport = pdfDataRangeTransport; this.commonObjs = new PDFObjects(); this.fontLoader = new FontLoader(loadingTask.docId); this.destroyed = false; this.destroyCapability = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = createPromiseCapability(); this.setupMessageHandler(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { if (this.destroyCapability) { return this.destroyCapability.promise; } this.destroyed = true; this.destroyCapability = createPromiseCapability(); var waitOn = []; // We need to wait for all renderings to be completed, e.g. // timeout/rAF can take a long time. this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } }); this.pageCache = []; this.pagePromises = []; var self = this; // We also need to wait for the worker to finish its long running tasks. var terminated = this.messageHandler.sendWithPromise('Terminate', null); waitOn.push(terminated); Promise.all(waitOn).then(function () { self.fontLoader.clear(); if (self.pdfDataRangeTransport) { self.pdfDataRangeTransport.abort(); self.pdfDataRangeTransport = null; } if (self.messageHandler) { self.messageHandler.destroy(); self.messageHandler = null; } self.destroyCapability.resolve(); }, this.destroyCapability.reject); return this.destroyCapability.promise; }, setupMessageHandler: function WorkerTransport_setupMessageHandler() { var messageHandler = this.messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); pdfDataRangeTransport.addProgressiveReadListener(function(chunk) { messageHandler.send('OnDataRange', { chunk: chunk }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var loadingTask = this.loadingTask; var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask); this.pdfDocument = pdfDocument; loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportNeedPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject( new InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject( new MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject( new UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject( new UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) { if (this.pdfDataRangeTransport) { this.pdfDataRangeTransport.transportReady(); } }, this); messageHandler.on('StartRenderPage', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; var font; if ('error' in exportedData) { var error = exportedData.error; warn('Error during font loading: ' + error); this.commonObjs.resolve(id, error); break; } else { font = new FontFaceObject(exportedData); } this.fontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { error(data.error); } }, this); messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var featureId = data.featureId; var loadingTask = this.loadingTask; if (loadingTask.onUnsupportedFeature) { loadingTask.onUnsupportedFeature(featureId); } PDFJS.UnsupportedManager.notify(featureId); }, this); messageHandler.on('JpegDecode', function(data) { if (this.destroyed) { return Promise.reject('Worker was terminated'); } var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject( new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height}); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }, this); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { if (pageNumber <= 0 || pageNumber > this.numPages || (pageNumber|0) !== pageNumber) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { if (this.destroyed) { throw new Error('Transport destroyed'); } var page = new PDFPageProxy(pageIndex, pageInfo, this); this.pageCache[pageIndex] = page; return page; }.bind(this)); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex, intent: intent, }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id }); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null). then(function transportMetadata(results) { return { info: results[0], metadata: (results[1] ? new Metadata(results[1]) : null) }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.sendWithPromise('Cleanup', null). then(function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.cleanup(); } } this.commonObjs.clear(); this.fontLoader.clear(); }.bind(this)); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = {}; } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: createPromiseCapability(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = {}; } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class * @alias RenderTask */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ this.onContinue = null; } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Promise for rendering task completion. * @return {Promise} */ get promise() { return this._internalRenderTask.capability.promise; }, /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, /** * Registers callbacks to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.useRequestAnimationFrame = false; this.cancelled = false; this.capability = createPromiseCapability(); this.task = new RenderTask(this); // caching this-bound methods this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); } InternalRenderTask.prototype = { initalizeGraphics: function InternalRenderTask_initalizeGraphics(transparency) { if (this.cancelled) { return; } if (PDFJS.pdfBug && 'StepperManager' in globalScope && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.transform, params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue.call(this.task, this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { if (this.useRequestAnimationFrame) { window.requestAnimationFrame(this._nextBound); } else { Promise.resolve(undefined).then(this._nextBound); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); /** * (Deprecated) Global observer of unsupported feature usages. Use * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance. */ PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead'); listeners.push(cb); }, notify: function (featureId) { for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); exports.getDocument = PDFJS.getDocument; exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFDocumentProxy = PDFDocumentProxy; exports.PDFPageProxy = PDFPageProxy; })); }).call(pdfjsLibs); exports.PDFJS = pdfjsLibs.pdfjsSharedGlobal.PDFJS; exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument; exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport; exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer; exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer; exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle; exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses; exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException; exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException; exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException; }));
sreym/cdnjs
ajax/libs/pdf.js/1.3.177/pdf.js
JavaScript
mit
313,996
var FormData = require('form-data'); function form(obj) { var form = new FormData(); if (obj) { Object.keys(obj).forEach(function (name) { form.append(name, obj[name]); }); } return form; } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = form; //# sourceMappingURL=form.js.map
carmine/northshore
ui/node_modules/popsicle/dist/form.js
JavaScript
apache-2.0
353
if (!self.GLOBAL || self.GLOBAL.isWindow()) { test(() => { assert_equals(document.title, "foo"); }, '<title> exists'); test(() => { assert_equals(document.querySelectorAll("meta[name=timeout][content=long]").length, 1); }, '<meta name=timeout> exists'); } scripts.push('expect-title-meta.js');
scheib/chromium
third_party/blink/web_tests/external/wpt/infrastructure/server/resources/expect-title-meta.js
JavaScript
bsd-3-clause
312
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ /* Network API overview: http://dvcs.w3.org/hg/dap/raw-file/tip/network-api/Overview.html */ var cordova = require('cordova'); module.exports = { var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; getConnectionInfo: function (win, fail, args) { /* bandwidth of type double, readonly The user agent must set the value of the bandwidth attribute to: 0 if the user is currently offline; Infinity if the bandwidth is unknown; an estimation of the current bandwidth in MB/s (Megabytes per seconds) available for communication with the browsing context active document's domain. */ win(connection.bandwidth); }, isMetered: function (win, fail, args) { /* readonly attribute boolean metered A connection is metered when the user's connection is subject to a limitation from his Internet Service Provider strong enough to request web applications to be careful with the bandwidth usage. What is a metered connection is voluntarily left to the user agent to judge. It would not be possible to give an exhaustive list of limitations considered strong enough to flag the connection as metered and even if doable, some limitations can be considered strong or weak depending on the context. Examples of metered connections are mobile connections with a small bandwidth quota or connections with a pay-per use plan. The user agent MUST set the value of the metered attribute to true if the connection with the browsing context active document's domain is metered and false otherwise. If the implementation is not able to know the status of the connection or if the user is offline, the value MUST be set to false. If unable to know if a connection is metered, a user agent could ask the user about the status of his current connection. */ win(connection.metered); } }; require("cordova/firefoxos/commandProxy").add("Network", module.exports);
alejo8591/cyav
unidad-4/testappavantel3/plugins/org.apache.cordova.network-information/src/firefoxos/NetworkProxy.js
JavaScript
mit
2,982
/* * bag.js - js/css/other loader + kv storage * * Copyright 2013-2014 Vitaly Puzrin * https://github.com/nodeca/bag.js * * License MIT */ /*global define*/ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = factory(); } else { root.Bag = factory(); } } (this, function () { 'use strict'; var head = document.head || document.getElementsByTagName('head')[0]; ////////////////////////////////////////////////////////////////////////////// // helpers function _nope() { return; } function _isString(obj) { return Object.prototype.toString.call(obj) === '[object String]'; } var _isArray = Array.isArray || function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; function _isFunction(obj) { return Object.prototype.toString.call(obj) === '[object Function]'; } function _each(obj, iterator) { if (_isArray(obj)) { if (obj.forEach) { return obj.forEach(iterator); } for (var i = 0; i < obj.length; i++) { iterator(obj[i], i, obj); } } else { for (var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) { iterator(obj[k], k); } } } } function _default(obj, src) { // extend obj with src properties if not exists; _each(src, function (val, key) { if (!obj[key]) { obj[key] = src[key]; } }); } function _asyncEach(arr, iterator, callback) { callback = callback || _nope; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, function (err) { if (err) { callback(err); callback = _nope; } else { completed += 1; if (completed >= arr.length) { callback(); } } }); }); } ////////////////////////////////////////////////////////////////////////////// // Adapters for Store class function DomStorage(namespace) { var self = this; var _ns = namespace + '__'; var _storage = localStorage; this.init = function (callback) { callback(); }; this.remove = function (key, callback) { callback = callback || _nope; _storage.removeItem(_ns + key); callback(); }; this.set = function (key, value, expire, callback) { var obj = { value: value, expire: expire }; var err; try { _storage.setItem(_ns + key, JSON.stringify(obj)); } catch (e) { // On quota error try to reset storage & try again. // Just remove all keys, without conditions, no optimizations needed. if (e.name.toUpperCase().indexOf('QUOTA') >= 0) { try { _each(_storage, function (val, name) { var k = name.split(_ns)[1]; if (k) { self.remove(k); } }); _storage.setItem(_ns + key, JSON.stringify(obj)); } catch (e2) { err = e2; } } else { err = e; } } callback(err); }; this.get = function (key, raw, callback) { if (_isFunction(raw)) { callback = raw; raw = false; } var err, data; try { data = JSON.parse(_storage.getItem(_ns + key)); data = raw ? data : data.value; } catch (e) { err = new Error('Can\'t read key: ' + key); } callback(err, data); }; this.clear = function (expiredOnly, callback) { var now = +new Date(); _each(_storage, function (val, name) { var key = name.split(_ns)[1]; if (!key) { return; } if (!expiredOnly) { self.remove(key); return; } var raw; self.get(key, true, function (__, data) { raw = data; // can use this hack, because get is sync; }); if (raw && (raw.expire > 0) && ((raw.expire - now) < 0)) { self.remove(key); } }); callback(); }; } DomStorage.prototype.exists = function () { try { localStorage.setItem('__ls_test__', '__ls_test__'); localStorage.removeItem('__ls_test__'); return true; } catch (e) { return false; } }; function WebSql(namespace) { var db; this.init = function (callback) { db = window.openDatabase(namespace, '1.0', 'bag.js db', 2e5); if (!db) { return callback('Can\'t open webdql database'); } db.transaction(function (tx) { tx.executeSql( 'CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT, expire INTEGER KEY)', [], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.remove = function (key, callback) { callback = callback || _nope; db.transaction(function (tx) { tx.executeSql( 'DELETE FROM kv WHERE key = ?', [ key ], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.set = function (key, value, expire, callback) { db.transaction(function (tx) { tx.executeSql( 'INSERT OR REPLACE INTO kv (key, value, expire) VALUES (?, ?, ?)', [ key, JSON.stringify(value), expire ], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.get = function (key, callback) { db.readTransaction(function (tx) { tx.executeSql( 'SELECT value FROM kv WHERE key = ?', [ key ], function (tx, result) { if (result.rows.length === 0) { return callback(new Error('key not found: ' + key)); } var value = result.rows.item(0).value; var err, data; try { data = JSON.parse(value); } catch (e) { err = new Error('Can\'t unserialise data: ' + value); } callback(err, data); }, function (tx, err) { return callback(err); } ); }); }; this.clear = function (expiredOnly, callback) { db.transaction(function (tx) { if (expiredOnly) { tx.executeSql( 'DELETE FROM kv WHERE expire > 0 AND expire < ?', [ +new Date() ], function () { return callback(); }, function (tx, err) { return callback(err); } ); } else { db.transaction(function (tx) { tx.executeSql( 'DELETE FROM kv', [], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); } }); }; } WebSql.prototype.exists = function () { return (!!window.openDatabase); }; function Idb(namespace) { var db; this.init = function (callback) { var idb = this.idb = window.indexedDB; /* || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;*/ var req = idb.open(namespace, 2 /*version*/); req.onsuccess = function (e) { db = e.target.result; callback(); }; req.onblocked = function (e) { callback(new Error('IndexedDB blocked. ' + e.target.errorCode)); }; req.onerror = function (e) { callback(new Error('IndexedDB opening error. ' + e.target.errorCode)); }; req.onupgradeneeded = function (e) { db = e.target.result; if (db.objectStoreNames.contains('kv')) { db.deleteObjectStore('kv'); } var store = db.createObjectStore('kv', { keyPath: 'key' }); store.createIndex('expire', 'expire', { unique: false }); }; }; this.remove = function (key, callback) { var tx = db.transaction('kv', 'readwrite'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key remove error: ', e.target)); }; // IE 8 not allow to use reserved keywords as functions. More info: // http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/ tx.objectStore('kv')['delete'](key).onerror = function () { tx.abort(); }; }; this.set = function (key, value, expire, callback) { var tx = db.transaction('kv', 'readwrite'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key set error: ', e.target)); }; tx.objectStore('kv').put({ key: key, value: value, expire: expire }).onerror = function () { tx.abort(); }; }; this.get = function (key, callback) { var err, result; var tx = db.transaction('kv'); tx.oncomplete = function () { callback(err, result); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key get error: ', e.target)); }; tx.objectStore('kv').get(key).onsuccess = function (e) { if (e.target.result) { result = e.target.result.value; } else { err = new Error('key not found: ' + key); } }; }; this.clear = function (expiredOnly, callback) { var keyrange = window.IDBKeyRange; /* || window.webkitIDBKeyRange || window.msIDBKeyRange;*/ var tx, store; tx = db.transaction('kv', 'readwrite'); store = tx.objectStore('kv'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Clear error: ', e.target)); }; if (expiredOnly) { var cursor = store.index('expire').openCursor(keyrange.bound(1, +new Date())); cursor.onsuccess = function (e) { var _cursor = e.target.result; if (_cursor) { // IE 8 not allow to use reserved keywords as functions (`delete` and `continue`). More info: // http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/ store['delete'](_cursor.primaryKey).onerror = function () { tx.abort(); }; _cursor['continue'](); } }; } else { // Just clear everything tx.objectStore('kv').clear().onerror = function () { tx.abort(); }; } }; } Idb.prototype.exists = function () { var db = window.indexedDB /*|| window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB*/; if (!db) { return false; } // Check outdated idb implementations, where `onupgradeneede` event doesn't work, // see https://github.com/pouchdb/pouchdb/issues/1207 for more details var dbName = '__idb_test__'; var result = db.open(dbName, 1).onupgradeneeded === null; if (db.deleteDatabase) { db.deleteDatabase(dbName); } return result; }; ///////////////////////////////////////////////////////////////////////////// // key/value storage with expiration var storeAdapters = { indexeddb: Idb, websql: WebSql, localstorage: DomStorage }; // namespace - db name or similar // storesList - array of allowed adapter names to use // function Storage(namespace, storesList) { var self = this; var db = null; // States of db init singletone process // 'done' / 'progress' / 'failed' / undefined var initState; var initStack = []; _each(storesList, function (name) { // do storage names case insensitive name = name.toLowerCase(); if (!storeAdapters[name]) { throw new Error('Wrong storage adapter name: ' + name, storesList); } if (storeAdapters[name].prototype.exists() && !db) { db = new storeAdapters[name](namespace); return false; // terminate search on first success } }); if (!db) { /* eslint-disable no-console */ // If no adaprets - don't make error for correct fallback. // Just log that we continue work without storing results. if (typeof console !== 'undefined' && console.log) { console.log('None of requested storages available: ' + storesList); } /* eslint-enable no-console */ } this.init = function (callback) { if (!db) { callback(new Error('No available db')); return; } if (initState === 'done') { callback(); return; } if (initState === 'progress') { initStack.push(callback); return; } initStack.push(callback); initState = 'progress'; db.init(function (err) { initState = !err ? 'done' : 'failed'; _each(initStack, function (cb) { cb(err); }); initStack = []; // Clear expired. A bit dirty without callback, // but we don't care until clear compleete if (!err) { self.clear(true); } }); }; this.set = function (key, value, expire, callback) { if (_isFunction(expire)) { callback = expire; expire = null; } callback = callback || _nope; expire = expire ? +(new Date()) + (expire * 1000) : 0; this.init(function (err) { if (err) { return callback(err); } db.set(key, value, expire, callback); }); }; this.get = function (key, callback) { this.init(function (err) { if (err) { return callback(err); } db.get(key, callback); }); }; this.remove = function (key, callback) { callback = callback || _nope; this.init(function (err) { if (err) { return callback(err); } db.remove(key, callback); }); }; this.clear = function (expiredOnly, callback) { if (_isFunction(expiredOnly)) { callback = expiredOnly; expiredOnly = false; } callback = callback || _nope; this.init(function (err) { if (err) { return callback(err); } db.clear(expiredOnly, callback); }); }; } ////////////////////////////////////////////////////////////////////////////// // Bag class implementation function Bag(options) { if (!(this instanceof Bag)) { return new Bag(options); } var self = this; options = options || {}; this.prefix = options.prefix || 'bag'; this.timeout = options.timeout || 20; // 20 seconds this.expire = options.expire || 30 * 24; // 30 days this.isValidItem = options.isValidItem || null; this.stores = _isArray(options.stores) ? options.stores : [ 'indexeddb', 'websql', 'localstorage' ]; var storage = null; this._queue = []; this._chained = false; this._createStorage = function () { if (!storage) { storage = new Storage(self.prefix, self.stores); } }; function getUrl(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { callback(null, { content: xhr.responseText, type: xhr.getResponseHeader('content-type') }); callback = _nope; } else { callback(new Error('Can\'t open url ' + url + (xhr.status ? xhr.statusText + ' (' + xhr.status + ')' : ''))); callback = _nope; } } }; setTimeout(function () { if (xhr.readyState < 4) { xhr.abort(); callback(new Error('Timeout')); callback = _nope; } }, self.timeout * 1000); xhr.send(); } function createCacheObj(obj, response) { var cacheObj = {}; _each([ 'url', 'key', 'unique' ], function (key) { if (obj[key]) { cacheObj[key] = obj[key]; } }); var now = +new Date(); cacheObj.data = response.content; cacheObj.originalType = response.type; cacheObj.type = obj.type || response.type; cacheObj.stamp = now; return cacheObj; } function saveUrl(obj, callback) { getUrl(obj.url_real, function (err, result) { if (err) { return callback(err); } var delay = (obj.expire || self.expire) * 60 * 60; // in seconds var cached = createCacheObj(obj, result); self.set(obj.key, cached, delay, function () { // Don't check error - have to return data anyway _default(obj, cached); callback(null, obj); }); }); } function isCacheValid(cached, obj) { return !cached || cached.expire - +new Date() < 0 || obj.unique !== cached.unique || obj.url !== cached.url || (self.isValidItem && !self.isValidItem(cached, obj)); } function fetch(obj, callback) { if (!obj.url) { return callback(); } obj.key = (obj.key || obj.url); self.get(obj.key, function (err_cache, cached) { // Check error only on forced fetch from cache if (err_cache && obj.cached) { callback(err_cache); return; } // if can't get object from store, then just load it from web. obj.execute = (obj.execute !== false); var shouldFetch = !!err_cache || isCacheValid(cached, obj); // If don't have to load new date - return one from cache if (!obj.live && !shouldFetch) { obj.type = obj.type || cached.originalType; _default(obj, cached); callback(null, obj); return; } // calculate loading url obj.url_real = obj.url; if (obj.unique) { // set parameter to prevent browser cache obj.url_real = obj.url + ((obj.url.indexOf('?') > 0) ? '&' : '?') + 'bag-unique=' + obj.unique; } saveUrl(obj, function (err_load) { if (err_cache && err_load) { callback(err_load); return; } if (err_load) { obj.type = obj.type || cached.originalType; _default(obj, cached); callback(null, obj); return; } callback(null, obj); }); }); } //////////////////////////////////////////////////////////////////////////// // helpers to set absolute sourcemap url /* eslint-disable max-len */ var sourceMappingRe = /(?:^([ \t]*\/\/[@|#][ \t]+sourceMappingURL=)(.+?)([ \t]*)$)|(?:^([ \t]*\/\*[@#][ \t]+sourceMappingURL=)(.+?)([ \t]*\*\/[ \t])*$)/mg; /* eslint-enable max-len */ function parse_url(url) { var pattern = new RegExp('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?'); var matches = url.match(pattern); return { scheme: matches[2], authority: matches[4], path: matches[5], query: matches[7], fragment: matches[9] }; } function patchMappingUrl(obj) { var refUrl = parse_url(obj.url); var done = false; var res = obj.data.replace(sourceMappingRe, function (match, p1, p2, p3, p4, p5, p6) { if (!match) { return null; } done = true; // select matched group of params if (!p1) { p1 = p4; p2 = p5; p3 = p6; } var mapUrl = parse_url(p2); var scheme = (mapUrl.scheme ? mapUrl.scheme : refUrl.scheme) || window.location.protocol.slice(0, -1); var authority = (mapUrl.authority ? mapUrl.authority : refUrl.authority) || window.location.host; /* eslint-disable max-len */ var path = mapUrl.path[0] === '/' ? mapUrl.path : refUrl.path.split('/').slice(0, -1).join('/') + '/' + mapUrl.path; /* eslint-enable max-len */ return p1 + (scheme + '://' + authority + path) + p3; }); return done ? res : ''; } //////////////////////////////////////////////////////////////////////////// var handlers = { 'application/javascript': function injectScript(obj) { var script = document.createElement('script'), txt; // try to change sourcemap address to absolute txt = patchMappingUrl(obj); if (!txt) { // or add script name for dev tools txt = obj.data + '\n//# sourceURL=' + obj.url; } // Have to use .text, since we support IE8, // which won't allow appending to a script script.text = txt; head.appendChild(script); return; }, 'text/css': function injectStyle(obj) { var style = document.createElement('style'), txt; // try to change sourcemap address to absolute txt = patchMappingUrl(obj); if (!txt) { // or add stylesheet script name for dev tools txt = obj.data + '\n/*# sourceURL=' + obj.url + ' */'; } // Needed to enable `style.styleSheet` in IE style.setAttribute('type', 'text/css'); if (style.styleSheet) { // We should append style element to DOM before assign css text to // workaround IE bugs with `@import` and `@font-face`. // https://github.com/andrewwakeling/ie-css-bugs head.appendChild(style); style.styleSheet.cssText = txt; // IE method } else { style.appendChild(document.createTextNode(txt)); // others head.appendChild(style); } return; } }; function execute(obj) { if (!obj.type) { return; } // Cut off encoding if exists: // application/javascript; charset=UTF-8 var handlerName = obj.type.split(';')[0]; // Fix outdated mime types if needed, to use single handler if (handlerName === 'application/x-javascript' || handlerName === 'text/javascript') { handlerName = 'application/javascript'; } if (handlers[handlerName]) { handlers[handlerName](obj); } return; } //////////////////////////////////////////////////////////////////////////// // // Public methods // this.require = function (resources, callback) { var queue = self._queue; if (_isFunction(resources)) { callback = resources; resources = null; } if (resources) { var res = _isArray(resources) ? resources : [ resources ]; // convert string urls to structures // and push to queue _each(res, function (r, i) { if (_isString(r)) { res[i] = { url: r }; } queue.push(res[i]); }); } self._createStorage(); if (!callback) { self._chained = true; return self; } _asyncEach(queue, fetch, function (err) { if (err) { // cleanup self._chained = false; self._queue = []; callback(err); return; } _each(queue, function (obj) { if (obj.execute) { execute(obj); } }); // return content only, if one need fuul info - // check input object, that will be extended. var replies = []; _each(queue, function (r) { replies.push(r.data); }); var result = (_isArray(resources) || self._chained) ? replies : replies[0]; // cleanup self._chained = false; self._queue = []; callback(null, result); }); }; // Create proxy methods (init store then subcall) _each([ 'remove', 'get', 'set', 'clear' ], function (method) { self[method] = function () { self._createStorage(); storage[method].apply(storage, arguments); }; }); this.addHandler = function (types, handler) { types = _isArray(types) ? types : [ types ]; _each(types, function (type) { handlers[type] = handler; }); }; this.removeHandler = function (types) { self.addHandler(types/*, undefined*/); }; } return Bag; }));
kiwi89/cdnjs
ajax/libs/bagjs/1.0.0/bag.js
JavaScript
mit
24,235
/*! * Cropper v0.4.0 * https://github.com/fengyuanchen/cropperjs * * Copyright (c) 2015 Fengyuan Chen * Released under the MIT license * * Date: 2015-12-02T06:35:32.008Z */ (function (global, factory) { if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = global.document ? factory(global, true) : function (w) { if (!w.document) { throw new Error('Cropper requires a window with a document'); } return factory(w); }; } else { factory(global); } })(typeof window !== 'undefined' ? window : this, function (window, noGlobal) { 'use strict'; // Globals var document = window.document; var location = window.location; // Constants var NAMESPACE = 'cropper'; // Classes var CLASS_MODAL = 'cropper-modal'; var CLASS_HIDE = 'cropper-hide'; var CLASS_HIDDEN = 'cropper-hidden'; var CLASS_INVISIBLE = 'cropper-invisible'; var CLASS_MOVE = 'cropper-move'; var CLASS_CROP = 'cropper-crop'; var CLASS_DISABLED = 'cropper-disabled'; var CLASS_BG = 'cropper-bg'; // Events var EVENT_MOUSE_DOWN = 'mousedown touchstart pointerdown MSPointerDown'; var EVENT_MOUSE_MOVE = 'mousemove touchmove pointermove MSPointerMove'; var EVENT_MOUSE_UP = 'mouseup touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel'; var EVENT_WHEEL = 'wheel mousewheel DOMMouseScroll'; var EVENT_DBLCLICK = 'dblclick'; var EVENT_RESIZE = 'resize'; var EVENT_ERROR = 'error'; var EVENT_LOAD = 'load'; // RegExps var REGEXP_ACTIONS = /^(e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/; var REGEXP_SPACES = /\s+/; var REGEXP_TRIM = /^\s+(.*)\s+^/; // Data var DATA_PREVIEW = 'preview'; var DATA_ACTION = 'action'; // Actions var ACTION_EAST = 'e'; var ACTION_WEST = 'w'; var ACTION_SOUTH = 's'; var ACTION_NORTH = 'n'; var ACTION_SOUTH_EAST = 'se'; var ACTION_SOUTH_WEST = 'sw'; var ACTION_NORTH_EAST = 'ne'; var ACTION_NORTH_WEST = 'nw'; var ACTION_ALL = 'all'; var ACTION_CROP = 'crop'; var ACTION_MOVE = 'move'; var ACTION_ZOOM = 'zoom'; var ACTION_NONE = 'none'; // Supports var SUPPORT_CANVAS = !!document.createElement('canvas').getContext; // Maths var num = Number; var min = Math.min; var max = Math.max; var abs = Math.abs; var sin = Math.sin; var cos = Math.cos; var sqrt = Math.sqrt; var round = Math.round; var floor = Math.floor; // Prototype var prototype = { version: '0.4.0' }; // Utilities var EMPTY_OBJECT = {}; var toString = EMPTY_OBJECT.toString; var hasOwnProperty = EMPTY_OBJECT.hasOwnProperty; function typeOf(obj) { return toString.call(obj).slice(8, -1).toLowerCase(); } function isString(str) { return typeof str === 'string'; } function isNumber(num) { return typeof num === 'number' && !isNaN(num); } function isUndefined(obj) { return typeof obj === 'undefined'; } function isObject(obj) { return typeof obj === 'object' && obj !== null; } function isPlainObject(obj) { var constructor; var prototype; if (!isObject(obj)) { return false; } try { constructor = obj.constructor; prototype = constructor.prototype; return constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf'); } catch (e) { return false; } } function isFunction(fn) { return typeOf(fn) === 'function'; } function isArray(arr) { return Array.isArray ? Array.isArray(arr) : typeOf(arr) === 'array'; } function toArray(obj, offset) { var args = []; // This is necessary for IE8 if (isNumber(offset)) { args.push(offset); } return args.slice.apply(obj, args); } function inArray(value, arr) { var index = -1; each(arr, function (n, i) { if (n === value) { index = i; return false; } }); return index; } function trim(str) { if (!isString(str)) { str = String(str); } if (str.trim) { str = str.trim(); } else { str = str.replace(REGEXP_TRIM, '$1'); } return str; } function each(obj, callback) { var length; var i; if (obj && isFunction(callback)) { if (isArray(obj) || isNumber(obj.length)/* array-like */) { for (i = 0, length = obj.length; i < length; i++) { if (callback.call(obj, obj[i], i, obj) === false) { break; } } } else if (isObject(obj)) { for (i in obj) { if (hasOwnProperty.call(obj, i)) { if (callback.call(obj, obj[i], i, obj) === false) { break; } } } } } return obj; } function extend(obj) { var args = toArray(arguments); if (args.length > 1) { args.shift(); } each(args, function (arg) { each(arg, function (prop, i) { obj[i] = prop; }); }); return obj; } function proxy(fn, context) { var args = toArray(arguments, 2); return function () { return fn.apply(context, args.concat(toArray(arguments))); }; } function parseClass(className) { return trim(className).split(REGEXP_SPACES); } function hasClass(element, value) { return element.className.indexOf(value) > -1; } function addClass(element, value) { var classes; if (isNumber(element.length)) { return each(element, function (elem) { addClass(elem, value); }); } classes = parseClass(element.className); each(parseClass(value), function (n) { if (inArray(n, classes) < 0) { classes.push(n); } }); element.className = classes.join(' '); } function removeClass(element, value) { var classes; if (isNumber(element.length)) { return each(element, function (elem) { removeClass(elem, value); }); } classes = parseClass(element.className); each(parseClass(value), function (n, i) { if ((i = inArray(n, classes)) > -1) { classes.splice(i, 1); } }); element.className = classes.join(' '); } function toggleClass(element, value, added) { return added ? addClass(element, value) : removeClass(element, value); } function getData(element, name) { if (isObject(element[name])) { return element[name]; } else if (element.dataset) { return element.dataset[name]; } else { return element.getAttribute('data-' + name); } } function setData(element, name, data) { if (isObject(data) && isUndefined(element[name])) { element[name] = data; } else if (element.dataset) { element.dataset[name] = data; } else { element.setAttribute('data-' + name, data); } } function removeData(element, name) { if (isObject(element[name])) { delete element[name]; } else if (element.dataset) { delete element.dataset[name]; } else { element.removeAttribute('data-' + name); } } function addListener(element, type, handler) { var types; if (!isFunction(handler)) { return; } types = trim(type).split(REGEXP_SPACES); if (types.length > 1) { return each(types, function (type) { addListener(element, type, handler); }); } if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent('on' + type, handler); } } function removeListener(element, type, handler) { var types; if (!isFunction(handler)) { return; } types = trim(type).split(REGEXP_SPACES); if (types.length > 1) { return each(types, function (type) { removeListener(element, type, handler); }); } if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent('on' + type, handler); } } function preventDefault(e) { if (e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } } function getEvent(event) { var e = event || window.event; var doc; // Fix target property (IE8) if (!e.target) { e.target = e.srcElement || document; } if (!isNumber(e.pageX)) { doc = document.documentElement; e.pageX = e.clientX + (window.scrollX || doc && doc.scrollLeft || 0) - (doc && doc.clientLeft || 0); e.pageY = e.clientY + (window.scrollY || doc && doc.scrollTop || 0) - (doc && doc.clientTop || 0); } return e; } function getOffset(element) { var doc = document.documentElement; var box = element.getBoundingClientRect(); return { left: box.left + (window.scrollX || doc && doc.scrollLeft || 0) - (doc && doc.clientLeft || 0), top: box.top + (window.scrollY || doc && doc.scrollTop || 0) - (doc && doc.clientTop || 0) }; } function querySelector(element, selector) { return element.querySelector(selector); } function querySelectorAll(element, selector) { return element.querySelectorAll(selector); } function insertBefore(element, elem) { element.parentNode.insertBefore(elem, element); } function appendChild(element, elem) { element.appendChild(elem); } function removeChild(element) { element.parentNode.removeChild(element); } function empty(element) { while (element.firstChild) { element.removeChild(element.firstChild); } } function isCrossOriginURL(url) { var parts = url.match(/^(https?:)\/\/([^\:\/\?#]+):?(\d*)/i); return parts && ( parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port ); } function setCrossOrigin(image, crossOrigin) { if (crossOrigin) { image.crossOrigin = crossOrigin; } } function addTimestamp(url) { var timestamp = 'timestamp=' + (new Date()).getTime(); return (url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp); } function getImageSize(image, callback) { var newImage; // Modern browsers if (image.naturalWidth) { return callback(image.naturalWidth, image.naturalHeight); } // IE8: Don't use `new Image()` here newImage = document.createElement('img'); newImage.onload = function () { callback(this.width, this.height); }; newImage.src = image.src; } function getTransform(options) { var transforms = []; var rotate = options.rotate; var scaleX = options.scaleX; var scaleY = options.scaleY; if (isNumber(rotate)) { transforms.push('rotate(' + rotate + 'deg)'); } if (isNumber(scaleX) && isNumber(scaleY)) { transforms.push('scale(' + scaleX + ',' + scaleY + ')'); } return transforms.length ? transforms.join(' ') : 'none'; } function getRotatedSizes(data, isReversed) { var deg = abs(data.degree) % 180; var arc = (deg > 90 ? (180 - deg) : deg) * Math.PI / 180; var sinArc = sin(arc); var cosArc = cos(arc); var width = data.width; var height = data.height; var aspectRatio = data.aspectRatio; var newWidth; var newHeight; if (!isReversed) { newWidth = width * cosArc + height * sinArc; newHeight = width * sinArc + height * cosArc; } else { newWidth = width / (cosArc + sinArc / aspectRatio); newHeight = newWidth / aspectRatio; } return { width: newWidth, height: newHeight }; } function getSourceCanvas(image, data) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var x = 0; var y = 0; var width = data.naturalWidth; var height = data.naturalHeight; var rotate = data.rotate; var scaleX = data.scaleX; var scaleY = data.scaleY; var scalable = isNumber(scaleX) && isNumber(scaleY) && (scaleX !== 1 || scaleY !== 1); var rotatable = isNumber(rotate) && rotate !== 0; var advanced = rotatable || scalable; var canvasWidth = width; var canvasHeight = height; var translateX; var translateY; var rotated; if (scalable) { translateX = width / 2; translateY = height / 2; } if (rotatable) { rotated = getRotatedSizes({ width: width, height: height, degree: rotate }); canvasWidth = rotated.width; canvasHeight = rotated.height; translateX = rotated.width / 2; translateY = rotated.height / 2; } canvas.width = canvasWidth; canvas.height = canvasHeight; if (advanced) { x = -width / 2; y = -height / 2; context.save(); context.translate(translateX, translateY); } if (rotatable) { context.rotate(rotate * Math.PI / 180); } // Should call `scale` after rotated if (scalable) { context.scale(scaleX, scaleY); } context.drawImage(image, floor(x), floor(y), floor(width), floor(height)); if (advanced) { context.restore(); } return canvas; } function Cropper(element, options) { this.element = element; this.options = extend({}, Cropper.DEFAULTS, isPlainObject(options) && options); this.isLoaded = false; this.isBuilt = false; this.isCompleted = false; this.isRotated = false; this.isCropped = false; this.isDisabled = false; this.isReplaced = false; this.isLimited = false; this.isImg = false; this.originalUrl = ''; this.crossOrigin = ''; this.canvasData = null; this.cropBoxData = null; this.previews = null; this.init(); } extend(prototype, { init: function () { var element = this.element; var tagName = element.tagName.toLowerCase(); var url; if (getData(element, NAMESPACE)) { return; } setData(element, NAMESPACE, this); if (tagName === 'img') { this.isImg = true; // e.g.: "img/picture.jpg" this.originalUrl = url = element.getAttribute('src'); // Stop when it's a blank image if (!url) { return; } // e.g.: "http://example.com/img/picture.jpg" url = element.src; } else if (tagName === 'canvas' && SUPPORT_CANVAS) { url = element.toDataURL(); } this.load(url); }, load: function (url) { var options = this.options; var element = this.element; var crossOrigin; var bustCacheUrl; var image; var start; var stop; if (!url) { return; } this.url = url; if (isFunction(options.build) && options.build.call(element) === false) { return; } if (options.checkCrossOrigin && isCrossOriginURL(url)) { crossOrigin = element.crossOrigin; if (!crossOrigin) { crossOrigin = 'anonymous'; bustCacheUrl = addTimestamp(url); } } this.crossOrigin = crossOrigin; image = document.createElement('img'); setCrossOrigin(image, crossOrigin); image.src = bustCacheUrl || url; this.image = image; this._start = start = proxy(this.start, this); this._stop = stop = proxy(this.stop, this); if (this.isImg) { if (element.complete) { this.start(); } else { addListener(element, EVENT_LOAD, start); } } else { addListener(image, EVENT_LOAD, start); addListener(image, EVENT_ERROR, stop); addClass(image, CLASS_HIDE); insertBefore(element, image); } }, start: function (event) { var image = this.isImg ? this.element : this.image; if (event) { removeListener(image, EVENT_LOAD, this._start); removeListener(image, EVENT_ERROR, this._stop); } getImageSize(image, proxy(function (naturalWidth, naturalHeight) { this.imageData = { naturalWidth: naturalWidth, naturalHeight: naturalHeight, aspectRatio: naturalWidth / naturalHeight }; this.isLoaded = true; this.build(); }, this)); }, stop: function () { var image = this.image; removeListener(image, EVENT_LOAD, this._start); removeListener(image, EVENT_ERROR, this._stop); removeChild(image); this.image = null; } }); extend(prototype, { build: function () { var options = this.options; var element = this.element; var image = this.image; var template; var cropper; var canvas; var dragBox; var cropBox; var face; if (!this.isLoaded) { return; } // Unbuild first when replace if (this.isBuilt) { this.unbuild(); } template = document.createElement('div'); template.innerHTML = Cropper.TEMPLATE; // Create cropper elements this.container = element.parentNode; this.cropper = cropper = querySelector(template, '.cropper-container'); this.canvas = canvas = querySelector(cropper, '.cropper-canvas'); this.dragBox = dragBox = querySelector(cropper, '.cropper-drag-box'); this.cropBox = cropBox = querySelector(cropper, '.cropper-crop-box'); this.viewBox = querySelector(cropper, '.cropper-view-box'); this.face = face = querySelector(cropBox, '.cropper-face'); appendChild(canvas, image); // Hide the original image addClass(element, CLASS_HIDDEN); insertBefore(element, cropper); // Show the image if is hidden if (!this.isImg) { removeClass(image, CLASS_HIDE); } this.initPreview(); this.bind(); options.aspectRatio = max(0, options.aspectRatio) || NaN; options.viewMode = max(0, min(3, round(options.viewMode))) || 0; if (options.autoCrop) { this.isCropped = true; if (options.modal) { addClass(dragBox, CLASS_MODAL); } } else { addClass(cropBox, CLASS_HIDDEN); } if (!options.guides) { addClass(querySelectorAll(cropBox, '.cropper-dashed'), CLASS_HIDDEN); } if (!options.center) { addClass(querySelector(cropBox, '.cropper-center'), CLASS_HIDDEN); } if (options.background) { addClass(cropper, CLASS_BG); } if (!options.highlight) { addClass(face, CLASS_INVISIBLE); } if (options.cropBoxMovable) { addClass(face, CLASS_MOVE); setData(face, DATA_ACTION, ACTION_ALL); } if (!options.cropBoxResizable) { addClass(querySelectorAll(cropBox, '.cropper-line'), CLASS_HIDDEN); addClass(querySelectorAll(cropBox, '.cropper-point'), CLASS_HIDDEN); } this.setDragMode(options.dragMode); this.render(); this.isBuilt = true; this.setData(options.data); // Call the built asynchronously to keep "image.cropper" is defined setTimeout(proxy(function () { if (isFunction(options.built)) { options.built.call(element); } if (isFunction(options.crop)) { options.crop.call(element, this.getData()); } this.isCompleted = true; }, this), 0); }, unbuild: function () { if (!this.isBuilt) { return; } this.isBuilt = false; this.initialImageData = null; // Clear `initialCanvasData` is necessary when replace this.initialCanvasData = null; this.initialCropBoxData = null; this.containerData = null; this.canvasData = null; // Clear `cropBoxData` is necessary when replace this.cropBoxData = null; this.unbind(); this.resetPreview(); this.previews = null; this.viewBox = null; this.cropBox = null; this.dragBox = null; this.canvas = null; this.container = null; removeChild(this.cropper); this.cropper = null; } }); extend(prototype, { render: function () { this.initContainer(); this.initCanvas(); this.initCropBox(); this.renderCanvas(); if (this.isCropped) { this.renderCropBox(); } }, initContainer: function () { var options = this.options; var element = this.element; var container = this.container; var cropper = this.cropper; var containerData; addClass(cropper, CLASS_HIDDEN); removeClass(element, CLASS_HIDDEN); this.containerData = containerData = { width: max(container.offsetWidth, num(options.minContainerWidth) || 200), height: max(container.offsetHeight, num(options.minContainerHeight) || 100) }; cropper.style.cssText = ( 'width:' + containerData.width + 'px;' + 'height:' + containerData.height + 'px;' ); addClass(element, CLASS_HIDDEN); removeClass(cropper, CLASS_HIDDEN); }, // Canvas (image wrapper) initCanvas: function () { var viewMode = this.options.viewMode; var containerData = this.containerData; var containerWidth = containerData.width; var containerHeight = containerData.height; var imageData = this.imageData; var aspectRatio = imageData.aspectRatio; var canvasData = { naturalWidth: imageData.naturalWidth, naturalHeight: imageData.naturalHeight, aspectRatio: aspectRatio, width: containerWidth, height: containerHeight }; if (containerHeight * aspectRatio > containerWidth) { if (viewMode === 3) { canvasData.width = containerHeight * aspectRatio; } else { canvasData.height = containerWidth / aspectRatio; } } else { if (viewMode === 3) { canvasData.height = containerWidth / aspectRatio; } else { canvasData.width = containerHeight * aspectRatio; } } canvasData.oldLeft = canvasData.left = (containerWidth - canvasData.width) / 2; canvasData.oldTop = canvasData.top = (containerHeight - canvasData.height) / 2; this.canvasData = canvasData; this.isLimited = (viewMode === 1 || viewMode === 2); this.limitCanvas(true, true); this.initialImageData = extend({}, imageData); this.initialCanvasData = extend({}, canvasData); }, limitCanvas: function (isSizeLimited, isPositionLimited) { var options = this.options; var viewMode = options.viewMode; var containerData = this.containerData; var containerWidth = containerData.width; var containerHeight = containerData.height; var canvasData = this.canvasData; var aspectRatio = canvasData.aspectRatio; var cropBoxData = this.cropBoxData; var isCropped = this.isCropped && cropBoxData; var minCanvasWidth; var minCanvasHeight; var newCanvasLeft; var newCanvasTop; if (isSizeLimited) { minCanvasWidth = num(options.minCanvasWidth) || 0; minCanvasHeight = num(options.minCanvasHeight) || 0; if (viewMode) { if (viewMode > 1) { minCanvasWidth = max(minCanvasWidth, containerWidth); minCanvasHeight = max(minCanvasHeight, containerHeight); if (viewMode === 3) { if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasWidth = minCanvasHeight * aspectRatio; } else { minCanvasHeight = minCanvasWidth / aspectRatio; } } } else { if (minCanvasWidth) { minCanvasWidth = max(minCanvasWidth, isCropped ? cropBoxData.width : 0); } else if (minCanvasHeight) { minCanvasHeight = max(minCanvasHeight, isCropped ? cropBoxData.height : 0); } else if (isCropped) { minCanvasWidth = cropBoxData.width; minCanvasHeight = cropBoxData.height; if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasWidth = minCanvasHeight * aspectRatio; } else { minCanvasHeight = minCanvasWidth / aspectRatio; } } } } if (minCanvasWidth && minCanvasHeight) { if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasHeight = minCanvasWidth / aspectRatio; } else { minCanvasWidth = minCanvasHeight * aspectRatio; } } else if (minCanvasWidth) { minCanvasHeight = minCanvasWidth / aspectRatio; } else if (minCanvasHeight) { minCanvasWidth = minCanvasHeight * aspectRatio; } canvasData.minWidth = minCanvasWidth; canvasData.minHeight = minCanvasHeight; canvasData.maxWidth = Infinity; canvasData.maxHeight = Infinity; } if (isPositionLimited) { if (viewMode) { newCanvasLeft = containerWidth - canvasData.width; newCanvasTop = containerHeight - canvasData.height; canvasData.minLeft = min(0, newCanvasLeft); canvasData.minTop = min(0, newCanvasTop); canvasData.maxLeft = max(0, newCanvasLeft); canvasData.maxTop = max(0, newCanvasTop); if (isCropped && this.isLimited) { canvasData.minLeft = min( cropBoxData.left, cropBoxData.left + cropBoxData.width - canvasData.width ); canvasData.minTop = min( cropBoxData.top, cropBoxData.top + cropBoxData.height - canvasData.height ); canvasData.maxLeft = cropBoxData.left; canvasData.maxTop = cropBoxData.top; if (viewMode === 2) { if (canvasData.width >= containerWidth) { canvasData.minLeft = min(0, newCanvasLeft); canvasData.maxLeft = max(0, newCanvasLeft); } if (canvasData.height >= containerHeight) { canvasData.minTop = min(0, newCanvasTop); canvasData.maxTop = max(0, newCanvasTop); } } } } else { canvasData.minLeft = -canvasData.width; canvasData.minTop = -canvasData.height; canvasData.maxLeft = containerWidth; canvasData.maxTop = containerHeight; } } }, renderCanvas: function (isChanged) { var canvasData = this.canvasData; var imageData = this.imageData; var rotate = imageData.rotate; var naturalWidth = imageData.naturalWidth; var naturalHeight = imageData.naturalHeight; var aspectRatio; var rotatedData; if (this.isRotated) { this.isRotated = false; // Computes rotated sizes with image sizes rotatedData = getRotatedSizes({ width: imageData.width, height: imageData.height, degree: rotate }); aspectRatio = rotatedData.width / rotatedData.height; if (aspectRatio !== canvasData.aspectRatio) { canvasData.left -= (rotatedData.width - canvasData.width) / 2; canvasData.top -= (rotatedData.height - canvasData.height) / 2; canvasData.width = rotatedData.width; canvasData.height = rotatedData.height; canvasData.aspectRatio = aspectRatio; canvasData.naturalWidth = naturalWidth; canvasData.naturalHeight = naturalHeight; // Computes rotated sizes with natural image sizes if (rotate % 180) { rotatedData = getRotatedSizes({ width: naturalWidth, height: naturalHeight, degree: rotate }); canvasData.naturalWidth = rotatedData.width; canvasData.naturalHeight = rotatedData.height; } this.limitCanvas(true, false); } } if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) { canvasData.left = canvasData.oldLeft; } if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) { canvasData.top = canvasData.oldTop; } canvasData.width = min( max(canvasData.width, canvasData.minWidth), canvasData.maxWidth ); canvasData.height = min( max(canvasData.height, canvasData.minHeight), canvasData.maxHeight ); this.limitCanvas(false, true); canvasData.oldLeft = canvasData.left = min( max(canvasData.left, canvasData.minLeft), canvasData.maxLeft ); canvasData.oldTop = canvasData.top = min( max(canvasData.top, canvasData.minTop), canvasData.maxTop ); this.canvas.style.cssText = ( 'width:' + canvasData.width + 'px;' + 'height:' + canvasData.height + 'px;' + 'left:' + canvasData.left + 'px;' + 'top:' + canvasData.top + 'px;' ); this.renderImage(); if (this.isCropped && this.isLimited) { this.limitCropBox(true, true); } if (isChanged) { this.output(); } }, renderImage: function (isChanged) { var canvasData = this.canvasData; var imageData = this.imageData; var reversedData; var transform; if (imageData.rotate) { reversedData = getRotatedSizes({ width: canvasData.width, height: canvasData.height, degree: imageData.rotate, aspectRatio: imageData.aspectRatio }, true); } extend(imageData, reversedData ? { width: reversedData.width, height: reversedData.height, left: (canvasData.width - reversedData.width) / 2, top: (canvasData.height - reversedData.height) / 2 } : { width: canvasData.width, height: canvasData.height, left: 0, top: 0 }); transform = getTransform(imageData); this.image.style.cssText = ( 'width:' + imageData.width + 'px;' + 'height:' + imageData.height + 'px;' + 'margin-left:' + imageData.left + 'px;' + 'margin-top:' + imageData.top + 'px;' + '-webkit-transform:' + transform + ';' + '-ms-transform:' + transform + ';' + 'transform:' + transform + ';' ); if (isChanged) { this.output(); } }, initCropBox: function () { var options = this.options; var aspectRatio = options.aspectRatio; var autoCropArea = num(options.autoCropArea) || 0.8; var canvasData = this.canvasData; var cropBoxData = { width: canvasData.width, height: canvasData.height }; if (aspectRatio) { if (canvasData.height * aspectRatio > canvasData.width) { cropBoxData.height = cropBoxData.width / aspectRatio; } else { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.cropBoxData = cropBoxData; this.limitCropBox(true, true); // Initialize auto crop area cropBoxData.width = min( max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth ); cropBoxData.height = min( max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight ); // The width/height of auto crop area must large than "minWidth/Height" cropBoxData.width = max( cropBoxData.minWidth, cropBoxData.width * autoCropArea ); cropBoxData.height = max( cropBoxData.minHeight, cropBoxData.height * autoCropArea ); cropBoxData.oldLeft = cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2; cropBoxData.oldTop = cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2; this.initialCropBoxData = extend({}, cropBoxData); }, limitCropBox: function (isSizeLimited, isPositionLimited) { var options = this.options; var aspectRatio = options.aspectRatio; var containerData = this.containerData; var containerWidth = containerData.width; var containerHeight = containerData.height; var canvasData = this.canvasData; var cropBoxData = this.cropBoxData; var isLimited = this.isLimited; var minCropBoxWidth; var minCropBoxHeight; var maxCropBoxWidth; var maxCropBoxHeight; if (isSizeLimited) { minCropBoxWidth = num(options.minCropBoxWidth) || 0; minCropBoxHeight = num(options.minCropBoxHeight) || 0; // The min/maxCropBoxWidth/Height must be less than containerWidth/Height minCropBoxWidth = min(minCropBoxWidth, containerWidth); minCropBoxHeight = min(minCropBoxHeight, containerHeight); maxCropBoxWidth = min(containerWidth, isLimited ? canvasData.width : containerWidth); maxCropBoxHeight = min(containerHeight, isLimited ? canvasData.height : containerHeight); if (aspectRatio) { if (minCropBoxWidth && minCropBoxHeight) { if (minCropBoxHeight * aspectRatio > minCropBoxWidth) { minCropBoxHeight = minCropBoxWidth / aspectRatio; } else { minCropBoxWidth = minCropBoxHeight * aspectRatio; } } else if (minCropBoxWidth) { minCropBoxHeight = minCropBoxWidth / aspectRatio; } else if (minCropBoxHeight) { minCropBoxWidth = minCropBoxHeight * aspectRatio; } if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) { maxCropBoxHeight = maxCropBoxWidth / aspectRatio; } else { maxCropBoxWidth = maxCropBoxHeight * aspectRatio; } } // The minWidth/Height must be less than maxWidth/Height cropBoxData.minWidth = min(minCropBoxWidth, maxCropBoxWidth); cropBoxData.minHeight = min(minCropBoxHeight, maxCropBoxHeight); cropBoxData.maxWidth = maxCropBoxWidth; cropBoxData.maxHeight = maxCropBoxHeight; } if (isPositionLimited) { if (isLimited) { cropBoxData.minLeft = max(0, canvasData.left); cropBoxData.minTop = max(0, canvasData.top); cropBoxData.maxLeft = min(containerWidth, canvasData.left + canvasData.width) - cropBoxData.width; cropBoxData.maxTop = min(containerHeight, canvasData.top + canvasData.height) - cropBoxData.height; } else { cropBoxData.minLeft = 0; cropBoxData.minTop = 0; cropBoxData.maxLeft = containerWidth - cropBoxData.width; cropBoxData.maxTop = containerHeight - cropBoxData.height; } } }, renderCropBox: function () { var options = this.options; var containerData = this.containerData; var containerWidth = containerData.width; var containerHeight = containerData.height; var cropBoxData = this.cropBoxData; if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) { cropBoxData.left = cropBoxData.oldLeft; } if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) { cropBoxData.top = cropBoxData.oldTop; } cropBoxData.width = min( max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth ); cropBoxData.height = min( max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight ); this.limitCropBox(false, true); cropBoxData.oldLeft = cropBoxData.left = min( max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft ); cropBoxData.oldTop = cropBoxData.top = min( max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop ); if (options.movable && options.cropBoxDataMovable) { // Turn to move the canvas when the crop box is equal to the container setData(this.face, DATA_ACTION, (cropBoxData.width === containerWidth && cropBoxData.height === containerHeight) ? ACTION_MOVE : ACTION_ALL); } this.cropBox.style.cssText = ( 'width:' + cropBoxData.width + 'px;' + 'height:' + cropBoxData.height + 'px;' + 'left:' + cropBoxData.left + 'px;' + 'top:' + cropBoxData.top + 'px;' ); if (this.isCropped && this.isLimited) { this.limitCanvas(true, true); } if (!this.isDisabled) { this.output(); } }, output: function () { var options = this.options; this.preview(); if (this.isCompleted && isFunction(options.crop)) { options.crop.call(this.element, this.getData()); } } }); extend(prototype, { initPreview: function () { var preview = this.options.preview; var image = document.createElement('img'); var crossOrigin = this.crossOrigin; var url = this.url; var previews; setCrossOrigin(image, crossOrigin); image.src = url; appendChild(this.viewBox, image); if (!preview) { return; } this.previews = previews = querySelectorAll(document, preview); each(previews, function (element) { var image = document.createElement('img'); // Save the original size for recover setData(element, DATA_PREVIEW, { width: element.offsetWidth, height: element.offsetHeight, html: element.innerHTML }); setCrossOrigin(image, crossOrigin); image.src = url; /** * Override img element styles * Add `display:block` to avoid margin top issue * Add `height:auto` to override `height` attribute on IE8 * (Occur only when margin-top <= -height) */ image.style.cssText = ( 'display:block;width:100%;height:auto;' + 'min-width:0!important;min-height:0!important;' + 'max-width:none!important;max-height:none!important;' + 'image-orientation:0deg!important;"' ); empty(element); appendChild(element, image); }); }, resetPreview: function () { each(this.previews, function (element) { var data = getData(element, DATA_PREVIEW); element.style.width = data.width + 'px'; element.style.height = data.height + 'px'; element.innerHTML = data.html; removeData(element, DATA_PREVIEW); }); }, preview: function () { var imageData = this.imageData; var canvasData = this.canvasData; var cropBoxData = this.cropBoxData; var cropBoxWidth = cropBoxData.width; var cropBoxHeight = cropBoxData.height; var width = imageData.width; var height = imageData.height; var left = cropBoxData.left - canvasData.left - imageData.left; var top = cropBoxData.top - canvasData.top - imageData.top; var transform = getTransform(imageData); if (!this.isCropped || this.isDisabled) { return; } querySelector(this.viewBox, 'img').style.cssText = ( 'width:' + width + 'px;' + 'height:' + height + 'px;' + 'margin-left:' + -left + 'px;' + 'margin-top:' + -top + 'px;' + '-webkit-transform:' + transform + ';' + '-ms-transform:' + transform + ';' + 'transform:' + transform + ';' ); each(this.previews, function (element) { var imageStyle = querySelector(element, 'img').style; var data = getData(element, DATA_PREVIEW); var originalWidth = data.width; var originalHeight = data.height; var newWidth = originalWidth; var newHeight = originalHeight; var ratio = 1; if (cropBoxWidth) { ratio = originalWidth / cropBoxWidth; newHeight = cropBoxHeight * ratio; } if (cropBoxHeight && newHeight > originalHeight) { ratio = originalHeight / cropBoxHeight; newWidth = cropBoxWidth * ratio; newHeight = originalHeight; } element.style.width = newWidth + 'px'; element.style.height = newHeight + 'px'; imageStyle.width = width * ratio + 'px'; imageStyle.height = height * ratio + 'px'; imageStyle.marginLeft = -left * ratio + 'px'; imageStyle.marginTop = -top * ratio + 'px'; imageStyle.WebkitTransform = transform; imageStyle.msTransform = transform; imageStyle.transform = transform; }); } }); extend(prototype, { bind: function () { var options = this.options; var cropper = this.cropper; addListener(cropper, EVENT_MOUSE_DOWN, proxy(this.cropStart, this)); if (options.zoomable && options.zoomOnWheel) { addListener(cropper, EVENT_WHEEL, proxy(this.wheel, this)); } if (options.toggleDragModeOnDblclick) { addListener(cropper, EVENT_DBLCLICK, proxy(this.dblclick, this)); } addListener(document, EVENT_MOUSE_MOVE, (this._cropMove = proxy(this.cropMove, this))); addListener(document, EVENT_MOUSE_UP, (this._cropEnd = proxy(this.cropEnd, this))); if (options.responsive) { addListener(window, EVENT_RESIZE, (this._resize = proxy(this.resize, this))); } }, unbind: function () { var options = this.options; var cropper = this.cropper; removeListener(cropper, EVENT_MOUSE_DOWN, this.cropStart); if (options.zoomable && options.zoomOnWheel) { removeListener(cropper, EVENT_WHEEL, this.wheel); } if (options.toggleDragModeOnDblclick) { removeListener(cropper, EVENT_DBLCLICK, this.dblclick); } removeListener(document, EVENT_MOUSE_MOVE, this._cropMove); removeListener(document, EVENT_MOUSE_UP, this._cropEnd); if (options.responsive) { removeListener(window, EVENT_RESIZE, this._resize); } } }); extend(prototype, { resize: function () { var restore = this.options.restore; var container = this.container; var containerData = this.containerData; var canvasData; var cropBoxData; var ratio; // Check `container` is necessary for IE8 if (this.isDisabled || !containerData) { return; } ratio = container.offsetWidth / containerData.width; // Resize when width changed or height changed if (ratio !== 1 || container.offsetHeight !== containerData.height) { if (restore) { canvasData = this.getCanvasData(); cropBoxData = this.getCropBoxData(); } this.render(); if (restore) { this.setCanvasData(each(canvasData, function (n, i) { canvasData[i] = n * ratio; })); this.setCropBoxData(each(cropBoxData, function (n, i) { cropBoxData[i] = n * ratio; })); } } }, dblclick: function () { if (this.isDisabled) { return; } this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? ACTION_MOVE : ACTION_CROP); }, wheel: function (event) { var e = getEvent(event); var ratio = num(this.options.wheelZoomRatio) || 0.1; var delta = 1; if (this.isDisabled) { return; } preventDefault(e); if (e.deltaY) { delta = e.deltaY > 0 ? 1 : -1; } else if (e.wheelDelta) { delta = -e.wheelDelta / 120; } else if (e.detail) { delta = e.detail > 0 ? 1 : -1; } this.zoom(-delta * ratio, e); }, cropStart: function (event) { var options = this.options; var e = getEvent(event); var touches = e.touches; var touchesLength; var touch; var action; if (this.isDisabled) { return; } if (touches) { touchesLength = touches.length; if (touchesLength > 1) { if (options.zoomable && options.zoomOnTouch && touchesLength === 2) { touch = touches[1]; this.startX2 = touch.pageX; this.startY2 = touch.pageY; action = ACTION_ZOOM; } else { return; } } touch = touches[0]; } action = action || getData(e.target, DATA_ACTION); if (REGEXP_ACTIONS.test(action)) { if (isFunction(options.cropstart) && options.cropstart.call(this.element, { originalEvent: e, action: action }) === false) { return; } preventDefault(e); this.action = action; this.cropping = false; this.startX = touch ? touch.pageX : e.pageX; this.startY = touch ? touch.pageY : e.pageY; if (action === ACTION_CROP) { this.cropping = true; addClass(this.dragBox, CLASS_MODAL); } } }, cropMove: function (event) { var options = this.options; var e = getEvent(event); var touches = e.touches; var action = this.action; var touchesLength; var touch; if (this.isDisabled) { return; } if (touches) { touchesLength = touches.length; if (touchesLength > 1) { if (options.zoomable && options.zoomOnTouch && touchesLength === 2) { touch = touches[1]; this.endX2 = touch.pageX; this.endY2 = touch.pageY; } else { return; } } touch = touches[0]; } if (action) { if (isFunction(options.cropmove) && options.cropmove.call(this.element, { originalEvent: e, action: action }) === false) { return; } preventDefault(e); this.endX = touch ? touch.pageX : e.pageX; this.endY = touch ? touch.pageY : e.pageY; this.change(e.shiftKey, action === ACTION_ZOOM ? e : null); } }, cropEnd: function (event) { var options = this.options; var e = getEvent(event); var action = this.action; if (this.isDisabled) { return; } if (action) { preventDefault(e); if (this.cropping) { this.cropping = false; toggleClass(this.dragBox, CLASS_MODAL, this.isCropped && options.modal); } this.action = ''; if (isFunction(options.cropend)) { options.cropend.call(this.element, { originalEvent: e, action: action }); } } } }); extend(prototype, { change: function (shiftKey, originalEvent) { var options = this.options; var aspectRatio = options.aspectRatio; var action = this.action; var containerData = this.containerData; var canvasData = this.canvasData; var cropBoxData = this.cropBoxData; var width = cropBoxData.width; var height = cropBoxData.height; var left = cropBoxData.left; var top = cropBoxData.top; var right = left + width; var bottom = top + height; var minLeft = 0; var minTop = 0; var maxWidth = containerData.width; var maxHeight = containerData.height; var renderable = true; var offset; var range; // Locking aspect ratio in "free mode" by holding shift key if (!aspectRatio && shiftKey) { aspectRatio = width && height ? width / height : 1; } if (this.isLimited) { minLeft = cropBoxData.minLeft; minTop = cropBoxData.minTop; maxWidth = minLeft + min(containerData.width, canvasData.width); maxHeight = minTop + min(containerData.height, canvasData.height); } range = { x: this.endX - this.startX, y: this.endY - this.startY }; if (aspectRatio) { range.X = range.y * aspectRatio; range.Y = range.x / aspectRatio; } switch (action) { // Move crop box case ACTION_ALL: left += range.x; top += range.y; break; // Resize crop box case ACTION_EAST: if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) { renderable = false; break; } width += range.x; if (aspectRatio) { height = width / aspectRatio; top -= range.Y / 2; } if (width < 0) { action = ACTION_WEST; width = 0; } break; case ACTION_NORTH: if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) { renderable = false; break; } height -= range.y; top += range.y; if (aspectRatio) { width = height * aspectRatio; left += range.X / 2; } if (height < 0) { action = ACTION_SOUTH; height = 0; } break; case ACTION_WEST: if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) { renderable = false; break; } width -= range.x; left += range.x; if (aspectRatio) { height = width / aspectRatio; top += range.Y / 2; } if (width < 0) { action = ACTION_EAST; width = 0; } break; case ACTION_SOUTH: if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) { renderable = false; break; } height += range.y; if (aspectRatio) { width = height * aspectRatio; left -= range.X / 2; } if (height < 0) { action = ACTION_NORTH; height = 0; } break; case ACTION_NORTH_EAST: if (aspectRatio) { if (range.y <= 0 && (top <= minTop || right >= maxWidth)) { renderable = false; break; } height -= range.y; top += range.y; width = height * aspectRatio; } else { if (range.x >= 0) { if (right < maxWidth) { width += range.x; } else if (range.y <= 0 && top <= minTop) { renderable = false; } } else { width += range.x; } if (range.y <= 0) { if (top > minTop) { height -= range.y; top += range.y; } } else { height -= range.y; top += range.y; } } if (width < 0 && height < 0) { action = ACTION_SOUTH_WEST; height = 0; width = 0; } else if (width < 0) { action = ACTION_NORTH_WEST; width = 0; } else if (height < 0) { action = ACTION_SOUTH_EAST; height = 0; } break; case ACTION_NORTH_WEST: if (aspectRatio) { if (range.y <= 0 && (top <= minTop || left <= minLeft)) { renderable = false; break; } height -= range.y; top += range.y; width = height * aspectRatio; left += range.X; } else { if (range.x <= 0) { if (left > minLeft) { width -= range.x; left += range.x; } else if (range.y <= 0 && top <= minTop) { renderable = false; } } else { width -= range.x; left += range.x; } if (range.y <= 0) { if (top > minTop) { height -= range.y; top += range.y; } } else { height -= range.y; top += range.y; } } if (width < 0 && height < 0) { action = ACTION_SOUTH_EAST; height = 0; width = 0; } else if (width < 0) { action = ACTION_NORTH_EAST; width = 0; } else if (height < 0) { action = ACTION_SOUTH_WEST; height = 0; } break; case ACTION_SOUTH_WEST: if (aspectRatio) { if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) { renderable = false; break; } width -= range.x; left += range.x; height = width / aspectRatio; } else { if (range.x <= 0) { if (left > minLeft) { width -= range.x; left += range.x; } else if (range.y >= 0 && bottom >= maxHeight) { renderable = false; } } else { width -= range.x; left += range.x; } if (range.y >= 0) { if (bottom < maxHeight) { height += range.y; } } else { height += range.y; } } if (width < 0 && height < 0) { action = ACTION_NORTH_EAST; height = 0; width = 0; } else if (width < 0) { action = ACTION_SOUTH_EAST; width = 0; } else if (height < 0) { action = ACTION_NORTH_WEST; height = 0; } break; case ACTION_SOUTH_EAST: if (aspectRatio) { if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) { renderable = false; break; } width += range.x; height = width / aspectRatio; } else { if (range.x >= 0) { if (right < maxWidth) { width += range.x; } else if (range.y >= 0 && bottom >= maxHeight) { renderable = false; } } else { width += range.x; } if (range.y >= 0) { if (bottom < maxHeight) { height += range.y; } } else { height += range.y; } } if (width < 0 && height < 0) { action = ACTION_NORTH_WEST; height = 0; width = 0; } else if (width < 0) { action = ACTION_SOUTH_WEST; width = 0; } else if (height < 0) { action = ACTION_NORTH_EAST; height = 0; } break; // Move canvas case ACTION_MOVE: this.move(range.x, range.y); renderable = false; break; // Zoom canvas case ACTION_ZOOM: this.zoom((function (x1, y1, x2, y2) { var z1 = sqrt(x1 * x1 + y1 * y1); var z2 = sqrt(x2 * x2 + y2 * y2); return (z2 - z1) / z1; })( abs(this.startX - this.startX2), abs(this.startY - this.startY2), abs(this.endX - this.endX2), abs(this.endY - this.endY2) ), originalEvent); this.startX2 = this.endX2; this.startY2 = this.endY2; renderable = false; break; // Create crop box case ACTION_CROP: if (!range.x || !range.y) { renderable = false; break; } offset = getOffset(this.cropper); left = this.startX - offset.left; top = this.startY - offset.top; width = cropBoxData.minWidth; height = cropBoxData.minHeight; if (range.x > 0) { action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST; } else if (range.x < 0) { left -= width; action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST; } if (range.y < 0) { top -= height; } // Show the crop box if is hidden if (!this.isCropped) { removeClass(this.cropBox, CLASS_HIDDEN); this.isCropped = true; if (this.isLimited) { this.limitCropBox(true, true); } } break; // No default } if (renderable) { cropBoxData.width = width; cropBoxData.height = height; cropBoxData.left = left; cropBoxData.top = top; this.action = action; this.renderCropBox(); } // Override this.startX = this.endX; this.startY = this.endY; } }); extend(prototype, { // Show the crop box manually crop: function () { if (this.isBuilt && !this.isDisabled) { if (!this.isCropped) { this.isCropped = true; this.limitCropBox(true, true); if (this.options.modal) { addClass(this.dragBox, CLASS_MODAL); } removeClass(this.cropBox, CLASS_HIDDEN); } this.setCropBoxData(this.initialCropBoxData); } return this; }, // Reset the image and crop box to their initial states reset: function () { if (this.isBuilt && !this.isDisabled) { this.imageData = extend({}, this.initialImageData); this.canvasData = extend({}, this.initialCanvasData); this.cropBoxData = extend({}, this.initialCropBoxData); this.renderCanvas(); if (this.isCropped) { this.renderCropBox(); } } return this; }, // Clear the crop box clear: function () { if (this.isCropped && !this.isDisabled) { extend(this.cropBoxData, { left: 0, top: 0, width: 0, height: 0 }); this.isCropped = false; this.renderCropBox(); this.limitCanvas(); // Render canvas after crop box rendered this.renderCanvas(); removeClass(this.dragBox, CLASS_MODAL); addClass(this.cropBox, CLASS_HIDDEN); } return this; }, /** * Replace the image's src and rebuild the cropper * * @param {String} url */ replace: function (url) { if (!this.isDisabled && url) { if (this.isImg) { this.isReplaced = true; this.element.src = url; } // Clear previous data this.options.data = null; this.load(url); } return this; }, // Enable (unfreeze) the cropper enable: function () { if (this.isBuilt) { this.isDisabled = false; removeClass(this.cropper, CLASS_DISABLED); } return this; }, // Disable (freeze) the cropper disable: function () { if (this.isBuilt) { this.isDisabled = true; addClass(this.cropper, CLASS_DISABLED); } return this; }, // Destroy the cropper and remove the instance from the image destroy: function () { var element = this.element; var image = this.image; if (this.isLoaded) { if (this.isImg && this.isReplaced) { element.src = this.originalUrl; } this.unbuild(); removeClass(element, CLASS_HIDDEN); } else { if (this.isImg) { element.off(EVENT_LOAD, this.start); } else if (image) { removeChild(image); } } removeData(element, NAMESPACE); return this; }, /** * Move the canvas with relative offsets * * @param {Number} offsetX * @param {Number} offsetY (optional) */ move: function (offsetX, offsetY) { var canvasData = this.canvasData; return this.moveTo( isUndefined(offsetX) ? offsetX : canvasData.left + num(offsetX), isUndefined(offsetY) ? offsetY : canvasData.top + num(offsetY) ); }, /** * Move the canvas to an absolute point * * @param {Number} x * @param {Number} y (optional) */ moveTo: function (x, y) { var canvasData = this.canvasData; var isChanged = false; // If "y" is not present, its default value is "x" if (isUndefined(y)) { y = x; } x = num(x); y = num(y); if (this.isBuilt && !this.isDisabled && this.options.movable) { if (isNumber(x)) { canvasData.left = x; isChanged = true; } if (isNumber(y)) { canvasData.top = y; isChanged = true; } if (isChanged) { this.renderCanvas(true); } } return this; }, /** * Zoom the canvas with a relative ratio * * @param {Number} ratio * @param {Event} _originalEvent (private) */ zoom: function (ratio, _originalEvent) { var canvasData = this.canvasData; ratio = num(ratio); if (ratio < 0) { ratio = 1 / (1 - ratio); } else { ratio = 1 + ratio; } return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, _originalEvent); }, /** * Zoom the canvas to an absolute ratio * * @param {Number} ratio * @param {Event} _originalEvent (private) */ zoomTo: function (ratio, _originalEvent) { var options = this.options; var canvasData = this.canvasData; var width = canvasData.width; var height = canvasData.height; var naturalWidth = canvasData.naturalWidth; var naturalHeight = canvasData.naturalHeight; var newWidth; var newHeight; ratio = num(ratio); if (ratio >= 0 && this.isBuilt && !this.isDisabled && options.zoomable) { newWidth = naturalWidth * ratio; newHeight = naturalHeight * ratio; if (isFunction(options.zoom) && options.zoom.call(this.element, { originalEvent: _originalEvent, oldRatio: width / naturalWidth, ratio: newWidth / naturalWidth }) === false) { return this; } canvasData.left -= (newWidth - width) / 2; canvasData.top -= (newHeight - height) / 2; canvasData.width = newWidth; canvasData.height = newHeight; this.renderCanvas(true); } return this; }, /** * Rotate the canvas with a relative degree * * @param {Number} degree */ rotate: function (degree) { return this.rotateTo((this.imageData.rotate || 0) + num(degree)); }, /** * Rotate the canvas to an absolute degree * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#rotate() * * @param {Number} degree */ rotateTo: function (degree) { degree = num(degree); if (isNumber(degree) && this.isBuilt && !this.isDisabled && this.options.rotatable) { this.imageData.rotate = degree % 360; this.isRotated = true; this.renderCanvas(true); } return this; }, /** * Scale the image * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#scale() * * @param {Number} scaleX * @param {Number} scaleY (optional) */ scale: function (scaleX, scaleY) { var imageData = this.imageData; var isChanged = false; // If "scaleY" is not present, its default value is "scaleX" if (isUndefined(scaleY)) { scaleY = scaleX; } scaleX = num(scaleX); scaleY = num(scaleY); if (this.isBuilt && !this.isDisabled && this.options.scalable) { if (isNumber(scaleX)) { imageData.scaleX = scaleX; isChanged = true; } if (isNumber(scaleY)) { imageData.scaleY = scaleY; isChanged = true; } if (isChanged) { this.renderImage(true); } } return this; }, /** * Scale the abscissa of the image * * @param {Number} scaleX */ scaleX: function (scaleX) { var scaleY = this.imageData.scaleY; return this.scale(scaleX, isNumber(scaleY) ? scaleY : 1); }, /** * Scale the ordinate of the image * * @param {Number} scaleY */ scaleY: function (scaleY) { var scaleX = this.imageData.scaleX; return this.scale(isNumber(scaleX) ? scaleX : 1, scaleY); }, /** * Get the cropped area position and size data (base on the original image) * * @param {Boolean} isRounded (optional) * @return {Object} data */ getData: function (isRounded) { var options = this.options; var imageData = this.imageData; var canvasData = this.canvasData; var cropBoxData = this.cropBoxData; var ratio; var data; if (this.isBuilt && this.isCropped) { data = { x: cropBoxData.left - canvasData.left, y: cropBoxData.top - canvasData.top, width: cropBoxData.width, height: cropBoxData.height }; ratio = imageData.width / imageData.naturalWidth; each(data, function (n, i) { n = n / ratio; data[i] = isRounded ? round(n) : n; }); } else { data = { x: 0, y: 0, width: 0, height: 0 }; } if (options.rotatable) { data.rotate = imageData.rotate || 0; } if (options.scalable) { data.scaleX = imageData.scaleX || 1; data.scaleY = imageData.scaleY || 1; } return data; }, /** * Set the cropped area position and size with new data * * @param {Object} data */ setData: function (data) { var options = this.options; var imageData = this.imageData; var canvasData = this.canvasData; var cropBoxData = {}; var isRotated; var isScaled; var ratio; if (isFunction(data)) { data = data.call(this.element); } if (this.isBuilt && !this.isDisabled && isPlainObject(data)) { if (options.rotatable) { if (isNumber(data.rotate) && data.rotate !== imageData.rotate) { imageData.rotate = data.rotate; this.isRotated = isRotated = true; } } if (options.scalable) { if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) { imageData.scaleX = data.scaleX; isScaled = true; } if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) { imageData.scaleY = data.scaleY; isScaled = true; } } if (isRotated) { this.renderCanvas(); } else if (isScaled) { this.renderImage(); } ratio = imageData.width / imageData.naturalWidth; if (isNumber(data.x)) { cropBoxData.left = data.x * ratio + canvasData.left; } if (isNumber(data.y)) { cropBoxData.top = data.y * ratio + canvasData.top; } if (isNumber(data.width)) { cropBoxData.width = data.width * ratio; } if (isNumber(data.height)) { cropBoxData.height = data.height * ratio; } this.setCropBoxData(cropBoxData); } return this; }, /** * Get the container size data * * @return {Object} data */ getContainerData: function () { return this.isBuilt ? this.containerData : {}; }, /** * Get the image position and size data * * @return {Object} data */ getImageData: function () { return this.isLoaded ? this.imageData : {}; }, /** * Get the canvas position and size data * * @return {Object} data */ getCanvasData: function () { var canvasData = this.canvasData; var data = {}; if (this.isBuilt) { each([ 'left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight' ], function (n) { data[n] = canvasData[n]; }); } return data; }, /** * Set the canvas position and size with new data * * @param {Object} data */ setCanvasData: function (data) { var canvasData = this.canvasData; var aspectRatio = canvasData.aspectRatio; if (isFunction(data)) { data = data.call(this.element); } if (this.isBuilt && !this.isDisabled && isPlainObject(data)) { if (isNumber(data.left)) { canvasData.left = data.left; } if (isNumber(data.top)) { canvasData.top = data.top; } if (isNumber(data.width)) { canvasData.width = data.width; canvasData.height = data.width / aspectRatio; } else if (isNumber(data.height)) { canvasData.height = data.height; canvasData.width = data.height * aspectRatio; } this.renderCanvas(true); } return this; }, /** * Get the crop box position and size data * * @return {Object} data */ getCropBoxData: function () { var cropBoxData = this.cropBoxData; var data; if (this.isBuilt && this.isCropped) { data = { left: cropBoxData.left, top: cropBoxData.top, width: cropBoxData.width, height: cropBoxData.height }; } return data || {}; }, /** * Set the crop box position and size with new data * * @param {Object} data */ setCropBoxData: function (data) { var cropBoxData = this.cropBoxData; var aspectRatio = this.options.aspectRatio; var isWidthChanged; var isHeightChanged; if (isFunction(data)) { data = data.call(this.element); } if (this.isBuilt && this.isCropped && !this.isDisabled && isPlainObject(data)) { if (isNumber(data.left)) { cropBoxData.left = data.left; } if (isNumber(data.top)) { cropBoxData.top = data.top; } if (isNumber(data.width) && data.width !== cropBoxData.width) { isWidthChanged = true; cropBoxData.width = data.width; } if (isNumber(data.height) && data.height !== cropBoxData.height) { isHeightChanged = true; cropBoxData.height = data.height; } if (aspectRatio) { if (isWidthChanged) { cropBoxData.height = cropBoxData.width / aspectRatio; } else if (isHeightChanged) { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.renderCropBox(); } return this; }, /** * Get a canvas drawn the cropped image * * @param {Object} options (optional) * @return {HTMLCanvasElement} canvas */ getCroppedCanvas: function (options) { var originalWidth; var originalHeight; var canvasWidth; var canvasHeight; var scaledWidth; var scaledHeight; var scaledRatio; var aspectRatio; var canvas; var context; var data; if (!this.isBuilt || !this.isCropped || !SUPPORT_CANVAS) { return; } if (!isPlainObject(options)) { options = {}; } data = this.getData(); originalWidth = data.width; originalHeight = data.height; aspectRatio = originalWidth / originalHeight; if (isPlainObject(options)) { scaledWidth = options.width; scaledHeight = options.height; if (scaledWidth) { scaledHeight = scaledWidth / aspectRatio; scaledRatio = scaledWidth / originalWidth; } else if (scaledHeight) { scaledWidth = scaledHeight * aspectRatio; scaledRatio = scaledHeight / originalHeight; } } // The canvas element will use `Math.floor` on a float number, so round first canvasWidth = round(scaledWidth || originalWidth); canvasHeight = round(scaledHeight || originalHeight); canvas = document.createElement('canvas'); canvas.width = canvasWidth; canvas.height = canvasHeight; context = canvas.getContext('2d'); if (options.fillColor) { context.fillStyle = options.fillColor; context.fillRect(0, 0, canvasWidth, canvasHeight); } // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage context.drawImage.apply(context, (function () { var source = getSourceCanvas(this.image, this.imageData); var sourceWidth = source.width; var sourceHeight = source.height; var args = [source]; // Source canvas var srcX = data.x; var srcY = data.y; var srcWidth; var srcHeight; // Destination canvas var dstX; var dstY; var dstWidth; var dstHeight; if (srcX <= -originalWidth || srcX > sourceWidth) { srcX = srcWidth = dstX = dstWidth = 0; } else if (srcX <= 0) { dstX = -srcX; srcX = 0; srcWidth = dstWidth = min(sourceWidth, originalWidth + srcX); } else if (srcX <= sourceWidth) { dstX = 0; srcWidth = dstWidth = min(originalWidth, sourceWidth - srcX); } if (srcWidth <= 0 || srcY <= -originalHeight || srcY > sourceHeight) { srcY = srcHeight = dstY = dstHeight = 0; } else if (srcY <= 0) { dstY = -srcY; srcY = 0; srcHeight = dstHeight = min(sourceHeight, originalHeight + srcY); } else if (srcY <= sourceHeight) { dstY = 0; srcHeight = dstHeight = min(originalHeight, sourceHeight - srcY); } args.push(floor(srcX), floor(srcY), floor(srcWidth), floor(srcHeight)); // Scale destination sizes if (scaledRatio) { dstX *= scaledRatio; dstY *= scaledRatio; dstWidth *= scaledRatio; dstHeight *= scaledRatio; } // Avoid "IndexSizeError" in IE and Firefox if (dstWidth > 0 && dstHeight > 0) { args.push(floor(dstX), floor(dstY), floor(dstWidth), floor(dstHeight)); } return args; }).call(this)); return canvas; }, /** * Change the aspect ratio of the crop box * * @param {Number} aspectRatio */ setAspectRatio: function (aspectRatio) { var options = this.options; if (!this.isDisabled && !isUndefined(aspectRatio)) { // 0 -> NaN options.aspectRatio = max(0, aspectRatio) || NaN; if (this.isBuilt) { this.initCropBox(); if (this.isCropped) { this.renderCropBox(); } } } return this; }, /** * Change the drag mode * * @param {String} mode (optional) */ setDragMode: function (mode) { var options = this.options; var dragBox = this.dragBox; var face = this.face; var croppable; var movable; if (this.isLoaded && !this.isDisabled) { croppable = mode === ACTION_CROP; movable = options.movable && mode === ACTION_MOVE; mode = (croppable || movable) ? mode : ACTION_NONE; setData(dragBox, DATA_ACTION, mode); toggleClass(dragBox, CLASS_CROP, croppable); toggleClass(dragBox, CLASS_MOVE, movable); if (!options.cropBoxMovable) { // Sync drag mode to crop box when it is not movable setData(face, DATA_ACTION, mode); toggleClass(face, CLASS_CROP, croppable); toggleClass(face, CLASS_MOVE, movable); } } return this; } }); extend(Cropper.prototype, prototype); Cropper.DEFAULTS = { // Define the view mode of the cropper viewMode: 0, // 0, 1, 2, 3 // Define the dragging mode of the cropper dragMode: 'crop', // 'crop', 'move' or 'none' // Define the aspect ratio of the crop box aspectRatio: NaN, // An object with the previous cropping result data data: null, // A selector for adding extra containers to preview preview: '', // Re-render the cropper when resize the window responsive: true, // Restore the cropped area after resize the window restore: true, // Check if the target image is cross origin checkCrossOrigin: true, // Show the black modal modal: true, // Show the dashed lines for guiding guides: true, // Show the center indicator for guiding center: true, // Show the white modal to highlight the crop box highlight: true, // Show the grid background background: true, // Enable to crop the image automatically when initialize autoCrop: true, // Define the percentage of automatic cropping area when initializes autoCropArea: 0.8, // Enable to move the image movable: true, // Enable to rotate the image rotatable: true, // Enable to scale the image scalable: true, // Enable to zoom the image zoomable: true, // Enable to zoom the image by dragging touch zoomOnTouch: true, // Enable to zoom the image by wheeling mouse zoomOnWheel: true, // Define zoom ratio when zoom the image by wheeling mouse wheelZoomRatio: 0.1, // Enable to move the crop box cropBoxMovable: true, // Enable to resize the crop box cropBoxResizable: true, // Toggle drag mode between "crop" and "move" when click twice on the cropper toggleDragModeOnDblclick: true, // Size limitation minCanvasWidth: 0, minCanvasHeight: 0, minCropBoxWidth: 0, minCropBoxHeight: 0, minContainerWidth: 200, minContainerHeight: 100, // Shortcuts of events build: null, built: null, cropstart: null, cropmove: null, cropend: null, crop: null, zoom: null }; Cropper.TEMPLATE = ( '<div class="cropper-container">' + '<div class="cropper-wrap-box">' + '<div class="cropper-canvas"></div>' + '</div>' + '<div class="cropper-drag-box"></div>' + '<div class="cropper-crop-box">' + '<span class="cropper-view-box"></span>' + '<span class="cropper-dashed dashed-h"></span>' + '<span class="cropper-dashed dashed-v"></span>' + '<span class="cropper-center"></span>' + '<span class="cropper-face"></span>' + '<span class="cropper-line line-e" data-action="e"></span>' + '<span class="cropper-line line-n" data-action="n"></span>' + '<span class="cropper-line line-w" data-action="w"></span>' + '<span class="cropper-line line-s" data-action="s"></span>' + '<span class="cropper-point point-e" data-action="e"></span>' + '<span class="cropper-point point-n" data-action="n"></span>' + '<span class="cropper-point point-w" data-action="w"></span>' + '<span class="cropper-point point-s" data-action="s"></span>' + '<span class="cropper-point point-ne" data-action="ne"></span>' + '<span class="cropper-point point-nw" data-action="nw"></span>' + '<span class="cropper-point point-sw" data-action="sw"></span>' + '<span class="cropper-point point-se" data-action="se"></span>' + '</div>' + '</div>' ); var _Cropper = window.Cropper; Cropper.noConflict = function () { window.Cropper = _Cropper; return Cropper; }; Cropper.setDefaults = function (options) { extend(Cropper.DEFAULTS, options); }; if (typeof define === 'function' && define.amd) { define('cropper', [], function () { return Cropper; }); } if (typeof noGlobal === 'undefined') { window.Cropper = Cropper; } return Cropper; });
redmunds/cdnjs
ajax/libs/cropperjs/0.4.0/cropper.js
JavaScript
mit
83,381
var isIterateeCall = require('./isIterateeCall'), rest = require('../rest'); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return rest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = typeof customizer == 'function' ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner;
zverevalexei/bierman-topology
web/node_modules/bower/node_modules/lodash/internal/createAssigner.js
JavaScript
mit
984
/// <reference path="../../typings/_custom.d.ts" /> /* * TODO: ES5 for now until I make a webpack plugin for protractor */ describe('App', function() { var subject; var result; beforeEach(function() { browser.get('/'); }); afterEach(function() { expect(subject).toEqual(result); }); it('should have a title', function() { subject = browser.getTitle(); result = 'Angular2 Webpack Starter by @gdi2990 from @AngularClass'; }); it('should have <header>', function() { subject = element(by.deepCss('app /deep/ header')).isPresent(); result = true; }); it('should have <main>', function() { subject = element(by.deepCss('app /deep/ main')).isPresent(); result = true; }); it('should have <footer>', function() { subject = element(by.deepCss('app /deep/ footer')).getText(); result = 'WebPack Angular 2 Starter by @AngularClass'; }); });
yanivefraim/angular2-webpack-starter
test/app/app.e2e.js
JavaScript
mit
916
/** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jshint evil:true*/ require('mock-modules').autoMockOff(); describe('static type function syntax', function() { var flowSyntaxVisitors; var jstransform; beforeEach(function() { require('mock-modules').dumpCache(); flowSyntaxVisitors = require('../type-syntax.js').visitorList; jstransform = require('jstransform'); }); function transform(code, visitors) { code = code.join('\n'); // We run the flow transform first code = jstransform.transform( flowSyntaxVisitors, code ).code; if (visitors) { code = jstransform.transform( visitors, code ).code; } return code; } describe('param type annotations', () => { it('strips single param annotation', () => { var code = transform([ 'function foo(param1: bool) {', ' return param1;', '}', '', 'var bar = function(param1: bool) {', ' return param1;', '}' ]); eval(code); expect(foo(42)).toBe(42); expect(bar(42)).toBe(42); }); it('strips multiple param annotations', () => { var code = transform([ 'function foo(param1: bool, param2: number) {', ' return [param1, param2];', '}', '', 'var bar = function(param1: bool, param2: number) {', ' return [param1, param2];', '}' ]); eval(code); expect(foo(true, 42)).toEqual([true, 42]); expect(bar(true, 42)).toEqual([true, 42]); }); it('strips higher-order param annotations', () => { var code = transform([ 'function foo(param1: (_:bool) => number) {', ' return param1;', '}', '', 'var bar = function(param1: (_:bool) => number) {', ' return param1;', '}' ]); eval(code); var callback = function(param) { return param ? 42 : 0; }; expect(foo(callback)).toBe(callback); expect(bar(callback)).toBe(callback); }); it('strips annotated params next to non-annotated params', () => { var code = transform([ 'function foo(param1, param2: number) {', ' return [param1, param2];', '}', '', 'var bar = function(param1, param2: number) {', ' return [param1, param2];', '}' ]); eval(code); expect(foo('p1', 42)).toEqual(['p1', 42]); expect(bar('p1', 42)).toEqual(['p1', 42]); }); it('strips annotated params before a rest parameter', () => { var restParamVisitors = require('../es6-rest-param-visitors').visitorList; var code = transform([ 'function foo(param1: number, ...args) {', ' return [param1, args];', '}', '', 'var bar = function(param1: number, ...args) {', ' return [param1, args];', '}' ], restParamVisitors); eval(code); expect(foo(42, 43, 44)).toEqual([42, [43, 44]]); expect(bar(42, 43, 44)).toEqual([42, [43, 44]]); }); it('strips annotated rest parameter', () => { var restParamVisitors = require('../es6-rest-param-visitors').visitorList; var code = transform([ 'function foo(param1: number, ...args: Array<number>) {', ' return [param1, args];', '}', '', 'var bar = function(param1: number, ...args: Array<number>) {', ' return [param1, args];', '}' ], restParamVisitors); eval(code); expect(foo(42, 43, 44)).toEqual([42, [43, 44]]); expect(bar(42, 43, 44)).toEqual([42, [43, 44]]); }); it('strips optional param marker without type annotation', () => { var code = transform([ 'function foo(param1?, param2 ?) {', ' return 42;', '}' ]); eval(code); expect(foo()).toBe(42); }); it('strips optional param marker with type annotation', () => { var code = transform([ 'function foo(param1?:number, param2 ?: string, param3 ? : bool) {', ' return 42;', '}' ]); eval(code); expect(foo()).toBe(42); }); }); describe('return type annotations', () => { it('strips function return types', () => { var code = transform([ 'function foo(param1:number): () => number {', ' return function() { return param1; };', '}', '', 'var bar = function(param1:number): () => number {', ' return function() { return param1; };', '}' ]); eval(code); expect(foo(42)()).toBe(42); expect(bar(42)()).toBe(42); }); it('strips void return types', () => { var code = transform([ 'function foo(param1): void {', ' param1();', '}', '', 'var bar = function(param1): void {', ' param1();', '}' ]); eval(code); var counter = 0; function testFn() { counter++; } foo(testFn); expect(counter).toBe(1); bar(testFn); expect(counter).toBe(2); }); it('strips void return types with rest params', () => { var code = transform( [ 'function foo(param1, ...rest): void {', ' param1();', '}', '', 'var bar = function(param1, ...rest): void {', ' param1();', '}' ], require('../es6-rest-param-visitors').visitorList ); eval(code); var counter = 0; function testFn() { counter++; } foo(testFn); expect(counter).toBe(1); bar(testFn); expect(counter).toBe(2); }); it('strips object return types', () => { var code = transform([ 'function foo(param1:number): {num: number} {', ' return {num: param1};', '}', '', 'var bar = function(param1:number): {num: number} {', ' return {num: param1};', '}' ]); eval(code); expect(foo(42)).toEqual({num: 42}); expect(bar(42)).toEqual({num: 42}); }); }); describe('parametric type annotation', () => { it('strips parametric type annotations', () => { var code = transform([ 'function foo<T>(param1) {', ' return param1;', '}', '', 'var bar = function<T>(param1) {', ' return param1;', '}', ]); eval(code); expect(foo(42)).toBe(42); expect(bar(42)).toBe(42); }); it('strips multi-parameter type annotations', () => { var restParamVisitors = require('../es6-rest-param-visitors').visitorList; var code = transform([ 'function foo<T, S>(param1) {', ' return param1;', '}', '', 'var bar = function<T,S>(param1) {', ' return param1;', '}' ], restParamVisitors); eval(code); expect(foo(42)).toBe(42); expect(bar(42)).toBe(42); }); }); describe('arrow functions', () => { // TODO: We don't currently support arrow functions, but we should // soon! The only reason we don't now is because we don't // need it at this very moment and I'm in a rush to get the // basics in. }); });
demns/todomvc-perf-comparison
todomvc/react/node_modules/reactify/node_modules/react-tools/node_modules/jstransform/visitors/__tests__/type-function-syntax-test.js
JavaScript
mit
7,860
(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){ var Core = _dereq_('../lib/Core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":5,"../lib/View":26}],2:[function(_dereq_,module,exports){ "use strict"; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. */ var Shared = _dereq_('./Shared'); /** * The active bucket class. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof obj[sortType.key]; if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += obj[sortType.key]; } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Shared":25}],3:[function(_dereq_,module,exports){ "use strict"; /** * The main collection class. Collections store multiple documents and * can operate on them using the query language to insert, read, update * and delete. */ var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Collection object used to store data. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // Set the subset to itself since it is the root collection this._subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Get the internal data * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (this._state !== 'dropped') { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log('Dropping collection ' + this._name); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); } } return this.$super.apply(this, arguments); }); /** * Sets the collection's data to the array of documents passed. * @param data * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw('ForerunnerDB.Collection "' + this.name() + '": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = JSON.stringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Handle transform update = this.transformIn(update); if (this.debug()) { console.log('Updating some collection data for collection "' + this.name() + '"'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (originalDoc) { var newDoc = self.decouple(originalDoc), triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, originalDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, originalDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, update, query, options, ''); } return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw('ForerunnerDB.Collection "' + this.name() + '": Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return true; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': this._updateIncrement(doc, i, update[i]); updated = true; break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw('ForerunnerDB.Collection "' + this.name() + '": Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = JSON.stringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (JSON.stringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!'); } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!'); } break; } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')'); } break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. * @private */ Collection.prototype.deferEmit = function () { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout if (this._changeTimeout) { clearTimeout(this._changeTimeout); } // Set a timeout this._changeTimeout = setTimeout(function () { if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. */ Collection.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } this[type](dataArr); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } } }; /** * Inserts a document or array of documents into the collection. * @param {Object||Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object||Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); this._onInsert(inserted, failed); if (callback) { callback(); } this.deferEmit('change', {type: 'insert', data: inserted}); return { inserted: inserted, failed: failed }; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc; this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = JSON.stringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = JSON.stringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Returns the index of the document identified by the passed item's primary key. * @param {Object} item The item whose primary key should be used to lookup. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (item) { return this._data.indexOf( this._primaryIndex.get( item[this._primaryKey] ) ); }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets the collection that this collection is a subset of. * @returns {Collection} */ Collection.prototype.subsetOf = function () { return this.__subsetOf; }; /** * Sets the collection that this collection is a subset of. * @param {Collection} collection The collection to set as the parent of this subset. * @returns {*} This object for chaining. * @private */ Collection.prototype._subsetOf = function (collection) { this.__subsetOf = collection; return this; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = JSON.stringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, //finalQuery, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearch, joinMulti, joinRequire, joinFindResults, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, matcher = function (doc) { return self._match(doc, query, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(query, options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } op.time('tableScan: ' + scanLength); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB joinCollectionInstance = this._db.collection(joinCollectionName); // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearch = {}; joinMulti = false; joinRequire = false; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; /*default: // Check for a double-dollar which is a back-reference to the root collection item if (joinMatchIndex.substr(0, 3) === '$$.') { // Back reference // TODO: Support complex joins } break;*/ } } else { // TODO: Could optimise this by caching path objects // Get the data to match against and store in the search object joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0]; } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearch); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @returns {Number} */ Collection.prototype.indexOf = function (query) { var item = this.find(query, {$decouple: false})[0]; if (item) { return this._data.indexOf(item); } }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = sortKey; sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets buckets = this.bucket(keyObj.___fdbKey, arr); // Loop buckets and sort contents for (i in buckets) { if (buckets.hasOwnProperty(i)) { arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i])); } } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, buckets = {}; for (i = 0; i < arr.length; i++) { buckets[arr[i][key]] = buckets[arr[i][key]] || []; buckets[arr[i][key]].push(arr[i]); } return buckets; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param match * @param path * @param subDocQuery * @param subDocOptions * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } resultObj.subDocs.push(subDocResults); resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.noStats) { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw('ForerunnerDB.Collection "' + this.name() + '": Collection diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); break; case 'update': obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); break; case 'remove': obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); break; default: } }); }, 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {Object} options An options object. * @returns {Collection} */ 'object': function (options) { return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This get's called by all the other variants and * handles the actual logic of the overloaded method. * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log('Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name).db(this); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { if (search) { if (search.exec(i)) { arr.push({ name: i, count: this._collection[i].count() }); } } else { arr.push({ name: i, count: this._collection[i].count() }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":6,"./IndexBinaryTree":8,"./IndexHashMap":9,"./KeyValueStore":10,"./Metrics":11,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":25}],4:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw('ForerunnerDB.CollectionGroup "' + this.name() + '": All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function () { if (this._state !== 'dropped') { var i, collArr, viewArr; if (this._debug) { console.log('Dropping collection group ' + this._name); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":3,"./Shared":25}],5:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB core object. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function () { this._db = {}; this._debug = {}; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":7,"./Metrics.js":11,"./Overload":22,"./Shared":25}],6:[function(_dereq_,module,exports){ "use strict"; var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB db object. * @constructor */ var Db = function (name) { this.init.apply(this, arguments); }; Db.prototype.init = function (name) { this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. */ '': function () { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name).core(this); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing. */ Core.prototype.databases = function (search) { var arr = [], i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { if (search) { if (search.exec(i)) { arr.push({ name: i, collectionCount: this._db[i].collections().length }); } } else { arr.push({ name: i, collectionCount: this._db[i].collections().length }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; module.exports = Db; },{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":11,"./Overload":22,"./Shared":25}],8:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), btree = function () {}; /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./Path":23,"./Shared":25}],9:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":23,"./Shared":25}],10:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":25}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":21,"./Shared":25}],12:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],13:[function(_dereq_,module,exports){ "use strict"; // TODO: Document the methods in this mixin var ChainReactor = { chain: function (obj) { this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, count = arr.length, index; for (index = 0; index < count; index++) { arr[index].chainReceive(this, type, data, options); } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],14:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return JSON.parse(JSON.stringify(data)); } else { var i, json = JSON.stringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(JSON.parse(json)); } return copyArr; } } return undefined; }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]) }; module.exports = Common; },{"./Overload":22}],15:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],16:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount; // Handle global emit if (this._listeners[event]['*']) { var arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key var listenerIdArr = this._listeners[event], listenerIdCount, listenerIdIndex; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } return this; } }; module.exports = Events; },{"./Overload":22}],17:[function(_dereq_,module,exports){ "use strict"; var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (typeof(source) === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (inArr[inArrIndex] === source) { return true; } } return false; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootQuery['//distinctLookup'] = options.$rootQuery['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootQuery['//distinctLookup'][distinctProp] = options.$rootQuery['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; } return -1; } }; module.exports = Matching; },{}],18:[function(_dereq_,module,exports){ "use strict"; var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],19:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":22}],20:[function(_dereq_,module,exports){ "use strict"; var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "' + prop + '" for "' + this.name() + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for "' + this.name() + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item from the array stack. * @param {Object} doc The document to modify. * @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false; if (doc.length > 0) { if (val === 1) { doc.pop(); updated = true; } else if (val === -1) { doc.shift(); updated = true; } } return updated; } }; module.exports = Updating; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":23,"./Shared":25}],22:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":25}],24:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); ReactorIO.prototype.drop = function () { if (this._state !== 'dropped') { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":25}],25:[function(_dereq_,module,exports){ "use strict"; var Shared = { version: '1.3.50', modules: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { this.modules[name] = module; this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { this.modules[name]._fdbFinished = true; this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: function (obj, mixinName) { var system = this.mixins[mixinName]; if (system) { for (var i in system) { if (system.hasOwnProperty(i)) { obj[i] = system[i]; } } } else { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } }, /** * Generates a generic getter/setter method for the passed method name. * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @param arr * @returns {Function} * @constructor */ overload: _dereq_('./Overload'), /** * Define the mixins that other modules can use as required. */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":12,"./Mixin.ChainReactor":13,"./Mixin.Common":14,"./Mixin.Constants":15,"./Mixin.Events":16,"./Mixin.Matching":17,"./Mixin.Sorting":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],26:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * The view constructor. * @param name * @param query * @param options * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection('__FDB__view_privateData_' + this._name); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); Shared.synthesize(View.prototype, 'name'); Shared.synthesize(View.prototype, 'cursor'); /** * Executes an insert against the view's underlying data-source. */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the collection from which the view will assemble its data. * @param {Collection} collection The collection to use to assemble view data. * @returns {View} */ View.prototype.from = function (collection) { var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" collection and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(collection, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = collection.find(this._querySettings.query, this._querySettings.options); this._transformPrimaryKey(collection.primaryKey()); this._transformSetData(collData); this._privateData.primaryKey(collection.primaryKey()); this._privateData.setData(collData); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } } return this; }; View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, //tempData, //dataIsArray, updates, //finalUpdates, primaryKey, tQuery, item, currentIndex, i; switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log('ForerunnerDB.View: Setting data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); // Modify transform data this._transformSetData(collData); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log('ForerunnerDB.View: Inserting some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log('ForerunnerDB.View: Updating some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } if (this._transformEnabled && this._transformIn) { primaryKey = this._publicData.primaryKey(); for (i = 0; i < updates.length; i++) { tQuery = {}; item = updates[i]; tQuery[primaryKey] = item[primaryKey]; this._transformUpdate(tQuery, item); } } break; case 'remove': if (this.debug()) { console.log('ForerunnerDB.View: Removing some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Modify transform data this._transformRemove(chainPacket.data.query, chainPacket.options); this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; View.prototype.on = function () { this._privateData.on.apply(this._privateData, arguments); }; View.prototype.off = function () { this._privateData.off.apply(this._privateData, arguments); }; View.prototype.emit = function () { this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._privateData.distinct.apply(this._privateData, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ View.prototype.primaryKey = function () { return this._privateData.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function () { if (this._state !== 'dropped') { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); if (this.debug() || (this._db && this._db.debug())) { console.log('ForerunnerDB.View: Dropping view ' + this._name); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } } else { return true; } return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ View.prototype.db = function (db) { if (db !== undefined) { this._db = db; this.privateData().db(db); this.publicData().db(db); return this; } return this._db; }; /** * Gets / sets the query that the view uses to build it's data set. * @param {Object=} query * @param {Boolean=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Gets / sets the query being used to generate the view data. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._privateData && this._privateData._data ? this._privateData._data.length : 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } // Update the transformed data object this._transformPrimaryKey(this.privateData().primaryKey()); this._transformSetData(this.privateData().find()); return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; /** * Updates the public data object to match data from the private data object * by running private data through the dataIn method provided in * the transform() call. * @private */ View.prototype._transformSetData = function (data) { if (this._transformEnabled) { // Clear existing data this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); this._publicData.setData(data); } }; View.prototype._transformInsert = function (data, index) { if (this._transformEnabled && this._publicData) { this._publicData.insert(data, index); } }; View.prototype._transformUpdate = function (query, update, options) { if (this._transformEnabled && this._publicData) { this._publicData.update(query, update, options); } }; View.prototype._transformRemove = function (query, options) { if (this._transformEnabled && this._publicData) { this._publicData.remove(query, options); } }; View.prototype._transformPrimaryKey = function (key) { if (this._transformEnabled && this._publicData) { this._publicData.primaryKey(key); } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { if (!this._view[viewName]) { if (this.debug() || (this._db && this._db.debug())) { console.log('Db.View: Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { arr.push({ name: i, count: this._view[i].count() }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":24,"./Shared":25}]},{},[1]);
Piicksarn/cdnjs
ajax/libs/forerunnerdb/1.3.50/fdb-core+views.js
JavaScript
mit
223,891
YUI.add("lang/datatype-date-format_zh-Hant-HK",function(a){a.Intl.add("datatype-date-format","zh-Hant-HK",{"a":["週日","週一","週二","週三","週四","週五","週六"],"A":["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],"b":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"B":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"c":"%Y年%b%d日%a%Z%p%l時%M分%S秒","p":["上午","下午"],"P":["上午","下午"],"x":"%y年%m月%d日","X":"%p%l時%M分%S秒"});},"@VERSION@");YUI.add("lang/datatype-date_zh-Hant-HK",function(a){},"@VERSION@",{use:["lang/datatype-date-format_zh-Hant-HK"]});
Piicksarn/cdnjs
ajax/libs/yui/3.4.0pr2/datatype/lang/datatype-date_zh-Hant-HK.js
JavaScript
mit
717
/** * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Unobtrusive Form Validation library * * Inspired by: Chris Campbell <www.particletree.com> * * @package Joomla.Framework * @subpackage Forms * @since 1.5 */ var JFormValidator = function($) { var handlers, custom, inputEmail; var setHandler = function(name, fn, en) { en = (en === '') ? true : en; handlers[name] = { enabled : en, exec : fn }; }; var handleResponse = function(state, $el) { // Find the label object for the given field if it exists if (!$el.get(0).labelref) { $('label').each(function() { var $label = $(this); if ($label.attr('for') === $el.attr('id')) { $el.get(0).labelref = this; } }); } var labelref = $el.get(0).labelref; // Set the element and its label (if exists) invalid state if (state === false) { $el.addClass('invalid').attr('aria-invalid', 'true'); if (labelref) { $(labelref).addClass('invalid').attr('aria-invalid', 'true'); } } else { $el.removeClass('invalid').attr('aria-invalid', 'false'); if (labelref) { $(labelref).removeClass('invalid').attr('aria-invalid', 'false'); } } }; var validate = function(el) { var $el = $(el); // Ignore the element if its currently disabled, because are not submitted for the http-request. For those case return always true. if ($el.attr('disabled')) { handleResponse(true, $el); return true; } // If the field is required make sure it has a value if ($el.hasClass('required')) { var tagName = $el.prop("tagName").toLowerCase(), i = 0, selector; if (tagName === 'fieldset' && ($el.hasClass('radio') || $el.hasClass('checkboxes'))) { while (true) { selector = "#" + $el.attr('id') + i; if ($(selector).get(0)) { if ($(selector).is(':checked')) { break; } } else { handleResponse(false, $el); return false; } i++; } //If element has class placeholder that means it is empty. } else if (!$el.val() || $el.hasClass('placeholder') || ($el.attr('type') === 'checkbox' && !$el.is(':checked'))) { handleResponse(false, $el); return false; } } // Only validate the field if the validate class is set var handler = ($el.attr('class') && $el.attr('class').match(/validate-([a-zA-Z0-9\_\-]+)/)) ? $el.attr('class').match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : ""; if (handler === '') { handleResponse(true, $el); return true; } // Check the additional validation types if ((handler) && (handler !== 'none') && (handlers[handler]) && $el.val()) { // Execute the validation handler and return result if (handlers[handler].exec($el.val()) !== true) { handleResponse(false, $el); return false; } } // Return validation state handleResponse(true, $el); return true; }; var isValid = function(form) { var valid = true, $form = $(form), i; // Validate form fields $form.find('input, textarea, select, button, fieldset').each(function(index, el){ if (validate(el) === false) { valid = false; } }); // Run custom form validators if present new Hash(custom).each(function(validator) { if (validator.exec() !== true) { valid = false; } }); if (!valid) { var message, errors, error; message = Joomla.JText._('JLIB_FORM_FIELD_INVALID'); errors = $("label.invalid"); error = {}; error.error = []; for ( i = 0; i < errors.length; i++) { var label = $(errors[i]).text(); if (label !== 'undefined') { error.error[i] = message + label.replace("*", ""); } } Joomla.renderMessages(error); } return valid; }; var attachToForm = function(form) { // Iterate through the form object and attach the validate method to all input fields. $(form).find('input,textarea,select,button').each(function() { var $el = $(this), tagName = $el.prop("tagName").toLowerCase(); if ($el.attr('required') === 'required') { $el.attr('aria-required', 'true'); } if ((tagName === 'input' && $el.attr('type') === 'submit') || (tagName === 'button' && $el.attr('type') === undefined)) { if ($el.hasClass('validate')) { $el.on('click', function() { return isValid(form); }); } } else { $el.on('blur', function() { return validate(this); }); if ($el.hasClass('validate-email') && inputEmail) { $el.get(0).type = 'email'; } } }); }; var initialize = function() { handlers = {}; custom = {}; inputEmail = (function() { var input = document.createElement("input"); input.setAttribute("type", "email"); return input.type !== "text"; })(); // Default handlers setHandler('username', function(value) { regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i"); return !regex.test(value); }); setHandler('password', function(value) { regex = /^\S[\S ]{2,98}\S$/; return regex.test(value); }); setHandler('numeric', function(value) { regex = /^(\d|-)?(\d|,)*\.?\d*$/; return regex.test(value); }); setHandler('email', function(value) { regex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; return regex.test(value); }); // Attach to forms with class 'form-validate' $('form.form-validate').each(function() { attachToForm(this); }); }; return { initialize : initialize, isValid : isValid, validate : validate }; }; document.formvalidator = null; window.addEvent('domready', function() { document.formvalidator = new JFormValidator(jQuery.noConflict()); document.formvalidator.initialize(); });
google-code/asianspecialroad
plugins/media/system/js/validate-jquery-uncompressed.js
JavaScript
gpl-2.0
5,696
(function (env) { "use strict"; env.ddg_spice_bacon_ipsum = function(api_result){ if (!api_result || api_result.error) { return Spice.failed('bacon_ipsum'); } var pageContent = ''; for (var i in api_result) { pageContent += "<p>" + api_result[i] + "</p>"; } Spice.add({ id: 'bacon_ipsum', name: 'Bacon Ipsum', data: { content: pageContent, title: "Bacon Ipsum", subtitle: "Randomly generated text" }, meta: { sourceName: 'Bacon Ipsum', sourceUrl: 'http://baconipsum.com/' }, templates: { group: 'text', options: { content: Spice.bacon_ipsum.content } } }); }; }(this));
hshackathons/zeroclickinfo-spice
share/spice/bacon_ipsum/bacon_ipsum.js
JavaScript
apache-2.0
910
require('../lib/node_loader'); var AWS = require('../lib/core'); var Service = require('../lib/service'); var apiLoader = require('../lib/api_loader'); apiLoader.services['cloudsearchdomain'] = {}; AWS.CloudSearchDomain = Service.defineService('cloudsearchdomain', ['2013-01-01']); require('../lib/services/cloudsearchdomain'); Object.defineProperty(apiLoader.services['cloudsearchdomain'], '2013-01-01', { get: function get() { var model = require('../apis/cloudsearchdomain-2013-01-01.min.json'); return model; }, enumerable: true, configurable: true }); module.exports = AWS.CloudSearchDomain;
edeati/alexa-translink-skill-js
test/node_modules/aws-sdk/clients/cloudsearchdomain.js
JavaScript
apache-2.0
615
/** * Listens for the app launching then creates the window * * @see http://developer.chrome.com/apps/app.runtime.html * @see http://developer.chrome.com/apps/app.window.html */ chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('index.html', { id: "camCaptureID", innerBounds: { width: 700, height: 600 } }); });
Jabqooo/chrome-app-samples
samples/camera-capture/background.js
JavaScript
apache-2.0
375
/** * Copyright (C) 2011 Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // markup required: // <span class=" field-with-fancyplaceholder"><label for="email">Email Address</span></label><input type="text" id="login_apple_id"></span> // // css required: // span.field-with-fancyplaceholder{display:block;display:inline-block;position:relative;vertical-align:top;} // span.field-with-fancyplaceholder label.placeholder{color:#999;cursor:text;pointer-events:none;} // span.field-with-fancyplaceholder label.placeholder span{position:absolute;z-index:2;-webkit-user-select:none;padding:3px 6px;} // span.field-with-fancyplaceholder label.focus{color:#ccc;} // span.field-with-fancyplaceholder label.hidden{color:#fff;} // span.field-with-fancyplaceholder input.invalid{background:#ffffc5;color:#F30;} // span.field-with-fancyplaceholder input.editing{color:#000;background:none repeat scroll 0 0 transparent;overflow:hidden;} // // then: $(".field-with-fancyplaceholder input").fancyPlaceholder(); define(['jquery'], function($) { $.fn.fancyPlaceholder = function() { var pollingInterval, foundInputsAndLables = []; function hideOrShowLabels(){ $.each(foundInputsAndLables, function(i, inputAndLable){ inputAndLable[1][inputAndLable[0].val() ? 'hide' : 'show'](); }); } return this.each(function() { var $input = $(this), $label = $("label[for="+$input.attr('id')+"]"); $label.addClass('placeholder').wrapInner("<span/>").css({ 'font-family' : $input.css('font-family'), 'font-size' : $input.css('font-size') }); $input .focus(function(){ $label.addClass('focus', 300); }) .blur(function(){ $label.removeClass('focus', 300); }) .bind('keyup', hideOrShowLabels); // if this was already focused before we got here, make it light gray now. sorry, ie7 cant do :focus selector, it doesn't get this. try { if ($("input:focus").get(0) == this) { $input.triggerHandler('focus'); } } catch(e) {} foundInputsAndLables.push([$input, $label]); if (!pollingInterval) { window.setInterval(hideOrShowLabels, 100); } }); }; });
ajpi222/canvas-lms-hdi
public/javascripts/jquery.fancyplaceholder.js
JavaScript
agpl-3.0
2,861
if (require.register) { var qs = require('querystring'); } else { var qs = require('../') , expect = require('expect.js'); } var date = new Date(0); var str_identities = { 'basics': [ { str: 'foo=bar', obj: {'foo' : 'bar'}}, { str: 'foo=%22bar%22', obj: {'foo' : '\"bar\"'}}, { str: 'foo=', obj: {'foo': ''}}, { str: 'foo=1&bar=2', obj: {'foo' : '1', 'bar' : '2'}}, { str: 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', obj: {'my weird field': "q1!2\"'w$5&7/z8)?"}}, { str: 'foo%3Dbaz=bar', obj: {'foo=baz': 'bar'}}, { str: 'foo=bar&bar=baz', obj: {foo: 'bar', bar: 'baz'}} ], 'escaping': [ { str: 'foo=foo%20bar', obj: {foo: 'foo bar'}}, { str: 'cht=p3&chd=t%3A60%2C40&chs=250x100&chl=Hello%7CWorld', obj: { cht: 'p3' , chd: 't:60,40' , chs: '250x100' , chl: 'Hello|World' }} ], 'nested': [ { str: 'foo[0]=bar&foo[1]=quux', obj: {'foo' : ['bar', 'quux']}}, { str: 'foo[0]=bar', obj: {foo: ['bar']}}, { str: 'foo[0]=1&foo[1]=2', obj: {'foo' : ['1', '2']}}, { str: 'foo=bar&baz[0]=1&baz[1]=2&baz[2]=3', obj: {'foo' : 'bar', 'baz' : ['1', '2', '3']}}, { str: 'foo[0]=bar&baz[0]=1&baz[1]=2&baz[2]=3', obj: {'foo' : ['bar'], 'baz' : ['1', '2', '3']}}, { str: 'x[y][z]=1', obj: {'x' : {'y' : {'z' : '1'}}}}, { str: 'x[y][z][0]=1', obj: {'x' : {'y' : {'z' : ['1']}}}}, { str: 'x[y][z]=2', obj: {'x' : {'y' : {'z' : '2'}}}}, { str: 'x[y][z][0]=1&x[y][z][1]=2', obj: {'x' : {'y' : {'z' : ['1', '2']}}}}, { str: 'x[y][0][z]=1', obj: {'x' : {'y' : [{'z' : '1'}]}}}, { str: 'x[y][0][z][0]=1', obj: {'x' : {'y' : [{'z' : ['1']}]}}}, { str: 'x[y][0][z]=1&x[y][0][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'w' : '2'}]}}}, { str: 'x[y][0][v][w]=1', obj: {'x' : {'y' : [{'v' : {'w' : '1'}}]}}}, { str: 'x[y][0][z]=1&x[y][0][v][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'v' : {'w' : '2'}}]}}}, { str: 'x[y][0][z]=1&x[y][1][z]=2', obj: {'x' : {'y' : [{'z' : '1'}, {'z' : '2'}]}}}, { str: 'x[y][0][z]=1&x[y][0][w]=a&x[y][1][z]=2&x[y][1][w]=3', obj: {'x' : {'y' : [{'z' : '1', 'w' : 'a'}, {'z' : '2', 'w' : '3'}]}}}, { str: 'user[name][first]=tj&user[name][last]=holowaychuk', obj: { user: { name: { first: 'tj', last: 'holowaychuk' }}}} ], 'errors': [ { obj: 'foo=bar', message: 'stringify expects an object' }, { obj: ['foo', 'bar'], message: 'stringify expects an object' } ], 'numbers': [ { str: 'limit[0]=1&limit[1]=2&limit[2]=3', obj: { limit: [1, 2, '3'] }}, { str: 'limit=1', obj: { limit: 1 }} ], 'others': [ { str: 'at=' + encodeURIComponent(date), obj: { at: date } } ] }; function test(type) { return function(){ var str, obj; for (var i = 0; i < str_identities[type].length; i++) { str = str_identities[type][i].str; obj = str_identities[type][i].obj; expect(qs.stringify(obj)).to.eql(str); } } } describe('qs.stringify()', function(){ it('should support the basics', test('basics')) it('should support escapes', test('escaping')) it('should support nesting', test('nested')) it('should support numbers', test('numbers')) it('should support others', test('others')) })
gglinux/node.js
webChat/node_modules/qs/test/stringify.js
JavaScript
apache-2.0
3,198
// Copyright 2013 the V8 project authors. All rights reserved. // Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. description( "This test checks that the following expressions or statements are valid ECMASCRIPT code or should throw parse error" ); function runTest(_a, errorType) { var success; if (typeof _a != "string") testFailed("runTest expects string argument: " + _a); try { eval(_a); success = true; } catch (e) { success = !(e instanceof SyntaxError); } if ((!!errorType) == !success) { if (errorType) testPassed('Invalid: "' + _a + '"'); else testPassed('Valid: "' + _a + '"'); } else { if (errorType) testFailed('Invalid: "' + _a + '" should throw ' + errorType.name); else testFailed('Valid: "' + _a + '" should NOT throw '); } } function valid(_a) { // Test both the grammar and the syntax checker runTest(_a, false); runTest("function f() { " + _a + " }", false); } function invalid(_a, _type) { _type = _type || SyntaxError; // Test both the grammar and the syntax checker runTest(_a, true); runTest("function f() { " + _a + " }", true); } // known issue: // some statements requires statement as argument, and // it seems the End-Of-File terminator is converted to semicolon // "a:[EOF]" is not parse error, while "{ a: }" is parse error // "if (a)[EOF]" is not parse error, while "{ if (a) }" is parse error // known issues of bison parser: // accepts: 'function f() { return 6 + }' (only inside a function declaration) // some comma expressions: see reparsing-semicolon-insertion.js debug ("Unary operators and member access"); valid (""); invalid("(a"); invalid("a[5"); invalid("a[5 + 6"); invalid("a."); invalid("()"); invalid("a.'l'"); valid ("a: +~!new a"); invalid("new -a"); valid ("new (-1)") valid ("a: b: c: new f(x++)++") valid ("(a)++"); valid ("(1--).x"); invalid("a-- ++"); invalid("(a:) --b"); valid ("++ -- ++ a"); valid ("++ new new a ++"); valid ("delete void 0"); invalid("delete the void"); invalid("(a++"); valid ("++a--"); valid ("++((a))--"); valid ("(a.x++)++"); invalid("1: null"); invalid("+-!~"); invalid("+-!~(("); invalid("a)"); invalid("a]"); invalid(".l"); invalid("1.l"); valid ("1 .l"); debug ("Binary and conditional operators"); valid ("a + + typeof this"); invalid("a + * b"); invalid("a ? b"); invalid("a ? b :"); invalid("%a"); invalid("a-"); valid ("a = b ? b = c : d = e"); valid ("s: a[1].l ? b.l['s'] ? c++ : d : true"); valid ("a ? b + 1 ? c + 3 * d.l : d[5][6] : e"); valid ("a in b instanceof delete -c"); invalid("a in instanceof b.l"); valid ("- - true % 5"); invalid("- false = 3"); valid ("a: b: c: (1 + null) = 3"); valid ("a[2] = b.l += c /= 4 * 7 ^ !6"); invalid("a + typeof b += c in d"); invalid("typeof a &= typeof b"); valid ("a: ((typeof (a))) >>>= a || b.l && c"); valid ("a: b: c[a /= f[a %= b]].l[c[x] = 7] -= a ? b <<= f : g"); valid ("-void+x['y'].l == x.l != 5 - f[7]"); debug ("Function calls (and new with arguments)"); valid ("a()()()"); valid ("s: l: a[2](4 == 6, 5 = 6)(f[4], 6)"); valid ("s: eval(a.apply(), b.call(c[5] - f[7]))"); invalid("a("); invalid("a(5"); invalid("a(5,"); invalid("a(5,)"); invalid("a(5,6"); valid ("a(b[7], c <d> e.l, new a() > b)"); invalid("a(b[5)"); invalid("a(b.)"); valid ("~new new a(1)(i++)(c[l])"); invalid("a(*a)"); valid ("((((a))((b)()).l))()"); valid ("(a)[b + (c) / (d())].l--"); valid ("new (5)"); invalid("new a(5"); valid ("new (f + 5)(6, (g)() - 'l'() - true(false))"); invalid("a(.length)"); debug ("function declaration and expression"); valid ("function f() {}"); valid ("function f(a,b) {}"); invalid("function () {}"); invalid("function f(a b) {}"); invalid("function f(a,) {}"); invalid("function f(a,"); invalid("function f(a, 1) {}"); valid ("function g(arguments, eval) {}"); valid ("function f() {} + function g() {}"); invalid("(function a{})"); invalid("(function this(){})"); valid ("(delete new function f(){} + function(a,b){}(5)(6))"); valid ("6 - function (m) { function g() {} }"); invalid("function l() {"); invalid("function l++(){}"); debug ("Array and object literal, comma operator"); // Note these are tested elsewhere, no need to repeat those tests here valid ("[] in [5,6] * [,5,] / [,,5,,] || [a,] && new [,b] % [,,]"); invalid("[5,"); invalid("[,"); invalid("(a,)"); valid ("1 + {get get(){}, set set(a){}, get1:4, set1:get-set, }"); invalid("1 + {a"); invalid("1 + {a:"); invalid("1 + {get l("); invalid(",a"); valid ("(4,(5,a(3,4))),f[4,a-6]"); invalid("(,f)"); invalid("a,,b"); invalid("a ? b, c : d"); debug ("simple statements"); valid ("{ }"); invalid("{ { }"); valid ("{ ; ; ; }"); valid ("a: { ; }"); invalid("{ a: }"); valid ("{} f; { 6 + f() }"); valid ("{ a[5],6; {} ++b-new (-5)() } c().l++"); valid ("{ l1: l2: l3: { this } a = 32 ; { i++ ; { { { } } ++i } } }"); valid ("if (a) ;"); invalid("{ if (a) }"); invalid("if a {}"); invalid("if (a"); invalid("if (a { }"); valid ("x: s: if (a) ; else b"); invalid("else {}"); valid ("if (a) if (b) y; else {} else ;"); invalid("if (a) {} else x; else"); invalid("if (a) { else }"); valid ("if (a.l + new b()) 4 + 5 - f()"); valid ("if (a) with (x) ; else with (y) ;"); invalid("with a.b { }"); valid ("while (a() - new b) ;"); invalid("while a {}"); valid ("do ; while(0) i++"); // Is this REALLY valid? (Firefox also accepts this) valid ("do if (a) x; else y; while(z)"); invalid("do g; while 4"); invalid("do g; while ((4)"); valid ("{ { do do do ; while(0) while(0) while(0) } }"); valid ("do while (0) if (a) {} else y; while(0)"); valid ("if (a) while (b) if (c) with(d) {} else e; else f"); invalid("break ; break your_limits ; continue ; continue living ; debugger"); invalid("debugger X"); invalid("break 0.2"); invalid("continue a++"); invalid("continue (my_friend)"); valid ("while (1) break"); valid ("do if (a) with (b) continue; else debugger; while (false)"); invalid("do if (a) while (false) else debugger"); invalid("while if (a) ;"); valid ("if (a) function f() {} else function g() {}"); valid ("if (a()) while(0) function f() {} else function g() {}"); invalid("if (a()) function f() { else function g() }"); invalid("if (a) if (b) ; else function f {}"); invalid("if (a) if (b) ; else function (){}"); valid ("throw a"); valid ("throw a + b in void c"); invalid("throw"); debug ("var and const statements"); valid ("var a, b = null"); valid ("const a = 5, b, c"); invalid("var"); invalid("var = 7"); invalid("var c (6)"); valid ("if (a) var a,b; else const b, c"); invalid("var 5 = 6"); valid ("while (0) var a, b, c=6, d, e, f=5*6, g=f*h, h"); invalid("var a = if (b) { c }"); invalid("var a = var b"); valid ("const a = b += c, a, a, a = (b - f())"); invalid("var a %= b | 5"); invalid("var (a) = 5"); invalid("var a = (4, b = 6"); invalid("const 'l' = 3"); invalid("var var = 3"); valid ("var varr = 3 in 1"); valid ("const a, a, a = void 7 - typeof 8, a = 8"); valid ("const x_x = 6 /= 7 ? e : f"); invalid("var a = ?"); invalid("const a = *7"); invalid("var a = :)"); valid ("var a = a in b in c instanceof d"); invalid("var a = b ? c, b"); invalid("const a = b : c"); debug ("for statement"); valid ("for ( ; ; ) { break }"); valid ("for ( a ; ; ) { break }"); valid ("for ( ; a ; ) { break }"); valid ("for ( ; ; a ) { break }"); valid ("for ( a ; a ; ) break"); valid ("for ( a ; ; a ) break"); valid ("for ( ; a ; a ) break"); invalid("for () { }"); invalid("for ( a ) { }"); invalid("for ( ; ) ;"); invalid("for a ; b ; c { }"); invalid("for (a ; { }"); invalid("for ( a ; ) ;"); invalid("for ( ; a ) break"); valid ("for (var a, b ; ; ) { break } "); valid ("for (var a = b, b = a ; ; ) break"); valid ("for (var a = b, c, d, b = a ; x in b ; ) { break }"); valid ("for (var a = b, c, d ; ; 1 in a()) break"); invalid("for ( ; var a ; ) break"); invalid("for (const a; ; ) break"); invalid("for ( %a ; ; ) { }"); valid ("for (a in b) break"); valid ("for (a() in b) break"); valid ("for (a().l[4] in b) break"); valid ("for (new a in b in c in d) break"); valid ("for (new new new a in b) break"); invalid("for (delete new a() in b) break"); invalid("for (a * a in b) break"); valid ("for ((a * a) in b) break"); invalid("for (a++ in b) break"); valid ("for ((a++) in b) break"); invalid("for (++a in b) break"); valid ("for ((++a) in b) break"); invalid("for (a, b in c) break"); invalid("for (a,b in c ;;) break"); valid ("for (a,(b in c) ;;) break"); valid ("for ((a, b) in c) break"); invalid("for (a ? b : c in c) break"); valid ("for ((a ? b : c) in c) break"); valid ("for (var a in b in c) break"); valid ("for (var a = 5 += 6 in b) break"); invalid("for (var a += 5 in b) break"); invalid("for (var a = in b) break"); invalid("for (var a, b in b) break"); invalid("for (var a = -6, b in b) break"); invalid("for (var a, b = 8 in b) break"); valid ("for (var a = (b in c) in d) break"); invalid("for (var a = (b in c in d) break"); invalid("for (var (a) in b) { }"); valid ("for (var a = 7, b = c < d >= d ; f()[6]++ ; --i()[1]++ ) {}"); debug ("try statement"); invalid("try { break } catch(e) {}"); valid ("try {} finally { c++ }"); valid ("try { with (x) { } } catch(e) {} finally { if (a) ; }"); invalid("try {}"); invalid("catch(e) {}"); invalid("finally {}"); invalid("try a; catch(e) {}"); invalid("try {} catch(e) a()"); invalid("try {} finally a()"); invalid("try {} catch(e)"); invalid("try {} finally"); invalid("try {} finally {} catch(e) {}"); invalid("try {} catch (...) {}"); invalid("try {} catch {}"); valid ("if (a) try {} finally {} else b;"); valid ("if (--a()) do with(1) try {} catch(ke) { f() ; g() } while (a in b) else {}"); invalid("if (a) try {} else b; catch (e) { }"); invalid("try { finally {}"); debug ("switch statement"); valid ("switch (a) {}"); invalid("switch () {}"); invalid("case 5:"); invalid("default:"); invalid("switch (a) b;"); invalid("switch (a) case 3: b;"); valid ("switch (f()) { case 5 * f(): default: case '6' - 9: ++i }"); invalid("switch (true) { default: case 6: default: }"); invalid("switch (l) { f(); }"); invalid("switch (l) { case 1: ; a: case 5: }"); valid ("switch (g() - h[5].l) { case 1 + 6: a: b: c: ++f }"); invalid("switch (g) { case 1: a: }"); invalid("switch (g) { case 1: a: default: }"); invalid("switch g { case 1: l() }"); invalid("switch (g) { case 1:"); valid ("switch (l) { case a = b ? c : d : }"); valid ("switch (sw) { case a ? b - 7[1] ? [c,,] : d = 6 : { } : }"); invalid("switch (l) { case b ? c : }"); valid ("switch (l) { case 1: a: with(g) switch (g) { case 2: default: } default: }"); invalid("switch (4 - ) { }"); invalid("switch (l) { default case: 5; }"); invalid("L: L: ;"); invalid("L: L1: L: ;"); invalid("L: L1: L2: L3: L4: L: ;"); invalid("for(var a,b 'this shouldn\'t be allowed' false ; ) ;"); invalid("for(var a,b '"); valid("function __proto__(){}") valid("(function __proto__(){})") valid("'use strict'; function __proto__(){}") valid("'use strict'; (function __proto__(){})") valid("if (0) $foo; ") valid("if (0) _foo; ") valid("if (0) foo$; ") valid("if (0) foo_; ") valid("if (0) obj.$foo; ") valid("if (0) obj._foo; ") valid("if (0) obj.foo$; ") valid("if (0) obj.foo_; ") valid("if (0) obj.foo\\u03bb; ") valid("if (0) new a(b+c).d = 5"); valid("if (0) new a(b+c) = 5"); valid("([1 || 1].a = 1)"); valid("({a: 1 || 1}.a = 1)"); invalid("var a.b = c"); invalid("var a.b;"); try { eval("a.b.c = {};"); } catch(e1) { e=e1; shouldBe("e.line", "1") } foo = 'FAIL'; bar = 'PASS'; try { eval("foo = 'PASS'; a.b.c = {}; bar = 'FAIL';"); } catch(e) { shouldBe("foo", "'PASS'"); shouldBe("bar", "'PASS'"); }
victorzhao/miniblink49
v8_4_5/test/webkit/fast/js/parser-syntax-check.js
JavaScript
gpl-3.0
13,137
/** * bootbox.js v2.3.0 * * The MIT License * * Copyright (C) 2011-2012 by Nick Payne <nick@kurai.co.uk> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE */ var bootbox=window.bootbox||function(){function j(b,a){null==a&&(a=k);return"string"==typeof h[a][b]?h[a][b]:a!=l?j(b,l):b}var k="en",l="en",o=!0,g={},f={},h={en:{OK:"OK",CANCEL:"Cancel",CONFIRM:"OK"},fr:{OK:"OK",CANCEL:"Annuler",CONFIRM:"D'accord"},de:{OK:"OK",CANCEL:"Abbrechen",CONFIRM:"Akzeptieren"},es:{OK:"OK",CANCEL:"Cancelar",CONFIRM:"Aceptar"},br:{OK:"OK",CANCEL:"Cancelar",CONFIRM:"Sim"},nl:{OK:"OK",CANCEL:"Annuleren",CONFIRM:"Accepteren"},ru:{OK:"OK",CANCEL:"\u041e\u0442\u043c\u0435\u043d\u0430", CONFIRM:"\u041f\u0440\u0438\u043c\u0435\u043d\u0438\u0442\u044c"}};f.setLocale=function(b){for(var a in h)if(a==b){k=b;return}throw Error("Invalid locale: "+b);};f.addLocale=function(b,a){"undefined"==typeof h[b]&&(h[b]={});for(var c in a)h[b][c]=a[c]};f.setIcons=function(b){g=b;if("object"!==typeof g||null==g)g={}};f.alert=function(){var b="",a=j("OK"),c=null;switch(arguments.length){case 1:b=arguments[0];break;case 2:b=arguments[0];"function"==typeof arguments[1]?c=arguments[1]:a=arguments[1];break; case 3:b=arguments[0];a=arguments[1];c=arguments[2];break;default:throw Error("Incorrect number of arguments: expected 1-3");}return f.dialog(b,{label:a,icon:g.OK,callback:c},{onEscape:c})};f.confirm=function(){var b="",a=j("CANCEL"),c=j("CONFIRM"),e=null;switch(arguments.length){case 1:b=arguments[0];break;case 2:b=arguments[0];"function"==typeof arguments[1]?e=arguments[1]:a=arguments[1];break;case 3:b=arguments[0];a=arguments[1];"function"==typeof arguments[2]?e=arguments[2]:c=arguments[2];break; case 4:b=arguments[0];a=arguments[1];c=arguments[2];e=arguments[3];break;default:throw Error("Incorrect number of arguments: expected 1-4");}return f.dialog(b,[{label:a,icon:g.CANCEL,callback:function(){"function"==typeof e&&e(!1)}},{label:c,icon:g.CONFIRM,callback:function(){"function"==typeof e&&e(!0)}}])};f.prompt=function(){var b="",a=j("CANCEL"),c=j("CONFIRM"),e=null;switch(arguments.length){case 1:b=arguments[0];break;case 2:b=arguments[0];"function"==typeof arguments[1]?e=arguments[1]:a=arguments[1]; break;case 3:b=arguments[0];a=arguments[1];"function"==typeof arguments[2]?e=arguments[2]:c=arguments[2];break;case 4:b=arguments[0];a=arguments[1];c=arguments[2];e=arguments[3];break;default:throw Error("Incorrect number of arguments: expected 1-4");}var m=$("<form></form>");m.append("<input type=text />");var h=f.dialog(m,[{label:a,icon:g.CANCEL,callback:function(){"function"==typeof e&&e(null)}},{label:c,icon:g.CONFIRM,callback:function(){"function"==typeof e&&e(m.find("input[type=text]").val())}}], {header:b});m.on("submit",function(a){a.preventDefault();h.find(".btn-primary").click()});return h};f.modal=function(){var b,a,c,e={onEscape:null,keyboard:!0,backdrop:!0};switch(arguments.length){case 1:b=arguments[0];break;case 2:b=arguments[0];"object"==typeof arguments[1]?c=arguments[1]:a=arguments[1];break;case 3:b=arguments[0];a=arguments[1];c=arguments[2];break;default:throw Error("Incorrect number of arguments: expected 1-3");}e.header=a;c="object"==typeof c?$.extend(e,c):e;return f.dialog(b, [],c)};f.dialog=function(b,a,c){var e=null,f="",h=[],c=c||{};null==a?a=[]:"undefined"==typeof a.length&&(a=[a]);for(var d=a.length;d--;){var g=null,j=null,k="",l=null;if("undefined"==typeof a[d].label&&"undefined"==typeof a[d]["class"]&&"undefined"==typeof a[d].callback){var g=0,p=null,n;for(n in a[d])if(p=n,1<++g)break;1==g&&"function"==typeof a[d][n]&&(a[d].label=p,a[d].callback=a[d][n])}"function"==typeof a[d].callback&&(l=a[d].callback);a[d]["class"]?j=a[d]["class"]:d==a.length-1&&2>=a.length&& (j="btn-primary");g=a[d].label?a[d].label:"Option "+(d+1);a[d].icon&&(k="<i class='"+a[d].icon+"'></i> ");f+="<a data-handler='"+d+"' class='btn "+j+"' href='#'>"+k+""+g+"</a>";h[d]=l}a=["<div class='bootbox modal'>"];if(c.header){d="";if("undefined"==typeof c.headerCloseButton||c.headerCloseButton)d="<a href='#' class='close'>&times;</a>";a.push("<div class='modal-header'>"+d+"<h3>"+c.header+"</h3></div>")}a.push("<div class='modal-body'></div>");f&&a.push("<div class='modal-footer'>"+f+"</div>"); a.push("</div>");var i=$(a.join("\n"));("undefined"===typeof c.animate?o:c.animate)&&i.addClass("fade");$(".modal-body",i).html(b);i.bind("hidden",function(){i.remove()});i.bind("hide",function(){if("escape"==e&&"function"==typeof c.onEscape)c.onEscape()});$(document).bind("keyup.modal",function(a){27==a.which&&(e="escape")});i.bind("shown",function(){$("a.btn-primary:last",i).focus()});i.on("click",".modal-footer a, a.close",function(a){var b=$(this).data("handler"),b=h[b],c=null;"function"==typeof b&& (c=b());!1!==c&&(a.preventDefault(),e="button",i.modal("hide"))});null==c.keyboard&&(c.keyboard="function"==typeof c.onEscape);$("body").append(i);i.modal({backdrop:c.backdrop||!0,keyboard:c.keyboard});return i};f.hideAll=function(){$(".bootbox").modal("hide")};f.animate=function(b){o=b};return f}();
tmthrgd/pagespeed-libraries-cdnjs
packages/bootbox.js/2.3.0/bootbox.min.js
JavaScript
mit
6,055
#!/usr/bin/env node var DocGenerator = require('../lib/utilities/doc-generator.js'); (new DocGenerator()).generate();
waddedMeat/ember-proxy-example
test-app/node_modules/ember-cli/bin/generate-docs.js
JavaScript
mit
119
/*! UIkit 2.13.1 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ (function(addon) { var component; if (jQuery && UIkit) { component = addon(jQuery, UIkit); } if (typeof define == "function" && define.amd) { define("uikit-notify", ["uikit"], function(){ return component || addon(jQuery, UIkit); }); } })(function($, UI){ "use strict"; var containers = {}, messages = {}, notify = function(options){ if ($.type(options) == 'string') { options = { message: options }; } if (arguments[1]) { options = $.extend(options, $.type(arguments[1]) == 'string' ? {status:arguments[1]} : arguments[1]); } return (new Message(options)).show(); }, closeAll = function(group, instantly){ var id; if (group) { for(id in messages) { if(group===messages[id].group) messages[id].close(instantly); } } else { for(id in messages) { messages[id].close(instantly); } } }; var Message = function(options){ var $this = this; this.options = $.extend({}, Message.defaults, options); this.uuid = UI.Utils.uid("notifymsg"); this.element = UI.$([ '<div class="@-notify-message">', '<a class="@-close"></a>', '<div></div>', '</div>' ].join('')).data("notifyMessage", this); this.content(this.options.message); // status if (this.options.status) { this.element.addClass('@-notify-message-'+this.options.status); this.currentstatus = this.options.status; } this.group = this.options.group; messages[this.uuid] = this; if(!containers[this.options.pos]) { containers[this.options.pos] = UI.$('<div class="@-notify @-notify-'+this.options.pos+'"></div>').appendTo('body').on("click", UI.prefix(".@-notify-message"), function(){ UI.$(this).data("notifyMessage").close(); }); } }; $.extend(Message.prototype, { uuid: false, element: false, timout: false, currentstatus: "", group: false, show: function() { if (this.element.is(":visible")) return; var $this = this; containers[this.options.pos].show().prepend(this.element); var marginbottom = parseInt(this.element.css("margin-bottom"), 10); this.element.css({"opacity":0, "margin-top": -1*this.element.outerHeight(), "margin-bottom":0}).animate({"opacity":1, "margin-top": 0, "margin-bottom":marginbottom}, function(){ if ($this.options.timeout) { var closefn = function(){ $this.close(); }; $this.timeout = setTimeout(closefn, $this.options.timeout); $this.element.hover( function() { clearTimeout($this.timeout); }, function() { $this.timeout = setTimeout(closefn, $this.options.timeout); } ); } }); return this; }, close: function(instantly) { var $this = this, finalize = function(){ $this.element.remove(); if(!containers[$this.options.pos].children().length) { containers[$this.options.pos].hide(); } $this.options.onClose.apply($this, []); delete messages[$this.uuid]; }; if (this.timeout) clearTimeout(this.timeout); if (instantly) { finalize(); } else { this.element.animate({"opacity":0, "margin-top": -1* this.element.outerHeight(), "margin-bottom":0}, function(){ finalize(); }); } }, content: function(html){ var container = this.element.find(">div"); if(!html) { return container.html(); } container.html(html); return this; }, status: function(status) { if (!status) { return this.currentstatus; } this.element.removeClass('@-notify-message-'+this.currentstatus).addClass('@-notify-message-'+status); this.currentstatus = status; return this; } }); Message.defaults = { message: "", status: "", timeout: 5000, group: null, pos: 'top-center', onClose: function() {} }; UI.notify = notify; UI.notify.message = Message; UI.notify.closeAll = closeAll; return notify; });
AppConcur/islacart
sites/all/themes/marketplace/vendor/uikit/js/components/notify.js
JavaScript
gpl-2.0
4,965
/*! * Bootstrap-select v1.7.0 (http://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2015 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Nu a fost selectat nimic', noneResultsText: 'Nu exista niciun rezultat {0}', countSelectedText: '{0} din {1} selectat(e)', maxOptionsText: ['Limita a fost atinsa ({n} {var} max)', 'Limita de grup a fost atinsa ({n} {var} max)', ['iteme', 'item']], multipleSeparator: ', ' }; })(jQuery);
dominic/cdnjs
ajax/libs/bootstrap-select/1.7.0/js/i18n/defaults-ro_RO.js
JavaScript
mit
597
// Utility functions String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, ''); }; function supportsHtmlStorage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function get_text(el) { ret = " "; var length = el.childNodes.length; for(var i = 0; i < length; i++) { var node = el.childNodes[i]; if(node.nodeType != 8) { if ( node.nodeType != 1 ) { // Strip white space. ret += node.nodeValue; } else { ret += get_text( node ); } } } return ret.trim(); }
sandbox-team/techtalk-portal
vendor/zenpen/js/utils.js
JavaScript
mit
641
'use strict'; var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-native'); var DESCRIPTORS = require('../internals/descriptors'); var global = require('../internals/global'); var isObject = require('../internals/is-object'); var has = require('../internals/has'); var classof = require('../internals/classof'); var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var redefine = require('../internals/redefine'); var defineProperty = require('../internals/object-define-property').f; var getPrototypeOf = require('../internals/object-get-prototype-of'); var setPrototypeOf = require('../internals/object-set-prototype-of'); var wellKnownSymbol = require('../internals/well-known-symbol'); var uid = require('../internals/uid'); var Int8Array = global.Int8Array; var Int8ArrayPrototype = Int8Array && Int8Array.prototype; var Uint8ClampedArray = global.Uint8ClampedArray; var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; var TypedArray = Int8Array && getPrototypeOf(Int8Array); var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype); var ObjectPrototype = Object.prototype; var isPrototypeOf = ObjectPrototype.isPrototypeOf; var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); // Fixing native typed arrays in Opera Presto crashes the browser, see #595 var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera'; var TYPED_ARRAY_TAG_REQIRED = false; var NAME; var TypedArrayConstructorsList = { Int8Array: 1, Uint8Array: 1, Uint8ClampedArray: 1, Int16Array: 2, Uint16Array: 2, Int32Array: 4, Uint32Array: 4, Float32Array: 4, Float64Array: 8 }; var isView = function isView(it) { var klass = classof(it); return klass === 'DataView' || has(TypedArrayConstructorsList, klass); }; var isTypedArray = function (it) { return isObject(it) && has(TypedArrayConstructorsList, classof(it)); }; var aTypedArray = function (it) { if (isTypedArray(it)) return it; throw TypeError('Target is not a typed array'); }; var aTypedArrayConstructor = function (C) { if (setPrototypeOf) { if (isPrototypeOf.call(TypedArray, C)) return C; } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) { var TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) { return C; } } throw TypeError('Target is not a typed array constructor'); }; var exportTypedArrayMethod = function (KEY, property, forced) { if (!DESCRIPTORS) return; if (forced) for (var ARRAY in TypedArrayConstructorsList) { var TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) { delete TypedArrayConstructor.prototype[KEY]; } } if (!TypedArrayPrototype[KEY] || forced) { redefine(TypedArrayPrototype, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property); } }; var exportTypedArrayStaticMethod = function (KEY, property, forced) { var ARRAY, TypedArrayConstructor; if (!DESCRIPTORS) return; if (setPrototypeOf) { if (forced) for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) { delete TypedArrayConstructor[KEY]; } } if (!TypedArray[KEY] || forced) { // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable try { return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property); } catch (error) { /* empty */ } } else return; } for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { redefine(TypedArrayConstructor, KEY, property); } } }; for (NAME in TypedArrayConstructorsList) { if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false; } // WebKit bug - typed arrays constructors prototype is Object.prototype if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) { // eslint-disable-next-line no-shadow TypedArray = function TypedArray() { throw TypeError('Incorrect invocation'); }; if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global[NAME]) setPrototypeOf(global[NAME], TypedArray); } } if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) { TypedArrayPrototype = TypedArray.prototype; if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype); } } // WebKit bug - one more object in Uint8ClampedArray prototype chain if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); } if (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) { TYPED_ARRAY_TAG_REQIRED = true; defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () { return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; } }); for (NAME in TypedArrayConstructorsList) if (global[NAME]) { createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME); } } module.exports = { NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG, aTypedArray: aTypedArray, aTypedArrayConstructor: aTypedArrayConstructor, exportTypedArrayMethod: exportTypedArrayMethod, exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, isView: isView, isTypedArray: isTypedArray, TypedArray: TypedArray, TypedArrayPrototype: TypedArrayPrototype };
BigBoss424/portfolio
v8/development/node_modules/jimp/node_modules/core-js/internals/array-buffer-view-core.js
JavaScript
apache-2.0
6,017
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $ */ /** * The view that controls the showing and hiding of the sidebar. * * Although the sidebar view doesn't dispatch any events directly, it is a * resizable element (../utils/Resizer.js), which means it can dispatch Resizer * events. For example, if you want to listen for the sidebar showing * or hiding itself, set up listeners for the corresponding Resizer events, * panelCollapsed and panelExpanded: * * $("#sidebar").on("panelCollapsed", ...); * $("#sidebar").on("panelExpanded", ...); */ define(function (require, exports, module) { "use strict"; var AppInit = require("utils/AppInit"), ProjectManager = require("project/ProjectManager"), WorkingSetView = require("project/WorkingSetView"), MainViewManager = require("view/MainViewManager"), CommandManager = require("command/CommandManager"), Commands = require("command/Commands"), Strings = require("strings"), Resizer = require("utils/Resizer"), _ = require("thirdparty/lodash"); // These vars are initialized by the htmlReady handler // below since they refer to DOM elements var $sidebar, $gearMenu, $splitViewMenu, $projectTitle, $projectFilesContainer, $workingSetViewsContainer; var _cmdSplitNone, _cmdSplitVertical, _cmdSplitHorizontal; /** * @private * Update project title when the project root changes */ function _updateProjectTitle() { var displayName = ProjectManager.getProjectRoot().name; var fullPath = ProjectManager.getProjectRoot().fullPath; if (displayName === "" && fullPath === "/") { displayName = "/"; } $projectTitle.html(_.escape(displayName)); $projectTitle.attr("title", fullPath); // Trigger a scroll on the project files container to // reposition the scroller shadows and avoid issue #2255 $projectFilesContainer.trigger("scroll"); } /** * Toggle sidebar visibility. */ function toggle() { Resizer.toggle($sidebar); } /** * Show the sidebar. */ function show() { Resizer.show($sidebar); } /** * Hide the sidebar. */ function hide() { Resizer.hide($sidebar); } /** * Returns the visibility state of the sidebar. * @return {boolean} true if element is visible, false if it is not visible */ function isVisible() { return Resizer.isVisible($sidebar); } /** * Update state of working set * @private */ function _updateWorkingSetState() { if (MainViewManager.getPaneCount() === 1 && MainViewManager.getWorkingSetSize(MainViewManager.ACTIVE_PANE) === 0) { $workingSetViewsContainer.hide(); $gearMenu.hide(); } else { $workingSetViewsContainer.show(); $gearMenu.show(); } } /** * Update state of splitview and option elements * @private */ function _updateUIStates() { var spriteIndex, ICON_CLASSES = ["splitview-icon-none", "splitview-icon-vertical", "splitview-icon-horizontal"], layoutScheme = MainViewManager.getLayoutScheme(); if (layoutScheme.columns > 1) { spriteIndex = 1; } else if (layoutScheme.rows > 1) { spriteIndex = 2; } else { spriteIndex = 0; } // SplitView Icon $splitViewMenu.removeClass(ICON_CLASSES.join(" ")) .addClass(ICON_CLASSES[spriteIndex]); // SplitView Menu _cmdSplitNone.setChecked(spriteIndex === 0); _cmdSplitVertical.setChecked(spriteIndex === 1); _cmdSplitHorizontal.setChecked(spriteIndex === 2); // Options icon _updateWorkingSetState(); } /** * Handle No Split Command * @private */ function _handleSplitViewNone() { MainViewManager.setLayoutScheme(1, 1); } /** * Handle Vertical Split Command * @private */ function _handleSplitViewVertical() { MainViewManager.setLayoutScheme(1, 2); } /** * Handle Horizontal Split Command * @private */ function _handleSplitViewHorizontal() { MainViewManager.setLayoutScheme(2, 1); } // Initialize items dependent on HTML DOM AppInit.htmlReady(function () { $sidebar = $("#sidebar"); $gearMenu = $sidebar.find(".working-set-option-btn"); $splitViewMenu = $sidebar.find(".working-set-splitview-btn"); $projectTitle = $sidebar.find("#project-title"); $projectFilesContainer = $sidebar.find("#project-files-container"); $workingSetViewsContainer = $sidebar.find("#working-set-list-container"); function _resizeSidebarSelection() { var $element; $sidebar.find(".sidebar-selection").each(function (index, element) { $element = $(element); $element.width($element.parent()[0].scrollWidth); }); } // init $sidebar.on("panelResizeStart", function (evt, width) { $sidebar.find(".sidebar-selection-extension").css("display", "none"); $sidebar.find(".scroller-shadow").css("display", "none"); }); $sidebar.on("panelResizeUpdate", function (evt, width) { $sidebar.find(".sidebar-selection").width(width); ProjectManager._setFileTreeSelectionWidth(width); }); $sidebar.on("panelResizeEnd", function (evt, width) { _resizeSidebarSelection(); $sidebar.find(".sidebar-selection-extension").css("display", "block").css("left", width); $sidebar.find(".scroller-shadow").css("display", "block"); $projectFilesContainer.triggerHandler("scroll"); WorkingSetView.syncSelectionIndicator(); }); $sidebar.on("panelCollapsed", function (evt, width) { CommandManager.get(Commands.VIEW_HIDE_SIDEBAR).setName(Strings.CMD_SHOW_SIDEBAR); }); $sidebar.on("panelExpanded", function (evt, width) { WorkingSetView.refresh(); _resizeSidebarSelection(); $sidebar.find(".scroller-shadow").css("display", "block"); $sidebar.find(".sidebar-selection-extension").css("left", width); $projectFilesContainer.triggerHandler("scroll"); WorkingSetView.syncSelectionIndicator(); CommandManager.get(Commands.VIEW_HIDE_SIDEBAR).setName(Strings.CMD_HIDE_SIDEBAR); }); // AppInit.htmlReady in utils/Resizer executes before, so it's possible that the sidebar // is collapsed before we add the event. Check here initially if (!$sidebar.is(":visible")) { $sidebar.trigger("panelCollapsed"); } // wire up an event handler to monitor when panes are created MainViewManager.on("paneCreate", function (evt, paneId) { WorkingSetView.createWorkingSetViewForPane($workingSetViewsContainer, paneId); }); MainViewManager.on("paneLayoutChange", function () { _updateUIStates(); }); MainViewManager.on("workingSetAdd workingSetAddList workingSetRemove workingSetRemoveList workingSetUpdate", function () { _updateWorkingSetState(); }); // create WorkingSetViews for each pane already created _.forEach(MainViewManager.getPaneIdList(), function (paneId) { WorkingSetView.createWorkingSetViewForPane($workingSetViewsContainer, paneId); }); _updateUIStates(); // Tooltips $gearMenu.attr("title", Strings.GEAR_MENU_TOOLTIP); $splitViewMenu.attr("title", Strings.SPLITVIEW_MENU_TOOLTIP); }); ProjectManager.on("projectOpen", _updateProjectTitle); /** * Register Command Handlers */ _cmdSplitNone = CommandManager.register(Strings.CMD_SPLITVIEW_NONE, Commands.CMD_SPLITVIEW_NONE, _handleSplitViewNone); _cmdSplitVertical = CommandManager.register(Strings.CMD_SPLITVIEW_VERTICAL, Commands.CMD_SPLITVIEW_VERTICAL, _handleSplitViewVertical); _cmdSplitHorizontal = CommandManager.register(Strings.CMD_SPLITVIEW_HORIZONTAL, Commands.CMD_SPLITVIEW_HORIZONTAL, _handleSplitViewHorizontal); CommandManager.register(Strings.CMD_HIDE_SIDEBAR, Commands.VIEW_HIDE_SIDEBAR, toggle); // Define public API exports.toggle = toggle; exports.show = show; exports.hide = hide; exports.isVisible = isVisible; });
resir014/brackets
src/project/SidebarView.js
JavaScript
mit
10,278
export default function Home() { return <div className="red-text">This text should be red.</div> }
flybayer/next.js
test/integration/scss-fixtures/webpack-error/pages/index.js
JavaScript
mit
101
/* */ module.exports = { "default": require("core-js/library/fn/math/sign"), __esModule: true };
pauldijou/outdated
test/basic/jspm_packages/npm/babel-runtime@5.8.9/core-js/math/sign.js
JavaScript
apache-2.0
97
function loadedScript() { return "externalScript1"; }
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/svg/linking/scripted/testScripts/externalScript1.js
JavaScript
bsd-3-clause
56
/** * angular-strap * @version v2.1.2 - 2014-10-19 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes (olivier@mg-crea.com) * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict'; angular.module('mgcrea.ngStrap.popover').run(['$templateCache', function($templateCache) { $templateCache.put('popover/popover.tpl.html', '<div class="popover"><div class="arrow"></div><h3 class="popover-title" ng-bind="title" ng-show="title"></h3><div class="popover-content" ng-bind="content"></div></div>'); }]);
radhikabhanu/crowdsource-platform
staticfiles/bower_components/angular-strap/dist/modules/popover.tpl.js
JavaScript
mit
553
module.exports = TapProducer var Results = require("./tap-results") , inherits = require("inherits") , yamlish = require("yamlish") TapProducer.encode = function (result, diag) { var tp = new TapProducer(diag) , out = "" tp.on("data", function (c) { out += c }) if (Array.isArray(result)) { result.forEach(tp.write, tp) } else tp.write(result) tp.end() return out } var Stream = require("stream").Stream inherits(TapProducer, Stream) function TapProducer (diag) { Stream.call(this) this.diag = diag this.count = 0 this.readable = this.writable = true this.results = new Results } TapProducer.prototype.trailer = true TapProducer.prototype.write = function (res) { // console.error("TapProducer.write", res) if (typeof res === "function") throw new Error("wtf?") if (!this.writable) this.emit("error", new Error("not writable")) if (!this._didHead) { this.emit("data", "TAP version 13\n") this._didHead = true } var diag = res.diag if (diag === undefined) diag = this.diag this.emit("data", encodeResult(res, this.count + 1, diag)) if (typeof res === "string") return true if (res.bailout) { var bo = "bail out!" if (typeof res.bailout === "string") bo += " " + res.bailout this.emit("data", bo) return } this.results.add(res, false) this.count ++ } TapProducer.prototype.end = function (res) { if (res) this.write(res) // console.error("TapProducer end", res, this.results) this.emit("data", "\n1.."+this.results.testsTotal+"\n") if (this.trailer && typeof this.trailer !== "string") { // summary trailer. var trailer = "tests "+this.results.testsTotal + "\n" if (this.results.pass) { trailer += "pass " + this.results.pass + "\n" } if (this.results.fail) { trailer += "fail " + this.results.fail + "\n" } if (this.results.skip) { trailer += "skip "+this.results.skip + "\n" } if (this.results.todo) { trailer += "todo "+this.results.todo + "\n" } if (this.results.bailedOut) { trailer += "bailed out" + "\n" } if (this.results.testsTotal === this.results.pass) { trailer += "\nok\n" } this.trailer = trailer } if (this.trailer) this.write(this.trailer) this.writable = false this.emit("end", null, this.count, this.ok) } function encodeResult (res, count, diag) { // console.error(res, count, diag) if (typeof res === "string") { res = res.split(/\r?\n/).map(function (l) { if (!l.trim()) return l.trim() return "# " + l }).join("\n") if (res.substr(-1) !== "\n") res += "\n" return res } if (res.bailout) return "" if (!!process.env.TAP_NODIAG) diag = false else if (!!process.env.TAP_DIAG) diag = true else if (diag === undefined) diag = !res.ok var output = "" res.name = res.name && ("" + res.name).trim() output += ( !res.ok ? "not " : "") + "ok " + count + ( !res.name ? "" : " " + res.name.replace(/[\r\n]/g, " ") ) + ( res.skip ? " # SKIP " + ( res.explanation || "" ) : res.todo ? " # TODO " + ( res.explanation || "" ) : "" ) + "\n" if (!diag) return output var d = {} , dc = 0 Object.keys(res).filter(function (k) { return k !== "ok" && k !== "name" && k !== "id" }).forEach(function (k) { dc ++ d[k] = res[k] }) //console.error(d, "about to encode") if (dc > 0) output += " ---"+yamlish.encode(d)+"\n ...\n" return output }
joshdrink/app_swig
wp-content/themes/brew/node_modules/grunt-contrib-nodeunit/node_modules/nodeunit/node_modules/tap/lib/tap-producer.js
JavaScript
gpl-2.0
3,516
/** * Resource drag and drop. * * @class M.course.dragdrop.resource * @constructor * @extends M.core.dragdrop */ var DRAGRESOURCE = function() { DRAGRESOURCE.superclass.constructor.apply(this, arguments); }; Y.extend(DRAGRESOURCE, M.core.dragdrop, { initializer: function() { // Set group for parent class this.groups = ['resource']; this.samenodeclass = CSS.ACTIVITY; this.parentnodeclass = CSS.SECTION; this.resourcedraghandle = this.get_drag_handle(M.util.get_string('move', 'moodle'), CSS.EDITINGMOVE, CSS.ICONCLASS, true); this.samenodelabel = { identifier: 'dragtoafter', component: 'quiz' }; this.parentnodelabel = { identifier: 'dragtostart', component: 'quiz' }; // Go through all sections this.setup_for_section(); // Initialise drag & drop for all resources/activities var nodeselector = 'li.' + CSS.ACTIVITY; var del = new Y.DD.Delegate({ container: '.' + CSS.COURSECONTENT, nodes: nodeselector, target: true, handles: ['.' + CSS.EDITINGMOVE], dragConfig: {groups: this.groups} }); del.dd.plug(Y.Plugin.DDProxy, { // Don't move the node at the end of the drag moveOnEnd: false, cloneNode: true }); del.dd.plug(Y.Plugin.DDConstrained, { // Keep it inside the .mod-quiz-edit-content constrain: '#' + CSS.SLOTS }); del.dd.plug(Y.Plugin.DDWinScroll); M.mod_quiz.quizbase.register_module(this); M.mod_quiz.dragres = this; }, /** * Apply dragdrop features to the specified selector or node that refers to section(s) * * @method setup_for_section * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_section: function() { Y.Node.all('.mod-quiz-edit-content ul.slots ul.section').each(function(resources) { resources.setAttribute('data-draggroups', this.groups.join(' ')); // Define empty ul as droptarget, so that item could be moved to empty list new Y.DD.Drop({ node: resources, groups: this.groups, padding: '20 0 20 0' }); // Initialise each resource/activity in this section this.setup_for_resource('li.activity'); }, this); }, /** * Apply dragdrop features to the specified selector or node that refers to resource(s) * * @method setup_for_resource * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_resource: function(baseselector) { Y.Node.all(baseselector).each(function(resourcesnode) { // Replace move icons var move = resourcesnode.one('a.' + CSS.EDITINGMOVE); if (move) { move.replace(this.resourcedraghandle.cloneNode(true)); } }, this); }, drag_start: function(e) { // Get our drag object var drag = e.target; drag.get('dragNode').setContent(drag.get('node').get('innerHTML')); drag.get('dragNode').all('img.iconsmall').setStyle('vertical-align', 'baseline'); }, drag_dropmiss: function(e) { // Missed the target, but we assume the user intended to drop it // on the last ghost node location, e.drag and e.drop should be // prepared by global_drag_dropmiss parent so simulate drop_hit(e). this.drop_hit(e); }, drop_hit: function(e) { var drag = e.drag; // Get a reference to our drag node var dragnode = drag.get('node'); var dropnode = e.drop.get('node'); // Add spinner if it not there var actionarea = dragnode.one(CSS.ACTIONAREA); var spinner = M.util.add_spinner(Y, actionarea); var params = {}; // Handle any variables which we must pass back through to var pageparams = this.get('config').pageparams; var varname; for (varname in pageparams) { params[varname] = pageparams[varname]; } // Prepare request parameters params.sesskey = M.cfg.sesskey; params.courseid = this.get('courseid'); params.quizid = this.get('quizid'); params['class'] = 'resource'; params.field = 'move'; params.id = Number(Y.Moodle.mod_quiz.util.slot.getId(dragnode)); params.sectionId = Y.Moodle.core_course.util.section.getId(dropnode.ancestor('li.section', true)); var previousslot = dragnode.previous(SELECTOR.SLOT); if (previousslot) { params.previousid = Number(Y.Moodle.mod_quiz.util.slot.getId(previousslot)); } var previouspage = dragnode.previous(SELECTOR.PAGE); if (previouspage) { params.page = Number(Y.Moodle.mod_quiz.util.page.getId(previouspage)); } // Do AJAX request var uri = M.cfg.wwwroot + this.get('ajaxurl'); Y.io(uri, { method: 'POST', data: params, on: { start: function() { this.lock_drag_handle(drag, CSS.EDITINGMOVE); spinner.show(); }, success: function(tid, response) { var responsetext = Y.JSON.parse(response.responseText); var params = {element: dragnode, visible: responsetext.visible}; M.mod_quiz.quizbase.invoke_function('set_visibility_resource_ui', params); this.unlock_drag_handle(drag, CSS.EDITINGMOVE); window.setTimeout(function() { spinner.hide(); }, 250); M.mod_quiz.resource_toolbox.reorganise_edit_page(); }, failure: function(tid, response) { this.ajax_failure(response); this.unlock_drag_handle(drag, CSS.SECTIONHANDLE); spinner.hide(); window.location.reload(true); } }, context:this }); }, global_drop_over: function(e) { //Overriding parent method so we can stop the slots being dragged before the first page node. // Check that drop object belong to correct group. if (!e.drop || !e.drop.inGroup(this.groups)) { return; } // Get a reference to our drag and drop nodes. var drag = e.drag.get('node'), drop = e.drop.get('node'); // Save last drop target for the case of missed target processing. this.lastdroptarget = e.drop; // Are we dropping within the same parent node? if (drop.hasClass(this.samenodeclass)) { var where; if (this.goingup) { where = "before"; } else { where = "after"; } drop.insert(drag, where); } else if ((drop.hasClass(this.parentnodeclass) || drop.test('[data-droptarget="1"]')) && !drop.contains(drag)) { // We are dropping on parent node and it is empty if (this.goingup) { drop.append(drag); } else { drop.prepend(drag); } } this.drop_over(e); } }, { NAME: 'mod_quiz-dragdrop-resource', ATTRS: { courseid: { value: null }, quizid: { value: null }, ajaxurl: { value: 0 }, config: { value: 0 } } }); M.mod_quiz = M.mod_quiz || {}; M.mod_quiz.init_resource_dragdrop = function(params) { new DRAGRESOURCE(params); };
ernestovi/ups
moodle/mod/quiz/yui/src/dragdrop/js/resource.js
JavaScript
gpl-3.0
7,887
// Heartbeat options: // heartbeatInterval: interval to send pings, in milliseconds. // heartbeatTimeout: timeout to close the connection if a reply isn't // received, in milliseconds. // sendPing: function to call to send a ping on the connection. // onTimeout: function to call to close the connection. DDPCommon.Heartbeat = function (options) { var self = this; self.heartbeatInterval = options.heartbeatInterval; self.heartbeatTimeout = options.heartbeatTimeout; self._sendPing = options.sendPing; self._onTimeout = options.onTimeout; self._seenPacket = false; self._heartbeatIntervalHandle = null; self._heartbeatTimeoutHandle = null; }; _.extend(DDPCommon.Heartbeat.prototype, { stop: function () { var self = this; self._clearHeartbeatIntervalTimer(); self._clearHeartbeatTimeoutTimer(); }, start: function () { var self = this; self.stop(); self._startHeartbeatIntervalTimer(); }, _startHeartbeatIntervalTimer: function () { var self = this; self._heartbeatIntervalHandle = Meteor.setInterval( _.bind(self._heartbeatIntervalFired, self), self.heartbeatInterval ); }, _startHeartbeatTimeoutTimer: function () { var self = this; self._heartbeatTimeoutHandle = Meteor.setTimeout( _.bind(self._heartbeatTimeoutFired, self), self.heartbeatTimeout ); }, _clearHeartbeatIntervalTimer: function () { var self = this; if (self._heartbeatIntervalHandle) { Meteor.clearInterval(self._heartbeatIntervalHandle); self._heartbeatIntervalHandle = null; } }, _clearHeartbeatTimeoutTimer: function () { var self = this; if (self._heartbeatTimeoutHandle) { Meteor.clearTimeout(self._heartbeatTimeoutHandle); self._heartbeatTimeoutHandle = null; } }, // The heartbeat interval timer is fired when we should send a ping. _heartbeatIntervalFired: function () { var self = this; // don't send ping if we've seen a packet since we last checked, // *or* if we have already sent a ping and are awaiting a timeout. // That shouldn't happen, but it's possible if // `self.heartbeatInterval` is smaller than // `self.heartbeatTimeout`. if (! self._seenPacket && ! self._heartbeatTimeoutHandle) { self._sendPing(); // Set up timeout, in case a pong doesn't arrive in time. self._startHeartbeatTimeoutTimer(); } self._seenPacket = false; }, // The heartbeat timeout timer is fired when we sent a ping, but we // timed out waiting for the pong. _heartbeatTimeoutFired: function () { var self = this; self._heartbeatTimeoutHandle = null; self._onTimeout(); }, messageReceived: function () { var self = this; // Tell periodic checkin that we have seen a packet, and thus it // does not need to send a ping this cycle. self._seenPacket = true; // If we were waiting for a pong, we got it. if (self._heartbeatTimeoutHandle) { self._clearHeartbeatTimeoutTimer(); } } });
lawrenceAIO/meteor
packages/ddp-common/heartbeat.js
JavaScript
mit
3,044
require('./angular-locale_nl-cw'); module.exports = 'ngLocale';
DamascenoRafael/cos482-qualidade-de-software
www/src/main/webapp/bower_components/angular-i18n/nl-cw.js
JavaScript
mit
64
require('./angular-locale_en-im'); module.exports = 'ngLocale';
DamascenoRafael/cos482-qualidade-de-software
www/src/main/webapp/bower_components/angular-i18n/en-im.js
JavaScript
mit
64
// This depends on tinytest, so it's a little weird to put it in // test-helpers, but it'll do for now. // Provides the testAsyncMulti helper, which creates an async test // (using Tinytest.addAsync) that tracks parallel and sequential // asynchronous calls. Specifically, the two features it provides // are: // 1) Executing an array of functions sequentially when those functions // contain async calls. // 2) Keeping track of when callbacks are outstanding, via "expect". // // To use, pass an array of functions that take arguments (test, expect). // (There is no onComplete callback; completion is determined automatically.) // Expect takes a callback closure and wraps it, returning a new callback closure, // and making a note that there is a callback oustanding. Pass this returned closure // to async functions as the callback, and the machinery in the wrapper will // record the fact that the callback has been called. // // A second form of expect takes data arguments to test for. // Essentially, expect("foo", "bar") is equivalent to: // expect(function(arg1, arg2) { test.equal([arg1, arg2], ["foo", "bar"]); }). // // You cannot "nest" expect or call it from a callback! Even if you have a chain // of callbacks, you need to call expect at the "top level" (synchronously) // but the callback you wrap has to be the last/innermost one. This sometimes // leads to some code contortions and should probably be fixed. // Example: (at top level of test file) // // testAsyncMulti("test name", [ // function(test, expect) { // ... tests here // Meteor.defer(expect(function() { // ... tests here // })); // // call_something_async('foo', 'bar', expect('baz')); // implicit callback // // }, // function(test, expect) { // ... more tests // } // ]); var ExpectationManager = function (test, onComplete) { var self = this; self.test = test; self.onComplete = onComplete; self.closed = false; self.dead = false; self.outstanding = 0; }; _.extend(ExpectationManager.prototype, { expect: function (/* arguments */) { var self = this; if (typeof arguments[0] === "function") var expected = arguments[0]; else var expected = _.toArray(arguments); if (self.closed) throw new Error("Too late to add more expectations to the test"); self.outstanding++; return function (/* arguments */) { if (self.dead) return; if (typeof expected === "function") { try { expected.apply({}, arguments); } catch (e) { if (self.cancel()) self.test.exception(e); } } else { self.test.equal(_.toArray(arguments), expected); } self.outstanding--; self._check_complete(); }; }, done: function () { var self = this; self.closed = true; self._check_complete(); }, cancel: function () { var self = this; if (! self.dead) { self.dead = true; return true; } return false; }, _check_complete: function () { var self = this; if (!self.outstanding && self.closed && !self.dead) { self.dead = true; self.onComplete(); } } }); testAsyncMulti = function (name, funcs) { // XXX Tests on remote browsers are _slow_. We need a better solution. var timeout = 180000; Tinytest.addAsync(name, function (test, onComplete) { var remaining = _.clone(funcs); var context = {}; var i = 0; var runNext = function () { var func = remaining.shift(); if (!func) { delete test.extraDetails.asyncBlock; onComplete(); } else { var em = new ExpectationManager(test, function () { Meteor.clearTimeout(timer); runNext(); }); var timer = Meteor.setTimeout(function () { if (em.cancel()) { test.fail({type: "timeout", message: "Async batch timed out"}); onComplete(); } return; }, timeout); test.extraDetails.asyncBlock = i++; try { func.apply(context, [test, _.bind(em.expect, em)]); } catch (exception) { if (em.cancel()) test.exception(exception); Meteor.clearTimeout(timer); // Because we called test.exception, we're not to call onComplete. return; } em.done(); } }; runNext(); }); }; // Call `fn` periodically until it returns true. If it does, call // `success`. If it doesn't before the timeout, call `failed`. simplePoll = function (fn, success, failed, timeout, step) { timeout = timeout || 10000; step = step || 100; var start = (new Date()).valueOf(); var helper = function () { if (fn()) { success(); return; } if (start + timeout < (new Date()).valueOf()) { failed(); return; } Meteor.setTimeout(helper, step); }; helper(); }; pollUntil = function (expect, f, timeout, step, noFail) { noFail = noFail || false; step = step || 100; var expectation = expect(true); simplePoll( f, function () { expectation(true) }, function () { expectation(noFail) }, timeout, step ); };
jrudio/meteor
packages/test-helpers/async_multi.js
JavaScript
mit
5,209
var assert = require('assert'); var Kareem = require('../'); describe('execPre', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('handles errors with multiple pres', function(done) { var execed = {}; hooks.pre('cook', function(done) { execed.first = true; done(); }); hooks.pre('cook', function(done) { execed.second = true; done('error!'); }); hooks.pre('cook', function(done) { execed.third = true; done(); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('error!'); }, 5); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { done('other error!'); }, 10); next(); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors in next()', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 15); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { next('error!'); done('another error!'); }, 5); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors in next() when already done', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 5); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { next('error!'); done('another error!'); }, 25); }); hooks.execPre('cook', null, function(err) { assert.equal('other error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('async pres with clone()', function(done) { var execed = false; hooks.pre('cook', true, function(next, done) { execed = true; setTimeout( function() { done(); }, 5); next(); }); hooks.clone().execPre('cook', null, function(err) { assert.ifError(err); assert.ok(execed); done(); }); }); it('returns correct error when async pre errors', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 5); next(); }); hooks.pre('cook', function(next) { execed.second = true; setTimeout( function() { next('error!'); }, 15); }); hooks.execPre('cook', null, function(err) { assert.equal('other error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('lets async pres run when fully sync pres are done', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done(); }, 5); next(); }); hooks.pre('cook', function() { execed.second = true; }); hooks.execPre('cook', null, function(err) { assert.ifError(err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('allows passing arguments to the next pre', function(done) { var execed = {}; hooks.pre('cook', function(next) { execed.first = true; next(null, 'test'); }); hooks.pre('cook', function(next, p) { execed.second = true; assert.equal(p, 'test'); next(); }); hooks.pre('cook', function(next, p) { execed.third = true; assert.ok(!p); next(); }); hooks.execPre('cook', null, function(err) { assert.ifError(err); assert.equal(3, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); assert.ok(execed.third); done(); }); }); }); describe('execPreSync', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('executes hooks synchronously', function() { var execed = {}; hooks.pre('cook', function() { execed.first = true; }); hooks.pre('cook', function() { execed.second = true; }); hooks.execPreSync('cook', null); assert.ok(execed.first); assert.ok(execed.second); }); it('works with no hooks specified', function() { assert.doesNotThrow(function() { hooks.execPreSync('cook', null); }); }); });
ChrisChenSZ/code
表单注册验证/node_modules/kareem/test/pre.test.js
JavaScript
apache-2.0
5,771
var s = `a b c`; assert.equal(s, 'a\n b\n c');
oleksandr-minakov/northshore
ui/node_modules/es6-templates/test/examples/multi-line.js
JavaScript
apache-2.0
61
var gulp = require('gulp'); var browserSync = require('browser-sync'); var sass = require('gulp-sass'); var reload = browserSync.reload; var src = { scss: 'app/scss/*.scss', css: 'app/css', html: 'app/*.html' }; // Static Server + watching scss/html files gulp.task('serve', ['sass'], function() { browserSync({ server: "./app" }); gulp.watch(src.scss, ['sass']); gulp.watch(src.html).on('change', reload); }); // Compile sass into CSS gulp.task('sass', function() { return gulp.src(src.scss) .pipe(sass()) .pipe(gulp.dest(src.css)) .pipe(reload({stream: true})); }); gulp.task('default', ['serve']);
yuyang545262477/Resume
项目二电商首页/node_modules/bs-recipes/recipes/gulp.sass/gulpfile.js
JavaScript
mit
691
// Validate.js 0.1.1 // (c) 2013 Wrapp // Validate.js may be freely distributed under the MIT license. // For all details and documentation: // http://validatejs.org/ (function(exports, module) { "use strict"; // The main function that calls the validators specified by the constraints. // The options are the following: // var validate = function(attributes, constraints, options) { var attr , error , validator , validatorName , validatorOptions , value , validators , errors = {}; options = options || {}; // Loops through each constraints, finds the correct validator and run it. for (attr in constraints) { value = attributes[attr]; validators = v.result(constraints[attr], value, attributes, attr); for (validatorName in validators) { validator = v.validators[validatorName]; if (!validator) { error = v.format("Unknown validator %{name}", {name: validatorName}); throw new Error(error); } validatorOptions = validators[validatorName]; // This allows the options to be a function. The function will be called // with the value, attribute name and the complete dict of attribues. // This is useful when you want to have different validations depending // on the attribute value. validatorOptions = v.result(validatorOptions, value, attributes, attr); if (!validatorOptions) continue; error = validator.call(validator, value, validatorOptions, attr, attributes); // The validator is allowed to return a string or an array. if (v.isString(error)) error = [error]; if (error && error.length > 0) errors[attr] = (errors[attr] || []).concat(error); } } // Return the errors if we have any for (attr in errors) return v.fullMessages(errors, options); }; var v = validate , root = this , XDate = root.XDate // Finds %{key} style patterns in the given string , FORMAT_REGEXP = /%\{([^\}]+)\}/g; // Copies over attributes from one or more sources to a single destination. // Very much similar to underscore's extend. // The first argument is the target object and the remaining arguments will be // used as targets. v.extend = function(obj) { var i , attr , source , sources = [].slice.call(arguments, 1); for (i = 0; i < sources.length; ++i) { source = sources[i]; for (attr in source) obj[attr] = source[attr]; } return obj; }; v.extend(validate, { // If the given argument is a call: function the and: function return the value // otherwise just return the value. Additional arguments will be passed as // arguments to the function. // Example: // ``` // result('foo') // 'foo' // result(Math.max, 1, 2) // 2 // ``` result: function(value) { var args = [].slice.call(arguments, 1); if (typeof value === 'function') value = value.apply(null, args); return value; }, // Checks if the value is a number. This function does not consider NaN a // number like many other `isNumber` functions do. isNumber: function(value) { return typeof value === 'number' && !isNaN(value); }, // A simple check to verify that the value is an integer. Uses `isNumber` // and a simple modulo check. isInteger: function(value) { return v.isNumber(value) && value % 1 === 0; }, // Uses the `Object` function to check if the given argument is an object. isObject: function(obj) { return obj === Object(obj); }, // Returns false if the object is `null` of `undefined` isDefined: function(obj) { return obj !== null && obj !== undefined; }, // Formats the specified strings with the given values like so: // ``` // format("Foo: %{foo}", {foo: "bar"}) // "Foo bar" // ``` format: function(str, vals) { return str.replace(FORMAT_REGEXP, function(m0, m1) { return String(vals[m1]); }); }, // "Prettifies" the given string. // Prettifying means replacing - and _ with spaces as well as splitting // camel case words. prettify: function(str) { return str // Replaces - and _ with spaces .replace(/[_\-]/g, ' ') // Splits camel cased words .replace(/([a-z])([A-Z])/g, function(m0, m1, m2) { return "" + m1 + " " + m2.toLowerCase(); }) .toLowerCase(); }, isString: function(value) { return typeof value === 'string'; }, isArray: function(value) { return {}.toString.call(value) === '[object Array]'; }, contains: function(obj, value) { var i; if (!v.isDefined(obj)) return false; if (v.isArray(obj)) { if (obj.indexOf(value)) return obj.indexOf(value) !== -1; for (i = obj.length - 1; i >= 0; --i) { if (obj[i] === value) return true; } return false; } return value in obj; }, capitalize: function(str) { if (!str) return str; return str[0].toUpperCase() + str.slice(1); }, fullMessages: function(errors, options) { options = options || {}; var ret = options.flatten ? [] : {} , attr , i , error; if (!errors) return ret; // Converts the errors of object of the format // {attr: [<error>, <error>, ...]} to contain the attribute name. for (attr in errors) { for (i = 0; i < errors[attr].length; ++i) { error = errors[attr][i]; if (error[0] === '^') error = error.slice(1); else if (options.fullMessages !== false) { error = v.format("%{attr} %{message}", { attr: v.capitalize(v.prettify(attr)), message: error }); } error = error.replace(/\\\^/g, "^"); // If flatten is true a flat array is returned. if (options.flatten) ret.push(error); else (ret[attr] || (ret[attr] = [])).push(error); } } return ret; }, }); validate.validators = { // Presence validates that the value isn't empty presence: function(value, options) { var message = options.message || "can't be blank" , attr; // Null and undefined aren't allowed if (!v.isDefined(value)) return message; if (typeof value === 'string') { // Tests if the string contains only whitespace (tab, newline, space etc) if ((/^\s*$/).test(value)) return message; } else if (v.isArray(value)) { // For arrays we use the length property if (value.length === 0) return message; } else if (v.isObject(value)) { // If we find at least one property we consider it non empty for (attr in value) return; return message; } }, length: function(value, options) { // Null and undefined are fine if (!v.isDefined(value)) return; var is = options.is , maximum = options.maximum , minimum = options.minimum , tokenizer = options.tokenizer || function(val) { return val; } , err , errors = []; value = tokenizer(value); // Is checks if (v.isNumber(is) && value.length !== is) { err = options.wrongLength || "is the wrong length (should be %{count} characters)"; errors.push(v.format(err, {count: is})); } if (v.isNumber(minimum) && value.length < minimum) { err = options.tooShort || "is too short (minimum is %{count} characters)"; errors.push(v.format(err, {count: minimum})); } if (v.isNumber(maximum) && value.length > maximum) { err = options.tooLong || "is too long (maximum is %{count} characters)"; errors.push(v.format(err, {count: maximum})); } if (errors.length > 0) return options.message || errors; }, numericality: function(value, options) { if (!v.isDefined(value)) return; var errors = [] , name , count , checks = { greaterThan: function(v, c) { return v > c; }, greaterThanOrEqualTo: function(v, c) { return v >= c; }, equalTo: function(v, c) { return v === c; }, lessThan: function(v, c) { return v < c; }, lessThanOrEqualTo: function(v, c) { return v <= c; } }; // Coerce the value to a number unless we're being strict. if (options.noStrings !== true && v.isString(value)) value = +value; // If it's not a number we shouldn't continue since it will compare it. if (!v.isNumber(value)) return options.message || "is not a number"; // Same logic as above, sort of. Don't bother with comparisons if this // doesn't pass. if (options.onlyInteger && !v.isInteger(value)) return options.message || "must be an integer"; for (name in checks) { count = options[name]; if (v.isNumber(count) && !checks[name](value, count)) { errors.push(v.format("must be %{type} %{count}", { count: count, type: v.prettify(name) })); } } if (options.odd && value % 2 !== 1) errors.push("must be odd"); if (options.even && value % 2 !== 0) errors.push("must be even"); if (errors.length) return options.message || errors; }, datetime: v.extend(function(value, options) { if (!v.isDefined(value)) return; var err , errors = [] , message = options.message , earliest = options.earliest ? this.parse(options.earliest, options) : NaN , latest = options.latest ? this.parse(options.latest, options) : NaN; value = this.parse(value, options); if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) return message || "must be a valid date"; if (!isNaN(earliest) && value < earliest) { err = "must be no earlier than %{date}"; err = v.format(err, {date: this.format(earliest, options)}); errors.push(err); } if (!isNaN(latest) && value > latest) { err = "must be no later than %{date}"; err = v.format(err, {date: this.format(latest, options)}); errors.push(err); } if (errors.length) return options.message || errors; }, { // This is the function that will be used to convert input to the number // of millis since the epoch. // It should return NaN if it's not a valid date. parse: function(value, options) { return new XDate(value, true).getTime(); }, // Formats the given timestamp. Uses ISO8601 to format them. // If options.dateOnly is true then only the year, month and day will be // output. format: function(date, options) { var format = options.dateFormat || (options.dateOnly ? "yyyy-MM-dd" : "u"); return new XDate(date, true).toString(format); } }), date: function(value, options) { options = v.extend({}, options, {onlyDate: true}); return v.validators.datetime(value, options); }, format: function(value, options) { if (v.isString(options) || (options instanceof RegExp)) options = {pattern: options}; var message = options.message || "is invalid" , pattern = options.pattern , match; if (!v.isDefined(value)) return; if (!v.isString(value)) return message; if (v.isString(pattern)) pattern = new RegExp(options.pattern, options.flags); match = pattern.exec(value); if (!match || match[0].length != value.length) return message; }, inclusion: function(value, options) { if (v.isArray(options)) options = {within: options}; if (!v.isDefined(value)) return; if (v.contains(options.within, value)) return; var message = options.message || "^%{value} is not included in the list"; return v.format(message, {value: value}); }, exclusion: function(value, options) { if (v.isArray(options)) options = {within: options}; if (!v.isDefined(value)) return; if (!v.contains(options.within, value)) return; var message = options.message || "^%{value} is restricted"; return v.format(message, {value: value}); } }; if (exports) { if (module && module.exports) exports = module.exports = validate; exports.validate = validate; } else root.validate = validate; }).call(this, typeof exports !== 'undefined' ? exports : null, typeof module !== 'undefined' ? module : null);
Piicksarn/cdnjs
ajax/libs/validate.js/0.1.1/validate.js
JavaScript
mit
12,865
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["sourceMap"] = factory(); else root["sourceMap"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; exports.SourceNode = __webpack_require__(10).SourceNode; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var base64VLQ = __webpack_require__(2); var util = __webpack_require__(4); var ArraySet = __webpack_require__(5).ArraySet; var MappingList = __webpack_require__(6).MappingList; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following * properties: * * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name != null) { name = String(name); if (!this._names.has(name)) { this._names.add(name); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = Object.create(null); } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param aSourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "sourceFile" this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { // Copy mapping mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util.join(aSourceMapPath, mapping.source) } if (sourceRoot != null) { mapping.source = util.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aSourceMapPath != null) { sourceFile = util.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { // When aOriginal is truthy but has empty values for .line and .column, // it is most likely a programmer error. In this case we throw a very // specific error message to try to guide them the right way. // For example: https://github.com/Polymer/polymer-bundler/pull/519 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { throw new Error( 'original.line and original.column are not numbers -- you probably meant to omit ' + 'the original mapping entirely and only map the generated position. If so, pass ' + 'null for the original mapping instead of an object with empty or null values.' ); } if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = '' if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } next += ','; } } next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map.file = this._file; } if (this._sourceRoot != null) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var base64 = __webpack_require__(3); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; /***/ }), /* 3 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function (number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; /** * Decode a single base 64 character code digit to an integer. Returns -1 on * failure. */ exports.decode = function (charCode) { var bigA = 65; // 'A' var bigZ = 90; // 'Z' var littleA = 97; // 'a' var littleZ = 122; // 'z' var zero = 48; // '0' var nine = 57; // '9' var plus = 43; // '+' var slash = 47; // '/' var littleOffset = 26; var numberOffset = 52; // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ if (bigA <= charCode && charCode <= bigZ) { return (charCode - bigA); } // 26 - 51: abcdefghijklmnopqrstuvwxyz if (littleA <= charCode && charCode <= littleZ) { return (charCode - littleA + littleOffset); } // 52 - 61: 0123456789 if (zero <= charCode && charCode <= nine) { return (charCode - zero + numberOffset); } // 62: + if (charCode == plus) { return 62; } // 63: / if (charCode == slash) { return 63; } // Invalid base64 digit. return -1; }; /***/ }), /* 4 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '<dir>/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(4); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = hasNativeMap ? new Map() : Object.create(null); } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util.toSetString(aStr); return has.call(this._set, sStr); } }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(4); /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(4); var binarySearch = __webpack_require__(8); var ArraySet = __webpack_require__(5).ArraySet; var base64VLQ = __webpack_require__(2); var quickSort = __webpack_require__(9).quickSort; function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap); } SourceMapConsumer.fromSourceMap = function(aSourceMap) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap); } /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); if (source != null && sourceRoot != null) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a either the line we are searching for or the next * closest line that has any mappings. Otherwise, returns all mappings * corresponding to the given line and either the column we are searching for * or the next closest column that has any offsets. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: Optional. the column number in the original source. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util.getArg(aArgs, 'line'); // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. var needle = { source: util.getArg(aArgs, 'source'), originalLine: line, originalColumn: util.getArg(aArgs, 'column', 0) }; if (this.sourceRoot != null) { needle.source = util.relative(this.sourceRoot, needle.source); } if (!this._sources.has(needle.source)) { return []; } needle.source = this._sources.indexOf(needle.source); var mappings = []; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index >= 0) { var mapping = this._originalMappings[index]; if (aArgs.column === undefined) { var originalLine = mapping.originalLine; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we found. Since // mappings are sorted, this is guaranteed to find all mappings for // the line we found. while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } else { var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we were searching for. // Since mappings are sorted, this is guaranteed to find all mappings for // the line we are searching for. while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: Optional. The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function BasicSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } sources = sources .map(String) // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. .map(util.normalize) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. .map(function (source) { return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; }); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns BasicSourceMapConsumer */ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; // Because we are modifying the entries (by converting string sources and // names to indices into the sources and names ArraySets), we have to make // a copy of the entry or else bad things happen. Shared mutable state // strikes again! See github issue #191. var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; var destMapping = new Mapping; destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; }, this); } }); /** * Provide the JIT with a nice shape / hidden class. */ function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment, end, value; while (index < length) { if (aStr.charAt(index) === ';') { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ',') { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, // many segments often have the same encoding. We can exploit this // fact by caching the parsed variable length fields of each segment, // allowing us to avoid a second parse if we encounter the same // segment again. for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); segment = cachedSegments[str]; if (segment) { index += str.length; } else { segment = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error('Found a source, but no line and column'); } if (segment.length === 3) { throw new Error('Found a source and line, but no column'); } cachedSegments[str] = segment; } // Generated column. mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { // Original source. mapping.source = previousSource + segment[1]; previousSource += segment[1]; // Original line. mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; // Original column. mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { // Original name. mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { originalMappings.push(mapping); } } } quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util.compareByOriginalPositions); this.__originalMappings = originalMappings; }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } // The last mapping for each line spans the entire line. mapping.lastGeneratedColumn = Infinity; } }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util.getArg(mapping, 'source', null); if (source !== null) { source = this._sources.at(source); if (this.sourceRoot != null) { source = util.join(this.sourceRoot, source); } } var name = util.getArg(mapping, 'name', null); if (name !== null) { name = this._names.at(name); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: name }; } } return { source: null, line: null, column: null, name: null }; }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) { return sc == null; }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } if (this.sourceRoot != null) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } // This function is used recursively from // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we // don't want to throw if we can't find the source - we just want to // return null, so we provide a flag to exit gracefully. if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util.getArg(aArgs, 'source'); if (this.sourceRoot != null) { source = util.relative(this.sourceRoot, source); } if (!this._sources.has(source)) { return { line: null, column: null, lastColumn: null }; } source = this._sources.indexOf(source); var needle = { source: source, originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; exports.BasicSourceMapConsumer = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in * that it takes "indexed" source maps (i.e. ones with a "sections" field) as * input. * * The only parameter is a raw source map (either as a JSON string, or already * parsed to an object). According to the spec for indexed source maps, they * have the following attributes: * * - version: Which version of the source map spec this map is following. * - file: Optional. The generated file this source map is associated with. * - sections: A list of section definitions. * * Each value under the "sections" field has two fields: * - offset: The offset into the original specified at which this section * begins to apply, defined as an object with a "line" and "column" * field. * - map: A source map definition. This source map could also be indexed, * but doesn't have to be. * * Instead of the "map" field, it's also possible to have a "url" field * specifying a URL to retrieve a source map from, but that's currently * unsupported. * * Here's an example source map, taken from the source map spec[0], but * modified to omit a section which uses the "url" field. * * { * version : 3, * file: "app.js", * sections: [{ * offset: {line:100, column:10}, * map: { * version : 3, * file: "section.js", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AAAA,E;;ABCDE;" * } * }], * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ function IndexedSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sections = util.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function (s) { if (s.url) { // The url field will require support for asynchronicity. // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } var offset = util.getArg(s, 'offset'); var offsetLine = util.getArg(offset, 'line'); var offsetColumn = util.getArg(offset, 'column'); if (offsetLine < lastOffset.line || (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { throw new Error('Section offsets must be ordered and non-overlapping.'); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, 'map')) } }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; /** * The version of the source mapping spec that we are consuming. */ IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { get: function () { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } } return sources; } }); /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; // Find the section containing the generated position we're trying to map // to an original position. var sectionIndex = binarySearch.search(needle, this._sections, function(needle, section) { var cmp = needle.generatedLine - section.generatedOffset.generatedLine; if (cmp) { return cmp; } return (needle.generatedColumn - section.generatedOffset.generatedColumn); }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function (s) { return s.consumer.hasContentsOfAllSources(); }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; // Only consider this section if the requested source is in the list of // sources of the consumer. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[j]; var source = section.consumer._sources.at(mapping.source); if (section.consumer.sourceRoot !== null) { source = util.join(section.consumer.sourceRoot, source); } this._sources.add(source); source = this._sources.indexOf(source); var name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); // The mappings coming from the consumer for the section have // generated positions relative to the start of the section, so we // need to offset them to be relative to the start of the concatenated // generated file. var adjustedMapping = { source: source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === 'number') { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util.compareByOriginalPositions); }; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; /***/ }), /* 8 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } /** * This is an implementation of binary search which will always try and return * the index of the closest element if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND); if (index < 0) { return -1; } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; /***/ }), /* 9 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ // It turns out that some (most?) JavaScript engines don't self-host // `Array.prototype.sort`. This makes sense because C++ will likely remain // faster than JS when doing raw CPU-intensive sorting. However, when using a // custom comparator function, calling back and forth between the VM's C++ and // JIT'd JS is rather slow *and* loses JIT type information, resulting in // worse generated code for the comparator function than would be optimal. In // fact, when sorting with a comparator, these costs outweigh the benefits of // sorting in C++. By using our own JS-implemented Quick Sort (below), we get // a ~3500ms mean speed-up in `bench/bench.html`. /** * Swap the elements indexed by `x` and `y` in the array `ary`. * * @param {Array} ary * The array. * @param {Number} x * The index of the first item. * @param {Number} y * The index of the second item. */ function swap(ary, x, y) { var temp = ary[x]; ary[x] = ary[y]; ary[y] = temp; } /** * Returns a random integer within the range `low .. high` inclusive. * * @param {Number} low * The lower bound on the range. * @param {Number} high * The upper bound on the range. */ function randomIntInRange(low, high) { return Math.round(low + (Math.random() * (high - low))); } /** * The Quick Sort algorithm. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. * @param {Number} p * Start index of the array * @param {Number} r * End index of the array */ function doQuickSort(ary, comparator, p, r) { // If our lower bound is less than our upper bound, we (1) partition the // array into two pieces and (2) recurse on each half. If it is not, this is // the empty array and our base case. if (p < r) { // (1) Partitioning. // // The partitioning chooses a pivot between `p` and `r` and moves all // elements that are less than or equal to the pivot to the before it, and // all the elements that are greater than it after it. The effect is that // once partition is done, the pivot is in the exact place it will be when // the array is put in sorted order, and it will not need to be moved // again. This runs in O(n) time. // Always choose a random pivot so that an input array which is reverse // sorted does not cause O(n^2) running time. var pivotIndex = randomIntInRange(p, r); var i = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; // Immediately after `j` is incremented in this loop, the following hold // true: // // * Every element in `ary[p .. i]` is less than or equal to the pivot. // // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; swap(ary, i, j); } } swap(ary, i + 1, j); var q = i + 1; // (2) Recurse on each half. doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } /** * Sort the given array in-place with the given comparator function. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. */ exports.quickSort = function (ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; var util = __webpack_require__(4); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are accessed by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); // The last line of a file might not have a newline. var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : undefined; } }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[remainingLinesIndex]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.splice(remainingLinesIndex).join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; /***/ }) /******/ ]) }); ;
hellokidder/js-studying
微信小程序/wxtest/node_modules/source-map/dist/source-map.js
JavaScript
mit
101,940