1
0
mirror of https://github.com/locomotivemtl/locomotive-boilerplate.git synced 2026-01-15 00:55:08 +08:00

108 Commits

Author SHA1 Message Date
Chauncey McAskill
89ce8ce1ad Add support for arbitrary data in template tags
Where data is defined under a `data` field in 'loconfig.json'.

Example:

```json5
{
    "paths": {…},
    "data": {
        "foo": "b"
    },
    "tasks": {
        "concats": [
            {
                "includes": [
                    "{% paths.scripts.src %}/vendors/*.js"
                ],
                "outfile": "{% paths.scripts.dest %}/a{% foo %}c.js"
            }
        ]
    }
}
```
2023-03-23 10:27:04 -04:00
Deven Caron
8aac2ffea6 Merge pull request #132 from locomotivemtl/feature/build-task-chores
Various fixes and changes to build utilities
2023-03-06 09:07:04 -05:00
Chauncey McAskill
349d110dee Revert merging of usrconfig to use let declaration 2023-03-03 13:13:31 -05:00
Chauncey McAskill
7be5e48f22 Fix import of merge util in 'watch.js'
The `merge` function is provided by 'utils/index.js'.
2023-03-03 13:07:47 -05:00
Chauncey McAskill
1ee315663e Fix glob.js and improve documentation
Documented API inconsistencies between supported glob libraries (expected/supported parameters and return types).

Fixed API inconsistencies between 'tiny-glob', 'globby', and 'glob', to match 'fast-glob'.

Fixed broken support for preset options for 'tiny-glob'.
2023-03-03 13:04:22 -05:00
Chauncey McAskill
89bb00790f Update postcss.js documentation 2023-03-03 13:04:22 -05:00
Chauncey McAskill
9db0c71a82 Move helpers/utils exports to end of file
Improves readability by always expecting exports at the end of the file.
2023-03-03 13:04:22 -05:00
Chauncey McAskill
7742bbb9d0 Add block comments to task iteratees 2023-03-03 13:04:22 -05:00
Chauncey McAskill
c9a9209b4b Refactor build utilities
Separated generic functions from build helpers.

Changed:
- Moved 'utils/*.js' to 'helpers/*.js'
- From 'utils/config.js':
  - Moved function `merge` to 'utils/index.js'.
  - Moved function `isObjectLike` to 'utils/index.js'.
- From 'utils/template.js':
  - Moved function `flatten` to 'utils/index.js'.
  - Moved function `escapeRegExp` to 'utils/index.js'.
- From 'tasks/styles.js':
  - Moved function `createPostCSSProcessor` to 'helpers/postcss.js' as `createProcessor`.
- Replaced function `Object.assign` with `merge` for task options parsing in all tasks.
2023-03-03 13:04:22 -05:00
Chauncey McAskill
9d758f3b2c Improve postcss.js
Added constant `supportsPostCSS` to provide a boolean to check if PostCSS is available.
2023-03-03 13:04:22 -05:00
Chauncey McAskill
0738dd6491 Improve glob.js
Added constant `supportsGlob` to provide a boolean to check if a glob function is available.
2023-03-03 13:04:22 -05:00
Chauncey McAskill
a4656f59ed Improve concats.js, scripts.js, svgs.js
Added:
- Condition to cast `includes` into an array.

Removed:
- Variable `files` in favour of reusing `includes` in 'concats.js'.
2023-03-03 13:04:20 -05:00
Deven Caron
7ff6094e40 Move sass to dev dependencies 2023-03-03 10:49:57 -05:00
Chauncey McAskill
3fee6f4888 Update NPM depdencies
Updated:
- browser-sync v2.27.5 → v2.27.11
- esbuild v0.16.17 → v0.17.6
- engine.io v3.5.0 → v6.4.0
- qs v6.2.3 → v6.11.0

Changed:
- Overrode ua-parser-js constraint in browser-sync from `1.0.2` to `~1.0.33` to fix security notice.
2023-02-09 10:52:26 -05:00
Deven Caron
f774482255 Update README node version 2023-02-09 10:21:39 -05:00
Deven Caron
b7d9311ac6 Remove container width; replace with padding 2023-02-09 10:18:47 -05:00
Deven Caron
c22a006079 Merge pull request #139 from locomotivemtl/feature/update-node-version
Update node version to v17.9 and switch from node-sass to sass
2023-02-09 10:15:42 -05:00
Deven Caron
af57ebd9cb Merge branch 'master' into feature/update-node-version 2023-02-09 10:11:24 -05:00
Deven Caron
c82e9916d0 Merge branch 'master' into feature/update-node-version 2023-02-09 10:05:25 -05:00
Deven Caron
943324220a Downgrade to node v17.9 2023-02-09 10:00:31 -05:00
Deven Caron
477cec7763 Merge pull request #141 from locomotivemtl/feature/optimize-grid
Optimise grid-column loops / Use css vars for grid columns
2023-02-09 09:08:35 -05:00
Deven Caron
5d38685460 Merge branch 'master' into feature/optimize-grid 2023-02-09 09:07:35 -05:00
Deven Caron
9079d735bc Merge pull request #138 from locomotivemtl/feature/css-variables
Feature / CSS Variables
2023-02-09 09:02:59 -05:00
Deven Caron
87238fcdd5 Merge branch 'master' into feature/css-variables 2023-02-09 09:01:24 -05:00
Deven Caron
2f75d8f3d2 Merge pull request #142 from locomotivemtl/dependabot/npm_and_yarn/http-cache-semantics-4.1.1
Bump http-cache-semantics from 4.1.0 to 4.1.1
2023-02-07 09:30:26 -05:00
dependabot[bot]
0346a15b57 Bump http-cache-semantics from 4.1.0 to 4.1.1
Bumps [http-cache-semantics](https://github.com/kornelski/http-cache-semantics) from 4.1.0 to 4.1.1.
- [Release notes](https://github.com/kornelski/http-cache-semantics/releases)
- [Commits](https://github.com/kornelski/http-cache-semantics/compare/v4.1.0...v4.1.1)

---
updated-dependencies:
- dependency-name: http-cache-semantics
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-04 05:43:43 +00:00
Deven Caron
a2d658bc13 Remove log to prevent throwing unwanted errors 2023-02-02 10:14:48 -05:00
Deven Caron
7c1b61eda9 Add build config dynamic import assertation type 2023-02-02 10:00:20 -05:00
Lucas Vallenet
1fe30a9837 Optimize grid-column loops / Use css vars for grid columns 2023-02-01 10:23:43 +01:00
Deven Caron
e4ae03a94c Remove unused sass env function 2023-01-31 15:37:40 -05:00
Deven Caron
3cde7d40ee Update readme 2023-01-31 14:15:56 -05:00
Deven Caron
d1d4fb5fe5 Bump node-version & upgrade node-sass to sass 2023-01-31 13:57:51 -05:00
Chauncey McAskill
3cd81bdb3e Improve asset versioning task
Improved logic for replacing the value to allow for simpler regular expression patterns. Lookbehinds and lookaheads are no longer required.
2023-01-13 16:42:47 -05:00
Chauncey McAskill
b6970832a3 Improve asset versioning task
Added support for replacing a string in a file using a regular expression.

The routine uses Node's Readline and Stream modules.

The `outfile` will be renamed with a `~` suffix, then stream each line, writing to a new `outfile`.

On success, the backup file (with `~`) is deleted.

On error, any new file is deleted, then the backup file is renamed without a `~` suffix.

Usage:

```json
"versions": [
    {
        "format": "timestamp",
        "key": "regexp:(?<=\bdefine\('ASSETS_VERSION', )[^\)]+(?=\);)",
        "outfile": "src/bootstrap.php"
    }
]
```

```php
<?php

define( 'ASSETS_VERSION', 1665071717350 );
```
2023-01-13 15:08:50 -05:00
Chauncey McAskill
b8f0a24cdc Update NPM dependencies
Updated:
- esbuild v0.16.13 → v0.16.17
- postcss v8.4.20 → v8.4.21
2023-01-13 14:55:01 -05:00
Chauncey McAskill
0c718a2644 Update Development documentation
Changed:
- Bumped NPM requirement.
- Added note about benefits of using NVM.
- Added note about support for PurgeCSS to Styles task.
- Added details about Versions task.
2023-01-05 10:37:52 -05:00
Chauncey McAskill
56d255eac8 Fix NPM dependency constraints on svg-mixer
Changed:
- Fixed svg-mixer constraint from `^2.3.14` to `~2.3.14` to stay within `2.3` range since `2.4.0` appears to be an anomaly.
- Overrode postcss constraint in svg-mixer from `^6.0.21` to `^8.4.20` to fix security notice.
2023-01-04 11:01:40 -05:00
Chauncey McAskill
e7e343e62c Bump NPM requirement to 8+
To take advantage of NPM dependency overrides.
2023-01-04 11:01:40 -05:00
Chauncey McAskill
590e06fc03 Update NPM dependencies
Updated:
- autoprefixer v10.4.12 → v10.4.13
- browser-sync v2.27.10 → v2.27.11
- esbuild v0.14.54 → v0.16.13
- node-sass v7.0.3 → v8.0.0
- postcss v8.4.17 → v8.4.20
2023-01-04 11:01:38 -05:00
Lucas Vallenet
4fd7968b86 Fix SCSS syntax error and duplicate 2023-01-04 11:26:56 +01:00
Lucas Vallenet
aba77ea2d9 Add default CSS Variables 2023-01-04 11:21:43 +01:00
Lucas Bigot
20b167da33 Invert grid-helper visibility condition 2022-11-22 14:51:37 -05:00
Deven Caron
f7ca837782 Disable browsersync ghostMode 2022-11-02 11:15:49 -04:00
Deven Caron
0c8ed9595f Merge pull request #112 from locomotivemtl/feature/grid-helper 2022-10-31 14:34:13 -04:00
arnvvd
eead1d27cd Move grid helper call to global.js 2022-10-31 14:27:18 -04:00
arnvvd
2e3db21ec8 Update dynamic imports condition 2022-10-31 14:25:22 -04:00
arnvvd
9c478f5f7d grid helper refactoring + prepare JS dynamic import + add app-env function for Sass conditions 2022-10-31 14:25:20 -04:00
Jérémy Minié
ebcbb6dc84 Only use GridHelper's margin setting for lateral grid spacing 2022-10-31 14:22:31 -04:00
Lucas Vallenet
b7c49086c9 Add custom grid helper based on CSS custom properties 2022-10-31 14:20:59 -04:00
Chauncey McAskill
9219a4cc0a Rename default function in versions.js task
Renamed from `bumpVersion` to `bumpVersions` for consistency with the default functions of other tasks.
2022-10-13 12:53:32 -04:00
Chauncey McAskill
14afe2295a Improve asset versioning task
Added:
- Support for writing multiple times to the same file.
- Support for random hexadecimal value instead of timestamp.

Usage:

```json
"versions": [
    {
        "format": "timestamp",
        "key": "now",
        "outfile": "./assets.json"
    },
    {
        "format": "hex:8",
        "key": "hex",
        "outfile": "./assets.json"
    }
]
```

```json
{
    "now": 1665071717350,
    "hex": "6ef54181c4ba"
}
```
2022-10-12 12:07:24 -04:00
Deven Caron
1bdd2def8d Compile assets 2022-10-06 14:00:32 -04:00
Deven Caron
84ce496df7 Tweak images size to match block ratio 2022-10-06 14:00:26 -04:00
Deven Caron
05e631dbca Fixed locomotive-scroll rendering glitch 2022-10-06 13:59:42 -04:00
Chauncey McAskill
f8f0a7779c Implement simple asset versioning task
A task to allow one to define zero or more JSON files and keys to create or update with the current timestamp.

By default, the boilerplate will maintain a './assets.json' file which should be imported by the Web framework and applied to compiled assets.
2022-10-06 11:32:04 -04:00
Arnaud Pinot
8e320f2cd0 Merge pull request #120 from locomotivemtl/feature/es6-updates 2022-10-05 16:56:16 -04:00
Arnaud Pinot
a8314d064f Update assets/scripts/utils/maths.js
Co-authored-by: Chauncey McAskill <chauncey@locomotive.ca>
2022-10-05 16:54:36 -04:00
arnvvd
76614e8126 Merge branch 'master' into feature/es6-updates 2022-10-05 16:43:57 -04:00
arnvvd
bed84ce392 Merge branch 'feature/es6-updates' of github.com:locomotivemtl/locomotive-boilerplate into feature/es6-updates 2022-10-05 16:39:30 -04:00
arnvvd
feb2241164 Add documentation for esbuild process.env 2022-10-05 16:39:25 -04:00
arnvvd
b1f5a00b8c Delete transform utils function 2022-10-05 16:38:55 -04:00
Arnaud Pinot
2b30d9ac5c Update assets/scripts/utils/is.js
Co-authored-by: Chauncey McAskill <chauncey@locomotive.ca>
2022-10-05 16:36:20 -04:00
Arnaud Pinot
9e5704238e Update assets/scripts/utils/tickers.js
Co-authored-by: Chauncey McAskill <chauncey@locomotive.ca>
2022-10-05 16:35:23 -04:00
Arnaud Pinot
1ede84e1b1 Update assets/scripts/utils/tickers.js
Co-authored-by: Chauncey McAskill <chauncey@locomotive.ca>
2022-10-05 16:34:49 -04:00
Arnaud Pinot
3a83a3209b Merge pull request #129 from locomotivemtl/feature/eager-fonts
Add support for the CSS Font Loading API
2022-10-05 14:42:00 -04:00
arnvvd
98957eb6c4 Merge branch 'master' of github.com:locomotivemtl/locomotive-boilerplate into feature/eager-fonts 2022-10-05 14:38:55 -04:00
arnvvd
6712d2d24d Remove unused constant 2022-10-05 14:27:36 -04:00
Chauncey McAskill
139a6739f6 Update NPM dependencies
Updated:
- autoprefixer v10.4.4 → v10.4.12
- browser-sync v2.27.9 → v2.27.10
- esbuild v0.14.27 → v0.14.54
- kleur v4.1.4 → v4.1.5
- postcss v8.4.12 → v8.4.17
- purgecss v4.1.3 → v4.1.3
2022-10-05 12:54:05 -04:00
Chauncey McAskill
3272521dba Add constant to collect all eager fonts 2022-10-04 16:56:31 -04:00
Chauncey McAskill
e7f0455ce4 Testing CSS Font Loading API
The code in this commit is not intended for production environments;
it requires further testing.

Added:
- Multiple "Source Sans 3" fonts to test many `FontFace` entries.

Changed:
- Removed quotes from font family name to avoid them being included in `FontFace.family` value.

Notes:
- Replaces hidden `<span>` elements with `FaceFace.load()` and `FaceFace.loaded` to eagerly load fonts.
- Fonts are eagerly using custom `loadFonts()` (see 'app.js').
- Acting upon loaded fonts is done using `whenReady()` (see 'Example.js').
2022-09-27 11:11:31 -04:00
Deven Caron
bf425521c4 Fix "z()" sass function typo 2022-08-25 14:45:24 -04:00
Chauncey McAskill
4bdaa5d085 Fix typo in styles.js
Resolves #125
2022-08-12 14:03:55 -04:00
Deven Caron
a385f6ed11 Merge pull request #108 from locomotivemtl/feature/grid-css
Add grid CSS layout system
2022-06-07 13:13:31 -04:00
Deven Caron
4079752fe0 Add ul,ol condition grid reset styles 2022-06-07 10:46:44 -04:00
Deven Caron
14d7e09b2b Compile assets 2022-06-06 16:43:51 -04:00
Deven Caron
e70bf33409 Update variable names to kebab-case 2022-06-06 16:43:13 -04:00
Deven Caron
8b0926269a Apply suggestions from code review
Co-authored-by: Chauncey McAskill <chauncey@mcaskill.ca>
2022-06-06 16:30:59 -04:00
Deven Caron
8d1b548ad0 Update PurgeCSS import order 2022-06-06 16:28:07 -04:00
Deven Caron
7ca7486913 Fix $container-width conflict 2022-06-06 14:42:25 -04:00
Jérémy Minié
520b75185f Remove unused $container-width SCSS variable 2022-06-06 13:26:47 -04:00
Jérémy Minié
a056a87855 Fix grid.md code sample closure + Link grid doc in README 2022-06-06 13:26:07 -04:00
Deven Caron
9b99a1958b Manually apply some #108 suggestions 2022-06-06 13:26:07 -04:00
Deven Caron
d6193a41fa Apply suggestions from code review
Co-authored-by: Chauncey McAskill <chauncey@mcaskill.ca>
2022-06-06 13:26:07 -04:00
Deven Caron
4fafcb8e1d Update docs/grid.md
Co-authored-by: Chauncey McAskill <chauncey@mcaskill.ca>
2022-06-06 13:26:07 -04:00
Deven Caron
aadc410e44 Change PurgeCSS task message label
Co-authored-by: Chauncey McAskill <chauncey@mcaskill.ca>
2022-06-06 13:26:07 -04:00
Deven Caron
0439b165cf Apply suggestions from code review
Co-authored-by: Chauncey McAskill <chauncey@mcaskill.ca>
2022-06-06 13:26:07 -04:00
Deven Caron
f98eebc9e1 Add global readme grid reference 2022-06-06 13:26:07 -04:00
Deven Caron
cb80a2ed13 Add missing grid readme instructions 2022-06-06 13:26:07 -04:00
Deven Caron
07c3155c29 Compile styles 2022-06-06 13:15:56 -04:00
Deven Caron
c264cb7905 [WIP] Start grid doc 2022-06-06 13:07:57 -04:00
Deven Caron
1050b83326 Add template links 2022-06-06 13:07:57 -04:00
Deven Caron
d0a075ff24 Add css grid system base styles 2022-06-06 13:07:12 -04:00
Deven Caron
ad4a1c7d47 Add PurgeCSS u-gc* tasks 2022-06-06 13:03:06 -04:00
Chauncey McAskill
de6b3d73a1 Merge pull request #124 from GregoireCiles-fix/scss-build-font-faces
* GregoireCiles-fix/scss-build-font-faces:
  Support for building a single font family
  Fix alignment and mixin in _fonts.scss
2022-06-06 11:37:45 -04:00
Grégoire Ciles
e8af22009c Support for building a single font family
Co-authored-by: Chauncey McAskill <chauncey@mcaskill.ca>
2022-06-06 11:36:37 -04:00
Grégoire Ciles
de1a5904a8 Fix alignment and mixin in _fonts.scss 2022-06-06 11:36:31 -04:00
Lucas Vallenet
f527488464 Delete queryClosestParent function 2022-06-02 17:23:06 +02:00
Lucas Vallenet
cf3f40c956 Update functions comments 2022-06-02 16:45:31 +02:00
Lucas Vallenet
ebb55769f9 Remove isEqual and isNumeric functions 2022-06-02 11:09:32 +02:00
Lucas Vallenet
9a461ab4c0 Remove events.js 2022-06-01 14:21:14 +02:00
Lucas Vallenet
eddc0ee156 Edit logs 2022-05-26 13:42:49 +02:00
Lucas Vallenet
202e4064f8 Remove removeCustomEvent (no use). Add logs 2022-05-26 13:42:38 +02:00
Lucas Vallenet
e20111fd2e Add removeCustomEvent util 2022-05-26 13:32:52 +02:00
Lucas Vallenet
de0c4993cb Add config.js / Add tickers utils / Add events utils 2022-05-26 13:06:27 +02:00
Lucas Vallenet
6a4043408b Remove export comment 2022-05-25 13:28:15 +02:00
Lucas Vallenet
92500f908f Add roundNumber util 2022-05-25 13:27:40 +02:00
Lucas Vallenet
d97fa82c77 Remove array util 2022-05-25 13:27:30 +02:00
Lucas Vallenet
ccf813f6be Update functions / ES6 syntax / Add functions comments 2022-05-20 16:51:24 +02:00
68 changed files with 4490 additions and 10825 deletions

1
.gitignore vendored
View File

@@ -3,3 +3,4 @@ node_modules
Thumbs.db
loconfig.*.json
!loconfig.example.json
.prettierrc

2
.nvmrc
View File

@@ -1 +1 @@
v14.17
v17.9

View File

@@ -15,6 +15,7 @@
* Uses [SVG Mixer] for processing SVG files and generating spritesheets.
* Uses [ITCSS] for a sane and scalable CSS architecture.
* Uses [Locomotive Scroll] for smooth scrolling with parallax effects.
* Uses a custom [grid system](docs/grid.md) for layout creation.
Learn more about [languages and technologies](docs/technologies.md).
@@ -22,8 +23,8 @@ Learn more about [languages and technologies](docs/technologies.md).
Make sure you have the following installed:
* [Node] — at least 14.17, the latest LTS is recommended.
* [NPM] — at least 6.0, the latest LTS is recommended.
* [Node] — at least 17.9, the latest LTS is recommended.
* [NPM] — at least 8.0, the latest LTS is recommended.
> 💡 You can use [NVM] to install and use different versions of Node via the command-line.
@@ -84,6 +85,7 @@ Learn more about [development and building](docs/development.md).
* [Development and building](docs/development.md)
* [Languages and technologies](docs/technologies.md)
* [Grid system](docs/grid.md)
[BrowserSync]: https://npmjs.com/package/browser-sync
[ESBuild]: https://npmjs.com/package/esbuild

3
assets.json Normal file
View File

@@ -0,0 +1,3 @@
{
"version": 1675955478084
}

View File

@@ -2,9 +2,11 @@ import modular from 'modujs';
import * as modules from './modules';
import globals from './globals';
import { html } from './utils/environment';
import config from './config'
import { isFontLoadingAPIAvailable, loadFonts } from './utils/fonts';
const app = new modular({
modules: modules
modules: modules,
});
window.onload = (event) => {
@@ -23,6 +25,11 @@ window.onload = (event) => {
}
};
export const EAGER_FONTS = [
{ family: 'Source Sans', style: 'normal', weight: 400 },
{ family: 'Source Sans', style: 'normal', weight: 700 },
];
function init() {
globals();
@@ -31,5 +38,23 @@ function init() {
html.classList.add('is-loaded');
html.classList.add('is-ready');
html.classList.remove('is-loading');
}
/**
* Eagerly load the following fonts.
*/
if (isFontLoadingAPIAvailable) {
loadFonts(EAGER_FONTS, config.IS_DEV).then((eagerFonts) => {
html.classList.add('fonts-loaded');
if (config.IS_DEV) {
console.group('Eager fonts loaded!', eagerFonts.length, '/', document.fonts.size);
console.group('State of eager fonts:')
eagerFonts.forEach((font) => console.log(font.family, font.style, font.weight, font.status/*, font*/))
console.groupEnd()
console.group('State of all fonts:')
document.fonts.forEach((font) => console.log(font.family, font.style, font.weight, font.status/*, font*/))
console.groupEnd()
}
});
}
}

24
assets/scripts/config.js Normal file
View File

@@ -0,0 +1,24 @@
/**
* > When using the esBuild API, all `process.env.NODE_ENV` expressions
* > are automatically defined to `"production"` if all minification
* > options are enabled and `"development"` otherwise. This only happens
* > if `process`, `process.env`, and `process.env.NODE_ENV` are not already
* > defined. This substitution is necessary to avoid code crashing instantly
* > (since `process` is a Node API, not a web API).
* > — https://esbuild.github.io/api/#platform
*/
const env = process.env.NODE_ENV
export default config = Object.freeze({
// Environments
ENV: env,
IS_PROD: env === 'production',
IS_DEV: env === 'development',
// CSS class names
CSS_CLASS: {
LOADING: 'is-loading',
READY: 'is-ready',
LOADED: 'is-loaded',
},
})

View File

@@ -1,5 +1,23 @@
import svg4everybody from 'svg4everybody';
import config from './config';
export default function() {
// Dynamic imports for development mode only
let gridHelper;
(async () => {
if (config.IS_DEV) {
const gridHelperModule = await import('./utils/grid-helper');
gridHelper = gridHelperModule?.gridHelper;
}
})();
export default function () {
/**
* Use external SVG spritemaps
*/
svg4everybody();
/**
* Add grid helper
*/
gridHelper?.();
}

View File

@@ -1,2 +1,3 @@
export {default as Example} from './modules/Example';
export {default as Load} from './modules/Load';
export {default as Scroll} from './modules/Scroll';

View File

@@ -1,4 +1,6 @@
import { module } from 'modujs';
import { EAGER_FONTS } from '../app';
import { whenReady } from '../utils/fonts';
export default class extends module {
constructor(m) {
@@ -6,5 +8,10 @@ export default class extends module {
}
init() {
whenReady(EAGER_FONTS).then((fonts) => this.onFontsLoaded(fonts));
}
onFontsLoaded(fonts) {
console.log('Example: Eager Fonts Loaded!', fonts)
}
}

View File

@@ -1,101 +0,0 @@
import { isArray } from './is';
export function addToArray ( array, value ) {
const index = array.indexOf( value );
if ( index === -1 ) {
array.push( value );
}
}
export function arrayContains ( array, value ) {
for ( let i = 0, c = array.length; i < c; i++ ) {
if ( array[i] == value ) {
return true;
}
}
return false;
}
export function arrayContentsMatch ( a, b ) {
let i;
if ( !isArray( a ) || !isArray( b ) ) {
return false;
}
if ( a.length !== b.length ) {
return false;
}
i = a.length;
while ( i-- ) {
if ( a[i] !== b[i] ) {
return false;
}
}
return true;
}
export function ensureArray ( x ) {
if ( typeof x === 'string' ) {
return [ x ];
}
if ( x === undefined ) {
return [];
}
return x;
}
export function lastItem ( array ) {
return array[ array.length - 1 ];
}
export function removeFromArray ( array, member ) {
if ( !array ) {
return;
}
const index = array.indexOf( member );
if ( index !== -1 ) {
array.splice( index, 1 );
}
}
export function toArray ( arrayLike ) {
const array = [];
let i = arrayLike.length;
while ( i-- ) {
array[i] = arrayLike[i];
}
return array;
}
export function findByKeyValue( array, key, value ) {
return array.filter(function( obj ) {
return obj[key] === value;
});
}
export function cloneArray( array ) {
return JSON.parse(JSON.stringify(array));
}
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
export function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}

View File

@@ -1,15 +0,0 @@
export default function(func, wait, immediate) {
let timeout;
return function() {
const context = this;
const args = arguments;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}

View File

@@ -5,4 +5,5 @@ const html = document.documentElement;
const body = document.body;
const isDebug = html.hasAttribute('data-debug');
export { APP_NAME, DATA_API_KEY, html, body, isDebug };

View File

@@ -0,0 +1,402 @@
/**
* Font Faces
*
* Provides utilities to facilitate interactions with the CSS Font Loading API.
*
* Features functions to:
*
* - Retrieve one or more `FontFace` instances based on a font search query.
* - Check if a `FontFace` instance matches a font search query.
* - Eagerly load fonts that match a font search query.
* - Wait until fonts that match a font search query are loaded.
*
* References:
*
* - {@link https://developer.mozilla.org/en-US/docs/Web/API/CSS_Font_Loading_API}
*/
/**
* @typedef {Object} FontFaceReference
*
* @property {string} family - The name used to identify the font in our CSS.
* @property {string} [style] - The style used by the font in our CSS.
* @property {string} [weight] - The weight used by the font in our CSS.
*/
const isFontLoadingAPIAvailable = ('fonts' in document);
/**
* Determines if the given font matches the given `FontFaceReference`.
*
* @param {FontFace} font - The font to inspect.
* @param {FontFaceReference} criterion - The object of property values to match.
*
* @returns {boolean}
*/
function conformsToReference(font, criterion)
{
for (const [ key, value ] of Object.entries(criterion)) {
switch (key) {
case 'family': {
if (trim(font[key]) !== value) {
return false;
}
break;
}
case 'weight': {
/**
* Note concerning font weights:
* Loose equality (`==`) is used to compare numeric weights,
* a number (`400`) and a numeric string (`"400"`).
* Comparison between numeric and keyword values is neglected.
*
* @link https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#common_weight_name_mapping
*/
if (font[key] != value) {
return false;
}
break;
}
default: {
if (font[key] !== value) {
return false;
}
break;
}
}
}
return true;
}
/**
* Determines if the given font matches the given font shorthand.
*
* @param {FontFace} font - The font to inspect.
* @param {string} criterion - The font shorthand to match.
*
* @returns {boolean}
*/
function conformsToShorthand(font, criterion)
{
const family = trim(font.family);
if (trim(family) === criterion) {
return true;
}
if (
criterion.endsWith(trim(family)) && (
criterion.match(font.weight) ||
criterion.match(font.style)
)
) {
return true;
}
return true;
}
/**
* Determines if the given font matches any of the given criteria.
*
* @param {FontFace} font - The font to inspect.
* @param {FontFaceReference[]} criteria - A list of objects with property values to match.
*
* @returns {boolean}
*/
function conformsToAnyReference(font, criteria)
{
for (const criterion of criteria) {
if (conformsToReference(font, criterion)) {
return true;
}
}
return false;
}
/**
* Returns an iterator of all `FontFace` from `document.fonts` that satisfy
* the provided `FontFaceReference`.
*
* @param {FontFaceReference} font
*
* @returns {FontFace[]}
*/
function findManyByReference(search)
{
const found = [];
for (const font of document.fonts) {
if (conformsToReference(font, search)) {
found.push(font);
}
}
return found;
}
/**
* Returns an iterator of all `FontFace` from `document.fonts` that satisfy
* the provided font shorthand.
*
* @param {string} font
*
* @returns {FontFace[]}
*/
function findManyByShorthand(search)
{
const found = [];
for (const font of document.fonts) {
if (conformsToShorthand(font, search)) {
found.push(font);
}
}
return found;
}
/**
* Returns the first `FontFace` from `document.fonts` that satisfies
* the provided `FontFaceReference`.
*
* @param {FontFaceReference} font
*
* @returns {?FontFace}
*/
function findOneByReference(search)
{
for (const font of document.fonts) {
if (conformsToReference(font, criterion)) {
return font;
}
}
return null;
}
/**
* Returns the first `FontFace` from `document.fonts` that satisfies
* the provided font shorthand.
*
* Examples:
*
* - "Roboto"
* - "italic bold 16px Roboto"
*
* @param {string} font
*
* @returns {?FontFace}
*/
function findOneByShorthand(search)
{
for (const font of document.fonts) {
if (conformsToShorthand(font, search)) {
return font;
}
}
return null;
}
/**
* Returns a `FontFace` from `document.fonts` that satisfies
* the provided query.
*
* @param {FontFaceReference|string} font - Either:
* - a `FontFaceReference` object
* - a font family name
* - a font specification, for example "italic bold 16px Roboto"
*
* @returns {?FontFace}
*
* @throws {TypeError}
*/
function getAny(search) {
if (search) {
switch (typeof search) {
case 'string':
return findOneByShorthand(search);
case 'object':
return findOneByReference(search);
}
}
throw new TypeError(
'Expected font query to be font shorthand or font reference'
);
}
/**
* Returns an iterator of all `FontFace` from `document.fonts` that satisfy
* the provided queries.
*
* @param {FontFaceReference|string|(FontFaceReference|string)[]} queries
*
* @returns {FontFace[]}
*
* @throws {TypeError}
*/
function getMany(queries) {
if (!Array.isArray(queries)) {
queries = [ queries ];
}
const found = new Set();
queries.forEach((search) => {
if (search) {
switch (typeof search) {
case 'string':
found.add(...findManyByShorthand(search));
return;
case 'object':
found.add(...findManyByReference(search));
return;
}
}
throw new TypeError(
'Expected font query to be font shorthand or font reference'
);
})
return [ ...found ];
}
/**
* Determines if a font face is registered.
*
* @param {FontFace|FontFaceReference|string} search - Either:
* - a `FontFace` instance
* - a `FontFaceReference` object
* - a font family name
* - a font specification, for example "italic bold 16px Roboto"
*
* @returns {boolean}
*/
function hasAny(search) {
if (search instanceof FontFace) {
return document.fonts.has(search);
}
return getAny(search) != null;
}
/**
* Eagerly load fonts.
*
* Most user agents only fetch and load fonts when they are first needed
* ("lazy loaded"), which can result in a perceptible delay.
*
* This function will "eager load" the fonts.
*
* @param {(FontFace|FontFaceReference)[]} fontsToLoad - List of fonts to load.
* @param {boolean} [debug] - If TRUE, log details to the console.
*
* @returns {Promise}
*/
async function loadFonts(fontsToLoad, debug = false)
{
if ((fontsToLoad.size ?? fontsToLoad.length) === 0) {
throw new TypeError(
'Expected at least one font'
);
}
return await loadFontsWithAPI([ ...fontsToLoad ], debug);
}
/**
* Eagerly load a font using `FontFaceSet` API.
*
* @param {FontFace} font
*
* @returns {Promise}
*/
async function loadFontFaceWithAPI(font)
{
return await (font.status === 'unloaded'
? font.load()
: font.loaded
).then((font) => font, (err) => font)
}
/**
* Eagerly load fonts using `FontFaceSet` API.
*
* @param {FontFaceReference[]} fontsToLoad
* @param {boolean} [debug]
*
* @returns {Promise}
*/
async function loadFontsWithAPI(fontsToLoad, debug = false)
{
debug && console.group('[loadFonts:API]', fontsToLoad.length, '/', document.fonts.size);
const fontsToBeLoaded = [];
for (const fontToLoad of fontsToLoad) {
if (fontToLoad instanceof FontFace) {
if (!document.fonts.has(fontToLoad)) {
document.fonts.add(fontToLoad);
}
fontsToBeLoaded.push(
loadFontFaceWithAPI(fontToLoad)
);
} else {
fontsToBeLoaded.push(
...getMany(fontToLoad).map((font) => loadFontFaceWithAPI(font))
);
}
}
debug && console.groupEnd();
return await Promise.all(fontsToBeLoaded);
}
/**
* Removes quotes from the the string.
*
* When a `@font-face` is declared, the font family is sometimes
* defined in quotes which end up included in the `FontFace` instance.
*
* @param {string} value
*
* @returns {string}
*/
function trim(value) {
return value.replace(/['"]+/g, '');
}
/**
* Returns a Promise that resolves with the specified fonts
* when they are done loading or failed.
*
* @param {FontFaceReference|string|(FontFaceReference|string)[]} queries
*
* @returns {Promise}
*/
async function whenReady(queries)
{
const fonts = getMany(queries);
return await Promise.all(fonts.map((font) => font.loaded));
}
export {
getAny,
getMany,
hasAny,
isFontLoadingAPIAvailable,
loadFonts,
whenReady,
}

View File

@@ -0,0 +1,138 @@
/**
* Grid Helper
*
* Provides a grid based on the design guidelines and is helpful for web integration.
*
* - `Control + g` to toggle the grid
*
*/
/**
* @typedef {Object} GridHelperReference
*
* @property {string} [gutterCssVar=GRID_HELPER_GUTTER_CSS_VAR] - CSS variable used to define grid gutters.
* @property {string} [marginCssVar=GRID_HELPER_MARGIN_CSS_VAR] - CSS variable used to define grid margins.
* @property {string} [rgbaColor=GRID_HELPER_RGBA_COLOR] - RGBA color for the grid appearence.
*/
const GRID_HELPER_GUTTER_CSS_VAR = '--grid-gutter';
const GRID_HELPER_MARGIN_CSS_VAR = '--grid-margin';
const GRID_HELPER_RGBA_COLOR = 'rgba(255, 0, 0, .1)';
/**
* Create a grid helper
*
* @param {GridHelperReference}
*
*/
function gridHelper({
gutterCssVar = GRID_HELPER_GUTTER_CSS_VAR,
marginCssVar = GRID_HELPER_MARGIN_CSS_VAR,
rgbaColor = GRID_HELPER_RGBA_COLOR,
} = {}) {
// Set grid container
const $gridContainer = document.createElement('div');
document.body.append($gridContainer);
// Set grid appearence
setGridHelperColumns($gridContainer, rgbaColor);
setGridHelperStyles($gridContainer, gutterCssVar, marginCssVar);
// Set grid interactivity
setGridEvents($gridContainer, rgbaColor);
}
/**
* Set grid container styles
*
* @param {HTMLElement} $container - DOM Element that contains a list of generated columns
* @param {string} gutterCssVar - CSS variable used to define grid gutters.
* @param {string} marginCssVar - CSS variable used to define grid margins.
*
*/
function setGridHelperStyles($container, gutterCssVar, marginCssVar) {
const elStyles = $container.style;
elStyles.zIndex = '10000';
elStyles.position = 'fixed';
elStyles.top = '0';
elStyles.left = '0';
elStyles.display = 'flex';
elStyles.width = '100%';
elStyles.height = '100%';
elStyles.columnGap = `var(${gutterCssVar}, 0)`;
elStyles.paddingLeft = `var(${marginCssVar}, 0)`;
elStyles.paddingRight = `var(${marginCssVar}, 0)`;
elStyles.pointerEvents = 'none';
elStyles.visibility = 'hidden';
}
/**
* Set grid columns
*
* @param {HTMLElement} $container - DOM Element that will contain a list of generated columns
* @param {string} rgbaColor - RGBA color to stylize the generated columns
*
*/
function setGridHelperColumns($container, rgbaColor) {
// Clear columns
$container.innerHTML = '';
// Loop through columns
const columns = Number(
window.getComputedStyle($container).getPropertyValue('--grid-columns')
);
let $col;
for (var i = 0; i < columns; i++) {
$col = document.createElement('div');
$col.style.flex = '1 1 0';
$col.style.backgroundColor = rgbaColor;
$container.appendChild($col);
}
}
/**
* Set grid events
*
* Resize to rebuild columns
* Keydown/Keyup to toggle the grid display
*
* @param {HTMLElement} $container - DOM Element that contains a list of generated columns
* @param {string} rgbaColor - RGBA color to stylize the generated columns
*
*/
function setGridEvents($container, rgbaColor) {
// Handle resize
window.addEventListener(
'resize',
setGridHelperColumns($container, rgbaColor)
);
// Toggle grid
let ctrlDown = false;
let isActive = false;
document.addEventListener('keydown', (e) => {
if (e.key == 'Control') {
ctrlDown = true;
} else {
if (ctrlDown && e.key == 'g') {
if (isActive) {
$container.style.visibility = 'hidden';
} else {
$container.style.visibility = 'visible';
}
isActive = !isActive;
}
}
});
document.addEventListener('keyup', (e) => {
if (e.key == 'Control') {
ctrlDown = false;
}
});
}
export { gridHelper };

View File

@@ -1,141 +1,140 @@
/**
* @see https://github.com/ractivejs/ractive/blob/dev/src/utils/html.js
* Escape HTML string
* @param {string} str - string to escape
* @return {string} escaped string
*/
export function escapeHtml(str) {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
const escapeHtml = str =>
str.replace(/[&<>'"]/g, tag => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;'
}[tag]))
/**
* Prepare HTML content that contains mustache characters for use with Ractive
* @param {string} str
* @return {string}
* Unescape HTML string
* @param {string} str - string to unescape
* @return {string} unescaped string
*/
export function unescapeHtml(str) {
return str
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&');
}
const unescapeHtml = str =>
str.replace('&amp;', '&')
.replace('&lt;', '<')
.replace('&gt;', '>')
.replace('&#39;', "'")
.replace('&quot;', '"')
/**
* Get element data attributes
* @param {DOMElement} node
* @return {Array} data
* @param {HTMLElement} node - node element
* @return {array} node data
*/
export function getNodeData(node) {
const getNodeData = node => {
// All attributes
const attributes = node.attributes;
const attributes = node.attributes
// Regex Pattern
const pattern = /^data\-(.+)$/;
const pattern = /^data\-(.+)$/
// Output
const data = {};
const data = {}
for (let i in attributes) {
if (!attributes[i]) {
continue;
continue
}
// Attributes name (ex: data-module)
let name = attributes[i].name;
let name = attributes[i].name
// This happens.
if (!name) {
continue;
continue
}
let match = name.match(pattern);
let match = name.match(pattern)
if (!match) {
continue;
continue
}
// If this throws an error, you have some
// serious problems in your HTML.
data[match[1]] = getData(node.getAttribute(name));
data[match[1]] = getData(node.getAttribute(name))
}
return data;
}
const rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/;
/**
* Parse value to data type.
*
* @link https://github.com/jquery/jquery/blob/3.1.1/src/data.js
* @param {string} data - A value to convert.
* @return {mixed} Returns the value in its natural data type.
* @param {string} data - value to convert
* @return {mixed} value in its natural data type
*/
export function getData(data) {
const rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/
const getData = data => {
if (data === 'true') {
return true;
return true
}
if (data === 'false') {
return false;
return false
}
if (data === 'null') {
return null;
return null
}
// Only convert to a number if it doesn't change the string
if (data === +data+'') {
return +data;
return +data
}
if (rbrace.test( data )) {
return JSON.parse( data );
if (rbrace.test(data)) {
return JSON.parse(data)
}
return data;
return data
}
/**
* Returns an array containing all the parent nodes of the given node
* @param {object} node
* @return {array} parent nodes
* @param {HTMLElement} $el - DOM Element
* @return {array} parent nodes
*/
export function getParents(elem) {
const getParents = $el => {
// Set up a parent array
let parents = [];
let parents = []
// Push each parent element to the array
for ( ; elem && elem !== document; elem = elem.parentNode ) {
parents.push(elem);
for (; $el && $el !== document; $el = $el.parentNode) {
parents.push($el)
}
// Return our parent array
return parents;
return parents
}
// https://gomakethings.com/how-to-get-the-closest-parent-element-with-a-matching-selector-using-vanilla-javascript/
export function queryClosestParent(elem, selector) {
// Element.matches() polyfill
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
// Get the closest matching element
for ( ; elem && elem !== document; elem = elem.parentNode ) {
if ( elem.matches( selector ) ) return elem;
}
return null;
};
export {
escapeHtml,
unescapeHtml,
getNodeData,
getData,
getParents,
}

View File

@@ -1,18 +1,39 @@
const LAZY_LOADED_IMAGES = []
/**
* Get an image meta data
*
* @param {HTMLImageElement} $img - The image element.
* @return {object} The given image meta data
*/
export function loadImage(url, options = {}) {
const getImageMetadata = $img => ({
url: $img.src,
width: $img.naturalWidth,
height: $img.naturalHeight,
ratio: $img.naturalWidth / $img.naturalHeight,
})
/**
* Load the given image.
*
* @param {string} url - The URI to lazy load into $el.
* @param {object} options - An object of options
* @return {void}
*/
const loadImage = (url, options = {}) => {
return new Promise((resolve, reject) => {
const $img = new Image();
const $img = new Image()
if (options.crossOrigin) {
$img.crossOrigin = options.crossOrigin;
$img.crossOrigin = options.crossOrigin
}
const loadCallback = () => {
resolve({
element: $img,
...getImageMetadata($img),
});
})
}
if($img.decode) {
@@ -23,31 +44,26 @@ export function loadImage(url, options = {}) {
} else {
$img.onload = loadCallback
$img.onerror = (e) => {
reject(e);
};
reject(e)
}
$img.src = url
}
});
})
}
export function getImageMetadata($img) {
return {
url: $img.src,
width: $img.naturalWidth,
height: $img.naturalHeight,
ratio: $img.naturalWidth / $img.naturalHeight,
};
}
/**
* Lazy load the given image.
*
* @param {HTMLImageElement} $el - The image element.
* @param {?string} url - The URI to lazy load into $el.
* @param {HTMLImageElement} $el - The image element.
* @param {?string} url - The URI to lazy load into $el.
* If falsey, the value of the `data-src` attribute on $el will be used as the URI.
* @param {?function} callback - A function to call when the image is loaded.
* @param {?function} callback - A function to call when the image is loaded.
* @return {void}
*/
export async function lazyLoadImage($el, url, callback) {
const LAZY_LOADED_IMAGES = []
const lazyLoadImage = async ($el, url, callback) => {
let src = url ? url : $el.dataset.src
let loadedImage = LAZY_LOADED_IMAGES.find(image => image.url === src)
@@ -56,7 +72,7 @@ export async function lazyLoadImage($el, url, callback) {
loadedImage = await loadImage(src)
if (!loadedImage.url) {
return;
return
}
LAZY_LOADED_IMAGES.push(loadedImage)
@@ -67,13 +83,13 @@ export async function lazyLoadImage($el, url, callback) {
}
if ($el.tagName === 'IMG') {
$el.src = loadedImage.url;
$el.src = loadedImage.url
} else {
$el.style.backgroundImage = `url(${loadedImage.url})`;
$el.style.backgroundImage = `url(${loadedImage.url})`
}
requestAnimationFrame(() => {
let lazyParent = $el.closest('.c-lazy');
let lazyParent = $el.closest('.c-lazy')
if(lazyParent) {
lazyParent.classList.add('-lazy-loaded')
@@ -85,3 +101,10 @@ export async function lazyLoadImage($el, url, callback) {
callback?.()
})
}
export {
getImageMetadata,
loadImage,
lazyLoadImage
}

View File

@@ -1,37 +1,25 @@
const toString = Object.prototype.toString;
const arrayLikePattern = /^\[object (?:Array|FileList)\]$/;
/**
* Determines if the argument is object-like.
*
* A value is object-like if it's not `null` and has a `typeof` result of "object".
*
* @param {*} x - The value to be checked.
* @return {boolean}
*/
// thanks, http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
export function isArray ( thing ) {
return toString.call( thing ) === '[object Array]';
}
export function isArrayLike ( obj ) {
return arrayLikePattern.test( toString.call( obj ) );
}
export function isEqual ( a, b ) {
if ( a === null && b === null ) {
return true;
}
if ( typeof a === 'object' || typeof b === 'object' ) {
return false;
}
return a === b;
}
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
export function isNumeric ( thing ) {
return !isNaN( parseFloat( thing ) ) && isFinite( thing );
}
export function isObject ( thing ) {
return ( thing && toString.call( thing ) === '[object Object]' );
}
export function isFunction( thing ) {
const getType = {};
return thing && getType.toString.call(thing) === '[object Function]';
const isObject = x => (x && typeof x === 'object')
/**
* Determines if the argument is a function.
*
* @param {*} x - The value to be checked.
* @return {boolean}
*/
const isFunction = x => typeof x === 'function'
export {
isObject,
isFunction
}

View File

@@ -1,3 +1,54 @@
export function lerp(start, end, amt){
return (1 - amt) * start + amt * end
/**
* Clamp value
* @param {number} min - start value
* @param {number} max - end value
* @param {number} a - alpha value
* @return {number} clamped value
*/
const clamp = (min = 0, max = 1, a) => Math.min(max, Math.max(min, a))
/**
* Calculate lerp
* @param {number} x - start value
* @param {number} y - end value
* @param {number} a - alpha value
* @return {number} lerp value
*/
const lerp = (x, y, a) => x * (1 - a) + y * a
/**
* Calculate inverted lerp
* @param {number} x - start value
* @param {number} y - end value
* @param {number} a - alpha value
* @return {number} inverted lerp value
*/
const invlerp = (x, y, a) => clamp((v - x)/(a - x))
/**
* Round number to the specified precision.
*
* This function is necessary because `Number.prototype.toPrecision()`
* and `Number.prototype.toFixed()`
*
* @param {number} number - The floating point number to round.
* @param {number} [precision] - The number of digits to appear after the decimal point.
* @return {number} The rounded number.
*/
const roundNumber = (number, precision = 2) => {
return Number.parseFloat(number.toPrecision(precision));
}
export {
clamp,
lerp,
invlerp,
roundNumber
}

View File

@@ -0,0 +1,78 @@
/**
* Creates a debounced function.
*
* A debounced function delays invoking `callback` until after
* `delay` milliseconds have elapsed since the last time the
* debounced function was invoked.
*
* Useful for behaviour that should only happen _before_ or
* _after_ an event has stopped occurring.
*
* @template {function} T
*
* @param {T} callback - The function to debounce.
* @param {number} delay - The number of milliseconds to wait.
* @param {boolean} [immediate] -
* If `true`, `callback` is invoked before `delay`.
* If `false`, `callback` is invoked after `delay`.
* @return {function<T>} The new debounced function.
*/
const debounce = (callback, delay, immediate = false) => {
let timeout = null
return (...args) => {
clearTimeout(timeout)
const later = () => {
timeout = null
if (!immediate) {
callback(...args)
}
}
if (immediate && !timeout) {
callback(...args)
}
timeout = setTimeout(later, delay)
}
}
/**
* Creates a throttled function.
*
* A throttled function invokes `callback` at most once per every
* `delay` milliseconds.
*
* Useful for rate-limiting an event that occurs in quick succession.
*
* @template {function} T
*
* @param {T} callback - The function to throttle.
* @param {number} delay - The number of milliseconds to wait.
* @return {function<T>} The new throttled function.
*/
const throttle = (callback, delay) => {
let timeout = false
return (...args) => {
if (!timeout) {
timeout = true
callback(...args)
setTimeout(() => {
timeout = false
}, delay)
}
}
}
export {
debounce,
throttle
}

View File

@@ -1,21 +1,35 @@
export function transform(el, transformValue){
el.style.webkitTransform = transformValue;
el.style.msTransform = transformValue;
el.style.transform = transformValue;
/**
* Get translate function
* @param {HTMLElement} $el - DOM Element
* @return {number|object} translate value
*/
const getTranslate = $el => {
if(!window.getComputedStyle) {
return
}
let translate
const style = getComputedStyle($el)
const transform = style.msTransform || style.webkitTransform || style.MozTransform || style.OTransform || style.transform
const matrix3D = transform.match(/^matrix3d\((.+)\)$/)
if(matrix3D) {
translate = parseFloat(matrix3D[1].split(', ')[13])
} else {
const matrix = transform.match(/^matrix\((.+)\)$/)
translate = {
x: matrix ? parseFloat(matrix[1].split(', ')[4]) : 0
y: matrix ? parseFloat(matrix[1].split(', ')[5]) : 0
}
}
return translate
}
export function getTranslate(el){
const translate = {}
if(!window.getComputedStyle) return;
const style = getComputedStyle(el);
const transform = style.transform || style.webkitTransform || style.mozTransform;
let mat = transform.match(/^matrix3d\((.+)\)$/);
if(mat) return parseFloat(mat[1].split(', ')[13]);
mat = transform.match(/^matrix\((.+)\)$/);
translate.x = mat ? parseFloat(mat[1].split(', ')[4]) : 0;
translate.y = mat ? parseFloat(mat[1].split(', ')[5]) : 0;
return translate;
export {
transform,
getTranslate
}

View File

@@ -63,7 +63,7 @@ $checkbox-icon-color: $input-icon-color;
top: 50%;
left: 0;
display: inline-block;
margin-top: (-$checkbox / 2);
margin-top: math.div(-$checkbox, 2);
padding: 0;
width: $checkbox;
height: $checkbox;

View File

@@ -3,30 +3,29 @@
// ==========================================================================
.c-heading {
line-height: $line-height-h;
margin-bottom: rem(30px);
&.-h1 {
font-size: rem($font-size-h1);
font-size: var(--font-size-h1);
}
&.-h2 {
font-size: rem($font-size-h2);
font-size: var(--font-size-h2);
}
&.-h3 {
font-size: rem($font-size-h3);
font-size: var(--font-size-h3);
}
&.-h4 {
font-size: rem($font-size-h4);
font-size: var(--font-size-h4);
}
&.-h5 {
font-size: rem($font-size-h5);
font-size: var(--font-size-h5);
}
&.-h6 {
font-size: rem($font-size-h6);
font-size: var(--font-size-h6);
}
}

View File

@@ -2,6 +2,7 @@
// Elements / Document
// ==========================================================================
//
// Simple page-level setup.
//
// 1. Include web fonts
@@ -13,10 +14,9 @@
html {
min-height: 100%; // [2]
line-height: $line-height;
line-height: $line-height; // [3]
font-family: ff("sans");
color: $font-color;
line-height: $line-height; // [3]
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@@ -54,6 +54,11 @@ html {
&.has-scroll-smooth {
overflow: hidden;
position: fixed;
left: 0;
top: 0;
height: 100%;
width: 100%;
}
&.has-scroll-dragging {

View File

@@ -1,13 +1,7 @@
// ==========================================================================
// Main
// ==========================================================================
// Settings
// ==========================================================================
@import "settings/config.eases";
@import "settings/config.colors";
@import "settings/config";
@use "sass:math";
// ==========================================================================
// Tools
@@ -17,10 +11,18 @@
@import "tools/functions";
@import "tools/mixins";
@import "tools/fonts";
@import "tools/layout";
@import "tools/widths";
// @import "tools/layout";
// @import "tools/widths";
// @import "tools/family";
// Settings
// ==========================================================================
@import "settings/config.eases";
@import "settings/config.colors";
@import "settings/config";
@import "settings/config.variables";
// Generic
// ==========================================================================
@@ -42,8 +44,8 @@
@import "objects/container";
@import "objects/ratio";
@import "objects/icons";
@import "objects/layout";
// @import "objects/crop";
@import "objects/grid";
// @import "objects/layout";
// @import "objects/table";
// Vendors
@@ -62,7 +64,8 @@
// ==========================================================================
@import "utilities/ratio";
@import "utilities/widths";
@import "utilities/grid-column";
// @import "utilities/widths";
// @import "utilities/align";
// @import "utilities/helpers";
// @import "utilities/states";

View File

@@ -13,7 +13,6 @@
.o-container {
margin-right: auto;
margin-left: auto;
padding-right: rem($padding);
padding-left: rem($padding);
max-width: rem($container-width + ($padding * 2));
padding-left: var(--grid-margin);
padding-right: var(--grid-margin);
}

View File

@@ -1,83 +0,0 @@
// ==========================================================================
// Objects / Crop
// ==========================================================================
// @link https://github.com/inuitcss/inuitcss/blob/19d0c7e/objects/_objects.crop.scss
// A list of cropping ratios that get generated as modifier classes.
$crop-ratios: (
(2:1),
(4:3),
(16:9),
) !default;
// Provide a cropping container in order to display media (usually images)
// cropped to certain ratios.
//
// 1. Set up a positioning context in which the image can sit.
// 2. This is the crucial part: where the cropping happens.
.o-crop {
position: relative; // [1]
display: block;
overflow: hidden; // [2]
}
// Apply this class to the content (usually `img`) that needs cropping.
//
// 1. Images default positioning is top-left in the cropping box.
// 2. Make sure the media doesnt stop itself too soon.
.o-crop_content {
position: absolute;
top: 0; // [1]
left: 0; // [1]
max-width: none; // [2]
// We can position the media in different locations within the cropping area.
&.-right {
right: 0;
left: auto;
}
&.-bottom {
top: auto;
bottom: 0;
}
&.-center {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
}
/* stylelint-disable */
// Generate a series of crop classes to be used like so:
//
// @example
// <div class="o-crop -16:9">
.o-crop {
@each $crop in $crop-ratios {
@each $antecedent, $consequent in $crop {
@if (type-of($antecedent) != number) {
@error "`#{$antecedent}` needs to be a number.";
}
@if (type-of($consequent) != number) {
@error "`#{$consequent}` needs to be a number.";
}
&.-#{$antecedent}\:#{$consequent} {
padding-bottom: ($consequent/$antecedent) * 100%;
}
}
}
}
/* stylelint-enable */

View File

@@ -0,0 +1,178 @@
// ==========================================================================
// Grid helper
// ==========================================================================
// Help: https://css-tricks.com/snippets/css/complete-guide-grid/
//
/**
* Usage:
*
* ```html
* <div class="o-grid -col-4 -col-12@from-medium -gutters">
* <div class="o-grid_item u-gc-1/2 u-gc-3/9@from-medium">
* <p>Hello</p>
* </div>
* <div class="o-grid_item u-gc-3/4 u-gc-9/13@from-medium">
* <p>Hello</p>
* </div>
* </div>
* ```
*/
.o-grid {
display: grid;
width: 100%;
&:is(ul, ol) {
margin: 0;
padding: 0;
list-style: none;
}
// ==========================================================================
// Cols
// ==========================================================================
// Responsive grid columns based on `--grid-columns`
&.-cols {
grid-template-columns: repeat(var(--grid-columns), 1fr);
}
&.-col-#{$base-column-nb} {
grid-template-columns: repeat(#{$base-column-nb}, 1fr);
}
&.-col-4 {
grid-template-columns: repeat(4, 1fr);
}
&.-col-#{$base-column-nb}\@from-medium {
@media (min-width: $from-medium) {
grid-template-columns: repeat(#{$base-column-nb}, 1fr);
}
}
// ==========================================================================
// Gutters
// ==========================================================================
// Gutters rows and columns
&.-gutters {
gap: var(--grid-gutter);
column-gap: var(--grid-gutter);
}
// ==========================================================================
// Modifiers
// ==========================================================================
&.-full-height {
height: 100%;
}
// ==========================================================================
// Aligns
// ==========================================================================
// ==========================================================================
// Items inside cells
//
&.-top-items {
align-items: start;
}
&.-right-items {
justify-items: end;
}
&.-bottom-items {
align-items: end;
}
&.-left-items {
justify-items: start;
}
&.-center-items {
align-items: center;
justify-items: center;
}
&.-center-items-x {
justify-items: center;
}
&.-center-items-y {
align-items: center;
}
&.-stretch-items {
align-items: stretch;
justify-items: stretch;
}
// ==========================================================================
// Cells
//
&.-top-cells {
align-content: start;
}
&.-right-cells {
justify-content: end;
}
&.-bottom-cells {
align-content: end;
}
&.-left-cells {
justify-content: start;
}
&.-center-cells {
align-content: center;
justify-content: center;
}
&.-center-cells-x {
justify-content: center;
}
&.-center-cells-y {
align-content: center;
}
&.-stretch-cells {
align-content: stretch;
justify-content: stretch;
}
&.-space-around-cells {
align-content: space-around;
justify-content: space-around;
}
&.-space-around-cells-x {
justify-content: space-around;
}
&.-space-around-cells-y {
align-content: space-around;
}
&.-space-between-cells {
justify-content: space-between;
align-content: space-between;
}
&.-space-between-cells-x {
justify-content: space-between;
}
&.-space-between-cells-y {
align-content: space-between;
}
&.-space-evenly-cells {
justify-content: space-evenly;
align-content: space-evenly;
}
&.-space-evenly-cells-x {
justify-content: space-evenly;
}
&.-space-evenly-cells-y {
align-content: space-evenly;
}
}
// ==========================================================================
// Grid item
// ==========================================================================
// By default, a grid item takes full width of its parent.
//
.o-grid_item {
grid-column-start: var(--gc-start, 1);
grid-column-end: var(--gc-end, -1);
&.-align-end {
align-self: end;
}
}

View File

@@ -28,9 +28,7 @@ $font-fallback-mono: Menlo, Consolas, Monaco, Liberation Mono, Lucida Console
// <font-id>: (<font-name>, <font-fallbacks>)
// ```
$font-families: (
"sans": ("Webfont Sans", $font-fallback-sans),
// "serif": ("Webfont Serif", $font-fallback-serif),
// "mono": ("Webfont Mono", $font-fallback-mono)
sans: join("Source Sans", $font-fallback-sans, $separator: comma),
);
// List of custom font faces as tuples.
@@ -39,9 +37,10 @@ $font-families: (
// <font-name> <font-file-basename> <font-weight> <font-style>
// ```
$font-faces: (
// "Webfont Sans" "webfont-sans_regular" 400 normal,
// "Webfont Sans" "webfont-sans_regular-italic" 400 italic,
// "Webfont Serif" "webfont-sans_bold" 700 normal,
("Source Sans", "SourceSans3-Bold", 700, normal),
("Source Sans", "SourceSans3-BoldIt", 700, italic),
("Source Sans", "SourceSans3-Regular", 400, normal),
("Source Sans", "SourceSans3-RegularIt", 400, italic),
);
// Typography
@@ -49,18 +48,9 @@ $font-faces: (
// Base
$font-size: 16px;
$line-height: 24px / $font-size;
$line-height: math.div(24px, $font-size);
$font-color: $color-darkest;
// Headings
$font-size-h1: 36px !default;
$font-size-h2: 28px !default;
$font-size-h3: 24px !default;
$font-size-h4: 20px !default;
$font-size-h5: 18px !default;
$font-size-h6: 16px !default;
$line-height-h: $line-height;
// Weights
$font-weight-light: 300;
$font-weight-normal: 400;
@@ -75,15 +65,16 @@ $easing: $ease-power2-out;
// Spacing Units
// =============================================================================
$unit: 60px;
$unit-small: 30px;
$unit: 60px;
$unit-small: 20px;
// Container
// =============================================================================
// ==========================================================================
$padding: $unit;
$container-width: 2000px;
$padding: $unit;
// Grid
// ==========================================================================
$base-column-nb: 12;
// Breakpoints
// =============================================================================
@@ -111,15 +102,7 @@ $to-colossal: $from-colossal - 1 !default;
// =============================================================================
$z-indexes: (
"goku": 9000,
"transition": 500,
"toast": 400,
"popover": 300,
"modal": 250,
"sheet": 200,
"fixed": 150,
"sticky": 100,
"dropdown": 50,
"default": 1,
"limbo": -999
"header": 200,
"above": 1,
"below": -1
);

View File

@@ -0,0 +1,29 @@
// ==========================================================================
// Settings / Config / CSS VARS
// ==========================================================================
:root {
// Grid
--grid-columns: 4;
--grid-gutter: #{rem(10px)};
--grid-gutter-half: calc(0.5 * var(--grid-gutter));
--grid-margin: #{rem(10px)};
// Container
--container-width: calc(100% - 2 * var(--grid-margin));
// Font sizes
--font-size-h1: #{rem(36px)};
--font-size-h2: #{rem(28px)};
--font-size-h3: #{rem(24px)};
--font-size-h4: #{rem(20px)};
--font-size-h5: #{rem(18px)};
--font-size-h6: #{rem(16px)};
@media (min-width: $from-small) {
--grid-columns: #{$base-column-nb};
--grid-gutter: #{rem(16px)};
--grid-margin: #{rem(20px)};
}
}

View File

@@ -32,8 +32,14 @@
// @output The `@font-face` at-rules specifying the custom fonts.
@mixin font-faces($webfonts, $dir) {
@each $webfont in $webfonts {
@include font-face($webfont, $dir);
@if (length($webfonts) > 0) {
@if (type-of(nth($webfonts, 1)) == "list") {
@each $webfont in $webfonts {
@include font-face($webfont, $dir);
}
} @else {
@include font-face($webfonts, $dir);
}
}
}
@@ -47,8 +53,8 @@
@function ff($font-family) {
@if not map-has-key($font-families, $font-family) {
@error "No font-family found in $font-families map for `#{$font-family}`.";
}
@error "No font-family found in $font-families map for `#{$font-family}`.";
}
$value: map-get($font-families, $font-family);
@return $value;

View File

@@ -26,7 +26,7 @@
@error "`#{$base}` needs to be a number in pixel.";
}
@return ($size / $base) * 1em;
@return math.div($size, $base) * 1em;
}
// Converts the given pixel value to its REM quivalent.
@@ -45,7 +45,7 @@
@error "`#{$base}` needs to be a number in pixel.";
}
@return ($size / $base) * 1rem;
@return math.div($size, $base) * 1rem;
}
// Retrieves the z-index from the {@see $layers master list}.
@@ -60,7 +60,7 @@
// @return {number} The computed z-index of $layer and $modifier.
@function z($layer, $modifier: 0) {
@if not map-has-key($layers, $layer) {
@if not map-has-key($z-indexes, $layer) {
@error "Unknown master z-index layer: #{$layer}";
}

View File

@@ -57,7 +57,7 @@
@if (type-of($line-height) == number or $line-height == "inherit" or $line-height == "normal") {
line-height: $line-height $important;
}
@elseif ($line-height != "none" and $line-height != false) {
@else if ($line-height != "none" and $line-height != false) {
@error "Doh! `#{$line-height}` is not a valid value for `$line-height`.";
}
}

View File

@@ -0,0 +1,41 @@
// ==========================================================================
// Tools / Grid Columns
// ==========================================================================
//
// Grid layout system.
//
// This tool generates columns for all needed media queries.
// Unused classes will be purge by the css post-processor.
//
$colsMax: $base-column-nb + 1;
$breakpoints: (
"null" null,
"from-tiny" $from-tiny,
"from-small" $from-small,
"from-medium" $from-medium,
"from-large" $from-large,
"from-big" $from-big
) !default;
@each $breakpoint, $mediaquery in $breakpoints {
@for $fromIndex from 1 through $colsMax {
@for $toIndex from 1 through $colsMax {
@if $mediaquery == null {
.u-gc-#{$fromIndex}\/#{$toIndex} {
--gc-start: #{$fromIndex};
--gc-end: #{$toIndex};
}
} @else {
.u-gc-#{$fromIndex}\/#{$toIndex}\@#{$breakpoint} {
@media (min-width: #{$mediaquery}) {
--gc-start: #{$fromIndex};
--gc-end: #{$toIndex};
}
}
}
}
}
}

View File

@@ -28,8 +28,8 @@ $aspect-ratios: (
@error "`#{$consequent}` needs to be a number."
}
&.u-#{$antecedent}\:#{$consequent}::before {
padding-bottom: ($consequent/$antecedent) * 100%;
.u-#{$antecedent}\:#{$consequent}::before {
padding-bottom: math.div($consequent, $antecedent) * 100%;
}
}
}

View File

@@ -1,9 +1,11 @@
import concatFiles from './tasks/concats.js';
import compileScripts from './tasks/scripts.js';
import compileStyles from './tasks/styles.js' ;
import compileSVGs from './tasks/svgs.js' ;
import compileStyles from './tasks/styles.js';
import compileSVGs from './tasks/svgs.js';
import bumpVersions from './tasks/versions.js';
concatFiles();
compileScripts();
compileStyles();
compileSVGs();
bumpVersions();

29
build/helpers/config.js Normal file
View File

@@ -0,0 +1,29 @@
/**
* @file Provides simple user configuration options.
*/
import loconfig from '../../loconfig.json' assert { type: 'json' };
import { merge } from '../utils/index.js';
let usrconfig;
try {
usrconfig = await import('../../loconfig.local.json', {
assert: { type: 'json' },
});
usrconfig = usrconfig.default;
merge(loconfig, usrconfig);
} catch (err) {
// do nothing
}
loconfig.data = (loconfig.data ?? {});
loconfig.paths = (loconfig.paths ?? {});
loconfig.tasks = (loconfig.tasks ?? {});
export default loconfig;
export {
loconfig,
};

162
build/helpers/glob.js Normal file
View File

@@ -0,0 +1,162 @@
/**
* @file Retrieve the first available glob library.
*
* Note that options vary between libraries.
*
* Candidates:
*
* - {@link https://npmjs.com/package/tiny-glob tiny-glob} [1][5][6]
* - {@link https://npmjs.com/package/globby globby} [2][5]
* - {@link https://npmjs.com/package/fast-glob fast-glob} [3]
* - {@link https://npmjs.com/package/glob glob} [1][4][5]
*
* Notes:
*
* - [1] The library's function accepts only a single pattern.
* - [2] The library's function accepts only an array of patterns.
* - [3] The library's function accepts either a single pattern
* or an array of patterns.
* - [4] The library's function does not return a Promise but will be
* wrapped in a function that does return a Promise.
* - [5] The library's function will be wrapped in a function that
* supports a single pattern and an array of patterns.
* - [6] The library's function returns files and directories but will be
* preconfigured to return only files.
*/
import { promisify } from 'node:util';
/**
* @callback GlobFn
*
* @param {string|string[]} patterns - A string pattern
* or an array of string patterns.
* @param {object} options
*
* @returns {Promise<string[]>}
*/
/**
* @typedef {object} GlobOptions
*/
/**
* @type {GlobFn|undefined} The discovered glob function.
*/
let glob;
/**
* @type {string[]} A list of packages to attempt import.
*/
const candidates = [
'tiny-glob',
'globby',
'fast-glob',
'glob',
];
try {
glob = await importGlob();
} catch (err) {
// do nothing
}
/**
* @type {boolean} Whether a glob function was discovered (TRUE) or not (FALSE).
*/
const supportsGlob = (typeof glob === 'function');
/**
* Imports the first available glob function.
*
* @throws {TypeError} If no glob library was found.
*
* @returns {GlobFn}
*/
async function importGlob() {
for (let name of candidates) {
try {
let globModule = await import(name);
if (typeof globModule.default !== 'function') {
throw new TypeError(`Expected ${name} to be a function`);
}
/**
* Wrap the function to ensure
* a common pattern.
*/
switch (name) {
case 'tiny-glob':
/** [1][5] */
return createArrayableGlob(
/** [6] */
createPresetGlob(globModule.default, {
filesOnly: true
})
);
case 'globby':
/** [2][5] - If `patterns` is a string, wraps into an array. */
return (patterns, options) => globModule.default([].concat(patterns), options);
case 'glob':
/** [1][5] */
return createArrayableGlob(
/** [4] */
promisify(globModule.default)
);
default:
return globModule.default;
}
} catch (err) {
// swallow this error; skip to the next candidate.
}
}
throw new TypeError(
`No glob library was found, expected one of: ${candidates.join(', ')}`
);
}
/**
* Creates a wrapper function for the glob function
* to provide support for arrays of patterns.
*
* @param {function} globFn - The glob function.
*
* @returns {GlobFn}
*/
function createArrayableGlob(globFn) {
return (patterns, options) => {
/** [2] If `patterns` is a string, wraps into an array. */
patterns = [].concat(patterns);
const globs = patterns.map((pattern) => globFn(pattern, options));
return Promise.all(globs).then((files) => {
return [].concat.apply([], files);
});
};
}
/**
* Creates a wrapper function for the glob function
* to define new default options.
*
* @param {function} globFn - The glob function.
* @param {GlobOptions} presets - The glob function options to preset.
*
* @returns {GlobFn}
*/
function createPresetGlob(globFn, presets) {
return (patterns, options) => globFn(patterns, Object.assign({}, presets, options));
}
export default glob;
export {
glob,
supportsGlob,
};

View File

@@ -11,12 +11,16 @@ import kleur from 'kleur';
* @param {string} [type] - The type of message.
* @param {string} [timerID] - The console time label to output.
*/
export default function message(text, type, timerID) {
function message(text, type, timerID) {
switch (type) {
case 'success':
console.log('✅ ', kleur.bgGreen().black(text));
break;
case 'chore':
console.log('🧹 ', kleur.bgGreen().black(text));
break;
case 'notice':
console.log(' ', kleur.bgBlue().black(text));
break;
@@ -48,4 +52,10 @@ export default function message(text, type, timerID) {
}
console.log('');
}
export default message;
export {
message,
};

View File

@@ -16,7 +16,7 @@ import notifier from 'node-notifier';
* @param {function} callback - The notification callback.
* @return {void}
*/
export default function notification(options, callback) {
function notification(options, callback) {
if (typeof options === 'string') {
options = {
message: options
@@ -42,4 +42,10 @@ export default function notification(options, callback) {
}
notifier.notify(options, callback);
}
export default notification;
export {
notification,
};

139
build/helpers/postcss.js Normal file
View File

@@ -0,0 +1,139 @@
/**
* @file If available, returns the PostCSS Processor creator and
* any the Autoprefixer PostCSS plugin.
*/
/**
* @typedef {import('autoprefixer').autoprefixer.Options} AutoprefixerOptions
*/
/**
* @typedef {import('postcss').AcceptedPlugin} AcceptedPlugin
*/
/**
* @typedef {import('postcss').Postcss} Postcss
*/
/**
* @typedef {import('postcss').ProcessOptions} ProcessOptions
*/
/**
* @typedef {import('postcss').Processor} Processor
*/
/**
* @typedef {AcceptedPlugin[]} PluginList
*/
/**
* @typedef {object<string, AcceptedPlugin>} PluginMap
*/
/**
* @typedef {PluginList|PluginMap} PluginCollection
*/
/**
* @typedef {object} PostCSSOptions
*
* @property {ProcessOptions} processor - The `Processor#process()` options.
* @property {AutoprefixerOptions} autoprefixer - The `autoprefixer()` options.
*/
/**
* @type {Postcss|undefined} postcss - The discovered PostCSS function.
* @type {AcceptedPlugin|undefined} autoprefixer - The discovered Autoprefixer function.
*/
let postcss, autoprefixer;
try {
postcss = await import('postcss');
postcss = postcss.default;
autoprefixer = await import('autoprefixer');
autoprefixer = autoprefixer.default;
} catch (err) {
// do nothing
}
/**
* @type {boolean} Whether PostCSS was discovered (TRUE) or not (FALSE).
*/
const supportsPostCSS = (typeof postcss === 'function');
/**
* @type {PluginList} A list of supported plugins.
*/
const pluginsList = [
autoprefixer,
];
/**
* @type {PluginMap} A map of supported plugins.
*/
const pluginsMap = {
'autoprefixer': autoprefixer,
};
/**
* Attempts to create a PostCSS Processor with the given plugins and options.
*
* @param {PluginCollection} pluginsListOrMap - A list or map of plugins.
* If a map of plugins, the plugin name looks up `options`.
* @param {PostCSSOptions} options - The PostCSS wrapper options.
*
* @returns {Processor|null}
*/
function createProcessor(pluginsListOrMap, options)
{
if (!postcss) {
return null;
}
const plugins = parsePlugins(pluginsListOrMap, options);
return postcss(plugins);
}
/**
* Parses the PostCSS plugins and options.
*
* @param {PluginCollection} pluginsListOrMap - A list or map of plugins.
* If a map of plugins, the plugin name looks up `options`.
* @param {PostCSSOptions} options - The PostCSS wrapper options.
*
* @returns {PluginList}
*/
function parsePlugins(pluginsListOrMap, options)
{
if (Array.isArray(pluginsListOrMap)) {
return pluginsListOrMap;
}
/** @type {PluginList} */
const plugins = [];
for (let [ name, plugin ] of Object.entries(pluginsListOrMap)) {
if (name in options) {
plugin = plugin[name](options[name]);
}
plugins.push(plugin);
}
return plugins;
}
export default postcss;
export {
autoprefixer,
createProcessor,
parsePlugins,
pluginsList,
pluginsMap,
postcss,
supportsPostCSS,
};

View File

@@ -3,9 +3,14 @@
*/
import loconfig from './config.js';
import {
escapeRegExp,
flatten
} from '../utils/index.js';
const templateData = flatten({
paths: loconfig.paths
...loconfig.data,
paths: loconfig.paths,
});
/**
@@ -22,7 +27,7 @@ const templateData = flatten({
* @param {object} [data] - An object in the form `{ 'from': 'to', … }`.
* @return {*} Returns the transformed value.
*/
export default function resolve(input, data = templateData) {
function resolve(input, data = templateData) {
switch (typeof input) {
case 'string': {
return resolveValue(input, data);
@@ -56,7 +61,7 @@ export default function resolve(input, data = templateData) {
* @param {object} [data] - An object in the form `{ 'from': 'to', … }`.
* @return {string} Returns the translated string.
*/
export function resolveValue(input, data = templateData) {
function resolveValue(input, data = templateData) {
const tags = [];
if (data !== templateData) {
@@ -93,55 +98,9 @@ export function resolveValue(input, data = templateData) {
});
}
/**
* Creates a new object with all nested object properties
* concatenated into it recursively.
*
* Nested keys are flattened into a property path:
*
* ```js
* {
* a: {
* b: {
* c: 1
* }
* },
* d: 1
* }
* ```
*
* ```js
* {
* "a.b.c": 1,
* "d": 1
* }
* ```
*
* @param {object} input - The object to flatten.
* @param {string} prefix - The parent key prefix.
* @param {object} target - The object that will receive the flattened properties.
* @return {object} Returns the `target` object.
*/
function flatten(input, prefix, target = {}) {
for (let key in input) {
let field = (prefix ? prefix + '.' + key : key);
export default resolve;
if (typeof input[key] === 'object') {
flatten(input[key], field, target);
} else {
target[field] = input[key];
}
}
return target;
}
/**
* Quotes regular expression characters.
*
* @param {string} str - The input string.
* @return {string} Returns the quoted (escaped) string.
*/
function escapeRegExp(str) {
return str.replace(/[\[\]\{\}\(\)\-\*\+\?\.\,\\\^\$\|\#\s]/g, '\\$&');
}
export {
resolve,
resolveValue,
};

View File

@@ -1,8 +1,9 @@
import loconfig from '../utils/config.js';
import glob from '../utils/glob.js';
import message from '../utils/message.js';
import notification from '../utils/notification.js';
import resolve from '../utils/template.js';
import loconfig from '../helpers/config.js';
import glob, { supportsGlob } from '../helpers/glob.js';
import message from '../helpers/message.js';
import notification from '../helpers/notification.js';
import resolve from '../helpers/template.js';
import { merge } from '../utils/index.js';
import concat from 'concat';
import {
basename,
@@ -64,7 +65,7 @@ export const productionConcatFilesArgs = [
* @return {Promise}
*/
export default async function concatFiles(globOptions = null, concatOptions = null) {
if (glob) {
if (supportsGlob) {
if (globOptions == null) {
globOptions = productionGlobOptions;
} else if (
@@ -72,7 +73,7 @@ export default async function concatFiles(globOptions = null, concatOptions = nu
globOptions !== developmentGlobOptions &&
globOptions !== productionGlobOptions
) {
globOptions = Object.assign({}, defaultGlobOptions, globOptions);
globOptions = merge({}, defaultGlobOptions, globOptions);
}
}
@@ -82,9 +83,18 @@ export default async function concatFiles(globOptions = null, concatOptions = nu
concatOptions !== developmentConcatOptions &&
concatOptions !== productionConcatOptions
) {
concatOptions = Object.assign({}, defaultConcatOptions, concatOptions);
concatOptions = merge({}, defaultConcatOptions, concatOptions);
}
/**
* @async
* @param {object} entry - The entrypoint to process.
* @param {string[]} entry.includes - One or more paths to process.
* @param {string} entry.outfile - The file to write to.
* @param {?string} [entry.label] - The task label.
* Defaults to the outfile name.
* @return {Promise}
*/
loconfig.tasks.concats.forEach(async ({
includes,
outfile,
@@ -98,25 +108,25 @@ export default async function concatFiles(globOptions = null, concatOptions = nu
console.time(timeLabel);
try {
if (!Array.isArray(includes)) {
includes = [ includes ];
}
includes = resolve(includes);
outfile = resolve(outfile);
let files;
if (glob && globOptions) {
files = await glob(includes, globOptions);
} else {
files = includes;
if (supportsGlob && globOptions) {
includes = await glob(includes, globOptions);
}
if (concatOptions.removeDuplicates) {
files = files.map((path) => normalize(path));
files = [ ...new Set(files) ];
includes = includes.map((path) => normalize(path));
includes = [ ...new Set(includes) ];
}
await concat(files, outfile);
await concat(includes, outfile);
if (files.length) {
if (includes.length) {
message(`${label} concatenated`, 'success', timeLabel);
} else {
message(`${label} is empty`, 'notice', timeLabel);

View File

@@ -1,7 +1,8 @@
import loconfig from '../utils/config.js';
import message from '../utils/message.js';
import notification from '../utils/notification.js';
import resolve from '../utils/template.js';
import loconfig from '../helpers/config.js';
import message from '../helpers/message.js';
import notification from '../helpers/notification.js';
import resolve from '../helpers/template.js';
import { merge } from '../utils/index.js';
import esbuild from 'esbuild';
import { basename } from 'node:path';
@@ -50,9 +51,20 @@ export default async function compileScripts(esBuildOptions = null) {
esBuildOptions !== developmentESBuildOptions &&
esBuildOptions !== productionESBuildOptions
) {
esBuildOptions = Object.assign({}, defaultESBuildOptions, esBuildOptions);
esBuildOptions = merge({}, defaultESBuildOptions, esBuildOptions);
}
/**
* @async
* @param {object} entry - The entrypoint to process.
* @param {string[]} entry.includes - One or more paths to process.
* @param {string} [entry.outdir] - The directory to write to.
* @param {string} [entry.outfile] - The file to write to.
* @param {?string} [entry.label] - The task label.
* Defaults to the outdir or outfile name.
* @throws {TypeError} If outdir and outfile are missing.
* @return {Promise}
*/
loconfig.tasks.scripts.forEach(async ({
includes,
outdir = '',
@@ -67,6 +79,10 @@ export default async function compileScripts(esBuildOptions = null) {
console.time(timeLabel);
try {
if (!Array.isArray(includes)) {
includes = [ includes ];
}
includes = resolve(includes);
if (outdir) {

View File

@@ -1,12 +1,18 @@
import loconfig from '../utils/config.js';
import message from '../utils/message.js';
import notification from '../utils/notification.js';
import postcss, { pluginsMap as postcssPluginsMap } from '../utils/postcss.js';
import resolve from '../utils/template.js';
import loconfig from '../helpers/config.js';
import message from '../helpers/message.js';
import notification from '../helpers/notification.js';
import {
createProcessor,
pluginsMap as postcssPluginsMap,
supportsPostCSS
} from '../helpers/postcss.js';
import resolve from '../helpers/template.js';
import { merge } from '../utils/index.js';
import { writeFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { promisify } from 'node:util';
import sass from 'node-sass';
import sass from 'sass';
import { PurgeCSS } from 'purgecss';
const sassRender = promisify(sass.render);
@@ -22,6 +28,7 @@ export const defaultSassOptions = {
sourceMap: true,
sourceMapContents: true,
};
export const developmentSassOptions = Object.assign({}, defaultSassOptions, {
outputStyle: 'expanded',
});
@@ -80,10 +87,10 @@ export default async function compileStyles(sassOptions = null, postcssOptions =
sassOptions !== developmentSassOptions &&
sassOptions !== productionSassOptions
) {
sassOptions = Object.assign({}, defaultSassOptions, sassOptions);
sassOptions = merge({}, defaultSassOptions, sassOptions);
}
if (postcss) {
if (supportsPostCSS) {
if (postcssOptions == null) {
postcssOptions = productionPostCSSOptions;
} else if (
@@ -91,10 +98,19 @@ export default async function compileStyles(sassOptions = null, postcssOptions =
postcssOptions !== developmentPostCSSOptions &&
postcssOptions !== productionPostCSSOptions
) {
postcssOptions = Object.assign({}, defaultPostCSSOptions, postcssOptions);
postcssOptions = merge({}, defaultPostCSSOptions, postcssOptions);
}
}
/**
* @async
* @param {object} entry - The entrypoint to process.
* @param {string[]} entry.infile - The file to process.
* @param {string} entry.outfile - The file to write to.
* @param {?string} [entry.label] - The task label.
* Defaults to the outfile name.
* @return {Promise}
*/
loconfig.tasks.styles.forEach(async ({
infile,
outfile,
@@ -114,9 +130,9 @@ export default async function compileStyles(sassOptions = null, postcssOptions =
outFile: outfile,
}));
if (postcss && postcssOptions) {
if (supportsPostCSS && postcssOptions) {
if (typeof postcssProcessor === 'undefined') {
postcssProcessor = createPostCSSProcessor(
postcssProcessor = createProcessor(
postcssPluginsMap,
postcssOptions
);
@@ -142,7 +158,12 @@ export default async function compileStyles(sassOptions = null, postcssOptions =
}
try {
await writeFile(outfile, result.css);
await writeFile(outfile, result.css).then(() => {
// Purge CSS once file exists.
if (outfile) {
purgeUnusedCSS(outfile, `${label || `${filestem}.css`}`);
}
});
if (result.css) {
message(`${label || `${filestem}.css`} compiled`, 'success', timeLabel);
@@ -185,30 +206,36 @@ export default async function compileStyles(sassOptions = null, postcssOptions =
};
/**
* Creates a PostCSS Processor with the given plugins and options.
* Purge unused styles from CSS files.
*
* @param {array<(function|object)>|object<string, (function|object)>} pluginsListOrMap -
* A list or map of plugins.
* If a map of plugins, the plugin name looks up `options`.
* @param {object} options - The PostCSS options.
* @async
*
* @param {string} outfile - The path of a css file
* If missing the function stops.
* @param {string} label - The CSS file label or name.
* @return {Promise}
*/
function createPostCSSProcessor(pluginsListOrMap, options)
{
let plugins;
async function purgeUnusedCSS(outfile, label) {
label = label ?? basename(outfile);
if (Array.isArray(pluginsListOrMap)) {
plugins = pluginsListOrMap;
} else {
plugins = [];
const timeLabel = `${label} purged in`;
console.time(timeLabel);
for (let [ name, plugin ] of Object.entries(pluginsListOrMap)) {
if (name in options) {
plugin = plugin[name](options[name]);
}
const purgeCSSContentFiles = Array.from(loconfig.tasks.purgeCSS.content);
plugins.push(plugin);
const purgeCSSResults = await (new PurgeCSS()).purge({
content: purgeCSSContentFiles,
css: [ outfile ],
rejected: true,
defaultExtractor: (content) => content.match(/[a-z0-9_\-\\\/\@]+/gi) || [],
safelist: {
standard: [ /^((?!\bu-gc-).)*$/ ]
}
}
})
return postcss(plugins);
for (let result of purgeCSSResults) {
await writeFile(outfile, result.css)
message(`${label} purged`, 'chore', timeLabel);
}
}

View File

@@ -1,7 +1,8 @@
import loconfig from '../utils/config.js';
import message from '../utils/message.js';
import notification from '../utils/notification.js';
import resolve from '../utils/template.js';
import loconfig from '../helpers/config.js';
import message from '../helpers/message.js';
import notification from '../helpers/notification.js';
import resolve from '../helpers/template.js';
import { merge } from '../utils/index.js';
import { basename } from 'node:path';
import mixer from 'svg-mixer';
@@ -44,9 +45,18 @@ export default async function compileSVGs(mixerOptions = null) {
mixerOptions !== developmentMixerOptions &&
mixerOptions !== productionMixerOptions
) {
mixerOptions = Object.assign({}, defaultMixerOptions, mixerOptions);
mixerOptions = merge({}, defaultMixerOptions, mixerOptions);
}
/**
* @async
* @param {object} entry - The entrypoint to process.
* @param {string[]} entry.includes - One or more paths to process.
* @param {string} entry.outfile - The file to write to.
* @param {?string} [entry.label] - The task label.
* Defaults to the outfile name.
* @return {Promise}
*/
loconfig.tasks.svgs.forEach(async ({
includes,
outfile,
@@ -60,6 +70,10 @@ export default async function compileSVGs(mixerOptions = null) {
console.time(timeLabel);
try {
if (!Array.isArray(includes)) {
includes = [ includes ];
}
includes = resolve(includes);
outfile = resolve(outfile);

327
build/tasks/versions.js Normal file
View File

@@ -0,0 +1,327 @@
import loconfig from '../helpers/config.js';
import message from '../helpers/message.js';
import resolve from '../helpers/template.js';
import { merge } from '../utils/index.js';
import { randomBytes } from 'node:crypto';
import events from 'node:events';
import {
createReadStream,
createWriteStream,
} from 'node:fs';
import {
mkdir,
rename,
rm,
readFile,
writeFile,
} from 'node:fs/promises';
import {
basename,
dirname,
} from 'node:path';
import readline from 'node:readline';
/**
* @typedef {object} VersionOptions
* @property {string|number|null} prettyPrint - A string or number to insert
* white space into the output JSON string for readability purposes.
* @property {string} versionFormat - The version number format.
* @property {string|RegExp} versionKey - Either:
* - A string representing the JSON field name assign the version number to.
*
* Explicit:
*
* ```json
* "key": "json:version"
* ```
*
* Implicit:
*
* ```json
* "key": "version"
* ```
*
* - A `RegExp` object or regular expression string prefixed with `regexp:`.
*
* ```json
* "key": "regexp:(?<=^const ASSETS_VERSION = ')(?<version>\\d+)(?=';$)"
* ```
*
* ```js
* key: new RegExp('(?<=^const ASSETS_VERSION = ')(?<version>\\d+)(?=';$)')
* ```
*
* ```js
* key: /(?<=^const ASSETS_VERSION = ')(?<version>\d+)(?=';$)/
* ```
*/
/**
* @const {VersionOptions} defaultVersionOptions - The default shared version options.
* @const {VersionOptions} developmentVersionOptions - The predefined version options for development.
* @const {VersionOptions} productionVersionOptions - The predefined version options for production.
*/
export const defaultVersionOptions = {
prettyPrint: 4,
versionFormat: 'timestamp',
versionKey: 'version',
};
export const developmentVersionOptions = Object.assign({}, defaultVersionOptions);
export const productionVersionOptions = Object.assign({}, defaultVersionOptions);
/**
* @const {object} developmentVersionFilesArgs - The predefined `bumpVersion()` options for development.
* @const {object} productionVersionFilesArgs - The predefined `bumpVersion()` options for production.
*/
export const developmentVersionFilesArgs = [
developmentVersionOptions,
];
export const productionVersionFilesArgs = [
productionVersionOptions,
];
/**
* Bumps version numbers in file.
*
* @async
* @param {object} [versionOptions=null] - Customize the version options.
* If `null`, default production options are used.
* @return {Promise}
*/
export default async function bumpVersions(versionOptions = null) {
if (versionOptions == null) {
versionOptions = productionVersionOptions;
} else if (
versionOptions !== developmentVersionOptions &&
versionOptions !== productionVersionOptions
) {
versionOptions = merge({}, defaultVersionOptions, versionOptions);
}
const queue = new Map();
/**
* @async
* @param {object} entry - The entrypoint to process.
* @param {string} entry.outfile - The file to write to.
* @param {?string} [entry.label] - The task label.
* Defaults to the outfile name.
* @param {?string} [entry.format] - The version number format.
* @param {?string} [entry.key] - The JSON field name assign the version number to.
* @param {?string|number} [entry.pretty] - The white space to use to format the JSON file.
* @return {Promise}
*/
loconfig.tasks.versions.forEach(({
outfile,
label = null,
...options
}) => {
if (!label) {
label = basename(outfile || 'undefined');
}
options.pretty = (options.pretty ?? versionOptions.prettyPrint);
options.format = (options.format ?? versionOptions.versionFormat);
options.key = (options.key ?? versionOptions.versionKey);
if (queue.has(outfile)) {
queue.get(outfile).then(() => handleBumpVersion(outfile, label, options));
} else {
queue.set(outfile, handleBumpVersion(outfile, label, options));
}
});
};
/**
* Creates a formatted version number or string.
*
* @param {string} format - The version format.
* @return {string|number}
*/
function createVersionNumber(format) {
let [ type, modifier ] = format.split(':', 2);
switch (type) {
case 'hex':
case 'hexadecimal':
modifier = Number.parseInt(modifier);
if (Number.isNaN(modifier)) {
modifier = 6;
}
return randomBytes(modifier).toString('hex');
case 'regex':
return new RegExp(modifier);
case 'timestamp':
return Date.now().valueOf();
}
throw new TypeError(
'Expected \'format\' to be either "timestamp" or "hexadecimal"'
);
}
/**
* @async
* @param {string} outfile
* @param {string} label
* @param {object} options
* @return {Promise}
*/
async function handleBumpVersion(outfile, label, options) {
const timeLabel = `${label} bumped in`;
console.time(timeLabel);
try {
options.key = parseVersionKey(options.key);
if (options.key instanceof RegExp) {
await handleBumpVersionWithRegExp(outfile, label, options);
} else {
await handleBumpVersionInJson(outfile, label, options);
}
message(`${label} bumped`, 'success', timeLabel);
} catch (err) {
message(`Error bumping ${label}`, 'error');
message(err);
notification({
title: `${label} bumping failed 🚨`,
message: `${err.name}: ${err.message}`
});
}
}
/**
* Changes the version number for the provided JSON key in file.
*
* @async
* @param {string} outfile
* @param {string} label
* @param {object} options
* @param {string} options.key
* @return {Promise}
*/
async function handleBumpVersionInJson(outfile, label, options) {
outfile = resolve(outfile);
let json;
try {
json = JSON.parse(await readFile(outfile, { encoding: 'utf8' }));
} catch (err) {
json = {};
message(`${label} is a new file`, 'notice');
await mkdir(dirname(outfile), { recursive: true });
}
const version = createVersionNumber(options.format);
json[options.key] = version;
return await writeFile(
outfile,
JSON.stringify(json, null, options.pretty),
{ encoding: 'utf8' }
);
}
/**
* Changes the version number for the provided RegExp in file.
*
* @async
* @param {string} outfile
* @param {string} label
* @param {object} options
* @param {RegExp} options.key
* @return {Promise}
*/
async function handleBumpVersionWithRegExp(outfile, label, options) {
outfile = resolve(outfile);
const bckfile = `${outfile}~`;
await rename(outfile, bckfile);
try {
const rl = readline.createInterface({
input: createReadStream(bckfile),
});
const version = createVersionNumber(options.format);
const writeStream = createWriteStream(outfile, { encoding: 'utf8' });
rl.on('line', (line) => {
const found = line.match(options.key);
if (found) {
const groups = (found.groups ?? {});
const replace = found[0].replace(
(groups.build ?? groups.version ?? found[1] ?? found[0]),
version
);
line = line.replace(found[0], replace);
}
writeStream.write(line + "\n");
});
await events.once(rl, 'close');
await rm(bckfile);
} catch (err) {
await rm(outfile, { force: true });
await rename(bckfile, outfile);
throw err;
}
}
/**
* Parses the version key.
*
* @param {*} key - The version key.
* @return {string|RegExp}
*/
function parseVersionKey(key) {
if (key instanceof RegExp) {
return key;
}
if (typeof key !== 'string') {
throw new TypeError(
'Expected \'key\' to be either a string or a RegExp'
);
}
const delimiter = key.indexOf(':');
if (delimiter === -1) {
// Assumes its a JSON key
return key;
}
const type = key.slice(0, delimiter);
const value = key.slice(delimiter + 1);
switch (type) {
case 'json':
return value;
case 'regex':
case 'regexp':
return new RegExp(value);
}
throw new TypeError(
'Expected \'key\' type to be either "json" or "regexp"'
);
}

View File

@@ -1,64 +0,0 @@
/**
* @file Provides simple user configuration options.
*/
import loconfig from '../../loconfig.json';
let usrconfig;
try {
usrconfig = await import('../../loconfig.local.json');
usrconfig = usrconfig.default;
merge(loconfig, usrconfig);
} catch (err) {
// do nothing
}
export default loconfig;
/**
* Creates a new object with all nested object properties
* merged into it recursively.
*
* @param {object} target - The target object.
* @param {object[]} ...sources - The source object(s).
* @throws {TypeError} If the target and source are the same.
* @return {object} Returns the `target` object.
*/
export function merge(target, ...sources) {
for (const source of sources) {
if (target === source) {
throw new TypeError(
'Cannot merge, target and source are the same'
);
}
for (const key in source) {
if (source[key] != null) {
if (isObjectLike(source[key]) && isObjectLike(target[key])) {
merge(target[key], source[key]);
continue;
} else if (Array.isArray(source[key]) && Array.isArray(target[key])) {
target[key] = target[key].concat(source[key]);
continue;
}
}
target[key] = source[key];
}
}
return target;
}
/**
* Determines whether the passed value is an `Object`.
*
* @param {*} value - The value to be checked.
* @return {boolean} Returns `true` if the value is an `Object`,
* otherwise `false`.
*/
function isObjectLike(value) {
return (value != null && typeof value === 'object');
}

View File

@@ -1,95 +0,0 @@
/**
* @file Retrieve the first available glob library.
*
* Note that options vary between libraries.
*
* Candidates:
*
* - {@link https://npmjs.com/package/tiny-glob tiny-glob}
* - {@link https://npmjs.com/package/globby globby}
* - {@link https://npmjs.com/package/fast-glob fast-glob}
* - {@link https://npmjs.com/package/glob glob}
*/
import { promisify } from 'node:util';
/**
* @type {string[]} A list of packages to attempt import.
*/
const candidates = [
'tiny-glob',
'globby',
'fast-glob',
'glob',
];
let glob;
try {
glob = await importGlob();
} catch (err) {
// do nothing
}
export default glob;
/**
* Imports the first available glob function.
*
* @throws {TypeError} If no glob library was found.
* @return {function}
*/
async function importGlob() {
let glob, module;
for (let name of candidates) {
try {
module = await import(name);
if (typeof module.default !== 'function') {
throw new TypeError(`Expected ${name} to be a function`);
}
/**
* Wrap the function to ensure
* a common pattern.
*/
switch (name) {
case 'tiny-glob':
return createArrayableGlob(module.default, {
filesOnly: true
});
case 'glob':
return promisify(module.default);
default:
return module.default;
}
} catch (err) {
// swallow this error; skip to the next candidate.
}
}
throw new TypeError(
`No glob library was found, expected one of: ${candidates.join(', ')}`
);
}
/**
* Creates a wrapper function for the glob function
* to provide support for arrays of patterns.
*
* @param {function} glob - The glob function.
* @param {object} options - The glob options.
* @return {function}
*/
function createArrayableGlob(glob, options) {
return (patterns, options) => {
const globs = patterns.map((pattern) => glob(pattern, options));
return Promise.all(globs).then((files) => {
return [].concat.apply([], files);
});
};
}

115
build/utils/index.js Normal file
View File

@@ -0,0 +1,115 @@
/**
* @file Provides generic functions and constants.
*/
/**
* @type {RegExp} - Match all special characters.
*/
const regexUnescaped = /[\[\]\{\}\(\)\-\*\+\?\.\,\\\^\$\|\#\s]/g;
/**
* Quotes regular expression characters.
*
* @param {string} str - The input string.
* @return {string} Returns the quoted (escaped) string.
*/
function escapeRegExp(str) {
return str.replace(regexUnescaped, '\\$&');
}
/**
* Creates a new object with all nested object properties
* concatenated into it recursively.
*
* Nested keys are flattened into a property path:
*
* ```js
* {
* a: {
* b: {
* c: 1
* }
* },
* d: 1
* }
* ```
*
* ```js
* {
* "a.b.c": 1,
* "d": 1
* }
* ```
*
* @param {object} input - The object to flatten.
* @param {string} prefix - The parent key prefix.
* @param {object} target - The object that will receive the flattened properties.
* @return {object} Returns the `target` object.
*/
function flatten(input, prefix, target = {}) {
for (const key in input) {
const field = (prefix ? prefix + '.' + key : key);
if (isObjectLike(input[key])) {
flatten(input[key], field, target);
} else {
target[field] = input[key];
}
}
return target;
}
/**
* Determines whether the passed value is an `Object`.
*
* @param {*} value - The value to be checked.
* @return {boolean} Returns `true` if the value is an `Object`,
* otherwise `false`.
*/
function isObjectLike(value) {
return (value != null && typeof value === 'object');
}
/**
* Creates a new object with all nested object properties
* merged into it recursively.
*
* @param {object} target - The target object.
* @param {object[]} ...sources - The source object(s).
* @throws {TypeError} If the target and source are the same.
* @return {object} Returns the `target` object.
*/
function merge(target, ...sources) {
for (const source of sources) {
if (target === source) {
throw new TypeError(
'Cannot merge, target and source are the same'
);
}
for (const key in source) {
if (source[key] != null) {
if (isObjectLike(source[key]) && isObjectLike(target[key])) {
merge(target[key], source[key]);
continue;
} else if (Array.isArray(source[key]) && Array.isArray(target[key])) {
target[key] = target[key].concat(source[key]);
continue;
}
}
target[key] = source[key];
}
}
return target;
}
export {
escapeRegExp,
flatten,
isObjectLike,
merge,
regexUnescaped,
};

View File

@@ -1,27 +0,0 @@
/**
* @file If available, returns the PostCSS Processor creator and
* any the Autoprefixer PostCSS plugin.
*/
let postcss, autoprefixer;
try {
postcss = await import('postcss');
postcss = postcss.default;
autoprefixer = await import('autoprefixer');
autoprefixer = autoprefixer.default;
} catch (err) {
// do nothing
}
export default postcss;
export const pluginsList = [
autoprefixer,
];
export const pluginsMap = {
'autoprefixer': autoprefixer,
};
export {
autoprefixer
};

View File

@@ -2,10 +2,11 @@ import concatFiles, { developmentConcatFilesArgs } from './tasks/concats.js';
import compileScripts, { developmentScriptsArgs } from './tasks/scripts.js';
import compileStyles, { developmentStylesArgs } from './tasks/styles.js' ;
import compileSVGs, { developmentSVGsArgs } from './tasks/svgs.js';
import loconfig, { merge } from './utils/config.js';
import message from './utils/message.js';
import notification from './utils/notification.js';
import resolve from './utils/template.js';
import loconfig from './helpers/config.js';
import message from './helpers/message.js';
import notification from './helpers/notification.js';
import resolve from './helpers/template.js';
import { merge } from './utils/index.js';
import browserSync from 'browser-sync';
import { join } from 'node:path';
@@ -113,7 +114,8 @@ function createServerOptions({
}) {
const config = {
open: false,
notify: false
notify: false,
ghostMode: false
};
// Resolve the URL for the BrowserSync server

View File

@@ -15,6 +15,7 @@
* [`scripts`](#scripts)
* [`styles`](#styles)
* [`svgs`](#svgs)
* [`versions`](#versions)
---
@@ -28,7 +29,9 @@ Learn more about the boilerplate's [tasks](#tasks) below.
Make sure you have the following installed:
* [Node] — at least 14.17, the latest LTS is recommended.
* [NPM] — at least 6.0, the latest LTS is recommended.
* [NPM] — at least 8.0, the latest LTS is recommended.
> 💡 You can use [NVM] to install and use different versions of Node via the command-line.
```sh
# Switch to recommended Node version from .nvmrc
@@ -262,8 +265,8 @@ See [`scripts.js`](../build/tasks/scripts.js) for details.
### `styles`
A wrapper around [node-sass] (and optionally [Autoprefixer] via [PostCSS])
for compiling and minifying Sass into CSS.
A wrapper around [sass] (with optional support for [Autoprefixer]
via [PostCSS]) for compiling and minifying Sass into CSS.
By default, [PostCSS] and [Autoprefixer] are installed with the boilerplate.
@@ -298,6 +301,9 @@ Example:
See [`styles.js`](../build/tasks/styles.js) for details.
The task also supports [PurgeCSS] to remove unused CSS.
See the [documentation on our Grid System](grid.md#build-tasks) for details.
### `svgs`
A wrapper around [SVG Mixer] for transforming and minifying SVG files
@@ -328,6 +334,80 @@ Example:
See [`svgs.js`](../build/tasks/svgs.js) for details.
### `versions`
A task to create and update values for use in versioning assets.
Can generate a hexadecimal value (using random bytes) or
use the current timestamp.
Example:
```json
{
"versions": [
{
"format": "timestamp",
"key": "now",
"outfile": "./assets.json"
},
{
"format": "hex:8",
"key": "hex",
"outfile": "./assets.json"
}
]
}
```
```json
{
"now": 1665071717350,
"hex": "6ef54181c4ba"
}
```
The task supports replacing the value of a data key in a JSON file or replacing
a string in a file using a [regular expression](RegExp).
* Explicit JSON field name:
```json
{
"key": "json:version"
}
```
* Implicit JSON field name:
```json
{
"key": "version"
}
```
The regular expression can be a `RegExp` object or a pattern prefixed with `regexp:`.
* ```json
{
"key": "regexp:(?<=^const ASSETS_VERSION = ')(?<build>\\d+)(?=';$)"
}
```
* ```js
{
key: new RegExp('(?<=^const ASSETS_VERSION = ')(?<version>\\d+)(?=';$)')
}
```
* ```js
{
key: /^ \* Version: +(?:.+?)\+(.+?)$/
}
```
The regular expression pattern will match the first occurrence and replace
the first match in the following order: `build` (named capture), `version`
(named capture), `1` (first capture), or `0` (whole match).
See [`versions.js`](../build/tasks/versions.js) for details.
[Autoprefixer]: https://npmjs.com/package/autoprefixer
[BrowserSync]: https://npmjs.com/package/browser-sync
[concat]: https://npmjs.com/package/concat
@@ -336,9 +416,11 @@ See [`svgs.js`](../build/tasks/svgs.js) for details.
[glob]: https://npmjs.com/package/glob
[globby]: https://npmjs.com/package/globby
[Node]: https://nodejs.org/
[node-sass]: https://npmjs.com/package/node-sass
[sass]: https://npmjs.com/package/sass
[NPM]: https://npmjs.com/
[NVM]: https://github.com/nvm-sh/nvm
[PostCSS]: https://npmjs.com/package/postcss
[PurgeCSS]: https://purgecss.com/
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
[SVG Mixer]: https://npmjs.com/package/svg-mixer
[tiny-glob]: https://npmjs.com/package/tiny-glob

109
docs/grid.md Normal file
View File

@@ -0,0 +1,109 @@
# Grid system
* [Architectures](#architecture)
* [Build tasks](#build-tasks)
* [Configuration](#configuration)
* [Usage](#usage)
* [Example](#example)
## Architecture
The boilerplate's grid system is meant to be simple and easy to use. The goal is to create a light, flexible, and reusable way to build layouts.
The following styles are needed to work properly:
* [`o-grid`](../assets/styles/objects/_grid.scss) — Object file where the default grid styles are set such as column numbers, modifiers, and options.
* [`u-grid-columns`](../assets/styles/utilities/_grid-column.scss) — Utility file that generates the styles for every possible column based on an array of media queries and column numbers.
### Build tasks
The columns generated by [`u-grid-columns`](../assets/styles/utilities/_grid-column.scss) adds a lot of styles to the compiled CSS file. To mitigate that, [PurgeCSS] is integrated into the `styles` build task to purge unused CSS.
#### Configuration
Depending on your project, you will need to specify all the files that include CSS classes from the grid system. These files will be scanned by [PurgeCSS] to your compiled CSS files.
Example of a Charcoal project:
```jsonc
"purgeCSS": {
"content": [
"./views/app/template/**/*.mustache",
"./src/App/Template/*.php",
"./assets/scripts/**/*" // use case: `el.classList.add('u-gc-1/2')`
]
}
```
## Usage
The first step is to set intial SCSS values in the following files :
- [`settings/_config.scss`](../assets/styles/settings/_config.scss)
```scss
// Grid
// ==========================================================================
$base-column-nb: 12;
$base-column-gap: $unit-small;
```
You can create multiple column layouts depending on media queries.
- [`objects/_grid.scss`](../assets/styles/objects/_grid.scss)
```scss
.o-grid {
display: grid;
width: 100%;
margin: 0;
padding: 0;
list-style: none;
// ==========================================================================
// Cols
// ==========================================================================
&.-col-#{$base-column-nb} {
grid-template-columns: repeat(#{$base-column-nb}, 1fr);
}
&.-col-4 {
grid-template-columns: repeat(4, 1fr);
}
&.-col-#{$base-column-nb}\@from-medium {
@media (min-width: $from-medium) {
grid-template-columns: repeat(#{$base-column-nb}, 1fr);
}
}
// …
```
### Example
The following layout has 4 columns at `>=999px` and 12 columns at `<1000px`.
```html
<div class="o-container">
<h1 class="c-heading -h1">Hello</h1>
<div class="o-grid -col-4 -col-12@from-medium -gutters">
<div class="o-grid_item u-gc-1/8@from-medium">
<h2 class="c-heading -h2">This grid has 4 columns and 12 columns from `medium` MQ</h2>
</div>
<div class="o-grid_item u-gc-1/5@from-medium">
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Expedita provident distinctio deleniti eaque cumque doloremque aut quo dicta porro commodi, temporibus totam dolor autem tempore quasi ullam sed suscipit vero?</p>
</div>
<div class="o-grid_item u-gc-5/9@from-medium">
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Expedita provident distinctio deleniti eaque cumque doloremque aut quo dicta porro commodi, temporibus totam dolor autem tempore quasi ullam sed suscipit vero?</p>
</div>
<div class="o-grid_item u-gc-9/13@from-medium">
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Expedita provident distinctio deleniti eaque cumque doloremque aut quo dicta porro commodi, temporibus totam dolor autem tempore quasi ullam sed suscipit vero?</p>
</div>
</div>
</div>
```
[PurgeCSS]: https://purgecss.com/

View File

@@ -19,7 +19,7 @@
"dest": "./www/assets/images"
},
"views": {
"src": "./views/boilerplate/template"
"src": "./www/"
}
},
"tasks": {
@@ -56,6 +56,17 @@
],
"outfile": "{% paths.svgs.dest %}/sprite.svg"
}
],
"purgeCSS": {
"content": [
"./www/**/*.html",
"./assets/scripts/**/*"
]
},
"versions": [
{
"outfile": "./assets.json"
}
]
}
}

7280
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,8 +6,8 @@
"author": "Locomotive <info@locomotive.ca>",
"type": "module",
"engines": {
"node": ">=14.17",
"npm": ">=6.0"
"node": ">=17.9",
"npm": ">=8.0"
},
"scripts": {
"start": "node --experimental-json-modules --no-warnings build/watch.js",
@@ -21,15 +21,24 @@
"svg4everybody": "^2.1.9"
},
"devDependencies": {
"autoprefixer": "^10.4.4",
"browser-sync": "^2.27.9",
"autoprefixer": "^10.4.13",
"browser-sync": "^2.27.11",
"concat": "^1.0.3",
"esbuild": "^0.14.27",
"kleur": "^4.1.4",
"esbuild": "^0.17.6",
"kleur": "^4.1.5",
"node-notifier": "^10.0.1",
"node-sass": "^7.0.1",
"postcss": "^8.4.12",
"svg-mixer": "^2.3.14",
"postcss": "^8.4.21",
"purgecss": "^5.0.0",
"sass": "^1.57.1",
"svg-mixer": "~2.3.14",
"tiny-glob": "^0.2.9"
},
"overrides": {
"browser-sync": {
"ua-parser-js": "~1.0.33"
},
"svg-mixer": {
"postcss": "^8.4.20"
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -25,6 +25,7 @@
<ul>
<li><a href="images.html">Images</a></li>
<li><a href="form.html" data-load="customTransition">Form</a></li>
<li><a href="grid.html">Grid</a></li>
</ul>
</nav>
</header>

96
www/grid.html Normal file
View File

@@ -0,0 +1,96 @@
<!doctype html>
<html class="is-loading" lang="en" data-page="grid">
<head>
<meta charset="utf-8">
<title>Locomotive Boilerplate</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<meta name="msapplication-TileColor" content="#ffffff">
<link rel="manifest" href="site.webmanifest">
<link rel="apple-touch-icon" sizes="180x180" href="assets/images/favicons/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="assets/images/favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="assets/images/favicons/favicon-16x16.png">
<link rel="mask-icon" href="assets/images/favicons/safari-pinned-tab.svg" color="#000000">
<!-- For a dark mode managment and svg favicon add this in your favicon.svg -->
<!--
<style>
path {
fill: #000;
}
@media (prefers-color-scheme: dark) {
path {
fill: #fff;
}
}
</style>
-->
<!-- <link rel="icon" href="assets/images/favicons/favicon.svg"> -->
<link id="main-css" rel="stylesheet" href="assets/styles/main.css" media="print"
onload="this.media='all'; this.onload=null; this.isLoaded=true">
</head>
<body data-module-load>
<div data-load-container>
<div class="o-scroll" data-module-scroll="main">
<header data-scroll-section>
<a href="/">
<h1>Locomotive Boilerplate</h1>
</a>
<nav>
<ul>
<li><a href="images.html">Images</a></li>
<li><a href="form.html" data-load="customTransition">Form</a></li>
<li><a href="grid.html">Grid</a></li>
</ul>
</nav>
</header>
<main data-scroll-section>
<div class="o-container">
<h1 class="c-heading -h1">Hello</h1>
<div class="o-grid -col-4 -col-12@from-medium -gutters">
<div class="o-grid_item u-gc-1/8@from-medium" style="background-color: gray;">
<h2 class="c-heading -h2">This grid has 4 columns and 12 columns from `medium` MQ</h2>
</div>
<div class="o-grid_item u-gc-1/5@from-medium" style="background-color: yellow;">
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Expedita provident distinctio deleniti eaque cumque doloremque aut quo dicta porro commodi, temporibus totam dolor autem tempore quasi ullam sed suscipit vero?</p>
</div>
<div class="o-grid_item u-gc-5/9@from-medium" style="background-color: red;">
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Expedita provident distinctio deleniti eaque cumque doloremque aut quo dicta porro commodi, temporibus totam dolor autem tempore quasi ullam sed suscipit vero?</p>
</div>
<div class="o-grid_item u-gc-9/13@from-medium" style="background-color: blue;">
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Expedita provident distinctio deleniti eaque cumque doloremque aut quo dicta porro commodi, temporibus totam dolor autem tempore quasi ullam sed suscipit vero?</p>
</div>
<div class="o-grid_item u-gc-1/3 u-gc-5/13@from-medium" style="background-color: pink;">
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Expedita provident distinctio deleniti eaque cumque doloremque aut quo dicta porro commodi, temporibus totam dolor autem tempore quasi ullam sed suscipit vero?</p>
</div>
</div>
</div>
</main>
<footer data-scroll-section>
<p>Made with <a href="https://github.com/locomotivemtl/locomotive-boilerplate"
title="Locomotive Boilerplate" target="_blank" rel="noopener">🚂</a></p>
</footer>
</div>
</div>
<script nomodule src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.6.0/polyfill.min.js"
crossorigin="anonymous"></script>
<script nomodule
src="https://polyfill.io/v3/polyfill.min.js?features=Element.prototype.remove%2CElement.prototype.append%2Cfetch%2CCustomEvent%2CElement.prototype.matches%2CNodeList.prototype.forEach%2CAbortController"
crossorigin="anonymous"></script>
<script src="assets/scripts/vendors.js" defer></script>
<script src="assets/scripts/app.js" defer></script>
</body>
</html>

View File

@@ -25,6 +25,7 @@
<ul>
<li><a href="images.html">Images</a></li>
<li><a href="form.html" data-load="customTransition">Form</a></li>
<li><a href="grid.html">Grid</a></li>
</ul>
</nav>
</header>
@@ -39,8 +40,8 @@
<h3 class="c-heading -h3">Basic</h3>
<div style="width: 640px; max-width: 100%;">
<div class="o-ratio u-4:3"><img data-load-src="http://picsum.photos/640/480?v=1" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></div>
<div class="o-ratio u-4:3"><img data-load-src="http://picsum.photos/640/480?v=2" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></div>
<div class="o-ratio u-4:3"><img data-load-src="http://picsum.photos/800/600?v=1" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></div>
<div class="o-ratio u-4:3"><img data-load-src="http://picsum.photos/800/600?v=2" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></div>
</div>
<h4 class="c-heading -h3">Using o-ratio & background-image</h3>
@@ -58,30 +59,30 @@
<div style="width: 640px; max-width: 100%;">
<div class="o-ratio u-4:3">
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=1" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/800/600?v=1" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
</div>
<div class="o-ratio u-4:3">
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=2" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/800/600?v=2" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
</div>
<div class="o-ratio u-4:3">
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=3" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/800/600?v=3" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
</div>
<div class="o-ratio u-4:3">
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=4" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/800/600?v=4" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
</div>
<div class="o-ratio u-4:3">
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=5" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
<img data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/800/600?v=5" alt="" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />
</div>
</div>
<h4 class="c-heading -h3">Using o-ratio & background-image</h3>
<div style="width: 480px; max-width: 100%;">
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=1"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=2"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=3"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=4"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/640/480?v=5"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/1280/720?v=1"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/1280/720?v=2"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/1280/720?v=3"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/1280/720?v=4"></div>
<div style="background-size: cover; background-position: center;" class="o-ratio u-16:9" data-scroll data-scroll-call="lazyLoad, Scroll, main" data-src="http://picsum.photos/1280/720?v=5"></div>
</div>
<h4 class="c-heading -h3">Using SVG viewport for ratio</h3>

View File

@@ -29,11 +29,18 @@
-->
<!-- <link rel="icon" href="assets/images/favicons/favicon.svg"> -->
<!-- Preload Fonts -->
<link rel="preload" href="assets/fonts/SourceSans3-Bold.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/SourceSans3-BoldIt.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/SourceSans3-Regular.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/SourceSans3-RegularIt.woff2" as="font" type="font/woff2" crossorigin>
<link id="main-css" rel="stylesheet" href="assets/styles/main.css" media="print"
onload="this.media='all'; this.onload=null; this.isLoaded=true">
</head>
<body data-module-load>
<div data-load-container>
<div class="o-scroll" data-module-scroll="main">
<header data-scroll-section>
@@ -44,11 +51,12 @@
<ul>
<li><a href="images.html">Images</a></li>
<li><a href="form.html" data-load="customTransition">Form</a></li>
<li><a href="grid.html">Grid</a></li>
</ul>
</nav>
</header>
<main data-scroll-section>
<main data-module-example data-scroll-section>
<div class="o-container">
<h1 class="c-heading -h1">Hello</h1>
</div>