Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Configure code style #98

Merged
merged 37 commits into from
Oct 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
a15a85d
Define `lint` script and install `eslint`
kbighorse Oct 25, 2023
5719fa6
Extend and install airbnb style guide
kbighorse Oct 25, 2023
5c8c117
Support commonjs
kbighorse Oct 25, 2023
0c63441
First pass of lint fixes
kbighorse Oct 25, 2023
0c01aec
Declare and initialize local variables
kbighorse Oct 25, 2023
b5da850
Define functions in order of usage
kbighorse Oct 25, 2023
a739a9b
Use eqeqeq
kbighorse Oct 25, 2023
a97beef
Remove console calls
kbighorse Oct 25, 2023
126d074
Remove redundant declaration
kbighorse Oct 25, 2023
22360a3
Move dependencies out of `devDependencies`
kbighorse Oct 25, 2023
1bbdf2e
Update dependencies
kbighorse Oct 25, 2023
3748e82
Merge branch 'main' into configure-code-style
kbighorse Oct 25, 2023
ac9ca66
Merge branch 'configure-code-style' of https://github.com/18F/guides …
kbighorse Oct 25, 2023
981b596
Reinstall style guide
kbighorse Oct 25, 2023
7d54abe
Reinstall dependencies
kbighorse Oct 25, 2023
7709523
Move dependencies out of dev
kbighorse Oct 25, 2023
6036f63
Add lint step to workflow
kbighorse Oct 25, 2023
9a973c5
Adding rulefix for param variable reassign
eric-gade Oct 26, 2023
43a1aca
Resolving remaining linter exceptions
eric-gade Oct 26, 2023
ed14e73
Updating airbnb base eslint config dependency
eric-gade Oct 27, 2023
fe36be0
Updating pull request github action for lint
eric-gade Oct 27, 2023
17edf78
Fixing workflow
eric-gade Oct 27, 2023
a04d68c
Fix whitespace
kbighorse Oct 27, 2023
a5f6de7
Bumping node version for pa11y-ci workflow
eric-gade Oct 30, 2023
c05e116
eslint ignore the build directory and remove ext
eric-gade Oct 30, 2023
9e683e4
Trying to fix pa11y run
eric-gade Oct 30, 2023
adfb88c
Adding prettier to deps along with a basic config
eric-gade Oct 30, 2023
95f74cf
Fixing package script
eric-gade Oct 30, 2023
c79ec2c
Cleaning up lint command w/ default config location
eric-gade Oct 30, 2023
ea22905
Updating pa11y-ci version
eric-gade Oct 31, 2023
b72e5c1
Fixing dev vs prod dependencies
eric-gade Oct 31, 2023
81882fb
Fixing logging on build step
eric-gade Oct 31, 2023
ddbf832
Updating README with Prettier info & git hook template
eric-gade Oct 31, 2023
f469390
Updating README internal link
eric-gade Oct 31, 2023
33cf338
Trying to fix yaml of workflow
eric-gade Oct 31, 2023
42916f1
Removing before script from pa11y workflow
eric-gade Oct 31, 2023
b1eca3a
Fixing lints
eric-gade Oct 31, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"env": {
"browser": true,
"commonjs": true,
"es2021": true
},
"ignorePatterns": ["/_site"],
"extends": ["eslint-config-airbnb-base", "prettier"],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"no-param-reassign": ["error", { "props": false }],
"quotes": ["error", "single"],
"no-iterator": ["off"],
"no-return-await": ["off"]
}
}
16 changes: 15 additions & 1 deletion .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ jobs:
- name: Use Node
uses: actions/setup-node@v3
with:
node-version: '17.x'
node-version: 18
- name: Install node dependencies
run: npm install
- name: Refresh assets
Expand Down Expand Up @@ -78,3 +78,17 @@ jobs:
- name: Test all links
run: npm run test:links

lint:
name: Run linter
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Use Node
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install node dependencies
run: npm install
- name: Run eslint
run: npm run lint
echappen marked this conversation as resolved.
Show resolved Hide resolved

1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
18
6 changes: 6 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2
}
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ on every pull request, but it can also be run locally. To run locally, type:
```
npm run test:pa11y-ci
```
### Code Formatting ###

#### Prettier ####
We use [Prettier](https://prettier.io/) for code formatting. You can run prettier manually with
```
npx prettier . --write
```
Note that this will overwrite files in place. See `npx prettier --help` for more CLI options.

An easier way to use prettier is to integrate it into your IDE/editor. For example, [integration exists for VS Code](https://github.com/prettier/prettier-vscode) such that prettier runs on a file every time you save it.

You can also add prettier as a [git commit hook](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks), but you will need to set up the script yourself. For example, you can symlink [this template](/utils/pre-commit) file into `.git/hooks/pre-commit`

## Contributing
If you are interested in contributing to this repository, you can read more at
[CONTRIBUTING](CONTRIBUTING.md).
Expand Down
2 changes: 1 addition & 1 deletion _data/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
*/
module.exports = {
production:
process.env.NODE_ENV == "production" || process.env.BRANCH == "main",
process.env.NODE_ENV === 'production' || process.env.BRANCH === 'main',
};
23 changes: 11 additions & 12 deletions assets/accessibility/js/flashing.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
window.addEventListener('DOMContentLoaded', function () {
console.log('foo')
var blinking = false,
interval,
blinkEl = document.getElementsByClassName('blink')[0],
blinkBtn = document.getElementById('blinkbutton');
window.addEventListener('DOMContentLoaded', () => {
let blinking = false;
let interval;
const blinkEl = document.getElementsByClassName('blink')[0];
const blinkBtn = document.getElementById('blinkbutton');

function toggleBlinking(el) {
var display = el.style.display;
const { display } = el.style;
if (display === 'inline') {
el.style.display = 'none';
} else {
el.style.display = 'inline';
}
}

blinkBtn.addEventListener('click', function () {
blinkBtn.addEventListener('click', () => {
if (!blinking) {
blinkBtn.innerText = 'Click to stop blinking'
interval = setInterval(function () {
toggleBlinking(blinkEl)
blinkBtn.innerText = 'Click to stop blinking';
interval = setInterval(() => {
toggleBlinking(blinkEl);
}, 200);
blinking = true;
} else {
Expand All @@ -27,5 +26,5 @@ window.addEventListener('DOMContentLoaded', function () {
blinkEl.style.display = 'none';
blinking = false;
}
})
});
});
16 changes: 8 additions & 8 deletions assets/accessibility/js/keyboard-access.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
window.addEventListener('DOMContentLoaded', function() {
var moveFocusLinks = document.getElementsByClassName('moveFocus');
var keyboardTrapLinks = document.getElementsByClassName('keyboardTrap');
window.addEventListener('DOMContentLoaded', () => {
const moveFocusLinks = document.getElementsByClassName('moveFocus');
const keyboardTrapLinks = document.getElementsByClassName('keyboardTrap');

function handleFocus() {
keyboardTrapLinks[0].focus();
}

Array.from(moveFocusLinks).map(function(el) {
Array.from(moveFocusLinks).forEach((el) => {
el.addEventListener('focus', handleFocus);
});

Array.from(keyboardTrapLinks).map(function(el) {
el.addEventListener('click', function() {
Array.from(moveFocusLinks).map(function(el) {
el.removeEventListener('focus', handleFocus);
Array.from(keyboardTrapLinks).forEach((trapLinkEl) => {
trapLinkEl.addEventListener('click', () => {
Array.from(moveFocusLinks).forEach((focusLinkEl) => {
focusLinkEl.removeEventListener('focus', handleFocus);
});
});
});
Expand Down
23 changes: 13 additions & 10 deletions assets/accessibility/js/time-outs.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
window.addEventListener('DOMContentLoaded', function () {
var timer,
pForm = document.getElementById('pForm');
/* eslint no-alert: 0 */
window.addEventListener('DOMContentLoaded', () => {
let timer;
const pForm = document.getElementById('pForm');

Array.from(pForm.getElementsByTagName('input')).map(function (el) {
el.addEventListener('input', function () {
Array.from(pForm.getElementsByTagName('input')).forEach((el) => {
el.addEventListener('input', () => {
if (timer) {
clearTimeout(timer);
}

timer = setTimeout(function () {
var c = confirm('Would you like more time to complete the form?'),
timer
if (c == true) {
timer = setTimeout(() => {
const c = window.confirm(
'Would you like more time to complete the form?',
);

if (c === true) {
clearTimeout(timer);
} else {
pForm.reset();
}
}, 2000);
})
});
});
});
40 changes: 25 additions & 15 deletions assets/derisking/js/current-link.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,50 @@
/* eslint no-plusplus: 0 */
/**
* Find the most recently passed heading and adds a usa-current
* class to the correspoing link in the sidenav subnav
*/
function setCurrentLink(){
if (!document.querySelector('.usa-sidenav')) { return; }
if (!document.querySelector('.usa-sidenav__sublist')) { return; }
function setCurrentLink() {
if (!document.querySelector('.usa-sidenav')) {
return;
}
if (!document.querySelector('.usa-sidenav__sublist')) {
return;
}

let h3s = document.querySelectorAll('h3');
if (h3s.length <= 1) { return; }
const h3s = document.querySelectorAll('h3');
if (h3s.length <= 1) {
return;
}

let scrollPos = document.documentElement.scrollTop;
const scrollPos = document.documentElement.scrollTop;
let topHead = h3s[0];
let i = 0;
let found = false;
while (!found && i < h3s.length) {
if (scrollPos < h3s[i].offsetTop){
if (scrollPos < h3s[i].offsetTop) {
found = true;
}
else {
} else {
topHead = h3s[i];
}
i++;
}
let href = topHead.id;
let oldLink = document.querySelector('.usa-sidenav__sublist .usa-current');
const href = topHead.id;
const oldLink = document.querySelector('.usa-sidenav__sublist .usa-current');
if (oldLink) {
oldLink.classList.remove('usa-current');
}
let currentLink = document.querySelector('.usa-sidenav__sublist [href="#'+href+'"]').parentElement;
const currentLink = document.querySelector(
`.usa-sidenav__sublist [href='#${href}']`,
).parentElement;
currentLink.classList.add('usa-current');
}

/**
* Add the event listener to find the nearest heading on user scroll
*/
if (document.querySelector('.usa-sidenav') && document.querySelectorAll('h3').length > 1){
window.addEventListener('scroll',setCurrentLink);
if (
document.querySelector('.usa-sidenav')
&& document.querySelectorAll('h3').length > 1
) {
window.addEventListener('scroll', setCurrentLink);
}

32 changes: 21 additions & 11 deletions config/buildAssets.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint no-restricted-syntax: 0 no-shadow: 0 */
/** eslint doesn't like iterators/generators */
const fs = require('fs/promises');
const path = require('path');
const esbuild = require('esbuild');
Expand All @@ -17,32 +19,36 @@
}

async function createAssetPaths() {
let pathPrefix = ''
let pathPrefix = '';

if (process.env.BASEURL) {
pathPrefix = process.env.BASEURL
pathPrefix = process.env.BASEURL;
}

const assetPath = path.join(__dirname, '../_site/assets');
const assetDirs = await fs.readdir(assetPath);
const assetsFiles = await Promise.all(
assetDirs.map(async (dir) => {
const files = []
for await (const f of getFilesInDirectory(path.join(__dirname, '../_site/assets',dir))) {
const files = [];
for await (const f of getFilesInDirectory(
path.join(__dirname, '../_site/assets', dir),
)) {
files.push(f);
}
return files.map((file) => {
const { name, ext } = path.parse(file);
const publicDir = '_site/';
const assetDirs = file.slice(file.indexOf(publicDir) + publicDir.length);
const assetDirs = file.slice(
file.indexOf(publicDir) + publicDir.length,
);
const hashedAt = name.lastIndexOf('-');
const originalName = name.slice(0, hashedAt);
const key = `${originalName}${ext}`;
return {
[key]: `${pathPrefix}/${assetDirs}`,
};
});
})
}),
);
const assets = Object.assign({}, ...assetsFiles.flat());
const outputData = path.join(__dirname, '../_data/assetPaths.json');
Expand All @@ -52,7 +58,11 @@

esbuild
.build({
entryPoints: ['assets/_common/styles/styles.scss', 'assets/_common/js/app.js', 'assets/_common/js/admin.js'],
entryPoints: [
'assets/_common/styles/styles.scss',
'assets/_common/js/app.js',
'assets/_common/js/admin.js',
],
entryNames: '[dir]/[name]-[hash]',
outdir: '_site/assets/',
format: 'iife',
Expand All @@ -67,22 +77,22 @@
minify: process.env.ELEVENTY_ENV === 'production',
sourcemap: process.env.ELEVENTY_ENV !== 'production',
target: ['chrome58', 'firefox57', 'safari11', 'edge18'],
plugins: [
plugins: [
sassPlugin({
loadPaths: [
"./node_modules/@uswds",
"./node_modules/@uswds/uswds/packages"
]
'./node_modules/@uswds',
'./node_modules/@uswds/uswds/packages',
],
}),
],
bundle: true,
})
.then(() => createAssetPaths())
.then(() => {
console.log('Assets have been built!');

Check warning on line 92 in config/buildAssets.js

View workflow job for this annotation

GitHub Actions / Run linter

Unexpected console statement
process.exit();
})
.catch((err) => {
console.error(err);

Check warning on line 96 in config/buildAssets.js

View workflow job for this annotation

GitHub Actions / Run linter

Unexpected console statement
process.exit(1);
});
27 changes: 9 additions & 18 deletions config/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,12 @@

const { DateTime } = require('luxon');

const readableDate = (dateObj) => {
return DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat(
'dd LLL yyyy'
);
};
const readableDate = (dateObj) => DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat(
'dd LLL yyyy',
);

// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
const htmlDateString = (dateObj) => {
return DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat('yyyy-LL-dd');
};
const htmlDateString = (dateObj) => DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat('yyyy-LL-dd');

// Get the first `n` elements of a collection.
const head = (array, n) => {
Expand All @@ -25,21 +21,16 @@ const head = (array, n) => {
};

// Return the smallest number argument
const min = (...numbers) => {
return Math.min.apply(null, numbers);
};

const filterTagList = (tags) => {
return (tags || []).filter(
(tag) => ['all', 'nav', 'post', 'posts'].indexOf(tag) === -1
);
}
const min = (...numbers) => Math.min.apply(null, numbers);

const filterTagList = (tags) => (tags || []).filter(
(tag) => ['all', 'nav', 'post', 'posts'].indexOf(tag) === -1,
);

module.exports = {
readableDate,
htmlDateString,
head,
min,
filterTagList
filterTagList,
};
Loading