How to use relevant_reports method in wpt

Best JavaScript code snippet using wpt

featurepolicy.js

Source:featurepolicy.js Github

copy

Full Screen

1// Feature test to avoid timeouts2function assert_feature_policy_supported() {3 assert_not_equals(document.featurePolicy, undefined,4 'Feature Policy is supported');5}6// Tests whether a feature that is enabled/disabled by feature policy works7// as expected.8// Arguments:9// feature_description: a short string describing what feature is being10// tested. Examples: "usb.GetDevices()", "PaymentRequest()".11// test: test created by testharness. Examples: async_test, promise_test.12// src: URL where a feature's availability is checked. Examples:13// "/feature-policy/resources/feature-policy-payment.html",14// "/feature-policy/resources/feature-policy-usb.html".15// expect_feature_available: a callback(data, feature_description) to16// verify if a feature is available or unavailable as expected.17// The file under the path "src" defines what "data" is sent back as a18// postMessage. Inside the callback, some tests (e.g., EXPECT_EQ,19// EXPECT_TRUE, etc) are run accordingly to test a feature's20// availability.21// Example: expect_feature_available_default(data, feature_description).22// feature_name: Optional argument, only provided when testing iframe allow23// attribute. "feature_name" is the feature name of a policy controlled24// feature (https://wicg.github.io/feature-policy/#features).25// See examples at:26// https://github.com/WICG/feature-policy/blob/master/features.md27// allow_attribute: Optional argument, only used for testing fullscreen:28// "allowfullscreen"29function test_feature_availability(30 feature_description, test, src, expect_feature_available, feature_name,31 allow_attribute) {32 let frame = document.createElement('iframe');33 frame.src = src;34 if (typeof feature_name !== 'undefined') {35 frame.allow = frame.allow.concat(";" + feature_name);36 }37 if (typeof allow_attribute !== 'undefined') {38 frame.setAttribute(allow_attribute, true);39 }40 window.addEventListener('message', test.step_func(function handler(evt) {41 if (evt.source === frame.contentWindow) {42 expect_feature_available(evt.data, feature_description);43 document.body.removeChild(frame);44 window.removeEventListener('message', handler);45 test.done();46 }47 }));48 document.body.appendChild(frame);49}50// Default helper functions to test a feature's availability:51function expect_feature_available_default(data, feature_description) {52 assert_true(data.enabled, feature_description);53}54function expect_feature_unavailable_default(data, feature_description) {55 assert_false(data.enabled, feature_description);56}57// This is the same as test_feature_availability() but instead of passing in a58// function to check the result of the message sent back from an iframe, instead59// just compares the result to an expected result passed in.60// Arguments:61// test: test created by testharness. Examples: async_test, promise_test.62// src: the URL to load in an iframe in which to test the feature.63// expected_result: the expected value to compare to the data passed back64// from the src page by postMessage.65// allow_attribute: Optional argument, only provided when an allow66// attribute should be specified on the iframe.67function test_feature_availability_with_post_message_result(68 test, src, expected_result, allow_attribute) {69 var test_result = function(data, feature_description) {70 assert_equals(data, expected_result);71 };72 test_feature_availability(null, test, src, test_result, allow_attribute);73}74// If this page is intended to test the named feature (according to the URL),75// tests the feature availability and posts the result back to the parent.76// Otherwise, does nothing.77function test_feature_in_iframe(feature_name, feature_promise_factory) {78 if (location.hash.endsWith(`#${feature_name}`)) {79 feature_promise_factory().then(80 () => window.parent.postMessage('#OK', '*'),81 (e) => window.parent.postMessage('#' + e.name, '*'));82 }83}84// Returns true if the URL for this page indicates that it is embedded in an85// iframe.86function page_loaded_in_iframe() {87 return location.hash.startsWith('#iframe');88}89// Returns a same-origin (relative) URL suitable for embedding in an iframe for90// testing the availability of the feature.91function same_origin_url(feature_name) {92 // Append #iframe to the URL so we can detect the iframe'd version of the93 // page.94 return location.pathname + '#iframe#' + feature_name;95}96// Returns a cross-origin (absolute) URL suitable for embedding in an iframe for97// testing the availability of the feature.98function cross_origin_url(base_url, feature_name) {99 return base_url + same_origin_url(feature_name);100}101// This function runs all feature policy tests for a particular feature that102// has a default policy of "self". This includes testing:103// 1. Feature usage succeeds by default in the top level frame.104// 2. Feature usage succeeds by default in a same-origin iframe.105// 3. Feature usage fails by default in a cross-origin iframe.106// 4. Feature usage suceeds when an allow attribute is specified on a107// cross-origin iframe.108//109// The same page which called this function will be loaded in the iframe in110// order to test feature usage there. When this function is called in that111// context it will simply run the feature and return a result back via112// postMessage.113//114// Arguments:115// cross_origin: A cross-origin URL base to be used to load the page which116// called into this function.117// feature_name: The name of the feature as it should be specified in an118// allow attribute.119// error_name: If feature usage does not succeed, this is the string120// representation of the error that will be passed in the rejected121// promise.122// feature_promise_factory: A function which returns a promise which tests123// feature usage. If usage succeeds, the promise should resolve. If it124// fails, the promise should reject with an error that can be125// represented as a string.126function run_all_fp_tests_allow_self(127 cross_origin, feature_name, error_name, feature_promise_factory) {128 // This may be the version of the page loaded up in an iframe. If so, just129 // post the result of running the feature promise back to the parent.130 if (page_loaded_in_iframe()) {131 test_feature_in_iframe(feature_name, feature_promise_factory);132 return;133 }134 // Run the various tests.135 // 1. Allowed in top-level frame.136 promise_test(137 () => feature_promise_factory(),138 'Default "' + feature_name +139 '" feature policy ["self"] allows the top-level document.');140 // 2. Allowed in same-origin iframe.141 const same_origin_frame_pathname = same_origin_url(feature_name);142 async_test(143 t => {144 test_feature_availability_with_post_message_result(145 t, same_origin_frame_pathname, '#OK');146 },147 'Default "' + feature_name +148 '" feature policy ["self"] allows same-origin iframes.');149 // 3. Blocked in cross-origin iframe.150 const cross_origin_frame_url = cross_origin_url(cross_origin, feature_name);151 async_test(152 t => {153 test_feature_availability_with_post_message_result(154 t, cross_origin_frame_url, '#' + error_name);155 },156 'Default "' + feature_name +157 '" feature policy ["self"] disallows cross-origin iframes.');158 // 4. Allowed in cross-origin iframe with "allow" attribute.159 async_test(160 t => {161 test_feature_availability_with_post_message_result(162 t, cross_origin_frame_url, '#OK', feature_name);163 },164 'Feature policy "' + feature_name +165 '" can be enabled in cross-origin iframes using "allow" attribute.');166}167// This function runs all feature policy tests for a particular feature that168// has a default policy of "*". This includes testing:169// 1. Feature usage succeeds by default in the top level frame.170// 2. Feature usage succeeds by default in a same-origin iframe.171// 3. Feature usage succeeds by default in a cross-origin iframe.172// 4. Feature usage fails when an allow attribute is specified on a173// cross-origin iframe with a value of "feature-name 'none'".174//175// The same page which called this function will be loaded in the iframe in176// order to test feature usage there. When this function is called in that177// context it will simply run the feature and return a result back via178// postMessage.179//180// Arguments:181// cross_origin: A cross-origin URL base to be used to load the page which182// called into this function.183// feature_name: The name of the feature as it should be specified in an184// allow attribute.185// error_name: If feature usage does not succeed, this is the string186// representation of the error that will be passed in the rejected187// promise.188// feature_promise_factory: A function which returns a promise which tests189// feature usage. If usage succeeds, the promise should resolve. If it190// fails, the promise should reject with an error that can be191// represented as a string.192function run_all_fp_tests_allow_all(193 cross_origin, feature_name, error_name, feature_promise_factory) {194 // This may be the version of the page loaded up in an iframe. If so, just195 // post the result of running the feature promise back to the parent.196 if (page_loaded_in_iframe()) {197 test_feature_in_iframe(feature_name, feature_promise_factory);198 return;199 }200 // Run the various tests.201 // 1. Allowed in top-level frame.202 promise_test(203 () => feature_promise_factory(),204 'Default "' + feature_name +205 '" feature policy ["*"] allows the top-level document.');206 // 2. Allowed in same-origin iframe.207 const same_origin_frame_pathname = same_origin_url(feature_name);208 async_test(209 t => {210 test_feature_availability_with_post_message_result(211 t, same_origin_frame_pathname, '#OK');212 },213 'Default "' + feature_name +214 '" feature policy ["*"] allows same-origin iframes.');215 // 3. Allowed in cross-origin iframe.216 const cross_origin_frame_url = cross_origin_url(cross_origin, feature_name);217 async_test(218 t => {219 test_feature_availability_with_post_message_result(220 t, cross_origin_frame_url, '#OK');221 },222 'Default "' + feature_name +223 '" feature policy ["*"] allows cross-origin iframes.');224 // 4. Blocked in cross-origin iframe with "allow" attribute set to 'none'.225 async_test(226 t => {227 test_feature_availability_with_post_message_result(228 t, cross_origin_frame_url, '#' + error_name,229 feature_name + " 'none'");230 },231 'Feature policy "' + feature_name +232 '" can be disabled in cross-origin iframes using "allow" attribute.');233 // 5. Blocked in same-origin iframe with "allow" attribute set to 'none'.234 async_test(235 t => {236 test_feature_availability_with_post_message_result(237 t, same_origin_frame_pathname, '#' + error_name,238 feature_name + " 'none'");239 },240 'Feature policy "' + feature_name +241 '" can be disabled in same-origin iframes using "allow" attribute.');242}243// This function tests that a given policy allows each feature for the correct244// list of origins specified by the |expected_policy|.245// Arguments:246// expected_policy: A list of {feature, allowlist} pairs where the feature is247// enabled for every origin in the allowlist, in the |policy|.248// policy: Either a document.featurePolicy or an iframe.featurePolicy to be249// tested.250// message: A short description of what policy is being tested.251function test_allowlists(expected_policy, policy, message) {252 for (var allowlist of allowlists) {253 test(function() {254 assert_array_equals(255 policy.getAllowlistForFeature(allowlist.feature),256 allowlist.allowlist);257 }, message + ' for feature ' + allowlist.feature);258 }259}260// This function tests that a subframe's document policy allows a given feature.261// A feature is allowed in a frame either through inherited policy or specified262// by iframe allow attribute.263// Arguments:264// test: test created by testharness. Examples: async_test, promise_test.265// feature: feature name that should be allowed in the frame.266// src: the URL to load in the frame.267// allow: the allow attribute (container policy) of the iframe268function test_allowed_feature_for_subframe(message, feature, src, allow) {269 let frame = document.createElement('iframe');270 if (typeof allow !== 'undefined') {271 frame.allow = allow;272 }273 promise_test(function() {274 assert_feature_policy_supported();275 frame.src = src;276 return new Promise(function(resolve, reject) {277 window.addEventListener('message', function handler(evt) {278 resolve(evt.data);279 }, { once: true });280 document.body.appendChild(frame);281 }).then(function(data) {282 assert_true(data.includes(feature), feature);283 });284 }, message);285}286// This function tests that a subframe's document policy disallows a given287// feature. A feature is allowed in a frame either through inherited policy or288// specified by iframe allow attribute.289// Arguments:290// test: test created by testharness. Examples: async_test, promise_test.291// feature: feature name that should not be allowed in the frame.292// src: the URL to load in the frame.293// allow: the allow attribute (container policy) of the iframe294function test_disallowed_feature_for_subframe(message, feature, src, allow) {295 let frame = document.createElement('iframe');296 if (typeof allow !== 'undefined') {297 frame.allow = allow;298 }299 promise_test(function() {300 assert_feature_policy_supported();301 frame.src = src;302 return new Promise(function(resolve, reject) {303 window.addEventListener('message', function handler(evt) {304 resolve(evt.data);305 }, { once: true });306 document.body.appendChild(frame);307 }).then(function(data) {308 assert_false(data.includes(feature), feature);309 });310 }, message);311}312// This function tests that a subframe with header policy defined on a given313// feature allows and disallows the feature as expected.314// Arguments:315// feature: feature name.316// frame_header_policy: either *, 'self' or 'none', defines the frame317// document's header policy on |feature|.318// src: the URL to load in the frame.319// test_expects: contains 6 expected results of either |feature| is allowed320// or not inside of a local or remote iframe nested inside321// the subframe given the header policy to be either *,322// 'slef', or 'none'.323// test_name: name of the test.324function test_subframe_header_policy(325 feature, frame_header_policy, src, test_expects, test_name) {326 let frame = document.createElement('iframe');327 promise_test(function() {328 assert_feature_policy_supported()329 frame.src = src + '?pipe=sub|header(Feature-Policy,' + feature + ' '330 + frame_header_policy + ';)';331 return new Promise(function(resolve) {332 window.addEventListener('message', function handler(evt) {333 resolve(evt.data);334 });335 document.body.appendChild(frame);336 }).then(function(results) {337 for (var j = 0; j < results.length; j++) {338 var data = results[j];339 function test_result(message, test_expect) {340 if (test_expect) {341 assert_true(data.allowedfeatures.includes(feature), message);342 } else {343 assert_false(data.allowedfeatures.includes(feature), message);344 }345 }346 if (data.frame === 'local') {347 if (data.policy === '*') {348 test_result('local_all:', test_expects.local_all);349 }350 if (data.policy === '\'self\'') {351 test_result('local_self:', test_expects.local_self);352 }353 if (data.policy === '\'none\'') {354 test_result('local_none:', test_expects.local_none);355 }356 }357 if (data.frame === 'remote') {358 if (data.policy === '*') {359 test_result('remote_all:', test_expects.remote_all);360 }361 if (data.policy === '\'self\'') {362 test_result('remote_self:', test_expects.remote_self);363 }364 if (data.policy === '\'none\'') {365 test_result('remote_none:', test_expects.remote_none);366 }367 }368 }369 });370 }, test_name);371}372// This function tests that frame policy allows a given feature correctly. A373// feature is allowed in a frame either through inherited policy or specified374// by iframe allow attribute.375// Arguments:376// feature: feature name.377// src: the URL to load in the frame. If undefined, the iframe will have a378// srcdoc="" attribute379// test_expect: boolean value of whether the feature should be allowed.380// allow: optional, the allow attribute (container policy) of the iframe.381// allowfullscreen: optional, boolean value of allowfullscreen attribute.382// sandbox: optional boolean. If true, the frame will be sandboxed (with383// allow-scripts, so that tests can run in it.)384function test_frame_policy(385 feature, src, srcdoc, test_expect, allow, allowfullscreen, sandbox) {386 let frame = document.createElement('iframe');387 document.body.appendChild(frame);388 // frame_policy should be dynamically updated as allow and allowfullscreen is389 // updated.390 var frame_policy = frame.featurePolicy;391 if (typeof allow !== 'undefined') {392 frame.setAttribute('allow', allow);393 }394 if (!!allowfullscreen) {395 frame.setAttribute('allowfullscreen', true);396 }397 if (!!sandbox) {398 frame.setAttribute('sandbox', 'allow-scripts');399 }400 if (!!src) {401 frame.src = src;402 }403 if (!!srcdoc) {404 frame.srcdoc = "<h1>Hello world!</h1>";405 }406 if (test_expect) {407 assert_true(frame_policy.allowedFeatures().includes(feature));408 } else {409 assert_false(frame_policy.allowedFeatures().includes(feature));410 }411}412function expect_reports(report_count, policy_name, description) {413 async_test(t => {414 var num_received_reports = 0;415 new ReportingObserver(t.step_func((reports, observer) => {416 const relevant_reports = reports.filter(r => (r.body.featureId === policy_name));417 num_received_reports += relevant_reports.length;418 if (num_received_reports >= report_count) {419 t.done();420 }421 }), {types: ['permissions-policy-violation'], buffered: true}).observe();422 }, description);...

Full Screen

Full Screen

routes.js

Source:routes.js Github

copy

Full Screen

1angular.module('Aggie')2.config([3 '$stateProvider',4 function($stateProvider) {5 var lastAnalysis;6 $stateProvider.state('home', {7 url: '/',8 onEnter: function($state) {9 $state.go('reports');10 },11 data: {12 public: true13 }14 });15 $stateProvider.state('profile', {16 url: '/profile/:userName',17 templateUrl: '/templates/users/profile.html',18 controller: 'UsersProfileController',19 resolve: {20 users: ['User', function(User) {21 return User.query().$promise;22 }]23 }24 });25 $stateProvider.state('login', {26 url: '/login',27 templateUrl: '/templates/login.html',28 controller: 'LoginController',29 data: {30 public: true31 }32 });33 $stateProvider.state('reset_admin_password', {34 url: '/reset_admin_password',35 templateUrl: '/templates/reset-admin-password.html',36 controller: 'ResetAdminPasswordController'37 });38 $stateProvider.state('reports', {39 url: '/reports?keywords&page&before&after&sourceId&status&media&incidentId&author&tags&list',40 templateUrl: '/templates/reports/index.html',41 controller: 'ReportsIndexController',42 resolve: {43 reports: ['Report', '$stateParams', function(Report, params) {44 var page = params.page || 1;45 return Report.query({46 page: page - 1,47 keywords: params.keywords,48 after: params.after,49 before: params.before,50 sourceId: params.sourceId,51 media: params.media,52 incidentId: params.incidentId,53 status: params.status,54 author: params.author,55 tags: params.tags,56 list: params.list,57 isRelevantReports: false,58 }).$promise;59 }],60 ctLists: ['CTLists', function(CTLists) {61 return CTLists.get().$promise;62 }],63 sources: ['Source', function(Source) {64 return Source.query().$promise;65 }],66 incidents: ['Incident', function(Incident) {67 return Incident.query().$promise;68 }],69 smtcTags: ['SMTCTag', function(SMTCTag) {70 return SMTCTag.query().$promise;71 }]72 }73 });74 $stateProvider.state('relevant_reports', {75 url: '/relevant_reports?keywords&page&before&after&sourceId&status&media&incidentId&author&tags&list&escalated&veracity',76 templateUrl: '/templates/reports/relevant_reports.html',77 controller: 'RelevantReportsIndexController',78 resolve: {79 reports: ['Report', '$stateParams', function(Report, params) {80 var page = params.page || 1;81 return Report.query({82 page: page - 1,83 keywords: params.keywords,84 after: params.after,85 before: params.before,86 sourceId: params.sourceId,87 media: params.media,88 incidentId: params.incidentId,89 status: params.status,90 author: params.author,91 tags: params.tags,92 list: params.list,93 escalated: params.escalated,94 veracity: params.veracity,95 isRelevantReports: true,96 }).$promise;97 }],98 ctLists: ['CTLists', function(CTLists) {99 return CTLists.get().$promise;100 }],101 sources: ['Source', function(Source) {102 return Source.query().$promise;103 }],104 incidents: ['Incident', function(Incident) {105 return Incident.query().$promise;106 }],107 smtcTags: ['SMTCTag', function(SMTCTag) {108 return SMTCTag.query().$promise;109 }]110 }111 });112 $stateProvider.state('batch', {113 url: '/reports/batch?keywords&before&after&sourceId&status&media&incidentId&author&tags&list',114 templateUrl: '/templates/reports/batch.html',115 controller: 'ReportsIndexController',116 resolve: {117 reports: ['Batch', function(Batch) {118 if (Batch.resource) return Batch.resource;119 return Batch.load({}).$promise;120 }],121 sources: ['Source', function(Source) {122 return Source.query().$promise;123 }],124 incidents: ['Incident', function(Incident) {125 return Incident.query().$promise;126 }],127 smtcTags: ['SMTCTag', function(SMTCTag) {128 return SMTCTag.query().$promise;129 }],130 ctLists: ['CTLists', function(CTLists) {131 return CTLists.get().$promise;132 }],133 },134 });135 $stateProvider.state('report', {136 url: '/reports/:id?page',137 templateUrl: '/templates/reports/show.html',138 controller: 'ReportsShowController',139 resolve: {140 data: ['$stateParams', '$q', 'Report', 'Source', function($stateParams, $q, Report, Source) {141 var deferred = $q.defer();142 Report.get({ id: $stateParams.id }, function(report) {143 report.content = Autolinker.link(report.content);144 var data = { report: report };145 var sourcePromises = report._sources.map(function(sourceId) {146 var promise = $q.defer();147 Source.get({ id: sourceId }, function(source) {148 promise.resolve(source);149 });150 return promise.promise;151 });152 $q.all(sourcePromises).then(function(sources) {153 data.sources = sources;154 deferred.resolve(data);155 });156 });157 return deferred.promise;158 }],159 comments: ['Report', '$stateParams', function(Report, params) {160 var page = params.page || 1;161 return Report.queryComments({162 id: params.id,163 page: page - 1,164 }).$promise;165 }],166 incidents: ['Incident', function(Incident) {167 return Incident.query().$promise;168 }],169 smtcTags: ['SMTCTag', function(SMTCTag) {170 return SMTCTag.query().$promise;171 }],172 sources: ['Source', function(Source) {173 return Source.query().$promise;174 }],175 }176 });177 $stateProvider.state('incidents', {178 url: '/incidents?page&title&locationName&assignedTo&status&veracity&tags&escalated&public&before&after&idnum&creator',179 templateUrl: '/templates/incidents/index.html',180 controller: 'IncidentsIndexController',181 resolve: {182 incidents: ['Incident', '$stateParams', function(Incident, params) {183 var page = params.page || 1;184 return Incident.query({185 page: page - 1,186 title: params.title,187 locationName: params.locationName,188 assignedTo: params.assignedTo,189 status: params.status,190 veracity: params.veracity,191 tags: params.tags,192 escalated: params.escalated,193 public: params.public,194 after: params.after,195 before: params.before,196 idnum: (params.idnum == null) ? params.idnum: params.idnum -1,197 creator: params.creator,198 }).$promise;199 }],200 users: ['User', function(User) {201 return User.query().$promise;202 }],203 smtcTags: ['SMTCTag', function(SMTCTag) {204 return SMTCTag.query().$promise;205 }]206 }207 });208 $stateProvider.state('incident', {209 url: '/incidents/:id?page',210 templateUrl: '/templates/incidents/show.html',211 controller: 'IncidentsShowController',212 resolve: {213 incident: ['Incident', '$stateParams', function(Incident, params) {214 return Incident.get({ id: params.id }).$promise;215 }],216 reports: ['Report', '$stateParams', function(Report, params) {217 var page = params.page || 1;218 return Report.query({219 incidentId: params.id,220 page: page - 1221 }).$promise;222 }],223 sources: ['Source', function(Source) {224 return Source.query().$promise;225 }],226 smtcTags: ['SMTCTag', function(SMTCTag) {227 return SMTCTag.query().$promise;228 }]229 }230 });231 $stateProvider.state('credentials', {232 url: '/credentials',233 templateUrl: '/templates/credentials/index.html',234 controller: 'CredentialsIndexController',235 resolve: {236 credentials: ['Credentials', function(Credentials) {237 return Credentials.query().$promise;238 }]239 }240 });241 $stateProvider.state('credential', {242 url: '/credentials/:id',243 templateUrl: '/templates/credentials/show.html',244 controller: 'CredentialsShowController',245 resolve: {246 credentials: ['Credentials', '$stateParams', function(Credentials, params) {247 return Credentials.get({ id: params.id }).$promise;248 }],249 sources: ['Source', function(Source) {250 return Source.query().$promise;251 }],252 }253 });254 $stateProvider.state('sources', {255 url: '/sources',256 templateUrl: '/templates/sources/index.html',257 controller: 'SourcesIndexController',258 resolve: {259 sources: ['Source', function(Source) {260 return Source.query().$promise;261 }],262 }263 });264 $stateProvider.state('source', {265 url: '/sources/:id',266 templateUrl: '/templates/sources/show.html',267 controller: 'SourcesShowController',268 resolve: {269 source: ['Source', '$stateParams', function(Source, params) {270 return Source.get({ id: params.id }).$promise;271 }],272 }273 });274 $stateProvider.state('users', {275 url: '/users',276 templateUrl: '/templates/users/index.html',277 controller: 'UsersIndexController',278 resolve: {279 users: ['User', function(User) {280 return User.query().$promise;281 }]282 }283 });284 $stateProvider.state('tags', {285 url: '/tags',286 templateUrl: '/templates/tags/index.html',287 controller: 'TagsIndexController',288 resolve: {289 smtcTags: ['SMTCTag', function(SMTCTag) {290 return SMTCTag.query().$promise;291 }]292 }293 });294 $stateProvider.state("analysis", {295 url: "/analysis",296 templateUrl: "/templates/analysis/index.html",297 controller: "AnalysisController",298 resolve: {299 data: [300 "Visualization",301 function (Visualization) {302 return Visualization.get().$promise;303 },304 ],305 },306 });307 $stateProvider.state('lastAnalysis', {308 onEnter: function($state) {309 if (!lastAnalysis) {310 lastAnalysis = 'analysis.trend-lines';311 }312 $state.go(lastAnalysis);313 }314 });315 $stateProvider.state('analysis.trend-lines', {316 url: '/trend-lines',317 templateUrl: '/templates/trends/lines.html',318 controller: 'TrendsLinesController',319 onEnter: function($state) {320 lastAnalysis = 'analysis.trend-lines';321 },322 resolve: {323 sources: ['Source', function(Source) {324 return Source.query().$promise;325 }],326 incidents: ['Incident', function(Incident) {327 return Incident.query().$promise;328 }],329 trends: ['Trend', function(Trend) {330 return Trend.query().$promise;331 }]332 }333 });334 $stateProvider.state('analysis.trend-bars', {335 url: '/trend-bars',336 templateUrl: '/templates/trends/bars.html',337 controller: 'TrendsBarsController',338 onEnter: function($state) {339 lastAnalysis = 'analysis.trend-bars';340 },341 resolve: {342 sources: ['Source', function(Source) {343 return Source.query().$promise;344 }],345 incidents: ['Incident', function(Incident) {346 return Incident.query().$promise;347 }],348 trends: ['Trend', function(Trend) {349 return Trend.query().$promise;350 }]351 }352 });353 $stateProvider.state('analysis.incidentsMap', {354 url: '/incidents-map',355 onEnter: function($state) {356 lastAnalysis = 'analysis.incidentsMap';357 },358 templateUrl: '/templates/incidents/map.html',359 controller: 'IncidentsMapController',360 resolve: {361 incidents: ['Incident', function(Incident) {362 return Incident.query().$promise;363 }]364 }365 });366 $stateProvider.state('config', {367 url: '/config',368 templateUrl: '/templates/config.html',369 controller: 'SettingsController'370 });371 $stateProvider.state('password_reset', {372 url: '/password_reset/:token',373 templateUrl: '/templates/password_reset.html',374 controller: 'PasswordResetController',375 data: {376 public: true377 }378 });379 $stateProvider.state('choose_password', {380 url: '/choose_password/:token',381 templateUrl: '/templates/choose_password.html',382 controller: 'ChoosePasswordController',383 data: {384 public: true385 }386 });387 $stateProvider.state('404', {388 url: '/404',389 templateUrl: '/templates/404.html',390 data: {391 public: true392 }393 });394 }...

Full Screen

Full Screen

ReportlistScreen.js

Source:ReportlistScreen.js Github

copy

Full Screen

1import React, { useEffect, useState } from "react";2import { StyleSheet, View, ScrollView, RefreshControl} from "react-native";3import { useNavigation } from "@react-navigation/native";4import { useNetInfo } from "@react-native-community/netinfo";5import AppActivityIndicator from "../components/AppActivityIndicator";6import { appColors } from "../config";7import AppButton from "../components/AppButton";8import AppText from "../components/AppText";9import cache from "../utility/cache";10import reportAPI from "../api/reports";11import ReportItem from "../components/ReportItem";12import { useApi } from "../hooks";13import useAuth from "../auth/useAuth";14 /**15 * Function that renders tthe scrollview with all performed follow-up trips16 * @returns {View} View containing all content to be rendered17 */18const ReportlistScreen = () => {19 const navigation = useNavigation();20 const [refreshing, serRefreshing] = useState(false); 21 const [renderNum, setRenderNum] = useState(2);22 const [notsynced, setNotsynced] = useState();23 const netInfo = useNetInfo();24 const {user} = useAuth();25 const getReports = useApi(reportAPI.getAllData);26 const postReports = useApi(reportAPI.postReport);27/**28 * Function that runs upon view load and runs refresh and sync function29 * @returns {Void}30 */31 useEffect( () => {32 refreshAndSync();33 }, []);34 35/**36 * Function that uploads images if they are not in synch with database37 * @returns {Void}38 */39 const uploadImage = async (reportsNotInSync) => {40 reportsNotInSync.forEach( r => {41 r.markers.forEach( m => {42 if(m.photos){43 m.photos.forEach( async (p) => {44 let base64Img = `data:image/jpg;base64,${p.base64}`;45 let apiUrl =46 'https://api.cloudinary.com/v1_1/dlpfyaci8/image/upload';47 let data = {48 file: base64Img,49 upload_preset: 'myUploadPreset'50 };51 let response = await fetch(apiUrl, {52 body: JSON.stringify(data),53 headers: {54 'content-type': 'application/json'55 },56 method: 'POST'57 });58 let response_data = await response.json();59 if(response_data.secure_url){60 console.log(response_data.secure_url);61 p["url"] = response_data.secure_url62 }63 else{64 console.log(response_data);65 }66 })67 }68 })69 });70 }71 /**72 * Syncing the data in cache with thte data in db if internet concection. Triggerd on swipe-down gesture73 * @returns {Void}74 */75 const refreshAndSync = async () => {76 console.log("Refeshing and syncing..")77 const reportsNotInSync = await cache.syncWithDb();78 const noInternet = netInfo.type !== "unknown" && netInfo.isInternetReachable === false;79 if(reportsNotInSync && !noInternet){80 await uploadImage(reportsNotInSync);81 await postReports.request(reportsNotInSync, false);82 }83 await getReports.request(user.userId, noInternet);84 }85 /**86 * Function that returs the performed follow-up trips in a an array if any87 * @returns {array} Returns as list of all performed follow-trips if any88 */89 const renderReports = () => {90 if(getReports.data){91 let relevant_reports = getReports.data.slice(0, renderNum);92 relevant_reports.forEach( r => r["id"] = Math.floor(Math.random() * 13003))93 return getReports.data.slice(0, renderNum).map((report) => (94 <ReportItem95 key={report.id}96 item={report}97 onPress={() => {navigation.navigate("Report", { item: report })}}98 />99 ));100 }101 }102 return (103 <View style={{flex: 1}}>104 {notsynced && <AppText text={notsynced.starttime} />}105 {getReports.error && (106 <View style={styles.errorView}>107 <AppText108 style={styles.errorTextStyle}109 text="Coudn't retrive reports.."110 />111 <AppButton112 buttonStyle={styles.errorButton}113 onPress={() => refreshAndSync()}114 buttonText="Reload"115 textColor={appColors.secondaryLight}116 textSize={24}117 />118 </View>119 )}120 <AppActivityIndicator visible={getReports.loading} />121 <ScrollView122 alwaysBounceVertical123 refreshControl={124 <RefreshControl125 refreshing={refreshing}126 onRefresh={() => refreshAndSync()}127 />128 }129 >130 {renderReports()}131 {getReports.data.length === 0 &&(132 <View style={styles.errorView}>133 <AppText134 style={styles.errorTextStyle}135 text="Create your first report by clicking the pluss button below"136 />137 </View> 138 )}139 {getReports.data.slice(0, renderNum).length < getReports.data.length && <View style={{alignItems:"center", paddingBottom: 64}}>140 <AppButton textColor={appColors.primary} buttonStyle={styles.loadMoreButton} buttonText="Vis mer" onPress={() => setRenderNum(renderNum + 2)}/>141 </View>}142 </ScrollView>143 </View>144 );145}146const styles = StyleSheet.create({147 errorTextStyle: {148 fontSize: 32,149 fontStyle: "italic",150 color: appColors.gray600,151 marginBottom: 16,152 textAlign: "center",153 },154 errorView: {155 height: "100%",156 justifyContent: "center",157 alignItems: "center",158 padding: 16,159 },160 loadMoreButton:{161 top: 16,162 backgroundColor: appColors.transparent,163 borderColor: appColors.transparent,164 elevation: 0,165 height: 40166 }167});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');3wpt.getLocations(function(err, data) {4 if (!err) {5 console.log(data);6 }7});8var wpt = require('webpagetest');9var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');10 if (!err) {11 console.log(data);12 }13});14var wpt = require('webpagetest');15var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');16 if (!err) {17 console.log(data);18 }19});20var wpt = require('webpagetest');21var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');22var options = {23 videoParams: {24 },

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptreport = require('wptreport');2console.log(report);3var wptreport = require('wptreport');4 if (err) {5 console.log(err);6 }7 else {8 console.log(data);9 }10});11var wptreport = require('wptreport');12 if (err) {13 console.log(err);14 }15 else {16 console.log(data);17 }18});19var wptreport = require('wptreport');20 if (err) {21 console.log(err);22 }23 else {24 console.log(data);25 }26});27var wptreport = require('wptreport');28 if (err) {29 console.log(err);30 }31 else {32 console.log(data);33 }34});35var wptreport = require('wptreport');36 if (err) {37 console.log(err);38 }39 else {40 console.log(data);41 }42});43var wptreport = require('wptreport');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptreport = require('wptreport');2wptreport.relevant_reports(url, function(err, reports) {3 if (err) {4 console.log(err);5 } else {6 reports.forEach(function(report) {7 wptreport.get_report(report, function(err, report) {8 if (err) {9 console.log(err);10 } else {11 console.log(report);12 }13 });14 });15 }16});17 { loadTime: 1533,

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.6d3c0f1b9e2b8f3b6e0b6e3c0f1b9e2b');3var testId = "160516_4N_8d1e6e2f6e7b6d8e8d1e6e2f6e7b6d8e";4var options = {5 videoParams: {6 }7};8wpt.relevantReports(testId, function (err, data) {9 console.log(data);10});11{ statusCode: 400,12 data: 'Invalid test ID' }

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful