Fix skin watching, and watch templates

Fix skin watching, and watch templates

# Skin

*Allows the visual aspects of the site to be controlled by skin packages.*

    fs = require 'fs'
    path = require 'path'

    config = require 'config'
    pkgman = require 'pkgman'

    exports.pkgmanRegister = (registrar) ->

#### Implements hook `shrubConfigClient`.

      registrar.registerHook 'shrubConfigClient', ->

        skinAssets = {}
        for packagePath in pkgman.packagesImplementing 'shrubSkinAssets'
          skinAssets[packagePath] = exports.assets packagePath

        default: config.get 'packageSettings:shrub-skin:default'
        assets: skinAssets

#### Implements hook `shrubHttpMiddleware`.

      registrar.registerHook 'path', 'shrubHttpMiddleware', (http) ->

        label: 'Skin path handling'
        middleware: [

          (req, res, next) ->

If we get here and it's a skin URL, it must be a 404 otherwise, express/static
would have picked it up already.

            return res.send 404 if req.path.match /^\/skin\//

            next()
        ]

#### Implements hook `shrubHttpMiddleware`.

      registrar.registerHook 'render', 'shrubHttpMiddleware', (http) ->

        label: 'Render skinned page HTML'
        middleware: [

          (req, res, next) ->

            return exports.renderAppHtml().then((html) ->
              req.delivery = html
              next()
            ).catch (error) -> next error

      ]

#### Implements hook `shrubConfigServer`.

      registrar.registerHook 'shrubConfigServer', ->

Default skin.

        default: 'shrub-skin-strapped'

## activeKey

*Get the active skin's key*

    exports.activeKey = -> config.get 'packageSettings:shrub-skin:default'

## gruntSkin

*Helper function to copy skin assets. Configures a grunt task, e.g. if your
skin is named `my-special-skin`, the configured task is named
`my-special-skinCopy`. This is not automatically added to the build
dependencies, you do it manually so you can control exactly when it happens.*

    exports.gruntSkin = (gruntConfig, key) ->

      skinPath = path.dirname require.resolve key

      gruntConfig.clean ?= {}
      gruntConfig.copy ?= {}
      gruntConfig.watch ?= {}

      gruntConfig.configureTask 'clean', key, [
        "app/skin/#{key}"
      ]

      copyFiles = []

      copyFiles.push(
        expand: true
        cwd: "#{skinPath}/app"
        src: ["#{verbatim}/**/*"]
        dest: "app/skin/#{key}"
      ) for verbatim in ['css', 'fonts', 'img', 'js', 'lib']

      gruntConfig.configureTask 'copy', key, files: copyFiles

      gruntConfig.configureTask(
        'watch', "#{key}Copy"

        files: copyFiles.concat(
          src: "template/**/*"
        ).map(
          (copyFile) -> "#{skinPath}/app/#{copyFile.src}"
        )
        tasks: [
          "newer:copy:#{key}"
        ]
        options: livereload: true
      )

## renderAppHtml

*Render the application HTML.*

    exports.renderAppHtml = ->

      Promise = require 'bluebird'

      cheerio = require 'cheerio'

      assets = require 'shrub-assets'

      skinKey = exports.activeKey()
      skinDirectory = exports.skinDirectory skinKey

      environmentKey = if 'production' is process.env.NODE_ENV
        'production'
      else
        'default'

Read the app HTML.

      readFile = Promise.promisify fs.readFile, fs
      readFile(
        "#{skinDirectory}/app/template/app.html", encoding: 'utf8'
      ).then (html) ->

        $ = cheerio.load html

        pkgman.invoke 'skinRenderAppHtml', $

        $head = $('head')
        $body = $('body')

Inject the application-level assets first.

        appAssets = assets.assets()

        $head.append $('<link />').attr(
          type: 'text/css'
          rel: 'styleSheet'
          href: styleSheet
        ) for styleSheet in appAssets.styleSheets

        $body.append $('<script />').attr(
          src: script
        ) for script in appAssets.scripts

Inject the skin-level assets.

        skinAssets = exports.assets skinKey

        $head.append $('<link />').attr(
          class: 'skin'
          type: 'text/css'
          rel: 'stylesheet'
          href: "/skin/#{skinKey}/#{styleSheet}"
        ) for styleSheet in skinAssets.styleSheets[environmentKey] ? []

        $body.append $('<script />').attr(
          class: 'skin'
          src: "/skin/#{skinKey}/#{script}"
        ) for script in skinAssets.scripts[environmentKey] ? []

        $.html()

## skinDirectory

* (String) `key` - The skin key.

*Get the directory a skin lives within.*

    exports.skinDirectory = (key) -> path.dirname require.resolve key

## assets

* (String) `key` - The skin key.

*Get the assets for a skin.*

###### TODO: This needs caching.

    exports.assets = (skinKey) ->

      glob = require 'simple-glob'
      pkgman = require 'pkgman'

      skinPath = path.dirname require.resolve skinKey
      skinModule = require skinKey

Read in all the templates.

      templates = {}
      for templatePath in glob cwd: "#{skinPath}/app/template", [
        '**/*.html', '!app.html'
      ]

Strip out most of the unnecessary whitespace.

        templates[templatePath] = fs.readFileSync(
          "#{skinPath}/app/template/#{templatePath}"
        ).toString('utf8').replace /\s+/g, ' '

Assets currently default to .js/.css for default and .min.js and .min.css for
production.

      skinAssets =

        templates: templates

        scripts:

          default: glob cwd: "#{skinPath}/app", [
            'js/**/*.js', '!js/**/*.min.js'
          ]

          production: glob cwd: "#{skinPath}/app", [
            'js/**/*.min.js'
          ]

        styleSheets:

          default: glob cwd: "#{skinPath}/app", [
            'css/**/*.css', '!css/**/*.min.css'
          ]

          production: glob cwd: "#{skinPath}/app", [
            'css/**/*.min.css'
          ]

#### Invoke hook `shrubSkinAssets`.

      pkgman.invokePackage skinKey, 'shrubSkinAssets', skinAssets

      skinAssets

# Skin

*Allows the visual aspects of the site to be controlled by skin packages.*

    fs = require 'fs'
    path = require 'path'

    config = require 'config'
    pkgman = require 'pkgman'

    exports.pkgmanRegister = (registrar) ->

#### Implements hook `shrubConfigClient`.

      registrar.registerHook 'shrubConfigClient', ->

        skinAssets = {}
        for packagePath in pkgman.packagesImplementing 'shrubSkinAssets'
          skinAssets[packagePath] = exports.assets packagePath

        default: config.get 'packageSettings:shrub-skin:default'
        assets: skinAssets

#### Implements hook `shrubHttpMiddleware`.

      registrar.registerHook 'path', 'shrubHttpMiddleware', (http) ->

        label: 'Skin path handling'
        middleware: [

          (req, res, next) ->

If we get here and it's a skin URL, it must be a 404 otherwise, express/static
would have picked it up already.

            return res.send 404 if req.path.match /^\/skin\//

            next()
        ]

#### Implements hook `shrubHttpMiddleware`.

      registrar.registerHook 'render', 'shrubHttpMiddleware', (http) ->

        label: 'Render skinned page HTML'
        middleware: [

          (req, res, next) ->

            return exports.renderAppHtml().then((html) ->
              req.delivery = html
              next()
            ).catch (error) -> next error

      ]

#### Implements hook `shrubConfigServer`.

      registrar.registerHook 'shrubConfigServer', ->

Default skin.

        default: 'shrub-skin-strapped'

## activeKey

*Get the active skin's key*

    exports.activeKey = -> config.get 'packageSettings:shrub-skin:default'

## gruntSkin

*Helper function to copy skin assets. Configures a grunt task, e.g. if your
skin is named `my-special-skin`, the configured task is named
`my-special-skinCopy`. This is not automatically added to the build
dependencies, you do it manually so you can control exactly when it happens.*

    exports.gruntSkin = (gruntConfig, key) ->

      skinPath = path.dirname require.resolve key

      gruntConfig.clean ?= {}
      gruntConfig.copy ?= {}
      gruntConfig.watch ?= {}

      gruntConfig.configureTask 'clean', key, [
        "app/skin/#{key}"
      ]

      copyFiles = []

      copyFiles.push(
        expand: true
        cwd: "#{skinPath}/app"
        src: ["#{verbatim}/**/*"]
        dest: "app/skin/#{key}"
      ) for verbatim in ['css', 'fonts', 'img', 'js', 'lib']

      gruntConfig.configureTask 'copy', key, files: copyFiles

      gruntConfig.configureTask(
        'watch', "#{key}Copy"

        files: copyFiles.map((copyFile) -> copyFile.src).reduce(
          ((l, r) -> l.concat r), []
        )
        tasks: [
          "newer:copy:#{key}"
        ]
      )

## renderAppHtml

*Render the application HTML.*

    exports.renderAppHtml = ->

      Promise = require 'bluebird'

      cheerio = require 'cheerio'

      assets = require 'shrub-assets'

      skinKey = exports.activeKey()
      skinDirectory = exports.skinDirectory skinKey

      environmentKey = if 'production' is process.env.NODE_ENV
        'production'
      else
        'default'

Read the app HTML.

      readFile = Promise.promisify fs.readFile, fs
      readFile(
        "#{skinDirectory}/app/template/app.html", encoding: 'utf8'
      ).then (html) ->

        $ = cheerio.load html

        pkgman.invoke 'skinRenderAppHtml', $

        $head = $('head')
        $body = $('body')

Inject the application-level assets first.

        appAssets = assets.assets()

        $head.append $('<link />').attr(
          type: 'text/css'
          rel: 'styleSheet'
          href: styleSheet
        ) for styleSheet in appAssets.styleSheets

        $body.append $('<script />').attr(
          src: script
        ) for script in appAssets.scripts

Inject the skin-level assets.

        skinAssets = exports.assets skinKey

        $head.append $('<link />').attr(
          class: 'skin'
          type: 'text/css'
          rel: 'stylesheet'
          href: "/skin/#{skinKey}/#{styleSheet}"
        ) for styleSheet in skinAssets.styleSheets[environmentKey] ? []

        $body.append $('<script />').attr(
          class: 'skin'
          src: "/skin/#{skinKey}/#{script}"
        ) for script in skinAssets.scripts[environmentKey] ? []

        $.html()

## skinDirectory

* (String) `key` - The skin key.

*Get the directory a skin lives within.*

    exports.skinDirectory = (key) -> path.dirname require.resolve key

## assets

* (String) `key` - The skin key.

*Get the assets for a skin.*

###### TODO: This needs caching.

    exports.assets = (skinKey) ->

      glob = require 'simple-glob'
      pkgman = require 'pkgman'

      skinPath = path.dirname require.resolve skinKey
      skinModule = require skinKey

Read in all the templates.

      templates = {}
      for templatePath in glob cwd: "#{skinPath}/app/template", [
        '**/*.html', '!app.html'
      ]

Strip out most of the unnecessary whitespace.

        templates[templatePath] = fs.readFileSync(
          "#{skinPath}/app/template/#{templatePath}"
        ).toString('utf8').replace /\s+/g, ' '

Assets currently default to .js/.css for default and .min.js and .min.css for
production.

      skinAssets =

        templates: templates

        scripts:

          default: glob cwd: "#{skinPath}/app", [
            'js/**/*.js', '!js/**/*.min.js'
          ]

          production: glob cwd: "#{skinPath}/app", [
            'js/**/*.min.js'
          ]

        styleSheets:

          default: glob cwd: "#{skinPath}/app", [
            'css/**/*.css', '!css/**/*.min.css'
          ]

          production: glob cwd: "#{skinPath}/app", [
            'css/**/*.min.css'
          ]

#### Invoke hook `shrubSkinAssets`.

      pkgman.invokePackage skinKey, 'shrubSkinAssets', skinAssets

      skinAssets


Add note about handling unknown routes

Add note about handling unknown routes

# /api/App Components/Batman.App/Batman.App Routing

The batman.js routing DSL is similar to the [Rails routing DSL](http://guides.rubyonrails.org/routing.html). It is oriented around the notion of a resource.

## Handling unknown routes

When batman.js doesn't have a way to handle a route, it:

- fires `"error"` on the running app, passing an object like:
  ```javascript
  {
    type: "404"
    isPrevented: false
    preventDefault: -> @isPrevented = true
  }
  ```
- if `error.isPrevented` isn't set to `true` by a handler, redirects to `/404`

So, you can handle these in your App routing:

```coffeescript
class MyApp extends Batman.App
  # handle the event:
  @on 'error', ->
    if error.type is "404"
      alert('Not Found!')
      error.preventDefault()
```

__or:__

```coffeescript
class MyApp extends Batman.App
  # handle the redirect:
  @route '/404', (params) -> alert("Not found!")
```

## @route

`@route` defines a custom route and can be pointed to a controller action directly. For example:

```coffeescript
class window.Example extends Batman.App
  @route 'comments', 'pages#comments'

class Example.PagesController extends Batman.Controller
  comments: ->
```

Would result in `/comments` being added to the routing map, pointed to `PagesController#comments`.

## @resources(resourceName : String[, otherResourceNames... : String][, options : Object][, scopedCallback : Function])

`@resources` is modeled after the Rails routing `resources` method. It automatically defines some routes and matches them to controller actions. For example,

```coffeescript
class App extends Batman.App
  @resources 'pages'

class App.PagesController extends Batman.Controller
  index: ->
    # ...
  new: ->
    # ...
  show: (params) ->
    App.Page.find params.id, (err, page) ->
      @set('currentPage', page)
  edit: (params) ->
    App.Page.find params.id, (err, page) ->
      @set('currentPage', page)
```

Will set up these routes:

Path | Controller Action
-- | -- |
/pages | App.PagesController#index
/pages/new | App.PagesController#new
/pages/:id | App.PagesController#show
/pages/:id/edit | App.PagesController#edit

Note that unlike Rails, `destroy`, `update`, and `create` are not performed by controller actions in batman.js. Instead, call `save` or `destroy` on your records directly.
To access a generated route from within a view, use the [`data-route` binding](batman.view_bindings.html#data-route).

### Nested Resources

You may also nest resources, as in Rails:

```coffeescript
class App extends Batman.App
  @resources 'pages', ->
    @resources 'comments'
```

Will set up these routes for `App.Comment`:

Path | Controller Action
-- | -- |
/pages/:page_id/comments | App.CommentsController#index
/pages/:page_id/comments/new | App.CommentsController#new
/pages/:page_id/comments/:id | App.CommentsController#show
/pages/:page_id/comments/:id/edit | App.CommentsController#edit

## @member

`@member` defines a routable action you can call on a specific instance of a member of a collection resource. For example, if you have a collection of `Page` resources, and a user can post a comment on a specific page:

```coffeescript
class window.Example extends Batman.App
  @resources 'pages', ->
    @member 'comment'

class Example.PagesController extends Batman.Controller
  comment: (params) ->
```

Would result in `/pages/:id/comment` being added to the routing map, pointed to `PagesController#comment`.

## @collection

`@collection` is similar to `@member` in that it adds routable actions to a `@resources` set of routes. In this case the action would apply to the entire collection. For example, if you have a list of spam comments made across _all_ your `Page` resources:

```coffeescript
class window.Example extends Batman.App
  @resources 'pages', ->
    @collection 'spam_comments'

class Example.PagesController extends Batman.Controller
  comments: ->
```

Would result in `/pages/spam_comments` being added to the routing map, pointed to `PagesController#spam_comments`.

## @root

`@root` defines the root controller and action to be used when visiting the base application URL. For example:

```coffeescript
class window.Example extends Batman.App
  @root 'pages#index'

class Example.PagesController extends Batman.Controller
  index: ->
```

Would result in `/` being pointed to `PagesController#index`.

# /api/App Components/Batman.App/Batman.App Routing

The batman.js routing DSL is similar to the [Rails routing DSL](http://guides.rubyonrails.org/routing.html). It is oriented around the notion of a resource:

## @route

`@route` defines a custom route and can be pointed to a controller action directly. For example:

```coffeescript
class window.Example extends Batman.App
  @route 'comments', 'pages#comments'

class Example.PagesController extends Batman.Controller
  comments: ->
```

Would result in `/comments` being added to the routing map, pointed to `PagesController#comments`.

## @resources(resourceName : String[, otherResourceNames... : String][, options : Object][, scopedCallback : Function])

`@resources` is modeled after the Rails routing `resources` method. It automatically defines some routes and matches them to controller actions. For example,

```coffeescript
class App extends Batman.App
  @resources 'pages'

class App.PagesController extends Batman.Controller
  index: ->
    # ...
  new: ->
    # ...
  show: (params) ->
    App.Page.find params.id, (err, page) ->
      @set('currentPage', page)
  edit: (params) ->
    App.Page.find params.id, (err, page) ->
      @set('currentPage', page)
```

Will set up these routes:

Path | Controller Action
-- | -- |
/pages | App.PagesController#index
/pages/new | App.PagesController#new
/pages/:id | App.PagesController#show
/pages/:id/edit | App.PagesController#edit

Note that unlike Rails, `destroy`, `update`, and `create` are not performed by controller actions in batman.js. Instead, call `save` or `destroy` on your records directly.
To access a generated route from within a view, use the [`data-route` binding](batman.view_bindings.html#data-route).

### Nested Resources

You may also nest resources, as in Rails:

```coffeescript
class App extends Batman.App
  @resources 'pages', ->
    @resources 'comments'
```

Will set up these routes for `App.Comment`:

Path | Controller Action
-- | -- |
/pages/:page_id/comments | App.CommentsController#index
/pages/:page_id/comments/new | App.CommentsController#new
/pages/:page_id/comments/:id | App.CommentsController#show
/pages/:page_id/comments/:id/edit | App.CommentsController#edit

## @member

`@member` defines a routable action you can call on a specific instance of a member of a collection resource. For example, if you have a collection of `Page` resources, and a user can post a comment on a specific page:

```coffeescript
class window.Example extends Batman.App
  @resources 'pages', ->
    @member 'comment'

class Example.PagesController extends Batman.Controller
  comment: (params) ->
```

Would result in `/pages/:id/comment` being added to the routing map, pointed to `PagesController#comment`.

## @collection

`@collection` is similar to `@member` in that it adds routable actions to a `@resources` set of routes. In this case the action would apply to the entire collection. For example, if you have a list of spam comments made across _all_ your `Page` resources:

```coffeescript
class window.Example extends Batman.App
  @resources 'pages', ->
    @collection 'spam_comments'

class Example.PagesController extends Batman.Controller
  comments: ->
```

Would result in `/pages/spam_comments` being added to the routing map, pointed to `PagesController#spam_comments`.

## @root

`@root` defines the root controller and action to be used when visiting the base application URL. For example:

```coffeescript
class window.Example extends Batman.App
  @root 'pages#index'

class Example.PagesController extends Batman.Controller
  index: ->
```

Would result in `/` being pointed to `PagesController#index`.


weya base lint

weya base lint

#Weya.Base.js

    @Weya = {} unless @Weya?
    Weya = @Weya

##Weya.Base
Introduces class level function initialize and include.

    class Base
     _initialize: []
     on: {}

Extend Events

     @extend: ->
      events = @::on
      @::on = {}
      @::on[k] = v for k, v of events

Add event listeners

     @listen: (name, func) ->
      @::on[name] = func

Getter

     @get: (name, func) ->
      @::__defineGetter__ name, func

Setter

     @set: (name, func) ->
      @::__defineSetter__ name, func

     constructor: ->
      @_init.apply this, arguments

####Register initialize functions.
All initializer funcitons in subclasses will be called with the constructor
arguments.

     @initialize: (func) ->
      @::_initialize = @::_initialize.slice()
      @::_initialize.push func

     _init: ->
      for init in @_initialize
       init.apply this, arguments

      return

####Include objects.
You can include objects by registering them with @include. This tries to
solve the problem of single inheritence.

     @include: (obj) ->
      for k, v of obj
       switch k
        when 'initialize'
         @::_initialize.push v
        when 'on'
         for event, listener of v
          @::on[event] = listener
        else
         @::[k] = v

     @initialize ->
      events = @on
      @on = {}
      for k, v of events
       @on[k] = v.bind this

    Weya.Base = Base

    if module?
     module.exports = Weya.Base

#Weya.Base.js

    @Weya = {} unless @Weya?
    Weya = @Weya

##Weya.Base
Introduces class level function initialize and include.

    class Base
     _initialize: []
     on: {}

Extend Events

     @extend: ->
      events = @::on
      @::on = {}
      @::on[k] = v for k, v of events

Add event listeners

     @listen: (name, func) ->
      @::on[name] = func

Getter

     @get: (name, func) ->
      @::__defineGetter__ name, func

Setter

     @set: (name, func) ->
      @::__defineSetter__ name, func

     constructor: ->
      @_init.apply @, arguments

####Register initialize functions.
All initializer funcitons in subclasses will be called with the constructor
arguments.

     @initialize: (func) ->
      @::_initialize = @::_initialize.slice()
      @::_initialize.push func

     _init: ->
      for init in @_initialize
       init.apply @, arguments

      return

####Include objects.
You can include objects by registering them with @include. This tries to
solve the problem of single inheritence.

     @include: (obj) ->
      for k, v of obj
       switch k
        when 'initialize'
         @::_initialize.push v
        when 'on'
         for event, listener of v
          @::on[event] = listener
        else
         @::[k] = v

     @initialize ->
      events = @on
      @on = {}
      for k, v of events
       @on[k] = v.bind this

    Weya.Base = Base

    if module?
     module.exports = Weya.Base


Fixed creating not run transition

Fixed creating not run transition

# Transition

```javascript
Rectangle {
    width: 100; height: 100;
    color: 'red'
    pointer.onClick: function () {
        this.x = Math.random() * 300;
    }
    Transition {
        property: 'x'
        animation: NumberAnimation {
            duration: 1500
        }
    }
}
```

    'use strict'

    utils = require 'src/utils'
    assert = require 'src/assert'
    signal = require 'src/signal'
    log = require 'src/log'

    log = log.scope 'Renderer', 'Transition'

    module.exports = (Renderer, Impl, itemUtils) -> class Transition extends Renderer.Extension
        @__name__ = 'Transition'

## *Transition* Transition.New([*Object* options])

        @New = (opts) ->
            item = new Transition
            itemUtils.Object.initialize item, opts
            item

## *Transition* Transition::constructor() : *Renderer.Extension*

        constructor: ->
            super()
            @_running = true
            @_ready = false
            @_animation = null
            @_property = ''
            @_animationClass = Renderer.Class.New
                priority: -2
                changes:
                    updateProperty: Renderer.PropertyAnimation.NEVER

        listener = (oldVal) ->
            {animation} = @
            to = @_target[@property]
            shouldRun = animation and @running and @_ready and not animation.updatePending
            shouldRun and= utils.isFloat(oldVal) and utils.isFloat(to)
            unless shouldRun
                return

            animation.stop()
            animation.from = oldVal
            animation.to = to
            animation.start()
            return

        onTargetReady = ->
            @_ready = true

        itemUtils.defineProperty
            constructor: @
            name: 'target'
            defaultValue: null
            setter: (_super) -> (val) ->
                oldVal = @target
                if oldVal is val
                    return

                {animation, property} = @

                if animation
                    animation.stop()
                    animation.target = val

                _super.call @, val

                if oldVal
                    utils.remove oldVal._extensions, @

                @_ready = false
                if val instanceof itemUtils.Object
                    item = val
                else if val instanceof itemUtils.MutableDeepObject
                    item = val._ref
                else
                    setImmediate onTargetReady.bind(@)

                if item
                    item._extensions.push @
                    @_ready = true

                if property
                    handlerName = itemUtils.getPropHandlerName property
                    if oldVal
                        oldVal[handlerName]?.disconnect listener, @

                    if val
                        if handlerName of val
                            val[handlerName] listener, @
                        else
                            log.error "'#{property}' property signal not found"
                return

## *PropertyAnimation* Transition::animation

## *Signal* Transition::onAnimationChange(*PropertyAnimation* oldValue)

        itemUtils.defineProperty
            constructor: @
            name: 'animation'
            defaultValue: null
            developmentSetter: (val) ->
                assert.instanceOf val, Renderer.PropertyAnimation if val?
            setter: (_super) -> (val) ->
                oldVal = @animation
                if oldVal is val
                    return

                _super.call @, val

                if oldVal
                    @_animationClass.disable()
                    oldVal.target = null
                    oldVal.stop()

                if val
                    @_animationClass.target = val
                    @_animationClass.running = true
                    val.target = @target
                    val.property = @property
                return

## *String* Transition::property

## *Signal* Transition::onPropertyChange(*String* oldValue)

        itemUtils.defineProperty
            constructor: @
            name: 'property'
            defaultValue: ''
            setter: (_super) -> (val) ->
                oldVal = @property
                if oldVal is val
                    return

                {animation, target} = @

                if target and val.indexOf('.') isnt -1
                    chains = val.split '.'
                    n = chains.length
                    for chain, i in chains when i < n - 1
                        target = target[chain]
                        unless target
                            log.error "No object found for the '#{val}' property"
                            break
                    val = chains[n - 1]
                    @target = target

                if animation
                    animation.stop()
                    animation.property = val

                _super.call @, val

                if target
                    if oldVal
                        handlerName = itemUtils.getPropHandlerName oldVal
                        target[handlerName].disconnect listener, @

                    if val
                        handlerName = itemUtils.getPropHandlerName val
                        target[handlerName] listener, @
                return

# Transition

```javascript
Rectangle {
    width: 100; height: 100;
    color: 'red'
    pointer.onClick: function () {
        this.x = Math.random() * 300;
    }
    Transition {
        property: 'x'
        animation: NumberAnimation {
            duration: 1500
        }
    }
}
```

    'use strict'

    utils = require 'src/utils'
    assert = require 'src/assert'
    signal = require 'src/signal'
    log = require 'src/log'

    log = log.scope 'Renderer', 'Transition'

    module.exports = (Renderer, Impl, itemUtils) -> class Transition extends Renderer.Extension
        @__name__ = 'Transition'

## *Transition* Transition.New([*Object* options])

        @New = (opts) ->
            item = new Transition
            itemUtils.Object.initialize item, opts
            item

## *Transition* Transition::constructor() : *Renderer.Extension*

        constructor: ->
            super()
            @_animation = null
            @_property = ''
            @_animationClass = Renderer.Class.New
                priority: -2
                changes:
                    updateProperty: Renderer.PropertyAnimation.NEVER

        listener = (oldVal) ->
            {animation} = @
            to = @_target[@property]
            shouldRun = animation and @running and not animation.updatePending
            shouldRun and= utils.isFloat(oldVal) and utils.isFloat(to)
            unless shouldRun
                return

            animation.stop()
            animation.from = oldVal
            animation.to = to
            animation.start()
            return

        onTargetReady = ->
            @_running = true

        itemUtils.defineProperty
            constructor: @
            name: 'target'
            defaultValue: null
            setter: (_super) -> (val) ->
                oldVal = @target
                if oldVal is val
                    return

                {animation, property} = @

                if animation
                    animation.stop()
                    animation.target = val

                _super.call @, val

                if oldVal
                    utils.remove oldVal._extensions, @

                @_running = false
                if val instanceof itemUtils.Object
                    item = val
                else if val instanceof itemUtils.MutableDeepObject
                    item = val._ref
                else
                    setImmediate onTargetReady.bind(@)

                if item
                    item._extensions.push @
                    @_running = true

                if property
                    handlerName = itemUtils.getPropHandlerName property
                    if oldVal
                        oldVal[handlerName]?.disconnect listener, @

                    if val
                        if handlerName of val
                            val[handlerName] listener, @
                        else
                            log.error "'#{property}' property signal not found"
                return

## *PropertyAnimation* Transition::animation

## *Signal* Transition::onAnimationChange(*PropertyAnimation* oldValue)

        itemUtils.defineProperty
            constructor: @
            name: 'animation'
            defaultValue: null
            developmentSetter: (val) ->
                assert.instanceOf val, Renderer.PropertyAnimation if val?
            setter: (_super) -> (val) ->
                oldVal = @animation
                if oldVal is val
                    return

                _super.call @, val

                if oldVal
                    @_animationClass.disable()
                    oldVal.target = null
                    oldVal.stop()

                if val
                    @_animationClass.target = val
                    @_animationClass.running = true
                    val.target = @target
                    val.property = @property
                return

## *String* Transition::property

## *Signal* Transition::onPropertyChange(*String* oldValue)

        itemUtils.defineProperty
            constructor: @
            name: 'property'
            defaultValue: ''
            setter: (_super) -> (val) ->
                oldVal = @property
                if oldVal is val
                    return

                {animation, target} = @

                if target and val.indexOf('.') isnt -1
                    chains = val.split '.'
                    n = chains.length
                    for chain, i in chains when i < n - 1
                        target = target[chain]
                        unless target
                            log.error "No object found for the '#{val}' property"
                            break
                    val = chains[n - 1]
                    @target = target

                if animation
                    animation.stop()
                    animation.property = val

                _super.call @, val

                if target
                    if oldVal
                        handlerName = itemUtils.getPropHandlerName oldVal
                        target[handlerName].disconnect listener, @

                    if val
                        handlerName = itemUtils.getPropHandlerName val
                        target[handlerName] listener, @
                return


correct documentation mistake, model required page

# Page Controller

To access this module, use the following code:
`page = require('../page')`.  Methods can be called as:
`page.getPage(model, name, (page) -> { ... })`.

    module.exports = {}

## getPage

Requires:

- **model** - the Page model
- **name** - the name of the page to fetch
- **callback** - (page) -> {...}
    - **page** - a dict containing:
        - **page.name** - a string of the page name
        - **page.title** - a string of the page title
        - **page.body** - a string of the page body

Code:

    getPage = (model, name, callback) ->
      model.findOne {name: name}, (err, doc) ->
        if err
          console.error err.stack
        if !doc
          callback null
        else
          callback {
            name: doc.get 'name'
            title: doc.get 'title'
            body: doc.get 'body'
          }
    module.exports.getPage = getPage

## setPage

Requires:

- **model** - the Page model
- **page** - a dict of the page to set containing:
    - **page.name** - a string of the page name
    - **page.title** - a string of the page title
    - **page.body** - a string of the page body
- **callback** - (page) -> {...}
    - **page** - a dict of the page written to the db (uses getPage):
        - **page.name** - a string of the page name
        - **page.title** - a string of the page title
        - **page.body** - a string of the page body

Code:

    setPage = (model, page, callback) ->
      if !page || !page.name || !page.title || !page.body
        console.error 'setPage called with invalid page'
        callback null
      model.create [page], (err) ->
        if err
          console.error err.stack
          callback null
        else
          getPage model, page.name, callback
    module.exports.setPage = setPage

## Copying

This software is released under the ISC License.

Copyright (c) 2013, Cameron King <cking@ecc12.com>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

<!-- vim: ts=2 sts=2 sw=2 expandtab
     CoffeeScript-friendly tabstops in vim. -->

# Page Controller

The Page controller requires access to models.  In this application, models can
be found at `app.models`.  To access this module, use the following code:
`page = require('../page')(app.models)`.

Also note, `models` contians:

- **models.db** - Mongoose MongoDB connection
- **models.MODELNAME** - model objects

Code:

    module.exports = {}

## getPage

Requires:

- **model** - the Page model
- **name** - the name of the page to fetch
- **callback** - (page) -> {...}
    - **page** - a dict containing:
        - **page.name** - a string of the page name
        - **page.title** - a string of the page title
        - **page.body** - a string of the page body

Code:

    getPage = (model, name, callback) ->
      model.findOne {name: name}, (err, doc) ->
        if err
          console.error err.stack
        if !doc
          callback null
        else
          callback {
            name: doc.get 'name'
            title: doc.get 'title'
            body: doc.get 'body'
          }
    module.exports.getPage = getPage

## setPage

Requires:

- **model** - the Page model
- **page** - a dict of the page to set containing:
    - **page.name** - a string of the page name
    - **page.title** - a string of the page title
    - **page.body** - a string of the page body
- **callback** - (page) -> {...}
    - **page** - a dict of the page written to the db (uses getPage):
        - **page.name** - a string of the page name
        - **page.title** - a string of the page title
        - **page.body** - a string of the page body

Code:

    setPage = (model, page, callback) ->
      if !page || !page.name || !page.title || !page.body
        console.error 'setPage called with invalid page'
        callback null
      model.create [page], (err) ->
        if err
          console.error err.stack
          callback null
        else
          getPage model, page.name, callback
    module.exports.setPage = setPage

## Copying

This software is released under the ISC License.

Copyright (c) 2013, Cameron King <cking@ecc12.com>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

<!-- vim: ts=2 sts=2 sw=2 expandtab
     CoffeeScript-friendly tabstops in vim. -->


more api friendly

more api friendly

Setup dependencies

    bodyParser = require "body-parser"
    express = require "express"
    exphbs = require "express-handlebars"
    fs = require "fs"
    http = require "http"
    async = require "async"
    lessMiddleware = require "less-middleware"
    methodOverride = require "method-override"
    path = require "path"
    AWS = require "aws-sdk"
    leech = require "./leech"

    DOMAIN = process.env["DOMAIN"]
    AWS.config.update {
        accessKeyId: process.env["AWS_ACCESS_KEY"],
        secretAccessKey: process.env["AWS_SECRET_KEY"]
    }
    AWS.config.region = 'us-east-1'

    s3 = new AWS.S3()
    app = express()
    app.set "port", process.env.PORT || 3000

Set up views

    app.set "views", path.join(__dirname, "..", "views")
    app.set "view engine", "html"
    app.engine "html", exphbs(
      defaultLayout: "main"
      extname: ".html"
    )
    #helpers: helpers
    app.enable "view cache"

Set up static assests

    app.use lessMiddleware(path.join(__dirname, "..", "public"), {}, {},
      compress: true
      sourceMap: true
    )
    app.use express.static(path.join(__dirname, "..", "public"))

Add methods PUT & DELETE

    app.use methodOverride()

Body parsing middleware

    app.use bodyParser.urlencoded(extended: true)
    app.use bodyParser.json()

Ze routes...

    app.get "/", (req, res) ->
      res.render "index", { isHome: true }

Simple route to look at all the URLs we've shortened.

    app.get "/history", (req, res) ->
      params = { Bucket: DOMAIN }
      s3.listObjects params, (err, objs) ->
        if err
            console.log "[ERROR]: could not list objects: " + err
            return res.redirect "/"

        urls = []
        async.each objs.Contents, (obj, callback) ->
          s3.headObject { Bucket: DOMAIN, Key: obj.Key }, (err, data) ->
            if err
              console.log "error", data
            url = { key: "http://#{DOMAIN}/#{obj.Key}", url: data.Metadata.url }
            if url.url
              urls.push url
            callback()
        , (err) ->
          res.render "history", { isHistory: true, urls: urls }

    app.get "/about", (req, res) ->
      res.render "about", { isAbout: true }

    app.get "/setup", (req, res) ->
      res.render "setup", { isSetup: true }

    app.post "/", (req, res) ->
      if req.body.url
        leech req.body.url, (err, url) ->
          if err
            res.render "index", { isHome: true, url: "ERROR" }
          else
            if req.query.format=="json"
              res.json { status: "OK", short_url: url, original_url: req.body.url }
            else
              res.render "index", { isHome: true, url: url }
      else
        res.json { status: "ERROR", error: "No URL Provided" }

    app.get "*", (req, res) ->
      res.render "404"

    http.createServer(app).listen app.get("port"), ->
        console.log "Express server listening on port " + app.get("port")

Setup dependencies

    bodyParser = require "body-parser"
    express = require "express"
    exphbs = require "express-handlebars"
    fs = require "fs"
    http = require "http"
    async = require "async"
    lessMiddleware = require "less-middleware"
    methodOverride = require "method-override"
    path = require "path"
    AWS = require "aws-sdk"
    leech = require "./leech"

    DOMAIN = process.env["DOMAIN"]
    AWS.config.update {
        accessKeyId: process.env["AWS_ACCESS_KEY"],
        secretAccessKey: process.env["AWS_SECRET_KEY"]
    }
    AWS.config.region = 'us-east-1'

    s3 = new AWS.S3()
    app = express()
    app.set "port", process.env.PORT || 3000

Set up views

    app.set "views", path.join(__dirname, "..", "views")
    app.set "view engine", "html"
    app.engine "html", exphbs(
      defaultLayout: "main"
      extname: ".html"
    )
    #helpers: helpers
    app.enable "view cache"

Set up static assests

    app.use lessMiddleware(path.join(__dirname, "..", "public"), {}, {},
      compress: true
      sourceMap: true
    )
    app.use express.static(path.join(__dirname, "..", "public"))

Add methods PUT & DELETE

    app.use methodOverride()

Body parsing middleware

    app.use bodyParser.urlencoded(extended: true)
    app.use bodyParser.json()

Ze routes...

    app.get "/", (req, res) ->
      res.render "index", { isHome: true }

Simple route to look at all the URLs we've shortened.

    app.get "/history", (req, res) ->
      params = { Bucket: DOMAIN }
      s3.listObjects params, (err, objs) ->
        if err
            console.log "[ERROR]: could not list objects: " + err
            return res.redirect "/"

        urls = []
        async.each objs.Contents, (obj, callback) ->
          s3.headObject { Bucket: DOMAIN, Key: obj.Key }, (err, data) ->
            if err
              console.log "error", data
            url = { key: "http://#{DOMAIN}/#{obj.Key}", url: data.Metadata.url }
            if url.url
              urls.push url
            callback()
        , (err) ->
          res.render "history", { isHistory: true, urls: urls }

    app.get "/about", (req, res) ->
      res.render "about", { isAbout: true }

    app.get "/setup", (req, res) ->
      res.render "setup", { isSetup: true }

    app.post "/", (req, res) ->
      if req.body.url
        leech req.body.url, (err, url) ->
          if err
            res.render "index", { isHome: true, url: "ERROR" }
          else
            res.render "index", { isHome: true, url: url }
      else
        res.json { "error": "No URL Provided" }

    app.get "*", (req, res) ->
      res.render "404"

    http.createServer(app).listen app.get("port"), ->
        console.log "Express server listening on port " + app.get("port")


weya data attribute

weya data attribute

Gist of SVG elements

    Tags =
     svg: 'a altGlyph altGlyphDef altGlyphItem animate animateColor
      animateMotion animateTransform circle clipPath color-profile cursor
      defs desc ellipse feBlend feColorMatrix feComponentTransfer
      feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap
      feDistantLight feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur
      feImage feMerge feMergeNode feMorphology feOffset fePointLight
      feSpecularLighting feSpotLight feTile feTurbulence
      filter font font-face font-face-format font-face-name font-face-src
      font-face-uri foreignObject g glyph glyphRef hkern image line
      linearGradient marker mask metadata missing-glyph mpath path pattern
      polygon polyline radialGradient rect script set stop style svg symbol
      text textPath title tref tspan use view vkern switch foreignObject'

List of HTML elements

     html: 'a abbr address article aside audio b bdi bdo blockquote body button
      canvas caption cite code colgroup datalist dd del details dfn div dl dt
      em fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header
      hgroup html i iframe ins kbd label legend li main map mark menu meter
      nav noscript object ol optgroup option output p pre progress q rp rt
      ruby s samp script section select small span strong style sub summary
      sup table tbody td textarea tfoot th thead time title tr u ul video'

     htmlVoid: 'area base br col command embed hr img input keygen link meta
      param source track wbr'

Wrapper for browser API

    Api =
     document: @document

Parse id and class string

    parseIdClass = (str) ->
     res =
      id: null
      class: []

     for c, i in str.split "."
      if c.indexOf("#") is 0
       res.id = c.substr 1
      else if c isnt ""
       if not res.class?
        res.class = [c]
       else
        res.class.push c

     return res

    getParameters = (args) ->
     params =
      idClass: null
      text: null
      attrs: null
      func: null

     for arg, i in args
      switch typeof arg
       when 'function' then params.func = arg
       when 'object' then params.attrs = arg
       when 'string'
        if args.length is 1
         params.text = arg
        else
         c = arg.charAt 0

         if i is 0 and (c is '#' or c is '.')
          params.idClass = parseIdClass arg
         else
          params.text = arg

     return params

#Weya DOM

    weyaDomCreate = ->

Weya object to be passed as `this`

     weya =
      _elem: null

Manipulating dom objects

     setStyles = (elem, styles) ->
      for k, v of styles
       if v?
        elem.style.setProperty k, v
       else
        elem.style.removeProperty k

     setEvents = (elem, events) ->
      for k, v of events
       elem.addEventListener k, v, false

     setData = (elem, data) ->
      for k, v of data
       elem[k] = v

     setAttributes = (elem, attrs) ->
      for k, v of attrs
       switch k
        when 'style' then setStyles elem, v
        when 'on' then setEvents elem, v
        when 'data' then setData elem, v
        else
         if v?
          elem.setAttribute k, v
         else
          elem.removeAttribute k

     setIdClass = (elem, idClass) ->
      if idClass.id?
       elem.id = idClass.id

      if idClass.class?
       if elem.classList?
        for c in idClass.class
         elem.classList.add c
       else #For older browsers; does not work with svgs
        className = ''
        for c in idClass.class
         className += ' ' if className isnt ''
         className += "#{c}"
        elem.className = className

Append a child element

     append = (ns, name, args) ->
      params = getParameters args

Keep a reference to parent element

      pElem = @_elem

Keep a reference of `elem` to return at the end of the function

      if ns?
       elem = @_elem = Api.document.createElementNS ns, name
      else
       elem = @_elem = Api.document.createElement name

      if params.idClass?
       setIdClass elem, params.idClass

      if params.attrs?
       setAttributes elem, params.attrs

      if pElem?
       pElem.appendChild elem

      if params.func?
       params.func.call this
      else if params.text?
       elem.textContent = params.text

      @_elem = pElem
      return elem

Wrap `append`

     wrapAppend = (ns, name) ->
      ->
       append.call this, ns, name, arguments

Initialize

     for name in Tags.svg.split ' '
      weya[name] = wrapAppend "http://www.w3.org/2000/svg", name

     for name in Tags.html.split ' '
      weya[name] = wrapAppend "http://www.w3.org/1999/xhtml", name

     for name in Tags.htmlVoid.split ' '
      weya[name] = wrapAppend null, name

     return weya

#Weya Markup

    weyaMarkupCreate = ->

Weya object to be passed as `this`

     weya =
      _buf: null
      _indent: 0

Render components

     setStyles = (buf, styles) ->
      buf.push " style=\""
      for k, v of styles
       buf.push "#{k}:#{v};"
      buf.push "\""

     setEvents = (buf, events) ->
      for k, v of events
       buf.push " on#{k}=\"#{v}\""

     setData = (buf, data) ->
      for k, v of data
       buf.push " data-#{k}=\"#{v}\""

     setAttributes = (buf, attrs) ->
      for k, v of attrs
       switch k
        when 'style' then setStyles buf, v
        when 'on' then setEvents buf, v
        when 'data' then setData buf, v
        else
         buf.push " #{k}=\"#{v}\""

     setIndent = (buf, indent) ->
      for i in [0...indent]
       buf.push " "

Append a child element

     append = (ns, name, args) ->
      params = getParameters args

      buf = @_buf

      setIndent buf, @_indent

      buf.push "<#{name}"

      if params.idClass?
       if params.idClass.id?
        buf.push " id=\"#{params.idClass.id}\""
       if params.idClass.class?
        buf.push " class=\"#{params.idClass.class}\""

      if params.attrs?
       setAttributes buf, params.attrs

Can close void elements (element that self close) with a `/>`

      buf.push ">\n"
      @_indent++

      if params.func?
       params.func.call this
      else if params.text?
       setIndent buf, @_indent
       buf.push params.text
       buf.push "\n"

      @_indent--
      setIndent buf, @_indent
      buf.push "</#{name}>\n"

Wrap `append`

     wrapAppend = (ns, name) ->
      ->
       append.call this, ns, name, arguments

Initialize

     for name in Tags.svg.split ' '
      weya[name] = wrapAppend "http://www.w3.org/2000/svg", name

     for name in Tags.html.split ' '
      weya[name] = wrapAppend null, name

     for name in Tags.htmlVoid.split ' '
      weya[name] = wrapAppend null, name

     return weya

#Weya API

    weyaDom = weyaDomCreate()
    weyaMarkup = weyaMarkupCreate()

Create and append to `options.elem`. If `options.context` is provied it can be
accessed via `@$`. If `options.elem` is `null`, the element is created but
not appended.

    @Weya = Weya = (options, func) ->
     weya = weyaDom
     pContext = weya.$
     weya.$ = options.context
     helpersAdded = []

     if options.helpers?
      for name, helper of options.helpers
       if not weya[name]?
        helpersAdded.push name
        weya[name] = helper.bind weya

     pElem = weya._elem
     weya._elem = options.elem
     r = func?.call weya
     weya._elem = pElem
     weya.$ = pContext

     for name in helpersAdded
      delete weya[name]

     return r

    Weya.markup = (options, func) ->
     weya = weyaMarkup
     pContext = weya.$
     weya.$ = options.context
     helpersAdded = []

     if options.helpers?
      for name, helper of options.helpers
       if not weya[name]?
        helpersAdded.push name
        weya[name] = helper.bind weya

     pBuf = weya._buf
     weya._buf = []
     r = func?.call weya
     buf = weya._buf
     weya._buf = pBuf
     weya.$ = pContext

     for name in helpersAdded
      delete weya[name]

     return buf.join ''

    Weya.setApi = (api) ->
     for k, v of api
      Api[k] = v

    if module?
     module.exports = Weya

Gist of SVG elements

    Tags =
     svg: 'a altGlyph altGlyphDef altGlyphItem animate animateColor
      animateMotion animateTransform circle clipPath color-profile cursor
      defs desc ellipse feBlend feColorMatrix feComponentTransfer
      feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap
      feDistantLight feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur
      feImage feMerge feMergeNode feMorphology feOffset fePointLight
      feSpecularLighting feSpotLight feTile feTurbulence
      filter font font-face font-face-format font-face-name font-face-src
      font-face-uri foreignObject g glyph glyphRef hkern image line
      linearGradient marker mask metadata missing-glyph mpath path pattern
      polygon polyline radialGradient rect script set stop style svg symbol
      text textPath title tref tspan use view vkern switch foreignObject'

List of HTML elements

     html: 'a abbr address article aside audio b bdi bdo blockquote body button
      canvas caption cite code colgroup datalist dd del details dfn div dl dt
      em fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header
      hgroup html i iframe ins kbd label legend li main map mark menu meter
      nav noscript object ol optgroup option output p pre progress q rp rt
      ruby s samp script section select small span strong style sub summary
      sup table tbody td textarea tfoot th thead time title tr u ul video'

     htmlVoid: 'area base br col command embed hr img input keygen link meta
      param source track wbr'

Wrapper for browser API

    Api =
     document: @document

Parse id and class string

    parseIdClass = (str) ->
     res =
      id: null
      class: []

     for c, i in str.split "."
      if c.indexOf("#") is 0
       res.id = c.substr 1
      else if c isnt ""
       if not res.class?
        res.class = [c]
       else
        res.class.push c

     return res

    getParameters = (args) ->
     params =
      idClass: null
      text: null
      attrs: null
      func: null

     for arg, i in args
      switch typeof arg
       when 'function' then params.func = arg
       when 'object' then params.attrs = arg
       when 'string'
        if args.length is 1
         params.text = arg
        else
         c = arg.charAt 0

         if i is 0 and (c is '#' or c is '.')
          params.idClass = parseIdClass arg
         else
          params.text = arg

     return params

#Weya DOM

    weyaDomCreate = ->

Weya object to be passed as `this`

     weya =
      _elem: null

Manipulating dom objects

     setStyles = (elem, styles) ->
      for k, v of styles
       if v?
        elem.style.setProperty k, v
       else
        elem.style.removeProperty k

     setEvents = (elem, events) ->
      for k, v of events
       elem.addEventListener k, v, false

     setAttributes = (elem, attrs) ->
      for k, v of attrs
       switch k
        when 'style' then setStyles elem, v
        when 'on' then setEvents elem, v
        else
         if v?
          elem.setAttribute k, v
         else
          elem.removeAttribute k

     setIdClass = (elem, idClass) ->
      if idClass.id?
       elem.id = idClass.id

      if idClass.class?
       if elem.classList?
        for c in idClass.class
         elem.classList.add c
       else #For older browsers; does not work with svgs
        className = ''
        for c in idClass.class
         className += ' ' if className isnt ''
         className += "#{c}"
        elem.className = className

Append a child element

     append = (ns, name, args) ->
      params = getParameters args

Keep a reference to parent element

      pElem = @_elem

Keep a reference of `elem` to return at the end of the function

      if ns?
       elem = @_elem = Api.document.createElementNS ns, name
      else
       elem = @_elem = Api.document.createElement name

      if params.idClass?
       setIdClass elem, params.idClass

      if params.attrs?
       setAttributes elem, params.attrs

      if pElem?
       pElem.appendChild elem

      if params.func?
       params.func.call this
      else if params.text?
       elem.textContent = params.text

      @_elem = pElem
      return elem

Wrap `append`

     wrapAppend = (ns, name) ->
      ->
       append.call this, ns, name, arguments

Initialize

     for name in Tags.svg.split ' '
      weya[name] = wrapAppend "http://www.w3.org/2000/svg", name

     for name in Tags.html.split ' '
      weya[name] = wrapAppend "http://www.w3.org/1999/xhtml", name

     for name in Tags.htmlVoid.split ' '
      weya[name] = wrapAppend null, name

     return weya

#Weya Markup

    weyaMarkupCreate = ->

Weya object to be passed as `this`

     weya =
      _buf: null
      _indent: 0

Render components

     setStyles = (buf, styles) ->
      buf.push " style=\""
      for k, v of styles
       buf.push "#{k}:#{v};"
      buf.push "\""

     setEvents = (buf, events) ->
      for k, v of events
       buf.push " on#{k}=\"#{v}\""

     setAttributes = (buf, attrs) ->
      for k, v of attrs
       switch k
        when 'style' then setStyles buf, v
        when 'on' then setEvents buf, v
        else
         buf.push " #{k}=\"#{v}\""

     setIndent = (buf, indent) ->
      for i in [0...indent]
       buf.push " "

Append a child element

     append = (ns, name, args) ->
      params = getParameters args

      buf = @_buf

      setIndent buf, @_indent

      buf.push "<#{name}"

      if params.idClass?
       if params.idClass.id?
        buf.push " id=\"#{params.idClass.id}\""
       if params.idClass.class?
        buf.push " class=\"#{params.idClass.class}\""

      if params.attrs?
       setAttributes buf, params.attrs

Can close void elements (element that self close) with a `/>`

      buf.push ">\n"
      @_indent++

      if params.func?
       params.func.call this
      else if params.text?
       setIndent buf, @_indent
       buf.push params.text
       buf.push "\n"

      @_indent--
      setIndent buf, @_indent
      buf.push "</#{name}>\n"

Wrap `append`

     wrapAppend = (ns, name) ->
      ->
       append.call this, ns, name, arguments

Initialize

     for name in Tags.svg.split ' '
      weya[name] = wrapAppend "http://www.w3.org/2000/svg", name

     for name in Tags.html.split ' '
      weya[name] = wrapAppend null, name

     for name in Tags.htmlVoid.split ' '
      weya[name] = wrapAppend null, name

     return weya

#Weya API

    weyaDom = weyaDomCreate()
    weyaMarkup = weyaMarkupCreate()

Create and append to `options.elem`. If `options.context` is provied it can be
accessed via `@$`. If `options.elem` is `null`, the element is created but
not appended.

    @Weya = Weya = (options, func) ->
     weya = weyaDom
     pContext = weya.$
     weya.$ = options.context
     helpersAdded = []

     if options.helpers?
      for name, helper of options.helpers
       if not weya[name]?
        helpersAdded.push name
        weya[name] = helper.bind weya

     pElem = weya._elem
     weya._elem = options.elem
     r = func?.call weya
     weya._elem = pElem
     weya.$ = pContext

     for name in helpersAdded
      delete weya[name]

     return r

    Weya.markup = (options, func) ->
     weya = weyaMarkup
     pContext = weya.$
     weya.$ = options.context
     helpersAdded = []

     if options.helpers?
      for name, helper of options.helpers
       if not weya[name]?
        helpersAdded.push name
        weya[name] = helper.bind weya

     pBuf = weya._buf
     weya._buf = []
     r = func?.call weya
     buf = weya._buf
     weya._buf = pBuf
     weya.$ = pContext

     for name in helpersAdded
      delete weya[name]

     return buf.join ''

    Weya.setApi = (api) ->
     for k, v of api
      Api[k] = v

    if module?
     module.exports = Weya


Change  to

Change  to


fixing spacing

fixing spacing

Docco
=====

**Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style
documentation generator. It produces HTML
that displays your comments alongside your code. Comments are passed through
[Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
passed through [Pygments](http://pygments.org/) syntax highlighting, if it
is present on the system.
This page is the result of running Docco against its own source file.

If you install Docco, you can run it from the command-line: `docco src/*.coffee`

...will generate an HTML documentation page for each of the named source files,
with a menu linking to the other pages, saving it into a `docs` folder.

The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,
and released under the MIT license.

To install Docco, first make sure you have [Node.js](http://nodejs.org/),
[Pygments](http://pygments.org/) (install the latest dev version of Pygments
from [its Mercurial repo](https://bitbucket.org/birkenfeld/pygments-main)), and
[CoffeeScript](http://coffeescript.org/).

Then, with NPM: `sudo npm install -g docco`

Docco can be used to process CoffeeScript, JavaScript, Ruby, Python, or TeX files.
Only single-line comments are processed -- block comments are ignored.

Partners in Crime:
------------------

* If **Node.js** doesn't run on your platform, or you'd prefer a more
convenient package, get [Ryan Tomayko](http://github.com/rtomayko)'s
[Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's
available as a gem.

* If you're writing shell scripts, try
[Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**,
also by Mr. Tomayko.

* If Python's more your speed, take a look at
[Nick Fitzgerald](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/).

* For **Clojure** fans, [Fogus](http://blog.fogus.me/)'s
[Marginalia](http://fogus.me/fun/marginalia/) is a bit of a departure from
"quick-and-dirty", but it'll get the job done.

* **Lua** enthusiasts can get their fix with
[Robert Gieseke](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).

* And if you happen to be a **.NET**
aficionado, check out [Don Wilson](https://github.com/dontangg)'s
[Nocco](http://dontangg.github.com/nocco/).

Main Documentation Generation Functions
---------------------------------------

Generate the documentation for a source file by reading it in, splitting it
up into comment/code sections, highlighting them for the appropriate language,
and merging them into an HTML template.

    generateDocumentation = (source, config, callback) ->
      fs.readFile source, (error, buffer) ->
        throw error if error
        code = buffer.toString()
        sections = parse source, code, config
        highlight source, sections, config, ->
          generateHtml source, sections, config
          callback()

    document = (sources, options = {}, callback = null) ->
      config = {}
      config[key] = defaults[key] for key,value of defaults
      config[key] = value for key,value of options if key of defaults

      config.sources = sources.filter((source) -> getLanguage source, config).sort()
      console.log "docco: skipped unknown type (#{m})" for m in sources when m not in config.sources

      config.doccoTemplate = _.template fs.readFileSync(config.template).toString()
      doccoStyles = fs.readFileSync(config.css).toString()

      ensureDirectory config.output, ->
        fs.writeFileSync path.join(config.output,path.basename(config.css)), doccoStyles
        files = config.sources.slice()
        nextFile = ->
          callback() if callback? and not files.length
          generateDocumentation files.shift(), config, nextFile if files.length
        nextFile()

Given a string of source code, parse out each comment and the code that
follows it, and create an individual **section** for it.

    parse = (source, code, config) ->
      lines    = code.split '\n'
      sections = []
      language = getLanguage source, config
      hasCode  = docsText = codeText = ''

      save = ->
        sections.push {docsText, codeText}
        hasCode = docsText = codeText = ''

      if language.literate
        for line, i in lines
          lines[i] = if /^\s*$/.test line
            ''
          else if match = (/^([ ]{4}|\t)/).exec line
            line[match[0].length..]
          else
            '# ' + line

      for line in lines
        if (not line and prev is 'text') or (line.match(language.commentMatcher) and not line.match(language.commentFilter))
          save() if hasCode
          docsText += (line = line.replace(language.commentMatcher, '')) + '\n'
          save() if /^(---+|===+)$/.test line
          prev = 'text'
        else
          hasCode = yes
          codeText += line + '\n'
          prev = 'code'
      save()

      sections

Highlights parsed sections of code, using **Pygments** over stdio,
and runs the text of their corresponding comments through **Markdown**, using
[Marked](https://github.com/chjj/marked).  If Pygments is not present
on the system, output the code in plain text.

We process all sections with single calls to Pygments and Marked, by
inserting marker comments between them, and then splitting the result
string wherever the marker occurs.

    highlight = (source, sections, config, callback) ->
      language = getLanguage source, config
      pygments = spawn 'pygmentize', [
        '-l', language.name,
        '-f', 'html',
        '-O', 'encoding=utf-8,tabsize=2'
      ]
      output = ''
      code = (section.codeText for section in sections).join language.codeSplitText
      docs = (section.docsText for section in sections).join language.docsSplitText

      pygments.stderr.on 'data', ->
      pygments.stdin.on 'error', ->
      pygments.stdout.on 'data', (result) ->
        output += result if result

      pygments.on 'exit', ->
        output = output.replace(highlightStart, '').replace(highlightEnd, '')
        if output is ''
          codeFragments = (htmlEscape section.codeText for section in sections)
        else
          codeFragments = output.split language.codeSplitHtml
        docsFragments = marked(docs).split language.docsSplitHtml

        for section, i in sections
          section.codeHtml = highlightStart + codeFragments[i] + highlightEnd
          section.docsHtml = docsFragments[i]
        callback()

      if pygments.stdin.writable
        pygments.stdin.write code
        pygments.stdin.end()

Escape an html string, to produce valid non-highlighted output when pygments
is not present on the system.

    htmlEscape = (string) ->
      string.replace(/&/g, '&')
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/\//g,'/')

Once all of the code is finished highlighting, we can generate the HTML file by
passing the completed sections into the template, and then writing the file to
the specified output path.

    generateHtml = (source, sections, config) ->
      destination = (filepath) ->
        path.join(config.output, path.basename(filepath, path.extname(filepath)) + '.html')
      hasTitle = marked.lexer(sections[0].docsText)[0].type is 'heading'
      title = if hasTitle then null else path.basename(source)
      dest  = destination source
      html  = config.doccoTemplate {
        title      : title,
        sections   : sections,
        sources    : config.sources,
        path       : path,
        destination: destination
        css        : path.basename(config.css)
      }
      console.log "docco: #{source} -> #{dest}"
      fs.writeFileSync dest, html

Helpers & Setup
---------------

Require our external dependencies.

    _             = require 'underscore'
    fs            = require 'fs'
    path          = require 'path'
    marked        = require 'marked'
    commander     = require 'commander'
    {spawn, exec} = require 'child_process'

Read resource file and return its content.

    getResource = (name) ->
      fullPath = path.join __dirname, 'resources', name
      fs.readFileSync(fullPath).toString()

Languages are stored in JSON format in the file `resources/languages.json`
Each item maps the file extension to the name of the Pygments lexer and the
symbol that indicates a comment. To add a new language, modify the file.

    languages = JSON.parse getResource 'languages.json'

Build out the appropriate matchers and delimiters for each language.

    for ext, l of languages

      # Does the line begin with a comment?
      l.commentMatcher = ///^\s*#{l.symbol}\s?///

      # Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix\))
      # and interpolations...
      l.commentFilter = /(^#![/]|^\s*#\{)/

      # The dividing token we feed into Pygments, to delimit the boundaries between
      # sections.
      l.codeSplitText = "\n#{l.symbol}DIVIDER\n"

      # The mirror of `codeSplitText` that we expect Pygments to return. We can split
      # on this to recover the original sections.
      # Note: the class is "c" for Python and "c1" for the other languages
      l.codeSplitHtml = ///\n*#{l.symbol}DIVIDER<\/span>\n*///

      # The dividing token we feed into markdown, to delimit the boundaries between
      # sections.
      l.docsSplitText = "\n##{l.name}DOCDIVIDER\n"

      # The mirror of `docsSplitText` that we expect markdown to return. We can split
      # on this to recover the original sections.
      l.docsSplitHtml = ///
#{l.name}DOCDIVIDER
///

Get the current language we're documenting, based on the extension.

    getLanguage = (source, config) ->
      ext  = config.extension or path.extname(source)
      lang = languages[ext]
      if lang.name is 'markdown'
        codeExt = path.extname(path.basename(source, ext))
        if codeExt and codeLang = languages[codeExt]
          lang = _.extend {}, codeLang, {literate: yes}
      lang

Ensure that the destination directory exists.

    ensureDirectory = (dir, cb, made=null) ->
      mode = parseInt '0777', 8
      fs.mkdir dir, mode, (er) ->
        return cb null, made || dir if not er
        if er.code == 'ENOENT'
          return ensureDirectory path.dirname(dir), (er, made) ->
            if er then cb er, made else ensureDirectory dir, cb, made
        cb er, made

The start of each Pygments highlight block.

    highlightStart = '

'

The end of each Pygments highlight block.

    highlightEnd   = '

'

Extract the docco version from `package.json`

    version = JSON.parse(fs.readFileSync("#{__dirname}/package.json")).version

Default configuration options.

    defaults =
      template : "#{__dirname}/resources/docco.jst"
      css      : "#{__dirname}/resources/docco.css"
      output   : "docs/"
      extension: null

Run from Commandline
--------------------

Run Docco from a set of command line arguments.
Parse command line using [Commander JS](https://github.com/visionmedia/commander.js).

    run = (args=process.argv) ->
      commander.version(version)
        .usage("[options] <filePattern ...>")
        .option("-c, --css [file]","use a custom css file", defaults.css)
        .option("-o, --output [path]","use a custom output path", defaults.output)
        .option("-t, --template [file]","use a custom .jst template", defaults.template)
        .option("-e, --extension <ext>","use the given file extension for all inputs", defaults.extension)
        .parse(args)
        .name = "docco"
      if commander.args.length
        document(commander.args.slice(), commander)
      else
        console.log commander.helpInformation()

Public API
----------

    Docco = module.exports = {run, document, parse, version}

Docco
=====

**Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style
documentation generator. It produces HTML
that displays your comments alongside your code. Comments are passed through
[Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
passed through [Pygments](http://pygments.org/) syntax highlighting, if it
is present on the system.
This page is the result of running Docco against its own source file.

If you install Docco, you can run it from the command-line: `docco src/*.coffee`

...will generate an HTML documentation page for each of the named source files,
with a menu linking to the other pages, saving it into a `docs` folder.

The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,
and released under the MIT license.

To install Docco, first make sure you have [Node.js](http://nodejs.org/),
[Pygments](http://pygments.org/) (install the latest dev version of Pygments
from [its Mercurial repo](https://bitbucket.org/birkenfeld/pygments-main)), and
[CoffeeScript](http://coffeescript.org/).

Then, with NPM: `sudo npm install -g docco`

Docco can be used to process CoffeeScript, JavaScript, Ruby, Python, or TeX files.
Only single-line comments are processed -- block comments are ignored.

Partners in Crime:
------------------

* If **Node.js** doesn't run on your platform, or you'd prefer a more
convenient package, get [Ryan Tomayko](http://github.com/rtomayko)'s
[Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's
available as a gem.

* If you're writing shell scripts, try
[Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**,
also by Mr. Tomayko.

* If Python's more your speed, take a look at
[Nick Fitzgerald](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/).

* For **Clojure** fans, [Fogus](http://blog.fogus.me/)'s
[Marginalia](http://fogus.me/fun/marginalia/) is a bit of a departure from
"quick-and-dirty", but it'll get the job done.

* **Lua** enthusiasts can get their fix with
[Robert Gieseke](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).

* And if you happen to be a **.NET**
aficionado, check out [Don Wilson](https://github.com/dontangg)'s
[Nocco](http://dontangg.github.com/nocco/).

Main Documentation Generation Functions
---------------------------------------

Generate the documentation for a source file by reading it in, splitting it
up into comment/code sections, highlighting them for the appropriate language,
and merging them into an HTML template.

    generateDocumentation = (source, config, callback) ->
      fs.readFile source, (error, buffer) ->
        throw error if error
        code = buffer.toString()
        sections = parse source, code, config
        highlight source, sections, config, ->
          generateHtml source, sections, config
          callback()

    document = (sources, options = {}, callback = null) ->
      config = {}
      config[key] = defaults[key] for key,value of defaults
      config[key] = value for key,value of options if key of defaults

      config.sources = sources.filter((source) -> getLanguage source, config).sort()
      console.log "docco: skipped unknown type (#{m})" for m in sources when m not in config.sources

      config.doccoTemplate = _.template fs.readFileSync(config.template).toString()
      doccoStyles = fs.readFileSync(config.css).toString()

      ensureDirectory config.output, ->
        fs.writeFileSync path.join(config.output,path.basename(config.css)), doccoStyles
        files = config.sources.slice()
        nextFile = ->
          callback() if callback? and not files.length
          generateDocumentation files.shift(), config, nextFile if files.length
        nextFile()

Given a string of source code, parse out each comment and the code that
follows it, and create an individual **section** for it.

    parse = (source, code, config) ->
      lines    = code.split '\n'
      sections = []
      language = getLanguage source, config
      hasCode  = docsText = codeText = ''

      save = ->
        sections.push {docsText, codeText}
        hasCode = docsText = codeText = ''

      if language.literate
        for line, i in lines
          lines[i] = if /^\s*$/.test line
            ''
          else if match = (/^([ ]{4}|\t)/).exec line
            line[match[0].length..]
          else
            '# ' + line

      for line in lines
        if (not line and prev is 'text') or (line.match(language.commentMatcher) and not line.match(language.commentFilter))
          save() if hasCode
          docsText += (line = line.replace(language.commentMatcher, '')) + '\n'
          save() if /^(---+|===+)$/.test line
          prev = 'text'
        else
          hasCode = yes
          codeText += line + '\n'
          prev = 'code'
      save()

      sections

Highlights parsed sections of code, using **Pygments** over stdio,
and runs the text of their corresponding comments through **Markdown**, using
[Marked](https://github.com/chjj/marked).  If Pygments is not present
on the system, output the code in plain text.

We process all sections with single calls to Pygments and Marked, by
inserting marker comments between them, and then splitting the result
string wherever the marker occurs.

    highlight = (source, sections, config, callback) ->
      language = getLanguage source, config
      pygments = spawn 'pygmentize', [
        '-l', language.name,
        '-f', 'html',
        '-O', 'encoding=utf-8,tabsize=2'
      ]
      output = ''
      code = (section.codeText for section in sections).join language.codeSplitText
      docs = (section.docsText for section in sections).join language.docsSplitText

      pygments.stderr.on 'data', ->
      pygments.stdin.on 'error', ->
      pygments.stdout.on 'data', (result) ->
        output += result if result

      pygments.on 'exit', ->
        output = output.replace(highlightStart, '').replace(highlightEnd, '')
        if output is ''
          codeFragments = (htmlEscape section.codeText for section in sections)
        else
          codeFragments = output.split language.codeSplitHtml
        docsFragments = marked(docs).split language.docsSplitHtml

        for section, i in sections
          section.codeHtml = highlightStart + codeFragments[i] + highlightEnd
          section.docsHtml = docsFragments[i]
        callback()

      if pygments.stdin.writable
        pygments.stdin.write code
        pygments.stdin.end()

Escape an html string, to produce valid non-highlighted output when pygments
is not present on the system.

    htmlEscape = (string) ->
      string.replace(/&/g, '&')
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/\//g,'/')

Once all of the code is finished highlighting, we can generate the HTML file by
passing the completed sections into the template, and then writing the file to
the specified output path.

    generateHtml = (source, sections, config) ->
      destination = (filepath) ->
        path.join(config.output, path.basename(filepath, path.extname(filepath)) + '.html')
      hasTitle = marked.lexer(sections[0].docsText)[0].type is 'heading'
      title = if hasTitle then null else path.basename(source)
      dest  = destination source
      html  = config.doccoTemplate {
        title      : title,
        sections   : sections,
        sources    : config.sources,
        path       : path,
        destination: destination
        css        : path.basename(config.css)
      }
      console.log "docco: #{source} -> #{dest}"
      fs.writeFileSync dest, html

Helpers & Setup
---------------

Require our external dependencies.

    _             = require 'underscore'
    fs            = require 'fs'
    path          = require 'path'
    marked        = require 'marked'
    commander     = require 'commander'
    {spawn, exec} = require 'child_process'

Read resource file and return its content.

    getResource = (name) ->
      fullPath = path.join __dirname, 'resources', name
      fs.readFileSync(fullPath).toString()

Languages are stored in JSON format in the file `resources/languages.json`
Each item maps the file extension to the name of the Pygments lexer and the
symbol that indicates a comment. To add a new language, modify the file.

    languages = JSON.parse getResource 'languages.json'

Build out the appropriate matchers and delimiters for each language.

    for ext, l of languages

      # Does the line begin with a comment?
      l.commentMatcher = ///^\s*#{l.symbol}\s?///

      # Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix\))
      # and interpolations...
      l.commentFilter = /(^#![/]|^\s*#\{)/

      # The dividing token we feed into Pygments, to delimit the boundaries between
      # sections.
      l.codeSplitText = "\n#{l.symbol}DIVIDER\n"

      # The mirror of `codeSplitText` that we expect Pygments to return. We can split
      # on this to recover the original sections.
      # Note: the class is "c" for Python and "c1" for the other languages
      l.codeSplitHtml = ///\n*#{l.symbol}DIVIDER<\/span>\n*///

      # The dividing token we feed into markdown, to delimit the boundaries between
      # sections.
      l.docsSplitText = "\n##{l.name}DOCDIVIDER\n"

      # The mirror of `docsSplitText` that we expect markdown to return. We can split
      # on this to recover the original sections.
      l.docsSplitHtml = ///
#{l.name}DOCDIVIDER
///

Get the current language we're documenting, based on the extension.

    getLanguage = (source, config) ->
      ext  = config.extension or path.extname(source)
      lang = languages[ext]
      if lang.name is 'markdown'
        codeExt = path.extname(path.basename(source, ext))
        if codeExt and codeLang = languages[codeExt]
          lang = _.extend {}, codeLang, {literate: yes}
      lang

Ensure that the destination directory exists.

    ensureDirectory = (dir, cb, made=null) ->
      mode = parseInt '0777', 8
      fs.mkdir dir, mode, (er) ->
        return cb null, made || dir if not er
        if er.code == 'ENOENT'
          return ensureDirectory path.dirname(dir), (er, made) ->
            if er then cb er, made else ensureDirectory dir, cb, made
        cb er, made

The start of each Pygments highlight block.

    highlightStart = '

'

The end of each Pygments highlight block.

    highlightEnd   = '

'

Extract the docco version from `package.json`

    version = JSON.parse(fs.readFileSync("#{__dirname}/package.json")).version

Default configuration options.

    defaults =
      template : "#{__dirname}/resources/docco.jst"
      css      : "#{__dirname}/resources/docco.css"
      output   : "docs/"
      extension: null

Run from Commandline
--------------------

Run Docco from a set of command line arguments.
Parse command line using [Commander JS](https://github.com/visionmedia/commander.js).

    run = (args=process.argv) ->
      commander.version(version)
        .usage("[options] <filePattern ...>")
        .option("-c, --css [file]","use a custom css file",defaults.css)
        .option("-o, --output [path]","use a custom output path",defaults.output)
        .option("-t, --template [file]","use a custom .jst template",defaults.template)
        .option("-e, --extension <ext>","use the given file extension for all inputs",defaults.extension)
        .parse(args)
        .name = "docco"
      if commander.args.length
        document(commander.args.slice(),commander)
      else
        console.log commander.helpInformation()

Public API
----------

    Docco = module.exports = {run, document, parse, version}


Added bounce function to Ball

Added bounce function to Ball

Signed-off-by: Diwank Singh <a78369447041e6bcf2913d083e4ed301785fc609@gmail.com>

Re: [Letter to a Source-Code-Reader](http://stewd.io/pong/lib/pong.js)

Dear Stewart

Thanks for inspiring me and many like me with the wonders of js.
With all it's warts and issues, JS is still one of my favorite languages.
I think simply by it's virtue of being the language of the web, it surpasses most others
in it's ability to champion the spirit of openness.

I have tried to keep this as simple as possible for the many awesome source code lovers
to read, reuse and critique.

Thanks again for caring to write that letter in 2009. It made a kid smile.

Diwank Singh
July 2013

*****

Browser Bricks
==============

Alright, let's get on with it.

Helper Functions
----------------

First, let's define some helper functions for the application.

    _ =   # _ namespace
      # Extend objects
      extend: (dest, src) ->
        dest[k] = v for own k, v of src
        dest

      # Pick properties
      pick: (obj, props) ->
        result = {}
        result[k] = obj[k] for k in props when obj[k]?

        result

      # UUID function (Copied shamelessly from https://gist.github.com/bmc/1893440)
      uuid: ->
        'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) ->
          r = Math.random() * 16 | 0
          v = if c is 'x' then r else (r & 0x3|0x8)
          v.toString(16)
        )

      # Simple serializer for flat objects
      serialize: (obj, {sep, eq}, cb) ->
        # Exec callback on all values of obj
        obj[k] = cb v for own k, v of obj if cb?

        # Return serialized obj
        ("#{ k }#{ eq }#{ v }" for own k, v of obj).join sep

      # Defer execution of function
      defer: (fn, args...) -> window.setTimeout fn, 1, args...

      # Clone object
      clone: (obj) ->
        # If object extend
        if obj is Object obj
          _.extend {}, obj

        else  # Assume it's array otherwise
          obj.splice 0

Init Function
-------------

Let's write a global init function that can be used to register callbacks which are
executed 'onload'.

    # Callback register
    init = do ->
      # Store registered callbacks
      callbacks = []

      # Run callbacks in order registered
      exec = -> fn?() for fn in callbacks

      # Onload callback
      onLoad = (fn) ->
        window.removeEventListener 'load', init, false
        fn?()

      (cb) ->
        if cb?
          # Register callback
          callbacks.push cb
        else
          # Defer execution until stack cleared
          onLoad -> _.defer exec

        false

    # Attach DOM load listener
    window.addEventListener 'load', init, false

Class: Box
----------

Now, let's define a box that will be the basic building block for the game.
All the objects will inherit from this class.

    class Box
      # -- Private --

      _settings:
        # Default settings
        height: 100
        width:  200
        top:    0
        left:   0

      _props:
        # Fixed window props
        toolbar:     false
        directories: false
        fullscreen:  false
        location:    false
        menubar:     false
        resizable:   false
        scrollbars:  false
        status:      false

      _window: null  # Empty window object
      _url: '/index.html' # Fixed to current page, renders based on context

      _EDITABLE: -> Object.keys @constructor::_settings   # Editable settings

      _update: (settings) ->
        # Update settings
        _.extend @_settings, (_.pick settings, @_EDITABLE())

        # Adjust window props
        @_window?.moveTo?   (@_get 'left'), (@_get 'top')
        @_window?.resizeTo? (@_get 'width'), (@_get 'height')

        # Return a copy of settings
        @_getAll()

      _get: (prop) -> @_settings[prop] if prop in @_EDITABLE()
      _getAll: -> _.extend (_.clone @_settings), @_fixed

      _getDefault: -> @constructor::_settings

      # -- Public --

      constructor: (namespace='', settings) ->
        # Make a copy of default settings
        @_settings = _.clone @_settings

        # Override settings.
        @_update settings

        # Set random name with namespace
        @id = "#{ namespace }#{ if namespace then '-' else '' }#{ _.uuid() }"
        this

      # Show window with settings.
      show: ->
        # Serialize options
        opts = _.serialize @_getAll(), {sep: ',', eq: '='}, (v) ->
          switch v
            when false then 'no'
            when true then 'yes'
            else v+''

        @_window = window.open @_url, @id, opts
        this

      # Hide the window.
      hide: ->
        @_window.close()
        @_window = null
        this

      # Check if window is visible.
      isVisible: -> @_window?.location?

      # Reset window settings.
      reset: ->
        @_update @_getDefault()
        this

      # Return or update window position coords.
      position: (coords...) ->
        # Set new coords
        if coords.length then @_update
          left: coords[0] ? @_getDefault().left  # x
          top:  coords[1] ? @_getDefault().top   # y

        # Return coords
        _.pick @_getAll(), ['top', 'left']

      # Return or update window dimensions.
      size: (dimensions...) ->
        # Set new dimensions
        if dimensions.length then @_update
          width:  dimensions[0] ? @_getDefault().width
          height: dimensions[1] ? @_getDefault().height

        # Return dimensions
        _.pick @_getAll(), ['width', 'height']

Class: Brick (Box)
------------------

Now let's use the class `Box` to design the `Brick` class which
will be used to render the bricks.

It's pretty much a useless box.

    class Brick extends Box
      constructor: (args...) -> super @type(), args...
      type: -> 'brick'

Class: Ball (Box)
-----------------

Alright, so the ball is a little tricky. It has to move two-
dimensionally and bounce off of objects.

So, we need an instance that also stores it's velocity at any
instant and the methods to manipulate it.

    class Ball extends Box
      # -- Private --
      _velocity: [0, 0]

      # Override getDefault to get default velocity
      _getDefault: -> _.extend super(), velocity: _.clone @_velocity

      # -- Public --
      constructor: (args...) ->
        @_velocity = _.clone @_velocity
        super @type(), args...

      type: -> 'ball'

      # Set or retrieve velocity
      velocity: (vel...) ->
        # Set new velocity
        if vel.length then @_velocity = [
          vel[0] ? @_getDefault().velocity[0]         # vx

          # y velocity affects distance from top so inverted to preserve
          # upward positive velocity direction.
          (vel[1] ? @_getDefault().velocity[1]) * -1  # vy
        ]

        # Return velocity
        _.clone @_velocity

      # Invert velocity
      bounce: -> @velocity (@_velocity[0] * -1), (@_velocity[1] * -1)

Class: Paddle (Ball)
--------------------

A paddle is basically an enlarged ball that's constrained to move in a
straight line.

    class Paddle extends Ball
      type: -> 'paddle'

      # Override velocity to constrain 1D motion
      velocity: (vx) ->
        if vx?
          super vx, @_velocity[1]
        else
          super()

Exports
-------

List of vars exported to global namespace.

    _.extend window ? module.exports ? this,
      _: _
      init: init
      Box: Box
      Brick: Brick
      Ball: Ball
      Paddle: Paddle

Re: [Letter to a Source-Code-Reader](http://stewd.io/pong/lib/pong.js)

Dear Stewart

Thanks for inspiring me and many like me with the wonders of js.
With all it's warts and issues, JS is still one of my favorite languages.
I think simply by it's virtue of being the language of the web, it surpasses most others
in it's ability to champion the spirit of openness.

I have tried to keep this as simple as possible for the many awesome source code lovers
to read, reuse and critique.

Thanks again for caring to write that letter in 2009. It made a kid smile.

Diwank Singh
July 2013

*****

Browser Bricks
==============

Alright, let's get on with it.

Helper Functions
----------------

First, let's define some helper functions for the application.

    _ =   # _ namespace
      # Extend objects
      extend: (dest, src) ->
        dest[k] = v for own k, v of src
        dest

      # Pick properties
      pick: (obj, props) ->
        result = {}
        result[k] = obj[k] for k in props when obj[k]?

        result

      # UUID function (Copied shamelessly from https://gist.github.com/bmc/1893440)
      uuid: ->
        'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) ->
          r = Math.random() * 16 | 0
          v = if c is 'x' then r else (r & 0x3|0x8)
          v.toString(16)
        )

      # Simple serializer for flat objects
      serialize: (obj, {sep, eq}, cb) ->
        # Exec callback on all values of obj
        obj[k] = cb v for own k, v of obj if cb?

        # Return serialized obj
        ("#{ k }#{ eq }#{ v }" for own k, v of obj).join sep

      # Defer execution of function
      defer: (fn, args...) -> window.setTimeout fn, 1, args...

      # Clone object
      clone: (obj) ->
        # If object extend
        if obj is Object obj
          _.extend {}, obj

        else  # Assume it's array otherwise
          obj.splice 0

Init Function
-------------

Let's write a global init function that can be used to register callbacks which are
executed 'onload'.

    # Callback register
    init = do ->
      # Store registered callbacks
      callbacks = []

      # Run callbacks in order registered
      exec = -> fn?() for fn in callbacks

      # Onload callback
      onLoad = (fn) ->
        window.removeEventListener 'load', init, false
        fn?()

      (cb) ->
        if cb?
          # Register callback
          callbacks.push cb
        else
          # Defer execution until stack cleared
          onLoad -> _.defer exec

        false

    # Attach DOM load listener
    window.addEventListener 'load', init, false

Class: Box
----------

Now, let's define a box that will be the basic building block for the game.
All the objects will inherit from this class.

    class Box
      # -- Private --

      _settings:
        # Default settings
        height: 100
        width:  200
        top:    0
        left:   0

      _props:
        # Fixed window props
        toolbar:     false
        directories: false
        fullscreen:  false
        location:    false
        menubar:     false
        resizable:   false
        scrollbars:  false
        status:      false

      _window: null  # Empty window object
      _url: '/index.html' # Fixed to current page, renders based on context

      _EDITABLE: -> Object.keys @constructor::_settings   # Editable settings

      _update: (settings) ->
        # Update settings
        _.extend @_settings, (_.pick settings, @_EDITABLE())

        # Adjust window props
        @_window?.moveTo?   (@_get 'left'), (@_get 'top')
        @_window?.resizeTo? (@_get 'width'), (@_get 'height')

        # Return a copy of settings
        @_getAll()

      _get: (prop) -> @_settings[prop] if prop in @_EDITABLE()
      _getAll: -> _.extend (_.clone @_settings), @_fixed

      _getDefault: -> @constructor::_settings

      # -- Public --

      constructor: (namespace='', settings) ->
        # Make a copy of default settings
        @_settings = _.clone @_settings

        # Override settings.
        @_update settings

        # Set random name with namespace
        @id = "#{ namespace }#{ if namespace then '-' else '' }#{ _.uuid() }"
        this

      # Show window with settings.
      show: ->
        # Serialize options
        opts = _.serialize @_getAll(), {sep: ',', eq: '='}, (v) ->
          switch v
            when false then 'no'
            when true then 'yes'
            else v+''

        @_window = window.open @_url, @id, opts
        this

      # Hide the window.
      hide: ->
        @_window.close()
        @_window = null
        this

      # Check if window is visible.
      isVisible: -> @_window?.location?

      # Reset window settings.
      reset: ->
        @_update @_getDefault()
        this

      # Return or update window position coords.
      position: (coords...) ->
        # Set new coords
        if coords.length then @_update
          left: coords[0] ? @_getDefault().left  # x
          top:  coords[1] ? @_getDefault().top   # y

        # Return coords
        _.pick @_getAll(), ['top', 'left']

      # Return or update window dimensions.
      size: (dimensions...) ->
        # Set new dimensions
        if dimensions.length then @_update
          width:  dimensions[0] ? @_getDefault().width
          height: dimensions[1] ? @_getDefault().height

        # Return dimensions
        _.pick @_getAll(), ['width', 'height']

Class: Brick (Box)
------------------

Now let's use the class `Box` to design the `Brick` class which
will be used to render the bricks.

It's pretty much a useless box.

    class Brick extends Box
      constructor: (args...) -> super @type(), args...
      type: -> 'brick'

Class: Ball (Box)
-----------------

Alright, so the ball is a little tricky. It has to move two-
dimensionally and bounce off of objects.

So, we need an instance that also stores it's velocity at any
instant and the methods to manipulate it.

    class Ball extends Box
      # -- Private --
      _velocity: [0, 0]

      # Override getDefault to get default velocity
      _getDefault: -> _.extend super(), velocity: _.clone @_velocity

      # -- Public --
      constructor: (args...) ->
        @_velocity = _.clone @_velocity
        super @type(), args...

      type: -> 'ball'

      # Set or retrieve velocity
      velocity: (vel...) ->
        # Set new velocity
        if vel.length then @_velocity = [
          vel[0] ? @_getDefault().velocity[0]         # vx

          # y velocity affects distance from top so inverted to preserve
          # upward positive velocity direction.
          (vel[1] ? @_getDefault().velocity[1]) * -1  # vy
        ]

        # Return velocity
        _.clone @_velocity

Class: Paddle (Ball)
--------------------

A paddle is basically an enlarged ball that's constrained to move in a
straight line.

    class Paddle extends Ball
      type: -> 'paddle'

      # Override velocity to constrain 1D motion
      velocity: (vx) ->
        if vx?
          super vx, @_velocity[1]
        else
          super()

Exports
-------

List of vars exported to global namespace.

    _.extend window ? module.exports ? this,
      _: _
      init: init
      Box: Box
      Brick: Brick
      Ball: Ball
      Paddle: Paddle