feat(docs): Move docs to gh-pages, deploy as part of ci build on darwin

This commit is contained in:
Ben Gotow 2015-09-08 17:10:29 -07:00
parent ec4a0a228f
commit 54eb82d1e6
40 changed files with 1896 additions and 43 deletions

View file

@ -333,6 +333,7 @@ module.exports = (grunt) ->
ciTasks.push('codesign')
ciTasks.push('mkdmg') if process.platform is 'darwin'
ciTasks.push('create-windows-installer') if process.platform is 'win32'
# ciTasks.push('publish-docs') if process.platform is 'darwin'
ciTasks.push('publish-nylas-build') if process.platform is 'darwin'
grunt.registerTask('ci', ciTasks)

View file

@ -52,6 +52,9 @@ module.exports = (grunt) ->
{cp, mkdir, rm} = require('./task-helpers')(grunt)
relativePathForArticle = (filename) ->
filename[0..-4]+'.html'
relativePathForClass = (classname) ->
classname+'.html'
@ -96,6 +99,38 @@ module.exports = (grunt) ->
if _.isObject(val)
processFields(val, fields, tasks)
grunt.registerTask 'publish-docs', 'Publish the API docs to gh-pages', ->
done = @async()
docsOutputDir = grunt.config.get('docsOutputDir')
docsRepoDir = process.env.DOCS_REPO_DIR
if not docsRepoDir
console.log("DOCS_REPO_DIR is not set.")
return done()
exec = (require 'child_process').exec
execAll = (arr, callback) ->
console.log(arr[0])
exec arr[0], {cwd: docsRepoDir}, (err, stdout, stderr) ->
return callback(err) if callback and err
arr.splice(0, 1)
if arr.length > 0
execAll(arr, callback)
else
callback(null)
execAll [
"git fetch"
"git reset --hard origin/gh-pages"
"git clean -Xdf"
], (err) ->
return done(err) if err
cp(docsOutputDir, docsRepoDir)
execAll [
"git commit -am 'Jenkins updating docs'"
"git push --force origin/gh-pages"
], (err) ->
return done(err)
grunt.registerTask 'build-docs', 'Builds the API docs in src', ->
done = @async()
@ -167,8 +202,51 @@ module.exports = (grunt) ->
# Parse Article Markdown
articles = []
articlesPath = path.resolve(__dirname, '..', '..', 'docs')
fs.traverseTreeSync articlesPath, (file) ->
if path.extname(file) is '.md'
{html, meta} = marked(grunt.file.read(file))
filename = path.basename(file)
meta ||= {title: filename}
for key, val of meta
meta[key.toLowerCase()] = val
articles.push({
html: html
meta: meta
name: meta.title
filename: filename
link: relativePathForArticle(filename)
})
# Sort articles by the `Order` flag when present. Lower order, higher in list.
articles.sort (a, b) ->
(a.meta?.order ? 1000)/1 - (b.meta?.order ? 1000)/1
# Build Sidebar metadata we can hand off to each of the templates to
# generate the sidebar
sidebar = {sections: []}
sidebar.sections.push
name: 'Getting Started'
items: articles.filter ({meta}) -> meta.section is 'Getting Started'
sidebar.sections.push
name: 'Guides'
items: articles.filter ({meta}) -> meta.section is 'Guides'
sidebar.sections.push
name: 'Sample Code'
items: [{
name: 'Composer Translation'
link: 'https://github.com/nylas/edgehill-plugins/tree/master/translate'
external: true
},{
name: 'Github Sidebar'
link: 'https://github.com/nylas/edgehill-plugins/tree/master/sidebar-github-profile'
external: true
}]
referenceSections = {}
for klass in classes
@ -187,17 +265,11 @@ module.exports = (grunt) ->
for key, val of referenceSections
sorted.push(val)
api_sidebar_meta = sorted.map ({name, classes}) ->
name: name
items: classes.map ({name}) -> {name: name, link: relativePathForClass(name), slug: name.toLowerCase() }
console.log("Here's the sidebar info:")
console.log(api_sidebar_meta.toString())
docsOutputDir = grunt.config.get('docsOutputDir')
sidebarJson = JSON.stringify(api_sidebar_meta, null, 2)
sidebarPath = path.join(docsOutputDir, '_sidebar.json')
grunt.file.write(sidebarPath, sidebarJson)
sidebar.sections.push
name: 'API Reference'
items: sorted.map ({name, classes}) ->
name: name
items: classes.map ({name}) -> {name: name, link: relativePathForClass(name) }
# Prepare to render by loading handlebars partials
@ -212,6 +284,47 @@ module.exports = (grunt) ->
for classname, val of apiJSON.classes
knownClassnames[classname.toLowerCase()] = val
knownArticles = {}
for article in articles
knownArticles[article.filename.toLowerCase()] = article
expandTypeReferences = (val) ->
refRegex = /{([\w.]*)}/g
while (match = refRegex.exec(val)) isnt null
term = match[1].toLowerCase()
label = match[1]
url = false
if term in standardClasses
url = standardClassURLRoot+term
else if thirdPartyClasses[term]
url = thirdPartyClasses[term]
else if knownClassnames[term]
url = relativePathForClass(term)
else if knownArticles[term]
label = knownArticles[term].meta.title
url = relativePathForArticle(knownArticles[term].filename)
else
console.warn("Cannot find class named #{term}")
if url
val = val.replace(match[0], "<a href='#{url}'>#{label}</a>")
val
expandFuncReferences = (val) ->
refRegex = /{([\w]*)?::([\w]*)}/g
while (match = refRegex.exec(val)) isnt null
[text, a, b] = match
url = false
if a and b
url = "#{relativePathForClass(a)}##{b}"
label = "#{a}::#{b}"
else
url = "##{b}"
label = "#{b}"
if url
val = val.replace(text, "<a href='#{url}'>#{label}</a>")
val
# Render Class Pages
classTemplatePath = path.join(templatesPath, 'class.html')
@ -220,9 +333,28 @@ module.exports = (grunt) ->
for {name, documentation, section} in classes
# Recursively process `description` and `type` fields to process markdown,
# expand references to types, functions and other files.
processFields(documentation, ['description'], [marked.noMeta])
processFields(documentation, ['type'], [])
processFields(documentation, ['description'], [marked.noMeta, expandTypeReferences, expandFuncReferences])
processFields(documentation, ['type'], [expandTypeReferences])
result = classTemplate({name, documentation, section})
console.log(outputPathFor(relativePathForClass(name)))
result = classTemplate({name, documentation, section, sidebar})
grunt.file.write(outputPathFor(relativePathForClass(name)), result)
# Render Article Pages
articleTemplatePath = path.join(templatesPath, 'article.html')
articleTemplate = Handlebars.compile(grunt.file.read(articleTemplatePath))
for {name, meta, html, filename} in articles
# Process the article content to expand references to types, functions
for task in [expandTypeReferences, expandFuncReferences]
html = task(html)
result = articleTemplate({name, meta, html, sidebar})
grunt.file.write(outputPathFor(relativePathForArticle(filename)), result)
# Copy styles and images
imagesPath = path.resolve(__dirname, '..', '..', 'docs', 'images')
cssPath = path.resolve(__dirname, '..', '..', 'docs', 'css')
cp imagesPath, path.join(docsOutputDir, "images")
cp cssPath, path.join(docsOutputDir, "css")

View file

@ -0,0 +1,11 @@
</div>
<div id="footer">
<div class="container">
<img src="images/edgehill.png" class="logo" />
<div class="small">Nylas Mail Developer Preview<br><em>© 2014-2015 Nylas, Inc.</em></div>
</div>
</div>
</body>
</html>

View file

@ -0,0 +1,17 @@
<html>
<head>
<meta charset="utf-8">
<title>Nylas Mail — {{name}}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<link rel="stylesheet" type="text/css" href="css/tomorrow.css">
</head>
<body>
<div id="header">
<div class="container">
<img src="images/edgehill.png" class="logo" />
<div class="title">Nylas Mail<div class="small">Developer Preview</div></div>
</div>
</div>
<div class="container">

View file

@ -0,0 +1,3 @@
{{#each sidebar.sections}}
{{>_sidebarSection}}
{{/each}}

View file

@ -0,0 +1,10 @@
<div class="heading">{{name}}</div>
<ul>
{{#each items}}
{{#if items}}
{{> _sidebarSection}}
{{else}}
<li><a href="{{link}}" {{#if external}}target="_blank"{{/if}}>{{name}}</a></li>
{{/if}}
{{/each}}
</ul>

View file

@ -0,0 +1,15 @@
{{>_header}}
{{#if meta.TitleHidden}}
{{else}}
<div class="page-title">{{meta.title}}</div>
{{/if}}
<div id="sidebar">
{{>_sidebar}}
</div>
<div id="main" class="article">
{{{html}}}
</div>
{{>_footer}}

View file

@ -1,3 +1,5 @@
{{>_header}}
<div class="page-title">
{{name}}
{{#if documentation.superClass}}
@ -5,44 +7,51 @@
{{/if}}
</div>
<h2>Summary</h2>
<div class="markdown-from-sourecode">
<p>{{{documentation.description}}}</p>
<div id="sidebar">
{{>_sidebar}}
</div>
<ul>
{{#each documentation.sections}}
<li><a href="#{{name}}">{{name}}</a></li>
{{/each}}
</ul>
<div id="main">
<h2>Summary</h2>
<div class="markdown-from-sourecode">
<p>{{{documentation.description}}}</p>
</div>
<ul>
{{#each documentation.sections}}
<li><a href="#{{name}}">{{name}}</a></li>
{{/each}}
</ul>
{{#if documentation.classProperties.length}}
<h3>Class Properties</h3>
{{#if documentation.classProperties.length}}
<h3>Class Properties</h3>
{{#each documentation.classProperties}}
{{>_property}}
{{/each}}
{{#each documentation.classProperties}}
{{>_property}}
{{/each}}
{{/if}}
{{/if}}
{{#if documentation.classMethods.length}}
<h3>Class Methods</h3>
{{#if documentation.classMethods.length}}
<h3>Class Methods</h3>
{{#each documentation.classMethods}}
{{>_function}}
{{/each}}
{{#each documentation.classMethods}}
{{>_function}}
{{/each}}
{{/if}}
{{/if}}
{{#if documentation.instanceMethods.length}}
<h3>Instance Methods</h3>
{{#if documentation.instanceMethods.length}}
<h3>Instance Methods</h3>
{{#each documentation.instanceMethods}}
{{>_function}}
{{/each}}
{{#each documentation.instanceMethods}}
{{>_function}}
{{/each}}
{{/if}}
{{/if}}
</div>
{{>_footer}}

35
docs/Architecture.md Normal file
View file

@ -0,0 +1,35 @@
---
Title: Application Architecture
Section: Guides
Order: 3
---
Nylas Mail uses [Reflux](https://github.com/spoike/refluxjs), a slim implementation of Facebook's [Flux Application Architecture](https://facebook.github.io/flux/) to coordinate the movement of data through the application. Flux is extremely well suited for applications that support third-party extension because it emphasizes loose coupling and well defined interfaces between components. It enforces:
- **Uni-directional data flow**
- **Loose coupling between components**
For more information about the Flux pattern, check out [this diagram](https://facebook.github.io/flux/docs/overview.html#structure-and-data-flow). For a bit more insight into why we chose Reflux over other Flux implementations, there's a great [blog post](http://spoike.ghost.io/deconstructing-reactjss-flux/) by the author of Reflux.
There are several core stores in the application:
- **{NamespaceStore}**: When the user signs in to Nylas Mail, their auth token provides one or more namespaces. The NamespaceStore manages the available Namespaces, exposes the current Namespace, and allows you to observe changes to the current namespace.
- **{TaskQueue}**: Manages Tasks, operations queued for processing on the backend. Task objects represent individual API actions and are persisted to disk, ensuring that they are performed eventually. Each Task may depend on other tasks, and Tasks are executed in order.
- **{DatabaseStore}**: The {DatabaseStore} marshalls data in and out of the local cache, and exposes an ActiveRecord-style query interface. You can observe the DatabaseStore to monitor the state of data in Nylas Mail.
- **{DraftStore}**: Manages Drafts, which are {Message} objects the user is authoring. Drafts present a unique case in Nylas Mail because they may be updated frequently by disconnected parts of the application. You should use the {DraftStore} to create, edit, and send drafts.
- **{FocusedContentStore}**: Manages focus within the main applciation window. The {FocusedContentStore} allows you to query and monitor changes to the selected thread, tag, file, etc.
Most packages declare additional stores that subscribe to these Stores, as well as user Actions, and vend data to the package's React components.
###Actions
In Flux applications, views fire {Actions}, which anyone in the application can subscribe to. Typically, `Stores` listen to actions to perform business logic and trigger updates to their corresponding views. For example, when you click "Compose" in the top left corner of Nylas Mail, the React component for the button fires {Actions::composeNewBlankDraft}. The {DraftStore} listens to this action and opens a new composer window.
This approach means that your packages can fire existing {Actions}, like {Actions::composeNewBlankDraft}, or observe actions to add functionality. (For example, we have an Analytics package that also listens for {Actions::composeNewBlankDraft} and counts how many times it's been fired.) You can also define your own actions for use within your package.
For a complete list of available actions, see {Actions}.

171
docs/Database.md Normal file
View file

@ -0,0 +1,171 @@
---
Title: Accessing the Database
Section: Guides
Order: 5
---
Nylas Mail is built on top of a custom database layer modeled after ActiveRecord. For many parts of the application, the database is the source of truth. Data is retrieved from the API, written to the database, and changes to the database trigger Stores and components to refresh their contents. The illustration below shows this flow of data:
<img src="./images/database-flow.png">
The Database connection is managed by the {DatabaseStore}, a singleton object that exists in every window. All Database requests are asynchronous. Queries are forwarded to the application's `Browser` process via IPC and run in SQLite.
## Declaring Models
In Nylas Mail, Models are thin wrappers around data with a particular schema. Each {Model} class declares a set of attributes that define the object's data. For example:
```coffee
class Example extends Model
@attributes:
'id': Attributes.String
queryable: true
modelKey: 'id'
'object': Attributes.String
modelKey: 'object'
'namespaceId': Attributes.String
queryable: true
modelKey: 'namespaceId'
jsonKey: 'namespace_id'
'body': Attributes.JoinedData
modelTable: 'MessageBody'
modelKey: 'body'
'files': Attributes.Collection
modelKey: 'files'
itemClass: File
'unread': Attributes.Boolean
queryable: true
modelKey: 'unread'
```
When models are inflated from JSON using `fromJSON` or converted to JSON using `toJSON`, only the attributes declared on the model are copied. The `modelKey` and `jsonKey` options allow you to specify where a particular key should be found. Attributes are also coerced to the proper types: String attributes will always be strings, Boolean attributes will always be `true` or `false`, etc. `null` is a valid value for all types.
The {DatabaseStore} automatically maintains cache tables for storing Model objects. By default, models are stored in the cache as JSON blobs and basic attributes are not queryable. When the `queryable` option is specified on an attribute, it is given a separate column and index in the SQLite table for the model, and you can construct queries using the attribute:
```coffee
Thread.attributes.namespaceId.equals("123")
// where namespace_id = '123'
Thread.attributes.lastMessageTimestamp.greaterThan(123)
// where last_message_timestamp > 123
Thread.attributes.lastMessageTimestamp.descending()
// order by last_message_timestamp DESC
```
## Retrieving Models
You can make queries for models stored in SQLite using a {Promise}-based ActiveRecord-style syntax. There is no way to make raw SQL queries against the local data store.
```coffee
DatabaseStore.find(Thread, '123').then (thread) ->
# thread is a thread object
DatabaseStore.findBy(Thread, {subject: 'Hello World'}).then (thread) ->
# find a single thread by subject
DatabaseStore.findAll(Thread).where([Thread.attributes.tags.contains('inbox')]).then (threads) ->
# find threads with the inbox tag
DatabaseStore.count(Thread).where([Thread.attributes.lastMessageTimestamp.greaterThan(120315123)]).then (results) ->
# count threads where last message received since 120315123.
```
## Retrieving Pages of Models
If you need to paginate through a view of data, you should use a `DatabaseView`. Database views can be configured with a sort order and a set of where clauses. After the view is configured, it maintains a cache of models in memory in a highly efficient manner and makes it easy to implement pagination. `DatabaseView` also performs deep inspection of it's cache when models are changed and can avoid costly SQL queries.
## Saving and Updating Models
The {DatabaseStore} exposes two methods for creating and updating models: `persistModel` and `persistModels`. When you call `persistModel`, queries are automatically executed to update the object in the cache and the {DatabaseStore} triggers, broadcasting an update to the rest of the application so that views dependent on these kind of models can refresh.
When possible, you should accumulate the objects you want to save and call `persistModels`. The {DatabaseStore} will generate batch insert statements, and a single notification will be broadcast throughout the application. Since saving objects can result in objects being re-fetched by many stores and components, you should be mindful of database insertions.
## Saving Drafts
Drafts in Nylas Mail presented us with a unique challenge. The same draft may be edited rapidly by unrelated parts of the application, causing race scenarios. (For example, when the user is typing and attachments finish uploading at the same time.) This problem could be solved by object locking, but we chose to marshall draft changes through a central DraftStore that debounces database queries and adds other helpful features. See the {DraftStore} documentation for more information.
## Removing Models
The {DatabaseStore} exposes a single method, `unpersistModel`, that allows you to purge an object from the cache. You cannot remove a model by ID alone - you must load it first.
####Advanced Model Attributes
## Attribute.JoinedData
Joined Data attributes allow you to store certain attributes of an object in a separate table in the database. We use this attribute type for Message bodies. Storing message bodies, which can be very large, in a separate table allows us to make queries on message metadata extremely fast, and inflate Message objects without their bodies to build the thread list.
When building a {ModelQuery} on a model with a {JoinedDataAttribute}, you need to call `include` to explicitly load the joined data attribute. The query builder will automatically perform a `LEFT OUTER JOIN` with the secondary table to retrieve the attribute:
```coffee
DatabaseStore.find(Message, '123').then (message) ->
// message.body is undefined
DatabaseStore.find(Message, '123').include(Message.attributes.body).then (message) ->
// message.body is defined
```
When you call `persistModel`, JoinedData attributes are automatically written to the secondary table.
JoinedData attributes cannot be `queryable`.
## Attribute.Collection
Collection attributes provide basic support for one-to-many relationships. For example, {Thread}s in Nylas Mail have a collection of {Tag}s.
When Collection attributes are marked as `queryable`, the {DatabaseStore} automatically creates a join table and maintains it as you create, save, and delete models. When you call `persistModel`, entries are added to the join table associating the ID of the model with the IDs of models in the collection.
Collection attributes have an additional clause builder, `contains`:
```coffee
DatabaseStore.findAll(Thread).where([Thread.attributes.tags.contains('inbox')])
```
This is equivalent to writing the following SQL:
```sql
SELECT `Thread`.`data` FROM `Thread` INNER JOIN `Thread-Tag` AS `M1` ON `M1`.`id` = `Thread`.`id` WHERE `M1`.`value` = 'inbox' ORDER BY `Thread`.`last_message_timestamp` DESC
```
#### Listening for Changes
For many parts of the application, the Database is the source of truth. Funneling changes through the database ensures that they are available to the entire application. Basing your packages on the Database, and listening to it for changes, ensures that your views never fall out of sync.
Within Reflux Stores, you can listen to the {DatabaseStore} using the `listenTo` helper method:
```coffee
@listenTo(DatabaseStore, @_onDataChanged)
```
Within generic code, you can listen to the {DatabaseStore} using this syntax:
```coffee
@unlisten = DatabaseStore.listen(@_onDataChanged, @)
```
When a model is persisted or unpersisted from the database, your listener method will fire. It's very important to inspect the change payload before making queries to refresh your data. The change payload is a simple object with the following keys:
```
{
"objectClass": // string: the name of the class that was changed. ie: "Thread"
"objects": // array: the objects that were persisted or removed
}
```
## But why can't I...?
Nylas Mail exposes a minimal Database API that exposes high-level methods for saving and retrieving objects. The API was designed with several goals in mind, which will help us create a healthy ecosystem of third-party packages:
- Package code should not be tightly coupled to SQLite
- Queries should be composed in a way that makes invalid queries impossible
- All changes to the local database must be observable

46
docs/Debugging.md Normal file
View file

@ -0,0 +1,46 @@
---
Title: Debugging N1
Section: Guides
Order: 4
---
### Chromium DevTools
Nylas Mail is built on top of Electron, which runs the latest version of Chromium (at the time of writing, Chromium 43). You can access the standard [Chrome DevTools](https://developer.chrome.com/devtools) using the `Command-Option-I` (`Ctrl-Shift-I` on Windows/Linux) keyboard shortcut, including the Debugger, Profiler, and Console. You can find extensive information about the Chromium DevTools on [developer.chrome.com](https://developer.chrome.com/devtools).
Here are a few hidden tricks for getting the most out of the Chromium DevTools:
- You can use `Command-P` to "Open Quickly", jumping to a particular source file from any tab.
- You can set breakpoints by clicking the line number gutter while viewing a source file.
- While on a breakpoint, you can toggle the console panel by pressing `Esc` and type commands which are executed in the current scope.
- While viewing the DOM in the `Elements` panel, typing `$0` on the console refers to the currently selected DOM node.
### Nylas Developer Panel
If you choose `Developer > Relaunch with Debug Flags...` from the menu, you can enable the Nylas Developer Panel at the bottom of the main window.
The Developer Panel provides three views which you can click to activate:
- `Tasks`: This view allows you to inspect the {TaskQueue} and see the what tasks are pending and complete. Click a task to see its JSON representation and inspect it's values, including the last error it encountered.
- `Delta Stream`: This view allows you to see the streaming updates from the Nylas API that the app has received. You can click individual updates to see the exact JSON that was consumed by the app, and search in the lower left for updates pertaining to an object ID or type.
- `Requests`: This view shows the requests the app has made to the Nylas API in `curl`-equivalent form. (The app does not actually make `curl` requests). You can click "Copy" to copy a `curl` command to the clipboard, or "Run" to execute it in a new Terminal window.
The Developer Panel also allows you to toggle "View Component Regions". Turning on component regions adds a red border to areas of the app that render dynamically injected components, and shows the props passed to React components in each one. See {react} for more information.
### The Development Workflow
If you're debugging a package, you'll be modifying your code and re-running Nylas Mail over and over again. There are a few things you can do to make this development workflow less time consuming:
- **Inline Changes**: Using the Chromium DevTools, you can change the contents of your coffeescript and javascript source files, type `Command-S` to save, and hot-swap the code. This makes it easy to test small adjustments to your code without re-launching Nylas Mail.
- **View > Refresh**: From the View menu, choose "Refresh" to reload the Nylas Mail window just like a page in your browser. Refreshing is faster than restarting the app and allows you to iterate more quickly.
> Note: A bug in Electron causes the Chromium DevTools to become detatched if you refresh the app often. If you find that Chromium is not stopping at your breakpoints, quit Nylas Mail and re-launch it.
In the future, we'll support much richer hot-reloading of plugin components and code. Stay tuned!

View file

@ -0,0 +1,45 @@
---
Title: Extending the Composer
Section: Guides
Order: 6
---
The composer lies at the heart of Nylas Mail, and many improvements to the mail experience require deep integration with the composer. To enable these sort of plugins, the {DraftStore} exposes an extension API.
This API allows your package to:
- Display warning messages before a draft is sent. (ie: "Are you sure you want to send this without attaching a file?")
- Intercept keyboard and mouse events to the composer's text editor.
- Transform the draft and make additional changes before it is sent.
To create your own composer extensions, subclass {DraftStoreExtension} and override the methods your extension needs.
In the sample packages repository, [templates]() is an example of a package which uses a DraftStoreExtension to enhance the composer experience.
### Example
This extension displays a warning before sending a draft that contains the names of competitors' products. If the user proceeds to send the draft containing the words, it appends a disclaimer.
```coffee
{DraftStoreExtension} = require 'nylas-exports'
class ProductsExtension extends DraftStoreExtension
@warningsForSending: (draft) ->
words = ['acme', 'anvil', 'tunnel', 'rocket', 'dynamite']
body = draft.body.toLowercase()
for word in words
if body.indexOf(word) > 0
return ["with the word '#{word}'?"]
return []
@finalizeSessionBeforeSending: (session) ->
draft = session.draft()
if @warningsForSending(draft)
bodyWithWarning = draft.body += "<br>This email \
contains competitor's product names \
or trademarks used in context."
session.changes.add(body: bodyWithWarning)
```

29
docs/FAQ.md Normal file
View file

@ -0,0 +1,29 @@
---
Title: FAQ
Section: Guides
Order: 10
---
### Do I have to use React?
The short answer is yes, you need to use React. The {ComponentRegistry} expects React components, so you'll need to create them to extend the Nylas Mail interface.
However, if you have significant code already written in another framework, like Angular or Backbone, it's possible to attach your application to a React component. See [https://github.com/davidchang/ngReact/issues/80](https://github.com/davidchang/ngReact/issues/80).
### Can I write a package that does X?
If you don't find documentation for the part of Nylas Mail you want to extend, let us know! We're constantly working to enable new workflows by making more of the application extensible.
### Can I distribute my package?
Yes! We'll be sharing more information about publishing packages in the coming months. However, you can already publish and share packages by following the steps below:
1. Create a Github repository for your package, and publish a `Tag` to the repository matching the version number in your `package.json` file. (Ex: `0.1.0`)
2. Make the CURL request below to the package manager server to register your package:
curl -H "Content-Type:application/json" -X POST -d '{"repository":"https://github.com/<username>/<repo>"}' https://edgehill-packages.nylas.com/api/packages
3. Your package will now appear when users visit the Nylas Mail settings page and search for community packages.
Note: In the near future, we'll be formalizing the process of distributing packages, and packages you publish now may need to be resubmitted.

337
docs/First steps.md Normal file
View file

@ -0,0 +1,337 @@
---
Title: First Steps
TitleHidden: True
Section: Getting Started
Order: 2
---
<div class="row">
<div class="col-md-12">
<h2>Start building on top of Nylas in minutes:</h2>
<h3 class="first padded"><div class="number">1</div> Install Nylas Mail</h3>
<p>Download and install Nylas for <span id="platforms"></span>. Open it and sign in to your email account.</p>
</div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="second padded"><div class="number">2</div> Start a Package</h3>
<p>Packages lie at the heart of Nylas Mail. The thread list, composer and other core parts of the app are packages bundled with the app, and you have access to the same set of APIs. From the Developer Menu, choose <span class="instruction-literal">Create a Package...</span> and name your new package.</p>
</div>
<div class="col-md-4">
<img src="/static/img/Step2-Menu@2x.png" width="203" height="194" style="margin-top:88px;"/>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3 class="third padded"><div class="number">3</div> See it in Action</h3>
<p>Your new package comes with some basic code that adds a section to the message sidebar, and it's already enabled! View a message to see it in action. If you make changes to the source, choose <span class="instruction-literal">View > Refresh</span> to see your changes in Nylas Mail.</p>
</div>
</div>
<hr/>
<div class="row">
<div class="col-md-12">
<h2 class="continue"><a href="getting-started-2">Step 2: Build your first package</a></h2>
</div>
</div>
<hr />
<div class="row">
<div class="col-md-6" style="padding-right:30px;">
<h4><div class="letter">A</div> Explore the source</h4>
<img src="/static/img/Illu-ExploreTheSource@2x.png" width="121" height="96" style="margin:auto; margin-bottom:35px; display:block;"/>
<p>Nylas is built on the modern web - packages are written in Coffeescript or Javascript. Packages are a lot like node modules, with their own source, assets, and tests. Check out yours in <span class="instruction-literal">~/.nylas/dev/packages</span>.</p>
</div>
<div class="col-md-6" style="padding-left:30px;">
<h4><div class="letter">B</div> Run the specs</h4>
<img src="/static/img/illu-RunTheSpecs@2x.png" width="139" height="96" style="margin:auto; margin-bottom:35px; display:block;"/>
<p>In Nylas Mail, select <span class="instruction-literal">Developer > Run Package Specs...</span> from the menu to run your package's new specs. Nylas and its packages use the Jasmine testing framework.</p>
</div>
</div>
<script>
var platforms = document.getElementById('platforms');
var mac = '<a href="https://edgehill.nylas.com/download?platform=darwin">Mac OS X</a>'
var windows = '<a href="https://edgehill.nylas.com/download?platform=win32">Windows</a>'
var linux = '<a href="https://edgehill.nylas.com/download?platform=linux">Linux</a>'
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
if (OSName == 'MacOS') {
platforms.innerHTML = mac + " (or "+windows+", "+linux+")";
} else if (OSName == 'Windows') {
platforms.innerHTML = windows + " (or "+mac+", "+linux+")";
} else if (OSName == 'Linux') {
platforms.innerHTML = linux + " (or "+mac+", "+windows+")";
} else {
platforms.innerHTML = mac + ", "+windows+", or "+linux;
}
</script>
<h2 class="gsg-header">Step 2: Building your first package</h2>
If you followed the [first part](getting-started) of our Getting Started Guide, you should have a brand new package just waiting to be explored.
This sample package simply adds the name of the currently focused contact to the sidebar:
<img class="gsg-center" src="images/sidebar-example.png"/>
We're going to build on this to show the sender's [Gravatar](http://gravatar.com) image in the sidebar, instead of just their name. You can check out the full code for the package [in the sample packages repository](https://github.com/nylas/edgehill-plugins/tree/master/sidebar-gravatar).
Find the package source in `~/.nylas/dev/packages` and open the contents in your favorite text editor.
> We use [CJSX](https://github.com/jsdf/coffee-react), a [CoffeeScript](http://coffeescript.org/) syntax for [JSX](https://facebook.github.io/react/docs/jsx-in-depth.html), to streamline our package code.
For syntax highlighting, we recommend [Babel](https://github.com/babel/babel-sublime) for Sublime, or the [CJSX Language](https://atom.io/packages/language-cjsx) Atom package.
### Changing the data
Let's poke around and change what the sidebar displays.
You'll find the code responsible for the sidebar in `lib/my-message-sidebar.cjsx`. Take a look at the `render` method -- this generates the content which appears in the sidebar.
(How does it get in the sidebar? See [Interface Concepts](interfaceconcepts) and look at `main.cjsx` for clues. We'll dive into this more later in the guide.)
We can change the sidebar to display the contact's email address as well. Check out the [Contact attributes](reference/contact) and change the `_renderContent` method to display more information:
```coffee
_renderContent: =>
<div className="header">
<h1>Hi, {@state.contact.name} ({@state.contact.email})!</h1>
</div>
```
After making changes to the package, reload Nylas Mail by going to `View > Reload`.
### Installing a dependency
Now we've figured out how to show the contact's email address, we can use that to generate the [Gravatar](http://gravatar.com) for the contact. However, as per the [Gravatar documentation](https://en.gravatar.com/site/implement/images/), we need to be able to calculate the MD5 hash for an email address first.
Let's install the `md5` package and save it as a dependency in our `package.json`:
```bash
$ npm install md5 --save
```
Installing other dependencies works the same way.
Now, add the `md5` requirement in `my-message-sidebar.cjsx` and update the `_renderContent` method to show the md5 hash:
```coffee
md5 = require 'md5'
class MyMessageSidebar extends React.Component
@displayName: 'MyMessageSidebar'
...
_renderContent =>
<div className="header">
{md5(@state.contact.email)}
</div>
```
> JSX Tip: The `{..}` syntax is used for JavaScript expressions inside HTML elements. [Learn more](https://facebook.github.io/react/docs/jsx-in-depth.html)
You should see the MD5 hash appear in the sidebar (after you reload Nylas Mail):
<img class="gsg-center" src="images/sidebar-md5.png"/>
### Let's Render!
Turning the MD5 hash into a Gravatar image is simple. We need to add an `<img>` tag to the rendered HTML:
```coffee
_renderContent =>
<div className="header">
<img src={'http://www.gravatar.com/avatar/' + md5(@state.contact.email)}/>
</div>
```
Now the Gravatar image associated with the currently focused contact appears in the sidebar. If there's no image available, the Gravatar default will show; you can [add parameters to your image tag](https://en.gravatar.com/site/implement/images/) to change the default behavior.
<img class="gsg-center" src="images/sidebar-gravatar.png"/>
### Styling
Adding styles to our Gravatar image is a matter of editing `stylesheets/main.less` and applying the class to our `img` tag. Let's make it round:
<div class="filename">stylesheets/main.less</div>
```css
.gravatar {
border-radius: 45px;
border: 2px solid #ccc;
}
```
<div class="filename">lib/my-message-sidebar.cjsx</div>
```coffee
_renderContent =>
gravatar = "http://www.gravatar.com/avatar/" + md5(@state.contact.email)
<div className="header">
<img src={gravatar} className="gravatar"/>
</div>
```
> React Tip: Remember to use DOM property names, i.e. `className` instead of `class`.
You'll see these styles reflected in your sidebar.
<img class="gsg-center" src="images/sidebar-style.png"/>
If you're a fan of using the Chrome Developer Tools to tinker with styles, no fear; they work in Nylas Mail, too. Open them by going to `Developer > Toggle Developer Tools`. You'll also find them helpful for debugging in the event that your package isn't behaving as expected.
<hr/>
<h2 class="continue"><a href="getting-started-3">Continue this guide: adding a data store to your package</a></h2>
<hr/>
<h2 class="gsg-header">Step 3: Adding a Data Store</h2>
Building on the [previous part](getting-started-2) of our Getting Started guide, we're going to introduce a data store to give our sidebar superpowers.
## Stores and Data Flow
The Nylas data model revolves around a central `DatabaseStore` and lightweight `Models` that represent data with a particular schema. This works a lot like ActiveRecord, SQLAlchemy and other "smart model" ORMs. See the [Database](database) explanation for more details.
Using the [Flux pattern](https://facebook.github.io/flux/docs/overview.html#structure-and-data-flow) for data flow means that we set up our UI components to 'listen' to specific data stores. When those stores change, we update the state inside our component, and re-render the view.
We've already used this (without realizing) in the [Gravatar sidebar example](getting-started-2):
```coffee
componentDidMount: =>
@unsubscribe = FocusedContactsStore.listen(@_onChange)
...
_onChange: =>
@setState(@_getStateFromStores())
_getStateFromStores: =>
contact: FocusedContactsStore.focusedContact()
```
In this case, the sidebar listens to the `FocusedContactsStore`, which updates when the person selected in the conversation changes. This triggers the `_onChange` method which updates the component state; this causes React to render the view with the new state.
To add more depth to our sidebar package, we need to:
* Create our own data store which will listen to `FocusedContactsStore`
* Extend our data store to do additional things with the contact data
* Update our sidebar to listen to, and display data from, the new store.
In this guide, we'll fetch the GitHub profile for the currently focused contact and display a link to it, using the [GitHub API](https://developer.github.com/v3/search/).
## Creating the Store
The boilerplate to create a new store which listens to `FocusedContactsStore` looks like this:
<div class="filename">lib/github-user-store.coffee</div>
```coffee
Reflux = require 'reflux'
{FocusedContactsStore} = require 'nylas-exports'
module.exports =
GithubUserStore = Reflux.createStore
init: ->
@listenTo FocusedContactsStore, @_onFocusedContactChanged
_onFocusedContactChanged: ->
# TBD - This is fired when the focused contact changes
@trigger(@)
```
(Note: You'll need to set up the `reflux` dependency.)
You should be able to drop this store into the sidebar example's `componentDidMount` method -- all it does is listen for the `FocusedContactsStore` to change, and then `trigger` its own event.
Let's build this out to retrieve some new data based on the focused contact, and expose it via a UI component.
## Getting Data In
We'll expand the `_onFocusedContactChanged` method to do something when the focused contact changes. In this case, we'll see if there's a GitHub profile for that user, and display some information if there is.
```coffee
request = require 'request'
GithubUserStore = Reflux.createStore
init: ->
@_profile = null
@listenTo FocusedContactsStore, @_onFocusedContactChanged
getProfile: ->
@_profile
_onFocusedContactChanged: ->
# Get the newly focused contact
contact = FocusedContactsStore.focusedContact()
# Clear the profile we're currently showing
@_profile = null
if contact
@_fetchGithubProfile(contact.email)
@trigger(@)
_fetchGithubProfile: (email) ->
@_makeRequest "https://api.github.com/search/users?q=#{email}", (err, resp, data) =>
console.warn(data.message) if data.message?
# Make sure we actually got something back
github = data?.items?[0] ? false
if github
@_profile = github
console.log(github)
@trigger(@)
_makeRequest: (url, callback) ->
# GitHub needs a User-Agent header. Also, parse responses as JSON.
request({url: url, headers: {'User-Agent': 'request'}, json: true}, callback)
```
The `console.log` line should show the GitHub profile for a contact (if they have one!) inside the Developer Tools Console, which you can enable at `Developer > Toggle Developer Tools`.
You may run into rate-limiting issues with the GitHub API; to avoid these, you can add [authentication](https://developer.github.com/v3/#authentication) with a [pre-baked token](https://github.com/settings/tokens) by modifying the HTTP request your store makes. **Caution! Use this for local development only.** You could also try implementing a simple cache to avoid making the same request multiple times.
## Display Time
To display this new data in the sidebar, we need to make sure our component is listening to the store, and load the appropriate state when it changes.
```coffee
class GithubSidebar extends React.Component
...
componentDidMount: =>
@unsubscribe = GithubUserStore.listen(@_onChange)
_onChange: =>
@setState(@_getStateFromStores())
_getStateFromStores: =>
github: GithubUserStore.getProfile()
```
Now we can access `@state.github` (which is the GitHub user profile object), and display the information it contains by updating the `render` and `renderContent` methods.
For example:
```coffee
_renderContent: =>
<img className="github" src={@state.github.avatar_url}/> <a href={@state.github.html_url}>GitHub</a>
```
## Extending The Store
To make this package more compelling, we can extend the store to make further API requests and fetch more data about the user. Passing this data back to the UI component follows exactly the same pattern as the barebones data shown above, so we'll leave it as an exercise for the reader. :)
> You can find a more extensive version of this example in our [sample packages repository](https://github.com/nylas/edgehill-plugins/tree/master/sidebar-github-profile).

68
docs/Index.md Normal file
View file

@ -0,0 +1,68 @@
---
Title: Welcome
TitleHidden: true
Section: Getting Started
Order: 1
---
<img src="images/edgehill.png" class="center-logo"/>
<h2 style="text-align:center;">Nylas Package API</h2>
<p style="text-align:center; margin:auto; margin-bottom:60px;">
The Nylas Package API allows you to create powerful extensions to Nylas Mail. The client is built on top of Atom Shell and runs on Mac OS X, Windows, and Linux. It exposes rich APIs for working with the mail, contacts, and calendar and a robust local cache layer. Your packages can leverage NodeJS and other web technologies to create innovative new experiences.
</p>
<table class="no-border">
<tr><td style="width:50%;">
<h4>Installing Nylas Mail</h4>
<p>
Nylas Mail is available for Mac, Windows, and Linux. Download the latest build for your platform below:
</p>
<ul>
<li><a href="https://edgehill.nylas.com/download?platform=darwin">Mac OS X</a></li>
<li><a href="https://edgehill.nylas.com/download?platform=linux">Linux</a></li>
<li><a href="https://edgehill.nylas.com/download?platform=win32">Windows</a></li>
</ul>
</td><td style="width:50%;">
<h4>Package Architecture</h4>
<p>
Packages lie at the heart of Nylas Mail. Each part of the core experience is a separate package that uses the Nilas Package API to add functionality to the client. Learn more about packages and create your first package.
</p>
<ul>
<li><a href="./PackageOverview.html">Package Overview</a></li>
</ul>
</td></tr>
<tr><td style="width:50%; vertical-align:top;">
<h4>Dive Deeper</h4>
<ul>
<li><a href="./Architecture.html">Application Architecture</a></li>
<li><a href="./React.html">React & Component Injection</a></li>
<li><a href="./InterfaceConcepts.html">Core Interface Concepts</a></li>
<li><a href="./Database.html">Accessing the Database</a></li>
<li><a href="./DraftStoreExtensions.html">Draft Store Extensions</a></li>
</ul>
</td><td style="width:50%; vertical-align:top;">
<h4>Debugging Packages</h4>
<p>
Nylas Mail is built on top of Electron, which runs the latest version of Chromium. Learn how to access debug tools in Electron and use our Developer Tools Extensions:
</p>
<ul>
<li><a href="./Debugging.html">Debugging in Nylas</a></li>
</ul>
</td></tr>
<tr colspan="2"><td>
<h4>Questions?</h4>
<p>
Need help? Check out the [FAQ](./FAQ.html) or post a question in the [Nylas Mail Facebook Group](facebook.com/groups/nylas.mail)
</p>
</td></tr>
</table>

65
docs/InterfaceConcepts.md Normal file
View file

@ -0,0 +1,65 @@
---
Title: Interface Concepts
Section: Guides
Order: 1
---
The Nylas Mail user interface is conceptually organized into Sheets. Each Sheet represents a window of content. For example, the `Threads` sheet lies at the heart of the application. When the user chooses the "Files" tab, a separate `Files` sheet is displayed in place of `Threads`. When the user clicks a thread in single-pane mode, a `Thread` sheet is pushed on to the workspace and appears after a brief transition.
<img src="./images/sheets.png">
The {WorkspaceStore} maintains the state of the application's workspace and the stack of sheets currently being displayed. Your packages can declare "root" sheets which are listed in the app's main sidebar, or push custom sheets on top of sheets to display data.
The Nylas Workspace supports two display modes: `split` and `list`. Each Sheet describes it's appearance in each of the view modes it supports. For example, the `Threads` sheet describes a three column `split` view and a single column `list` view. Other sheets, like `Files` register for only one mode, and the user's mode preference is ignored.
For each mode, Sheets register a set of column names.
<img src="./images/columns.png">
```coffee
@defineSheet 'Threads', {root: true},
split: ['RootSidebar', 'ThreadList', 'MessageList', 'MessageListSidebar']
list: ['RootSidebar', 'ThreadList']
```
Column names are important. Once you've registered a sheet, your package (and other packages) register React components that appear in each column.
Sheets also have a `Header` and `Footer` region that spans all of their content columns. You can register components to appear in these regions to display notifications, add bars beneath the toolbar, etc.
```coffee
ComponentRegistry.register AccountSidebar,
location: WorkspaceStore.Location.RootSidebar
ComponentRegistry.register NotificationsStickyBar,
location: WorkspaceStore.Sheet.Threads.Header
```
Each column is laid out as a CSS Flexbox, making them extremely flexible. For more about layout using Flexbox, see Working with Flexbox.
###Toolbars
Toolbars in Nylas Mail are also powered by the {ComponentRegistry}. Though toolbars appear to be a single unit at the top of a sheet, they are divided into columns with the same widths as the columns in the sheet beneath them.
<img src="./images/toolbar.png">
Each Toolbar column is laid out using {Flexbox}. You can control where toolbar elements appear within the column using the CSS `order` attribute. To make it easy to position toolbar items on the left, right, or center of a column, we've added two "spacer" elements with `order:50` and `order:-50` that evenly use up available space. Other CSS attributes allow you to control whether your items shrink or expand as the column's size changes.
<img src="./images/toolbar-column.png">
To add items to a toolbar, you inject them via the {ComponentRegistry}. There are several ways of describing the location of a toolbar component which are useful in different scenarios:
- `<Location>.Toolbar`: This component will always appear in the toolbar above the column named `<Location>`.
(Example: Compose button which appears above the Left Sidebar column, regardless of what else is there.)
- `<ComponentName>.Toolbar`: This component will appear in the toolbar above `<ComponentName>`.
(Example: Archive button that should always be coupled with the MessageList component, placed anywhere a MessageList component is placed.)
- `Global.Toolbar.Left`: This component will always be added to the leftmost column of the toolbar.
(Example: Window Controls)

62
docs/Overview.md Normal file
View file

@ -0,0 +1,62 @@
<img src="/static/img/nylas-sdk-cuub@2x.png" class="center-logo"/>
<h2 style="text-align:center; margin-top:-20px;">Nylas SDK</h2>
<p style="text-align:center; margin:auto; margin-bottom:60px;">The Nylas SDK allows you to create powerful extensions to Nylas Mail, a mail client for Mac OS X, Windows, and Linux. Building on Nylas Mail saves time and allows you to build innovative new experiences fast.<br>
<a href="/sdk/getting-started" class="btn btn-redwood btn-sm btn-light btn-shadowed">Get Started</a>
</p>
<table class="no-border">
<tr><td style="width:50%;">
<h4>Installing Nylas Mail</h4>
<p>
Nylas Mail is available for Mac, Windows, and Linux. Download the latest build for your platform below:
</p>
<ul>
<li><a href="https://edgehill.nylas.com/download?platform=darwin">Mac OS X</a></li>
<li><a href="https://edgehill.nylas.com/download?platform=linux">Linux</a></li>
<li><a href="https://edgehill.nylas.com/download?platform=win32">Windows</a></li>
</ul>
</td><td style="width:50%;">
<h4>Package Architecture</h4>
<p>
Packages lie at the heart of Nylas Mail. Each part of the core experience is a separate package that uses the Nylas Package API to add functionality to the client. Learn more about packages and create your first package.
</p>
<ul>
<li><a href="/sdk/getting-started">Create a Package</a></li>
<li><a href="/sdk/packageoverview">Package Overview</a></li>
</ul>
</td></tr>
<tr><td style="width:50%; vertical-align:top;">
<h4>Dive Deeper</h4>
<ul>
<li><a href="/sdk/architecture">Application Architecture</a></li>
<li><a href="/sdk/react">React & Component Injection</a></li>
<li><a href="/sdk/interfaceconcepts">Core Interface Concepts</a></li>
<li><a href="/sdk/database">Accessing the Database</a></li>
<li><a href="/sdk/draftstoreextensions">Draft Store Extensions</a></li>
</ul>
</td><td style="width:50%; vertical-align:top;">
<h4>Debugging Packages</h4>
<p>
Nylas Mail is built on top of Electron, which runs the latest version of Chromium. Learn how to access debug tools in Electron and use our Developer Tools Extensions:
</p>
<ul>
<li><a href="/sdk/debugging">Debugging in Nylas</a></li>
</ul>
</td></tr>
<tr colspan="2"><td>
<h4>Questions?</h4>
<p>
Need help? Check out the <a href="FAQ.html">FAQ</a> or post a question in the <a href="http://slack-invite.nylas.com/">slack channel</a>.
</p>
</td></tr>
</table>

109
docs/PackageOverview.md Normal file
View file

@ -0,0 +1,109 @@
---
Title: Building a Package
Section: Guides
Order: 1
---
Packages lie at the heart of Nylas Mail. Each part of the core experience is a separate package that uses the Nylas Package API to add functionality to the client. Want to make a read-only mail client? Remove the core `Composer` package and you'll see reply buttons and composer functionality disappear.
Let's explore the files in a simple package that adds a Translate option to the Composer. When you tap the Translate button, we'll display a popup menu with a list of languages. When you pick a language, we'll make a web request and convert your reply into the desired language.
### Package Structure
Each package is defined by a `package.json` file that includes its name, version and dependencies. Packages may also declare dependencies which are loaded from npm - in this case, the [request](https://github.com/request/request) library. You'll need to `npm install` these dependencies locally when developing the package.
```
{
"name": "translate",
"version": "0.1.0",
"main": "./lib/main",
"description": "An example package for Nylas Mail",
"license": "Proprietary",
"engines": {
"atom": "*"
},
"dependencies": {
"request": "^2.53"
}
}
```
Our package also contains source files, a spec file with complete tests for the behavior the package adds, and a stylesheet for CSS:
```
- package.json
- lib/
- main.coffee
- translate-button.cjsx
- spec/
- main-spec.coffee
- stylesheets/
- translate.less
```
`package.json` lists `lib/main` as the root file of our package. Since Nylas Mail runs NodeJS, we can `require` other source files, Node packages, etc.
Nylas Mail can read `js`, `coffee`, `jsx`, and `cjsx` files automatically.
Inside `main.coffee`, there are two important functions being exported:
```coffee
require './translate-button'
module.exports =
# Activate is called when the package is loaded. If your package previously
# saved state using `serialize` it is provided.
#
activate: (@state) ->
ComponentRegistry.register TranslateButton,
role: 'Composer:ActionButton'
# Serialize is called when your package is about to be unmounted.
# You can return a state object that will be passed back to your package
# when it is re-activated.
#
serialize: ->
{}
# This optional method is called when the window is shutting down,
# or when your package is being updated or disabled. If your package is
# watching any files, holding external resources, providing commands or
# subscribing to events, release them here.
#
deactivate: ->
ComponentRegistry.unregister(TranslateButton)
```
> Nylas Mail uses CJSX, a Coffeescript version of JSX, which makes it easy to express Virtual DOM in React `render` methods! You may want to add the [Babel](https://github.com/babel/babel-sublime) plugin to Sublime Text, or the [CJSX Language](https://atom.io/packages/language-cjsx) for syntax highlighting.
### Package Stylesheets
Style sheets for your package should be placed in the _styles_ directory. Any style sheets in this directory will be loaded and attached to the DOM when your package is activated. Style sheets can be written as CSS or [Less](http://lesscss.org/), but Less is recommended.
Ideally, you won't need much in the way of styling. We've provided a standard set of components which define both the colors and UI elements for any package that fits into Nylas Mail seamlessly.
If you _do_ need special styling, try to keep only structural styles in the package stylesheets. If you _must_ specify colors and sizing, these should be taken from the active theme's [ui-variables.less][ui-variables]. For more information, see the [theme variables docs][theme-variables]. If you follow this guideline, your package will look good out of the box with any theme!
An optional `stylesheets` array in your `package.json` can list the style sheets by name to specify a loading order; otherwise, all style sheets are loaded.
### Package Assets
Many packages need other static files, like images. You can add static files anywhere in your package directory, and reference them at runtime using the `nylas://` url scheme:
```
<img src="nylas://my-package-name/assets/goofy.png">
a = new Audio()
a.src = "nylas://my-package-name/sounds/bloop.mp3"
a.play()
```
###Installing a Package
Nylas Mail ships with many packages already bundled with the application. When the application launches, it looks for additional packages in `~/.nylas/dev/packages`. Each package you create belongs in its own directory inside this folder.
In the future, it will be possible to install packages directly from within the client.

115
docs/React.md Normal file
View file

@ -0,0 +1,115 @@
---
Title: Interface Components
Section: Guides
Order: 2
---
Nylas Mail uses [React](https://facebook.github.io/react/) to create a fast, responsive UI. Packages that want to extend the Nylas Mail interface should use React. Using React's [JSX](https://facebook.github.io/react/jsx-in-depth.html) syntax is optional, but both [JSX](https://facebook.github.io/react/jsx-in-depth.html) and [CJSX](https://github.com/jsdf/coffee-react) (Coffeescript) are available.
For a quick introduction to React, take a look at Facebook's [Getting Started with React](https://facebook.github.io/react/getting-started.html).
#### React Components
Nylas Mail provides a set of core React components you can use in your packages. Many of the standard components listen for key events, include considerations for different platforms, and have extensive CSS. Wrapping standard components makes it easy to build rich interfaces that are consistent with the rest of the Nylas Mail platform.
To use a standard component, require it from `nylas-component-kit` and use it in your component's `render` method.
<p class="well">Keep in mind that React's Component model is based on composition rather than inheritance. On other platforms, you might subclass {Popover} to create your own custom Popover. In React, you should wrap the standard Popover component in your own component, which provides the Popover with <code>props</code> and children to customize its behavior.</p>
Here's a quick look at standard components you can require from `nylas-component-kit`:
- **{Menu}**: Allows you to display a list of items consistent with the rest of the Nylas Mail user experience.
- **{Spinner}**: Displays an indeterminate progress indicator centered within it's container.
- **{Popover}**: Component for creating menus and popovers that appear in response to a click and stay open until the user clicks outside them.
- **{Flexbox}**: Component for creating a Flexbox layout.
- **{RetinaImg}**: Replacement for standard `<img>` tags which automatically resolves the best version of the image for the user's display and can apply many image transforms.
- **{ListTabular}**: Component for creating a list of items backed by a paginating ModelView.
- **{MultiselectList}**: Component for creating a list that supports multi-selection. (Internally wraps ListTabular)
- **{MultiselectActionBar}**: Component for creating a contextual toolbar that is activated when the user makes a selection on a ModelView.
- **{ResizableRegion}**: Component that renders it's children inside a resizable region with a draggable handle.
- **{TokenizingTextField}**: Wraps a standard `<input>` and takes function props for tokenizing input values and displaying autocompletion suggestions.
- **{EventedIFrame}**: Replacement for the standard `<iframe>` tag which handles events directed at the iFrame to ensure a consistent user experience.
## React Component Injection
The Nylas Mail interface is composed at runtime from components added by different packages. The app's left sidebar contains components from the composer package, the source list package, the activity package, and more. You can leverage the flexiblity of this system to extend almost any part of Nylas Mail's interface.
### Registering Components
After you've created React components in your package, you should register them with the {ComponentRegistry}. The Component Registry manages the dynamic injection of components that makes Nylas Mail so extensible. You can request that your components appear in a specific `Location` defined by the {WorkspaceStore}, or register your component for a `Role` that another package has declared.
> The Component Registry allows you to insert your custom component without hacking up the DOM. Register for a `Location` or `Role` and your Component will be rendered into that part of the interface.
It's easy to see where registered components are displayed in Nylas Mail. Enable the Developer bar at the bottom of the app by opening the Inspector panel, and then click "**Component Regions**":
<img src="./images/injected-components.png">
Each region outlined in red is filled dynamically by looking up a React component or set of components from the Component Registry. You can see the role or location you'd need to register for, and the `props` that your component will receive in those locations.
Here are a few examples of how to use it to extend Nylas Mail. Typically, packages register components in their main `activate` method, and unregister them in `deactivate`:
1. Add a component to the Thread List column:
```coffee
ComponentRegistry.register ThreadList,
location: WorkspaceStore.Location.ThreadList
```
2. Add a component to the action bar at the bottom of the Composer:
```coffee
ComponentRegistry.register TemplatePicker,
role: 'Composer:ActionButton'
```
3. Replace the `Participants` component that ships with Nylas Mail to display thread participants on your own:
```coffee
ComponentRegistry.register ParticipantsWithStatusDots,
role: 'Participants'
```
*Tip: Remember to unregister components in the `deactivate` method of your package.*
### Using Registered Components
It's easy to build packages that use the Component Registry to display components vended by other parts of the application. You can query the Component Registry and display the components it returns. The Component Registry is a Reflux-compatible Store, so you can listen to it and update your state as the registry changes.
There are also several convenience components that make it easy to dynamically inject components into your Virtual DOM. These are the preferred way of using injected components.
- {InjectedComponent}: Renders the first component for the `matching` criteria you provide, and passes it the props in `externalProps`. See the API reference for more information.
```coffee
<InjectedComponent
matching={role:"Attachment"}
exposedProps={file: file, messageLocalId: @props.localId}/>
```
- {InjectedComponentSet}: Renders all of the components `matching` criteria you provide inside a {Flexbox}, and passes it the props in `externalProps`. See the API reference for more information.
```coffee
<InjectedComponentSet
className="message-actions"
matching={role:"MessageAction"}
exposedProps={thread:@props.thread, message: @props.message}>
```
### Unsafe Components
Nylas Mail considers all injected components "unsafe". When you render them using {InjectedComponent} or {InjectedComponentSet}, they will be wrapped in a component that prevents exceptions in their React render and lifecycle methods from impacting your component. Instead of your component triggering a React Invariant exception in the application, an exception notice will be rendered in place of the unsafe component.
<img src="./images/unsafe-component-exception.png">
In the future, Nylas Mail may automatically disable packages when their React components throw exceptions.

125
docs/WritingSpecs.md Normal file
View file

@ -0,0 +1,125 @@
---
Title: Writing Specs
TitleHidden: True
Section: Guides
Order: 7
---
# Writing specs
Nylas uses [Jasmine](http://jasmine.github.io/1.3/introduction.html) as its spec framework. As a package developer, you can write specs using Jasmine 1.3 and get some quick wins. Jasmine specs can be run in Nylas Mail directly from the Developer menu, and the test environment provides you with helpful stubs. You can also require your own test framework, or use Jasmine for integration tests and your own framework for your existing business logic.
This documentation describes using [Jasmine 1.3](http://jasmine.github.io/1.3/introduction.html) to write specs for a Nylas package.
#### Running Specs
You can run your package specs from `Developer > Run Package Specs...`. Once you've opened the spec window, you can see output and re-run your specs by clicking `Reload Specs`.
#### Writing Specs
To create specs, place `js`, `coffee`, or `cjsx` files in the `spec` directory of your package. Spec files must end with the `-spec` suffix.
Here's an annotated look at a typical Jasmine spec:
```coffee
# The `describe` method takes two arguments, a description and a function. If the description
# explains a behavior it typically begins with `when`; if it is more like a unit test it begins
# with the method name.
describe "when a test is written", ->
# The `it` method also takes two arguments, a description and a function. Try and make the
# description flow with the `it` method. For example, a description of `this should work`
# doesn't read well as `it this should work`. But a description of `should work` sounds
# great as `it should work`.
it "has some expectations that should pass", ->
# The best way to learn about expectations is to read the Jasmine documentation:
# http://jasmine.github.io/1.3/introduction.html#section-Expectations
# Below is a simple example.
expect("apples").toEqual("apples")
expect("oranges").not.toEqual("apples")
describe "Editor::moveUp", ->
...
```
#### Asynchronous Spcs
Writing Asynchronous specs can be tricky at first, but a combination of spec helpers can make things easy. Here are a few quick examples:
##### Promises
You can use the global `waitsForPromise` function to make sure that the test does not complete until the returned promise has finished, and run your expectations in a chained promise.
```coffee
describe "when requesting a Draft Session", ->
it "a session with the correct ID is returned", ->
waitsForPromise ->
DraftStore.sessionForLocalId('123').then (session) ->
expect(session.id).toBe('123')
```
This method can be used in the `describe`, `it`, `beforeEach` and `afterEach` functions.
```coffee
describe "when we open a file", ->
beforeEach ->
waitsForPromise ->
atom.workspace.open 'c.coffee'
it "should be opened in an editor", ->
expect(atom.workspace.getActiveTextEditor().getPath()).toContain 'c.coffee'
```
If you need to wait for multiple promises use a new `waitsForPromise` function for each promise. (Caution: Without `beforeEach` this example will fail!)
```coffee
describe "waiting for the packages to load", ->
beforeEach ->
waitsForPromise ->
atom.workspace.open('sample.js')
waitsForPromise ->
atom.packages.activatePackage('tabs')
waitsForPromise ->
atom.packages.activatePackage('tree-view')
it 'should have waited long enough', ->
expect(atom.packages.isPackageActive('tabs')).toBe true
expect(atom.packages.isPackageActive('tree-view')).toBe true
```
#### Asynchronous functions with callbacks
Specs for asynchronous functions can be done using the `waitsFor` and `runs` functions. A simple example.
```coffee
describe "fs.readdir(path, cb)", ->
it "is async", ->
spy = jasmine.createSpy('fs.readdirSpy')
fs.readdir('/tmp/example', spy)
waitsFor ->
spy.callCount > 0
runs ->
exp = [null, ['example.coffee']]
expect(spy.mostRecentCall.args).toEqual exp
expect(spy).toHaveBeenCalledWith(null, ['example.coffee'])
```
For a more detailed documentation on asynchronous tests please visit the http://jasmine.github.io/1.3/introduction.html#section-Asynchronous_Support)[Jasmine documentation].
#### Tips for Debugging Specs
To run a limited subset of specs use the `fdescribe` or `fit` methods. You can use those to focus a single spec or several specs. In the example above, focusing an individual spec looks like this:
```coffee
describe "when a test is written", ->
fit "has some expectations that should pass", ->
expect("apples").toEqual("apples")
expect("oranges").not.toEqual("apples")
```

355
docs/css/main.css Normal file
View file

@ -0,0 +1,355 @@
@font-face {
font-family: 'FaktPro';
font-style: normal;
font-weight: 400;
src: local('FaktPro-Blond'), url('fonts/FaktPro-Blond.ttf'), local('Helvetica Neue'), local('Helvetica');
}
@font-face {
font-family: 'FaktPro';
font-style: normal;
font-weight: 500;
src: local('FaktPro-Medium'), url('fonts/FaktPro-Medium.ttf'), local('Helvetica Neue'), local('Helvetica');
}
@font-face {
font-family: 'FaktPro';
font-style: normal;
font-weight: 600;
src: local('FaktPro-SemiBold'), url('fonts/FaktPro-SemiBold.ttf'), local('Helvetica Neue'), local('Helvetica');
}
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote {
margin: 0;
padding: 0;
}
strong {
color: #404040;
}
body {
font-family: 'FaktPro';
font-weight: normal;
font-size: 16px;
line-height: 1.5em;
color: #737373;
background-color: white;
margin: 0;
}
table {
margin: 10px 0 15px 0;
border-collapse: collapse;
}
td,th {
vertical-align: top;
border: 1px solid #ddd;
padding: 10px;
line-height: 1.5em;
}
th {
padding: 5px 10px;
}
a {
color: #0069d6;
text-decoration: none;
}
a:hover {
color: #0050a3;
text-decoration: none;
}
a img {
border: none;
}
p {
margin-bottom: 12px;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: #404040;
line-height: 36px;
}
h1 {
font-size: 40px;
margin-top:30px;
}
h2 {
font-size: 30px;
margin-top:30px;
}
h3 {
font-size: 24px;
margin-top:30px;
}
h4 {
font-size: 18px;
margin-top:20px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 14px;
}
hr {
margin: 0 0 19px;
border: 0;
border-bottom: 1px solid #ccc;
}
h1:first-child,
h2:first-child,
h3:first-child,
h4:first-child,
h5:first-child,
h6:first-child {
margin-top:0;
}
blockquote {
padding: 13px 13px 21px 15px;
margin-bottom: 18px;
font-family:georgia,serif;
font-style: italic;
border-left: 5px solid #C7DDDB;
background-color: #EAF7F6;
}
blockquote p {
font-size: 15px;
font-weight: normal;
margin-bottom: 0;
font-style: italic;
}
blockquote code {
background-color:white;
}
img {
max-width:100%;
}
code, pre {
font-family: Monaco, Andale Mono, Courier New, monospace;
}
code {
color: rgba(0, 0, 0, 0.75);
background-color: #EAF7F6;
padding: 1px 3px;
font-size: 14px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
pre {
margin: 0 0 18px;
line-height: 18px;
font-size: 14px;
border: 1px solid #d9d9d9;
white-space: pre-wrap;
word-wrap: break-word;
}
pre code {
font-size: 13px;
background-color: white;
padding: 0;
display: block;
padding: 14px;
}
sup {
font-size: 0.83em;
vertical-align: super;
line-height: 0;
}
* {
-webkit-print-color-adjust: exact;
}
.link {
width:18px;
height:18px;
display:inline-block;
vertical-align:sub;
opacity:0.4;
background:url(../images/link.png) top left;
background-size:cover;
}
@media screen and (min-width: 1020px) {
.container {
width: 960px;
margin:auto;
}
}
@media print {
body,code,pre code,h1,h2,h3,h4,h5,h6 {
color: black;
}
table, pre {
page-break-inside: avoid;
}
}
#header {
padding-top:40px;
padding-bottom:20px;
background-color:#eee;
margin-bottom:40px;
}
#footer {
margin-top:50px;
padding-top:30px;
padding-bottom:30px;
background-color:#eee;
clear:both;
}
#header .logo,
#footer .logo {
float:left;
width:50px;
padding-right: 15px;
}
#header .title,
#footer .title {
line-height: 22px;
font-size:20px;
font-weight:600;
padding-top:6px;
}
#header .small,
#footer .small {
font-weight:300;
font-size:0.9em;
}
#main {
margin-left:290px;
}
#sidebar {
float:left;
position:static;
width:250px;
}
#sidebar .heading {
color:#404040;
line-height:28px;
font-size:16px;
font-weight:bold;
}
#sidebar ul .heading {
line-height:22px;
font-size:14px;
padding-top:6px;
}
#sidebar ul {
margin-top:0;
padding-left:15px;
}
#sidebar ul li {
list-style-type:none;
}
#sidebar ul li a {
color:#404040;
font-size:14px;
line-height:1.8em;
}
.page-title {
font-weight:200;
font-size:40px;
color:#404040;
padding-bottom:40px;
padding-top:30px;
}
.page-title .extends {
font-style: italic;
font-size:0.7em;
color:#ccc;
}
/* It's not possible to make H3+ in Markdown parsed out of source code, because
Coffeescript uses the ### as the comment block character. Allow the use of #
and ##, but convert these h1 and h2 elements to smaller headings. */
.markdown-from-sourecode h1,
.markdown-from-sourecode h2 {
font-size: 24px;
margin-top:30px;
}
.article img {
margin-top:18px;
margin-bottom:18px;
}
.article .center-logo {
width:270px;
height:270px;
margin:auto;
margin-top:20px;
display:block;
border:0;
}
.function-name {
border-bottom:1px solid #ccc;
padding-top:10px;
}
.function-name .arg {
color: #999;
}
.function-name .arg:after {
content: ", ";
color: #999;
}
.function-name .arg:last-child:after {
content: "";
}
.function-description h1,
.function-description h2,
.function-description h3,
.function-description h4,
.function-description h5 {
font-size: 16px;
line-height:1.5em;
margin:0;
}
table th {
background-color: #EAF7F6;
text-align:left;
}
table td {
position:relative;
}
table.arguments {
width:100%;
}
table.arguments p {
margin-bottom:0;
}
table.arguments .optional {
background-color: #EAF7F6;
position:absolute;
top:0px;
right:0px;
padding-right: 4px;
padding-left: 4px;
font-weight: 500;
font-size: 11px;
line-height:16px;
}
table.no-border td {
border:0;
}

93
docs/css/tomorrow.css Normal file
View file

@ -0,0 +1,93 @@
/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */
/* Tomorrow Comment */
.hljs-comment {
color: #8e908c;
}
/* Tomorrow Red */
.hljs-variable,
.hljs-attribute,
.hljs-tag,
.hljs-regexp,
.ruby .hljs-constant,
.xml .hljs-tag .hljs-title,
.xml .hljs-pi,
.xml .hljs-doctype,
.html .hljs-doctype,
.css .hljs-id,
.css .hljs-class,
.css .hljs-pseudo {
color: #c82829;
}
/* Tomorrow Orange */
.hljs-number,
.hljs-preprocessor,
.hljs-pragma,
.hljs-built_in,
.hljs-literal,
.hljs-params,
.hljs-constant {
color: #f5871f;
}
/* Tomorrow Yellow */
.ruby .hljs-class .hljs-title,
.css .hljs-rule .hljs-attribute {
color: #eab700;
}
/* Tomorrow Green */
.hljs-string,
.hljs-value,
.hljs-inheritance,
.hljs-header,
.hljs-name,
.ruby .hljs-symbol,
.xml .hljs-cdata {
color: #718c00;
}
/* Tomorrow Aqua */
.hljs-title,
.css .hljs-hexcolor {
color: #3e999f;
}
/* Tomorrow Blue */
.hljs-function,
.python .hljs-decorator,
.python .hljs-title,
.ruby .hljs-function .hljs-title,
.ruby .hljs-title .hljs-keyword,
.perl .hljs-sub,
.javascript .hljs-title,
.coffeescript .hljs-title {
color: #4271ae;
}
/* Tomorrow Purple */
.hljs-keyword,
.javascript .hljs-function {
color: #8959a8;
}
.hljs {
display: block;
overflow-x: auto;
background: white;
color: #4d4d4c;
padding: 0.5em;
-webkit-text-size-adjust: none;
}
.coffeescript .javascript,
.javascript .xml,
.tex .hljs-formula,
.xml .javascript,
.xml .vbscript,
.xml .css,
.xml .hljs-cdata {
opacity: 0.5;
}

BIN
docs/images/columns.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

BIN
docs/images/edgehill.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

BIN
docs/images/link.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 608 B

BIN
docs/images/nylas.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

BIN
docs/images/sheets.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

BIN
docs/images/sidebar-md5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

BIN
docs/images/toolbar.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 545 KiB