Giter Club home page Giter Club logo

sc5-styleguide's Introduction

SC5 style guide generator

Build Status dependencies npm version

Looking for a maintainer

If you would like to maintain the project, create an issue and tell a few words about yourself.

Style guide generator is a handy little tool that helps you generate good looking style guides from style sheets using KSS notation. It can be used as a command line utility, gulp task or Grunt task (needs grunt-gulp) with minimal effort.

Table of contents

Usage

You should familiarize yourself with both KSS and node-kss to get yourself started.

SC5 Style guide provides additions to KSS syntax which you can learn below.

Prerequisites

The tool should be installed onto:

  • Node 4.2.x
  • Node 6.9.x

With Gulp

Install plugin locally:

npm install sc5-styleguide --save-dev

The Gulp plugin contains two functions that requires different set of file streams:

generate(): All unprocessed styles containing the KSS markup and style variables. This will process the KSS markup and collects variable information.

applyStyles(): Pre-processed/compiled style sheets. This will create necessary pseudo styles and create the actual style sheet to be used in the styleguide.

The following code shows complete example how to use styleguide with gulp-sass and with gulp watch.

var gulp = require('gulp');
var styleguide = require('sc5-styleguide');
var sass = require('gulp-sass');
var outputPath = 'output';

gulp.task('styleguide:generate', function() {
  return gulp.src('*.scss')
    .pipe(styleguide.generate({
        title: 'My Styleguide',
        server: true,
        rootPath: outputPath,
        overviewPath: 'README.md'
      }))
    .pipe(gulp.dest(outputPath));
});

gulp.task('styleguide:applystyles', function() {
  return gulp.src('main.scss')
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(styleguide.applyStyles())
    .pipe(gulp.dest(outputPath));
});

gulp.task('watch', ['styleguide'], function() {
  // Start watching changes and update styleguide whenever changes are detected
  // Styleguide automatically detects existing server instance
  gulp.watch(['*.scss'], ['styleguide']);
});

gulp.task('styleguide', ['styleguide:generate', 'styleguide:applystyles']);

This approach gives flexibility to use any preprocessor. For example, you can freely replace gulp-sass with gulp-ruby-sass. However, please notice that variable parsing works only for Sass, SCSS and Less files.

If you do not use preprocessor you can directly pipe CSS files to applyStyles().

See Build options section for complete documentation of different options.

With Grunt

For projects using Grunt, install the plugin, Gulp and the grunt-gulp bridge.

npm install sc5-styleguide gulp grunt-gulp --save-dev

Then you are able to use the same gulp task inside you Gruntfile:

var gulp = require('gulp'),
  styleguide = require('sc5-styleguide');

grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  gulp: {
    'styleguide-generate': function() {
      var outputPath = 'output';
      return gulp.src([''])
        .pipe(styleguide.generate({
            title: 'My Styleguide',
            server: true,
            rootPath: outputPath,
            overviewPath: 'README.md'
          }))
        .pipe(gulp.dest(outputPath));
    },
    'styleguide-applystyles': function() {
      return gulp.src('main.scss')
        .pipe(styleguide.applyStyles())
        .pipe(gulp.dest('output'));
    }
  },

  watch: {
    scss: {
      files: '**/*.scss',
      tasks: ['scss', 'gulp:styleguide-generate', 'gulp:styleguide-applystyles']
    }
  }
});

grunt.loadNpmTasks('grunt-gulp');

grunt.registerTask('default', ['gulp:styleguide-generate', 'gulp:styleguide-applystyles', 'watch']);

When using Grunt, we recommend processing styles in Grunt tasks as you do for your main application and pass the resultant CSS into styleguide's Gulp tasks.

For more specific documentation see the next section.

As a command line tool

This way of usage is not recommended, as it does not help as much with introduction of the styleguide into the day-to-day development process.

Install plugin globally:

npm install -g sc5-styleguide

Styleguide command line tool requires two sets of source files:

--kss-source: Unprocessed files containing the KSS markup and Less/Sass variables

--style-source Pre-processed/compiled style sheets to be used in the styleguide

Example usage:

styleguide --kss-source "sass/*.scss" --style-source "public/*.css" --output styleguide --watch --server

You need to either specify a single directory or you can specify one or more source directories with one or more --kss-source flags.

styleguide --kss-source "style/*.scss" --style-source "public/*.css" --output styleguide --watch --server

Other options parameters are defined in the Build options section.

Build options

CLI and gulp options accept identically named parameters

title (string, optional)

This string is used as a page title and in the page header

favIcon (string, optional)

This enables to replace the default SC5 favicon. It takes path as a string.

extraHead (array or string, optional)

These HTML elements are injected inside the style guide head tag.

sideNav (boolean, optional, default: false)

Enables side navigation. When this option parameter is enabled, styleguide will switch to side navbar.

showReferenceNumbers (boolean, optional, default: false)

When this option parameter is enabled, style guide will show reference numbers on navigation, headings and designer tool.

includeDefaultStyles (boolean, optional, default: true)

Include/exclude default styles.

showMarkupSection (boolean, optional, default: true)

Show/hide Markup section.

hideSubsectionsOnMainSection (boolean, optional, default: false)

This option enables to prevent loading of subsections.

beforeBody (array or string, optional)

These HTML elements are injected inside the style guide <body> tag, before any other content.

afterBody (array or string, optional)

These HTML elements are injected inside the style guide <body> tag, after any other content.

afterSections (array or string, optional)

These HTML elements are injected inside the style guide .sg-body section, after any other content.

commonClass (string or array of strings, optional)

The provided classes are added to all preview blocks in the generated style guide. This option is useful if you have some namespace classes that should to be added to every block, but you do not want to add it to every example section's markup.

server (boolean, optional)

Enable built-in web-server. To enable Designer tool the style guide must be served with the built-in web server. The server also has the ability to refresh changed styles or KSS markup without doing a full page reload.

port (number, optional)

Port of the server. Default is 3000.

disableServerLog (boolean, optional)

Disables embedded server log.

rootPath (string, optional)

Server root path. This must be defined if you run the built-in server via gulp or Grunt task. Point to the same path as the style guide output folder.

Note: This option is not needed when running styleguide via the CLI.

appRoot (string, optional)

Define the appRoot parameter if you are hosting the style guide from a directory other than the root directory of the HTTP server. If the style guide is hosted at http://example.com/styleguide the appRoot should be styleguide.

When using the build as a subdirectory of your application, tune your server to resolve all the paths to that subdirectory. This allows Angular to deal with the routing. However, the static files should be resolved as they are stored.

styleVariables (string, optional)

By default variable definitions are searched from every file passed in gulp.src. styleVariables parameter could be used to filter from which files variables are loaded.

disableEncapsulation (boolean, optional, default: false)

Disable Shadow DOM encapsulation. When this option parameter is enabled, all styles are defined in page head and markup examples are not encapsulated using Shadow DOM.

disableHtml5Mode (boolean, optional, default: false)

Disable HTML5 URL mode. When this option parameter is enabled, style guide will use hash bang URLs instead of HTML5 history API. This is useful when hosting static style guides.

basicAuth (object, optional, default: null)

Protect server with basic HTTP authentication.

basicAuth: {
  username: 'username',
  password: 'password'
}

readOnly (boolean, optional, default: false)

Disable variable saving from web interface.

customColors (string, optional)

Path to file that defines custom UI color overrides using PostCSS variables. See all possible variables here.

Internal styles could be overridden by defining new styles inside the styleguide_custom_styles mixin. This mixin is added to the end of the application style sheet.

You can define your own styles with

@define-mixin styleguide_custom_styles {
  /* Define your styles here */
}

PostCSS configuration supports mixins, nesting, variables, media queries.

parsers (object, optional)

default:

parsers: {
  sass: 'scss',
  scss: 'scss',
  less: 'less',
  postcss: 'postcss'
}

Styleguide tries to guess which parser to use when parsing variable information from style sheets. The object key defines the file extension to match and the value refers to the parser name. There are three parsers available: scss, less and postcss.

For example, to parse all .css files using postcss parser, following configuration could be used:

{
  css: 'postcss'
}

styleguideProcessors (object, optional)

default:

styleguideProcessors: {}

Styleguide has several processors that enrich or modify the data. For example the sg-wrapper replacement is done by a processor. You can add your own processor to enrich the styleguide data with your own content or modifications. You can also override existing functionality by overwriting the related processor. Currently these processors exist by default and should not be overwritten unless you know what you are doing:

styleguideProcessors: {
    10: replaceSectionReferences,
    20: generateSectionWrapperMarkup
}

You can define your own processors:

styleguideProcessors: {
  11: function(styleguide) {
    // this will run after replaceSectionReferences
    styleguide.sections[0].description = styleguide.sections[0].description + ' [Description from custom Processor]';
  },
  30: function(styleguide) {
    // this will run after generateSectionWrapperMarkup
  }
}

filesConfig (array, optional) (Experimental feature)

All HTML markup sections defined in the KSS block is dynamically compiled inside the styleguide thus it is possible to use Angular directive inside the markup. These external directives are lazy loaded in the styleguide Angular application. filesConfig configuration parameter could be used to define lazy loaded files. Files are only required, not copied automatically. You need to make sure that files are copied inside the styleguide output directory when generating the styleguide.

Configuration array containing paths to the dependencies of the hosted application

filesConfig: [
  {
    "name": "NameOfMainAppModule",
    "files": [
      "path/to/dependency-file.js",
      "path/to/application-file.js",
      "path/to/stylesheet.css",
    ],
    "template": "path/to/template-filename.html"
  }
]

Note: When using templateUrl in directives, the template path is relative to style guide index.html, not the hosted application root.

additionalNgDependencies (array or string, optional)

Some angular libraries (such as angular-material) can't be lazy loaded after bootstrapping. You can use the additionalNgDependencies property to inject additional angular dependencies to be bootstrapped by the style guide app.

You can pass either a string (if you only have one dependency to add) or an array of strings. The string(s) should be the same dependencies you would pass when bootstrapping dependencies in your own modules.

When using this property, you should also specify an afterBody or extraHead config in order to make sure the dependencies are loaded by the browser before they are bootstrapped.

Here's an example showing how to use angular-material:

additionalNgDependencies: ['ngMaterial']
extraHead: '
  <link rel="stylesheet" href="/angular-material/angular-material.css">
'
afterBody: '
  <script src="/angular-aria/angular-aria.js"></script>
  <script src="/angular-messages/angular-messages.js"></script>
  <script src="/angular-material/angular-material.js"></script>
'

Documenting syntax

Document your CSS components with KSS

Defining an Angular directive

If your components can be rendered with Angular directives, you can define them in KSS markup and so avoid copy-pasting in the markup field. This is how you can instruct the style guide to use Angular:

// Test directive
//
// markup:
// <div sg-test-directive>If you see this something is wrong</div>
//
// sg-angular-directive:
// name: NameOfMainAppModule
// template: path/to/template-filename.html
// file: path/to/application-file.js
//
// Styleguide 1.2.3

It is possible to define several files, so you can attach all the needed dependencies:

// sg-angular-directive:
// name: NameOfMainAppModule
// template: path/to/template-filename.html
// file: path/to/application-file.js
// file: path/to/dependency-file.js
// file: path/to/stylesheet.css

You can also write the same with comma-syntax

// sg-angular-directive:
// name: NameOfMainAppModule
// template: path/to/template-filename.html
// file: path/to/application-file.js, path/to/dependency-file.js, path/to/stylesheet.css

Ignore parts of the style sheet from being processed

You can ignore parts of the CSS or KSS from being processed using the following tags:

// styleguide:ignore:start
Ignored styles
// styleguide:ignore:end

Wrapper markup

Sometimes your component examples need a wrapper. For example:

  • you need to show how to use <li> element which works only with <ul> container;
  • your component is not visible with white background;
  • your component needs a container with a predefined height.

You can cover such cases by adding a wrapper to a component markup. The wrapper should be defined as a custom parameter in the KSS documentation block:

// markup:
// <li>
//   <a class="{$modifiers}">Item</a>
// </li>
//
// sg-wrapper:
// <nav class="sg side-nav">
//   <ul>
//     <sg-wrapper-content/>
//   </ul>
// </nav>

The <sg-wrapper-content/> inside shows where to place an example.

Wrappers can be used for fixes like this:

// markup:
// <div class="my-component">This is a white component</div>
//
// sg-wrapper:
// <div style="background-color: grey;">
//   <sg-wrapper-content/>
// </div>

The modifiers get the same wrapper as their parent section.

Wrappers are inheritable. A wrapper of a parent section is inherited by its children sections. This means that the following KSS markup

// Parent section
//
// markup:
// <div class="parent"></div>
//
// sg-wrapper:
// <div class="parent-wrapper">
//   <sg-wrapper-content/>
// </div>
//
// Styleguide 1.0

...

// Child section
//
// markup:
// <span class="child"></span>
//
// sg-wrapper:
// <div class="parent">
//   <sg-wrapper-content/>
// </div>
//
// Styleguide 1.1

would produce a Parent section:

<div class="parent-wrapper">
  <div class="parent"></div>
</div>

and a Child section:

<div class="parent-wrapper">
  <div class="parent">
    <span class="child"></span>
  </div>
</div>

Inserted markup

In the markup you can insert markup of the other sections by referring to its section number. The markup of the referred section will be inserted into the current one. You can also target specific modifiers or include all modifiers. All unknown {$modifiers} will be ignored. Nested insert also works.

// List
//
// markup:
// <ul>
//   <sg-insert>1.2.1</sg-insert>
//   <sg-insert>1.2.1-5</sg-insert> to insert the 5th modifier of 1.2.1
//   <sg-insert>1.2.1-all</sg-insert> to insert all modifiers of 1.2.1
// </ul>
//
// Styleguide 1.2

...

// List item
//
// markup:
// <li>Item</li>
//
// Styleguide 1.2.1

At the generated website the markup is shown expanded.

Pug (jade) markup

Set enablePug: true to enable Pug support with BEM (bemto). HTML supports with enabled Pug.

Gulpfile.js

gulp.task('styleguide:generate', function() {
  return gulp.src('*.css')
    .pipe(styleguide.generate({
        ...
        enablePug: true
        ...
      }))
    .pipe(gulp.dest(outputPath));
});
/*
Markup:
+b.block_modifier(class="{$modifiers}")
  +e.element
*/

Designer tool

Designer tool is a feature that allows editing style variable directly in the browser and saving the changes back to the source file. It is enabled when the styleVariables option is defined and the application is served with the built-in server.

The changed values are checked for syntax errors before saving, and if something is wrong, nothing is written to the source files and an error notification is shown on the client.

Images, fonts and other static assets

Images, fonts and other static assets should be copied to style guide output folder to make them accessible in the style guide. It is recommended to create a gulp or Grunt task to systematically do the copying when the style guide is generated.

If you modify your assets in gulp streams, you can add styleguide output directory as a second destination for your assets:

gulp.task('images', function() {
  gulp.src(['images/**'])
    // Do image sprites, optimizations etc.
    .pipe(gulp.dest(buildPath + '/images'))
    .pipe(gulp.dest(outputPath + '/images'));
});

Tips and pointers

<html> and <body> styles

Since each component's markup is isolated from the application styles with Shadow DOM, styles defined in <html> or <body> tags will not apply in the component previews. If you want for example to define a font that should also be used in the component previews, define a css class with the font definitions and add that class to the commonClass configuration option.

Providing additional CSS

Sometimes it is needed to apply additional CSS to the components. For example, make grid items of different colors so that they could be easily seen. But such CSS should not sit together with the basic CSS of the component because it is not supposed to be used in general. Obvious solution is to provide additional CSS which works in the styleguide only.

As the Styleguide shows the components isolated with Shadow DOM, any additional CSS provided with extraHead option will not affect the components. If you want to provide additional CSS which affects the components, this code should be added to the other styles when building:

var concat = require("gulp-concat");

...

gulp.task('styleguide:applystyles', function() {
  return gulp.src([
      'main.scss'
      'utils/additional.scss'
      ])
    .pipe(concat('all.scss'))
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(styleguide.applyStyles())
    .pipe(gulp.dest(outputPath));
});

Providing additional JavaScript

To provide additional JavaScript for the StyleGuide pages, define its <script> tag in the extraHead parameter:

gulp.task('styleguide:generate', function() {
  return gulp.src('*.scss')
    .pipe(styleguide.generate({
        ...
        extraHead: [
          '<script src="/path/to/my-js-file.js"></script>'
        ],
        disableEncapsulation: true
        ...
      }))
    .pipe(gulp.dest(outputPath));
});

Include other needed scripts, such as libraries, into the same array:

extraHead: [
  '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>',
  '<script src="/path/to/my-js-file.js"></script>'
]

This way you can enrich the documented components with JavaScript. Keep in mind that you need to use disableEncapsulation parameter to make the components visible for the parent page JavaScript (otherwise they are encapsulated with shadow DOM).

onRendered event

The components get visible onto the StyleGuide pages dynamically. This means that it takes some time to render them.

In your JavaScript you may need to operate components after they have been rendered. Catch styleguide:onRendered event on window for that:

$(window).bind("styleguide:onRendered", function(e) {
  // do anything here
  // use e.originalEvent.detail.elements to get elements
});

This is useful when you need to initialize your components. As this kind of initialization is only needed on the StyleGuide pages, you can provide it with an additional file:

extraHead: [
  '<script src="/path/to/my-js-file.js"></script>',
  '<script src="/js/init-styleguide.js"></script>'
]

Adding new section in between

You may use addSection helper in order to make it easier adding a new section (or subsection) in between of the existing. It shifts reference numbers of the following sections. To create a helping task, write this:

gulp.task("styleguide:addsection", function() {
  return gulp.src('path/to/components/**/*.less')
    .pipe(styleguide.addSection())
    .pipe(gulp.dest('path/to/components/'))
});

Use this task with the parameters:

gulp styleguide:new-section --name=NewSection --order=6.2.1

IMPORTANT: Check diff after doing this change!

NOTE: The tool also makes KSS comment block for a new section if it knows which file it should belong.

The addSection method is parametrized, you may tell which parser to use for the files with certain extension (by analogy to generate helper):

.pipe(styleguide.addSection({
  parsers: {
    scss: 'sass'
  }
}))

NOTE: Be careful with postcss parser. It may not preserve new lines and indents.

Demo

Build demo style guide and start a server on port 3000

npm run demo

Note: If you installed style guide by cloning repository directly instead of npm you need to run npm run build first

The demo generates style guide to demo-output directory.

Point your browser to http://localhost:3000

Additional Info

Articles, blog posts

Supplementary packages

sc5-styleguide's People

Contributors

aj-dev avatar alpadev avatar bassettsj avatar cyberixae avatar d2s avatar danielavalero avatar floatdrop avatar gambit3 avatar hannu avatar janpot avatar jcastano-xk avatar junaidrsd avatar karlhorky avatar kr3l avatar kraftner avatar levito avatar matudelic avatar philippevay avatar relicode avatar sascha-egerer avatar shekhardesigner avatar shooksm avatar simkall avatar sobolevn avatar soulfresh avatar tuire avatar varya avatar vivanac avatar vwxyutarooo avatar w74 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sc5-styleguide's Issues

Color variable name printed wrong in 0.3.5

This bug came with latest update. Didn't have it earlier.

So I have defined variable $color-white: #fffff; in sass. And then I'll print it out with KSS like:

// Colors
//
// Markup: <div style="background: {$modifiers}" class="styleguide-color">{$modifiers}</div>
//
// $color-white - white
//
// Styleguide 1.0

Now styleguide prints out following string "3px solid darken(#ffffff, 5%)" on top of color. There are several other colors with random text instead of name and some colors work fine.

It might be that if color is used somewhere and it is used in special way then name of it is getting some extra crap.

Here is several examples of output I get instead of color name:

  • lighten(2px solid lighten(#b0b0b1, 10%),20%)
  • 2px solid 2px solid #e0e0e1
  • 2px solid 2px solid 2px solid 2px solid 1px solid 1px solid 2px solid 2px solid 2px solid 2px solid 2px solid #0090f1

Sections use first number as grouping

I have styleguide with main sections from 1-12 and when I click first section 1. it will display also 11. and 12.

It looks like it is using first number to group items.

Simple example KSS to reproduce:

// Section 1
//
// Styleguide 1.0

// Section 11
//
// Styleguide 11.0

:not pseudo selector issue

Consider following case:

/*
test

Markup:
<div">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
</div

Styleguide 0
*/

.item {
  background: blue;
}

.item:not(:first-child) {
  background: red;
}

This shows all items in red while the first one is supposed to be blue. This seems to only happen when a pseudoselector is used in the :not selector. With a normal class it works. It seems the translated .pseudo-class-first-child is not added to the classlist.

It also seems to fail for :last-child, :first-of-type and :last-of-type

Edit
Ok, now I see what happens here. It seems there are two possible solutions IMO:

  1. Don't generate .pseudo-class-... rules for :first-child, last-child,... when they appear in the :not() clause
  2. Add pseudoclasses to the bound html through a directive, adding angular.element(element[0].querySelectorAll(':first-child')).addClass('pseudo-class-first-child'); in the dynamicCompile directive's watch function seemed to solve this particular case for me. Obviously you'd want a more robust solution that covers all cases and doesn't pollute the dynamicCompile directive.

Getting TypeError when starting styleguide with gulp on Windows

I'm using sc5-styleguide with gulp on Win8.1 64bit.
When I start gulp in my project folder, I get the following error:
TypeError: Cannot call method 'substr' of undefined
The same error appears when I just go gulp styleguide:generate.
When I empty the output-folder and try to generate the styleguide I only get a couple of css- and scss-files, but no html.
I already reinstalled everything in node_modules (no errors, no warnings) and emptied node's cache. I also tried the same project on OSX without a problem.

I tried to track the problem with my humble javascript-knowledge by inserting console.log("something") at strategic points in styleguide.js and taking note of when it prints and when it doesn't, and I think I was successfull on line 189:

...
console.log("test1"); // prints
Q.all([parseKSSPromise, parseVariablesPromise]).spread(function(sections, variables) {
console.log("test2"); // doesn't print
...

I guess either something broken gets passed into q or q itself is broken.
Does somebody have a suggestion? Any help or insight would be greatly appreciated.

"npm install -g sc5-styleguide" error with node 0.11

Getting an error when I try and install via npm:

Binary downloaded and installed at /Users/pete.nellius/.nvm/v0.11.14/lib/node_modules/sc5-styleguide/node_modules/kss/node_modules/node-sass/vendor/darwin-x64/binding.node

> [email protected] postinstall /Users/pete.nellius/.nvm/v0.11.14/lib/node_modules/sc5-styleguide/node_modules/kss/node_modules/node-sass
> node scripts/build.js

`darwin-x64` exists; testing
module.js:355
  Module._extensions[extension](this, filename);
                               ^
Error: Module did not self-register.
    at Error (native)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/pete.nellius/.nvm/v0.11.14/lib/node_modules/sc5-styleguide/node_modules/kss/node_modules/node-sass/lib/index.js:181:15)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)

npm ERR! Darwin 14.0.0
npm ERR! argv "/Users/pete.nellius/.nvm/v0.11.14/bin/node" "/Users/pete.nellius/.nvm/v0.11.14/bin/npm" "install" "-g" "sc5-styleguide"
npm ERR! node v0.11.14
npm ERR! npm  v2.0.0
npm ERR! code ELIFECYCLE
npm ERR! [email protected] postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script.
npm ERR! This is most likely a problem with the node-sass package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node scripts/build.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls node-sass
npm ERR! There is likely additional logging output above.

Fonts overwritten by styleguide fonts

My font is set on the body but gets overwritten everywhere by the .sg class. Any idea on what's the best strategy to get around this? I would really like to hold off on defining .sg in my css. Ideally sg style shouldn't interfere with mine.

Incrementation Support

Currently there is no way to generate code based on incrementation.

For example if I have to foundation code for even split buttons

// Button Group Advanced - Four Buttons
//
// .button-group.even-4 - Even division of four buttons.
//
// markup:
// <ul class="{$modifiers}">
//  <li><a href="#" class="button">Button 1</a></li>
//  <li><a href="#" class="button">Button 2</a></li>
//  <li><a href="#" class="button">Button 3</a></li>
//  <li><a href="#" class="button">Button 4</a></li>
// </ul>
//
// Styleguide 3.10.2.3

I have no way to tell the system to dynamically create 2-8 list items depending on the class or other hint. Here I propose a alternate way to handle this by extending the syntax. I am sure there is a better way, but this may help to show what I am thinking...

// Button Group Advanced - Even Buttons
//
// .button-group.even-2/count:2 - Even division of two buttons
// .button-group.even-3/count:3 - Even division of three buttons
// .button-group.even-4/count:4 - Even division of four buttons
// .button-group.even-5/count:5 - Even division of five buttons
// .button-group.even-6/count:6 - Even division of six buttons
// .button-group.even-7/count:7 - Even division of seven buttons
// .button-group.even-8/count:8 - Even division of eight buttons
//
// markup:
// <ul class="{$modifiers}">
//  {$count-print}<li><a href="#" class="button">Button {$count}</a></li>
// </ul>
//
// Styleguide 3.10.2

In general the idea would be to provide a hint above, that is not rendered in the styleguide.
Identify the line or block that is to be repeated, also not rendered in styleguide.
Print the count exposed by {$count}

Fails on bootstrap variables

Tried to compile bootstrap-sass variables to a styleguide. The kss parser seems to choke on two occasions

first line (not sure why):

$bootstrap-sass-asset-helper: (twbs-font-path("") != unquote('twbs-font-path("")')) !default;

https://github.com/twbs/bootstrap-sass/blob/d3531a6fded02ba8ecd3e2d1f987927bd414883b/assets/stylesheets/bootstrap/_variables.scss#L4

also some functions are called with dubble parentheses, seems problematic for the parser as well

$font-size-large: ceil(($font-size-base * 1.25)) !default; // ~18px

https://github.com/twbs/bootstrap-sass/blob/d3531a6fded02ba8ecd3e2d1f987927bd414883b/assets/stylesheets/bootstrap/_variables.scss#L57

My list styles mess up the menu and modifiers lists

I have following styles defined:

ul {
  padding-left: 0;

  li {
    list-style: none;
  }

  li:before {
    padding-right: 30px;
    content: "";
    font-size: 13px;
    color: #888888;
  }

  ul &, ol & {
    margin: 18px 0 18px 30px;
    li:before {
      content: "";
    }
  }
}

This is what that does to the menu and modifier lists

screen shot 2014-11-25 at 15 36 10
screen shot 2014-11-25 at 15 36 01

SCSS variables that refer to other SCSS variables...

Hi,

I just started using SC5 styleguide to document my SCSS code. It is working great, except for one particular application.

I have SCSS variables that refer to other SCSS variables:

eg. $main-font-color: $dark-grey;

When I add markup to my comments in this situation, I do not end up with the correct value compiled into my styleguide.

eg.

// $main-font-color - main font color
//
// markup:
// <p style="color: $main-font-color">Sample Text</p>

Compiles to in my styleguide:

<p style="color: $dark-grey">Sample Text</p>

It would obviously be preferable to have the actual value of $dark-grey compiled into the style guide.

Is there anyway around this problem?

Thanks,

Sarah

Variable names with -# or _# cause errors

Hello,

There seems to be a problem with variable names that have a hyphen or underscore followed by a number.

Example:
fontsize-1: 14px;

Generates the following error:

Parsing error: Please check the validity of the block starting from line #1

1*| $fontsize-1: 14px;

This seems to be incorrect, hyphens and underscores followed by a number are valid SASS variable names.

Multiple Copies of Example unneeded

The syntax should allow for me to identify classes and attributes within a markup example, without generating additional examples. Currently the following code will generate a example for each row in the description block, even though {$modifiers} is not present in the markup.

// Equalizer Basics
//
// data-equalizer - This attribute is used on the parent to identify the container which contents need to be equalized.
// data-equalizer-watch - This attribute is used on children within the parent container to identify the columns that need equalized.
//
// markup:
// <div class="row" data-equalizer>
//  <div class="large-6 columns panel" data-equalizer-watch>
//      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eget neque non dui blandit fermentum. Proin dictum metus sit amet pulvinar congue. In lectus justo, interdum a libero viverra, iaculis pretium nulla. Nunc sed volutpat sem. Ut dolor urna, congue ac lobortis pretium, maximus eget felis. Maecenas vitae luctus ante, a luctus libero. Nam volutpat dui libero, sed faucibus mauris rhoncus eu. Quisque iaculis, urna id vulputate vehicula, magna lorem tempus nulla, a semper dui neque vitae neque. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eget arcu eu velit dictum sollicitudin nec vitae lectus. Phasellus tempor bibendum sodales. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </p>
//  </div>
//  <div class="large-6 columns panel" data-equalizer-watch>
//      <p>Morbi molestie a nulla ut congue. Ut finibus vestibulum vestibulum. Nam eget mauris elit. Curabitur arcu orci, semper at accumsan vitae, condimentum sagittis lacus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus in ipsum dictum mi sodales dignissim ac non neque. Aliquam at dignissim urna. Fusce id nunc fermentum, commodo arcu nec, blandit mi. Sed suscipit odio accumsan nibh iaculis dapibus. Vivamus vel condimentum tellus. Quisque commodo turpis ultrices lorem sodales, sed pellentesque lorem volutpat. Donec nibh nibh, sodales sed accumsan sit amet, placerat eu ipsum. Nunc nulla ligula, gravida et tempor volutpat, porta quis nunc. Sed ligula lectus, faucibus ut ligula ac, mollis sodales purus. Suspendisse vitae viverra leo. Proin suscipit diam est, non bibendum nisi porta non. </p>
//  </div>
// </div>
//
// Styleguide 6.4.1

Expected action, is with the {$modifiers} missing from the markup block, the description should not impact the number of generated examples.

Use gulp-ruby-sass

If there is a chance to use gulp-ruby-sass instead of gulp-sass? gulp-sass is hopelessly behind with features and can't compile a lot of sass third party libraries.

Support KSS deprecated

Would be nice to be able to use KSS deprecated syntax to tell that section is deprecated. Also if parent section is having deprecated it should be inherited to child sections. Currently deprecated is not visually displayed in any way.

IDs can not have modifiers

IDs can not have modifiers -

// Modal Sizes
//
// .tiny - Sets the width of modal to 30%.
// .small - Sets the width of modal to 40%.
// .medium - Sets the width of modal to 60%.
// .large - Sets the width of modal to 70%.
// .xlarge - Sets the width of modal to 95%.
// .full - Sets the width AND height of modal to 100%.
//
// markup:
// <a href="#" data-reveal-id="sizeModal{$modifiers}">Click Me For A Different Sized Modal</a>
// <div id="sizeModal{$modifers}" class="reveal-modal {$modifiers}" data-reveal>
//  <h2>Modal Title</h2>
//  <p class="lead">This is a special decorated paragraph.</p>
//  <p>This is a generic paraphrah inside a modal for display to the user</p>
//  <a class="close-reveal-modal">&#215;</a>
// </div>
//
// Styleguide 4.4.3

The ID does not accept class name, string, or any other format. This makes it impossible to have variants created based on ID. Does this being rendered in a web component make it so that it is a non-issue? IDs need to be unique for the JS to work properly.

Thanks.

Extend KSS Syntax

I find KSS Syntax very good, but with a few caveats

    // Block Name
    // 
    // Description OR Classes
    // 
    // markup:
    // markup code here
    // 
    // Styleguide 1.0

It would be ideal if we could have a section to identify modifiers, as well as document other things within the same block. Currently, I have to make a new block for the documentation, then a sub-section to show the code. This is fairly minor different, but it would make things cleaner.

Additionally, it would be nice if we can define a specific description block that can output Markdown or HTML so we can provide links. This is something that needs to be done in markup as a example just to create cross-linking or showing outside dependencies.

Incorrect `styleguide-applystyles` task for Grunt in the README

When running grunt gulp:styleguide-applystyles, there is an error Warning: output is not defined Use --force to continue..

This is becaus ethe task is missing var outputPath = 'output'; in the beginning. And the destionation should be .pipe(gulp.dest(outputPath).

Parsing error messages are not very useful.

I get this error and it's not very obvious what's wrong with it:

Parsing error: Please check the validity of the block starting from line #53

51 | $link-size: 12px;
53*| // Establishes the text tempo
54 | $line-height-base: 12px;

Gonzales PE version: 3.0.0-12

A tool to insert a section in between existing ones

KSS requires to provide section reference numbers in comments. It's OK but when I need to add another block in between of existing ones, this makes me shift all the sections with bigger numbers. Sometimes it's a lot of work. It would be nice to have a tool which makes this automatically.
This tool should go as a CLI and gulp-plugin.

In out project we came up with a gulp task. It can be run with parameters like gulp styleguide:new-section --name=NewSection --order=6.2.1. It shift the sections after the given number and adds new section in the existing files. The code is shitty and does not consider many cases (like multiple line parameters). But I hope it will give you an idea how to move on.

'use strict';

var gulp;
var gutil = require('gulp-util');
var gonzales = require("gonzales-pe");
var minimist = require("minimist");
var through = require("through2");

module.exports = function registerTasks(g) {
    gulp = g;
    Object.keys(tasks).forEach(function(task) {
        gulp.task(task, tasks[task]);
    });
}

var tasks = {

    'styleguide:new-section': newSection

}

function newSection() {
    var args = minimist(process.argv.slice(2));

    var params = {
      name: args['name'] || args['n'],
      order: args['order'] || args['o']
    };

    var sourcePath = "public_html/scss";
    var source = sourcePath + "/**/*.scss";

    if (!params.name) {
      gutil.beep();
      gutil.log(gutil.colors.red('Define name with --name=my-name'));
      return;
    }

    if (!params.order) {
      gutil.beep();
      gutil.log(gutil.colors.red('Define name with --order=1.2.3'));
      return;
    }

    params.order = params.order.toString();

    // TODO: if order is not given, place into the last one
    // TODO: Check ref number parameter with regexp

    function getPreviousSection(section) {
      var previousSectionArray = section.split('.');
      previousSectionArray[previousSectionArray.length - 1] -= 1;
      if (previousSectionArray[previousSectionArray.length - 1] === 0) {
        previousSectionArray.pop();
      }
      return previousSectionArray.join('.');
    }

    function changeNumber(section) {

        var filesBuffer = {};

        var stream = through.obj(function(file, enc, cb) {

            var content = file.contents.toString('utf8');
            var syntax = 'scss';
            var ast = gonzales.parse(content, { syntax: syntax });
            var isKssMarkupBlock = /Styleguide [0-9]+/;

            function isLess(left, right) {
                left = left.split('.');
                right = right.split('.');

                var l = false;

                for(var i = 0; i< Math.max(left.length, right.length); i++ ) {
                    if (parseInt(left[i]) < parseInt(right[i])) {
                        l = true;
                        break;
                    }
                    if (parseInt(left[i]) > parseInt(right[i])) {
                        l = false;
                        break;
                    }
                }
                return l;

            }

            function ifBelongsToParent(parentSection, section) {

                var belongs = true;

                parentSection = parentSection && parentSection.split('.');
                section = section.split('.');

                parentSection && parentSection.forEach(function(val, n) {
                    if (val !== section[n]) {
                        belongs = false;
                    }
                });

                return belongs;

            }

            function increaseSection(section, diff) {
                section = section.split('.');
                var last = section.pop();
                section.push(parseInt(last) + diff);
                return section.join('.');
            }

            function newStream(content) {
             var stream = through();
             stream.write(content);
             return stream;
            }

            ast.map(function(declaration){
                // Take only comments
                if (
                    declaration.type !== 'commentSL' &&
                    declaration.type !== 'commentML'
                  ) return;
                // Skip everything which is not Styleguide reference
                if (!isKssMarkupBlock.test(declaration.content))
                   return;

                // Increase all the sections after the given one
                var matchRegexp = /(Styleguide )([0-9]+(\.[0-9]+)*)/;
                var match = declaration.content.match(matchRegexp);
                var currentNumber = match[2];

                // Skip sections with less reference number
                if (isLess(currentNumber, section))
                    return;

                // Skip everything which does not belong parent section
                var parentSection = section.split('.');
                parentSection.pop();
                parentSection = parentSection.join('.');

                if (!ifBelongsToParent(parentSection, currentNumber))
                    return;

                // Skip parent section itself
                if (parentSection === currentNumber)
                    return;

                // Increase everything with +1
                var newVal = increaseSection(currentNumber, 1);

                declaration.content = declaration.content.replace(matchRegexp, '$1' + newVal);

            });

            var newContent = new Buffer(ast.toCSS(syntax));
            file.contents = Buffer.concat([newContent]);

            this.push(file);
            cb();
        });

        return stream;
    }

    function insertSection(name, reference) {
        var inserted = false;
        var stream = through.obj(function(file, enc, cb) {
            // Content of the new Section
            var sectionContent =[
                '// ' + params.name,
                '//',
                '// Styleguide ' + params.order
            ];

            var previousSection = getPreviousSection(params.order);
            // Paste new section after a blog of previous section
            var content = file.contents.toString('utf8');
            var syntax = 'scss';
            var ast = gonzales.parse(content, { syntax: syntax });

            var isKssMarkupBlock = /Styleguide [0-9]+/;
            var commentBlockStarted = false;
            var startLookForSection = false;

            ast.map(function(declaration) {
                if (inserted) {
                    return;
                }
                if (declaration.type === 'commentSL' && declaration.content === ' Styleguide ' + previousSection) {
                    startLookForSection = true;
                    return;
                }
                if (!startLookForSection) {
                    return;
                }
                if (declaration.type === 'commentSL' && commentBlockStarted === false) {
                    commentBlockStarted = declaration;
                }
                if (
                    declaration.type !== 'commentSL'
                    && commentBlockStarted
                    && declaration.content !== '\n'
                    && declaration.content !== '\n\n'
                    ) {
                    commentBlockStarted = false;
                }
                if (
                      commentBlockStarted &&
                      declaration.type === 'commentSL' &&
                      isKssMarkupBlock.test(declaration.content)
                    ) {
                    // So, this was a KSS block, we need to place before commentBlockStarted

                    // TODO: rewrite normally when ast.insert is implemented
                    commentBlockStarted.content = '\n\n\n' + sectionContent.join('\n') + '\n\n//' + commentBlockStarted.content;
                    inserted = true;
                }
            });

            var endOfFile = ''
            if (inserted === false && startLookForSection === true) {
                // need to add by the end of the file
                endOfFile = '\n\n' + sectionContent.join('\n');
            }

            var newContent = new Buffer(ast.toCSS(syntax));
            endOfFile = new Buffer(endOfFile);
            file.contents = Buffer.concat([newContent, endOfFile]);
            this.push(file);
            cb();

        });
        return stream;
    }

    // Change all the numbers after giving one
    gulp.src(source)
        .pipe(changeNumber(params.order))
        .pipe(insertSection(params.name, params.order))
        .pipe(gulp.dest(sourcePath));
}

Description section is rendered incorrectly

Given the following snippet:

// Lorem Ipsum
//
// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vitae arcu non
// mauris efficitur pharetra sed a purus. Cras id sapien tortor. Nulla eget leo
// sed ligula molestie lobortis.
//
// Morbi ornare bibendum purus, non porta nibh hendrerit non. Praesent sed metus
// tincidunt, efficitur neque at, semper magna. Fusce vitae placerat ex. Cras
// rhoncus vehicula sodales. Aenean ac pulvinar augue, ut vulputate ex.
//
// Suspendisse gravida luctus accumsan. Curabitur dictum dolor ex, at suscipit
// ex rhoncus in.
//
// Styleguide 3.0

I would expect SC5 to render the description section as 3 paragraphs, but instead it combines them into a single paragraph.

Also, a lot of the markdown features are removed. For example, I can't use backticks to denote code or stars to denote emphasis.

Source files distributed across multiple directories

Hi,

I've been having an issue configuring the --kss-source for my SC5 styleguide. My SCSS source files are distributed across multiple directories in a structure similar to the example below:

myapp
  - styles
      - *.scss
  - module1
      - styles
           - *.scss
  - module2
      - styles
           - *.scss
  - module3
      - styles
           - *.scss
      - submodule
          - styles
               - *.scss

I have have been using your command line tool to compile my styleguide, as described here in your README: https://github.com/SC5/sc5-styleguide#as-a-command-line-tool . It is working great, with one caveat. Perhaps I have been missing something obvious, but I have been unable to find a way to configure the --kss-source to point to multiple separate directories as outlined in the sample directory structure above.

Is there currently support for this? If so, would you be able to give me any insight into how to correctly specify the --kss-source in this situation? If not, do you have any plans to add support for situations like this one?

Thanks in advance for your help, and all your great work on SC5-styleguide,

  • Sarah

Cannot parse if statements and $var: $var; declarations

I am trying to parse neat and bourbon files and getting parse errors such as the following. The code snippet is below - it looks like declaring variables as variables nor using if statements is well supported. Maybe an issue with

Error:
Parsing error: Please check the validity of the block starting from line #118

116 | @mixin flex-direction($value: row) {
118*|     $value-2009: $value;
119 |     $value-2011: $value;
120 |     $direction: "normal";

Snippet:

@mixin flex-direction($value: row) {

    $value-2009: $value;
    $value-2011: $value;
    $direction: "normal";

    @if $value == row {
        $value-2009: horizontal;
    }

    @elseif $value == "row-reverse" {
        $value-2009: horizontal;
        $direction: reverse;
    }

    @elseif $value == column {
        $value-2009: vertical;
    }

    @elseif $value == "column-reverse" {
        $value-2009: vertical;
        $direction: reverse;
    }

Sass Syntax Problem

Hey :)

I've stumbled across a little problem using .sass files and trying to copy your color example. I only got that to work only when I added the ; which don't really belong there when using sass.
Do you know what's wrong there?

Thanks

'no socket connections' with socket.io v1.3.2

When running the demo application I receive a no socket connections error in the browser. The package.json lists sockets.io as "^1.2.1 which when the packages are installed socket.io version is bumped to 1.3.2. If I explicity set the demo to use sockets.io v1.2.1 I do not receive this error.

sg-wrapper is not parsed correctly (on Windows)

I have file main.less , but sg-wrapper don't parse.

// Side nav item
//
// markup:
// <li><a class="">Item</a></li>
//
// sg-wrapper:
// <nav class="sg side-nav" style="background: green">
//   <ul>
//    <sg-wrapper-content/>
//   </ul>
// </nav>
// sg-wrapper:
// <nav class="sg side-nav" style="background: green">
//   <ul>
//    <sg-wrapper-content/>
//   </ul>
// </nav>
//
// Styleguide 1

Sass functions don't work inside variables

I use color functions to defined color variations of one of my color, like this:

$color-soften: tint($color-highlight, 30%);

But the variable isn't compile, the styleguide outputs tint(#3dc7a6, 30%) for the template name instead of the new generated color.

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.