GithubHelp home page GithubHelp logo

masaakim / stylefmt Goto Github PK

View Code? Open in Web Editor NEW
2.1K 37.0 89.0 583 KB

stylefmt is a tool that automatically formats stylesheets.

License: Other

JavaScript 69.54% CSS 30.46%
css formatter sass postcss postcss-plugins stylelint

stylefmt's Introduction

Modern CSS Formatter


Build Status NPM Version Downloads Dependency Status License Gitter


stylefmt is a tool that automatically formats CSS according to stylelint rules.

stylefmt'd code is:

  • easier to write : never worry about minor formatting concerns while hacking away.
  • easier to read : when all code looks the same you need not mentally convert others' formatting style into something you can understand.
  • easier to maintain : mechanical changes to the source don't cause unrelated changes to the file's formatting; diffs show only the real changes.
  • uncontroversial : never have a debate about spacing or brace position ever again!

NOTICE: Consider other tools before adopting stylefmt

If you are using stylefmt with stylelint configuration to format according to its rules, you can now use stylelint's --fix option (from v7.11.0) to autofix.

Another on the other hand, prettier supports to format not only JavaScript but also CSS, SCSS and Less code.

Features

  • Supports the latest CSS syntax: Including custom properties, range context for media features, calc() and nesting.
  • Understands CSS-like syntaxes: stylefmt is powered by PostCSS, so it understands any syntax that PostCSS can parse, including SCSS.
  • Works well with stylelint: stylelint is a mighty, modern CSS linter. stylefmt can understand the formatting rules specified in your stylelint configuration file (.stylelintrc).

Examples

Future CSS syntax (cssnext)

Input (input.css):

/* custom properties */
:root{--fontSize: 1rem;
  --mainColor       :#12345678;
--highlightColor:hwb(190, 35%, 20%);
}

/* custom media queries */
@custom-media

--viewport-medium(width<=50rem);

/* some var() & calc() */
body{color:var(--mainColor);
    font-size:var(--fontSize);
 line-height: calc(var(--fontSize) * 1.5);
padding: calc((var(--fontSize) / 2) + 1px)}

/* custom media query usage */
@media (--viewport-medium) {
body {font-size: calc(var(--fontSize) * 1.2); }
}

/* custom selectors */
@custom-selector :--heading h1,h2,h3,    h4,h5,h6;
:--heading { margin-top:0 }

/* colors stuff */
a{
color:var(--highlightColor);
    transition:color 1s;
}
a:hover{color  :gray(255,50%) }
a:active{color : rebeccapurple }
a:any-link { color:color(var(--highlightColor) blackness(+20%)) }

/* font stuff */
h2 {font-variant-caps:small-caps;
}table{font-variant-numeric: lining-nums;
}

/* filters */
.blur{filter:blur(4px)}.sepia{
filter: sepia(.8);}

Yield:

/* custom properties */
:root {
  --fontSize: 1rem;
  --mainColor: #12345678;
  --highlightColor: hwb(190, 35%, 20%);
}

/* custom media queries */
@custom-media --viewport-medium (width <= 50rem);

/* some var() & calc() */
body {
  color: var(--mainColor);
  font-size: var(--fontSize);
  line-height: calc(var(--fontSize) * 1.5);
  padding: calc((var(--fontSize) / 2) + 1px);
}

/* custom media query usage */
@media (--viewport-medium) {
  body {
    font-size: calc(var(--fontSize) * 1.2);
  }
}

/* custom selectors */
@custom-selector :--heading h1, h2, h3, h4, h5, h6;

:--heading {
  margin-top: 0;
}

/* colors stuff */
a {
  color: var(--highlightColor);
  transition: color 1s;
}

a:hover {
  color: gray(255, 50%);
}

a:active {
  color: rebeccapurple;
}

a:any-link {
  color: color(var(--highlightColor) blackness(+20%));
}

/* font stuff */
h2 {
  font-variant-caps: small-caps;
}

table {
  font-variant-numeric: lining-nums;
}

/* filters */
.blur {
  filter: blur(4px);
}

.sepia {
  filter: sepia(.8);
}

SCSS syntax

Input (input.scss):

// mixin for clearfix


        @mixin      clearfix    ()      { &:before,
  &:after {
                content:" ";
    display              : table;  }

  &:after        {clear: both;}
   }.class
{
       padding:10px;@include        clearfix();}
     .base {  color: red;  }

// placeholder
%base
{


padding: 12px
}

.foo{
@extend      .base;}

.bar
      {     @extend            %base;

}

Yield:

// mixin for clearfix
@mixin clearfix () {
  &:before,
  &:after {
    content: " ";
    display: table;
  }

  &:after {
    clear: both;
  }
}

.class {
  padding: 10px;
  @include clearfix();
}

.base {
  color: red;
}

// placeholder
%base {
  padding: 12px;
}

.foo {
  @extend .base;
}

.bar {
  @extend %base;
}

Installation

$ npm install stylefmt

Usage

in Command Line

CLI Help:

$ stylefmt --help
Usage: stylefmt [options] input-name [output-name]

Options:

  -b, --config-basedir   Path to the directory that relative paths defining "extends"
  -c, --config           Path to a specific configuration file (JSON, YAML, or CommonJS)
  -d, --diff             Output diff against original file
  -r, --recursive        Format list of space seperated files(globs) in place
  -v, --version          Output the version number
  -h, --help             Output usage information
  -i, --ignore-path      Path to a file containing patterns that describe files to ignore.
  --stdin-filename       A filename to assign stdin input.

stylefmt can also read a file from stdin if there are no input-file as argument in CLI.

$ cat input.css | stylefmt --stdin-filename input.css

in Node.js

var fs = require('fs');
var postcss = require('postcss');
var scss = require('postcss-scss'); // when you use scss syntax
var stylefmt = require('stylefmt');

var css = fs.readFileSync('input.css', 'utf-8');

postcss([
  stylefmt
]).process(css, {
    from: 'input.css',
    syntax: scss
  })
  .then(function (result) {
    result.css; // formatted code
  });

in Task Runners

We can use stylefmt in Grunt, gulp, and Fly.

stylelint rules that stylefmt can handle

stylefmt ❤️ stylelint

stylefmt supports the following stylelint rules:

and we can also format from the other stylelint's configration files or packages (e.g. stylelint-config-standard, stylelint-config-suitcss and so on) using extends property.

Default formatting rules (without stylelint config file)

Basic

  • 2 spaces indentation
  • require 1 space between a simple selector and combinator
  • require 1 space between selectors and {
  • require new line after {
  • disallow any spaces between property and :
  • require 1 space between : and values
  • require new line after declarations
  • require ; in last declaration
  • require 1 space between values and !important
  • disallow any spaces between ! and important
  • leave 1 blank line between rules
  • leave 1 blank line between rules in atrules
  • disallow any blank lines between @import

for nested selector syntax

  • leave 1 line between declarations and nested rules

SCSS

  • require 1 space between @mixin and mixin name
  • require 1 space between mixin name and (
  • require 1 space between @extend and base rules
  • require 1 space between @include and mixin name
  • disallow any spaces between $variable and :
  • require 1 space between : and name of variable

Option projects

Editor plugins

for Task Runners

License

The MIT License (MIT)

Copyright (c) 2015 Masaaki Morishita

stylefmt's People

Contributors

anber avatar appleboy avatar brunowego avatar callahad avatar cwonrails avatar dmnsgn avatar doochik avatar duncanbeevers avatar gitter-badger avatar hudochenkov avatar iblack10 avatar jorgebucaran avatar keens avatar kubosho avatar magicmark avatar masaakim avatar modosc avatar mrmlnc avatar nadavspi avatar nicolasartman avatar nkt avatar paazmaya avatar readmecritic avatar ryym avatar seka avatar sodoku avatar tomasalabes avatar vansosnin avatar vkryukov76 avatar vladimir-polyakov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stylefmt's Issues

Support for stylelint's max-line-length

For wrapping long list of selectors, support for max-line-length would be great to have. This can get a bit tricky to get right when it comes to comments and url, which should probably be left out from wrapping.

Example input

.aaaaaaaaaaaaaaaaaaaaaaaaaaa, .bbbbbbbbbbbbbbbbbbbbbbbbbbb, .ccccccccccccccccccccccccccc, .ddddddddddddddddddddddddddd {
  color: blue;
}

Example output, wrapped at 80:

.aaaaaaaaaaaaaaaaaaaaaaaaaaa, .bbbbbbbbbbbbbbbbbbbbbbbbbbb,
.ccccccccccccccccccccccccccc, .ddddddddddddddddddddddddddd {
  color: blue;
}

Empty line before nested rules

Hej,

Currently it adds an empty before nested rules even if there is no properties.

Input:

.Btn {
  &:hover {
  }

  &:active {
  }
}

Current output:

.Btn {

  &:hover {
  }

  &:active {
  }
}

Expected:

.Btn {
  &:hover {
  }

  &:active {
  }
}

Thanks

Incorrect spacing with @include

This:

@include font-face("Pictos", "../fonts/pictos-web");

Is formatted as:

// <-- line break
// <-- line break
@include font-face("Pictos", "../fonts/pictos-web") ; // <-- space before semicolon

Bug: indentation breaks when AtRules and Rules have different indentation

Indentation breaks when formatting this code (it should not change):

.class {
  @for $i from 1 through 10 {
    color: green;

    div {
      color: blue;
    }
  }
  color: white;
}
    expected: |-
      '.class {\n  @for $i from 1 through 10 {\n    color: green;\n\n    div {\n      color: blue;\n    }\n  }\n  color: white;\n}\n'
    actual: |-
      '.class {\n  @for $i from 1 through 10 {\n    color: green;\n\n    div {\n    color: blue;\n    }\n  }\n  color: white;\n}\n'

Everything works correctly if I remove the AtRule:

.class {
  div {
    color: green;

    div {
      color: blue;
    }
  }
  color: white;
}

Better format bracket

A plurality of nested brackets, ending a space reserved.

Input:

.foo {
  background: filter(radial-gradient(circle, #9ef, #0000af calc(100% - 20.38%)), hue-rotate(90deg))
}

Output:

.foo {
  background: filter( radial-gradient( circle, #9ef, #0000af calc(100% - 20.38%) ), hue-rotate(90deg) )
}

While adding an option, if you close this option, do not keep the space.

Doesn't work with NVM

Even though node is in the path it is not working with NVM.
Could also be related to my node version which is 5.6.0.

Dylans-MacBook-Pro:~ dylanpiercey$ which node
/Users/dylanpiercey/.nvm/versions/node/v5.6.0/bin/node
Dylans-MacBook-Pro:~ dylanpiercey$ node -v
v5.6.0

image

Add stylelint's color rules

It would be great to auto-correct colors according to the following stylelint rules:

color-hex-case: Specify lowercase or uppercase for hex colors.
color-hex-length: Specify short or long notation for hex colors.
color-named: Require (where possible) or disallow named colors.

http://stylelint.io/user-guide/rules/#color

I think all of those could be auto-corrected. Agree?

Need options?

Now, CSSfmt don't have options like Gofmt.
CSSfmt need options?

E.g:

  • indent width
  • when rule has only one declaration, allow to write one liner
  • not indent in Atrule block

Wrong media query indentation with @import

It doesn't indent the max-width properly when an @import declaration is on top:

@import "../../style/base/variables";
@import "bourbon";

.wrapper {
  @media (min-width: 1025px) {
  max-width: 600px;
  }
}

Wrong spacing on on adjacent selector (+) and parent (&) on SCSS

This:

.card-meta {
  @include padding(null 1rem 1rem);
  background-color: $card-base-background-color;
  color: $meta-font-color;

  .card-content--with-image + & { // <------
    padding-top: 1rem;
  }

  a {
    color: inherit;
  }
}

Gets spaced as:

.card-meta {
  @include padding(null 1rem 1rem);
  background-color: $card-base-background-color;
  color: $meta-font-color;

  .card-content--with-image+ & { // <------
    padding-top: 1rem;
  }

  a {
    color: inherit;
  }
}

Using the Sublime Plugin, but I assume it's a lib issue.

Ignoring a @font-face declaration

It's formatting this @font-face rule like this:

@font-face  {font-family:'Pictos';src:url("/fonts/pictos-web.eot");src:local("☺"),url("/fonts/pictos-web.woff") format("woff"),url("/fonts/pictos-web.ttf") format("truetype"),url("/fonts/pictos-web.svg#webfontIyfZbseF") format("svg");font-weight:normal;font-style:normal;
}

Any clues?

Format Sass function

input:

div {
  color: blue;
}
@function myFn  ($var-1,$var-2){
@return $var-1*$var-2;
}

we will get:

div {
  color: blue;
}

@function myFn($var-1, $var-2) {
  @return $var-1 * $var-2;
}

#47

Option to follow only rules described in .stylelintrc

Hey, it's great that you added support for .stylelintrc!
I started using it in my project and I have noticed that, apparently, stylefmt uses a merging strategy when choosing rules: it follows .stylelintrc rules and also applies stylefmt's standard ones for the rules it didn't find/recognize in .stylelintrc.
For instance, I follow stylelint-config-standard rules, where a block like

.selector-x { width: 10%; }

is allowed. Having a .stylelintrc with these simple contents

{
  "extends": "stylelint-config-standard"
}

does not raise an error or a warning when running stylelint for a block like the one ^. However, it gets auto formatted into

.selector-x { 
  width: 10%;
}

when I run stylefmt.

I think it would be great if there was a CLI option --only-stylelint or something like that which when passed would force stylefmt to format only the rules found/recognized in .stylelintrc file and do not do anything extra.

stylefmt adds a newline at the beginning of the file before variable declarations in scss

Hey, I found an issue with stylefmt default rules. It adds a newline at the beginning of the file when there is a variable declaration on the first line:

$border: 1px solid #fff;

.border {
  border: $border;
}

I run stylefmt example.scss and that file ^ gets transformed into:

// here there actually is a newline but github's markdown does not display it
$border: 1px solid #fff;

.border {
  border: $border;
}

In my opinion, it's not intended and a newline shouldn't be added in the beginning of the file.

data-url gets formatted badly

Running cmsfmt on a data-url (url(data:image/png;base64,iVBORw0KGg...)) got formatted so that an extra space is added after the decimal sign (url(data:image/png;base64, iVBORw0KGg...))

Editor plugins (add ST and others?)

Any plan on developing a bigger Editor plugins ecosystem? Sublime Text seems to be a good candidate for that kind of tool. A simple build system can do the trick for now:

{
    "cmd": ["cssfmt", "$file"],
    "selector": "source.css, source.scss",
    "path": "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin"
}

but it is not the more reliable solution.

Format Sass nested mixins

input:

@mixin test() {
  $values: blue red;
@each $val   in $values {
  color  : $val;
  @for $i   from  2   through    10 {
   background: $i;
  }
}
@for $i from 2 through 10 {
  color: $i;
}
}

we will get:

@mixin test() {
  $values: blue red;

  @each $val in $values {
    color: $val;

    @for $i from 2 through 10 {
      background: $i;
    }
  }

  @for $i from 2 through 10 {
    color: $i;
  }
}

#49

npm run script help

Please provide an example of how to get this working with npm run scripts. I am using SASS (and css-modules) but this is the error I am getting:

> stylefmt -R ./src/*.scss

/Users/chris/github/app/node_modules/stylefmt/bin/cli.js:72
    files.forEach(function (file) {
         ^

TypeError: Cannot read property 'forEach' of undefined

Appreciate it!

Space always missing when run cssfmt out of project folder

When I pipe content to the executable bin/cli.js in cssfmt folder, the result is corrent:

~/l/cssfmt(master|✚1…) $ cat ~/component-dev/iscroll/iscroll.css  | ./bin/cli.js
.iscroll-handlebar {
  position: absolute;
  right: 0px;
  top: 0px;
  transition: background-color 0.2s ease-out, transform 0.1s ease-out, width 0.1s ease-out, height 0.1s ease-out;
  width: 4px;
  border-radius: 2px;
  background-color: rgba(0, 0, 0, 0);
  z-index: 9999;
  height: 0px;
}

but when I run the command in another folder (like parent folder), all indent space is gone:

~/lib $ cat ~/component-dev/iscroll/iscroll.css | cssfmt/bin/cli.js
.iscroll-handlebar {
position: absolute;
right: 0px;
top: 0px;
transition: background-color 0.2s ease-out, transform 0.1s ease-out, width 0.1s ease-out, height 0.1s ease-out;
width: 4px;
border-radius: 2px;
background-color: rgba(0, 0, 0, 0);
z-index: 9999;
height: 0px;
}

Same bug occurs when I run command cssfmt

~/c/iscroll(master|…) $ cat iscroll.css | cssfmt
.iscroll-handlebar {
position: absolute;
right: 0px;
top: 0px;
transition: background-color 0.2s ease-out, transform 0.1s ease-out, width 0.1s ease-out, height 0.1s ease-out;
width: 4px;
border-radius: 2px;
background-color: rgba(0, 0, 0, 0);
z-index: 9999;
height: 0px;
}

I've no idea of how this could happen😞

my system is OSX El Capitan, npm version 2.14.7, node version v4.2.3

Thanks for help

stylefmt ignore .stylelintrc.json

Hi, Nice work for supporting stylelint configuration #61

I've noticed unexpected behavior that stylefmt ignore .stylelintrc.json(.stylelintrc.<ext> pattern).

stylelint can load config from .stylelintrc, .stylelintrc.json, .stylelintrc.yaml, .stylelintrc.js, .stylelintrc.config.js and a stylelint property in package.json.
Available file naming/format is defeined in cosmiconfig.

It is better that adding note like "only support .stylelintrc file (without extension)" to README, I think.

Declaration order

It would be awesome if you could make it so that it also orders the properties like this

.selector {
    /* Positioning */
    position: absolute;
    z-index: 10;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;

    /* Display & Box Model */
    display: inline-block;
    overflow: hidden;
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    padding: 10px;
    border: 10px solid #333;
    margin: 10px;

    /* Other */
    background: #000;
    color: #fff;
    font-family: sans-serif;
    font-size: 16px;
    text-align: right;
}

Or the way someone specifies. 😊

How many lines do you open between rules?

I see there is a ticket for options but was wondering is there a work around I could use to change this to only 1 line between rules? I am using your grunt plugin*

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.