From a3ec842e3f04a1789099123129943a84f06e363f Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Wed, 13 Dec 2023 13:59:42 +0200 Subject: [PATCH 01/10] Add JS linter --- .eslintrc | 3 ++ package-lock.json | 93 ++++++++++++++++++++++++----------------------- package.json | 8 ++-- 3 files changed, 55 insertions(+), 49 deletions(-) create mode 100644 .eslintrc diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000..4bf99f7f --- /dev/null +++ b/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": [ "plugin:@wordpress/eslint-plugin/recommended" ] +} diff --git a/package-lock.json b/package-lock.json index 8f157270..fec502c5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "@babel/preset-react": "^7.22.3", "@floating-ui/dom": "^1.2.9", "@wordpress/env": "*", + "@wordpress/eslint-plugin": "^17.5.0", "@wordpress/scripts": "^26.5.0", "axe-core": "^4.7.2", "babel-loader": "^9.1.2", @@ -4853,9 +4854,9 @@ } }, "node_modules/@wordpress/babel-plugin-import-jsx-pragma": { - "version": "4.30.0", - "resolved": "https://registry.npmjs.org/@wordpress/babel-plugin-import-jsx-pragma/-/babel-plugin-import-jsx-pragma-4.30.0.tgz", - "integrity": "sha512-UKkyFmEYk1UTO0ZPun6Kw5dNflTEDpDK/6RxAqxbVrsIWUVSkVahwBnqfS0v5LuvVU8y+5vJSR/WjlnKEmS3Sg==", + "version": "4.31.0", + "resolved": "https://registry.npmjs.org/@wordpress/babel-plugin-import-jsx-pragma/-/babel-plugin-import-jsx-pragma-4.31.0.tgz", + "integrity": "sha512-WlHCRCLBft3bSqE7FLB09w1gHG6QUQ7WAQpSDdcn6wRuLX45ZeMeT6YDqUdJdlYPRBx6Ke9WzrmAT7PrGLZi1Q==", "dev": true, "engines": { "node": ">=14" @@ -4865,9 +4866,9 @@ } }, "node_modules/@wordpress/babel-preset-default": { - "version": "7.31.0", - "resolved": "https://registry.npmjs.org/@wordpress/babel-preset-default/-/babel-preset-default-7.31.0.tgz", - "integrity": "sha512-LAiTOlolFvKW6xmL6qRkdbPG09LPwAsmDepz4zWrFXJZHSImDeO2QXHecF1GnFyzLLKr1myHR5MbN3K5MSzpqQ==", + "version": "7.32.0", + "resolved": "https://registry.npmjs.org/@wordpress/babel-preset-default/-/babel-preset-default-7.32.0.tgz", + "integrity": "sha512-B1S+JujsX3kZWp1jnSuvUu+hlJhp9j1TSlOmar+yuVCjH0vx/aW/58onKvCFNPTy3gJ00bSsYa3BctoCHs456A==", "dev": true, "dependencies": { "@babel/core": "^7.16.0", @@ -4876,9 +4877,9 @@ "@babel/preset-env": "^7.16.0", "@babel/preset-typescript": "^7.16.0", "@babel/runtime": "^7.16.0", - "@wordpress/babel-plugin-import-jsx-pragma": "^4.30.0", - "@wordpress/browserslist-config": "^5.30.0", - "@wordpress/warning": "^2.47.0", + "@wordpress/babel-plugin-import-jsx-pragma": "^4.31.0", + "@wordpress/browserslist-config": "^5.31.0", + "@wordpress/warning": "^2.48.0", "browserslist": "^4.21.10", "core-js": "^3.31.0", "react": "^18.2.0" @@ -4894,9 +4895,9 @@ "dev": true }, "node_modules/@wordpress/browserslist-config": { - "version": "5.30.0", - "resolved": "https://registry.npmjs.org/@wordpress/browserslist-config/-/browserslist-config-5.30.0.tgz", - "integrity": "sha512-HFgLCkvvxba+j7/qNjVn1od38tvMm1xVlIJBR+zukkTvvLu/AkdelWKAQpvAoFAXMaZJ7239VxDVBYbVolf6FQ==", + "version": "5.31.0", + "resolved": "https://registry.npmjs.org/@wordpress/browserslist-config/-/browserslist-config-5.31.0.tgz", + "integrity": "sha512-fjglKNuqMKfGXrxuqea8ndTLkga9MfnyBBYuniGZ7cQo3iOhOn6ZqlfKygZdAuZ19FOwQWaQ+9W9MpOtU/4oCA==", "dev": true, "engines": { "node": ">=14" @@ -5035,16 +5036,16 @@ } }, "node_modules/@wordpress/eslint-plugin": { - "version": "17.4.0", - "resolved": "https://registry.npmjs.org/@wordpress/eslint-plugin/-/eslint-plugin-17.4.0.tgz", - "integrity": "sha512-CT19Ib1Y0ttVQm/bOtjGP6Ge5eqfEaUSobTqCWreHt1RIoxJXTDmazJ1g0Q5MjqG4dEZ/Q/FI4sdqyiKRySkbQ==", + "version": "17.5.0", + "resolved": "https://registry.npmjs.org/@wordpress/eslint-plugin/-/eslint-plugin-17.5.0.tgz", + "integrity": "sha512-wwg4NTMSdiDbkJCFNirn1Oq+Q6wKKWXXmuhsRvK4KsIkayqHavmebnE9bctAiz4ZXI5+URpj8w/IdxYev8acYw==", "dev": true, "dependencies": { "@babel/eslint-parser": "^7.16.0", "@typescript-eslint/eslint-plugin": "^6.4.1", "@typescript-eslint/parser": "^6.4.1", - "@wordpress/babel-preset-default": "^7.31.0", - "@wordpress/prettier-config": "^3.4.0", + "@wordpress/babel-preset-default": "^7.32.0", + "@wordpress/prettier-config": "^3.5.0", "cosmiconfig": "^7.0.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-import": "^2.25.2", @@ -5237,9 +5238,9 @@ } }, "node_modules/@wordpress/prettier-config": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/@wordpress/prettier-config/-/prettier-config-3.4.0.tgz", - "integrity": "sha512-6qawlZqqbe6NDY0txzsPZThRFAXzf0a891wI/A4KNWVKUXQwTluXWMtGZx3xlFtvkX+9ZHdoqXbWysGQztiBOQ==", + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/@wordpress/prettier-config/-/prettier-config-3.5.0.tgz", + "integrity": "sha512-Nzp6TWu+nx1fzgqqa34/MdBiRDT/Yoqo8jFHBrYhx1kV3BPg8m5lvyGxNmzqoR3hZQatGkBJYdFlLs0WeAGGDQ==", "dev": true, "engines": { "node": ">=14" @@ -5613,9 +5614,9 @@ } }, "node_modules/@wordpress/warning": { - "version": "2.47.0", - "resolved": "https://registry.npmjs.org/@wordpress/warning/-/warning-2.47.0.tgz", - "integrity": "sha512-lmpLNI8Si7HrSY0LBBtp7Z6NzAkh1y7yeJI0LZw17EsJ0MM5FSXqXJRrNY7L4tM8G/vv3OacUw1mRAZX7bzBRQ==", + "version": "2.48.0", + "resolved": "https://registry.npmjs.org/@wordpress/warning/-/warning-2.48.0.tgz", + "integrity": "sha512-M8KB8OdxHHxLDPy/1DuSi4SKYrR4/LL2jLWS9GkTa0eSe7PKxIscXH3Q0giFwcREkz80J0rFuADCInCuyIr5Kg==", "dev": true, "engines": { "node": ">=12" @@ -27394,16 +27395,16 @@ } }, "@wordpress/babel-plugin-import-jsx-pragma": { - "version": "4.30.0", - "resolved": "https://registry.npmjs.org/@wordpress/babel-plugin-import-jsx-pragma/-/babel-plugin-import-jsx-pragma-4.30.0.tgz", - "integrity": "sha512-UKkyFmEYk1UTO0ZPun6Kw5dNflTEDpDK/6RxAqxbVrsIWUVSkVahwBnqfS0v5LuvVU8y+5vJSR/WjlnKEmS3Sg==", + "version": "4.31.0", + "resolved": "https://registry.npmjs.org/@wordpress/babel-plugin-import-jsx-pragma/-/babel-plugin-import-jsx-pragma-4.31.0.tgz", + "integrity": "sha512-WlHCRCLBft3bSqE7FLB09w1gHG6QUQ7WAQpSDdcn6wRuLX45ZeMeT6YDqUdJdlYPRBx6Ke9WzrmAT7PrGLZi1Q==", "dev": true, "requires": {} }, "@wordpress/babel-preset-default": { - "version": "7.31.0", - "resolved": "https://registry.npmjs.org/@wordpress/babel-preset-default/-/babel-preset-default-7.31.0.tgz", - "integrity": "sha512-LAiTOlolFvKW6xmL6qRkdbPG09LPwAsmDepz4zWrFXJZHSImDeO2QXHecF1GnFyzLLKr1myHR5MbN3K5MSzpqQ==", + "version": "7.32.0", + "resolved": "https://registry.npmjs.org/@wordpress/babel-preset-default/-/babel-preset-default-7.32.0.tgz", + "integrity": "sha512-B1S+JujsX3kZWp1jnSuvUu+hlJhp9j1TSlOmar+yuVCjH0vx/aW/58onKvCFNPTy3gJ00bSsYa3BctoCHs456A==", "dev": true, "requires": { "@babel/core": "^7.16.0", @@ -27412,9 +27413,9 @@ "@babel/preset-env": "^7.16.0", "@babel/preset-typescript": "^7.16.0", "@babel/runtime": "^7.16.0", - "@wordpress/babel-plugin-import-jsx-pragma": "^4.30.0", - "@wordpress/browserslist-config": "^5.30.0", - "@wordpress/warning": "^2.47.0", + "@wordpress/babel-plugin-import-jsx-pragma": "^4.31.0", + "@wordpress/browserslist-config": "^5.31.0", + "@wordpress/warning": "^2.48.0", "browserslist": "^4.21.10", "core-js": "^3.31.0", "react": "^18.2.0" @@ -27427,9 +27428,9 @@ "dev": true }, "@wordpress/browserslist-config": { - "version": "5.30.0", - "resolved": "https://registry.npmjs.org/@wordpress/browserslist-config/-/browserslist-config-5.30.0.tgz", - "integrity": "sha512-HFgLCkvvxba+j7/qNjVn1od38tvMm1xVlIJBR+zukkTvvLu/AkdelWKAQpvAoFAXMaZJ7239VxDVBYbVolf6FQ==", + "version": "5.31.0", + "resolved": "https://registry.npmjs.org/@wordpress/browserslist-config/-/browserslist-config-5.31.0.tgz", + "integrity": "sha512-fjglKNuqMKfGXrxuqea8ndTLkga9MfnyBBYuniGZ7cQo3iOhOn6ZqlfKygZdAuZ19FOwQWaQ+9W9MpOtU/4oCA==", "dev": true }, "@wordpress/dependency-extraction-webpack-plugin": { @@ -27531,16 +27532,16 @@ } }, "@wordpress/eslint-plugin": { - "version": "17.4.0", - "resolved": "https://registry.npmjs.org/@wordpress/eslint-plugin/-/eslint-plugin-17.4.0.tgz", - "integrity": "sha512-CT19Ib1Y0ttVQm/bOtjGP6Ge5eqfEaUSobTqCWreHt1RIoxJXTDmazJ1g0Q5MjqG4dEZ/Q/FI4sdqyiKRySkbQ==", + "version": "17.5.0", + "resolved": "https://registry.npmjs.org/@wordpress/eslint-plugin/-/eslint-plugin-17.5.0.tgz", + "integrity": "sha512-wwg4NTMSdiDbkJCFNirn1Oq+Q6wKKWXXmuhsRvK4KsIkayqHavmebnE9bctAiz4ZXI5+URpj8w/IdxYev8acYw==", "dev": true, "requires": { "@babel/eslint-parser": "^7.16.0", "@typescript-eslint/eslint-plugin": "^6.4.1", "@typescript-eslint/parser": "^6.4.1", - "@wordpress/babel-preset-default": "^7.31.0", - "@wordpress/prettier-config": "^3.4.0", + "@wordpress/babel-preset-default": "^7.32.0", + "@wordpress/prettier-config": "^3.5.0", "cosmiconfig": "^7.0.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-import": "^2.25.2", @@ -27663,9 +27664,9 @@ } }, "@wordpress/prettier-config": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/@wordpress/prettier-config/-/prettier-config-3.4.0.tgz", - "integrity": "sha512-6qawlZqqbe6NDY0txzsPZThRFAXzf0a891wI/A4KNWVKUXQwTluXWMtGZx3xlFtvkX+9ZHdoqXbWysGQztiBOQ==", + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/@wordpress/prettier-config/-/prettier-config-3.5.0.tgz", + "integrity": "sha512-Nzp6TWu+nx1fzgqqa34/MdBiRDT/Yoqo8jFHBrYhx1kV3BPg8m5lvyGxNmzqoR3hZQatGkBJYdFlLs0WeAGGDQ==", "dev": true, "requires": {} }, @@ -27916,9 +27917,9 @@ } }, "@wordpress/warning": { - "version": "2.47.0", - "resolved": "https://registry.npmjs.org/@wordpress/warning/-/warning-2.47.0.tgz", - "integrity": "sha512-lmpLNI8Si7HrSY0LBBtp7Z6NzAkh1y7yeJI0LZw17EsJ0MM5FSXqXJRrNY7L4tM8G/vv3OacUw1mRAZX7bzBRQ==", + "version": "2.48.0", + "resolved": "https://registry.npmjs.org/@wordpress/warning/-/warning-2.48.0.tgz", + "integrity": "sha512-M8KB8OdxHHxLDPy/1DuSi4SKYrR4/LL2jLWS9GkTa0eSe7PKxIscXH3Q0giFwcREkz80J0rFuADCInCuyIr5Kg==", "dev": true }, "@xtuc/ieee754": { diff --git a/package.json b/package.json index 5d5c7e4c..89d76440 100644 --- a/package.json +++ b/package.json @@ -16,8 +16,9 @@ "build": "npx webpack", "dev": "npx webpack --watch --mode development", "dist": "npx webpack --mode production && composer install --no-dev && composer dump-autoload --no-dev -o && wp-scripts plugin-zip && mv accessibility-checker.zip ./dist && composer install", - "lint": "./vendor/bin/phpcs", - "test:e2e": "npx wp-env clean tests && npx playwright test ./e2e/specs" + "lint": "./vendor/bin/phpcs && npm run lint:js", + "lint:js": "wp-scripts lint-js", + "test:e2e": "npx wp-env clean tests && npx playwright test ./e2e/specs" }, "files": [ "LICENSE.txt", @@ -33,9 +34,10 @@ "devDependencies": { "@babel/core": "^7.22.1", "@babel/preset-env": "^7.22.4", - "@babel/preset-react": "^7.22.3", + "@babel/preset-react": "^7.22.3", "@floating-ui/dom": "^1.2.9", "@wordpress/env": "*", + "@wordpress/eslint-plugin": "^17.5.0", "@wordpress/scripts": "^26.5.0", "axe-core": "^4.7.2", "babel-loader": "^9.1.2", From 48f167119fa17c401c88ad4e5067d8d5884da760 Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Wed, 13 Dec 2023 13:59:56 +0200 Subject: [PATCH 02/10] fix webpack.config.js --- webpack.config.js | 112 +++++++++++++++++++++++----------------------- 1 file changed, 55 insertions(+), 57 deletions(-) diff --git a/webpack.config.js b/webpack.config.js index 029f549a..4e1c083a 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,61 +1,59 @@ -const webpack = require('webpack'); // to access built-in plugins -const path = require('path'); -const { CleanWebpackPlugin } = require('clean-webpack-plugin'); -const MiniCssExtractPlugin = require("mini-css-extract-plugin"); -const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); - +const webpack = require( 'webpack' ); // to access built-in plugins +const path = require( 'path' ); +const { CleanWebpackPlugin } = require( 'clean-webpack-plugin' ); +const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' ); +const CssMinimizerPlugin = require( 'css-minimizer-webpack-plugin' ); module.exports = { - mode: "none", //development | production - watch: false, - entry: { - 'app': [ - './src/app/index.js', - './src/app/sass/accessibility-checker.scss', - ], - 'admin': [ - './src/admin/index.js', - './src/admin/sass/accessibility-checker-admin.scss', - ], - - }, + mode: 'none', //development | production + watch: false, + entry: { + app: [ + './src/app/index.js', + './src/app/sass/accessibility-checker.scss', + ], + admin: [ + './src/admin/index.js', + './src/admin/sass/accessibility-checker-admin.scss', + ], + }, - output: { - filename: '[name].bundle.js', - path: path.resolve(__dirname, 'build'), - }, + output: { + filename: '[name].bundle.js', + path: path.resolve( __dirname, 'build' ), + }, - module: { - rules: [ - { - test: /\.(js|jsx)$/, - exclude: /node_modules/, - use: ['babel-loader'] - }, - { - test: /\.(s(a|c)ss)$/, - use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'] - }, - // loader for images and icons (required if css references image files) - { - test: /\.(svg|png|jpg|gif)$/, - type: 'asset/resource', - generator: { - filename: './img/[name][ext]', - } - }, - ] - }, - plugins: [ - new webpack.ProgressPlugin(), - new CleanWebpackPlugin(), - new MiniCssExtractPlugin({ - filename: './css/[name].css' - }), - new CssMinimizerPlugin(), - - - ], - - -} + module: { + rules: [ + { + test: /\.(js|jsx)$/, + exclude: /node_modules/, + use: [ 'babel-loader' ], + }, + { + test: /\.(s(a|c)ss)$/, + use: [ + MiniCssExtractPlugin.loader, + 'css-loader', + 'sass-loader', + ], + }, + // loader for images and icons (required if css references image files) + { + test: /\.(svg|png|jpg|gif)$/, + type: 'asset/resource', + generator: { + filename: './img/[name][ext]', + }, + }, + ], + }, + plugins: [ + new webpack.ProgressPlugin(), + new CleanWebpackPlugin(), + new MiniCssExtractPlugin( { + filename: './css/[name].css', + } ), + new CssMinimizerPlugin(), + ], +}; From 8e358fc86aab32794def97557e5b2b1d7211846d Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Wed, 13 Dec 2023 14:55:59 +0200 Subject: [PATCH 03/10] src/admin/index.js: Auto-fix all fixable issues --- src/admin/index.js | 1732 +++++++++++++++++++++++--------------------- 1 file changed, 917 insertions(+), 815 deletions(-) diff --git a/src/admin/index.js b/src/admin/index.js index 771f5246..6132462c 100644 --- a/src/admin/index.js +++ b/src/admin/index.js @@ -1,99 +1,107 @@ - -(function ($) { - "use strict"; - - $(function () { - - // Accessibility Statement disable - $("input[type=checkbox][name=edac_add_footer_accessibility_statement]").on('change', function () { - if (this.checked) { - $("input[type=checkbox][name=edac_include_accessibility_statement_link]").prop('disabled', false); - } else { - $("input[type=checkbox][name=edac_include_accessibility_statement_link]").prop('disabled', true); - $("input[type=checkbox][name=edac_include_accessibility_statement_link]").prop('checked', false); - } - // - }); - - // Show Simplified Summary code on options page - if ($("input[type=radio][name=edac_simplified_summary_position]:checked").val() == "none") { - $("#ac-simplified-summary-option-code").show(); - } - $("input[type=radio][name=edac_simplified_summary_position]").on('load', function () { - if (this.value == "none") { - $("#ac-simplified-summary-option-code").show(); - } else { - $("#ac-simplified-summary-option-code").hide(); - } - }); - - }); - - - $(window).on('load', function () { - - /** - * Tabs - */ - - // Refresh data on summary and readability tabs - const refresh_summary_and_readability = () => { - - edac_summary_ajax( - () => { - edac_readability_ajax(); - $(".edac-panel").removeClass("edac-panel-loading"); - } - ); - - }; - - $(".edac-tab").click(function (e) { - e.preventDefault(); - var id = $("a", this).attr("href"); - - $(".edac-panel").hide(); - $(".edac-panel").removeClass("active"); - $(".edac-tab a").removeClass("active").attr("aria-current", false); - $(id).show(); - $(id).addClass("active"); - $("a", this).addClass("active").attr("aria-current", true); - }); - - // Details Tab on click Ajax - $(".edac-tab-details").click(function (e) { - edac_details_ajax(); - }); - - // Summary Tab on click Ajax - $(".edac-tab-summary").click(function (e) { - refresh_summary_and_readability(); - }); - - /** - * Ajax Summary - */ - function edac_summary_ajax(callback = null) { - - let post_id = edac_script_vars.postID; - - if (post_id == null) { - return; - } - - $.ajax({ - - url: ajaxurl, - method: 'GET', - data: { action: 'edac_summary_ajax', post_id: post_id, nonce: edac_script_vars.nonce } - - }).done(function (response) { - - if (true === response.success) { - - let response_json = $.parseJSON(response.data); - - /* +( function ( $ ) { + 'use strict'; + + $( function () { + // Accessibility Statement disable + $( + 'input[type=checkbox][name=edac_add_footer_accessibility_statement]' + ).on( 'change', function () { + if ( this.checked ) { + $( + 'input[type=checkbox][name=edac_include_accessibility_statement_link]' + ).prop( 'disabled', false ); + } else { + $( + 'input[type=checkbox][name=edac_include_accessibility_statement_link]' + ).prop( 'disabled', true ); + $( + 'input[type=checkbox][name=edac_include_accessibility_statement_link]' + ).prop( 'checked', false ); + } + // + } ); + + // Show Simplified Summary code on options page + if ( + $( + 'input[type=radio][name=edac_simplified_summary_position]:checked' + ).val() == 'none' + ) { + $( '#ac-simplified-summary-option-code' ).show(); + } + $( 'input[type=radio][name=edac_simplified_summary_position]' ).on( + 'load', + function () { + if ( this.value == 'none' ) { + $( '#ac-simplified-summary-option-code' ).show(); + } else { + $( '#ac-simplified-summary-option-code' ).hide(); + } + } + ); + } ); + + $( window ).on( 'load', function () { + /** + * Tabs + */ + + // Refresh data on summary and readability tabs + const refresh_summary_and_readability = () => { + edac_summary_ajax( () => { + edac_readability_ajax(); + $( '.edac-panel' ).removeClass( 'edac-panel-loading' ); + } ); + }; + + $( '.edac-tab' ).click( function ( e ) { + e.preventDefault(); + const id = $( 'a', this ).attr( 'href' ); + + $( '.edac-panel' ).hide(); + $( '.edac-panel' ).removeClass( 'active' ); + $( '.edac-tab a' ) + .removeClass( 'active' ) + .attr( 'aria-current', false ); + $( id ).show(); + $( id ).addClass( 'active' ); + $( 'a', this ).addClass( 'active' ).attr( 'aria-current', true ); + } ); + + // Details Tab on click Ajax + $( '.edac-tab-details' ).click( function ( e ) { + edac_details_ajax(); + } ); + + // Summary Tab on click Ajax + $( '.edac-tab-summary' ).click( function ( e ) { + refresh_summary_and_readability(); + } ); + + /** + * Ajax Summary + * @param callback + */ + function edac_summary_ajax( callback = null ) { + const post_id = edac_script_vars.postID; + + if ( post_id == null ) { + return; + } + + $.ajax( { + url: ajaxurl, + method: 'GET', + data: { + action: 'edac_summary_ajax', + post_id, + nonce: edac_script_vars.nonce, + }, + } ).done( function ( response ) { + if ( true === response.success ) { + const response_json = $.parseJSON( response.data ); + + /* if(response_json.password_protected && edac_gutenberg_active()){ wp.data.dispatch('core/notices').createInfoNotice( response_json.password_protected, @@ -107,534 +115,602 @@ } */ - $(".edac-summary").html(response_json.content); - - if (typeof callback === 'function') { - callback(); - } - - } else { - - console.log(response); - - } - - }); - - } - - /** - * Ajax Details - */ - function edac_details_ajax() { - - let post_id = edac_script_vars.postID; - - if (post_id == null) { - return; - } - - $.ajax({ - - url: ajaxurl, - method: 'GET', - data: { action: 'edac_details_ajax', post_id: post_id, nonce: edac_script_vars.nonce } - - }).done(function (response) { - - if (true === response.success) { - - let response_json = $.parseJSON(response.data); - - $(".edac-details").html(response_json); - - // Rule on click - $(".edac-details-rule-title").click(function (e) { - //$('.edac-details-rule-records').slideUp(); - if ($(this).hasClass("active")) { - $(this).next().slideUp(); - $(this).removeClass("active"); - } else { - $(this).next().slideDown(); - $(this).addClass("active"); - } - }); - - // Title arrow button on click - $(".edac-details-rule-title-arrow").click(function (e) { - e.preventDefault(); - if ($(this).attr("aria-expanded") === "true") { - $(this).attr("aria-expanded", "false"); - } else { - $(this).attr("aria-expanded", "true"); - } - }); - - // Ignore on click - $(".edac-details-rule-records-record-actions-ignore").click(function (e) { - e.preventDefault(); - $(this).parent().next(".edac-details-rule-records-record-ignore").slideToggle(); - if ($(this).attr("aria-expanded") === "true") { - $(this).attr("aria-expanded", "false"); - } else { - $(this).attr("aria-expanded", "true"); - } - }); - - // Ignore submit on click - ignore_submit(); - - } else { - - console.log(response); - - } - - }); - - } - - /** - * Ajax Readability - */ - function edac_readability_ajax() { - - let post_id = edac_script_vars.postID; - - if (post_id == null) { - return; - } - - $.ajax({ - - url: ajaxurl, - method: 'GET', - data: { action: 'edac_readability_ajax', post_id: post_id, nonce: edac_script_vars.nonce } - - }).done(function (response) { - - if (true === response.success) { - - let response_json = $.parseJSON(response.data); - - $(".edac-readability").html(response_json); - - // Simplified Summary on click - $(".edac-readability-simplified-summary").submit(function (event) { - event.preventDefault(); - - //var post_id = wp.data.select("core/editor").getCurrentPostId(); - let summary = $("#edac-readability-text").val(); - - $.ajax({ - - url: ajaxurl, - method: 'GET', - data: { action: 'edac_update_simplified_summary', post_id: post_id, summary: summary, nonce: edac_script_vars.nonce } - - }).done(function (response) { - - if (true === response.success) { - - let response_json = $.parseJSON(response.data); - - refresh_summary_and_readability(); - - } else { - - console.log(response); - - } - - }); - - }); - - } else { - - console.log(response); - - } - - }); - - } - - /** - * On Post Save Gutenberg - */ - if (edac_gutenberg_active()) { - var editPost = wp.data.select("core/edit-post"), - lastIsSaving = false; - - wp.data.subscribe(function () { - var isSaving = editPost.isSavingMetaBoxes(); - if (isSaving) { - $(".edac-panel").addClass("edac-panel-loading"); - } - if (isSaving !== lastIsSaving && !isSaving) { - lastIsSaving = isSaving; - - - // reset to first meta box tab - $(".edac-panel").hide(); - $(".edac-panel").removeClass("active"); - $(".edac-tab a").removeClass("active"); - $("#edac-summary").show(); - $("#edac-summary").addClass("active"); - $(".edac-tab:first-child a").addClass("active"); - - edac_details_ajax(); - refresh_summary_and_readability(); - - } - lastIsSaving = isSaving; - }); - } - - /** - * Ignore Submit on click - */ - function ignore_submit() { - - $(".edac-details-rule-records-record-ignore-submit").click(function (e) { - e.preventDefault(); - - let ids = [$(this).attr("data-id")]; - let ignore_action = $(this).attr("data-action"); - let ignore_type = $(this).attr("data-type"); - let comment = $( - ".edac-details-rule-records-record-ignore-comment", - $(this).parent() - ).val(); - - $.ajax({ - - url: ajaxurl, - method: 'GET', - data: { - action: 'edac_insert_ignore_data', - ids: ids, - comment: comment, - ignore_action: ignore_action, - ignore_type: ignore_type, - nonce: edac_script_vars.nonce - } - - }).done(function (response) { - - if (true === response.success) { - - let data = $.parseJSON(response.data); - - let record = "#edac-details-rule-records-record-" + data["ids"][0]; - let ignore_action = data["action"] == "enable" ? "disable" : "enable"; - let comment_disabled = data["action"] == "enable" ? true : false; - let actions_ignore_label = data["action"] == "enable" ? "Ignored" : "Ignore"; - let ignore_submit_label = data["action"] == "enable" ? "Stop Ignoring" : "Ignore This " + data['type']; - let username = data["user"] ? "Username: " + data["user"] : ""; - let date = data["date"] ? "Date: " + data["date"] : ""; - - $(record + " .edac-details-rule-records-record-ignore-submit").attr("data-action", ignore_action); - $(record + " .edac-details-rule-records-record-ignore-comment").attr("disabled", comment_disabled); - if (data["action"] != "enable") { - $(record + " .edac-details-rule-records-record-ignore-comment").val(""); - } - $(record + " .edac-details-rule-records-record-actions-ignore").toggleClass("active"); - $(".edac-details-rule-records-record-actions-ignore[data-id='" + ids[0] + "']").toggleClass("active"); // pro - $(record + " .edac-details-rule-records-record-actions-ignore-label").html(actions_ignore_label); - $(".edac-details-rule-records-record-actions-ignore[data-id='" + ids[0] + "'] .edac-details-rule-records-record-actions-ignore-label").html(actions_ignore_label); // pro - $(record + " .edac-details-rule-records-record-ignore-submit-label").html(ignore_submit_label); - $(record + " .edac-details-rule-records-record-ignore-info-user").html(username); - $(record + " .edac-details-rule-records-record-ignore-info-date").html(date); - - // Update rule count - let rule = $(record).parents(".edac-details-rule"); - let count = parseInt($(".edac-details-rule-count", rule).html()); - if (data["action"] == "enable") { - count--; - } else if (data["action"] == "disable") { - count++; - } - if (count == 0) { - $(".edac-details-rule-count", rule).removeClass("active"); - } else { - $(".edac-details-rule-count", rule).addClass("active"); - } - count.toString(); - $(".edac-details-rule-count", rule).html(count); - - // Update ignore rule count - var count_ignore = parseInt($(".edac-details-rule-count-ignore", rule).html()); - //console.log(count_ignore); - if (data["action"] == "enable") { - count_ignore++; - } else if (data["action"] == "disable") { - count_ignore--; - } - if (count_ignore == 0) { - $(".edac-details-rule-count-ignore", rule).hide(); - } else { - $(".edac-details-rule-count-ignore", rule).show(); - } - count_ignore.toString(); - $(".edac-details-rule-count-ignore", rule).html(count_ignore + ' Ignored Items'); - - // refresh page on ignore or unignore in pro - if ($('body').hasClass('accessibility-checker_page_accessibility_checker_issues') || $('body').hasClass('accessibility-checker_page_accessibility_checker_ignored')) { - location.reload(true); - } - - } else { - - console.log(response); - - } - - }); - - }); - } - - /** - * Check if Gutenberg is active - */ - function edac_gutenberg_active() { - - // return false if widgets page - if (document.body.classList.contains("widgets-php")) return false; - - // check if block editor page - return document.body.classList.contains("block-editor-page"); - } - - /** - * Review Notice Ajax - */ - if ($('.edac-review-notice').length) { - $('.edac-review-notice-review').on('click', function () { - edac_review_notice_ajax('stop', true); - }); - - $('.edac-review-notice-remind').on('click', function () { - edac_review_notice_ajax('pause', false); - }); - - $('.edac-review-notice-dismiss').on('click', function () { - edac_review_notice_ajax('stop', false); - }); - } - - function edac_review_notice_ajax(review_action, redirect) { - $.ajax({ - url: ajaxurl, - method: 'GET', - data: { action: 'edac_review_notice_ajax', review_action: review_action, nonce: edac_script_vars.nonce } - }).done(function (response) { - if (true === response.success) { - let response_json = $.parseJSON(response.data); - $('.edac-review-notice').fadeOut(); - if (redirect) { - window.location.href = 'https://wordpress.org/support/plugin/accessibility-checker/reviews/#new-post'; - } - } else { - //console.log(response); - } - }); - } - - /** - * Password Protected Notice Ajax - */ - if ($('.edac_password_protected_notice').length) { - $('.edac_password_protected_notice').on('click', function () { - edac_password_protected_notice_ajax(); - }); - } - - function edac_password_protected_notice_ajax() { - $.ajax({ - url: ajaxurl, - method: 'GET', - data: { action: 'edac_password_protected_notice_ajax', nonce: edac_script_vars.nonce } - }).done(function (response) { - if (true === response.success) { - let response_json = $.parseJSON(response.data); - } else { - //console.log(response); - } - }); - } - - /** - * GAAD Notice Ajax - */ - if ($('.edac_gaad_notice').length) { - $('.edac_gaad_notice .notice-dismiss').on('click', function () { - edac_gaad_notice_ajax('edac_gaad_notice_ajax'); - }); - } - - /** - * Black Friday Notice Ajax - */ - if ($('.edac_black_friday_notice').length) { - $('.edac_black_friday_notice .notice-dismiss').on('click', function () { - edac_gaad_notice_ajax('edac_black_friday_notice_ajax'); - }); - } - - function edac_gaad_notice_ajax(function_name = null) { - $.ajax({ - url: ajaxurl, - method: 'GET', - data: { action: function_name, nonce: edac_script_vars.nonce } - }).done(function (response) { - if (true === response.success) { - let response_json = $.parseJSON(response.data); - } else { - //console.log(response); - } - }); - } - - if ($('.edac-summary').length) { - refresh_summary_and_readability(); - } - if ($('.edac-details').length) { - edac_details_ajax(); - ignore_submit(); - } - if ($('.edac-details-rule-records-record-ignore').length) { - ignore_submit(); - } - if ($('.edac-readability').length) { - refresh_summary_and_readability(); - } - - - $('#dismiss_welcome_cta').on('click', function () { - // AJAX request to handle button click - $.ajax({ - type: 'POST', - url: ajaxurl, - data: { - action: 'edac_dismiss_welcome_cta_ajax', - }, - success: function (response) { - if (response === 'success') { - // Hide the CTA on button click - $('#edac_welcome_page_summary').hide(); - } - } - }); - }); - - - /** - * Handle widget modal close click - * @param {*} event - */ - function edac_widget_modal_content_close(e) { - - var modal = e.target.closest('.edac-widget-modal'); - if (modal) { - modal.style.display = 'none'; - } - - document.querySelector('.edac-summary').remove(); - - $.ajax({ - type: 'POST', - url: ajaxurl, - data: { - action: 'edac_dismiss_dashboard_cta_ajax', - } - }); - - - } - const modal_close_btn = document.querySelector('.edac-widget-modal-content-close'); - if (modal_close_btn) { - modal_close_btn.addEventListener('click', edac_widget_modal_content_close); - } - - - }); - - - -})(jQuery); - -window.addEventListener("load", function () { - - if (this.document.querySelector('.edac-widget .edac-summary')) { - fillDashboardWidget(); - } - - // Handle refresh button click. - if (this.document.querySelector('#edac_clear_cached_stats')) { - - this.document.querySelector('#edac_clear_cached_stats').addEventListener('click', function () { - - const container = document.querySelector('#edac_welcome_page_summary .edac-welcome-grid-container'); - if (container) { - container.classList.add("edac-panel-loading"); - } - - postData(edac_script_vars.edacApiUrl + '/clear-cached-scans-stats').then((data) => { - if (data.success) { - - if (container) { - container.classList.remove("edac-panel-loading"); - } - - // Reload the current page - location.reload(); - - } - }) - - }); - - } - - edac_timestamp_to_local(); - - -}); - + $( '.edac-summary' ).html( response_json.content ); + + if ( typeof callback === 'function' ) { + callback(); + } + } else { + console.log( response ); + } + } ); + } + + /** + * Ajax Details + */ + function edac_details_ajax() { + const post_id = edac_script_vars.postID; + + if ( post_id == null ) { + return; + } + + $.ajax( { + url: ajaxurl, + method: 'GET', + data: { + action: 'edac_details_ajax', + post_id, + nonce: edac_script_vars.nonce, + }, + } ).done( function ( response ) { + if ( true === response.success ) { + const response_json = $.parseJSON( response.data ); + + $( '.edac-details' ).html( response_json ); + + // Rule on click + $( '.edac-details-rule-title' ).click( function ( e ) { + //$('.edac-details-rule-records').slideUp(); + if ( $( this ).hasClass( 'active' ) ) { + $( this ).next().slideUp(); + $( this ).removeClass( 'active' ); + } else { + $( this ).next().slideDown(); + $( this ).addClass( 'active' ); + } + } ); + + // Title arrow button on click + $( '.edac-details-rule-title-arrow' ).click( + function ( e ) { + e.preventDefault(); + if ( + $( this ).attr( 'aria-expanded' ) === 'true' + ) { + $( this ).attr( 'aria-expanded', 'false' ); + } else { + $( this ).attr( 'aria-expanded', 'true' ); + } + } + ); + + // Ignore on click + $( + '.edac-details-rule-records-record-actions-ignore' + ).click( function ( e ) { + e.preventDefault(); + $( this ) + .parent() + .next( '.edac-details-rule-records-record-ignore' ) + .slideToggle(); + if ( $( this ).attr( 'aria-expanded' ) === 'true' ) { + $( this ).attr( 'aria-expanded', 'false' ); + } else { + $( this ).attr( 'aria-expanded', 'true' ); + } + } ); + + // Ignore submit on click + ignore_submit(); + } else { + console.log( response ); + } + } ); + } + + /** + * Ajax Readability + */ + function edac_readability_ajax() { + const post_id = edac_script_vars.postID; + + if ( post_id == null ) { + return; + } + + $.ajax( { + url: ajaxurl, + method: 'GET', + data: { + action: 'edac_readability_ajax', + post_id, + nonce: edac_script_vars.nonce, + }, + } ).done( function ( response ) { + if ( true === response.success ) { + const response_json = $.parseJSON( response.data ); + + $( '.edac-readability' ).html( response_json ); + + // Simplified Summary on click + $( '.edac-readability-simplified-summary' ).submit( + function ( event ) { + event.preventDefault(); + + //var post_id = wp.data.select("core/editor").getCurrentPostId(); + const summary = $( '#edac-readability-text' ).val(); + + $.ajax( { + url: ajaxurl, + method: 'GET', + data: { + action: 'edac_update_simplified_summary', + post_id, + summary, + nonce: edac_script_vars.nonce, + }, + } ).done( function ( response ) { + if ( true === response.success ) { + const response_json = $.parseJSON( + response.data + ); + + refresh_summary_and_readability(); + } else { + console.log( response ); + } + } ); + } + ); + } else { + console.log( response ); + } + } ); + } + + /** + * On Post Save Gutenberg + */ + if ( edac_gutenberg_active() ) { + let editPost = wp.data.select( 'core/edit-post' ), + lastIsSaving = false; + + wp.data.subscribe( function () { + const isSaving = editPost.isSavingMetaBoxes(); + if ( isSaving ) { + $( '.edac-panel' ).addClass( 'edac-panel-loading' ); + } + if ( isSaving !== lastIsSaving && ! isSaving ) { + lastIsSaving = isSaving; + + // reset to first meta box tab + $( '.edac-panel' ).hide(); + $( '.edac-panel' ).removeClass( 'active' ); + $( '.edac-tab a' ).removeClass( 'active' ); + $( '#edac-summary' ).show(); + $( '#edac-summary' ).addClass( 'active' ); + $( '.edac-tab:first-child a' ).addClass( 'active' ); + + edac_details_ajax(); + refresh_summary_and_readability(); + } + lastIsSaving = isSaving; + } ); + } + + /** + * Ignore Submit on click + */ + function ignore_submit() { + $( '.edac-details-rule-records-record-ignore-submit' ).click( + function ( e ) { + e.preventDefault(); + + const ids = [ $( this ).attr( 'data-id' ) ]; + const ignore_action = $( this ).attr( 'data-action' ); + const ignore_type = $( this ).attr( 'data-type' ); + const comment = $( + '.edac-details-rule-records-record-ignore-comment', + $( this ).parent() + ).val(); + + $.ajax( { + url: ajaxurl, + method: 'GET', + data: { + action: 'edac_insert_ignore_data', + ids, + comment, + ignore_action, + ignore_type, + nonce: edac_script_vars.nonce, + }, + } ).done( function ( response ) { + if ( true === response.success ) { + const data = $.parseJSON( response.data ); + + const record = + '#edac-details-rule-records-record-' + + data.ids[ 0 ]; + const ignore_action = + data.action == 'enable' ? 'disable' : 'enable'; + const comment_disabled = + data.action == 'enable' ? true : false; + const actions_ignore_label = + data.action == 'enable' ? 'Ignored' : 'Ignore'; + const ignore_submit_label = + data.action == 'enable' + ? 'Stop Ignoring' + : 'Ignore This ' + data.type; + const username = data.user + ? 'Username: ' + data.user + : ''; + const date = data.date + ? 'Date: ' + data.date + : ''; + + $( + record + + ' .edac-details-rule-records-record-ignore-submit' + ).attr( 'data-action', ignore_action ); + $( + record + + ' .edac-details-rule-records-record-ignore-comment' + ).attr( 'disabled', comment_disabled ); + if ( data.action != 'enable' ) { + $( + record + + ' .edac-details-rule-records-record-ignore-comment' + ).val( '' ); + } + $( + record + + ' .edac-details-rule-records-record-actions-ignore' + ).toggleClass( 'active' ); + $( + ".edac-details-rule-records-record-actions-ignore[data-id='" + + ids[ 0 ] + + "']" + ).toggleClass( 'active' ); // pro + $( + record + + ' .edac-details-rule-records-record-actions-ignore-label' + ).html( actions_ignore_label ); + $( + ".edac-details-rule-records-record-actions-ignore[data-id='" + + ids[ 0 ] + + "'] .edac-details-rule-records-record-actions-ignore-label" + ).html( actions_ignore_label ); // pro + $( + record + + ' .edac-details-rule-records-record-ignore-submit-label' + ).html( ignore_submit_label ); + $( + record + + ' .edac-details-rule-records-record-ignore-info-user' + ).html( username ); + $( + record + + ' .edac-details-rule-records-record-ignore-info-date' + ).html( date ); + + // Update rule count + const rule = + $( record ).parents( '.edac-details-rule' ); + let count = parseInt( + $( '.edac-details-rule-count', rule ).html() + ); + if ( data.action == 'enable' ) { + count--; + } else if ( data.action == 'disable' ) { + count++; + } + if ( count == 0 ) { + $( + '.edac-details-rule-count', + rule + ).removeClass( 'active' ); + } else { + $( '.edac-details-rule-count', rule ).addClass( + 'active' + ); + } + count.toString(); + $( '.edac-details-rule-count', rule ).html( count ); + + // Update ignore rule count + let count_ignore = parseInt( + $( + '.edac-details-rule-count-ignore', + rule + ).html() + ); + //console.log(count_ignore); + if ( data.action == 'enable' ) { + count_ignore++; + } else if ( data.action == 'disable' ) { + count_ignore--; + } + if ( count_ignore == 0 ) { + $( + '.edac-details-rule-count-ignore', + rule + ).hide(); + } else { + $( + '.edac-details-rule-count-ignore', + rule + ).show(); + } + count_ignore.toString(); + $( '.edac-details-rule-count-ignore', rule ).html( + count_ignore + ' Ignored Items' + ); + + // refresh page on ignore or unignore in pro + if ( + $( 'body' ).hasClass( + 'accessibility-checker_page_accessibility_checker_issues' + ) || + $( 'body' ).hasClass( + 'accessibility-checker_page_accessibility_checker_ignored' + ) + ) { + location.reload( true ); + } + } else { + console.log( response ); + } + } ); + } + ); + } + + /** + * Check if Gutenberg is active + */ + function edac_gutenberg_active() { + // return false if widgets page + if ( document.body.classList.contains( 'widgets-php' ) ) + return false; + + // check if block editor page + return document.body.classList.contains( 'block-editor-page' ); + } + + /** + * Review Notice Ajax + */ + if ( $( '.edac-review-notice' ).length ) { + $( '.edac-review-notice-review' ).on( 'click', function () { + edac_review_notice_ajax( 'stop', true ); + } ); + + $( '.edac-review-notice-remind' ).on( 'click', function () { + edac_review_notice_ajax( 'pause', false ); + } ); + + $( '.edac-review-notice-dismiss' ).on( 'click', function () { + edac_review_notice_ajax( 'stop', false ); + } ); + } + + function edac_review_notice_ajax( review_action, redirect ) { + $.ajax( { + url: ajaxurl, + method: 'GET', + data: { + action: 'edac_review_notice_ajax', + review_action, + nonce: edac_script_vars.nonce, + }, + } ).done( function ( response ) { + if ( true === response.success ) { + const response_json = $.parseJSON( response.data ); + $( '.edac-review-notice' ).fadeOut(); + if ( redirect ) { + window.location.href = + 'https://wordpress.org/support/plugin/accessibility-checker/reviews/#new-post'; + } + } else { + //console.log(response); + } + } ); + } + + /** + * Password Protected Notice Ajax + */ + if ( $( '.edac_password_protected_notice' ).length ) { + $( '.edac_password_protected_notice' ).on( 'click', function () { + edac_password_protected_notice_ajax(); + } ); + } + + function edac_password_protected_notice_ajax() { + $.ajax( { + url: ajaxurl, + method: 'GET', + data: { + action: 'edac_password_protected_notice_ajax', + nonce: edac_script_vars.nonce, + }, + } ).done( function ( response ) { + if ( true === response.success ) { + const response_json = $.parseJSON( response.data ); + } else { + //console.log(response); + } + } ); + } + + /** + * GAAD Notice Ajax + */ + if ( $( '.edac_gaad_notice' ).length ) { + $( '.edac_gaad_notice .notice-dismiss' ).on( 'click', function () { + edac_gaad_notice_ajax( 'edac_gaad_notice_ajax' ); + } ); + } + + /** + * Black Friday Notice Ajax + */ + if ( $( '.edac_black_friday_notice' ).length ) { + $( '.edac_black_friday_notice .notice-dismiss' ).on( + 'click', + function () { + edac_gaad_notice_ajax( 'edac_black_friday_notice_ajax' ); + } + ); + } + + function edac_gaad_notice_ajax( function_name = null ) { + $.ajax( { + url: ajaxurl, + method: 'GET', + data: { action: function_name, nonce: edac_script_vars.nonce }, + } ).done( function ( response ) { + if ( true === response.success ) { + const response_json = $.parseJSON( response.data ); + } else { + //console.log(response); + } + } ); + } + + if ( $( '.edac-summary' ).length ) { + refresh_summary_and_readability(); + } + if ( $( '.edac-details' ).length ) { + edac_details_ajax(); + ignore_submit(); + } + if ( $( '.edac-details-rule-records-record-ignore' ).length ) { + ignore_submit(); + } + if ( $( '.edac-readability' ).length ) { + refresh_summary_and_readability(); + } + + $( '#dismiss_welcome_cta' ).on( 'click', function () { + // AJAX request to handle button click + $.ajax( { + type: 'POST', + url: ajaxurl, + data: { + action: 'edac_dismiss_welcome_cta_ajax', + }, + success( response ) { + if ( response === 'success' ) { + // Hide the CTA on button click + $( '#edac_welcome_page_summary' ).hide(); + } + }, + } ); + } ); + + /** + * Handle widget modal close click + * @param {*} event + * @param e + */ + function edac_widget_modal_content_close( e ) { + const modal = e.target.closest( '.edac-widget-modal' ); + if ( modal ) { + modal.style.display = 'none'; + } + + document.querySelector( '.edac-summary' ).remove(); + + $.ajax( { + type: 'POST', + url: ajaxurl, + data: { + action: 'edac_dismiss_dashboard_cta_ajax', + }, + } ); + } + const modal_close_btn = document.querySelector( + '.edac-widget-modal-content-close' + ); + if ( modal_close_btn ) { + modal_close_btn.addEventListener( + 'click', + edac_widget_modal_content_close + ); + } + } ); +} )( jQuery ); + +window.addEventListener( 'load', function () { + if ( this.document.querySelector( '.edac-widget .edac-summary' ) ) { + fillDashboardWidget(); + } + + // Handle refresh button click. + if ( this.document.querySelector( '#edac_clear_cached_stats' ) ) { + this.document + .querySelector( '#edac_clear_cached_stats' ) + .addEventListener( 'click', function () { + const container = document.querySelector( + '#edac_welcome_page_summary .edac-welcome-grid-container' + ); + if ( container ) { + container.classList.add( 'edac-panel-loading' ); + } + + postData( + edac_script_vars.edacApiUrl + '/clear-cached-scans-stats' + ).then( ( data ) => { + if ( data.success ) { + if ( container ) { + container.classList.remove( 'edac-panel-loading' ); + } + + // Reload the current page + location.reload(); + } + } ); + } ); + } + + edac_timestamp_to_local(); +} ); // Fill the dashboard widget const fillDashboardWidget = () => { - - - getData(edac_script_vars.edacApiUrl + '/scans-stats').then((data) => { - if (data.success) { - - - // Set passed % - const passed_percentage = data.stats.passed_percentage; - const passed_percentage_formatted = data.stats.passed_percentage_formatted; - - const passed_percentage_el = document.querySelector('#edac-summary-passed'); - if (passed_percentage_el) { - passed_percentage_el.setAttribute('aria-valuenow', passed_percentage); - passed_percentage_el.style.background = - 'radial-gradient(closest-side, white 85%, transparent 80% 100%), conic-gradient(#006600 ' + passed_percentage + '%, #e2e4e7 0)'; - } - const passed_percentage_text_el = document.querySelector('#edac-summary-passed .edac-progress-percentage'); - if (passed_percentage_text_el) { - passed_percentage_text_el.textContent = passed_percentage_formatted; - } - - // Set completed_at - const completed_at = data.stats.fullscan_completed_at; - const completed_at_formatted = data.stats.fullscan_completed_at_formatted; - const completed_at_el = document.querySelector('#edac-summary-info-date'); - completed_at_el.textContent = completed_at_formatted; - - /* + getData( edac_script_vars.edacApiUrl + '/scans-stats' ) + .then( ( data ) => { + if ( data.success ) { + // Set passed % + const passed_percentage = data.stats.passed_percentage; + const passed_percentage_formatted = + data.stats.passed_percentage_formatted; + + const passed_percentage_el = document.querySelector( + '#edac-summary-passed' + ); + if ( passed_percentage_el ) { + passed_percentage_el.setAttribute( + 'aria-valuenow', + passed_percentage + ); + passed_percentage_el.style.background = + 'radial-gradient(closest-side, white 85%, transparent 80% 100%), conic-gradient(#006600 ' + + passed_percentage + + '%, #e2e4e7 0)'; + } + const passed_percentage_text_el = document.querySelector( + '#edac-summary-passed .edac-progress-percentage' + ); + if ( passed_percentage_text_el ) { + passed_percentage_text_el.textContent = + passed_percentage_formatted; + } + + // Set completed_at + const completed_at = data.stats.fullscan_completed_at; + const completed_at_formatted = + data.stats.fullscan_completed_at_formatted; + const completed_at_el = document.querySelector( + '#edac-summary-info-date' + ); + completed_at_el.textContent = completed_at_formatted; + + /* const expires_at = data.stats.expires_at; const now = Date.now(); const mins_to_exp = Math.round((expires_at - Math.floor(now / 1000))/60); @@ -646,204 +722,230 @@ const fillDashboardWidget = () => { } */ - // scanned - const posts_scanned = data.stats.posts_scanned; - const posts_scanned_formatted = data.stats.posts_scanned_formatted; - const posts_scanned_el = document.querySelector('#edac-summary-info-count'); - if (posts_scanned_el) { - posts_scanned_el.textContent = posts_scanned_formatted; - } - - - // errors - const errors = data.stats.distinct_errors_without_contrast; - const errors_formatted = data.stats.distinct_errors_without_contrast_formatted; - const errors_container_el = document.querySelector('.edac-summary-info-stats-box-error'); - if (errors > 0 && errors_container_el) { - errors_container_el.classList.add('has-errors'); - } - const errors_el = document.querySelector('#edac-summary-info-errors'); - if (errors_el) { - errors_el.textContent = errors_formatted; - } - - // constrast errors - const contrast_errors = data.stats.distinct_contrast_errors; - const contrast_errors_formatted = data.stats.distinct_contrast_errors_formatted; - const contrast_container_el = document.querySelector('.edac-summary-info-stats-box-contrast'); - if (errors > 0 && contrast_container_el) { - contrast_container_el.classList.add('has-errors'); - } - const contrast_errors_el = document.querySelector('#edac-summary-info-contrast-errors'); - if (contrast_errors_el) { - contrast_errors_el.textContent = contrast_errors_formatted; - } - - - // warnings - const warnings = data.stats.distinct_warnings; - const warnings_formatted = data.stats.distinct_warnings_formatted; - const warnings_container_el = document.querySelector('.edac-summary-info-stats-box-warning'); - if (warnings > 0 && warnings_container_el) { - warnings_container_el.classList.add('has-warning'); - } - const warnings_el = document.querySelector('#edac-summary-info-warnings'); - if (warnings_el) { - warnings_el.textContent = warnings_formatted; - } - - - // summary notice - if (errors + contrast_errors + warnings > 0) { - const has_issues_notice_el = document.querySelector('.edac-summary-notice-has-issues'); - if (has_issues_notice_el) { - has_issues_notice_el.classList.remove('edac-hidden'); - } - } else { - const has_no_issues_notice_el = document.querySelector('.edac-summary-notice-no-issues'); - if (has_no_issues_notice_el && posts_scanned > 0) { - has_no_issues_notice_el.classList.remove('edac-hidden'); - } - } - - // truncated notice - const is_truncated = data.stats.is_truncated; - const is_truncated_el = document.querySelector('.edac-summary-notice-is-truncated'); - if (is_truncated_el && is_truncated) { - is_truncated_el.classList.remove('edac-hidden'); - } - - - const wrapper = document.querySelector('.edac-summary.edac-modal-container'); - if (wrapper) { - wrapper.classList.remove('edac-hidden'); - } - - - //edac_timestamp_to_local(); - - } - }).catch((e) => { - //TODO: - }); - - - getData(edac_script_vars.edacApiUrl + '/scans-stats-by-post-types').then((data) => { - - if (data.success) { - - Object.entries(data.stats).forEach(([key, value]) => { - - if (data.stats[key]) { - - const errors = value['distinct_errors_without_contrast']; - const errors_formatted = value['distinct_errors_without_contrast_formatted']; - const contrast_errors = value['distinct_contrast_errors']; - const contrast_errors_formatted = value['distinct_contrast_errors_formatted']; - const warnings = value['distinct_warnings']; - const warnings_formatted = value['distinct_warnings_formatted']; - - const errors_el = document.querySelector('#' + key + '-errors'); - if (errors_el) { - errors_el.textContent = errors_formatted; - } - - const contrast_errors_el = document.querySelector('#' + key + '-contrast-errors'); - if (contrast_errors_el) { - contrast_errors_el.textContent = contrast_errors_formatted; - } - - const warnings_el = document.querySelector('#' + key + '-warnings'); - if (warnings_el) { - warnings_el.textContent = warnings_formatted; - } - - } else { - //We aren't tracking stats for this post type - - } - }); - - } - - const wrapper = document.querySelector('.edac-issues-summary'); - if (wrapper) { - wrapper.classList.remove('edac-hidden'); - } - - edac_timestamp_to_local(); - - }).catch((e) => { - console.log(e); - //TODO: - }); - + // scanned + const posts_scanned = data.stats.posts_scanned; + const posts_scanned_formatted = + data.stats.posts_scanned_formatted; + const posts_scanned_el = document.querySelector( + '#edac-summary-info-count' + ); + if ( posts_scanned_el ) { + posts_scanned_el.textContent = posts_scanned_formatted; + } + + // errors + const errors = data.stats.distinct_errors_without_contrast; + const errors_formatted = + data.stats.distinct_errors_without_contrast_formatted; + const errors_container_el = document.querySelector( + '.edac-summary-info-stats-box-error' + ); + if ( errors > 0 && errors_container_el ) { + errors_container_el.classList.add( 'has-errors' ); + } + const errors_el = document.querySelector( + '#edac-summary-info-errors' + ); + if ( errors_el ) { + errors_el.textContent = errors_formatted; + } + + // constrast errors + const contrast_errors = data.stats.distinct_contrast_errors; + const contrast_errors_formatted = + data.stats.distinct_contrast_errors_formatted; + const contrast_container_el = document.querySelector( + '.edac-summary-info-stats-box-contrast' + ); + if ( errors > 0 && contrast_container_el ) { + contrast_container_el.classList.add( 'has-errors' ); + } + const contrast_errors_el = document.querySelector( + '#edac-summary-info-contrast-errors' + ); + if ( contrast_errors_el ) { + contrast_errors_el.textContent = contrast_errors_formatted; + } + + // warnings + const warnings = data.stats.distinct_warnings; + const warnings_formatted = + data.stats.distinct_warnings_formatted; + const warnings_container_el = document.querySelector( + '.edac-summary-info-stats-box-warning' + ); + if ( warnings > 0 && warnings_container_el ) { + warnings_container_el.classList.add( 'has-warning' ); + } + const warnings_el = document.querySelector( + '#edac-summary-info-warnings' + ); + if ( warnings_el ) { + warnings_el.textContent = warnings_formatted; + } + + // summary notice + if ( errors + contrast_errors + warnings > 0 ) { + const has_issues_notice_el = document.querySelector( + '.edac-summary-notice-has-issues' + ); + if ( has_issues_notice_el ) { + has_issues_notice_el.classList.remove( 'edac-hidden' ); + } + } else { + const has_no_issues_notice_el = document.querySelector( + '.edac-summary-notice-no-issues' + ); + if ( has_no_issues_notice_el && posts_scanned > 0 ) { + has_no_issues_notice_el.classList.remove( + 'edac-hidden' + ); + } + } + + // truncated notice + const is_truncated = data.stats.is_truncated; + const is_truncated_el = document.querySelector( + '.edac-summary-notice-is-truncated' + ); + if ( is_truncated_el && is_truncated ) { + is_truncated_el.classList.remove( 'edac-hidden' ); + } + + const wrapper = document.querySelector( + '.edac-summary.edac-modal-container' + ); + if ( wrapper ) { + wrapper.classList.remove( 'edac-hidden' ); + } + + //edac_timestamp_to_local(); + } + } ) + .catch( ( e ) => { + //TODO: + } ); + + getData( edac_script_vars.edacApiUrl + '/scans-stats-by-post-types' ) + .then( ( data ) => { + if ( data.success ) { + Object.entries( data.stats ).forEach( ( [ key, value ] ) => { + if ( data.stats[ key ] ) { + const errors = value.distinct_errors_without_contrast; + const errors_formatted = + value.distinct_errors_without_contrast_formatted; + const contrast_errors = value.distinct_contrast_errors; + const contrast_errors_formatted = + value.distinct_contrast_errors_formatted; + const warnings = value.distinct_warnings; + const warnings_formatted = + value.distinct_warnings_formatted; + + const errors_el = document.querySelector( + '#' + key + '-errors' + ); + if ( errors_el ) { + errors_el.textContent = errors_formatted; + } + + const contrast_errors_el = document.querySelector( + '#' + key + '-contrast-errors' + ); + if ( contrast_errors_el ) { + contrast_errors_el.textContent = + contrast_errors_formatted; + } + + const warnings_el = document.querySelector( + '#' + key + '-warnings' + ); + if ( warnings_el ) { + warnings_el.textContent = warnings_formatted; + } + } else { + //We aren't tracking stats for this post type + } + } ); + } + + const wrapper = document.querySelector( '.edac-issues-summary' ); + if ( wrapper ) { + wrapper.classList.remove( 'edac-hidden' ); + } + + edac_timestamp_to_local(); + } ) + .catch( ( e ) => { + console.log( e ); + //TODO: + } ); }; - - /** - * Helper function to convert unixtime timestamp to the local date time. - */ + * Helper function to convert unixtime timestamp to the local date time. + */ function edac_timestamp_to_local() { - - var options = { year: "numeric", month: "short", day: "numeric" }; - - var elements = document.querySelectorAll(".edac-timestamp-to-local"); - - elements.forEach(function (element) { - - if (/^[0-9]+$/.test(element.textContent)) { //if only numbers - - var unixtime_in_seconds = element.textContent; - - var d = new Date(unixtime_in_seconds * 1000).toLocaleDateString([], options); - var t = new Date(unixtime_in_seconds * 1000).toLocaleTimeString([], { timeStyle: 'short' }); - - var parts = Intl.DateTimeFormat([], { timeZoneName: 'short' }).formatToParts(new Date()); - let tz = ''; - for (const part of parts) { - if (part.type === 'timeZoneName') { - tz = part.value; - break; - } - } - - element.innerHTML = '' + d + ' ' - + t + ' ' + tz + ''; - - element.classList.remove('edac-timestamp-to-local'); - - } - - }); - - -}; - - -const getData = async (url = "", data = {}) => { - const response = await fetch(url, { - method: "GET", - headers: { - 'X-WP-Nonce': edac_script_vars.restNonce - } - }); - return response.json(); + const options = { year: 'numeric', month: 'short', day: 'numeric' }; + + const elements = document.querySelectorAll( '.edac-timestamp-to-local' ); + + elements.forEach( function ( element ) { + if ( /^[0-9]+$/.test( element.textContent ) ) { + //if only numbers + + const unixtime_in_seconds = element.textContent; + + const d = new Date( unixtime_in_seconds * 1000 ).toLocaleDateString( + [], + options + ); + const t = new Date( unixtime_in_seconds * 1000 ).toLocaleTimeString( + [], + { timeStyle: 'short' } + ); + + const parts = Intl.DateTimeFormat( [], { + timeZoneName: 'short', + } ).formatToParts( new Date() ); + let tz = ''; + for ( const part of parts ) { + if ( part.type === 'timeZoneName' ) { + tz = part.value; + break; + } + } + + element.innerHTML = + '' + + d + + ' ' + + t + + ' ' + + tz + + ''; + + element.classList.remove( 'edac-timestamp-to-local' ); + } + } ); } +const getData = async ( url = '', data = {} ) => { + const response = await fetch( url, { + method: 'GET', + headers: { + 'X-WP-Nonce': edac_script_vars.restNonce, + }, + } ); + return response.json(); +}; - - -const postData = async (url = "", data = {}) => { - - const response = await fetch(url, { - method: "POST", - headers: { - 'X-WP-Nonce': edac_script_vars.restNonce - }, - body: JSON.stringify(data), - }); - return response.json(); -} - +const postData = async ( url = '', data = {} ) => { + const response = await fetch( url, { + method: 'POST', + headers: { + 'X-WP-Nonce': edac_script_vars.restNonce, + }, + body: JSON.stringify( data ), + } ); + return response.json(); +}; From e756c59ad08024e267818cfec2df142ffb1326ea Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Wed, 13 Dec 2023 15:32:22 +0200 Subject: [PATCH 04/10] src/admin/index.js: manually fix remaining issues --- src/admin/index.js | 398 ++++++++++++++++++++++++--------------------- 1 file changed, 211 insertions(+), 187 deletions(-) diff --git a/src/admin/index.js b/src/admin/index.js index 6132462c..718a2881 100644 --- a/src/admin/index.js +++ b/src/admin/index.js @@ -1,3 +1,5 @@ +/* eslint-disable no-unused-vars */ +/* global edac_script_vars, ajaxurl, jQuery */ ( function ( $ ) { 'use strict'; @@ -25,14 +27,14 @@ if ( $( 'input[type=radio][name=edac_simplified_summary_position]:checked' - ).val() == 'none' + ).val() === 'none' ) { $( '#ac-simplified-summary-option-code' ).show(); } $( 'input[type=radio][name=edac_simplified_summary_position]' ).on( 'load', function () { - if ( this.value == 'none' ) { + if ( this.value === 'none' ) { $( '#ac-simplified-summary-option-code' ).show(); } else { $( '#ac-simplified-summary-option-code' ).hide(); @@ -47,9 +49,9 @@ */ // Refresh data on summary and readability tabs - const refresh_summary_and_readability = () => { - edac_summary_ajax( () => { - edac_readability_ajax(); + const refreshSummaryAndReadability = () => { + edacSummaryAjax( () => { + edacReadabilityAjax(); $( '.edac-panel' ).removeClass( 'edac-panel-loading' ); } ); }; @@ -69,23 +71,24 @@ } ); // Details Tab on click Ajax - $( '.edac-tab-details' ).click( function ( e ) { - edac_details_ajax(); + $( '.edac-tab-details' ).click( function () { + edacDetailsAjax(); } ); // Summary Tab on click Ajax - $( '.edac-tab-summary' ).click( function ( e ) { - refresh_summary_and_readability(); + $( '.edac-tab-summary' ).click( function () { + refreshSummaryAndReadability(); } ); /** * Ajax Summary - * @param callback + * @param {Function} callback - Callback function to run after ajax is complete */ - function edac_summary_ajax( callback = null ) { - const post_id = edac_script_vars.postID; + function edacSummaryAjax( callback = null ) { + // eslint-disable-next-line camelcase + const postID = edac_script_vars.postID; - if ( post_id == null ) { + if ( postID === null ) { return; } @@ -94,17 +97,18 @@ method: 'GET', data: { action: 'edac_summary_ajax', - post_id, + post_id: postID, + // eslint-disable-next-line camelcase nonce: edac_script_vars.nonce, }, } ).done( function ( response ) { if ( true === response.success ) { - const response_json = $.parseJSON( response.data ); + const responseJSON = $.parseJSON( response.data ); /* - if(response_json.password_protected && edac_gutenberg_active()){ + if(responseJSON.password_protected && edacGutenbergActive()){ wp.data.dispatch('core/notices').createInfoNotice( - response_json.password_protected, + responseJSON.password_protected, { id: 'edac-password-protected-error', type: 'default', //default, or snackbar @@ -115,12 +119,13 @@ } */ - $( '.edac-summary' ).html( response_json.content ); + $( '.edac-summary' ).html( responseJSON.content ); if ( typeof callback === 'function' ) { callback(); } } else { + // eslint-disable-next-line no-console console.log( response ); } } ); @@ -129,10 +134,11 @@ /** * Ajax Details */ - function edac_details_ajax() { - const post_id = edac_script_vars.postID; + function edacDetailsAjax() { + // eslint-disable-next-line camelcase + const postID = edac_script_vars.postID; - if ( post_id == null ) { + if ( postID === null ) { return; } @@ -141,17 +147,18 @@ method: 'GET', data: { action: 'edac_details_ajax', - post_id, + post_id: postID, + // eslint-disable-next-line camelcase nonce: edac_script_vars.nonce, }, } ).done( function ( response ) { if ( true === response.success ) { - const response_json = $.parseJSON( response.data ); + const responseJSON = $.parseJSON( response.data ); - $( '.edac-details' ).html( response_json ); + $( '.edac-details' ).html( responseJSON ); // Rule on click - $( '.edac-details-rule-title' ).click( function ( e ) { + $( '.edac-details-rule-title' ).click( function () { //$('.edac-details-rule-records').slideUp(); if ( $( this ).hasClass( 'active' ) ) { $( this ).next().slideUp(); @@ -193,8 +200,9 @@ } ); // Ignore submit on click - ignore_submit(); + ignoreSubmit(); } else { + // eslint-disable-next-line no-console console.log( response ); } } ); @@ -203,10 +211,11 @@ /** * Ajax Readability */ - function edac_readability_ajax() { - const post_id = edac_script_vars.postID; + function edacReadabilityAjax() { + // eslint-disable-next-line camelcase + const postID = edac_script_vars.postID; - if ( post_id == null ) { + if ( postID === null ) { return; } @@ -215,21 +224,22 @@ method: 'GET', data: { action: 'edac_readability_ajax', - post_id, + post_id: postID, + // eslint-disable-next-line camelcase nonce: edac_script_vars.nonce, }, } ).done( function ( response ) { if ( true === response.success ) { - const response_json = $.parseJSON( response.data ); + const responseJSON = $.parseJSON( response.data ); - $( '.edac-readability' ).html( response_json ); + $( '.edac-readability' ).html( responseJSON ); // Simplified Summary on click $( '.edac-readability-simplified-summary' ).submit( function ( event ) { event.preventDefault(); - //var post_id = wp.data.select("core/editor").getCurrentPostId(); + // var postID = wp.data.select("core/editor").getCurrentPostId(); const summary = $( '#edac-readability-text' ).val(); $.ajax( { @@ -237,24 +247,27 @@ method: 'GET', data: { action: 'edac_update_simplified_summary', - post_id, + post_id: postID, summary, + // eslint-disable-next-line camelcase nonce: edac_script_vars.nonce, }, - } ).done( function ( response ) { - if ( true === response.success ) { - const response_json = $.parseJSON( - response.data + } ).done( function ( doneResponse ) { + if ( true === doneResponse.success ) { + const doneResponseJSON = $.parseJSON( + doneResponse.data ); - refresh_summary_and_readability(); + refreshSummaryAndReadability(); } else { - console.log( response ); + // eslint-disable-next-line no-console + console.log( doneResponse ); } } ); } ); } else { + // eslint-disable-next-line no-console console.log( response ); } } ); @@ -263,9 +276,9 @@ /** * On Post Save Gutenberg */ - if ( edac_gutenberg_active() ) { - let editPost = wp.data.select( 'core/edit-post' ), - lastIsSaving = false; + if ( edacGutenbergActive() ) { + const editPost = wp.data.select( 'core/edit-post' ); + let lastIsSaving = false; wp.data.subscribe( function () { const isSaving = editPost.isSavingMetaBoxes(); @@ -283,8 +296,8 @@ $( '#edac-summary' ).addClass( 'active' ); $( '.edac-tab:first-child a' ).addClass( 'active' ); - edac_details_ajax(); - refresh_summary_and_readability(); + edacDetailsAjax(); + refreshSummaryAndReadability(); } lastIsSaving = isSaving; } ); @@ -293,14 +306,14 @@ /** * Ignore Submit on click */ - function ignore_submit() { + function ignoreSubmit() { $( '.edac-details-rule-records-record-ignore-submit' ).click( function ( e ) { e.preventDefault(); const ids = [ $( this ).attr( 'data-id' ) ]; - const ignore_action = $( this ).attr( 'data-action' ); - const ignore_type = $( this ).attr( 'data-type' ); + const ignoreAction = $( this ).attr( 'data-action' ); + const ignoreType = $( this ).attr( 'data-type' ); const comment = $( '.edac-details-rule-records-record-ignore-comment', $( this ).parent() @@ -313,8 +326,9 @@ action: 'edac_insert_ignore_data', ids, comment, - ignore_action, - ignore_type, + ignore_action: ignoreAction, + ignore_type: ignoreType, + // eslint-disable-next-line camelcase nonce: edac_script_vars.nonce, }, } ).done( function ( response ) { @@ -324,14 +338,14 @@ const record = '#edac-details-rule-records-record-' + data.ids[ 0 ]; - const ignore_action = - data.action == 'enable' ? 'disable' : 'enable'; - const comment_disabled = - data.action == 'enable' ? true : false; - const actions_ignore_label = - data.action == 'enable' ? 'Ignored' : 'Ignore'; - const ignore_submit_label = - data.action == 'enable' + const doneIgnoreAction = + data.action === 'enable' ? 'disable' : 'enable'; + const doneCommentDisabled = + data.action === 'enable' ? true : false; + const doneActionsIgnoreLabel = + data.action === 'enable' ? 'Ignored' : 'Ignore'; + const ignoreSubmitLabel = + data.action === 'enable' ? 'Stop Ignoring' : 'Ignore This ' + data.type; const username = data.user @@ -344,12 +358,12 @@ $( record + ' .edac-details-rule-records-record-ignore-submit' - ).attr( 'data-action', ignore_action ); + ).attr( 'data-action', doneIgnoreAction ); $( record + ' .edac-details-rule-records-record-ignore-comment' - ).attr( 'disabled', comment_disabled ); - if ( data.action != 'enable' ) { + ).attr( 'disabled', doneCommentDisabled ); + if ( data.action !== 'enable' ) { $( record + ' .edac-details-rule-records-record-ignore-comment' @@ -367,16 +381,16 @@ $( record + ' .edac-details-rule-records-record-actions-ignore-label' - ).html( actions_ignore_label ); + ).html( doneActionsIgnoreLabel ); $( ".edac-details-rule-records-record-actions-ignore[data-id='" + ids[ 0 ] + "'] .edac-details-rule-records-record-actions-ignore-label" - ).html( actions_ignore_label ); // pro + ).html( doneActionsIgnoreLabel ); // pro $( record + ' .edac-details-rule-records-record-ignore-submit-label' - ).html( ignore_submit_label ); + ).html( ignoreSubmitLabel ); $( record + ' .edac-details-rule-records-record-ignore-info-user' @@ -392,12 +406,12 @@ let count = parseInt( $( '.edac-details-rule-count', rule ).html() ); - if ( data.action == 'enable' ) { + if ( data.action === 'enable' ) { count--; - } else if ( data.action == 'disable' ) { + } else if ( data.action === 'disable' ) { count++; } - if ( count == 0 ) { + if ( count === 0 ) { $( '.edac-details-rule-count', rule @@ -411,19 +425,19 @@ $( '.edac-details-rule-count', rule ).html( count ); // Update ignore rule count - let count_ignore = parseInt( + let countIgnore = parseInt( $( '.edac-details-rule-count-ignore', rule ).html() ); - //console.log(count_ignore); - if ( data.action == 'enable' ) { - count_ignore++; - } else if ( data.action == 'disable' ) { - count_ignore--; + //console.log(countIgnore); + if ( data.action === 'enable' ) { + countIgnore++; + } else if ( data.action === 'disable' ) { + countIgnore--; } - if ( count_ignore == 0 ) { + if ( countIgnore === 0 ) { $( '.edac-details-rule-count-ignore', rule @@ -434,9 +448,9 @@ rule ).show(); } - count_ignore.toString(); + countIgnore.toString(); $( '.edac-details-rule-count-ignore', rule ).html( - count_ignore + ' Ignored Items' + countIgnore + ' Ignored Items' ); // refresh page on ignore or unignore in pro @@ -448,9 +462,11 @@ 'accessibility-checker_page_accessibility_checker_ignored' ) ) { + // eslint-disable-next-line no-undef location.reload( true ); } } else { + // eslint-disable-next-line no-console console.log( response ); } } ); @@ -461,7 +477,7 @@ /** * Check if Gutenberg is active */ - function edac_gutenberg_active() { + function edacGutenbergActive() { // return false if widgets page if ( document.body.classList.contains( 'widgets-php' ) ) return false; @@ -475,30 +491,31 @@ */ if ( $( '.edac-review-notice' ).length ) { $( '.edac-review-notice-review' ).on( 'click', function () { - edac_review_notice_ajax( 'stop', true ); + edacReviewNoticeAjax( 'stop', true ); } ); $( '.edac-review-notice-remind' ).on( 'click', function () { - edac_review_notice_ajax( 'pause', false ); + edacReviewNoticeAjax( 'pause', false ); } ); $( '.edac-review-notice-dismiss' ).on( 'click', function () { - edac_review_notice_ajax( 'stop', false ); + edacReviewNoticeAjax( 'stop', false ); } ); } - function edac_review_notice_ajax( review_action, redirect ) { + function edacReviewNoticeAjax( reviewAction, redirect ) { $.ajax( { url: ajaxurl, method: 'GET', data: { action: 'edac_review_notice_ajax', - review_action, + review_action: reviewAction, + // eslint-disable-next-line camelcase nonce: edac_script_vars.nonce, }, } ).done( function ( response ) { if ( true === response.success ) { - const response_json = $.parseJSON( response.data ); + const responseJSON = $.parseJSON( response.data ); $( '.edac-review-notice' ).fadeOut(); if ( redirect ) { window.location.href = @@ -515,21 +532,22 @@ */ if ( $( '.edac_password_protected_notice' ).length ) { $( '.edac_password_protected_notice' ).on( 'click', function () { - edac_password_protected_notice_ajax(); + edacPasswordProtectedNoticeAjax(); } ); } - function edac_password_protected_notice_ajax() { + function edacPasswordProtectedNoticeAjax() { $.ajax( { url: ajaxurl, method: 'GET', data: { action: 'edac_password_protected_notice_ajax', + // eslint-disable-next-line camelcase nonce: edac_script_vars.nonce, }, } ).done( function ( response ) { if ( true === response.success ) { - const response_json = $.parseJSON( response.data ); + const responseJSON = $.parseJSON( response.data ); } else { //console.log(response); } @@ -541,7 +559,7 @@ */ if ( $( '.edac_gaad_notice' ).length ) { $( '.edac_gaad_notice .notice-dismiss' ).on( 'click', function () { - edac_gaad_notice_ajax( 'edac_gaad_notice_ajax' ); + edacGaadNoticeAjax( 'edac_gaad_notice_ajax' ); } ); } @@ -552,19 +570,23 @@ $( '.edac_black_friday_notice .notice-dismiss' ).on( 'click', function () { - edac_gaad_notice_ajax( 'edac_black_friday_notice_ajax' ); + edacGaadNoticeAjax( 'edac_black_friday_notice_ajax' ); } ); } - function edac_gaad_notice_ajax( function_name = null ) { + function edacGaadNoticeAjax( functionName = null ) { $.ajax( { url: ajaxurl, method: 'GET', - data: { action: function_name, nonce: edac_script_vars.nonce }, + data: { + action: functionName, + // eslint-disable-next-line camelcase + nonce: edac_script_vars.nonce, + }, } ).done( function ( response ) { if ( true === response.success ) { - const response_json = $.parseJSON( response.data ); + const responseJSON = $.parseJSON( response.data ); } else { //console.log(response); } @@ -572,17 +594,17 @@ } if ( $( '.edac-summary' ).length ) { - refresh_summary_and_readability(); + refreshSummaryAndReadability(); } if ( $( '.edac-details' ).length ) { - edac_details_ajax(); - ignore_submit(); + edacDetailsAjax(); + ignoreSubmit(); } if ( $( '.edac-details-rule-records-record-ignore' ).length ) { - ignore_submit(); + ignoreSubmit(); } if ( $( '.edac-readability' ).length ) { - refresh_summary_and_readability(); + refreshSummaryAndReadability(); } $( '#dismiss_welcome_cta' ).on( 'click', function () { @@ -604,10 +626,9 @@ /** * Handle widget modal close click - * @param {*} event - * @param e + * @param {Event} e - The event object */ - function edac_widget_modal_content_close( e ) { + function edacWidgetModalContentClose( e ) { const modal = e.target.closest( '.edac-widget-modal' ); if ( modal ) { modal.style.display = 'none'; @@ -623,13 +644,13 @@ }, } ); } - const modal_close_btn = document.querySelector( + const modalCloseBtn = document.querySelector( '.edac-widget-modal-content-close' ); - if ( modal_close_btn ) { - modal_close_btn.addEventListener( + if ( modalCloseBtn ) { + modalCloseBtn.addEventListener( 'click', - edac_widget_modal_content_close + edacWidgetModalContentClose ); } } ); @@ -653,6 +674,7 @@ window.addEventListener( 'load', function () { } postData( + // eslint-disable-next-line camelcase edac_script_vars.edacApiUrl + '/clear-cached-scans-stats' ).then( ( data ) => { if ( data.success ) { @@ -661,155 +683,154 @@ window.addEventListener( 'load', function () { } // Reload the current page - location.reload(); + window.location.reload(); } } ); } ); } - edac_timestamp_to_local(); + edacTimestampToLocal(); } ); // Fill the dashboard widget const fillDashboardWidget = () => { + // eslint-disable-next-line camelcase getData( edac_script_vars.edacApiUrl + '/scans-stats' ) .then( ( data ) => { if ( data.success ) { // Set passed % - const passed_percentage = data.stats.passed_percentage; - const passed_percentage_formatted = + const passedPercentage = data.stats.passed_percentage; + const passedPercentageFormatted = data.stats.passed_percentage_formatted; - const passed_percentage_el = document.querySelector( + const passedPercentageEl = document.querySelector( '#edac-summary-passed' ); - if ( passed_percentage_el ) { - passed_percentage_el.setAttribute( + if ( passedPercentageEl ) { + passedPercentageEl.setAttribute( 'aria-valuenow', - passed_percentage + passedPercentage ); - passed_percentage_el.style.background = + passedPercentageEl.style.background = 'radial-gradient(closest-side, white 85%, transparent 80% 100%), conic-gradient(#006600 ' + - passed_percentage + + passedPercentage + '%, #e2e4e7 0)'; } - const passed_percentage_text_el = document.querySelector( + const passedPercentageTextEl = document.querySelector( '#edac-summary-passed .edac-progress-percentage' ); - if ( passed_percentage_text_el ) { - passed_percentage_text_el.textContent = - passed_percentage_formatted; + if ( passedPercentageTextEl ) { + passedPercentageTextEl.textContent = + passedPercentageFormatted; } - // Set completed_at - const completed_at = data.stats.fullscan_completed_at; - const completed_at_formatted = + // Set completedAt + const completedAt = data.stats.fullscan_completed_at; + const completedAtFormatted = data.stats.fullscan_completed_at_formatted; - const completed_at_el = document.querySelector( + const completedAtEl = document.querySelector( '#edac-summary-info-date' ); - completed_at_el.textContent = completed_at_formatted; + completedAtEl.textContent = completedAtFormatted; /* const expires_at = data.stats.expires_at; const now = Date.now(); const mins_to_exp = Math.round((expires_at - Math.floor(now / 1000))/60); const cache_hit = data.stats.cache_hit; - if(completed_at_el && completed_at){ - completed_at_el.textContent = completed_at; - completed_at_el.setAttribute('data-edac-cache-hit', cache_hit); - completed_at_el.setAttribute('data-edac-cache-mins-to-expiration', mins_to_exp + ' minutes'); + if(completedAtEl && completedAt){ + completedAtEl.textContent = completedAt; + completedAtEl.setAttribute('data-edac-cache-hit', cache_hit); + completedAtEl.setAttribute('data-edac-cache-mins-to-expiration', mins_to_exp + ' minutes'); } */ // scanned - const posts_scanned = data.stats.posts_scanned; - const posts_scanned_formatted = + const postsScanned = data.stats.posts_scanned; + const postsScannedFormatted = data.stats.posts_scanned_formatted; - const posts_scanned_el = document.querySelector( + const postsScannedEl = document.querySelector( '#edac-summary-info-count' ); - if ( posts_scanned_el ) { - posts_scanned_el.textContent = posts_scanned_formatted; + if ( postsScannedEl ) { + postsScannedEl.textContent = postsScannedFormatted; } // errors const errors = data.stats.distinct_errors_without_contrast; - const errors_formatted = + const errorsFormatted = data.stats.distinct_errors_without_contrast_formatted; - const errors_container_el = document.querySelector( + const errorsContainerEl = document.querySelector( '.edac-summary-info-stats-box-error' ); - if ( errors > 0 && errors_container_el ) { - errors_container_el.classList.add( 'has-errors' ); + if ( errors > 0 && errorsContainerEl ) { + errorsContainerEl.classList.add( 'has-errors' ); } - const errors_el = document.querySelector( + const errorsEl = document.querySelector( '#edac-summary-info-errors' ); - if ( errors_el ) { - errors_el.textContent = errors_formatted; + if ( errorsEl ) { + errorsEl.textContent = errorsFormatted; } // constrast errors - const contrast_errors = data.stats.distinct_contrast_errors; - const contrast_errors_formatted = + const contrastErrors = data.stats.distinct_contrast_errors; + const contrastErrorsFormatted = data.stats.distinct_contrast_errors_formatted; - const contrast_container_el = document.querySelector( + const contrastContainerEl = document.querySelector( '.edac-summary-info-stats-box-contrast' ); - if ( errors > 0 && contrast_container_el ) { - contrast_container_el.classList.add( 'has-errors' ); + if ( errors > 0 && contrastContainerEl ) { + contrastContainerEl.classList.add( 'has-errors' ); } - const contrast_errors_el = document.querySelector( + const contrastErrorsEl = document.querySelector( '#edac-summary-info-contrast-errors' ); - if ( contrast_errors_el ) { - contrast_errors_el.textContent = contrast_errors_formatted; + if ( contrastErrorsEl ) { + contrastErrorsEl.textContent = contrastErrorsFormatted; } // warnings const warnings = data.stats.distinct_warnings; - const warnings_formatted = + const warningsFormatted = data.stats.distinct_warnings_formatted; - const warnings_container_el = document.querySelector( + const warningsContainerEl = document.querySelector( '.edac-summary-info-stats-box-warning' ); - if ( warnings > 0 && warnings_container_el ) { - warnings_container_el.classList.add( 'has-warning' ); + if ( warnings > 0 && warningsContainerEl ) { + warningsContainerEl.classList.add( 'has-warning' ); } - const warnings_el = document.querySelector( + const warningsEl = document.querySelector( '#edac-summary-info-warnings' ); - if ( warnings_el ) { - warnings_el.textContent = warnings_formatted; + if ( warningsEl ) { + warningsEl.textContent = warningsFormatted; } // summary notice - if ( errors + contrast_errors + warnings > 0 ) { - const has_issues_notice_el = document.querySelector( + if ( errors + contrastErrors + warnings > 0 ) { + const hasIssuesNoticeEl = document.querySelector( '.edac-summary-notice-has-issues' ); - if ( has_issues_notice_el ) { - has_issues_notice_el.classList.remove( 'edac-hidden' ); + if ( hasIssuesNoticeEl ) { + hasIssuesNoticeEl.classList.remove( 'edac-hidden' ); } } else { - const has_no_issues_notice_el = document.querySelector( + const hasNoIssuesNoticeEl = document.querySelector( '.edac-summary-notice-no-issues' ); - if ( has_no_issues_notice_el && posts_scanned > 0 ) { - has_no_issues_notice_el.classList.remove( - 'edac-hidden' - ); + if ( hasNoIssuesNoticeEl && postsScanned > 0 ) { + hasNoIssuesNoticeEl.classList.remove( 'edac-hidden' ); } } // truncated notice - const is_truncated = data.stats.is_truncated; - const is_truncated_el = document.querySelector( + const isTruncated = data.stats.is_truncated; + const isTruncatedEl = document.querySelector( '.edac-summary-notice-is-truncated' ); - if ( is_truncated_el && is_truncated ) { - is_truncated_el.classList.remove( 'edac-hidden' ); + if ( isTruncatedEl && isTruncated ) { + isTruncatedEl.classList.remove( 'edac-hidden' ); } const wrapper = document.querySelector( @@ -819,48 +840,49 @@ const fillDashboardWidget = () => { wrapper.classList.remove( 'edac-hidden' ); } - //edac_timestamp_to_local(); + //edacTimestampToLocal(); } } ) .catch( ( e ) => { //TODO: } ); + // eslint-disable-next-line camelcase getData( edac_script_vars.edacApiUrl + '/scans-stats-by-post-types' ) .then( ( data ) => { if ( data.success ) { Object.entries( data.stats ).forEach( ( [ key, value ] ) => { if ( data.stats[ key ] ) { const errors = value.distinct_errors_without_contrast; - const errors_formatted = + const errorsFormatted = value.distinct_errors_without_contrast_formatted; - const contrast_errors = value.distinct_contrast_errors; - const contrast_errors_formatted = + const contrastErrors = value.distinct_contrast_errors; + const contrastErrorsFormatted = value.distinct_contrast_errors_formatted; const warnings = value.distinct_warnings; - const warnings_formatted = + const warningsFormatted = value.distinct_warnings_formatted; - const errors_el = document.querySelector( + const errorsEl = document.querySelector( '#' + key + '-errors' ); - if ( errors_el ) { - errors_el.textContent = errors_formatted; + if ( errorsEl ) { + errorsEl.textContent = errorsFormatted; } - const contrast_errors_el = document.querySelector( + const contrastErrorsEl = document.querySelector( '#' + key + '-contrast-errors' ); - if ( contrast_errors_el ) { - contrast_errors_el.textContent = - contrast_errors_formatted; + if ( contrastErrorsEl ) { + contrastErrorsEl.textContent = + contrastErrorsFormatted; } - const warnings_el = document.querySelector( + const warningsEl = document.querySelector( '#' + key + '-warnings' ); - if ( warnings_el ) { - warnings_el.textContent = warnings_formatted; + if ( warningsEl ) { + warningsEl.textContent = warningsFormatted; } } else { //We aren't tracking stats for this post type @@ -873,18 +895,18 @@ const fillDashboardWidget = () => { wrapper.classList.remove( 'edac-hidden' ); } - edac_timestamp_to_local(); + edacTimestampToLocal(); } ) .catch( ( e ) => { + // eslint-disable-next-line no-console console.log( e ); - //TODO: } ); }; /** * Helper function to convert unixtime timestamp to the local date time. */ -function edac_timestamp_to_local() { +function edacTimestampToLocal() { const options = { year: 'numeric', month: 'short', day: 'numeric' }; const elements = document.querySelectorAll( '.edac-timestamp-to-local' ); @@ -893,13 +915,13 @@ function edac_timestamp_to_local() { if ( /^[0-9]+$/.test( element.textContent ) ) { //if only numbers - const unixtime_in_seconds = element.textContent; + const unixtimeInSeconds = element.textContent; - const d = new Date( unixtime_in_seconds * 1000 ).toLocaleDateString( + const d = new Date( unixtimeInSeconds * 1000 ).toLocaleDateString( [], options ); - const t = new Date( unixtime_in_seconds * 1000 ).toLocaleTimeString( + const t = new Date( unixtimeInSeconds * 1000 ).toLocaleTimeString( [], { timeStyle: 'short' } ); @@ -933,6 +955,7 @@ const getData = async ( url = '', data = {} ) => { const response = await fetch( url, { method: 'GET', headers: { + // eslint-disable-next-line camelcase 'X-WP-Nonce': edac_script_vars.restNonce, }, } ); @@ -943,6 +966,7 @@ const postData = async ( url = '', data = {} ) => { const response = await fetch( url, { method: 'POST', headers: { + // eslint-disable-next-line camelcase 'X-WP-Nonce': edac_script_vars.restNonce, }, body: JSON.stringify( data ), From aae7968ce7dc06846024eedd11b882e385a04fe9 Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Wed, 13 Dec 2023 15:37:27 +0200 Subject: [PATCH 05/10] add an extra script & auto-fix all issues that can be fixed --- package.json | 1 + src/app/index.js | 1572 +++++++++-------- src/app/scanner/checks/always-fail.js | 28 +- src/app/scanner/index.js | 108 +- .../scanner/rules/color-contrast-failure.js | 50 +- src/app/scanner/rules/custom-rule-1.js | 16 +- 6 files changed, 895 insertions(+), 880 deletions(-) diff --git a/package.json b/package.json index 89d76440..c3c3eff8 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "dist": "npx webpack --mode production && composer install --no-dev && composer dump-autoload --no-dev -o && wp-scripts plugin-zip && mv accessibility-checker.zip ./dist && composer install", "lint": "./vendor/bin/phpcs && npm run lint:js", "lint:js": "wp-scripts lint-js", + "lint:js:fix": "wp-scripts lint-js --fix", "test:e2e": "npx wp-env clean tests && npx playwright test ./e2e/specs" }, "files": [ diff --git a/src/app/index.js b/src/app/index.js index a013ef9d..c293d0ed 100644 --- a/src/app/index.js +++ b/src/app/index.js @@ -1,61 +1,84 @@ -import { computePosition, autoUpdate, shift, offset, inline } from '@floating-ui/dom'; +import { + computePosition, + autoUpdate, + shift, + offset, + inline, +} from '@floating-ui/dom'; import { createFocusTrap } from 'focus-trap'; import { isFocusable, isTabbable } from 'tabbable'; import { Notyf } from 'notyf'; import { scan } from './scanner'; -let JS_SCAN_ENABLED = false; -let INFO_ENABLED = false; -let DEBUG_ENABLED = false; +const JS_SCAN_ENABLED = false; +const INFO_ENABLED = false; +const DEBUG_ENABLED = false; let SCAN_INTERVAL_IN_SECONDS = 30; -if (edac_script_vars.mode === 'full-scan') { +if ( edac_script_vars.mode === 'full-scan' ) { SCAN_INTERVAL_IN_SECONDS = 3; } - class AccessibilityCheckerHighlight { - /** * Constructor + * @param settings */ - constructor(settings = {}) { - + constructor( settings = {} ) { const defaultSettings = { - showIgnored: false - } + showIgnored: false, + }; this.settings = { ...defaultSettings, ...settings }; this.addHighlightPanel(); - this.nextButton = document.querySelector('#edac-highlight-next'); - this.previousButton = document.querySelector('#edac-highlight-previous'); - this.panelToggle = document.querySelector('#edac-highlight-panel-toggle'); - this.closePanel = document.querySelector('#edac-highlight-panel-controls-close'); - this.panelDescription = document.querySelector('#edac-highlight-panel-description'); - this.panelControls = document.querySelector('#edac-highlight-panel-controls'); - this.descriptionCloseButton = document.querySelector('.edac-highlight-panel-description-close'); + this.nextButton = document.querySelector( '#edac-highlight-next' ); + this.previousButton = document.querySelector( + '#edac-highlight-previous' + ); + this.panelToggle = document.querySelector( + '#edac-highlight-panel-toggle' + ); + this.closePanel = document.querySelector( + '#edac-highlight-panel-controls-close' + ); + this.panelDescription = document.querySelector( + '#edac-highlight-panel-description' + ); + this.panelControls = document.querySelector( + '#edac-highlight-panel-controls' + ); + this.descriptionCloseButton = document.querySelector( + '.edac-highlight-panel-description-close' + ); this.issues = null; this.currentButtonIndex = null; - this.urlParameter = this.get_url_parameter('edac'); + this.urlParameter = this.get_url_parameter( 'edac' ); this.currentIssueStatus = null; this.tooltips = []; - this.panelControlsFocusTrap = createFocusTrap('#' + this.panelControls.id, { - clickOutsideDeactivates: true, - escapeDeactivates: () => { - this.panelClose(); + this.panelControlsFocusTrap = createFocusTrap( + '#' + this.panelControls.id, + { + clickOutsideDeactivates: true, + escapeDeactivates: () => { + this.panelClose(); + }, } - }); - this.panelDescriptionFocusTrap = createFocusTrap('#' + this.panelDescription.id, { - clickOutsideDeactivates: true, - escapeDeactivates: () => { - this.descriptionClose(); + ); + this.panelDescriptionFocusTrap = createFocusTrap( + '#' + this.panelDescription.id, + { + clickOutsideDeactivates: true, + escapeDeactivates: () => { + this.descriptionClose(); + }, } + ); - }); - - this.disableStylesButton = document.querySelector('#edac-highlight-disable-styles'); + this.disableStylesButton = document.querySelector( + '#edac-highlight-disable-styles' + ); this.stylesDisabled = false; this.originalCss = []; @@ -63,90 +86,88 @@ class AccessibilityCheckerHighlight { } /** - * This function initializes the component by setting up event listeners + * This function initializes the component by setting up event listeners * and managing the initial state of the panel based on the URL parameter. */ init() { // Add event listeners for 'next' and 'previous' buttons - this.nextButton.addEventListener('click', (event) => { + this.nextButton.addEventListener( 'click', ( event ) => { this.highlightFocusNext(); this.focusTrapDescription(); - }); - this.previousButton.addEventListener('click', (event) => { + } ); + this.previousButton.addEventListener( 'click', ( event ) => { this.highlightFocusPrevious(); this.focusTrapDescription(); - }); + } ); // Manage panel open/close operations - this.panelToggle.addEventListener('click', () => { + this.panelToggle.addEventListener( 'click', () => { this.panelOpen(); this.focusTrapControls(); - }); - this.closePanel.addEventListener('click', () => { + } ); + this.closePanel.addEventListener( 'click', () => { this.panelClose(); this.panelControlsFocusTrap.deactivate(); this.panelDescriptionFocusTrap.deactivate(); this.enableStyles(); - }); + } ); // Close description when close button is clicked - this.descriptionCloseButton.addEventListener('click', () => this.descriptionClose()); + this.descriptionCloseButton.addEventListener( 'click', () => + this.descriptionClose() + ); // Handle disable/enable styles - this.disableStylesButton.addEventListener('click', () => { - if (this.stylesDisabled) { + this.disableStylesButton.addEventListener( 'click', () => { + if ( this.stylesDisabled ) { this.enableStyles(); } else { this.disableStyles(); } - }); - - + } ); // Open panel if a URL parameter exists - if (this.urlParameter) { - this.panelOpen(this.urlParameter); + if ( this.urlParameter ) { + this.panelOpen( this.urlParameter ); } } /** * This function tries to find an element on the page that matches a given HTML snippet. - * It parses the HTML snippet, and compares the outer HTML of the parsed element - * with all elements present on the page. If a match is found, it + * It parses the HTML snippet, and compares the outer HTML of the parsed element + * with all elements present on the page. If a match is found, it * adds a tooltip, checks if the element is focusable, and then returns the element. * If no matching element is found, or if the parsed HTML snippet does not contain an element, * it returns null. * * @param {Object} value - Object containing the HTML snippet to be matched. * @param {number} index - Index of the element being searched. - * @returns {HTMLElement|null} - Returns the matching HTML element, or null if no match is found. + * @return {HTMLElement|null} - Returns the matching HTML element, or null if no match is found. */ - findElement(value, index) { - - + findElement( value, index ) { // Parse the HTML snippet let htmlToFind = value.object; const parser = new DOMParser(); - const parsedHtml = parser.parseFromString(htmlToFind, 'text/html'); + const parsedHtml = parser.parseFromString( htmlToFind, 'text/html' ); const firstParsedElement = parsedHtml.body.firstElementChild; - - if (firstParsedElement) { + + if ( firstParsedElement ) { htmlToFind = firstParsedElement.outerHTML; } - // Compare the outer HTML of the parsed element with all elements on the page - const allElements = document.body.querySelectorAll('*'); + const allElements = document.body.querySelectorAll( '*' ); - for (const element of allElements) { - - if (element.outerHTML.replace(/\W/g, '') === htmlToFind.replace(/\W/g, '')) { - - const tooltip = this.addTooltip(element, value, index); + for ( const element of allElements ) { + if ( + element.outerHTML.replace( /\W/g, '' ) === + htmlToFind.replace( /\W/g, '' ) + ) { + const tooltip = this.addTooltip( element, value, index ); - this.issues[index].tooltip = tooltip.tooltip; + this.issues[ index ].tooltip = tooltip.tooltip; - this.tooltips.push(tooltip); + this.tooltips.push( tooltip ); return element; } @@ -162,111 +183,113 @@ class AccessibilityCheckerHighlight { * Note: This function assumes that `edac_script_vars` is a global variable containing necessary data. */ highlightAjax() { - const self = this; - return new Promise(function (resolve, reject) { + return new Promise( function ( resolve, reject ) { const xhr = new XMLHttpRequest(); - const url = edac_script_vars.ajaxurl + '?action=edac_frontend_highlight_ajax&post_id=' + edac_script_vars.postID + '&nonce=' + edac_script_vars.nonce; + const url = + edac_script_vars.ajaxurl + + '?action=edac_frontend_highlight_ajax&post_id=' + + edac_script_vars.postID + + '&nonce=' + + edac_script_vars.nonce; - self.showWait(true); + self.showWait( true ); - xhr.open('GET', url); + xhr.open( 'GET', url ); xhr.onload = function () { - if (xhr.status === 200) { + if ( xhr.status === 200 ) { + self.showWait( false ); - self.showWait(false); + const response = JSON.parse( xhr.responseText ); + if ( true === response.success ) { + const response_json = JSON.parse( response.data ); - const response = JSON.parse(xhr.responseText); - if (true === response.success) { - const response_json = JSON.parse(response.data); - - if (self.settings.showIgnored) { - resolve(response_json); + if ( self.settings.showIgnored ) { + resolve( response_json ); } else { resolve( - response_json.filter(item => (item.id == self.urlParameter || item.rule_type !== 'ignored')) + response_json.filter( + ( item ) => + item.id == self.urlParameter || + item.rule_type !== 'ignored' + ) ); } - } else { - resolve([]); + resolve( [] ); //console.log(response); } } else { + self.showWait( false ); - self.showWait(false); + info( 'Request failed. Returned status of ' + xhr.status ); - info('Request failed. Returned status of ' + xhr.status); - - reject({ + reject( { status: xhr.status, - statusText: xhr.statusText - }); + statusText: xhr.statusText, + } ); } }; xhr.onerror = function () { + self.showWait( false ); - self.showWait(false); - - reject({ + reject( { status: xhr.status, - statusText: xhr.statusText - }); - } + statusText: xhr.statusText, + } ); + }; xhr.send(); - }); + } ); } /** * This function toggles showing Wait + * @param status */ - showWait(status = true) { - if (status) { - document.querySelector('body').classList.add('edac-app-wait'); + showWait( status = true ) { + if ( status ) { + document.querySelector( 'body' ).classList.add( 'edac-app-wait' ); } else { - document.querySelector('body').classList.remove('edac-app-wait'); + document + .querySelector( 'body' ) + .classList.remove( 'edac-app-wait' ); } } - /** * This function removes the highlight/tooltip buttons and runs cleanups for each. */ removeHighlightButtons() { - - this.tooltips.forEach((item) => { - + this.tooltips.forEach( ( item ) => { //remove click listener - item.tooltip.removeEventListener('click', item.listeners.onClick); + item.tooltip.removeEventListener( 'click', item.listeners.onClick ); //remove position/resize listener: https://floating-ui.com/docs/autoUpdate item.listeners.cleanup(); + } ); - }); - - const buttons = document.querySelectorAll('.edac-highlight-btn'); - buttons.forEach((button) => { + const buttons = document.querySelectorAll( '.edac-highlight-btn' ); + buttons.forEach( ( button ) => { button.remove(); - }); - + } ); } - /** * This function adds a new button element to the DOM, which acts as a tooltip for the highlighted element. - * + * * @param {HTMLElement} element - The DOM element before which the tooltip button will be inserted. - * @param {Object} value - An object containing properties used to customize the tooltip button. - * @param {Number} index - The index of the element being processed. + * @param {Object} value - An object containing properties used to customize the tooltip button. + * @param {number} index - The index of the element being processed. * @return {Object} - information about the tooltip */ - addTooltip(element, value, index) { + addTooltip( element, value, index ) { // Create the tooltip. - let tooltip = document.createElement('button'); - tooltip.classList = 'edac-highlight-btn edac-highlight-btn-' + value.rule_type; + const tooltip = document.createElement( 'button' ); + tooltip.classList = + 'edac-highlight-btn edac-highlight-btn-' + value.rule_type; tooltip.ariaLabel = value.rule_title; tooltip.ariaExpanded = 'false'; //tooltip.ariaControls = 'edac-highlight-tooltip-' + value.id; @@ -274,94 +297,86 @@ class AccessibilityCheckerHighlight { //add data-id to the tooltip/button so we can find it later. tooltip.dataset.id = value.id; - const onClick = (e) => { + const onClick = ( e ) => { const id = e.currentTarget.dataset.id; - this.showIssue(id); + this.showIssue( id ); this.focusTrapDescription(); }; - tooltip.addEventListener('click', onClick); - + tooltip.addEventListener( 'click', onClick ); // Add the tooltip to the page. - document.body.append(tooltip); + document.body.append( tooltip ); const updatePosition = function () { - - computePosition(element, tooltip, { + computePosition( element, tooltip, { placement: 'top-start', middleware: [], - }).then(({ x, y, middlewareData, placement }) => { - + } ).then( ( { x, y, middlewareData, placement } ) => { const elRect = element.getBoundingClientRect(); - const elHeight = element.offsetHeight == undefined ? 0 : element.offsetHeight; - const elWidth = element.offsetWidth == undefined ? 0 : element.offsetWidth; - const tooltipHeight = tooltip.offsetHeight == undefined ? 0 : tooltip.offsetHeight; - const tooltipWidth = tooltip.offsetWidth == undefined ? 0 : tooltip.offsetWidth; - + const elHeight = + element.offsetHeight == undefined + ? 0 + : element.offsetHeight; + const elWidth = + element.offsetWidth == undefined ? 0 : element.offsetWidth; + const tooltipHeight = + tooltip.offsetHeight == undefined + ? 0 + : tooltip.offsetHeight; + const tooltipWidth = + tooltip.offsetWidth == undefined ? 0 : tooltip.offsetWidth; let top = 0; - let left = 0; + const left = 0; - if (tooltipHeight <= (elHeight * .8)) { + if ( tooltipHeight <= elHeight * 0.8 ) { top = tooltipHeight; } - if (tooltipWidth >= (elWidth * .8)) { + if ( tooltipWidth >= elWidth * 0.8 ) { top = 0; } - if (elRect.left < tooltipWidth) { + if ( elRect.left < tooltipWidth ) { x = 0; } - if (elRect.left > window.screen) { + if ( elRect.left > window.screen ) { x = window.screen.width - tooltipWidth; } - if (elRect.top < tooltipHeight) { + if ( elRect.top < tooltipHeight ) { y = 0; } - Object.assign(tooltip.style, { - left: `${x + left}px`, - top: `${y + top}px` - }); - - }); - + Object.assign( tooltip.style, { + left: `${ x + left }px`, + top: `${ y + top }px`, + } ); + } ); }; - // Place the tooltip at the element's position on the page. - // See: https://floating-ui.com/docs/autoUpdate - const cleanup = autoUpdate( - element, - tooltip, - updatePosition, { + // See: https://floating-ui.com/docs/autoUpdate + const cleanup = autoUpdate( element, tooltip, updatePosition, { ancestorScroll: true, ancestorResize: true, elementResize: true, layoutShift: true, - animationFrame: true // TODO: Disable styles sometimes causes the toolbar to disappear until a scroll or resize event. This may help - but is expensive. - - - } - ); - + animationFrame: true, // TODO: Disable styles sometimes causes the toolbar to disappear until a scroll or resize event. This may help - but is expensive. + } ); return { element, tooltip, listeners: { onClick, - cleanup - } + cleanup, + }, }; - } - /** * This function adds a new div element to the DOM, which contains the accessibility checker panel. */ @@ -392,35 +407,37 @@ class AccessibilityCheckerHighlight { `; - document.body.insertAdjacentHTML('afterbegin', newElement); + document.body.insertAdjacentHTML( 'afterbegin', newElement ); } /** * This function highlights the next element on the page. It uses the 'currentButtonIndex' property to keep track of the current element. */ highlightFocusNext = () => { - if (this.currentButtonIndex == null) { + if ( this.currentButtonIndex == null ) { this.currentButtonIndex = 0; } else { - this.currentButtonIndex = (this.currentButtonIndex + 1) % this.issues.length; + this.currentButtonIndex = + ( this.currentButtonIndex + 1 ) % this.issues.length; } - const id = this.issues[this.currentButtonIndex]['id']; - this.showIssue(id); - } - + const id = this.issues[ this.currentButtonIndex ].id; + this.showIssue( id ); + }; /** * This function highlights the previous element on the page. It uses the 'currentButtonIndex' property to keep track of the current element. */ highlightFocusPrevious = () => { - if (this.currentButtonIndex == null) { + if ( this.currentButtonIndex == null ) { this.currentButtonIndex = this.issues.length - 1; } else { - this.currentButtonIndex = (this.currentButtonIndex - 1 + this.issues.length) % this.issues.length; + this.currentButtonIndex = + ( this.currentButtonIndex - 1 + this.issues.length ) % + this.issues.length; } - const id = this.issues[this.currentButtonIndex]['id']; - this.showIssue(id); - } + const id = this.issues[ this.currentButtonIndex ].id; + this.showIssue( id ); + }; /** * This function sets a focus trap on the controls panel @@ -429,11 +446,10 @@ class AccessibilityCheckerHighlight { this.panelDescriptionFocusTrap.deactivate(); this.panelControlsFocusTrap.activate(); - setTimeout(() => { + setTimeout( () => { this.panelControls.focus(); - }, 100); //give render time to complete. - - } + }, 100 ); //give render time to complete. + }; /** * This function sets a focus trap on the description panel @@ -442,58 +458,65 @@ class AccessibilityCheckerHighlight { this.panelControlsFocusTrap.deactivate(); this.panelDescriptionFocusTrap.activate(); - setTimeout(() => { + setTimeout( () => { this.panelDescription.focus(); - }, 100); //give render time to complete. - - } + }, 100 ); //give render time to complete. + }; /** * This function shows an issue related to an element. * @param {string} id - The ID of the element. */ - showIssue = (id) => { - + showIssue = ( id ) => { this.removeSelectedClasses(); - if (id === undefined) { + if ( id === undefined ) { return; } - const issue = this.issues.find(issue => issue.id == id); - this.currentButtonIndex = this.issues.findIndex(issue => issue.id == id); + const issue = this.issues.find( ( issue ) => issue.id == id ); + this.currentButtonIndex = this.issues.findIndex( + ( issue ) => issue.id == id + ); const tooltip = issue.tooltip; const element = issue.element; - if (tooltip && element) { - - tooltip.classList.add('edac-highlight-btn-selected'); - element.classList.add('edac-highlight-element-selected'); + if ( tooltip && element ) { + tooltip.classList.add( 'edac-highlight-btn-selected' ); + element.classList.add( 'edac-highlight-element-selected' ); - if (element.offsetWidth < 20) { - element.classList.add('edac-highlight-element-selected-min-width'); + if ( element.offsetWidth < 20 ) { + element.classList.add( + 'edac-highlight-element-selected-min-width' + ); } - if (element.offsetHeight < 5) { - element.classList.add('edac-highlight-element-selected-min-height'); + if ( element.offsetHeight < 5 ) { + element.classList.add( + 'edac-highlight-element-selected-min-height' + ); } - element.scrollIntoView({ block: 'center' }); + element.scrollIntoView( { block: 'center' } ); - if (isFocusable(tooltip)) { + if ( isFocusable( tooltip ) ) { //issueElement.focus(); - if (!this.checkVisibility(tooltip) || !this.checkVisibility(element)) { - this.currentIssueStatus = 'The element is not visible. Try disabling styles.'; + if ( + ! this.checkVisibility( tooltip ) || + ! this.checkVisibility( element ) + ) { + this.currentIssueStatus = + 'The element is not visible. Try disabling styles.'; //TODO: console.log(`Element with id ${id} is not visible!`); } else { this.currentIssueStatus = null; } - } else { - this.currentIssueStatus = 'The element is not focusable. Try disabling styles.'; + this.currentIssueStatus = + 'The element is not focusable. Try disabling styles.'; //TODO: console.log(`Element with id ${id} is not focusable!`); } } else { @@ -501,50 +524,47 @@ class AccessibilityCheckerHighlight { //TODO: console.log(`Element with id ${id} not found in the document!`); } - this.descriptionOpen(id); - } - + this.descriptionOpen( id ); + }; /** * This function checks if a given element is visible on the page. - * + * * @param {HTMLElement} el The element to check for visibility - * @returns + * @return */ - checkVisibility = (el) => { + checkVisibility = ( el ) => { //checkVisibility is still in draft but well supported on many browsers. //See: https://drafts.csswg.org/cssom-view-1/#dom-element-checkvisibility //See: https://caniuse.com/mdn-api_element_checkvisibility - if (typeof (el.checkVisibility) !== 'function') { - + if ( typeof el.checkVisibility !== 'function' ) { //See: https://github.com/jquery/jquery/blob/main/src/css/hiddenVisibleSelectors.js - return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length); - - } else { - return el.checkVisibility({ - checkOpacity: true, // Check CSS opacity property too - checkVisibilityCSS: true // Check CSS visibility property too - }); + return !! ( + el.offsetWidth || + el.offsetHeight || + el.getClientRects().length + ); } - } - + return el.checkVisibility( { + checkOpacity: true, // Check CSS opacity property too + checkVisibilityCSS: true, // Check CSS visibility property too + } ); + }; /** * This function opens the accessibility checker panel. + * @param id */ - panelOpen(id) { - + panelOpen( id ) { this.panelControls.style.display = 'block'; this.panelToggle.style.display = 'none'; // Get the issues for this page. - this.highlightAjax().then( - (json) => { - - if(json.length == 0){ + this.highlightAjax() + .then( ( json ) => { + if ( json.length == 0 ) { this.nextButton.disabled = true; this.previousButton.disabled = true; - } else { this.nextButton.disabled = false; this.previousButton.disabled = false; @@ -552,29 +572,25 @@ class AccessibilityCheckerHighlight { this.issues = json; - json.forEach(function (value, index) { - - const element = this.findElement(value, index); - if (element !== null) { - this.issues[index].element = element; - } - - }.bind(this)); - + json.forEach( + function ( value, index ) { + const element = this.findElement( value, index ); + if ( element !== null ) { + this.issues[ index ].element = element; + } + }.bind( this ) + ); this.showIssueCount(); - if (id !== undefined) { - - this.showIssue(id); + if ( id !== undefined ) { + this.showIssue( id ); this.focusTrapDescription(); - } - } - ).catch((err) => { - //TODO: - }); - + } ) + .catch( ( err ) => { + //TODO: + } ); } /** @@ -587,74 +603,97 @@ class AccessibilityCheckerHighlight { this.removeSelectedClasses(); this.removeHighlightButtons(); - this.closePanel.removeEventListener('click', this.panelControlsFocusTrap.deactivate); + this.closePanel.removeEventListener( + 'click', + this.panelControlsFocusTrap.deactivate + ); this.panelToggle.focus(); } - /** - * This function removes the classes that indicates a button or element are selected + * This function removes the classes that indicates a button or element are selected */ removeSelectedClasses = () => { //remove selected class from previously selected buttons - const selectedButtons = document.querySelectorAll('.edac-highlight-btn-selected'); - selectedButtons.forEach((selectedButton) => { - selectedButton.classList.remove('edac-highlight-btn-selected'); - }); + const selectedButtons = document.querySelectorAll( + '.edac-highlight-btn-selected' + ); + selectedButtons.forEach( ( selectedButton ) => { + selectedButton.classList.remove( 'edac-highlight-btn-selected' ); + } ); //remove selected class from previously selected elements - const selectedElements = document.querySelectorAll('.edac-highlight-element-selected'); - selectedElements.forEach((selectedElement) => { + const selectedElements = document.querySelectorAll( + '.edac-highlight-element-selected' + ); + selectedElements.forEach( ( selectedElement ) => { selectedElement.classList.remove( 'edac-highlight-element-selected', 'edac-highlight-element-selected-min-width', 'edac-highlight-element-selected-min-height' ); - if (selectedElement.classList.length == 0) { - selectedElement.removeAttribute('class'); + if ( selectedElement.classList.length == 0 ) { + selectedElement.removeAttribute( 'class' ); } - }); - } + } ); + }; /** * This function displays the description of the issue. - * - * @param {string} dataId + * + * @param {string} dataId */ - descriptionOpen(dataId) { + descriptionOpen( dataId ) { // get the value of the property by key const searchTerm = dataId; - const keyToSearch = "id"; - const matchingObj = this.issues.find(obj => obj[keyToSearch] === searchTerm); + const keyToSearch = 'id'; + const matchingObj = this.issues.find( + ( obj ) => obj[ keyToSearch ] === searchTerm + ); - if (matchingObj) { - const descriptionTitle = document.querySelector('.edac-highlight-panel-description-title'); - const descriptionContent = document.querySelector('.edac-highlight-panel-description-content'); - const descriptionCode = document.querySelector('.edac-highlight-panel-description-code code'); + if ( matchingObj ) { + const descriptionTitle = document.querySelector( + '.edac-highlight-panel-description-title' + ); + const descriptionContent = document.querySelector( + '.edac-highlight-panel-description-content' + ); + const descriptionCode = document.querySelector( + '.edac-highlight-panel-description-code code' + ); let content = ''; // Get the index and total - content += `
${this.currentButtonIndex + 1} of ${this.issues.length}
`; - + content += `
${ + this.currentButtonIndex + 1 + } of ${ this.issues.length }
`; // Get the status of the issue - if (this.currentIssueStatus) { - content += `
${this.currentIssueStatus}
`; + if ( this.currentIssueStatus ) { + content += `
${ this.currentIssueStatus }
`; } // Get the summary of the issue content += matchingObj.summary; // Get the link to the documentation - content += `
Full Documentation`; + content += `
Full Documentation`; // Get the code button content += ``; // title and content - descriptionTitle.innerHTML = matchingObj.rule_title + ' ' + matchingObj.rule_type + ''; + descriptionTitle.innerHTML = + matchingObj.rule_title + + ' ' + + matchingObj.rule_type + + ''; // content descriptionContent.innerHTML = content; @@ -663,20 +702,29 @@ class AccessibilityCheckerHighlight { // remove any non-html from the object const htmlSnippet = matchingObj.object; const parser = new DOMParser(); - const parsedHtml = parser.parseFromString(htmlSnippet, 'text/html'); + const parsedHtml = parser.parseFromString( + htmlSnippet, + 'text/html' + ); const firstParsedElement = parsedHtml.body.firstElementChild; - if (firstParsedElement) { + if ( firstParsedElement ) { descriptionCode.innerText = firstParsedElement.outerHTML; } else { - let textNode = document.createTextNode(matchingObj.object); + const textNode = document.createTextNode( matchingObj.object ); descriptionCode.innerText = textNode.nodeValue; } // set code button listener - this.codeContainer = document.querySelector('.edac-highlight-panel-description-code'); - this.codeButton = document.querySelector('.edac-highlight-panel-description-code-button'); - this.codeButton.addEventListener('click', () => this.codeToggle()); + this.codeContainer = document.querySelector( + '.edac-highlight-panel-description-code' + ); + this.codeButton = document.querySelector( + '.edac-highlight-panel-description-code-button' + ); + this.codeButton.addEventListener( 'click', () => + this.codeToggle() + ); // close the code container each time the description is opened this.codeContainer.style.display = 'none'; @@ -694,125 +742,134 @@ class AccessibilityCheckerHighlight { this.focusTrapControls(); } - /** * This function disables all styles on the page. */ disableStyles() { - /* If the site compiles css into a combined file, our method for disabling styles will cause out app's css to break. This checks if the app's css is loading into #edac-app-css as expected. If not, then we assume the css has been combined, so we manually add it to the document. */ - if( ! document.querySelector('#edac-app-css') ){ - debug('css is combined, so adding app.css to page.'); + if ( ! document.querySelector( '#edac-app-css' ) ) { + debug( 'css is combined, so adding app.css to page.' ); - var link = document.createElement('link'); + const link = document.createElement( 'link' ); link.rel = 'stylesheet'; link.id = 'edac-app-css'; link.type = 'text/css'; - link.href = edac_script_vars.appCssUrl, - link.media = 'all'; - document.head.appendChild(link); + ( link.href = edac_script_vars.appCssUrl ), ( link.media = 'all' ); + document.head.appendChild( link ); } - - - this.originalCss = Array.from(document.head.querySelectorAll('style[type="text/css"], style, link[rel="stylesheet"]')); - - var elementsWithStyle = document.querySelectorAll('*[style]:not([class^="edac"])'); - elementsWithStyle.forEach(function (element) { - element.removeAttribute("style"); - }); + this.originalCss = Array.from( + document.head.querySelectorAll( + 'style[type="text/css"], style, link[rel="stylesheet"]' + ) + ); - this.originalCss = this.originalCss.filter(function (element) { - if (element.id === 'edac-app-css' || element.id === 'dashicons-css') { + const elementsWithStyle = document.querySelectorAll( + '*[style]:not([class^="edac"])' + ); + elementsWithStyle.forEach( function ( element ) { + element.removeAttribute( 'style' ); + } ); + + this.originalCss = this.originalCss.filter( function ( element ) { + if ( + element.id === 'edac-app-css' || + element.id === 'dashicons-css' + ) { return false; } return true; - }); + } ); document.head.dataset.css = this.originalCss; - this.originalCss.forEach(function (element) { + this.originalCss.forEach( function ( element ) { element.remove(); - }); + } ); - document.querySelector('body').classList.add('edac-app-disable-styles'); + document + .querySelector( 'body' ) + .classList.add( 'edac-app-disable-styles' ); this.stylesDisabled = true; - this.disableStylesButton.textContent = "Enable Styles"; - + this.disableStylesButton.textContent = 'Enable Styles'; } /** * This function enables all styles on the page. */ enableStyles() { - this.originalCss.forEach(function (element) { - if (element.tagName === 'STYLE') { - document.head.appendChild(element.cloneNode(true)); + this.originalCss.forEach( function ( element ) { + if ( element.tagName === 'STYLE' ) { + document.head.appendChild( element.cloneNode( true ) ); } else { - const newElement = document.createElement('link'); + const newElement = document.createElement( 'link' ); newElement.rel = 'stylesheet'; newElement.href = element.href; - document.head.appendChild(newElement); + document.head.appendChild( newElement ); } - }); + } ); - - document.querySelector('body').classList.remove('edac-app-disable-styles'); + document + .querySelector( 'body' ) + .classList.remove( 'edac-app-disable-styles' ); this.stylesDisabled = false; - this.disableStylesButton.textContent = "Disable Styles"; + this.disableStylesButton.textContent = 'Disable Styles'; } - /** * * This function retrieves the value of a given URL parameter. - * - * @param {String} sParam The name of the URL parameter to be retrieved. - * @returns {String|Boolean} Returns the value of the URL parameter, or false if the parameter is not found. + * + * @param {string} sParam The name of the URL parameter to be retrieved. + * @return {string | boolean} Returns the value of the URL parameter, or false if the parameter is not found. */ - get_url_parameter(sParam) { - let sPageURL = window.location.search.substring(1); - let sURLVariables = sPageURL.split('&'); + get_url_parameter( sParam ) { + const sPageURL = window.location.search.substring( 1 ); + const sURLVariables = sPageURL.split( '&' ); let sParameterName, i; - for (i = 0; i < sURLVariables.length; i++) { - sParameterName = sURLVariables[i].split('='); + for ( i = 0; i < sURLVariables.length; i++ ) { + sParameterName = sURLVariables[ i ].split( '=' ); - if (sParameterName[0] === sParam) { - return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]); + if ( sParameterName[ 0 ] === sParam ) { + return sParameterName[ 1 ] === undefined + ? true + : decodeURIComponent( sParameterName[ 1 ] ); } } return false; - }; + } /** * This function toggles the code container. */ codeToggle() { - if (this.codeContainer.style.display === 'none' || this.codeContainer.style.display === '') { + if ( + this.codeContainer.style.display === 'none' || + this.codeContainer.style.display === '' + ) { this.codeContainer.style.display = 'block'; - this.codeButton.setAttribute('aria-expanded', 'true'); + this.codeButton.setAttribute( 'aria-expanded', 'true' ); } else { this.codeContainer.style.display = 'none'; - this.codeButton.setAttribute('aria-expanded', 'false'); + this.codeButton.setAttribute( 'aria-expanded', 'false' ); } - }; - + } /** * This function counts the number of issues of a given type. - * - * @param {String} rule_type The type of issue to be counted. - * @returns {Number} The number of issues of a given type. + * + * @param {string} rule_type The type of issue to be counted. + * @return {number} The number of issues of a given type. */ - countIssues(rule_type) { + countIssues( rule_type ) { let count = 0; - for (let issue of this.issues) { - if (issue.rule_type === rule_type) { + for ( const issue of this.issues ) { + if ( issue.rule_type === rule_type ) { count++; } } @@ -821,13 +878,13 @@ class AccessibilityCheckerHighlight { /** * This function counts the number of ignored issues. - * - * @returns {Number} The number of ignored issues. + * + * @return {number} The number of ignored issues. */ countIgnored() { let count = 0; - for (let issue of this.issues) { - if (issue.ignored == 1) { + for ( const issue of this.issues ) { + if ( issue.ignored == 1 ) { count++; } } @@ -838,280 +895,275 @@ class AccessibilityCheckerHighlight { * This function shows the count of issues in the panel. */ showIssueCount() { - let errorCount = this.countIssues('error'); - let warningCount = this.countIssues('warning'); - let ignoredCount = this.countIgnored(); - let div = document.querySelector('.edac-highlight-panel-controls-summary'); + const errorCount = this.countIssues( 'error' ); + const warningCount = this.countIssues( 'warning' ); + const ignoredCount = this.countIgnored(); + const div = document.querySelector( + '.edac-highlight-panel-controls-summary' + ); let textContent = 'No issues detected.'; - if (errorCount > 0 || warningCount > 0 || ignoredCount > 0) { + if ( errorCount > 0 || warningCount > 0 || ignoredCount > 0 ) { textContent = ''; - if (errorCount >= 0) { - textContent += errorCount + ' error' + (errorCount == 1 ? '' : 's') + ', '; + if ( errorCount >= 0 ) { + textContent += + errorCount + + ' error' + + ( errorCount == 1 ? '' : 's' ) + + ', '; } - if (warningCount >= 0) { - textContent += warningCount + ' warning' + (warningCount == 1 ? '' : 's') + ', '; + if ( warningCount >= 0 ) { + textContent += + warningCount + + ' warning' + + ( warningCount == 1 ? '' : 's' ) + + ', '; } - if (ignoredCount >= 0) { - textContent += 'and ' + ignoredCount + ' ignored issue' + (ignoredCount == 1 ? '' : 's') + ' detected.'; + if ( ignoredCount >= 0 ) { + textContent += + 'and ' + + ignoredCount + + ' ignored issue' + + ( ignoredCount == 1 ? '' : 's' ) + + ' detected.'; } else { // Remove the trailing comma and add "detected." - textContent = textContent.slice(0, -2) + ' detected.'; + textContent = textContent.slice( 0, -2 ) + ' detected.'; } } div.textContent = textContent; } - } - -if (window.top._scheduledScanRunning == undefined) { +if ( window.top._scheduledScanRunning == undefined ) { window.top._scheduledScanRunning = false; window.top._scheduledScanCurrentPost = false; } - - async function checkApi() { - - if (edac_script_vars.edacHeaders.Authorization == 'None') { + if ( edac_script_vars.edacHeaders.Authorization == 'None' ) { return 401; } - const response = await fetch(edac_script_vars.edacApiUrl + '/test', { - method: "POST", - headers: edac_script_vars.edacHeaders - }); + const response = await fetch( edac_script_vars.edacApiUrl + '/test', { + method: 'POST', + headers: edac_script_vars.edacHeaders, + } ); return response.status; - } - -async function postData(url = "", data = {}) { - - - if (edac_script_vars.edacHeaders.Authorization == 'None') { +async function postData( url = '', data = {} ) { + if ( edac_script_vars.edacHeaders.Authorization == 'None' ) { return; } - return await fetch(url, { - method: "POST", + return await fetch( url, { + method: 'POST', headers: edac_script_vars.edacHeaders, - body: JSON.stringify(data), - }).then((res) => { - return res.json(); - }).catch(() => { - return {}; - }); - + body: JSON.stringify( data ), + } ) + .then( ( res ) => { + return res.json(); + } ) + .catch( () => { + return {}; + } ); } -async function getData(url = "") { - - if (edac_script_vars.edacHeaders.Authorization == 'None') { +async function getData( url = '' ) { + if ( edac_script_vars.edacHeaders.Authorization == 'None' ) { return {}; } - return await fetch(url, { - method: "GET", - headers: edac_script_vars.edacHeaders - }).then((res) => { - return res.json(); - }).catch(() => { - return {}; - }); - + return await fetch( url, { + method: 'GET', + headers: edac_script_vars.edacHeaders, + } ) + .then( ( res ) => { + return res.json(); + } ) + .catch( () => { + return {}; + } ); } -function info(message) { - if (INFO_ENABLED) { - console.info(message); +function info( message ) { + if ( INFO_ENABLED ) { + console.info( message ); } } - -function debug(message) { - - if (DEBUG_ENABLED) { - - if (location.href !== window.top.location.href) { - console.debug('DEBUG [ ' + location.href + ' ]'); +function debug( message ) { + if ( DEBUG_ENABLED ) { + if ( location.href !== window.top.location.href ) { + console.debug( 'DEBUG [ ' + location.href + ' ]' ); } - if (typeof message !== 'object') { - console.debug('DEBUG: ' + message); + if ( typeof message !== 'object' ) { + console.debug( 'DEBUG: ' + message ); } else { - console.debug(message); + console.debug( message ); } } } -function saveScanResults(postId, violations, scheduled = false) { - +function saveScanResults( postId, violations, scheduled = false ) { // Confirm api service is working. - checkApi().then((status) => { - - - if (status >= 400) { - if (status == 401 && edac_script_vars.edacpApiUrl == '') { - - showNotice({ - msg: ' Whoops! It looks like your website is currently password protected. The free version of Accessibility Checker can only scan live websites. To scan this website for accessibility problems either remove the password protection or {link}. Scan results may be stored from a previous scan.', - type: 'warning', - url: 'https://equalizedigital.com/accessibility-checker/pricing/', - label: 'upgrade to Accessibility Checker Pro', - closeOthers: true - }); - - debug('Error: Password protected scans are not supported in the free version.'); - } else if (status == 401 && edac_script_vars.edacpApiUrl != '') { - showNotice({ - msg: 'Whoops! It looks like your website is currently password protected. To scan this website for accessibility problems {link}.', - type: 'warning', - url: '/wp-admin/admin.php?page=accessibility_checker_settings', - label: 'add your username and password to your Accessibility Checker Pro settings', - closeOthers: true - }); - - debug('Error: Password protected scan in Pro, but password is not correct.'); - } else { - showNotice({ - msg: 'Whoops! It looks like there was a problem connecting to the {link} which is required by Accessibility Checker.', - type: 'warning', - url: 'https://developer.wordpress.org/rest-api/frequently-asked-questions', - label: 'Rest API', - closeOthers: true - }); - - debug('Error: Cannot connect to API. Status code is: ' + status); - } - - } else { - - info('Saving ' + postId + ': started'); - - // Api is fine so we can send the scan results. - postData(edac_script_vars.edacApiUrl + '/post-scan-results/' + postId, { - violations: violations - }).then((data) => { - - debug(data); - - info('Saving ' + postId + ': done'); - - - - if (!data.success) { - - info('Saving ' + postId + ': error'); - - showNotice({ - msg: 'Whoops! It looks like there was a problem updating. Please try again.', - type: 'warning' - }); - + checkApi() + .then( ( status ) => { + if ( status >= 400 ) { + if ( status == 401 && edac_script_vars.edacpApiUrl == '' ) { + showNotice( { + msg: ' Whoops! It looks like your website is currently password protected. The free version of Accessibility Checker can only scan live websites. To scan this website for accessibility problems either remove the password protection or {link}. Scan results may be stored from a previous scan.', + type: 'warning', + url: 'https://equalizedigital.com/accessibility-checker/pricing/', + label: 'upgrade to Accessibility Checker Pro', + closeOthers: true, + } ); + + debug( + 'Error: Password protected scans are not supported in the free version.' + ); + } else if ( + status == 401 && + edac_script_vars.edacpApiUrl != '' + ) { + showNotice( { + msg: 'Whoops! It looks like your website is currently password protected. To scan this website for accessibility problems {link}.', + type: 'warning', + url: '/wp-admin/admin.php?page=accessibility_checker_settings', + label: 'add your username and password to your Accessibility Checker Pro settings', + closeOthers: true, + } ); + + debug( + 'Error: Password protected scan in Pro, but password is not correct.' + ); + } else { + showNotice( { + msg: 'Whoops! It looks like there was a problem connecting to the {link} which is required by Accessibility Checker.', + type: 'warning', + url: 'https://developer.wordpress.org/rest-api/frequently-asked-questions', + label: 'Rest API', + closeOthers: true, + } ); + + debug( + 'Error: Cannot connect to API. Status code is: ' + + status + ); } + } else { + info( 'Saving ' + postId + ': started' ); - if (scheduled) { - debug('_scheduledScanRunning: false'); - - window.top._scheduledScanRunning = false; - }; - - - }); + // Api is fine so we can send the scan results. + postData( + edac_script_vars.edacApiUrl + + '/post-scan-results/' + + postId, + { + violations, + } + ).then( ( data ) => { + debug( data ); - }; + info( 'Saving ' + postId + ': done' ); - }).catch((error) => { - info('Saving ' + postId + ': error'); + if ( ! data.success ) { + info( 'Saving ' + postId + ': error' ); - debug(error); - showNotice({ - msg: 'Whoops! It looks like there was a problem updating. Please try again.', - type: 'warning' - }); + showNotice( { + msg: 'Whoops! It looks like there was a problem updating. Please try again.', + type: 'warning', + } ); + } - }); + if ( scheduled ) { + debug( '_scheduledScanRunning: false' ); + window.top._scheduledScanRunning = false; + } + } ); + } + } ) + .catch( ( error ) => { + info( 'Saving ' + postId + ': error' ); + + debug( error ); + showNotice( { + msg: 'Whoops! It looks like there was a problem updating. Please try again.', + type: 'warning', + } ); + } ); } //TODO: see also https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel window.addEventListener( - "message", - (e) => { - - - if (e.origin !== edac_script_vars.edacUrl) return; - - if (window === window.top) { + 'message', + ( e ) => { + if ( e.origin !== edac_script_vars.edacUrl ) return; + if ( window === window.top ) { //There has been a request to start a scan. Pass the message to the scanner's window. - if (e.data && e.data.sender === 'edac_start_scan') { - var scanner = document.getElementById('edac_scanner'); - var scannerWindow = scanner.contentWindow; - scannerWindow.postMessage({ - 'sender': 'edac_start_scan', - 'message': e.data.message - }); - + if ( e.data && e.data.sender === 'edac_start_scan' ) { + const scanner = document.getElementById( 'edac_scanner' ); + const scannerWindow = scanner.contentWindow; + scannerWindow.postMessage( { + sender: 'edac_start_scan', + message: e.data.message, + } ); } //There has been a request to start a scheduled scan. Pass the message to the scanner's window. - if (e.data && e.data.sender === 'edac_start_scheduled_scan') { - var scheduledScanner = document.getElementById('edacp_scheduled_scanner'); - var scheduledScannerWindow = scheduledScanner.contentWindow; - scheduledScannerWindow.postMessage({ - 'sender': 'edac_start_scheduled_scan', - 'message': e.data.message - }); - + if ( e.data && e.data.sender === 'edac_start_scheduled_scan' ) { + const scheduledScanner = document.getElementById( + 'edacp_scheduled_scanner' + ); + const scheduledScannerWindow = scheduledScanner.contentWindow; + scheduledScannerWindow.postMessage( { + sender: 'edac_start_scheduled_scan', + message: e.data.message, + } ); } //There has been a request to save the scan. - if (e.data && e.data.sender === 'edac_save_scan') { - - saveScanResults(e.data.message.postId, e.data.message.violations, e.data.message.violations); - + if ( e.data && e.data.sender === 'edac_save_scan' ) { + saveScanResults( + e.data.message.postId, + e.data.message.violations, + e.data.message.violations + ); } - } else { - - if (e.data && e.data.sender === 'edac_start_scan') { + if ( e.data && e.data.sender === 'edac_start_scan' ) { const postId = e.data.message.postId; // We are running a scan in the iframe. We need to send the results // back to the top window so we can use that cookie to authenticate the rest post. // See: https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/ - info('Scan ' + postId + ': started'); - - - scan().then((results) => { + info( 'Scan ' + postId + ': started' ); - info('Scan ' + postId + ': done'); + scan().then( ( results ) => { + info( 'Scan ' + postId + ': done' ); - let violations = JSON.parse(JSON.stringify(results.violations)); - - window.top.postMessage({ - 'sender': 'edac_save_scan', - 'message': { - postId: postId, - violations: violations, - scheduled: false - } - }); - - - }); + const violations = JSON.parse( + JSON.stringify( results.violations ) + ); + window.top.postMessage( { + sender: 'edac_save_scan', + message: { + postId, + violations, + scheduled: false, + }, + } ); + } ); } - - - if (e.data && e.data.sender === 'edac_start_scheduled_scan') { - + if ( e.data && e.data.sender === 'edac_start_scheduled_scan' ) { // We are running a scheduled scan in the iframe. We need to send the results // back to the top window so we can use that cookie to authenticate the rest post. // See: https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/ @@ -1120,283 +1172,272 @@ window.addEventListener( window.top._scheduledScanRunning = true; - info("Scheduled scan: started " + postId); - debug('_scheduledScanRunning: true'); - - scan().then((results) => { - - - info("Scheduled scan: done " + postId); - - let violations = JSON.parse(JSON.stringify(results.violations)); - - window.top.postMessage({ - 'sender': 'edac_save_scan', - 'message': { - postId: postId, - violations: violations, - scheduled: true - } - }); - - - }); - + info( 'Scheduled scan: started ' + postId ); + debug( '_scheduledScanRunning: true' ); + + scan().then( ( results ) => { + info( 'Scheduled scan: done ' + postId ); + + const violations = JSON.parse( + JSON.stringify( results.violations ) + ); + + window.top.postMessage( { + sender: 'edac_save_scan', + message: { + postId, + violations, + scheduled: true, + }, + } ); + } ); } - } - }, - false, + false ); - -window.addEventListener('DOMContentLoaded', () => { - - debug('We are loading the app in ' + edac_script_vars.mode + ' mode.'); - - if(JS_SCAN_ENABLED){ - if (edac_script_vars.mode === 'editor-scan') { - - debug('App is loading from within the editor.'); - - // We are loading the app from within the editor (rather than the page preview). - // Create an iframe in the editor for loading the page preview. - // The page preview's url has an ?edac-action=scan, which tells the app - // loaded in the iframe to: 1) run the js scan, 2) post the results. - const iframe = document.createElement('iframe'); - iframe.setAttribute('id', 'edac_scanner'); - iframe.setAttribute('src', edac_script_vars.scanUrl); - iframe.style.width = screen.width + 'px'; - iframe.style.height = screen.height + 'px'; - iframe.style.position = 'absolute'; - iframe.style.left = '-' + screen.width + 'px'; - document.body.append(iframe); - - iframe.addEventListener("load", function (e) { - - debug('Scan iframe loaded.'); - - // The frame has loaded the preview page, so post the message that fires the iframe scan and save. - window.postMessage({ - 'sender': 'edac_start_scan', - 'message': { - postId: edac_script_vars.postID - } - }); - - }); - - - //Listen for dispatches from the wp data store - let saving = false; - if (wp.data !== undefined && wp.data.subscribe !== undefined) { - wp.data.subscribe(() => { - - // Rescan the page if user saves post - if (wp.data.select('core/editor').isSavingPost()) { - saving = true; - } else { - if (saving) { +window.addEventListener( 'DOMContentLoaded', () => { + debug( 'We are loading the app in ' + edac_script_vars.mode + ' mode.' ); + + if ( JS_SCAN_ENABLED ) { + if ( edac_script_vars.mode === 'editor-scan' ) { + debug( 'App is loading from within the editor.' ); + + // We are loading the app from within the editor (rather than the page preview). + // Create an iframe in the editor for loading the page preview. + // The page preview's url has an ?edac-action=scan, which tells the app + // loaded in the iframe to: 1) run the js scan, 2) post the results. + const iframe = document.createElement( 'iframe' ); + iframe.setAttribute( 'id', 'edac_scanner' ); + iframe.setAttribute( 'src', edac_script_vars.scanUrl ); + iframe.style.width = screen.width + 'px'; + iframe.style.height = screen.height + 'px'; + iframe.style.position = 'absolute'; + iframe.style.left = '-' + screen.width + 'px'; + document.body.append( iframe ); + + iframe.addEventListener( 'load', function ( e ) { + debug( 'Scan iframe loaded.' ); + + // The frame has loaded the preview page, so post the message that fires the iframe scan and save. + window.postMessage( { + sender: 'edac_start_scan', + message: { + postId: edac_script_vars.postID, + }, + } ); + } ); + + //Listen for dispatches from the wp data store + let saving = false; + if ( wp.data !== undefined && wp.data.subscribe !== undefined ) { + wp.data.subscribe( () => { + // Rescan the page if user saves post + if ( wp.data.select( 'core/editor' ).isSavingPost() ) { + saving = true; + } else if ( saving ) { saving = false; - checkApi().then((status) => { - if (status == 401 && edac_script_vars.edacpApiUrl == '') { - - showNotice({ + checkApi().then( ( status ) => { + if ( + status == 401 && + edac_script_vars.edacpApiUrl == '' + ) { + showNotice( { msg: ' Whoops! It looks like your website is currently password protected. The free version of Accessibility Checker can only scan live websites. To scan this website for accessibility problems either remove the password protection or {link}. Scan results may be stored from a previous scan.', type: 'warning', url: 'https://equalizedigital.com/accessibility-checker/pricing/', label: 'Upgrade to Accessibility Checker Pro', - closeOthers: true - }); + closeOthers: true, + } ); - debug('Password protected scans are not supported on the free version.') + debug( + 'Password protected scans are not supported on the free version.' + ); } else { - debug('Loading scan iframe: ' + edac_script_vars.scanUrl); - iframe.setAttribute('src', edac_script_vars.scanUrl); + debug( + 'Loading scan iframe: ' + + edac_script_vars.scanUrl + ); + iframe.setAttribute( + 'src', + edac_script_vars.scanUrl + ); } - }); - - + } ); } - } - - }); - - } else { - debug("Gutenberg is not enabled."); + } ); + } else { + debug( 'Gutenberg is not enabled.' ); + } } - } - - - if ( - (edac_script_vars.mode === 'editor-scan' && edac_script_vars.edacpApiUrl != '') || //&& edac_script_vars.pendingFullScan) || - (edac_script_vars.mode === 'full-scan') - ) { - - - debug('App is loading either from the editor page or from the scheduled full scan page.'); - - // Create an iframe in the editor for loading the page preview for the scheduled scans. - const iframeScheduledScanner = document.createElement('iframe'); - iframeScheduledScanner.setAttribute('id', 'edacp_scheduled_scanner'); - iframeScheduledScanner.style.width = screen.width + 'px'; - iframeScheduledScanner.style.height = screen.height + 'px'; - iframeScheduledScanner.style.position = 'absolute'; - iframeScheduledScanner.style.left = '-' + screen.width + 'px'; - - const onLoadIframeScheduledScanner = function (e) { - debug('Loading scheduled scan iframe: done'); - - var data = e.currentTarget.data; - - // The frame has loaded the preview page, so post the message that fires the iframe scan and save. - window.postMessage({ - 'sender': 'edac_start_scheduled_scan', - 'message': data - }); - - }; - iframeScheduledScanner.addEventListener('load', onLoadIframeScheduledScanner, false); - - document.body.append(iframeScheduledScanner); - - let scanInterval = setInterval(() => { - - - if (!window.top._scheduledScanRunning) { - - debug('Polling to see if there are any scans pending.'); - - - // Poll to see if there are any scans pending. - getData(edac_script_vars.edacpApiUrl + '/scheduled-scan-url') - .then((data) => { + if ( + ( edac_script_vars.mode === 'editor-scan' && + edac_script_vars.edacpApiUrl != '' ) || //&& edac_script_vars.pendingFullScan) || + edac_script_vars.mode === 'full-scan' + ) { + debug( + 'App is loading either from the editor page or from the scheduled full scan page.' + ); + // Create an iframe in the editor for loading the page preview for the scheduled scans. + const iframeScheduledScanner = document.createElement( 'iframe' ); + iframeScheduledScanner.setAttribute( + 'id', + 'edacp_scheduled_scanner' + ); + iframeScheduledScanner.style.width = screen.width + 'px'; + iframeScheduledScanner.style.height = screen.height + 'px'; + iframeScheduledScanner.style.position = 'absolute'; + iframeScheduledScanner.style.left = '-' + screen.width + 'px'; - if (data.code !== 'rest_no_route') { + const onLoadIframeScheduledScanner = function ( e ) { + debug( 'Loading scheduled scan iframe: done' ); - if (data.data !== undefined) { + const data = e.currentTarget.data; - if (data.data.scanUrl !== undefined) { + // The frame has loaded the preview page, so post the message that fires the iframe scan and save. + window.postMessage( { + sender: 'edac_start_scheduled_scan', + message: data, + } ); + }; + iframeScheduledScanner.addEventListener( + 'load', + onLoadIframeScheduledScanner, + false + ); - info('A post needs scanning: ' + data.data.scanUrl); - debug(data); + document.body.append( iframeScheduledScanner ); + + const scanInterval = setInterval( () => { + if ( ! window.top._scheduledScanRunning ) { + debug( 'Polling to see if there are any scans pending.' ); + + // Poll to see if there are any scans pending. + getData( + edac_script_vars.edacpApiUrl + '/scheduled-scan-url' + ).then( ( data ) => { + if ( data.code !== 'rest_no_route' ) { + if ( data.data !== undefined ) { + if ( data.data.scanUrl !== undefined ) { + info( + 'A post needs scanning: ' + + data.data.scanUrl + ); + debug( data ); //set the data so we can pass it to the onload handler iframeScheduledScanner.data = data.data; - // We have the url of the next in line to be scanned so pass to the iframe. - iframeScheduledScanner.setAttribute('src', data.data.scanUrl); - - + iframeScheduledScanner.setAttribute( + 'src', + data.data.scanUrl + ); } - } - } else { - - info('There was a problem connecting to the API.'); + info( + 'There was a problem connecting to the API.' + ); window.top._scheduledScanRunning = false; - debug('_scheduledScanRunning: false'); - + debug( '_scheduledScanRunning: false' ); } - }); - - } else { - debug('Waiting for previous scan to complete.'); - } - - }, SCAN_INTERVAL_IN_SECONDS * 1000); - - - - } + } ); + } else { + debug( 'Waiting for previous scan to complete.' ); + } + }, SCAN_INTERVAL_IN_SECONDS * 1000 ); + } } - if (edac_script_vars.mode === 'ui' && edac_script_vars.active) { - + if ( edac_script_vars.mode === 'ui' && edac_script_vars.active ) { // We are loading the app in a normal page preview so show the user the ui new AccessibilityCheckerHighlight(); - } +} ); - - - - - -}); - - -if (window.top === window && window._showNotice === undefined) { - - var link = document.createElement("link"); +if ( window.top === window && window._showNotice === undefined ) { + const link = document.createElement( 'link' ); link.href = 'https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.css'; - link.type = "text/css"; - link.rel = "stylesheet"; - link.media = "screen,print"; - document.getElementsByTagName("head")[0].appendChild(link); - - window._showNotice = function (options) { - - const settings = Object.assign({}, { - msg: '', - type: 'warning', - url: false, - label: '', - closeOthers: true - }, options); - - - if (window.wp !== undefined && window.wp.data !== undefined && window.wp.data.dispatch !== undefined) { + link.type = 'text/css'; + link.rel = 'stylesheet'; + link.media = 'screen,print'; + document.getElementsByTagName( 'head' )[ 0 ].appendChild( link ); + + window._showNotice = function ( options ) { + const settings = Object.assign( + {}, + { + msg: '', + type: 'warning', + url: false, + label: '', + closeOthers: true, + }, + options + ); - var o = { isDismissible: true }; + if ( + window.wp !== undefined && + window.wp.data !== undefined && + window.wp.data.dispatch !== undefined + ) { + const o = { isDismissible: true }; var msg = settings.msg; - if (settings.url) { - o.actions = [{ - url: settings.url, - label: settings.label - }]; + if ( settings.url ) { + o.actions = [ + { + url: settings.url, + label: settings.label, + }, + ]; - msg = msg.replace('{link}', settings.label); + msg = msg.replace( '{link}', settings.label ); } else { - msg = msg.replace('{link}', ''); + msg = msg.replace( '{link}', '' ); } - if (settings.closeOthers) { - document.querySelectorAll('.components-notice').forEach((element) => { - element.style.display = 'none'; - }); + if ( settings.closeOthers ) { + document + .querySelectorAll( '.components-notice' ) + .forEach( ( element ) => { + element.style.display = 'none'; + } ); } - setTimeout(function () { - wp.data.dispatch("core/notices").createNotice(settings.type, msg, o); - }, 10); - - - - - + setTimeout( function () { + wp.data + .dispatch( 'core/notices' ) + .createNotice( settings.type, msg, o ); + }, 10 ); } else { - //TODO: do we need to show notices on preview pages? If not we can remove this section and Notyf. var msg = settings.msg; - if (settings.url) { - msg = msg.replace('{link}', '' + settings.label + ''); + if ( settings.url ) { + msg = msg.replace( + '{link}', + '' + + settings.label + + '' + ); } else { - msg = msg.replace('{link}', ''); + msg = msg.replace( '{link}', '' ); } - const notyf = new Notyf({ + const notyf = new Notyf( { position: { x: 'left', y: 'top' }, ripple: false, types: [ @@ -1405,7 +1446,7 @@ if (window.top === window && window._showNotice === undefined) { background: '#eff9f1', duration: 2000, dismissible: true, - icon: false + icon: false, }, { @@ -1413,37 +1454,30 @@ if (window.top === window && window._showNotice === undefined) { background: '#fef8ee', duration: 0, dismissible: true, - icon: false + icon: false, }, { type: 'error', background: '#f4a2a2', duration: 0, dismissible: true, - icon: false - } - ] - }); + icon: false, + }, + ], + } ); - if (settings.closeOthers) { + if ( settings.closeOthers ) { notyf.dismissAll(); } - const notification = notyf.open({ + const notification = notyf.open( { type: settings.type, - message: msg - }); - - + message: msg, + } ); } - - - - } - + }; } - -function showNotice(options) { - window.top._showNotice(options); +function showNotice( options ) { + window.top._showNotice( options ); } diff --git a/src/app/scanner/checks/always-fail.js b/src/app/scanner/checks/always-fail.js index 7b184762..7e36bf92 100644 --- a/src/app/scanner/checks/always-fail.js +++ b/src/app/scanner/checks/always-fail.js @@ -1,15 +1,13 @@ -export default - -{ - id: 'always-fail', - metadata: { - impact: 'critical', - messages: { - pass: 'This test passed.', - fail: 'This test failed.', - }, - }, - evaluate: function () { - return false; - }, -} +export default { + id: 'always-fail', + metadata: { + impact: 'critical', + messages: { + pass: 'This test passed.', + fail: 'This test failed.', + }, + }, + evaluate() { + return false; + }, +}; diff --git a/src/app/scanner/index.js b/src/app/scanner/index.js index a51071ec..86650834 100644 --- a/src/app/scanner/index.js +++ b/src/app/scanner/index.js @@ -4,33 +4,28 @@ import colorContrastFailure from './rules/color-contrast-failure'; //import customRule1 from './rules/custom-rule-1'; //import alwaysFail from './checks/always-fail'; - -//TODO: +//TODO: //see: https://www.youtube.com/watch?v=AtsX0dPCG_4 //see: https://github.com/dequelabs/axe-core/blob/develop/doc/developer-guide.md#api-reference //see: https://www.deque.com/axe/core-documentation/api-documentation/ -export async function scan( - options = { configOptions: {}, runOptions: {} } -) { - - - const context = { exclude: ['#wpadminbar', '.edac-panel-container'] }; +export async function scan( options = { configOptions: {}, runOptions: {} } ) { + const context = { exclude: [ '#wpadminbar', '.edac-panel-container' ] }; const defaults = { configOptions: { - reporter: "raw", - - rules : [ + reporter: 'raw', + + rules: [ //customRule1, - colorContrastFailure + colorContrastFailure, ], checks: [ //alwaysFail, - ], + ], }, runOptions: { - runOnly: ['color_contrast_failure'] + runOnly: [ 'color_contrast_failure' ], /* //TODO: runOnly: { @@ -47,75 +42,70 @@ export async function scan( ] } */ - } + }, }; - const configOptions = Object.assign(defaults.configOptions, options.configOptions); - axe.configure(configOptions); - - const runOptions = Object.assign(defaults.runOptions, options.runOptions); + const configOptions = Object.assign( + defaults.configOptions, + options.configOptions + ); + axe.configure( configOptions ); - return await axe.run(context, runOptions) - .then((rules) => { + const runOptions = Object.assign( defaults.runOptions, options.runOptions ); + return await axe + .run( context, runOptions ) + .then( ( rules ) => { axe.reset(); - - let violations = []; - - rules.forEach(item => { + const violations = []; + rules.forEach( ( item ) => { //Build an array of the dom selectors and ruleIDs for violations/failed tests - item.violations.forEach( violation => { - if(violation.result === 'failed'){ - - - violations.push({ - selector:violation.node.selector, - html: document.querySelector(violation.node.selector).outerHTML, + item.violations.forEach( ( violation ) => { + if ( violation.result === 'failed' ) { + violations.push( { + selector: violation.node.selector, + html: document.querySelector( + violation.node.selector + ).outerHTML, ruleId: item.id, impact: item.impact, - tags: item.tags - }); + tags: item.tags, + } ); } - }); - - }); + } ); + } ); - let rules_min = rules.map((r) => { + const rules_min = rules.map( ( r ) => { return { id: r.id, description: r.description, help: r.help, impact: r.impact, - tags: r.tags - } - }); - + tags: r.tags, + }; + } ); + //Sort the violations by order they appear in the document - violations.sort(function(a,b) { - a = document.querySelector(a.selector); - b = document.querySelector(b.selector); - - if( a === b) return 0; - if( a.compareDocumentPosition(b) & 2) { + violations.sort( function ( a, b ) { + a = document.querySelector( a.selector ); + b = document.querySelector( b.selector ); + + if ( a === b ) return 0; + if ( a.compareDocumentPosition( b ) & 2 ) { // b comes before a return 1; } return -1; - }); - + } ); + return { rules, rules_min, violations }; - - - }).catch((err) => { + } ) + .catch( ( err ) => { axe.reset(); //TODO: return err; - }); - - - -}; - + } ); +} diff --git a/src/app/scanner/rules/color-contrast-failure.js b/src/app/scanner/rules/color-contrast-failure.js index 19ac034a..65e8e42a 100644 --- a/src/app/scanner/rules/color-contrast-failure.js +++ b/src/app/scanner/rules/color-contrast-failure.js @@ -1,26 +1,24 @@ -export default - -{ - "id": "color_contrast_failure", - "matches": "color-contrast-matches", - "excludeHidden": false, - "tags": [ - "cat.color", - "wcag2aa", - "wcag143", - "TTv5", - "TT13.c", - "EN-301-549", - "EN-9.1.4.3", - "ACT" - ], - "actIds": ["afw4f7", "09o5cg"], - "metadata": { - "description": "Ensures the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds", - "help": "Elements must meet minimum color contrast ratio thresholds" - }, - "all": [], - "any": ["color-contrast"], - "none": [] - } - \ No newline at end of file +export default { + id: 'color_contrast_failure', + matches: 'color-contrast-matches', + excludeHidden: false, + tags: [ + 'cat.color', + 'wcag2aa', + 'wcag143', + 'TTv5', + 'TT13.c', + 'EN-301-549', + 'EN-9.1.4.3', + 'ACT', + ], + actIds: [ 'afw4f7', '09o5cg' ], + metadata: { + description: + 'Ensures the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds', + help: 'Elements must meet minimum color contrast ratio thresholds', + }, + all: [], + any: [ 'color-contrast' ], + none: [], +}; diff --git a/src/app/scanner/rules/custom-rule-1.js b/src/app/scanner/rules/custom-rule-1.js index 7c61a174..395bb396 100644 --- a/src/app/scanner/rules/custom-rule-1.js +++ b/src/app/scanner/rules/custom-rule-1.js @@ -1,11 +1,5 @@ -export default - - { - id: 'custom-rule-1', - "tags": [ - "custom" - ], - all: ['always-fail'], - } -; - +export default { + id: 'custom-rule-1', + tags: [ 'custom' ], + all: [ 'always-fail' ], +}; From 7cde6ba0a1e177aad3a370e52e1352e47e21ef03 Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Wed, 13 Dec 2023 15:40:59 +0200 Subject: [PATCH 06/10] Add .editorconfig file --- .editorconfig | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..5987f266 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,25 @@ +# This file is for unifying the coding style for different editors and IDEs +# editorconfig.org + +# WordPress Coding Standards +# https://make.wordpress.org/core/handbook/coding-standards/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = tab + +[*.{yml,yaml}] +indent_style = space +indent_size = 2 + +[*.{gradle,java,kt}] +indent_style = space + +[packages/react-native-*/**.xml] +indent_style = space + From 782b13eac0d2cafab26073fa63ab093db721e8ec Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Thu, 14 Dec 2023 09:53:58 +0200 Subject: [PATCH 07/10] Manually fix remaining issues --- src/app/index.js | 151 +++++++++++++++++++++++---------------- src/app/scanner/index.js | 8 ++- 2 files changed, 93 insertions(+), 66 deletions(-) diff --git a/src/app/index.js b/src/app/index.js index c293d0ed..484e8fc1 100644 --- a/src/app/index.js +++ b/src/app/index.js @@ -1,12 +1,8 @@ -import { - computePosition, - autoUpdate, - shift, - offset, - inline, -} from '@floating-ui/dom'; +/* eslint-disable no-console */ +/* global edac_script_vars, DOMParser, XMLHttpRequest */ +import { computePosition, autoUpdate } from '@floating-ui/dom'; import { createFocusTrap } from 'focus-trap'; -import { isFocusable, isTabbable } from 'tabbable'; +import { isFocusable } from 'tabbable'; import { Notyf } from 'notyf'; import { scan } from './scanner'; @@ -16,6 +12,7 @@ const INFO_ENABLED = false; const DEBUG_ENABLED = false; let SCAN_INTERVAL_IN_SECONDS = 30; +// eslint-disable-next-line camelcase if ( edac_script_vars.mode === 'full-scan' ) { SCAN_INTERVAL_IN_SECONDS = 3; } @@ -23,7 +20,7 @@ if ( edac_script_vars.mode === 'full-scan' ) { class AccessibilityCheckerHighlight { /** * Constructor - * @param settings + * @param {Object} settings */ constructor( settings = {} ) { const defaultSettings = { @@ -91,11 +88,11 @@ class AccessibilityCheckerHighlight { */ init() { // Add event listeners for 'next' and 'previous' buttons - this.nextButton.addEventListener( 'click', ( event ) => { + this.nextButton.addEventListener( 'click', () => { this.highlightFocusNext(); this.focusTrapDescription(); } ); - this.previousButton.addEventListener( 'click', ( event ) => { + this.previousButton.addEventListener( 'click', () => { this.highlightFocusPrevious(); this.focusTrapDescription(); } ); @@ -187,10 +184,13 @@ class AccessibilityCheckerHighlight { return new Promise( function ( resolve, reject ) { const xhr = new XMLHttpRequest(); const url = + // eslint-disable-next-line camelcase edac_script_vars.ajaxurl + '?action=edac_frontend_highlight_ajax&post_id=' + + // eslint-disable-next-line camelcase edac_script_vars.postID + '&nonce=' + + // eslint-disable-next-line camelcase edac_script_vars.nonce; self.showWait( true ); @@ -203,15 +203,15 @@ class AccessibilityCheckerHighlight { const response = JSON.parse( xhr.responseText ); if ( true === response.success ) { - const response_json = JSON.parse( response.data ); + const responseJSON = JSON.parse( response.data ); if ( self.settings.showIgnored ) { - resolve( response_json ); + resolve( responseJSON ); } else { resolve( - response_json.filter( + responseJSON.filter( ( item ) => - item.id == self.urlParameter || + item.id === self.urlParameter || item.rule_type !== 'ignored' ) ); @@ -247,7 +247,7 @@ class AccessibilityCheckerHighlight { /** * This function toggles showing Wait - * @param status + * @param {boolean} status */ showWait( status = true ) { if ( status ) { @@ -282,10 +282,9 @@ class AccessibilityCheckerHighlight { * * @param {HTMLElement} element - The DOM element before which the tooltip button will be inserted. * @param {Object} value - An object containing properties used to customize the tooltip button. - * @param {number} index - The index of the element being processed. * @return {Object} - information about the tooltip */ - addTooltip( element, value, index ) { + addTooltip( element, value ) { // Create the tooltip. const tooltip = document.createElement( 'button' ); tooltip.classList = @@ -312,20 +311,20 @@ class AccessibilityCheckerHighlight { computePosition( element, tooltip, { placement: 'top-start', middleware: [], - } ).then( ( { x, y, middlewareData, placement } ) => { + } ).then( ( { x, y } ) => { const elRect = element.getBoundingClientRect(); const elHeight = - element.offsetHeight == undefined + element.offsetHeight === undefined ? 0 : element.offsetHeight; const elWidth = - element.offsetWidth == undefined ? 0 : element.offsetWidth; + element.offsetWidth === undefined ? 0 : element.offsetWidth; const tooltipHeight = - tooltip.offsetHeight == undefined + tooltip.offsetHeight === undefined ? 0 : tooltip.offsetHeight; const tooltipWidth = - tooltip.offsetWidth == undefined ? 0 : tooltip.offsetWidth; + tooltip.offsetWidth === undefined ? 0 : tooltip.offsetWidth; let top = 0; const left = 0; @@ -388,7 +387,7 @@ class AccessibilityCheckerHighlight {
-
+
@@ -403,7 +402,7 @@ class AccessibilityCheckerHighlight {
- + `; @@ -414,7 +413,7 @@ class AccessibilityCheckerHighlight { * This function highlights the next element on the page. It uses the 'currentButtonIndex' property to keep track of the current element. */ highlightFocusNext = () => { - if ( this.currentButtonIndex == null ) { + if ( this.currentButtonIndex === null ) { this.currentButtonIndex = 0; } else { this.currentButtonIndex = @@ -428,7 +427,7 @@ class AccessibilityCheckerHighlight { * This function highlights the previous element on the page. It uses the 'currentButtonIndex' property to keep track of the current element. */ highlightFocusPrevious = () => { - if ( this.currentButtonIndex == null ) { + if ( this.currentButtonIndex === null ) { this.currentButtonIndex = this.issues.length - 1; } else { this.currentButtonIndex = @@ -475,9 +474,9 @@ class AccessibilityCheckerHighlight { return; } - const issue = this.issues.find( ( issue ) => issue.id == id ); + const issue = this.issues.find( ( item ) => item.id === id ); this.currentButtonIndex = this.issues.findIndex( - ( issue ) => issue.id == id + ( item ) => item.id === id ); const tooltip = issue.tooltip; @@ -531,7 +530,6 @@ class AccessibilityCheckerHighlight { * This function checks if a given element is visible on the page. * * @param {HTMLElement} el The element to check for visibility - * @return */ checkVisibility = ( el ) => { //checkVisibility is still in draft but well supported on many browsers. @@ -553,7 +551,7 @@ class AccessibilityCheckerHighlight { /** * This function opens the accessibility checker panel. - * @param id + * @param {number|string} id */ panelOpen( id ) { this.panelControls.style.display = 'block'; @@ -562,7 +560,7 @@ class AccessibilityCheckerHighlight { // Get the issues for this page. this.highlightAjax() .then( ( json ) => { - if ( json.length == 0 ) { + if ( json.length === 0 ) { this.nextButton.disabled = true; this.previousButton.disabled = true; } else { @@ -588,7 +586,7 @@ class AccessibilityCheckerHighlight { this.focusTrapDescription(); } } ) - .catch( ( err ) => { + .catch( () => { //TODO: } ); } @@ -633,7 +631,7 @@ class AccessibilityCheckerHighlight { 'edac-highlight-element-selected-min-height' ); - if ( selectedElement.classList.length == 0 ) { + if ( selectedElement.classList.length === 0 ) { selectedElement.removeAttribute( 'class' ); } } ); @@ -748,7 +746,7 @@ class AccessibilityCheckerHighlight { disableStyles() { /* If the site compiles css into a combined file, our method for disabling styles will cause out app's css to break. - This checks if the app's css is loading into #edac-app-css as expected. + This checks if the app's css is loading into #edac-app-css as expected. If not, then we assume the css has been combined, so we manually add it to the document. */ if ( ! document.querySelector( '#edac-app-css' ) ) { @@ -758,6 +756,7 @@ class AccessibilityCheckerHighlight { link.rel = 'stylesheet'; link.id = 'edac-app-css'; link.type = 'text/css'; + // eslint-disable-next-line camelcase, no-unused-expressions ( link.href = edac_script_vars.appCssUrl ), ( link.media = 'all' ); document.head.appendChild( link ); } @@ -863,13 +862,13 @@ class AccessibilityCheckerHighlight { /** * This function counts the number of issues of a given type. * - * @param {string} rule_type The type of issue to be counted. + * @param {string} ruleType The type of issue to be counted. * @return {number} The number of issues of a given type. */ - countIssues( rule_type ) { + countIssues( ruleType ) { let count = 0; for ( const issue of this.issues ) { - if ( issue.rule_type === rule_type ) { + if ( issue.rule_type === ruleType ) { count++; } } @@ -884,7 +883,7 @@ class AccessibilityCheckerHighlight { countIgnored() { let count = 0; for ( const issue of this.issues ) { - if ( issue.ignored == 1 ) { + if ( issue.ignored === 1 ) { count++; } } @@ -909,14 +908,14 @@ class AccessibilityCheckerHighlight { textContent += errorCount + ' error' + - ( errorCount == 1 ? '' : 's' ) + + ( errorCount === 1 ? '' : 's' ) + ', '; } if ( warningCount >= 0 ) { textContent += warningCount + ' warning' + - ( warningCount == 1 ? '' : 's' ) + + ( warningCount === 1 ? '' : 's' ) + ', '; } if ( ignoredCount >= 0 ) { @@ -924,7 +923,7 @@ class AccessibilityCheckerHighlight { 'and ' + ignoredCount + ' ignored issue' + - ( ignoredCount == 1 ? '' : 's' ) + + ( ignoredCount === 1 ? '' : 's' ) + ' detected.'; } else { // Remove the trailing comma and add "detected." @@ -936,18 +935,21 @@ class AccessibilityCheckerHighlight { } } -if ( window.top._scheduledScanRunning == undefined ) { +if ( window.top._scheduledScanRunning === undefined ) { window.top._scheduledScanRunning = false; window.top._scheduledScanCurrentPost = false; } async function checkApi() { - if ( edac_script_vars.edacHeaders.Authorization == 'None' ) { + // eslint-disable-next-line camelcase + if ( edac_script_vars.edacHeaders.Authorization === 'None' ) { return 401; } + // eslint-disable-next-line camelcase const response = await fetch( edac_script_vars.edacApiUrl + '/test', { method: 'POST', + // eslint-disable-next-line camelcase headers: edac_script_vars.edacHeaders, } ); @@ -955,12 +957,14 @@ async function checkApi() { } async function postData( url = '', data = {} ) { - if ( edac_script_vars.edacHeaders.Authorization == 'None' ) { + // eslint-disable-next-line camelcase + if ( edac_script_vars.edacHeaders.Authorization === 'None' ) { return; } return await fetch( url, { method: 'POST', + // eslint-disable-next-line camelcase headers: edac_script_vars.edacHeaders, body: JSON.stringify( data ), } ) @@ -973,12 +977,14 @@ async function postData( url = '', data = {} ) { } async function getData( url = '' ) { - if ( edac_script_vars.edacHeaders.Authorization == 'None' ) { + // eslint-disable-next-line camelcase + if ( edac_script_vars.edacHeaders.Authorization === 'None' ) { return {}; } return await fetch( url, { method: 'GET', + // eslint-disable-next-line camelcase headers: edac_script_vars.edacHeaders, } ) .then( ( res ) => { @@ -997,8 +1003,8 @@ function info( message ) { function debug( message ) { if ( DEBUG_ENABLED ) { - if ( location.href !== window.top.location.href ) { - console.debug( 'DEBUG [ ' + location.href + ' ]' ); + if ( window.location.href !== window.top.location.href ) { + console.debug( 'DEBUG [ ' + window.location.href + ' ]' ); } if ( typeof message !== 'object' ) { console.debug( 'DEBUG: ' + message ); @@ -1013,7 +1019,8 @@ function saveScanResults( postId, violations, scheduled = false ) { checkApi() .then( ( status ) => { if ( status >= 400 ) { - if ( status == 401 && edac_script_vars.edacpApiUrl == '' ) { + // eslint-disable-next-line camelcase + if ( status === 401 && edac_script_vars.edacpApiUrl === '' ) { showNotice( { msg: ' Whoops! It looks like your website is currently password protected. The free version of Accessibility Checker can only scan live websites. To scan this website for accessibility problems either remove the password protection or {link}. Scan results may be stored from a previous scan.', type: 'warning', @@ -1026,8 +1033,9 @@ function saveScanResults( postId, violations, scheduled = false ) { 'Error: Password protected scans are not supported in the free version.' ); } else if ( - status == 401 && - edac_script_vars.edacpApiUrl != '' + status === 401 && + // eslint-disable-next-line camelcase + edac_script_vars.edacpApiUrl !== '' ) { showNotice( { msg: 'Whoops! It looks like your website is currently password protected. To scan this website for accessibility problems {link}.', @@ -1059,6 +1067,7 @@ function saveScanResults( postId, violations, scheduled = false ) { // Api is fine so we can send the scan results. postData( + // eslint-disable-next-line camelcase edac_script_vars.edacApiUrl + '/post-scan-results/' + postId, @@ -1102,6 +1111,7 @@ function saveScanResults( postId, violations, scheduled = false ) { window.addEventListener( 'message', ( e ) => { + // eslint-disable-next-line camelcase if ( e.origin !== edac_script_vars.edacUrl ) return; if ( window === window.top ) { @@ -1198,9 +1208,11 @@ window.addEventListener( ); window.addEventListener( 'DOMContentLoaded', () => { + // eslint-disable-next-line camelcase debug( 'We are loading the app in ' + edac_script_vars.mode + ' mode.' ); if ( JS_SCAN_ENABLED ) { + // eslint-disable-next-line camelcase if ( edac_script_vars.mode === 'editor-scan' ) { debug( 'App is loading from within the editor.' ); @@ -1210,20 +1222,22 @@ window.addEventListener( 'DOMContentLoaded', () => { // loaded in the iframe to: 1) run the js scan, 2) post the results. const iframe = document.createElement( 'iframe' ); iframe.setAttribute( 'id', 'edac_scanner' ); + // eslint-disable-next-line camelcase iframe.setAttribute( 'src', edac_script_vars.scanUrl ); - iframe.style.width = screen.width + 'px'; - iframe.style.height = screen.height + 'px'; + iframe.style.width = window.screen.width + 'px'; + iframe.style.height = window.screen.height + 'px'; iframe.style.position = 'absolute'; - iframe.style.left = '-' + screen.width + 'px'; + iframe.style.left = '-' + window.screen.width + 'px'; document.body.append( iframe ); - iframe.addEventListener( 'load', function ( e ) { + iframe.addEventListener( 'load', function () { debug( 'Scan iframe loaded.' ); // The frame has loaded the preview page, so post the message that fires the iframe scan and save. window.postMessage( { sender: 'edac_start_scan', message: { + // eslint-disable-next-line camelcase postId: edac_script_vars.postID, }, } ); @@ -1241,8 +1255,9 @@ window.addEventListener( 'DOMContentLoaded', () => { checkApi().then( ( status ) => { if ( - status == 401 && - edac_script_vars.edacpApiUrl == '' + status === 401 && + // eslint-disable-next-line camelcase + edac_script_vars.edacpApiUrl === '' ) { showNotice( { msg: ' Whoops! It looks like your website is currently password protected. The free version of Accessibility Checker can only scan live websites. To scan this website for accessibility problems either remove the password protection or {link}. Scan results may be stored from a previous scan.', @@ -1258,10 +1273,12 @@ window.addEventListener( 'DOMContentLoaded', () => { } else { debug( 'Loading scan iframe: ' + + // eslint-disable-next-line camelcase edac_script_vars.scanUrl ); iframe.setAttribute( 'src', + // eslint-disable-next-line camelcase edac_script_vars.scanUrl ); } @@ -1274,8 +1291,11 @@ window.addEventListener( 'DOMContentLoaded', () => { } if ( + // eslint-disable-next-line camelcase ( edac_script_vars.mode === 'editor-scan' && - edac_script_vars.edacpApiUrl != '' ) || //&& edac_script_vars.pendingFullScan) || + // eslint-disable-next-line camelcase + edac_script_vars.edacpApiUrl !== '' ) || //&& edac_script_vars.pendingFullScan) || + // eslint-disable-next-line camelcase edac_script_vars.mode === 'full-scan' ) { debug( @@ -1288,10 +1308,11 @@ window.addEventListener( 'DOMContentLoaded', () => { 'id', 'edacp_scheduled_scanner' ); - iframeScheduledScanner.style.width = screen.width + 'px'; - iframeScheduledScanner.style.height = screen.height + 'px'; + iframeScheduledScanner.style.width = window.screen.width + 'px'; + iframeScheduledScanner.style.height = window.screen.height + 'px'; iframeScheduledScanner.style.position = 'absolute'; - iframeScheduledScanner.style.left = '-' + screen.width + 'px'; + iframeScheduledScanner.style.left = + '-' + window.screen.width + 'px'; const onLoadIframeScheduledScanner = function ( e ) { debug( 'Loading scheduled scan iframe: done' ); @@ -1312,12 +1333,14 @@ window.addEventListener( 'DOMContentLoaded', () => { document.body.append( iframeScheduledScanner ); + // eslint-disable-next-line no-unused-vars const scanInterval = setInterval( () => { if ( ! window.top._scheduledScanRunning ) { debug( 'Polling to see if there are any scans pending.' ); // Poll to see if there are any scans pending. getData( + // eslint-disable-next-line camelcase edac_script_vars.edacpApiUrl + '/scheduled-scan-url' ).then( ( data ) => { if ( data.code !== 'rest_no_route' ) { @@ -1355,6 +1378,7 @@ window.addEventListener( 'DOMContentLoaded', () => { }, SCAN_INTERVAL_IN_SECONDS * 1000 ); } } + // eslint-disable-next-line camelcase if ( edac_script_vars.mode === 'ui' && edac_script_vars.active ) { // We are loading the app in a normal page preview so show the user the ui new AccessibilityCheckerHighlight(); @@ -1389,7 +1413,7 @@ if ( window.top === window && window._showNotice === undefined ) { ) { const o = { isDismissible: true }; - var msg = settings.msg; + let msg = settings.msg; if ( settings.url ) { o.actions = [ @@ -1420,7 +1444,7 @@ if ( window.top === window && window._showNotice === undefined ) { } else { //TODO: do we need to show notices on preview pages? If not we can remove this section and Notyf. - var msg = settings.msg; + let msg = settings.msg; if ( settings.url ) { msg = msg.replace( @@ -1470,6 +1494,7 @@ if ( window.top === window && window._showNotice === undefined ) { notyf.dismissAll(); } + // eslint-disable-next-line no-unused-vars const notification = notyf.open( { type: settings.type, message: msg, diff --git a/src/app/scanner/index.js b/src/app/scanner/index.js index 86650834..1fd715bc 100644 --- a/src/app/scanner/index.js +++ b/src/app/scanner/index.js @@ -1,3 +1,4 @@ +/* global axe */ import 'axe-core'; import colorContrastFailure from './rules/color-contrast-failure'; //TODO: examples: @@ -26,7 +27,7 @@ export async function scan( options = { configOptions: {}, runOptions: {} } ) { }, runOptions: { runOnly: [ 'color_contrast_failure' ], - /* + /* //TODO: runOnly: { type: 'tag', @@ -77,7 +78,7 @@ export async function scan( options = { configOptions: {}, runOptions: {} } ) { } ); } ); - const rules_min = rules.map( ( r ) => { + const rulesMin = rules.map( ( r ) => { return { id: r.id, description: r.description, @@ -93,6 +94,7 @@ export async function scan( options = { configOptions: {}, runOptions: {} } ) { b = document.querySelector( b.selector ); if ( a === b ) return 0; + // eslint-disable-next-line no-bitwise if ( a.compareDocumentPosition( b ) & 2 ) { // b comes before a return 1; @@ -100,7 +102,7 @@ export async function scan( options = { configOptions: {}, runOptions: {} } ) { return -1; } ); - return { rules, rules_min, violations }; + return { rules, rulesMin, violations }; } ) .catch( ( err ) => { axe.reset(); From df69108501400c6595a0128a17f16009a99d67dc Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Thu, 14 Dec 2023 10:02:26 +0200 Subject: [PATCH 08/10] Add workflow --- .github/workflows/lint-js.yml | 37 ++++++++++++++++++++ .github/workflows/{lint.yml => lint-php.yml} | 4 +-- package.json | 1 + 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/lint-js.yml rename .github/workflows/{lint.yml => lint-php.yml} (97%) diff --git a/.github/workflows/lint-js.yml b/.github/workflows/lint-js.yml new file mode 100644 index 00000000..2bea99d0 --- /dev/null +++ b/.github/workflows/lint-js.yml @@ -0,0 +1,37 @@ +name: Lint PHP + +on: + # Run on pushes to select branches and on all pull requests. + push: + branches: + - master + - develop + - trunk + - 'feature/**' + - 'release/**' + - 'hotfix/[0-9]+.[0-9]+*' + pull_request: + # Allow manually triggering the workflow. + workflow_dispatch: + +# Cancels all previous workflow runs for the same branch that have not yet completed. +concurrency: + # The concurrency group contains the workflow name and the branch name. + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + runs-on: ubuntu-latest + + name: "Lint: JS" + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + # The lint stage doesn't run the unit tests or use code style, so no need for PHPUnit, WPCS or phpcompatibility. + - name: 'Install NPM packages' + run: npm install + - name: 'Run ESLint' + run: npm run lint:js diff --git a/.github/workflows/lint.yml b/.github/workflows/lint-php.yml similarity index 97% rename from .github/workflows/lint.yml rename to .github/workflows/lint-php.yml index 549be610..ef96ec10 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint-php.yml @@ -1,4 +1,4 @@ -name: Lint +name: Lint PHP on: # Run on pushes to select branches and on all pull requests. @@ -69,4 +69,4 @@ jobs: tools: cs2pr - name: Lint against parse errors - run: composer lint -- --checkstyle | cs2pr \ No newline at end of file + run: composer lint -- --checkstyle | cs2pr diff --git a/package.json b/package.json index c3c3eff8..b57f2fa5 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "dev": "npx webpack --watch --mode development", "dist": "npx webpack --mode production && composer install --no-dev && composer dump-autoload --no-dev -o && wp-scripts plugin-zip && mv accessibility-checker.zip ./dist && composer install", "lint": "./vendor/bin/phpcs && npm run lint:js", + "lint:php": "./vendor/bin/phpcs", "lint:js": "wp-scripts lint-js", "lint:js:fix": "wp-scripts lint-js --fix", "test:e2e": "npx wp-env clean tests && npx playwright test ./e2e/specs" From 85233c8a3a3ae194728bc50a2a57b14bafd3b21a Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Thu, 14 Dec 2023 10:03:42 +0200 Subject: [PATCH 09/10] copy/paste error in the workflow --- .github/workflows/lint-js.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/lint-js.yml b/.github/workflows/lint-js.yml index 2bea99d0..1ac22dfc 100644 --- a/.github/workflows/lint-js.yml +++ b/.github/workflows/lint-js.yml @@ -1,4 +1,4 @@ -name: Lint PHP +name: Lint JS on: # Run on pushes to select branches and on all pull requests. From cff36d314b073c203dbd1e87f744c7b9b0b01708 Mon Sep 17 00:00:00 2001 From: Aristeides Stathopoulos Date: Fri, 15 Dec 2023 15:23:55 +0200 Subject: [PATCH 10/10] master branch was renamed to main --- .github/workflows/lint-js.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/lint-js.yml b/.github/workflows/lint-js.yml index 1ac22dfc..405c7959 100644 --- a/.github/workflows/lint-js.yml +++ b/.github/workflows/lint-js.yml @@ -4,7 +4,7 @@ on: # Run on pushes to select branches and on all pull requests. push: branches: - - master + - main - develop - trunk - 'feature/**'