Best JavaScript code snippet using wpt
webxr-test.js
Source:webxr-test.js  
...681    // Reserve the id for hit test source:682    const id = this.next_hit_test_id_++;683    const hitTestParameters = { isTransient: false, profileName: null };684    const controller = new FakeXRHitTestSourceController(id);685    return this._shouldHitTestSourceCreationSucceed(hitTestParameters, controller)686      .then((succeeded) => {687        if(succeeded) {688          // Store the subscription information as-is (including controller):689          this.hitTestSubscriptions_.set(id, { nativeOriginInformation, entityTypes, ray, controller });690          return Promise.resolve({691            result : device.mojom.SubscribeToHitTestResult.SUCCESS,692            subscriptionId : id693          });694        } else {695          return Promise.resolve({696            result : device.mojom.SubscribeToHitTestResult.FAILURE_GENERIC,697            subscriptionId : 0698          });699        }700      });701  }702  subscribeToHitTestForTransientInput(profileName, entityTypes, ray){703    if (!this.supportedModes_.includes(device.mojom.XRSessionMode.kImmersiveAr)) {704      // Reject outside of AR.705      return Promise.resolve({706        result : device.mojom.SubscribeToHitTestResult.FAILURE_GENERIC,707        subscriptionId : 0708      });709    }710    const id = this.next_hit_test_id_++;711    const hitTestParameters = { isTransient: true, profileName: profileName };712    const controller = new FakeXRHitTestSourceController(id);713    // Check if we have hit test source creation callback.714    // If yes, ask it if the hit test source creation should succeed.715    // If no, for back-compat, assume the hit test source creation succeeded.716    return this._shouldHitTestSourceCreationSucceed(hitTestParameters, controller)717      .then((succeeded) => {718        if(succeeded) {719          // Store the subscription information as-is (including controller):720          this.transientHitTestSubscriptions_.set(id, { profileName, entityTypes, ray, controller });721          return Promise.resolve({722            result : device.mojom.SubscribeToHitTestResult.SUCCESS,723            subscriptionId : id724          });725        } else {726          return Promise.resolve({727            result : device.mojom.SubscribeToHitTestResult.FAILURE_GENERIC,728            subscriptionId : 0729          });730        }731      });732  }733  unsubscribeFromHitTest(subscriptionId) {734    let controller = null;735    if(this.transientHitTestSubscriptions_.has(subscriptionId)){736      controller = this.transientHitTestSubscriptions_.get(subscriptionId).controller;737      this.transientHitTestSubscriptions_.delete(subscriptionId);738    } else if(this.hitTestSubscriptions_.has(subscriptionId)){739      controller = this.hitTestSubscriptions_.get(subscriptionId).controller;740      this.hitTestSubscriptions_.delete(subscriptionId);741    }742    if(controller) {743      controller.deleted = true;744    }745  }746  createAnchor(nativeOriginInformation, nativeOriginFromAnchor) {747    return new Promise((resolve) => {748      if(this.anchor_creation_callback_ == null) {749        resolve({750          result : device.mojom.CreateAnchorResult.FAILURE,751          anchorId : 0752        });753        return;754      }755      const mojoFromNativeOrigin = this._getMojoFromNativeOrigin(nativeOriginInformation);756      if(mojoFromNativeOrigin == null) {757        resolve({758          result : device.mojom.CreateAnchorResult.FAILURE,759          anchorId : 0760        });761        return;762      }763      const mojoFromAnchor = XRMathHelper.mul4x4(mojoFromNativeOrigin, nativeOriginFromAnchor);764      const anchorCreationParameters = {765        requestedAnchorOrigin: mojoFromAnchor,766        isAttachedToEntity: false,767      };768      const anchorController = new FakeXRAnchorController();769      this.anchor_creation_callback_(anchorCreationParameters, anchorController)770            .then((result) => {771              if(result) {772                // If the test allowed the anchor creation,773                // store the anchor controller & return success.774                const anchor_id = this.next_anchor_id_;775                this.next_anchor_id_++;776                this.anchor_controllers_.set(anchor_id, anchorController);777                anchorController.device = this;778                anchorController.id = anchor_id;779                resolve({780                  result : device.mojom.CreateAnchorResult.SUCCESS,781                  anchorId : anchor_id782                });783              } else {784                // The test has rejected anchor creation.785                resolve({786                  result : device.mojom.CreateAnchorResult.FAILURE,787                  anchorId : 0788                });789              }790            })791            .catch(() => {792              // The test threw an error, treat anchor creation as failed.793              resolve({794                result : device.mojom.CreateAnchorResult.FAILURE,795                anchorId : 0796              });797            });798    });799  }800  createPlaneAnchor(planeFromAnchor, planeId) {801    return new Promise((resolve) => {802      // Not supported yet.803      resolve({804        result : device.mojom.CreateAnchorResult.FAILURE,805        anchorId : 0806      });807    });808  }809  // Utility function810  requestRuntimeSession(sessionOptions) {811    return this.runtimeSupportsSession(sessionOptions).then((result) => {812      // The JavaScript bindings convert c_style_names to camelCase names.813      const options = new device.mojom.XRPresentationTransportOptions();814      options.transportMethod =815          device.mojom.XRPresentationTransportMethod.SUBMIT_AS_MAILBOX_HOLDER;816      options.waitForTransferNotification = true;817      options.waitForRenderNotification = true;818      let submit_frame_sink;819      if (result.supportsSession) {820        submit_frame_sink = {821          clientReceiver: this.presentation_provider_.getClientReceiver(),822          provider: this.presentation_provider_.bindProvider(sessionOptions),823          transportOptions: options824        };825        const dataProviderPtr = new device.mojom.XRFrameDataProviderPtr();826        const dataProviderRequest = mojo.makeRequest(dataProviderPtr);827        this.dataProviderBinding_ = new mojo.Binding(828            device.mojom.XRFrameDataProvider, this, dataProviderRequest);829        this.sessionOptions_ = sessionOptions;830        const clientReceiver = mojo.makeRequest(this.sessionClient_);831        const enabled_features = [];832        for (let i = 0; i < sessionOptions.requiredFeatures.length; i++) {833          if (this.supportedFeatures_.indexOf(sessionOptions.requiredFeatures[i]) !== -1) {834            enabled_features.push(sessionOptions.requiredFeatures[i]);835          } else {836            return Promise.resolve({session: null});837          }838        }839        for (let i =0; i < sessionOptions.optionalFeatures.length; i++) {840          if (this.supportedFeatures_.indexOf(sessionOptions.optionalFeatures[i]) !== -1) {841            enabled_features.push(sessionOptions.optionalFeatures[i]);842          }843        }844        return Promise.resolve({845          session: {846            submitFrameSink: submit_frame_sink,847            dataProvider: dataProviderPtr,848            clientReceiver: clientReceiver,849            displayInfo: this.displayInfo_,850            enabledFeatures: enabled_features,851          }852        });853      } else {854        return Promise.resolve({session: null});855      }856    });857  }858  runtimeSupportsSession(options) {859    return Promise.resolve({860      supportsSession: this.supportedModes_.includes(options.mode)861    });862  }863  // Private functions - utilities:864  _nativeOriginKnown(nativeOriginInformation){865    if (nativeOriginInformation.$tag == device.mojom.XRNativeOriginInformation.Tags.inputSourceId) {866      if (!this.input_sources_.has(nativeOriginInformation.inputSourceId)) {867        // Unknown input source.868        return false;869      }870      return true;871    } else if (nativeOriginInformation.$tag == device.mojom.XRNativeOriginInformation.Tags.referenceSpaceType) {872      // Bounded_floor & unbounded ref spaces are not yet supported for AR:873      if (nativeOriginInformation.referenceSpaceType == device.mojom.XRReferenceSpaceType.kUnbounded874       || nativeOriginInformation.referenceSpaceType == device.mojom.XRReferenceSpaceType.kBoundedFlor) {875        return false;876      }877      return true;878    } else {879      // Planes and anchors are not yet supported by the mock interface.880      return false;881    }882  }883  // Private functions - anchors implementation:884  // Modifies passed in frameData to add anchor information.885  _calculateAnchorInformation(frameData) {886    if (!this.supportedModes_.includes(device.mojom.XRSessionMode.kImmersiveAr)) {887      return;888    }889    frameData.anchorsData = new device.mojom.XRAnchorsData();890    frameData.anchorsData.allAnchorsIds = [];891    frameData.anchorsData.updatedAnchorsData = [];892    for(const [id, controller] of this.anchor_controllers_) {893      frameData.anchorsData.allAnchorsIds.push(id);894      // Send the entire anchor data over if there was a change since last GetFrameData().895      if(controller.dirty) {896        const anchorData = new device.mojom.XRAnchorData();897        anchorData.id = id;898        if(!controller.paused) {899          anchorData.mojoFromAnchor = XRMathHelper.decomposeRigidTransform(900            controller.getAnchorOrigin());901        }902        controller.markProcessed();903        frameData.anchorsData.updatedAnchorsData.push(anchorData);904      }905    }906  }907  // Private functions - hit test implementation:908  // Returns a Promise<bool> that signifies whether hit test source creation should succeed.909  // If we have a hit test source creation callback installed, invoke it and return its result.910  // If it's not installed, for back-compat just return a promise that resolves to true.911  _shouldHitTestSourceCreationSucceed(hitTestParameters, controller) {912    if(this.hit_test_source_creation_callback_) {913      return this.hit_test_source_creation_callback_(hitTestParameters, controller);914    } else {915      return Promise.resolve(true);916    }917  }918  // Modifies passed in frameData to add hit test results.919  _calculateHitTestResults(frameData) {920    if (!this.supportedModes_.includes(device.mojom.XRSessionMode.kImmersiveAr)) {921      return;922    }923    frameData.hitTestSubscriptionResults = new device.mojom.XRHitTestSubscriptionResultsData();924    frameData.hitTestSubscriptionResults.results = [];925    frameData.hitTestSubscriptionResults.transientInputResults = [];...Using AI Code Generation
1function runTest()2{3    if (_shouldHitTestSourceCreationSucceed())4        testPassed("Source creation should succeed");5        testFailed("Source creation should fail");6}7window.jsTestIsAsync = false;8runTest();9> +    if (window.testRunner && window.testRunner.overridePreference)10> +        window.testRunner.overridePreference("WebKitWebGLEnabled", "1"); 11> +    if (window.testRunner && window.testRunner.overridePreference)12> +        window.testRunner.overridePreference("WebKitWebGLEnabled", "1"); Using AI Code Generation
1function testShouldHitTestSourceCreationSucceed() {2    var canvas = document.createElement('canvas');3    var gl = canvas.getContext('webgl');4    var program = gl.createProgram();5    var vs = gl.createShader(gl.VERTEX_SHADER);6    var fs = gl.createShader(gl.FRAGMENT_SHADER);7    gl.shaderSource(vs, 'void main() { gl_Position = vec4(0.0, 0.0, 0.0, 1.0); }');8    gl.shaderSource(fs, 'void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); }');9    gl.compileShader(vs);10    gl.compileShader(fs);11    gl.attachShader(program, vs);12    gl.attachShader(program, fs);13    gl.linkProgram(program);14    var hitTestSource = gl.createHitTestSourceCHROMIUM();15    var hitTestSource2 = gl.createHitTestSourceCHROMIUM();16    var hitTestSource3 = gl.createHitTestSourceCHROMIUM();17    var hitTestSource4 = gl.createHitTestSourceCHROMIUM();18    var hitTestSource5 = gl.createHitTestSourceCHROMIUM();19    var hitTestSource6 = gl.createHitTestSourceCHROMIUM();20    var hitTestSource7 = gl.createHitTestSourceCHROMIUM();21    var hitTestSource8 = gl.createHitTestSourceCHROMIUM();22    var hitTestSource9 = gl.createHitTestSourceCHROMIUM();23    var hitTestSource10 = gl.createHitTestSourceCHROMIUM();24    var hitTestSource11 = gl.createHitTestSourceCHROMIUM();25    var hitTestSource12 = gl.createHitTestSourceCHROMIUM();26    var hitTestSource13 = gl.createHitTestSourceCHROMIUM();27    var hitTestSource14 = gl.createHitTestSourceCHROMIUM();28    var hitTestSource15 = gl.createHitTestSourceCHROMIUM();29    var hitTestSource16 = gl.createHitTestSourceCHROMIUM();30    var hitTestSource17 = gl.createHitTestSourceCHROMIUM();31    var hitTestSource18 = gl.createHitTestSourceCHROMIUM();Using AI Code Generation
1var wpt = require('./wpt');2var result = wpt._shouldHitTestSourceCreationSucceed();3console.log(result);4exports._shouldHitTestSourceCreationSucceed = function() {5  return true;6}7var wpt = require('./wpt');8var result = wpt._shouldHitTestSourceCreationSucceed();9console.log(result);10exports._shouldHitTestSourceCreationSucceed = function() {11  return true;12}13var wpt = require('./wpt');14var result = wpt._shouldHitTestSourceCreationSucceed();15console.log(result);16exports._shouldHitTestSourceCreationSucceed = function() {17  return true;18}Using AI Code Generation
1var wpt = require('./wpt.js');2var assert = require('assert');3var test = function () {4    var wpt = new wpt();5    var expected = true;6    var actual = wpt._shouldHitTestSourceCreationSucceed(source);7    assert.equal(expected, actual);8};9test();10var wpt = function () {11};12wpt.prototype._shouldHitTestSourceCreationSucceed = function (source) {13        return true;14    }15    return false;16};17module.exports = wpt;Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
