Browse Source

Merge pull request #25 from evrone/add-media-landscape

Add media landscape
pull/26/head
Dmitry Karpunin 7 years ago
committed by GitHub
parent
commit
8a04888323
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      .gitignore
  2. 26
      CHANGELOG.md
  3. 74
      CODE-OF-CONDUCT.md
  4. 25
      CONTRIBUTING.md
  5. 6
      LICENSE
  6. 120
      README.md
  7. 6
      example/index.js
  8. 4
      example/main-viewport.css
  9. 147
      index.js
  10. 2
      package.json
  11. 235
      spec/px-to-viewport.spec.js
  12. 14
      src/pixel-unit-regexp.js
  13. 152
      src/prop-list-matcher.js

1
.gitignore

@ -3,4 +3,5 @@ logs
*.log
npm-debug.log*
node_modules
.idea
postcss-px-to-em-master

26
CHANGELOG.md

@ -0,0 +1,26 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.1.0] - 2019-02-05
### Added
- `landscape` (Boolean) Adds `@media (orientation: landscape)` with values converted via `landscapeWidth`.
- `landscapeUnit` (String) Expected unit for `landscape` option
- `landscapeWidth` (Number) Viewport width for landscape orientation.
### Fixed
- `mediaQuery` option if `true` does not mutate its value now, but the rule inside it instead.
## [1.0.0] - 2019-01-28
### Added
- `replace` option - (Boolean) replaces rules containing `vw` instead of adding fallbacks.
- `propList` option - (Array) The properties that can change from `px` to `vw`.
- `exclude` option - (Array or Regexp) Ignore some files like `node_modules`.
### Changed
- zero values now remain unitless.
- replace regexp is now case sensitive, so if you want to change `px`, then `pX` values won't be changed.

74
CODE-OF-CONDUCT.md

@ -0,0 +1,74 @@
## Code of Conduct
### Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
### Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
### Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
### Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at codeofconduct@evrone.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

25
CONTRIBUTING.md

@ -0,0 +1,25 @@
# Contributing Guidelines
Thanks for taking the time to contribute!
The following is a set of guidelines for contributing to this project. These are just guidelines, not rules, so use your best judgement and feel free to propose changes to this document in a pull request.
## Reporting issues
Ensure the bug was not already reported by searching on GitHub under issues. If you're unable to find an open issue addressing the bug, open a new issue.
Please pay attention to the following points while opening an issue:
* How to reproduce the issue, step-by-step.
* The expected behavior (or what is wrong).
* Screenshots for GUI issues.
* The application version.
* The operating system.
## Pull Requests
Pull Requests are always welcome.
1. When you edit the code, please check the formatting of your code before you `git commit`.
2. Ensure the PR description clearly describes the problem and solution. It should include:
* The operating system on which you tested.
* The relevant issue number, if applicable.

6
LICENSE

@ -1,6 +1,6 @@
The MIT License (MIT)
MIT License
Copyright (c) 2016 Dmitry Karpunin <koderfunk@gmail.com>
Copyright (c) 2016-2019 Dmitry Karpunin <koderfunk@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOFTWARE.

120
README.md

@ -1,28 +1,20 @@
# postcss-px-to-viewport [![NPM version](https://badge.fury.io/js/postcss-px-to-viewport.svg)](http://badge.fury.io/js/postcss-px-to-viewport)
# postcss-px-to-viewport
[![NPM version](https://badge.fury.io/js/postcss-px-to-viewport.svg)](http://badge.fury.io/js/postcss-px-to-viewport)
A plugin for [PostCSS](https://github.com/postcss/postcss) that generates viewport units (vw, vh, vmin, vmax) from pixel units.
Feel free to start watching and ⭐ project in order not miss the release or updates.
<a href="https://evrone.com/?utm_source=postcss-px-to-viewport">
<img src="https://user-images.githubusercontent.com/417688/34437029-dbfe4ee6-ecab-11e7-9d80-2b274b4149b3.png"
alt="Sponsored by Evrone" width="231">
</a>
## Install
```
$ npm install postcss-px-to-viewport --save-dev
```
## Usage
## Demo
If your project involves a fixed width, this script will help to convert pixels into viewport units.
### Input/Output
### Input
```css
// input
.class {
margin: -10px .5vh;
padding: 5vmin 9.5px 1px;
@ -45,9 +37,10 @@ If your project involves a fixed width, this script will help to convert pixels
line-height: 22px;
}
}
```
// output
### Output
```css
.class {
margin: -3.125vw .5vh;
padding: 5vmin 2.96875vw 1px;
@ -64,58 +57,49 @@ If your project involves a fixed width, this script will help to convert pixels
line-height: 9.375vw;
}
@media (min-width: 234.375vw) {
@media (min-width: 750px) {
.class3 {
font-size: 5vw;
line-height: 6.875vw;
font-size: 16px;
line-height: 22px;
}
}
```
### Example
## Getting Started
```js
'use strict';
var fs = require('fs');
var postcss = require('postcss');
var pxToViewport = require('..');
var css = fs.readFileSync('main.css', 'utf8');
var options = {
replace: false
};
var processedCss = postcss(pxToViewport(options)).process(css).css;
fs.writeFile('main-viewport.css', processedCss, function (err) {
if (err) {
throw err;
}
console.log('File with viewport units written.');
});
### Installation
Add via npm
```
$ npm install postcss-px-to-viewport --save-dev
```
or yarn
```
$ yarn add postcss-px-to-viewport
```
### Options
### Usage
Default:
Default Options:
```js
{
unitToConvert: 'px',
viewportWidth: 320,
viewportHeight: 568, // not now used; TODO: need for different units and math for different properties
unitPrecision: 5,
propList: ['*'],
viewportUnit: 'vw',
fontViewportUnit: 'vw', // vmin is more suitable.
fontViewportUnit: 'vw',
selectorBlackList: [],
minPixelValue: 1,
mediaQuery: false,
replace: true,
exclude: [] // ignore some files
exclude: [],
landscape: false,
landscapeUnit: 'vw',
landscapeWidth: 568
}
```
- `unitToConvert` (String) unit to convert, by default, it is px.
- `viewportWidth` (Number) The width of the viewport.
- `viewportHeight` (Number) The height of the viewport.
- `unitPrecision` (Number) The decimal numbers to allow the vw units to grow to.
- `propList` (Array) The properties that can change from px to vw.
- Values need to be exact matches.
@ -136,9 +120,13 @@ Default:
- `exclude` (Array or Regexp) Ignore some files like 'node_modules'
- If value is regexp, will ignore the matches files.
- If value is array, the elements of the array are regexp.
- `landscape` (Boolean) Adds `@media (orientation: landscape)` with values converted via `landscapeWidth`.
- `landscapeUnit` (String) Expected unit for `landscape` option
- `landscapeWidth` (Number) Viewport width for landscape orientation.
### Use with gulp-postcss
add to your gulp config:
#### Use with gulp-postcss
add to your `gulpfile.js`:
```js
var gulp = require('gulp');
var postcss = require('gulp-postcss');
@ -158,8 +146,10 @@ gulp.task('css', function () {
.pipe(gulp.dest('build/css'));
});
```
### Use with Postcss configuration file
add to postcss.config.js
#### Use with PostCss configuration file
add to your `postcss.config.js`
```js
module.exports = {
plugins: {
@ -170,3 +160,41 @@ module.exports = {
}
}
```
## Running the tests
In order to run tests, you need to install `jasmine-node` globally:
```
$ npm install jasmine-node -g
```
Then run the tests via npm script:
```
$ npm run test
```
## Contributing
Please read [Code of Conduct](CODE-OF-CONDUCT.md) and [Contributing Guidelines](CONTRIBUTING.md) for submitting pull requests to us.
## Versioning
We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/evrone/postcss-px-to-viewport/tags).
## Changelog
The changelog is [here](CHANGELOG.md).
## Authors
* [Dmitry Karpunin](https://github.com/KODerFunk) - *Initial work*
* [Ivan Bunin](https://github.com/chernobelenkiy)
See also the list of [contributors](https://github.com/evrone/postcss-px-to-viewport/contributors) who participated in this project.
## License
This project is licensed under the [MIT License](LICENSE).
## Acknowledgments
* Hat tip to https://github.com/cuth/postcss-pxtorem/ for inspiring us for this project.

6
example/index.js

@ -4,10 +4,8 @@ var fs = require('fs');
var postcss = require('postcss');
var pxToViewport = require('..');
var css = fs.readFileSync('main.css', 'utf8');
var options = {
replace: false
};
var processedCss = postcss(pxToViewport(options)).process(css).css;
var processedCss = postcss(pxToViewport()).process(css).css;
fs.writeFile('main-viewport.css', processedCss, function (err) {
if (err) {

4
example/main-viewport.css

@ -14,8 +14,8 @@
}
@media (min-width: 750px) {
.class3 {
font-size: 5vw;
line-height: 6.875vw;
font-size: 16px;
line-height: 22px;
}
}

147
index.js

@ -3,6 +3,7 @@
var postcss = require('postcss');
var objectAssign = require('object-assign');
var { createPropListMatcher } = require('./src/prop-list-matcher');
var { getUnitRegexp } = require('./src/pixel-unit-regexp');
var defaults = {
unitToConvert: 'px',
@ -15,86 +16,107 @@ var defaults = {
propList: ['*'],
minPixelValue: 1,
mediaQuery: false,
replace: true
replace: true,
landscape: false,
landscapeUnit: 'vw',
landscapeWidth: 568
};
module.exports = postcss.plugin('postcss-px-to-viewport', function (options) {
var opts = objectAssign({}, defaults, options);
var pxReplace = createPxReplace(opts.viewportWidth, opts.minPixelValue, opts.unitPrecision, opts.viewportUnit);
// excluding regex trick: http://www.rexegg.com/regex-best-trick.html
// Not anything inside double quotes
// Not anything inside single quotes
// Not anything inside url()
// Any digit followed by px
// !singlequotes|!doublequotes|!url()|pixelunit
var pxRegex = new RegExp('"[^"]+"|\'[^\']+\'|url\\([^\\)]+\\)|(\\d*\\.?\\d+)' + opts.unitToConvert, 'g');
var satisfyPropList = createPropListMatcher(opts.propList);
var pxRegex = getUnitRegexp(opts.unitToConvert);
var satisfyPropList = createPropListMatcher(opts.propList);
var landscapeRules = [];
return function (css) {
css.walkDecls(function (decl, i) {
// Add exlclude option to ignore some files like 'node_modules'
if (opts.exclude && decl.source.input.file) {
css.walkRules(function (rule) {
// Add exclude option to ignore some files like 'node_modules'
var file = rule.source.input.file;
if (opts.exclude && file) {
if (Object.prototype.toString.call(opts.exclude) === '[object RegExp]') {
if (!handleExclude(opts.exclude, decl.source.input.file)) return;
if (isExclude(opts.exclude, file)) return;
} else if (Object.prototype.toString.call(opts.exclude) === '[object Array]') {
for (let i = 0; i < opts.exclude.length; ++i) {
if (!handleExclude(opts.exclude[i], decl.source.input.file)) return;
for (let i = 0; i < opts.exclude.length; i++) {
if (isExclude(opts.exclude[i], file)) return;
}
} else {
throw new Error('options.exclude should be RegExp or Array!');
throw new Error('options.exclude should be RegExp or Array.');
}
}
if (
decl.value.indexOf(opts.unitToConvert) === -1 ||
!satisfyPropList(decl.prop) ||
blacklistedSelector(opts.selectorBlackList, decl.parent.selector)
) return;
var unit = getUnit(decl.prop, opts);
var value = decl.value.replace(pxRegex, createPxReplace(opts.viewportWidth, opts.minPixelValue, opts.unitPrecision, unit));
if (declarationExists(decl.parent, decl.prop, value)) return;
if (opts.replace) {
decl.value = value;
} else {
decl.parent.insertAfter(i, decl.clone({ value: value }));
if (blacklistedSelector(opts.selectorBlackList, rule.selector)) return;
if (opts.landscape && !rule.parent.params) {
var landscapeRule = rule.clone().removeAll();
rule.walkDecls(function(decl) {
if (decl.value.indexOf(opts.unitToConvert) === -1) return;
if (!satisfyPropList(decl.prop)) return;
landscapeRule.append(decl.clone({
value: decl.value.replace(pxRegex, createPxReplace(opts, opts.landscapeUnit, opts.landscapeWidth))
}));
});
if (landscapeRule.nodes.length > 0) {
landscapeRules.push(landscapeRule);
}
}
});
if (opts.mediaQuery) {
css.walkAtRules('media', function (rule) {
if (rule.params.indexOf(opts.unitToConvert) === -1) return;
rule.params = rule.params.replace(pxRegex, pxReplace);
if (!validateParams(rule.parent.params, opts.mediaQuery)) return;
rule.walkDecls(function(decl, i) {
if (decl.value.indexOf(opts.unitToConvert) === -1) return;
if (!satisfyPropList(decl.prop)) return;
var unit;
var size;
var params = rule.parent.params;
if (opts.landscape && params && params.indexOf('landscape') !== -1) {
unit = opts.landscapeUnit;
size = opts.landscapeWidth;
} else {
unit = getUnit(decl.prop, opts);
size = opts.viewportWidth;
}
var value = decl.value.replace(pxRegex, createPxReplace(opts, unit, size));
if (declarationExists(decl.parent, decl.prop, value)) return;
if (opts.replace) {
decl.value = value;
} else {
decl.parent.insertAfter(i, decl.clone({ value: value }));
}
});
});
if (landscapeRules.length > 0) {
var landscapeRoot = new postcss.atRule({ params: '(orientation: landscape)', name: 'media' });
landscapeRules.forEach(function(rule) {
landscapeRoot.append(rule);
});
css.append(landscapeRoot);
}
};
});
function handleExclude (reg, file) {
if (Object.prototype.toString.call(reg) !== '[object RegExp]') {
throw new Error('options.exclude should be RegExp!');
}
if (file.match(reg) !== null) return false;
return true;
}
function getUnit(prop, opts) {
return prop.indexOf('font') === -1 ? opts.viewportUnit : opts.fontViewportUnit;
}
function createPxReplace(viewportSize, minPixelValue, unitPrecision, viewportUnit) {
function createPxReplace(opts, viewportUnit, viewportSize) {
return function (m, $1) {
if (!$1) return m;
var pixels = parseFloat($1);
if (pixels <= minPixelValue) return m;
var parsedVal = toFixed((pixels / viewportSize * 100), unitPrecision);
if (pixels <= opts.minPixelValue) return m;
var parsedVal = toFixed((pixels / viewportSize * 100), opts.unitPrecision);
return parsedVal === 0 ? '0' : parsedVal + viewportUnit;
};
}
@ -113,8 +135,19 @@ function blacklistedSelector(blacklist, selector) {
});
}
function isExclude(reg, file) {
if (Object.prototype.toString.call(reg) !== '[object RegExp]') {
throw new Error('options.exclude should be RegExp.');
}
return file.match(reg) !== null;
}
function declarationExists(decls, prop, value) {
return decls.some(function (decl) {
return (decl.prop === prop && decl.value === value);
});
}
return decls.some(function (decl) {
return (decl.prop === prop && decl.value === value);
});
}
function validateParams(params, mediaQuery) {
return !params || (params && mediaQuery);
}

2
package.json

@ -1,7 +1,7 @@
{
"name": "postcss-px-to-viewport",
"description": "A CSS post-processor that converts px to viewport units (vw, vh, vmin, vmax).",
"version": "1.0.0",
"version": "1.1.0",
"author": "Dmitry Karpunin <koderfunk@gmail.com>",
"license": "MIT",
"repository": {

235
spec/px-to-viewport.spec.js

@ -46,11 +46,18 @@ describe('px-to-viewport', function() {
});
it('should not add properties that already exist', function () {
var expected = '.rule { font-size: 16px; font-size: 5vw; }';
var processed = postcss(pxToViewport()).process(expected).css;
var expected = '.rule { font-size: 16px; font-size: 5vw; }';
var processed = postcss(pxToViewport()).process(expected).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
it('should not replace units inside mediaQueries by default', function() {
var expected = '@media (min-width: 500px) { .rule { font-size: 16px } }';
var processed = postcss(pxToViewport()).process('@media (min-width: 500px) { .rule { font-size: 16px } }').css;
expect(processed).toBe(expected);
})
});
describe('value parsing', function() {
@ -114,7 +121,7 @@ describe('viewportWidth', function() {
var expected = '.rule { font-size: 3.125vw }';
var options = {
viewportWidth: 480
}
};
var processed = postcss(pxToViewport(options)).process(basicCSS).css;
expect(processed).toBe(expected);
@ -123,13 +130,13 @@ describe('viewportWidth', function() {
describe('unitPrecision', function () {
it('should replace using a decimal of 2 places', function () {
var expected = '.rule { font-size: 4.69vw }';
var options = {
unitPrecision: 2
};
var processed = postcss(pxToViewport(options)).process(basicCSS).css;
var expected = '.rule { font-size: 4.69vw }';
var options = {
unitPrecision: 2
};
var processed = postcss(pxToViewport(options)).process(basicCSS).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
});
@ -161,104 +168,125 @@ describe('fontViewportUnit', function() {
describe('selectorBlackList', function () {
it('should ignore selectors in the selector black list', function () {
var rules = '.rule { font-size: 15px } .rule2 { font-size: 15px }';
var expected = '.rule { font-size: 4.6875vw } .rule2 { font-size: 15px }';
var options = {
selectorBlackList: ['.rule2']
};
var processed = postcss(pxToViewport(options)).process(rules).css;
var rules = '.rule { font-size: 15px } .rule2 { font-size: 15px }';
var expected = '.rule { font-size: 4.6875vw } .rule2 { font-size: 15px }';
var options = {
selectorBlackList: ['.rule2']
};
var processed = postcss(pxToViewport(options)).process(rules).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
it('should ignore every selector with `body$`', function () {
var rules = 'body { font-size: 16px; } .class-body$ { font-size: 16px; } .simple-class { font-size: 16px; }';
var expected = 'body { font-size: 5vw; } .class-body$ { font-size: 16px; } .simple-class { font-size: 5vw; }';
var options = {
selectorBlackList: ['body$']
};
var processed = postcss(pxToViewport(options)).process(rules).css;
var rules = 'body { font-size: 16px; } .class-body$ { font-size: 16px; } .simple-class { font-size: 16px; }';
var expected = 'body { font-size: 5vw; } .class-body$ { font-size: 16px; } .simple-class { font-size: 5vw; }';
var options = {
selectorBlackList: ['body$']
};
var processed = postcss(pxToViewport(options)).process(rules).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
it('should only ignore exactly `body`', function () {
var rules = 'body { font-size: 16px; } .class-body { font-size: 16px; } .simple-class { font-size: 16px; }';
var expected = 'body { font-size: 16px; } .class-body { font-size: 5vw; } .simple-class { font-size: 5vw; }';
var options = {
selectorBlackList: [/^body$/]
};
var processed = postcss(pxToViewport(options)).process(rules).css;
var rules = 'body { font-size: 16px; } .class-body { font-size: 16px; } .simple-class { font-size: 16px; }';
var expected = 'body { font-size: 16px; } .class-body { font-size: 5vw; } .simple-class { font-size: 5vw; }';
var options = {
selectorBlackList: [/^body$/]
};
var processed = postcss(pxToViewport(options)).process(rules).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
});
describe('mediaQuery', function () {
it('should replace px in media queries', function () {
var options = {
mediaQuery: true
};
var processed = postcss(pxToViewport(options)).process('@media (min-width: 500px) { .rule { font-size: 16px } }').css;
var expected = '@media (min-width: 156.25vw) { .rule { font-size: 5vw } }';
it('should replace px inside media queries if opts.mediaQuery', function() {
var options = {
mediaQuery: true
};
var processed = postcss(pxToViewport(options)).process('@media (min-width: 500px) { .rule { font-size: 16px } }').css;
var expected = '@media (min-width: 500px) { .rule { font-size: 5vw } }';
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
it('should not replace px inside media queries if not opts.mediaQuery', function() {
var options = {
mediaQuery: false
};
var processed = postcss(pxToViewport(options)).process('@media (min-width: 500px) { .rule { font-size: 16px } }').css;
var expected = '@media (min-width: 500px) { .rule { font-size: 16px } }';
expect(processed).toBe(expected);
});
it('should replace px inside media queries if it has params orientation landscape and landscape option', function() {
var options = {
mediaQuery: true,
landscape: true
};
var processed = postcss(pxToViewport(options)).process('@media (orientation-landscape) and (min-width: 500px) { .rule { font-size: 16px } }').css;
var expected = '@media (orientation-landscape) and (min-width: 500px) { .rule { font-size: 2.8169vw } }';
expect(processed).toBe(expected);
});
});
describe('propList', function () {
it('should only replace properties in the prop list', function () {
var css = '.rule { font-size: 16px; margin: 16px; margin-left: 5px; padding: 5px; padding-right: 16px }';
var expected = '.rule { font-size: 5vw; margin: 5vw; margin-left: 5px; padding: 5px; padding-right: 5vw }';
var options = {
propList: ['*font*', 'margin*', '!margin-left', '*-right', 'pad']
};
var processed = postcss(pxToViewport(options)).process(css).css;
var css = '.rule { font-size: 16px; margin: 16px; margin-left: 5px; padding: 5px; padding-right: 16px }';
var expected = '.rule { font-size: 5vw; margin: 5vw; margin-left: 5px; padding: 5px; padding-right: 5vw }';
var options = {
propList: ['*font*', 'margin*', '!margin-left', '*-right', 'pad']
};
var processed = postcss(pxToViewport(options)).process(css).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
it('should only replace properties in the prop list with wildcard', function () {
var css = '.rule { font-size: 16px; margin: 16px; margin-left: 5px; padding: 5px; padding-right: 16px }';
var expected = '.rule { font-size: 16px; margin: 5vw; margin-left: 5px; padding: 5px; padding-right: 16px }';
var options = {
propList: ['*', '!margin-left', '!*padding*', '!font*']
};
var processed = postcss(pxToViewport(options)).process(css).css;
var css = '.rule { font-size: 16px; margin: 16px; margin-left: 5px; padding: 5px; padding-right: 16px }';
var expected = '.rule { font-size: 16px; margin: 5vw; margin-left: 5px; padding: 5px; padding-right: 16px }';
var options = {
propList: ['*', '!margin-left', '!*padding*', '!font*']
};
var processed = postcss(pxToViewport(options)).process(css).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
it('should replace all properties when prop list is not given', function () {
var rules = '.rule { margin: 16px; font-size: 15px }';
var expected = '.rule { margin: 5vw; font-size: 4.6875vw }';
var processed = postcss(pxToViewport()).process(rules).css;
var rules = '.rule { margin: 16px; font-size: 15px }';
var expected = '.rule { margin: 5vw; font-size: 4.6875vw }';
var processed = postcss(pxToViewport()).process(rules).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
});
describe('minPixelValue', function () {
it('should not replace values below minPixelValue', function () {
var options = {
propWhiteList: [],
minPixelValue: 2
};
var rules = '.rule { border: 1px solid #000; font-size: 16px; margin: 1px 10px; }';
var expected = '.rule { border: 1px solid #000; font-size: 5vw; margin: 1px 3.125vw; }';
var processed = postcss(pxToViewport(options)).process(rules).css;
var options = {
propWhiteList: [],
minPixelValue: 2
};
var rules = '.rule { border: 1px solid #000; font-size: 16px; margin: 1px 10px; }';
var expected = '.rule { border: 1px solid #000; font-size: 5vw; margin: 1px 3.125vw; }';
var processed = postcss(pxToViewport(options)).process(rules).css;
expect(processed).toBe(expected);
expect(processed).toBe(expected);
});
});
describe('exclude', function () {
var rules = '.rule { border: 1px solid #000; font-size: 16px; margin: 1px 10px; }';
var covered = '.rule { border: 1px solid #000; font-size: 5vw; margin: 1px 3.125vw; }'
var covered = '.rule { border: 1px solid #000; font-size: 5vw; margin: 1px 3.125vw; }';
it('when using regex at the time, the style should not be overwritten.', function () {
var options = {
exclude: /node_modules/
}
};
var processed = postcss(pxToViewport(options)).process(rules, {
from: '/node_modules/main.css'
}).css;
@ -269,7 +297,7 @@ describe('exclude', function () {
it('when using regex at the time, the style should be overwritten.', function () {
var options = {
exclude: /node_modules/
}
};
var processed = postcss(pxToViewport(options)).process(rules, {
from: '/example/main.css'
}).css;
@ -280,7 +308,7 @@ describe('exclude', function () {
it('when using array at the time, the style should not be overwritten.', function () {
var options = {
exclude: [/node_modules/, /exclude/]
}
};
var processed = postcss(pxToViewport(options)).process(rules, {
from: '/exclude/main.css'
}).css;
@ -291,7 +319,7 @@ describe('exclude', function () {
it('when using array at the time, the style should be overwritten.', function () {
var options = {
exclude: [/node_modules/, /exclude/]
}
};
var processed = postcss(pxToViewport(options)).process(rules, {
from: '/example/main.css'
}).css;
@ -362,3 +390,72 @@ describe('filter-prop-list', function () {
});
});
describe('landscape', function() {
it('should add landscape atRule', function() {
var css = '.rule { font-size: 16px; margin: 16px; margin-left: 5px; padding: 5px; padding-right: 16px }';
var expected = '.rule { font-size: 5vw; margin: 5vw; margin-left: 1.5625vw; padding: 1.5625vw; padding-right: 5vw }@media (orientation: landscape) {.rule { font-size: 2.8169vw; margin: 2.8169vw; margin-left: 0.88028vw; padding: 0.88028vw; padding-right: 2.8169vw } }';
var options = {
landscape: true
};
var processed = postcss(pxToViewport(options)).process(css).css;
expect(processed).toBe(expected);
});
it('should add landscape atRule with specified landscapeUnits', function() {
var css = '.rule { font-size: 16px; margin: 16px; margin-left: 5px; padding: 5px; padding-right: 16px }';
var expected = '.rule { font-size: 5vw; margin: 5vw; margin-left: 1.5625vw; padding: 1.5625vw; padding-right: 5vw }@media (orientation: landscape) {.rule { font-size: 2.8169vh; margin: 2.8169vh; margin-left: 0.88028vh; padding: 0.88028vh; padding-right: 2.8169vh } }';
var options = {
landscape: true,
landscapeUnit: 'vh'
};
var processed = postcss(pxToViewport(options)).process(css).css;
expect(processed).toBe(expected);
});
it('should not add landscape atRule in mediaQueries', function() {
var css = '@media (min-width: 500px) { .rule { font-size: 16px } }';
var expected = '@media (min-width: 500px) { .rule { font-size: 5vw } }';
var options = {
landscape: true,
mediaQuery: true
};
var processed = postcss(pxToViewport(options)).process(css).css;
expect(processed).toBe(expected);
});
it('should not replace values inside landscape atRule', function() {
var options = {
replace: false,
landscape: true
};
var processed = postcss(pxToViewport(options)).process(basicCSS).css;
var expected = '.rule { font-size: 15px; font-size: 4.6875vw }@media (orientation: landscape) {.rule { font-size: 2.64085vw } }';
expect(processed).toBe(expected);
});
it('should add landscape atRule with specified landscapeWidth', function() {
var options = {
landscape: true,
landscapeWidth: 768
};
var processed = postcss(pxToViewport(options)).process(basicCSS).css;
var expected = '.rule { font-size: 4.6875vw }@media (orientation: landscape) {.rule { font-size: 1.95313vw } }';
expect(processed).toBe(expected);
});
it('should not add landscape atRule if it has no nodes', function() {
var css = '.rule { font-size: 15vw }';
var options = {
landscape: true
};
var processed = postcss(pxToViewport(options)).process(css).css;
var expected = '.rule { font-size: 15vw }';
expect(processed).toBe(expected);
})
});

14
src/pixel-unit-regexp.js

@ -0,0 +1,14 @@
// excluding regex trick: http://www.rexegg.com/regex-best-trick.html
// Not anything inside double quotes
// Not anything inside single quotes
// Not anything inside url()
// Any digit followed by px
// !singlequotes|!doublequotes|!url()|pixelunit
function getUnitRegexp(unit) {
return new RegExp('"[^"]+"|\'[^\']+\'|url\\([^\\)]+\\)|(\\d*\\.?\\d+)' + unit, 'g');
}
module.exports = {
getUnitRegexp
};

152
src/prop-list-matcher.js

@ -1,57 +1,57 @@
var filterPropList = {
exact: function (list) {
return list.filter(function (m) {
return m.match(/^[^\*\!]+$/);
});
return list.filter(function (m) {
return m.match(/^[^\*\!]+$/);
});
},
contain: function (list) {
return list.filter(function (m) {
return m.match(/^\*.+\*$/);
}).map(function (m) {
return m.substr(1, m.length - 2);
});
return list.filter(function (m) {
return m.match(/^\*.+\*$/);
}).map(function (m) {
return m.substr(1, m.length - 2);
});
},
endWith: function (list) {
return list.filter(function (m) {
return m.match(/^\*[^\*]+$/);
}).map(function (m) {
return m.substr(1);
});
return list.filter(function (m) {
return m.match(/^\*[^\*]+$/);
}).map(function (m) {
return m.substr(1);
});
},
startWith: function (list) {
return list.filter(function (m) {
return m.match(/^[^\*\!]+\*$/);
}).map(function (m) {
return m.substr(0, m.length - 1);
});
return list.filter(function (m) {
return m.match(/^[^\*\!]+\*$/);
}).map(function (m) {
return m.substr(0, m.length - 1);
});
},
notExact: function (list) {
return list.filter(function (m) {
return m.match(/^\![^\*].*$/);
}).map(function (m) {
return m.substr(1);
});
return list.filter(function (m) {
return m.match(/^\![^\*].*$/);
}).map(function (m) {
return m.substr(1);
});
},
notContain: function (list) {
return list.filter(function (m) {
return m.match(/^\!\*.+\*$/);
}).map(function (m) {
return m.substr(2, m.length - 3);
});
return list.filter(function (m) {
return m.match(/^\!\*.+\*$/);
}).map(function (m) {
return m.substr(2, m.length - 3);
});
},
notEndWith: function (list) {
return list.filter(function (m) {
return m.match(/^\!\*[^\*]+$/);
}).map(function (m) {
return m.substr(2);
});
return list.filter(function (m) {
return m.match(/^\!\*[^\*]+$/);
}).map(function (m) {
return m.substr(2);
});
},
notStartWith: function (list) {
return list.filter(function (m) {
return m.match(/^\![^\*]+\*$/);
}).map(function (m) {
return m.substr(1, m.length - 2);
});
return list.filter(function (m) {
return m.match(/^\![^\*]+\*$/);
}).map(function (m) {
return m.substr(1, m.length - 2);
});
}
};
@ -59,48 +59,48 @@ function createPropListMatcher(propList) {
var hasWild = propList.indexOf('*') > -1;
var matchAll = (hasWild && propList.length === 1);
var lists = {
exact: filterPropList.exact(propList),
contain: filterPropList.contain(propList),
startWith: filterPropList.startWith(propList),
endWith: filterPropList.endWith(propList),
notExact: filterPropList.notExact(propList),
notContain: filterPropList.notContain(propList),
notStartWith: filterPropList.notStartWith(propList),
notEndWith: filterPropList.notEndWith(propList)
exact: filterPropList.exact(propList),
contain: filterPropList.contain(propList),
startWith: filterPropList.startWith(propList),
endWith: filterPropList.endWith(propList),
notExact: filterPropList.notExact(propList),
notContain: filterPropList.notContain(propList),
notStartWith: filterPropList.notStartWith(propList),
notEndWith: filterPropList.notEndWith(propList)
};
return function (prop) {
if (matchAll) return true;
return (
(
hasWild ||
lists.exact.indexOf(prop) > -1 ||
lists.contain.some(function (m) {
return prop.indexOf(m) > -1;
}) ||
lists.startWith.some(function (m) {
return prop.indexOf(m) === 0;
}) ||
lists.endWith.some(function (m) {
return prop.indexOf(m) === prop.length - m.length;
})
) &&
!(
lists.notExact.indexOf(prop) > -1 ||
lists.notContain.some(function (m) {
return prop.indexOf(m) > -1;
}) ||
lists.notStartWith.some(function (m) {
return prop.indexOf(m) === 0;
}) ||
lists.notEndWith.some(function (m) {
return prop.indexOf(m) === prop.length - m.length;
})
)
);
if (matchAll) return true;
return (
(
hasWild ||
lists.exact.indexOf(prop) > -1 ||
lists.contain.some(function (m) {
return prop.indexOf(m) > -1;
}) ||
lists.startWith.some(function (m) {
return prop.indexOf(m) === 0;
}) ||
lists.endWith.some(function (m) {
return prop.indexOf(m) === prop.length - m.length;
})
) &&
!(
lists.notExact.indexOf(prop) > -1 ||
lists.notContain.some(function (m) {
return prop.indexOf(m) > -1;
}) ||
lists.notStartWith.some(function (m) {
return prop.indexOf(m) === 0;
}) ||
lists.notEndWith.some(function (m) {
return prop.indexOf(m) === prop.length - m.length;
})
)
);
};
}
module.exports = {
filterPropList,
createPropListMatcher
filterPropList,
createPropListMatcher
};
Loading…
Cancel
Save