value to string

value to string

Copyright 2014 - 2015
Author: Varuna Jayasiri http://blog.varunajayasiri.com

#Value

    Mod.require 'Models.Properties',
     'Models.Property.Base'
     'Weya.Base'
     'Weya'
     (PROPERTIES, Base, WeyaBase, Weya) ->

Class

      class Value extends Base
       @extend()

       propertyType: 'value'

       @default 'value', (str, stack) ->
        if (typeof str) isnt 'string'
         throw new Error "Exected string: #{typeof str}, #{str}"
        return str

       @default 'string', (value, stack) -> "#{str}"

       @default 'rows', 1
       @default 'columns', 20

       @default 'valid', (str, stack) ->
        if (typeof str) isnt 'string'
         return false
        else
         return true

       @default 'search', (str, stack) -> null

       @default 'default', -> ''

       @default 'isDefault', (value, stack) ->
        value is @schema.default()

       parse: (data, stack) ->
        r = super data, stack
        return r unless r is true
        if not @schema.valid data, stack
         return @error 'invalid'

        return {
         score: 1
         errors: []
         value: @schema.value data, stack
        }

       toJSON: (value, stack) -> value
       toJSONFull: (value, stack) -> value

       edit: (elem, value, onChanged, stack) ->
        new Edit this, elem, value, onChanged, stack

Edit

      class Edit extends WeyaBase
       @extend()

       @initialize (property, elem, value, onChanged, stack) ->
        @property = property
        @elems =
         parent: elem
        @value = value
        @onChanged = onChanged
        @stack = stack
        @render()

       render: ->
        schema = @property.schema
        width = 2 + Math.round schema.columns * 7.25
        Weya elem: @elems.parent, context: this, ->
         if schema.rows is 1
          @$.elems.input = @input '.value',
           type: 'text'
           placeholder: @$.property._name
           style:
            width: "#{width}px"
         else
          @$.elems.input = @textarea '.value',
           rows: schema.rows
           columns: schema.columns
           style:
            width: "#{width}px"
            height: "#{Math.round schema.rows * 18}px"

         @$.elems.search = @div '.search',
          style:
           display: 'none'
           width: "#{width}px"

        @elems.input.value = schema.string @value, @stack
        @elems.input.addEventListener "input", @on.change
        @elems.input.addEventListener "focus", @on.focus
        @elems.input.addEventListener "blur", @on.blur
        @elems.search.addEventListener 'click', @on.searchClick
        @change()

       search: ->
        value = @elems.input.value
        results = @property.schema.search.call @property, value, @stack
        return if not results?
        return if not Array.isArray results

        if results.length is 0
         @elems.search.style.display = 'none'
         return

        @elems.search.style.display = 'block'
        @elems.search.innerHTML = ''
        Weya elem: @elems.search, ->
         for r, i in results
          break if i > 10
          e = @div r
          e._result = r

       @listen 'searchClick', (e) ->
        n = e.target
        result = null
        while n? and n isnt @elems.search
         if n._result
          result = n._result
          break
         n = n.parentNode

        return if not result?
        @elems.input.value = result
        @elems.search.style.display = 'none'
        @change()

       @listen 'focus', (e) -> @search()
       @listen 'blur', (e) ->
        setTimeout =>
         @elems.search.style.display = 'none'
        , 400

       @listen 'change', (e) ->
        @search()
        @change()

       change: ->
        value = @elems.input.value
        if not @property.schema.valid.call @property, value, @stack
         @elems.input.classList.add 'invalid'
        else
         @elems.input.classList.remove 'invalid'
         value = @property.schema.value.call this, value, @stack
         @onChanged value, true

      PROPERTIES.register 'value', Value

Copyright 2014 - 2015
Author: Varuna Jayasiri http://blog.varunajayasiri.com

#Value

    Mod.require 'Models.Properties',
     'Models.Property.Base'
     'Weya.Base'
     'Weya'
     (PROPERTIES, Base, WeyaBase, Weya) ->

Class

      class Value extends Base
       @extend()

       propertyType: 'value'

       @default 'value', (str, stack) ->
        if (typeof str) isnt 'string'
         throw new Error "Exected string: #{typeof str}, #{str}"
        return str

       @default 'string', (value, stack) -> "#{str}"

       @default 'rows', 1
       @default 'columns', 20

       @default 'valid', (str, stack) ->
        if (typeof str) isnt 'string'
         return false
        else
         return true

       @default 'search', (str, stack) -> null

       @default 'default', -> ''

       @default 'isDefault', (value, stack) ->
        value is @schema.default()

       parse: (data, stack) ->
        r = super data, stack
        return r unless r is true
        if not @schema.valid data, stack
         return @error 'invalid'

        return {
         score: 1
         errors: []
         value: @schema.value data, stack
        }

       toJSON: (value, stack) -> value
       toJSONFull: (value, stack) -> value

       edit: (elem, value, onChanged, stack) ->
        new Edit this, elem, value, onChanged, stack

Edit

      class Edit extends WeyaBase
       @extend()

       @initialize (property, elem, value, onChanged, stack) ->
        @property = property
        @elems =
         parent: elem
        @value = value
        @onChanged = onChanged
        @stack = stack
        @render()

       render: ->
        schema = @property.schema
        width = 2 + Math.round schema.columns * 7.25
        Weya elem: @elems.parent, context: this, ->
         if schema.rows is 1
          @$.elems.input = @input '.value',
           type: 'text'
           placeholder: @$.property._name
           style:
            width: "#{width}px"
         else
          @$.elems.input = @textarea '.value',
           rows: schema.rows
           columns: schema.columns
           style:
            width: "#{width}px"
            height: "#{Math.round schema.rows * 18}px"

         @$.elems.search = @div '.search',
          style:
           display: 'none'
           width: "#{width}px"

        @elems.input.value = @value
        @elems.input.addEventListener "input", @on.change
        @elems.input.addEventListener "focus", @on.focus
        @elems.input.addEventListener "blur", @on.blur
        @elems.search.addEventListener 'click', @on.searchClick
        @change()

       search: ->
        value = @elems.input.value
        results = @property.schema.search.call @property, value, @stack
        return if not results?
        return if not Array.isArray results

        if results.length is 0
         @elems.search.style.display = 'none'
         return

        @elems.search.style.display = 'block'
        @elems.search.innerHTML = ''
        Weya elem: @elems.search, ->
         for r, i in results
          break if i > 10
          e = @div r
          e._result = r

       @listen 'searchClick', (e) ->
        n = e.target
        result = null
        while n? and n isnt @elems.search
         if n._result
          result = n._result
          break
         n = n.parentNode

        return if not result?
        @elems.input.value = result
        @elems.search.style.display = 'none'
        @change()

       @listen 'focus', (e) -> @search()
       @listen 'blur', (e) ->
        setTimeout =>
         @elems.search.style.display = 'none'
        , 400

       @listen 'change', (e) ->
        @search()
        @change()

       change: ->
        value = @elems.input.value
        if not @property.schema.valid.call @property, value, @stack
         @elems.input.classList.add 'invalid'
        else
         @elems.input.classList.remove 'invalid'
         value = @property.schema.value.call this, value, @stack
         @onChanged value, true

      PROPERTIES.register 'value', Value


documenting custom templates and the need for stylesheets

Docco
=====

**Docco** is a quick-and-dirty documentation generator, written in
[Literate CoffeeScript](http://coffeescript.org/#literate).
It produces an HTML document that displays your comments intermingled with your
code. All prose is passed through
[Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
passed through [Highlight.js](http://highlightjs.org/) syntax highlighting.
This page is the result of running Docco against its own
[source file](https://github.com/jashkenas/docco/blob/master/docco.litcoffee).

1. Install Docco with **npm**: `sudo npm install -g docco`

2. Run it against your code: `docco src/*.coffee`

There is no "Step 3". This will generate an HTML page for each of the named
source files, with a menu linking to the other pages, saving the whole mess
into a `docs` folder (configurable).

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

Docco can be used to process code written in any programming language. If it
doesn't handle your favorite yet, feel free to
[add it to the list](https://github.com/jashkenas/docco/blob/master/resources/languages.json).
Finally, the ["literate" style](http://coffeescript.org/#literate) of *any*
language is also supported — just tack an `.md` extension on the end:
`.coffee.md`, `.py.md`, and so on.

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.io/rocco/rocco.html), the **Ruby** port that's
available as a gem.

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

* If **Python** is more your speed, take a look at
[Nick Fitzgerald](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.io/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.

* There's a **Go** port called [Gocco](http://nikhilm.github.io/gocco/),
written by [Nikhil Marathe](https://github.com/nikhilm).

* For all you **PHP** buffs out there, Fredi Bach's
[sourceMakeup](http://jquery-jkit.com/sourcemakeup/) (we'll let the faux pas
with respect to our naming scheme slide), should do the trick nicely.

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

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

* Going further afield from the quick-and-dirty, [Groc](http://nevir.github.io/groc/)
is a **CoffeeScript** fork of Docco that adds a searchable table of contents,
and aims to gracefully handle large projects with complex hierarchies of code.

Note that not all ports will support all Docco features ... yet.

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

Generate the documentation for our configured source file by copying over static
assets, reading all the source files in, splitting them up into prose+code
sections, highlighting each file in the appropriate language, and printing them
out in an HTML template.

    document = (options = {}, callback) ->
      config = configure options

      fs.mkdirs config.output, ->

        callback or= (error) -> throw error if error
        copyAsset  = (file, callback) ->
          fs.copy file, path.join(config.output, path.basename(file)), callback
        complete   = ->
          copyAsset config.css, (error) ->
            if error then callback error
            else if fs.existsSync config.public then copyAsset config.public, callback
            else callback()

        files = config.sources.slice()

        nextFile = ->
          source = files.shift()
          fs.readFile source, (error, buffer) ->
            return callback error if error

            code = buffer.toString()
            sections = parse source, code, config
            format source, sections, config
            write source, sections, config
            if files.length then nextFile() else complete()

        nextFile()

Given a string of source code, **parse** out each block of prose and the code that
follows it — by detecting which is which, line by line — and then create an
individual **section** for it. Each section is an object with `docsText` and
`codeText` properties, and eventually `docsHtml` and `codeHtml` as well.

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

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

Our quick-and-dirty implementation of the literate programming style. Simply
invert the prose and code relationship on a per-line basis, and then continue as
normal below.

      if lang.literate
        isText = maybeCode = yes
        for line, i in lines
          lines[i] = if maybeCode and match = /^([ ]{4}|[ ]{0,3}\t)/.exec line
            isText = no
            line[match[0].length..]
          else if maybeCode = /^\s*$/.test line
            if isText then lang.symbol else ''
          else
            isText = yes
            lang.symbol + ' ' + line

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

      sections

To **format** and highlight the now-parsed sections of code, we use **Highlight.js**
over stdio, and run the text of their corresponding comments through
**Markdown**, using [Marked](https://github.com/chjj/marked).

    format = (source, sections, config) ->
      language = getLanguage source, config

Pass any user defined options to Marked if specified via command line option

      markedOptions =
        smartypants: true

      if config.marked
        markedOptions = config.marked

      marked.setOptions markedOptions

Tell Marked how to highlight code blocks within comments, treating that code
as either the language specified in the code block or the language of the file
if not specified.

      marked.setOptions {
        highlight: (code, lang) ->
          lang or= language.name

          if highlightjs.getLanguage(lang)
            highlightjs.highlight(lang, code).value
          else
            console.warn "docco: couldn't highlight code block with unknown language '#{lang}' in #{source}"
            code
      }

      for section, i in sections
        code = highlightjs.highlight(language.name, section.codeText).value
        code = code.replace(/\s+$/, '')
        section.codeHtml = "

#{code}

"
        section.docsHtml = marked(section.docsText)

Once all of the code has finished highlighting, we can **write** the resulting
documentation file by passing the completed HTML sections into the template,
and rendering it to the specified output path.

    write = (source, sections, config) ->

      destination = (file) ->
        path.join(config.output, file + '.html')

The **title** of the file is either the first heading in the prose, or the
name of the source file.

      firstSection = _.find sections, (section) ->
        section.docsText.length > 0
      first = marked.lexer(firstSection.docsText)[0] if firstSection
      hasTitle = first and first.type is 'heading' and first.depth is 1
      title = if hasTitle then first.text else path.basename source

      html = config.template {sources: config.sources, css: path.basename(config.css),
        title, hasTitle, sections, path, destination,}

      console.log "docco: #{source} -> #{destination source}"
      fs.writeFileSync destination(source), html

Configuration
-------------

Default configuration **options**. All of these may be extended by
user-specified options.

    defaults =
      layout:     'parallel'
      output:     'docs'
      template:   null
      css:        null
      extension:  null
      languages:  {}
      marked:     null

**Configure** this particular run of Docco. We might use a passed-in external
template, or one of the built-in **layouts**. We only attempt to process
source files for languages for which we have definitions.

    configure = (options) ->
      config = _.extend {}, defaults, _.pick(options, _.keys(defaults)...)

      config.languages = buildMatchers config.languages

The user is able to override the layout file used with the `--template` parameter.
In this case, it is also neccessary to explicitly specify a stylesheet file.
These custom templates are compiled exactly like the predefined ones, but the `public` folder
is only copied for the latter.

      if options.template
        unless options.css
          console.warn "docco: no stylesheet file specified"
        config.layout = null
      else
        dir = config.layout = path.join __dirname, 'resources', config.layout
        config.public       = path.join dir, 'public' if fs.existsSync path.join dir, 'public'
        config.template     = path.join dir, 'docco.jst'
        config.css          = options.css or path.join dir, 'docco.css'
      config.template = _.template fs.readFileSync(config.template).toString()

      if options.marked
        config.marked = JSON.parse fs.readFileSync(options.marked)

      config.sources = options.args.filter((source) ->
        lang = getLanguage source, config
        console.warn "docco: skipped unknown type (#{path.basename source})" unless lang
        lang
      ).sort()

      config

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

Require our external dependencies.

    _           = require 'underscore'
    fs          = require 'fs-extra'
    path        = require 'path'
    marked      = require 'marked'
    commander   = require 'commander'
    highlightjs = require 'highlight.js'

Languages are stored in JSON in the file `resources/languages.json`.
Each item maps the file extension to the name of the language and the
`symbol` that indicates a line comment. To add support for a new programming
language to Docco, just add it to the file.

    languages = JSON.parse fs.readFileSync(path.join(__dirname, 'resources', 'languages.json'))

Build out the appropriate matchers and delimiters for each language.

    buildMatchers = (languages) ->
      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_%28Unix%29) and interpolations...

        l.commentFilter = /(^#![/]|^\s*#\{)/
      languages
    languages = buildMatchers languages

A function to get the current language we're documenting, based on the
file extension. Detect and tag "literate" `.ext.md` variants.

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

Keep it DRY. Extract the docco **version** from `package.json`

    version = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'))).version

Command Line Interface
----------------------

Finally, let's define the interface to run Docco from the command line.
Parse options using [Commander](https://github.com/visionmedia/commander.js).

    run = (args = process.argv) ->
      c = defaults
      commander.version(version)
        .usage('[options] files')
        .option('-L, --languages [file]', 'use a custom languages.json', _.compose JSON.parse, fs.readFileSync)
        .option('-l, --layout [name]',    'choose a layout (parallel, linear or classic)', c.layout)
        .option('-o, --output [path]',    'output to a given folder', c.output)
        .option('-c, --css [file]',       'use a custom css file', c.css)
        .option('-t, --template [file]',  'use a custom .jst template', c.template)
        .option('-e, --extension [ext]',  'assume a file extension for all inputs', c.extension)
        .option('-m, --marked [file]',    'use custom marked options', c.marked)
        .parse(args)
        .name = "docco"
      if commander.args.length
        document commander
      else
        console.log commander.helpInformation()

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

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

Docco
=====

**Docco** is a quick-and-dirty documentation generator, written in
[Literate CoffeeScript](http://coffeescript.org/#literate).
It produces an HTML document that displays your comments intermingled with your
code. All prose is passed through
[Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
passed through [Highlight.js](http://highlightjs.org/) syntax highlighting.
This page is the result of running Docco against its own
[source file](https://github.com/jashkenas/docco/blob/master/docco.litcoffee).

1. Install Docco with **npm**: `sudo npm install -g docco`

2. Run it against your code: `docco src/*.coffee`

There is no "Step 3". This will generate an HTML page for each of the named
source files, with a menu linking to the other pages, saving the whole mess
into a `docs` folder (configurable).

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

Docco can be used to process code written in any programming language. If it
doesn't handle your favorite yet, feel free to
[add it to the list](https://github.com/jashkenas/docco/blob/master/resources/languages.json).
Finally, the ["literate" style](http://coffeescript.org/#literate) of *any*
language is also supported — just tack an `.md` extension on the end:
`.coffee.md`, `.py.md`, and so on.

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.io/rocco/rocco.html), the **Ruby** port that's
available as a gem.

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

* If **Python** is more your speed, take a look at
[Nick Fitzgerald](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.io/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.

* There's a **Go** port called [Gocco](http://nikhilm.github.io/gocco/),
written by [Nikhil Marathe](https://github.com/nikhilm).

* For all you **PHP** buffs out there, Fredi Bach's
[sourceMakeup](http://jquery-jkit.com/sourcemakeup/) (we'll let the faux pas
with respect to our naming scheme slide), should do the trick nicely.

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

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

* Going further afield from the quick-and-dirty, [Groc](http://nevir.github.io/groc/)
is a **CoffeeScript** fork of Docco that adds a searchable table of contents,
and aims to gracefully handle large projects with complex hierarchies of code.

Note that not all ports will support all Docco features ... yet.

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

Generate the documentation for our configured source file by copying over static
assets, reading all the source files in, splitting them up into prose+code
sections, highlighting each file in the appropriate language, and printing them
out in an HTML template.

    document = (options = {}, callback) ->
      config = configure options

      fs.mkdirs config.output, ->

        callback or= (error) -> throw error if error
        copyAsset  = (file, callback) ->
          fs.copy file, path.join(config.output, path.basename(file)), callback
        complete   = ->
          copyAsset config.css, (error) ->
            if error then callback error
            else if fs.existsSync config.public then copyAsset config.public, callback
            else callback()

        files = config.sources.slice()

        nextFile = ->
          source = files.shift()
          fs.readFile source, (error, buffer) ->
            return callback error if error

            code = buffer.toString()
            sections = parse source, code, config
            format source, sections, config
            write source, sections, config
            if files.length then nextFile() else complete()

        nextFile()

Given a string of source code, **parse** out each block of prose and the code that
follows it — by detecting which is which, line by line — and then create an
individual **section** for it. Each section is an object with `docsText` and
`codeText` properties, and eventually `docsHtml` and `codeHtml` as well.

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

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

Our quick-and-dirty implementation of the literate programming style. Simply
invert the prose and code relationship on a per-line basis, and then continue as
normal below.

      if lang.literate
        isText = maybeCode = yes
        for line, i in lines
          lines[i] = if maybeCode and match = /^([ ]{4}|[ ]{0,3}\t)/.exec line
            isText = no
            line[match[0].length..]
          else if maybeCode = /^\s*$/.test line
            if isText then lang.symbol else ''
          else
            isText = yes
            lang.symbol + ' ' + line

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

      sections

To **format** and highlight the now-parsed sections of code, we use **Highlight.js**
over stdio, and run the text of their corresponding comments through
**Markdown**, using [Marked](https://github.com/chjj/marked).

    format = (source, sections, config) ->
      language = getLanguage source, config

Pass any user defined options to Marked if specified via command line option

      markedOptions =
        smartypants: true

      if config.marked
        markedOptions = config.marked

      marked.setOptions markedOptions

Tell Marked how to highlight code blocks within comments, treating that code
as either the language specified in the code block or the language of the file
if not specified.

      marked.setOptions {
        highlight: (code, lang) ->
          lang or= language.name

          if highlightjs.getLanguage(lang)
            highlightjs.highlight(lang, code).value
          else
            console.warn "docco: couldn't highlight code block with unknown language '#{lang}' in #{source}"
            code
      }

      for section, i in sections
        code = highlightjs.highlight(language.name, section.codeText).value
        code = code.replace(/\s+$/, '')
        section.codeHtml = "

#{code}

"
        section.docsHtml = marked(section.docsText)

Once all of the code has finished highlighting, we can **write** the resulting
documentation file by passing the completed HTML sections into the template,
and rendering it to the specified output path.

    write = (source, sections, config) ->

      destination = (file) ->
        path.join(config.output, file + '.html')

The **title** of the file is either the first heading in the prose, or the
name of the source file.

      firstSection = _.find sections, (section) ->
        section.docsText.length > 0
      first = marked.lexer(firstSection.docsText)[0] if firstSection
      hasTitle = first and first.type is 'heading' and first.depth is 1
      title = if hasTitle then first.text else path.basename source

      html = config.template {sources: config.sources, css: path.basename(config.css),
        title, hasTitle, sections, path, destination,}

      console.log "docco: #{source} -> #{destination source}"
      fs.writeFileSync destination(source), html

Configuration
-------------

Default configuration **options**. All of these may be extended by
user-specified options.

    defaults =
      layout:     'parallel'
      output:     'docs'
      template:   null
      css:        null
      extension:  null
      languages:  {}
      marked:     null

**Configure** this particular run of Docco. We might use a passed-in external
template, or one of the built-in **layouts**. We only attempt to process
source files for languages for which we have definitions.

    configure = (options) ->
      config = _.extend {}, defaults, _.pick(options, _.keys(defaults)...)

      config.languages = buildMatchers config.languages
      if options.template
        config.layout = null
      else
        dir = config.layout = path.join __dirname, 'resources', config.layout
        config.public       = path.join dir, 'public' if fs.existsSync path.join dir, 'public'
        config.template     = path.join dir, 'docco.jst'
        config.css          = options.css or path.join dir, 'docco.css'
      config.template = _.template fs.readFileSync(config.template).toString()

      if options.marked
        config.marked = JSON.parse fs.readFileSync(options.marked)

      config.sources = options.args.filter((source) ->
        lang = getLanguage source, config
        console.warn "docco: skipped unknown type (#{path.basename source})" unless lang
        lang
      ).sort()

      config

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

Require our external dependencies.

    _           = require 'underscore'
    fs          = require 'fs-extra'
    path        = require 'path'
    marked      = require 'marked'
    commander   = require 'commander'
    highlightjs = require 'highlight.js'

Languages are stored in JSON in the file `resources/languages.json`.
Each item maps the file extension to the name of the language and the
`symbol` that indicates a line comment. To add support for a new programming
language to Docco, just add it to the file.

    languages = JSON.parse fs.readFileSync(path.join(__dirname, 'resources', 'languages.json'))

Build out the appropriate matchers and delimiters for each language.

    buildMatchers = (languages) ->
      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_%28Unix%29) and interpolations...

        l.commentFilter = /(^#![/]|^\s*#\{)/
      languages
    languages = buildMatchers languages

A function to get the current language we're documenting, based on the
file extension. Detect and tag "literate" `.ext.md` variants.

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

Keep it DRY. Extract the docco **version** from `package.json`

    version = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'))).version

Command Line Interface
----------------------

Finally, let's define the interface to run Docco from the command line.
Parse options using [Commander](https://github.com/visionmedia/commander.js).

    run = (args = process.argv) ->
      c = defaults
      commander.version(version)
        .usage('[options] files')
        .option('-L, --languages [file]', 'use a custom languages.json', _.compose JSON.parse, fs.readFileSync)
        .option('-l, --layout [name]',    'choose a layout (parallel, linear or classic)', c.layout)
        .option('-o, --output [path]',    'output to a given folder', c.output)
        .option('-c, --css [file]',       'use a custom css file', c.css)
        .option('-t, --template [file]',  'use a custom .jst template', c.template)
        .option('-e, --extension [ext]',  'assume a file extension for all inputs', c.extension)
        .option('-m, --marked [file]',    'use custom marked options', c.marked)
        .parse(args)
        .name = "docco"
      if commander.args.length
        document commander
      else
        console.log commander.helpInformation()

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

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


Use post-for

Use post-for

nodePush Pushserver
===================

Copyright Information
---------------------

	"@author	Tim Düsterhus"
	"@copyright	2012-2013 Tim Düsterhus"
	"@license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>"
	"@package	be.bastelstu.wcf.nodePush"

Setup
-----

First we import the required packages and make them available in a global variable.

	express = require 'express'
	http = require 'http'
	io = require 'socket.io'
	net = require 'net'
	fs = require 'fs'

Next we try to load the configuration file "config.js".

	try
		config = require '../config.js'
	catch e
		config = { }

In case not every configuration property is set we initialize it with a default property.

	config.outbound ?= { }
	config.outbound.useTCP ?= true
	config.outbound.port ?= 9001
	config.outbound.host ?= '0.0.0.0'
	config.outbound.socket ?= __dirname + "/../outbound.sock"
	config.inbound ?= { }
	config.inbound.useTCP ?= false
	config.inbound.port ?= 9002
	config.inbound.host ?= '127.0.0.1'
	config.inbound.socket ?= __dirname + "/../inbound.sock"
	config.user ?= 'nobody'
	config.group ?= 'nogroup'

We continue with creating some helper functions.

	log = (message) ->
		console.log "[be.bastelstu.wcf.nodePush] #{message}"

	thousandsSeparator = (number) ->
		String(number).replace /(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'

	fs.open "#{__dirname}/../tmp/nodePush.child.pid", "w", 0o600, (err, fd) ->
		fs.writeSync fd, process.pid

	# Ensure our namespace is present
	be = be ? {}
	be.bastelstu ?= {}
	be.bastelstu.wcf ?= {}

be.bastelstu.wcf.nodePush
=========================

	class be.bastelstu.wcf.nodePush

Attributes
----------

`app` will become an instance of `express`.

		app: null

`server` willbecome an instance of `http`.

		server: null

`io` will become an instance of `socket.io`.

		io: null

`stats` is an object with the different statistics recorded. Statistics will be shown on the status page.

		stats:
			status: 0
			outbound:
				total: 0
				current: 0
			inbound: 0
			messages: { }
			bootTime: new Date()

Methods
-------
**constructor()**
The constructor is executed when the class is initialized. It prints some helpful information,
such as the PID and the used sockets and continues with initializing everything.

		constructor: ->
			log "nodePush running (pid:#{process.pid})"

First we display the used inbound and outbound sockets.

			if config.inbound.useTCP
				log "Inbound: #{config.inbound.host}:#{config.inbound.port}"
			else
				log "Inbound: #{config.inbound.socket}"
			if config.outbound.useTCP
				log "Outbound: #{config.outbound.host}:#{config.outbound.port}"
			else
				log "Outbound: #{config.outbound.socket}"

			@stats.bootTime = new Date()

Afterwards we initialize the inbound and outbound connection.

			@initInbound()
			@initOutbound()

In order to do a proper cleanup on shutdown we bind the `shutdown` method to the needed events and signals.

			process.on 'exit', =>
				@shutdown()
			process.on 'uncaughtException', (message) =>
				@shutdown message, 1
			process.on 'SIGINT', =>
				@shutdown()
			process.on 'SIGTERM', =>
				@shutdown()
			process.on 'SIGHUP', =>
				@shutdown null, 2

At the end we set a nice title for `ps`.

			process.title = 'nodePush'

**initOutbound()**
`initOutbound` initializes the connection to the browser. That includes starting the HTTP server and preparing
socket.io.

		initOutbound: ->
			log 'Initializing outbound socket'

First we start the express based HTTP server.

			@app = express()
			@server = http.createServer @app
			@io = io.listen @server

Afterwards we set socket.io configuration for the default environment. Files will be minified and logging reduced to a minimum.

			@io.set 'log level', 1
			@io.set 'browser client etag', true
			@io.set 'browser client minification', true
			@io.set 'browser client gzip', true

In case `env` is set to development we show some more debug output.

			@io.configure 'development', =>
				@io.set 'log level', 3
				@io.set 'browser client etag', false
				@io.set 'browser client minification', false

Next we listen on the socket.io `connection` event to record statistics.

			@io.sockets.on 'connection', (socket) =>
				@stats.outbound.total++ if @app.get('env') is 'development'
				@stats.outbound.current++

				socket.on 'userID', (userID) =>
					socket.get 'userID', (_, currentUserID) =>

In case a client misbehaves, by sending the `userID` twice, we `disconnect` it.

						if currentUserID?
							socket.disconnect()
							return

Mark user as *authenticated* by joining **user**. If a client does not send a `userID` it will not receive any messages.

						socket.set 'userID', userID
						socket.join 'authenticated'
						socket.join "user#{userID}"
						socket.emit 'authenticated'

				socket.on 'disconnect', =>
					@stats.outbound.current--

We continue with creating a callback for the `listen` call.

			listenCallback = =>

In case we are running as root we try to shed root privilegies. If this is not possible we exit, as a service
running as root is dangerous.

				if process.getuid? and (process.getuid() is 0 or process.getgid() is 0)
					try
						log 'Trying to shed root privilegies'
						process.setgid config.group
						process.setuid config.user
						log "New User ID: #{process.getuid()}, New Group ID: #{process.getgid()}"
					catch e
						log 'Cowardly refusing to keep the process alive as root.'
						process.exit 1

After the the HTTP server is listening and we are no longer running as root we start some intervals for the builtin tick events.

				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick15'
				, 15e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick30'
				, 30e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick60'
				, 60e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick90'
				, 90e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick120'
				, 120e3

				log "Done"

Start listening on the configured outbound socket.

			if config.outbound.useTCP
				@server.listen config.outbound.port, config.outbound.host, null, listenCallback
			else
				@server.listen config.outbound.socket, listenCallback
				fs.chmod config.outbound.socket, '777'

Show the status page when '/' is requested.

			@app.get '/', (req, res) =>
				res.charset = 'utf-8';
				res.type 'txt'

Show detailed information when environment is `development`.

				if @app.get('env') is 'development'
					@stats.status++
					reply = """
					Up since: #{@stats.bootTime}
					Status page: #{thousandsSeparator @stats.status} Requests
					Outbound: #{thousandsSeparator @stats.outbound.current} now - #{thousandsSeparator @stats.outbound.total} Total
					Inbound: #{thousandsSeparator @stats.inbound}
					Messages:
					"""
					for message, amount of @stats.messages
						reply += "\n	#{message}: #{thousandsSeparator amount}"
				else
					reply = """
					Up since: #{@stats.bootTime}
					Outbound: #{thousandsSeparator @stats.outbound.current} now
					"""

				res.send reply

**sendMessage(name)**
Sends a message with the given name.

		sendMessage: (name, userIDs = [ ]) ->
			return unless /^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/.test name

			if name is 'be.bastelstu.wcf.nodePush._restart'
				process.kill process.pid, 'SIGHUP'

			if @app.get('env') is 'development'
				@stats.messages[name] ?= 0
				@stats.messages[name]++

			if userIDs.length
				@io.sockets.in("user#{userID}").send name for userID in userIDs
			else
				@io.sockets.in('authenticated').send name

**initInbound()**
`initInbound` initializes the PHP side socket.

		initInbound: ->
			log 'Initializing inbound socket'

We start by creating a server.

			socket = net.createServer (c) =>
				@stats.inbound++ if @app.get('env') is 'development'

In case data is written to the server we pass it to the connected browsers and close the connection afterwards.

				c.on 'data', (data) =>
					[ message, userIDs ] = data.toString().trim().split /:/
					if userIDs? and userIDs.length
						userIDs = userIDs.split /,/
						userIDs = (parseInt userID for userID in userIDs when not isNaN parseInt userID)
					else
						userIDs = [ ]

					setTimeout =>
						@sendMessage message, userIDs
					, 20
					c.end()

				c.on 'end', ->
					c.end()

In case nothing happens within 5 seconds we close the connection in order to save resources.

				c.setTimeout 5e3, ->
					c.end()

After all callbacks are bound we start listening.

			if config.inbound.useTCP
				socket.listen config.inbound.port, config.inbound.host
			else
				socket.listen config.inbound.socket
				fs.chmod config.inbound.socket, '777'

**shutdown()**
`shutdown` performs a clean shutdown of nodePush. It cleans up the unix socket files.

		shutdown: (message = null, code = 0) ->
			if message?
				log "Shutting down: #{message}"
			else
				log 'Shutting down'

			fs.unlinkSync config.inbound.socket if not config.inbound.useTCP and fs.existsSync config.inbound.socket
			fs.unlinkSync config.outbound.socket if not config.outbound.useTCP and fs.existsSync config.outbound.socket

			process.removeAllListeners()
			process.exit code

In the end we finally initialize the class with starts all the services.

	new be.bastelstu.wcf.nodePush()

nodePush Pushserver
===================

Copyright Information
---------------------

	"@author	Tim Düsterhus"
	"@copyright	2012-2013 Tim Düsterhus"
	"@license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>"
	"@package	be.bastelstu.wcf.nodePush"

Setup
-----

First we import the required packages and make them available in a global variable.

	express = require 'express'
	http = require 'http'
	io = require 'socket.io'
	net = require 'net'
	fs = require 'fs'

Next we try to load the configuration file "config.js".

	try
		config = require '../config.js'
	catch e
		config = { }

In case not every configuration property is set we initialize it with a default property.

	config.outbound ?= { }
	config.outbound.useTCP ?= true
	config.outbound.port ?= 9001
	config.outbound.host ?= '0.0.0.0'
	config.outbound.socket ?= __dirname + "/../outbound.sock"
	config.inbound ?= { }
	config.inbound.useTCP ?= false
	config.inbound.port ?= 9002
	config.inbound.host ?= '127.0.0.1'
	config.inbound.socket ?= __dirname + "/../inbound.sock"
	config.user ?= 'nobody'
	config.group ?= 'nogroup'

We continue with creating some helper functions.

	log = (message) ->
		console.log "[be.bastelstu.wcf.nodePush] #{message}"

	thousandsSeparator = (number) ->
		String(number).replace /(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'

	fs.open "#{__dirname}/../tmp/nodePush.child.pid", "w", 0o600, (err, fd) ->
		fs.writeSync fd, process.pid

	# Ensure our namespace is present
	be = be ? {}
	be.bastelstu ?= {}
	be.bastelstu.wcf ?= {}

be.bastelstu.wcf.nodePush
=========================

	class be.bastelstu.wcf.nodePush

Attributes
----------

`app` will become an instance of `express`.

		app: null

`server` willbecome an instance of `http`.

		server: null

`io` will become an instance of `socket.io`.

		io: null

`stats` is an object with the different statistics recorded. Statistics will be shown on the status page.

		stats:
			status: 0
			outbound:
				total: 0
				current: 0
			inbound: 0
			messages: { }
			bootTime: new Date()

Methods
-------
**constructor()**
The constructor is executed when the class is initialized. It prints some helpful information,
such as the PID and the used sockets and continues with initializing everything.

		constructor: ->
			log "nodePush running (pid:#{process.pid})"

First we display the used inbound and outbound sockets.

			if config.inbound.useTCP
				log "Inbound: #{config.inbound.host}:#{config.inbound.port}"
			else
				log "Inbound: #{config.inbound.socket}"
			if config.outbound.useTCP
				log "Outbound: #{config.outbound.host}:#{config.outbound.port}"
			else
				log "Outbound: #{config.outbound.socket}"

			@stats.bootTime = new Date()

Afterwards we initialize the inbound and outbound connection.

			@initInbound()
			@initOutbound()

In order to do a proper cleanup on shutdown we bind the `shutdown` method to the needed events and signals.

			process.on 'exit', =>
				@shutdown()
			process.on 'uncaughtException', (message) =>
				@shutdown message, 1
			process.on 'SIGINT', =>
				@shutdown()
			process.on 'SIGTERM', =>
				@shutdown()
			process.on 'SIGHUP', =>
				@shutdown null, 2

At the end we set a nice title for `ps`.

			process.title = 'nodePush'

**initOutbound()**
`initOutbound` initializes the connection to the browser. That includes starting the HTTP server and preparing
socket.io.

		initOutbound: ->
			log 'Initializing outbound socket'

First we start the express based HTTP server.

			@app = express()
			@server = http.createServer @app
			@io = io.listen @server

Afterwards we set socket.io configuration for the default environment. Files will be minified and logging reduced to a minimum.

			@io.set 'log level', 1
			@io.set 'browser client etag', true
			@io.set 'browser client minification', true
			@io.set 'browser client gzip', true

In case `env` is set to development we show some more debug output.

			@io.configure 'development', =>
				@io.set 'log level', 3
				@io.set 'browser client etag', false
				@io.set 'browser client minification', false

Next we listen on the socket.io `connection` event to record statistics.

			@io.sockets.on 'connection', (socket) =>
				@stats.outbound.total++ if @app.get('env') is 'development'
				@stats.outbound.current++

				socket.on 'userID', (userID) =>
					socket.get 'userID', (_, currentUserID) =>

In case a client misbehaves, by sending the `userID` twice, we `disconnect` it.

						if currentUserID?
							socket.disconnect()
							return

Mark user as *authenticated* by joining **user**. If a client does not send a `userID` it will not receive any messages.

						socket.set 'userID', userID
						socket.join 'authenticated'
						socket.join "user#{userID}"
						socket.emit 'authenticated'

				socket.on 'disconnect', =>
					@stats.outbound.current--

We continue with creating a callback for the `listen` call.

			listenCallback = =>

In case we are running as root we try to shed root privilegies. If this is not possible we exit, as a service
running as root is dangerous.

				if process.getuid? and (process.getuid() is 0 or process.getgid() is 0)
					try
						log 'Trying to shed root privilegies'
						process.setgid config.group
						process.setuid config.user
						log "New User ID: #{process.getuid()}, New Group ID: #{process.getgid()}"
					catch e
						log 'Cowardly refusing to keep the process alive as root.'
						process.exit 1

After the the HTTP server is listening and we are no longer running as root we start some intervals for the builtin tick events.

				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick15'
				, 15e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick30'
				, 30e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick60'
				, 60e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick90'
				, 90e3
				setInterval =>
					@sendMessage 'be.bastelstu.wcf.nodePush.tick120'
				, 120e3

				log "Done"

Start listening on the configured outbound socket.

			if config.outbound.useTCP
				@server.listen config.outbound.port, config.outbound.host, null, listenCallback
			else
				@server.listen config.outbound.socket, listenCallback
				fs.chmod config.outbound.socket, '777'

Show the status page when '/' is requested.

			@app.get '/', (req, res) =>
				res.charset = 'utf-8';
				res.type 'txt'

Show detailed information when environment is `development`.

				if @app.get('env') is 'development'
					@stats.status++
					reply = """
					Up since: #{@stats.bootTime}
					Status page: #{thousandsSeparator @stats.status} Requests
					Outbound: #{thousandsSeparator @stats.outbound.current} now - #{thousandsSeparator @stats.outbound.total} Total
					Inbound: #{thousandsSeparator @stats.inbound}
					Messages:
					"""
					for message, amount of @stats.messages
						reply += "\n	#{message}: #{thousandsSeparator amount}"
				else
					reply = """
					Up since: #{@stats.bootTime}
					Outbound: #{thousandsSeparator @stats.outbound.current} now
					"""

				res.send reply

**sendMessage(name)**
Sends a message with the given name.

		sendMessage: (name, userIDs = [ ]) ->
			return unless /^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/.test name

			if name is 'be.bastelstu.wcf.nodePush._restart'
				process.kill process.pid, 'SIGHUP'

			if @app.get('env') is 'development'
				@stats.messages[name] ?= 0
				@stats.messages[name]++

			if userIDs.length
				for userID in userIDs
					@io.sockets.in("user#{userID}").send name
			else
				@io.sockets.in('authenticated').send name

**initInbound()**
`initInbound` initializes the PHP side socket.

		initInbound: ->
			log 'Initializing inbound socket'

We start by creating a server.

			socket = net.createServer (c) =>
				@stats.inbound++ if @app.get('env') is 'development'

In case data is written to the server we pass it to the connected browsers and close the connection afterwards.

				c.on 'data', (data) =>
					[ message, userIDs ] = data.toString().trim().split /:/
					if userIDs? and userIDs.length
						userIDs = userIDs.split /,/
						userIDs = (parseInt userID for userID in userIDs when not isNaN parseInt userID)
					else
						userIDs = [ ]

					setTimeout =>
						@sendMessage message, userIDs
					, 20
					c.end()

				c.on 'end', ->
					c.end()

In case nothing happens within 5 seconds we close the connection in order to save resources.

				c.setTimeout 5e3, ->
					c.end()

After all callbacks are bound we start listening.

			if config.inbound.useTCP
				socket.listen config.inbound.port, config.inbound.host
			else
				socket.listen config.inbound.socket
				fs.chmod config.inbound.socket, '777'

**shutdown()**
`shutdown` performs a clean shutdown of nodePush. It cleans up the unix socket files.

		shutdown: (message = null, code = 0) ->
			if message?
				log "Shutting down: #{message}"
			else
				log 'Shutting down'

			fs.unlinkSync config.inbound.socket if not config.inbound.useTCP and fs.existsSync config.inbound.socket
			fs.unlinkSync config.outbound.socket if not config.outbound.useTCP and fs.existsSync config.outbound.socket

			process.removeAllListeners()
			process.exit code

In the end we finally initialize the class with starts all the services.

	new be.bastelstu.wcf.nodePush()


fixed copy/paste created typos

fixed copy/paste created typos

# TEST CLASS: Element
* Parent: [Index][Parent]

---

    should = require 'should'
    module.exports = (Element, name='Element') ->

      describe name, ->
        it 'should be a class', -> Element.should.be.a.class

---

## CONSTRUCTOR

        describe '#constructor(args)', ->
          it 'should return an instance of Element', ->
            (new Element).should.be.an.instanceof Element

Constructor should copy the **origin** passed as named arguments into the instance

          it 'should copy the origin to the instance', ->
            element = new Element origin: (origin = x:10, y:20)
            element.origin.x.should.be.equal 10
            element.origin.y.should.be.equal 20
            element.origin.should.not.be.equal origin

---

## METHODS

        describe '#localizeEventCoordinates(event)', ->
          it 'should localize event coordinates', ->
            element = new Element origin: x:5, y:10
            event = x:10, y:20
            element.localizeEventCoordinates event
            event.localX.should.be.equal 5
            event.localY.should.be.equal 10

---

## LISTENERS

Mousemove capturing listener should store the event in the runtime
and localize the event coordinates.

        describe '#mousemoveCaptureListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mousemoveCaptureListener()
              .should.be.equal element

          it 'should store the event in #___runtime', ->
            (new Element)
              .mousemoveCaptureListener('test')
              .___runtime.mousemoveEvent.should.be.equal 'test'

          it 'should localize the event coordinates', ->
            (new Element origin: x:10, y:20)
              .mousemoveCaptureListener (event = x:15, y:30)
            event.localX.should.be.equal 5
            event.localY.should.be.equal 10

---

Mousedown capturing listener should store the event in the runtime
and localize the event coordinates.

        describe '#mousedownCaptureListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mousedownCaptureListener()
              .should.be.equal element

          it 'should store the event in #___runtime', ->
            (new Element)
              .mousedownCaptureListener('test')
              .___runtime.mousedownEvent.should.be.equal 'test'

          it 'should localize the event coordinates', ->
            (new Element origin: x:10, y:20)
              .mousedownCaptureListener (event = x:15, y:30)
            event.localX.should.be.equal 5
            event.localY.should.be.equal 10

---

Mouseup capturing listener should store the event in the runtime
and localize the event coordinates.

        describe '#mouseupCaptureListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mouseupCaptureListener()
              .should.be.equal element

          it 'should store the event in #___runtime', ->
            (new Element)
              .mouseupCaptureListener('test')
              .___runtime.mouseupEvent.should.be.equal 'test'

          it 'should localize the event coordinates', ->
            (new Element origin: x:10, y:20)
              .mouseupCaptureListener (event = x:15, y:30)
            event.localX.should.be.equal 5
            event.localY.should.be.equal 10

---

Mousemove listener. A stub for descendants to call `super` on.

        describe '#mousemoveListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mousemoveListener()
              .should.be.equal element

---

Mousedown listener. A stub for descendants to call `super` on.

        describe '#mousedownListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mousedownListener()
              .should.be.equal element

---

Mouseup listener. A stub for descendants to call `super` on.

        describe '#mouseupListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mouseupListener()
              .should.be.equal element

[Element#constructor]: ../element.litcoffee#constructor
[Parent]: ./index.litcoffee

# TEST CLASS: Element
* Parent: [Index][Parent]

---

    should = require 'should'
    module.exports = (Element, name='Element') ->

      describe name, ->
        it 'should be a class', -> Element.should.be.a.class

---

## CONSTRUCTOR

        describe '#constructor(args)', ->
          it 'should return an instance of Element', ->
            (new Element).should.be.an.instanceof Element

Constructor should copy the **origin** passed as named arguments into the instance

          it 'should copy the origin to the instance', ->
            element = new Element origin: (origin = x:10, y:20)
            element.origin.x.should.be.equal 10
            element.origin.y.should.be.equal 20
            element.origin.should.not.be.equal origin

---

## METHODS

        describe '#localizeEventCoordinates(event)', ->
          it 'should localize event coordinates', ->
            element = new Element origin: x:5, y:10
            event = x:10, y:20
            element.localizeEventCoordinates event
            event.localX.should.be.equal 5
            event.localY.should.be.equal 10

---

## LISTENERS

Mousemove capturing listener should store the event in the runtime
and localize the event coordinates.

        describe '#mousemoveCaptureListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mousemoveCaptureListener()
              .should.be.equal element

          it 'should store the event in #___runtime', ->
            (new Element)
              .mousemoveCaptureListener('test')
              .___runtime.mousemoveEvent.should.be.equal 'test'

          it 'should localize the event coordinates', ->
            (new Element origin: x:10, y:20)
              .mousemoveCaptureListener (event = x:15, y:30)
            event.localX.should.be.equal 5
            event.localY.should.be.equal 10

---

Mousedown capturing listener should store the event in the runtime
and localize the event coordinates.

        describe '#mousedownCaptureListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mousedownCaptureListener()
              .should.be.equal element

          it 'should store the event in #___runtime', ->
            (new Element)
              .mousedownCaptureListener('test')
              .___runtime.mousedownEvent.should.be.equal 'test'

          it 'should localize the event coordinates', ->
            (new Element origin: x:10, y:20)
              .mousedownCaptureListener (event = x:15, y:30)
            event.localX.should.be.equal 5
            event.localY.should.be.equal 10

---

Mouseup capturing listener should store the event in the runtime
and localize the event coordinates.

        describe '#mouseupCaptureListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mouseupCaptureListener()
              .should.be.equal element

          it 'should store the event in #___runtime', ->
            (new Element)
              .mouseupCaptureListener('test')
              .___runtime.mouseupEvent.should.be.equal 'test'

          it 'should localize the event coordinates', ->
            (new Element origin: x:10, y:20)
              .mouseupCaptureListener (event = x:15, y:30)
            event.localX.should.be.equal 5
            event.localY.should.be.equal 10

---

Mousemove listener. A stub for descendants to call `super` on.

        describe '#mousemoveListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mousemoveCaptureListener()
              .should.be.equal element

---

Mousedown listener. A stub for descendants to call `super` on.

        describe '#mousedownListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mousedownCaptureListener()
              .should.be.equal element

---

Mouseup listener. A stub for descendants to call `super` on.

        describe '#mouseupListener', ->
          it 'should return the element', ->
            (element = new Element)
              .mouseupCaptureListener()
              .should.be.equal element

[Element#constructor]: ../element.litcoffee#constructor
[Parent]: ./index.litcoffee


NativeItem doc XXX -> XYZ

NativeItem doc XXX -> XYZ

# Native

    'use strict'

    utils = require 'src/utils'
    log = require 'src/log'
    assert = require 'src/assert'
    colorUtils = require 'src/renderer/utils/color'

    IS_NATIVE = not utils.isServer and not utils.isBrowser

    if IS_NATIVE
        nativeBridge = require 'src/native'

# **Class** Native : *Item*

    module.exports = (Renderer, Impl, itemUtils) ->

        class Native extends Renderer.Item
            @__name__ = 'Native'
            @__path__ = 'Renderer.Native'

            @New = (component, opts) ->
                item = new @
                itemUtils.Object.initialize item, component, opts
                unless IS_NATIVE
                    item.onParentChange Impl.updateNativeSize
                @Initialize? item
                item

## Native.defineProperty(*Object* config)

Defines new property with the given name.

For each property, signal `onXYZChange` is created,
where `XYZ` is the given name.

`config` parameter must be an object with specified keys:
- `enabled` - whether it's supported on current platform,
- `name` - name of the property,
- `type` - type of predefined condifuration described below,
- `defaultValue`,
- `setter`,
- `getter`,
- `developmentSetter`
- `implementationValue` - function returning value passed to the implementation.

### Predefined types

            PROPERTY_TYPES = Object.create null

#### text

            PROPERTY_TYPES.text = ->
                defaultValue: ''
                developmentSetter: (val) ->
                    assert.isString val

#### number

            PROPERTY_TYPES.number = ->
                defaultValue: 0
                developmentSetter: (val) ->
                    assert.isFloat val

#### boolean

            PROPERTY_TYPES.boolean = ->
                defaultValue: false
                developmentSetter: (val) ->
                    assert.isBoolean val

#### color

            PROPERTY_TYPES.color = (config) ->
                defaultValue: ''
                developmentSetter: (val) ->
                    assert.isString val
                implementationValue: (val) ->
                    if IS_NATIVE
                        colorUtils.toRGBAHex val, config.defaultValue
                    else
                        val

            @defineProperty = (config) ->
                itemName = @__name__
                properties = @_properties ||= []
                config = utils.clone config

                assert.isString itemName, '''
                    NativeItem.__name__ unique name must be specified
                '''
                assert.isObject config, '''
                    NativeItem.defineProperty config parameter must be an object
                '''
                assert.isString config.name, '''
                    NativeItem property name must be a string
                '''
                assert.isNotDefined properties[config.name], """
                    Property #{config.name} is already defined
                """
                assert.isDefined PROPERTY_TYPES[config.type], """
                    Unknown property type #{config.type}
                """ if config.type

                # type
                if typeConfigFunc = PROPERTY_TYPES[config.type]
                    typeConfig = typeConfigFunc(config)
                    for key, val of typeConfig
                        if key not of config
                            config[key] = val

                # constructor
                config.constructor = @

                # internalName
                config.internalName = itemUtils.getPropInternalName config.name

                # implementation
                config.implementation = do ->
                    if config.enabled is false
                        return utils.NOP

                    ctorName = utils.capitalize itemName
                    name = utils.capitalize config.name
                    if IS_NATIVE
                        funcName = "rendererSet#{ctorName}#{name}"
                        (val) ->
                            nativeBridge.callFunction funcName, @_impl.id, val
                    else
                        funcName = "set#{ctorName}#{name}"
                        (val) ->
                            Impl[funcName].call @, val

                # save
                properties.push config

                # create
                itemUtils.defineProperty config

            constructor: ->
                super()

                unless IS_NATIVE
                    @_autoWidth = true
                    @_autoHeight = true
                    @_width = -1
                    @_height = -1

                # save properties with default values
                if properties = @constructor._properties
                    for property in properties
                        @[property.internalName] = property.defaultValue

            unless IS_NATIVE
                _width: -1
                getter = utils.lookupGetter @::, 'width'
                itemWidthSetter = utils.lookupSetter @::, 'width'
                utils.defineProperty @::, 'width', null, getter,
                    do (_super = itemWidthSetter) -> (val) ->
                        if @_autoWidth = val is -1
                            _super.call @, @_contentWidth
                            Impl.updateNativeSize.call @
                        else
                            _super.call @, val
                        return

                _height: -1
                getter = utils.lookupGetter @::, 'height'
                itemHeightSetter = utils.lookupSetter @::, 'height'
                utils.defineProperty @::, 'height', null, getter,
                    do (_super = itemHeightSetter) -> (val) ->
                        if @_autoHeight = val is -1
                            _super.call @, @_contentHeight
                            Impl.updateNativeSize.call @
                        else
                            _super.call @, val
                        return

## Native::set(*String* propName, *Any* val)

            set: (name, val) ->
                assert.isString name

                ctorName = utils.capitalize @constructor.__name__
                id = @_impl.id
                name = utils.capitalize name

                if IS_NATIVE
                    funcName = "rendererSet#{ctorName}#{name}"
                    nativeBridge.callFunction funcName, id, val
                else
                    funcName = "set#{ctorName}#{name}"
                    Impl[funcName].call @, val
                return

## Native::call(*String* funcName, *Any* args...)

            call: (name, args...) ->
                assert.isString name

                ctorName = utils.capitalize @constructor.__name__
                id = @_impl.id
                name = utils.capitalize name

                if IS_NATIVE
                    funcName = "rendererCall#{ctorName}#{name}"
                    callArgs = [funcName, id, args...]
                    nativeBridge.callFunction.apply nativeBridge, callArgs
                else
                    funcName = "call#{ctorName}#{name}"
                    Impl[funcName].apply @, args
                return

## Native::on(*String* eventName, *Function* listener)

            # nativeEventName -> item id -> [item, listeners...]
            eventListeners = Object.create null

            createNativeEventListener = (listeners, eventName) -> (id) ->
                unless itemListeners = listeners[id]
                    log.warn "Got a native event '#{eventName}' for an item which " +
                        "didn't register a listener on this event; check if you " +
                        "properly call 'on()' method with a signal listener"
                    return

                length = arguments.length
                args = new Array length - 1
                for i in [0...length-1] by 1
                    args[i] = arguments[i + 1]

                item = itemListeners[0]
                for i in [1...itemListeners.length] by 1
                    itemListeners[i].apply item, args

                return

            on: (name, func) ->
                assert.isString name
                assert.isFunction func

                name = utils.capitalize name

                if IS_NATIVE
                    ctorName = utils.capitalize @constructor.__name__
                    eventName = "rendererOn#{ctorName}#{name}"

                    unless listeners = eventListeners[eventName]
                        listeners = eventListeners[eventName] = Object.create(null)
                        nativeBridge.on eventName, createNativeEventListener(listeners, eventName)

                    itemListeners = listeners[@_impl.id] ?= [@]
                    itemListeners.push func
                else
                    eventName = "on#{name}"
                    @_impl[eventName].connect func
                return

        Native

# Glossary

- [Native](#class-native)

# Native

    'use strict'

    utils = require 'src/utils'
    log = require 'src/log'
    assert = require 'src/assert'
    colorUtils = require 'src/renderer/utils/color'

    IS_NATIVE = not utils.isServer and not utils.isBrowser

    if IS_NATIVE
        nativeBridge = require 'src/native'

# **Class** Native : *Item*

    module.exports = (Renderer, Impl, itemUtils) ->

        class Native extends Renderer.Item
            @__name__ = 'Native'
            @__path__ = 'Renderer.Native'

            @New = (component, opts) ->
                item = new @
                itemUtils.Object.initialize item, component, opts
                unless IS_NATIVE
                    item.onParentChange Impl.updateNativeSize
                @Initialize? item
                item

## Native.defineProperty(*Object* config)

Defines new property with the given name.

For each property, signal `onXXXChange` is created,
where `XXX` is the given name.

`config` parameter must be an object with specified keys:
- `enabled` - whether it's supported on current platform,
- `name` - name of the property,
- `type` - type of predefined condifuration described below,
- `defaultValue`,
- `setter`,
- `getter`,
- `developmentSetter`
- `implementationValue` - function returning value passed to the implementation.

### Predefined types

            PROPERTY_TYPES = Object.create null

#### text

            PROPERTY_TYPES.text = ->
                defaultValue: ''
                developmentSetter: (val) ->
                    assert.isString val

#### number

            PROPERTY_TYPES.number = ->
                defaultValue: 0
                developmentSetter: (val) ->
                    assert.isFloat val

#### boolean

            PROPERTY_TYPES.boolean = ->
                defaultValue: false
                developmentSetter: (val) ->
                    assert.isBoolean val

#### color

            PROPERTY_TYPES.color = (config) ->
                defaultValue: ''
                developmentSetter: (val) ->
                    assert.isString val
                implementationValue: (val) ->
                    if IS_NATIVE
                        colorUtils.toRGBAHex val, config.defaultValue
                    else
                        val

            @defineProperty = (config) ->
                itemName = @__name__
                properties = @_properties ||= []
                config = utils.clone config

                assert.isString itemName, '''
                    NativeItem.__name__ unique name must be specified
                '''
                assert.isObject config, '''
                    NativeItem.defineProperty config parameter must be an object
                '''
                assert.isString config.name, '''
                    NativeItem property name must be a string
                '''
                assert.isNotDefined properties[config.name], """
                    Property #{config.name} is already defined
                """
                assert.isDefined PROPERTY_TYPES[config.type], """
                    Unknown property type #{config.type}
                """ if config.type

                # type
                if typeConfigFunc = PROPERTY_TYPES[config.type]
                    typeConfig = typeConfigFunc(config)
                    for key, val of typeConfig
                        if key not of config
                            config[key] = val

                # constructor
                config.constructor = @

                # internalName
                config.internalName = itemUtils.getPropInternalName config.name

                # implementation
                config.implementation = do ->
                    if config.enabled is false
                        return utils.NOP

                    ctorName = utils.capitalize itemName
                    name = utils.capitalize config.name
                    if IS_NATIVE
                        funcName = "rendererSet#{ctorName}#{name}"
                        (val) ->
                            nativeBridge.callFunction funcName, @_impl.id, val
                    else
                        funcName = "set#{ctorName}#{name}"
                        (val) ->
                            Impl[funcName].call @, val

                # save
                properties.push config

                # create
                itemUtils.defineProperty config

            constructor: ->
                super()

                unless IS_NATIVE
                    @_autoWidth = true
                    @_autoHeight = true
                    @_width = -1
                    @_height = -1

                # save properties with default values
                if properties = @constructor._properties
                    for property in properties
                        @[property.internalName] = property.defaultValue

            unless IS_NATIVE
                _width: -1
                getter = utils.lookupGetter @::, 'width'
                itemWidthSetter = utils.lookupSetter @::, 'width'
                utils.defineProperty @::, 'width', null, getter,
                    do (_super = itemWidthSetter) -> (val) ->
                        if @_autoWidth = val is -1
                            _super.call @, @_contentWidth
                            Impl.updateNativeSize.call @
                        else
                            _super.call @, val
                        return

                _height: -1
                getter = utils.lookupGetter @::, 'height'
                itemHeightSetter = utils.lookupSetter @::, 'height'
                utils.defineProperty @::, 'height', null, getter,
                    do (_super = itemHeightSetter) -> (val) ->
                        if @_autoHeight = val is -1
                            _super.call @, @_contentHeight
                            Impl.updateNativeSize.call @
                        else
                            _super.call @, val
                        return

## Native::set(*String* propName, *Any* val)

            set: (name, val) ->
                assert.isString name

                ctorName = utils.capitalize @constructor.__name__
                id = @_impl.id
                name = utils.capitalize name

                if IS_NATIVE
                    funcName = "rendererSet#{ctorName}#{name}"
                    nativeBridge.callFunction funcName, id, val
                else
                    funcName = "set#{ctorName}#{name}"
                    Impl[funcName].call @, val
                return

## Native::call(*String* funcName, *Any* args...)

            call: (name, args...) ->
                assert.isString name

                ctorName = utils.capitalize @constructor.__name__
                id = @_impl.id
                name = utils.capitalize name

                if IS_NATIVE
                    funcName = "rendererCall#{ctorName}#{name}"
                    callArgs = [funcName, id, args...]
                    nativeBridge.callFunction.apply nativeBridge, callArgs
                else
                    funcName = "call#{ctorName}#{name}"
                    Impl[funcName].apply @, args
                return

## Native::on(*String* eventName, *Function* listener)

            # nativeEventName -> item id -> [item, listeners...]
            eventListeners = Object.create null

            createNativeEventListener = (listeners, eventName) -> (id) ->
                unless itemListeners = listeners[id]
                    log.warn "Got a native event '#{eventName}' for an item which " +
                        "didn't register a listener on this event; check if you " +
                        "properly call 'on()' method with a signal listener"
                    return

                length = arguments.length
                args = new Array length - 1
                for i in [0...length-1] by 1
                    args[i] = arguments[i + 1]

                item = itemListeners[0]
                for i in [1...itemListeners.length] by 1
                    itemListeners[i].apply item, args

                return

            on: (name, func) ->
                assert.isString name
                assert.isFunction func

                name = utils.capitalize name

                if IS_NATIVE
                    ctorName = utils.capitalize @constructor.__name__
                    eventName = "rendererOn#{ctorName}#{name}"

                    unless listeners = eventListeners[eventName]
                        listeners = eventListeners[eventName] = Object.create(null)
                        nativeBridge.on eventName, createNativeEventListener(listeners, eventName)

                    itemListeners = listeners[@_impl.id] ?= [@]
                    itemListeners.push func
                else
                    eventName = "on#{name}"
                    @_impl[eventName].connect func
                return

        Native

# Glossary

- [Native](#class-native)


fix 'Path must be a string.' bug

fix 'Path must be a string.' bug

    path = require('path')

@.**path_Combine**

    String::path_Combine = (pathToAppend) ->
      if pathToAppend then path.join(@.toString(), pathToAppend) else @.toString()

@.**file_Dir_Name**

twin methods: file_Parent_Folder, parent_Folder

    String::file_Dir_Name  = () ->
      path.dirname @.toString()

    String::file_Parent_Folder = String::file_Dir_Name
    String::parent_Folder      = String::file_Dir_Name

@.**file_Extension**

    String::file_Extension = () ->
      path.extname(@.toString())

@.**file_Name**

    String::file_Name = () ->
      path.basename @.toString()

@.**file_Names**

    Array::file_Names = () ->
      file.file_Name() for file in @

@.**append_To_Process_Cwd_Path**

    String::append_To_Process_Cwd_Path  = () ->
      process.cwd().path_Combine(@.toString())

@.**file_Name_Without_Extension**

    String::file_Name_Without_Extension  = () ->
      path.basename @.toString()
                     .replace(@.toString().file_Extension(), "")

@.**file_Names_Without_Extension**

    Array:: file_Names_Without_Extension  = () ->
      file.file_Name_Without_Extension() for file in @

@.**folder_Name**

Returns the name of the current folder (which is the right-most segment of a path)

If you want the full path, use the **parent_Folder** method

    String::folder_Name = ()->
      @.valueOf().file_Name()

@.**folder_Names**

    Array::folder_Names = Array::file_Names

---
back to [index](index.html)

    path = require('path')

@.**path_Combine**

    String::path_Combine = (pathToAppend) ->
      if pathToAppend then path.join(@.toString(), pathToAppend) else @.toString()

@.**file_Dir_Name**

twin methods: file_Parent_Folder, parent_Folder

    String::file_Dir_Name  = () ->
      path.dirname @

    String::file_Parent_Folder = String::file_Dir_Name
    String::parent_Folder      = String::file_Dir_Name

@.**file_Extension**

    String::file_Extension = () ->
      path.extname(@.toString())

@.**file_Name**

    String::file_Name = () ->
      path.basename @.toString()

@.**file_Names**

    Array::file_Names = () ->
      file.file_Name() for file in @

@.**append_To_Process_Cwd_Path**

    String::append_To_Process_Cwd_Path  = () ->
      process.cwd().path_Combine(@.toString())

@.**file_Name_Without_Extension**

    String::file_Name_Without_Extension  = () ->
      path.basename @.toString()
                     .replace(@.toString().file_Extension(), "")

@.**file_Names_Without_Extension**

    Array:: file_Names_Without_Extension  = () ->
      file.file_Name_Without_Extension() for file in @

@.**folder_Name**

Returns the name of the current folder (which is the right-most segment of a path)

If you want the full path, use the **parent_Folder** method

    String::folder_Name = ()->
      @.valueOf().file_Name()

@.**folder_Names**

    Array::folder_Names = Array::file_Names

---
back to [index](index.html)