{ "sections": [ { "name": "Getting Started", "items": [ { "html": "\n\n\n
\n
\n

Start building on top of Nylas in minutes:

\n

1
Install N1

\n

Download and install Nylas for . Open it and sign in to your email account.

\n
\n
\n\n
\n
\n

2
Start a Package

\n

Packages lie at the heart of N1. 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 Create a Package... and name your new package.

\n
\n
\n \n
\n
\n\n
\n
\n

3
See it in Action

\n

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 View > Refresh to see your changes in N1.

\n
\n
\n\n
\n\n
\n
\n

Step 2: Build your first package

\n
\n
\n\n
\n\n
\n
\n

A
Explore the source

\n \n

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 ~/.nylas/dev/packages.

\n
\n
\n

B
Run the specs

\n \n

In N1, select Developer > Run Package Specs... from the menu to run your package's new specs. Nylas and its packages use the Jasmine testing framework.

\n
\n
\n\n

Step 2: Building your first package

\n\n

If you followed the first part of our Getting Started Guide, you should have a brand new package just waiting to be explored.

\n

This sample package simply adds the name of the currently focused contact to the sidebar:

\n

\n

We're going to build on this to show the sender's Gravatar image in the sidebar, instead of just their name. You can check out the full code for the package in the sample packages repository.

\n

Find the package source in ~/.nylas/dev/packages and open the contents in your favorite text editor.

\n
\n

We use CJSX, a CoffeeScript syntax for JSX, to streamline our package code.\n For syntax highlighting, we recommend Babel for Sublime, or the CJSX Language Atom package.

\n
\n

Changing the data

\n

Let's poke around and change what the sidebar displays.

\n

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.

\n

(How does it get in the sidebar? See Interface Concepts and look at main.cjsx for clues. We'll dive into this more later in the guide.)

\n

We can change the sidebar to display the contact's email address as well. Check out the Contact attributes and change the _renderContent method to display more information:

\n
_renderContent: =>\n  <div className=\"header\">\n      <h1>Hi, {@state.contact.name} ({@state.contact.email})!</h1>\n  </div>\n
\n

After making changes to the package, reload N1 by going to View > Reload.

\n

Installing a dependency

\n

Now we've figured out how to show the contact's email address, we can use that to generate the Gravatar for the contact. However, as per the Gravatar documentation, we need to be able to calculate the MD5 hash for an email address first.

\n

Let's install the md5 package and save it as a dependency in our package.json:

\n
$ npm install md5 --save\n
\n

Installing other dependencies works the same way.

\n

Now, add the md5 requirement in my-message-sidebar.cjsx and update the _renderContent method to show the md5 hash:

\n
md5 = require 'md5'\n\nclass MyMessageSidebar extends React.Component\n  @displayName: 'MyMessageSidebar'\n\n  ...\n\n  _renderContent: =>\n    <div className=\"header\">\n      {md5(@state.contact.email)}\n    </div>\n
\n
\n

JSX Tip: The {..} syntax is used for JavaScript expressions inside HTML elements. Learn more.

\n
\n

You should see the MD5 hash appear in the sidebar (after you reload N1):

\n

\n

Let's Render!

\n

Turning the MD5 hash into a Gravatar image is simple. We need to add an <img> tag to the rendered HTML:

\n
_renderContent =>\n    <div className=\"header\">\n      <img src={'http://www.gravatar.com/avatar/' + md5(@state.contact.email)}/>\n    </div>\n
\n

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 to change the default behavior.

\n

\n

Styling

\n

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:

\n

stylesheets/main.less

\n
.gravatar {\n    border-radius: 45px;\n    border: 2px solid #ccc;\n}\n
\n

lib/my-message-sidebar.cjsx

\n
_renderContent =>\n    gravatar = \"http://www.gravatar.com/avatar/\" + md5(@state.contact.email)\n\n    <div className=\"header\">\n      <img src={gravatar} className=\"gravatar\"/>\n    </div>\n
\n
\n

React Tip: Remember to use DOM property names, i.e. className instead of class.

\n
\n

You'll see these styles reflected in your sidebar.

\n

\n

If you're a fan of using the Chrome Developer Tools to tinker with styles, no fear; they work in N1, 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.

\n
\n\n

Continue this guide: adding a data store to your package

\n\n
\n\n\n

Step 3: Adding a Data Store

\n\n

Building on the previous part of our Getting Started guide, we're going to introduce a data store to give our sidebar superpowers.

\n

Stores and Data Flow

\n

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 explanation for more details.

\n

Using the Flux pattern 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.

\n

We've already used this (without realizing) in the Gravatar sidebar example:

\n
  componentDidMount: =>\n    @unsubscribe = FocusedContactsStore.listen(@_onChange)\n  ...\n  _onChange: =>\n    @setState(@_getStateFromStores())\n\n  _getStateFromStores: =>\n    contact: FocusedContactsStore.focusedContact()\n
\n

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.

\n

To add more depth to our sidebar package, we need to:

\n\n

In this guide, we'll fetch the GitHub profile for the currently focused contact and display a link to it, using the GitHub API.

\n

Creating the Store

\n

The boilerplate to create a new store which listens to FocusedContactsStore looks like this:

\n

lib/github-user-store.coffee

\n
Reflux = require 'reflux'\n{FocusedContactsStore} = require 'nylas-exports'\n\nmodule.exports =\n\nGithubUserStore = Reflux.createStore\n\n  init: ->\n      @listenTo FocusedContactsStore, @_onFocusedContactChanged\n\n  _onFocusedContactChanged: ->\n      # TBD - This is fired when the focused contact changes\n      @trigger(@)\n
\n

(Note: You'll need to set up the reflux dependency.)

\n

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.

\n

Let's build this out to retrieve some new data based on the focused contact, and expose it via a UI component.

\n

Getting Data In

\n

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.

\n
request = require 'request'\n\nGithubUserStore = Reflux.createStore\n  init: ->\n    @_profile = null\n    @listenTo FocusedContactsStore, @_onFocusedContactChanged\n\n  getProfile: ->\n    @_profile\n\n  _onFocusedContactChanged: ->\n    # Get the newly focused contact\n    contact = FocusedContactsStore.focusedContact()\n    # Clear the profile we're currently showing\n    @_profile = null    \n    if contact\n      @_fetchGithubProfile(contact.email)\n    @trigger(@)\n\n  _fetchGithubProfile: (email) ->\n    @_makeRequest \"https://api.github.com/search/users?q=#{email}\", (err, resp, data) =>\n      console.warn(data.message) if data.message?\n      # Make sure we actually got something back\n      github = data?.items?[0] ? false\n      if github\n        @_profile = github\n        console.log(github)\n    @trigger(@)\n\n  _makeRequest: (url, callback) ->\n    # GitHub needs a User-Agent header. Also, parse responses as JSON.\n    request({url: url, headers: {'User-Agent': 'request'}, json: true}, callback)\n
\n

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.

\n

You may run into rate-limiting issues with the GitHub API; to avoid these, you can add authentication with a pre-baked token 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.

\n

Display Time

\n

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.

\n
class GithubSidebar extends React.Component\n  ...\n  componentDidMount: =>\n    @unsubscribe = GithubUserStore.listen(@_onChange)\n\n  _onChange: =>\n    @setState(@_getStateFromStores())\n\n  _getStateFromStores: =>\n    github: GithubUserStore.getProfile()\n
\n

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.

\n

For example:

\n
  _renderContent: =>\n    <img className=\"github\" src={@state.github.avatar_url}/> <a href={@state.github.html_url}>GitHub</a>\n
\n

Extending The Store

\n

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. :)

\n
\n

You can find a more extensive version of this example in our sample packages repository.

\n
\n", "meta": { "Title": "First Steps", "TitleHidden": true, "Section": "Getting Started", "Order": 2, "title": "First Steps", "titlehidden": true, "section": "Getting Started", "order": 2 }, "name": "First Steps", "filename": "index.md", "link": "index.html" } ] }, { "name": "Guides", "items": [ { "html": "

Packages lie at the heart of N1. 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.

\n

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.

\n

Package Structure

\n

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 library. You'll need to npm install these dependencies locally when developing the package.

\n
{\n  \"name\": \"translate\",\n  \"version\": \"0.1.0\",\n  \"main\": \"./lib/main\",\n  \"description\": \"An example package for N1\",\n  \"license\": \"Proprietary\",\n  \"engines\": {\n    \"atom\": \"*\"\n  },\n  \"dependencies\": {\n    \"request\": \"^2.53\"\n  }\n}\n

Our package also contains source files, a spec file with complete tests for the behavior the package adds, and a stylesheet for CSS:

\n
- package.json\n- lib/\n   - main.coffee\n   - translate-button.cjsx\n- spec/\n   - main-spec.coffee\n- stylesheets/\n   - translate.less\n

package.json lists lib/main as the root file of our package. Since N1 runs NodeJS, we can require other source files, Node packages, etc.

\n

N1 can read js, coffee, jsx, and cjsx files automatically.

\n

Inside main.coffee, there are two important functions being exported:

\n
require './translate-button'\n\nmodule.exports =\n\n  # Activate is called when the package is loaded. If your package previously\n  # saved state using `serialize` it is provided.\n  #\n  activate: (@state) ->\n    ComponentRegistry.register TranslateButton,\n      role: 'Composer:ActionButton'\n\n  # Serialize is called when your package is about to be unmounted.\n  # You can return a state object that will be passed back to your package\n  # when it is re-activated.\n  #\n  serialize: ->\n      {}\n\n  # This optional method is called when the window is shutting down,\n  # or when your package is being updated or disabled. If your package is\n  # watching any files, holding external resources, providing commands or\n  # subscribing to events, release them here.\n  #\n  deactivate: ->\n    ComponentRegistry.unregister(TranslateButton)\n
\n
\n

N1 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 plugin to Sublime Text, or the CJSX Language for syntax highlighting.

\n
\n

Package Stylesheets

\n

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, but Less is recommended.

\n

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 N1 seamlessly.

\n

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!

\n

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.

\n

Package Assets

\n

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:

\n
<img src=\"nylas://my-package-name/assets/goofy.png\">\n\na = new Audio()\na.src = \"nylas://my-package-name/sounds/bloop.mp3\"\na.play()\n

Installing a Package

\n

N1 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.

\n

In the future, it will be possible to install packages directly from within the client.

\n", "meta": { "Title": "Building a Package", "Section": "Guides", "Order": 1, "title": "Building a Package", "section": "Guides", "order": 1 }, "name": "Building a Package", "filename": "PackageOverview.md", "link": "PackageOverview.html" }, { "html": "

The N1 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.

\n

\n

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.

\n

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.

\n

For each mode, Sheets register a set of column names.

\n

\n
@defineSheet 'Threads', {root: true},\n   split: ['RootSidebar', 'ThreadList', 'MessageList', 'MessageListSidebar']\n   list: ['RootSidebar', 'ThreadList']\n
\n

Column names are important. Once you've registered a sheet, your package (and other packages) register React components that appear in each column.

\n

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.

\n
ComponentRegistry.register AccountSidebar,\n  location: WorkspaceStore.Location.RootSidebar\n\n\nComponentRegistry.register NotificationsStickyBar,\n  location: WorkspaceStore.Sheet.Threads.Header\n
\n

Each column is laid out as a CSS Flexbox, making them extremely flexible. For more about layout using Flexbox, see Working with Flexbox.

\n

###Toolbars

\n

Toolbars in N1 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.

\n

\n

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.

\n

\n

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:

\n\n", "meta": { "Title": "Interface Concepts", "Section": "Guides", "Order": 1, "title": "Interface Concepts", "section": "Guides", "order": 1 }, "name": "Interface Concepts", "filename": "InterfaceConcepts.md", "link": "InterfaceConcepts.html" }, { "html": "

N1 uses React to create a fast, responsive UI. Packages that want to extend the N1 interface should use React. Using React's JSX syntax is optional, but both JSX and CJSX (CoffeeScript) are available.

\n

For a quick introduction to React, take a look at Facebook's Getting Started with React.

\n

React Components

\n

N1 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 N1 platform.

\n

To use a standard component, require it from nylas-component-kit and use it in your component's render method.

\n

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 props and children to customize its behavior.

\n\n\n

Here's a quick look at standard components you can require from nylas-component-kit:

\n\n

React Component Injection

\n

The N1 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 N1's interface.

\n

Registering Components

\n

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 N1 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.

\n
\n

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.

\n
\n

It's easy to see where registered components are displayed in N1. Enable the Developer bar at the bottom of the app by opening the Inspector panel, and then click "Component Regions":

\n

\n

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.

\n

Here are a few examples of how to use it to extend N1. Typically, packages register components in their main activate method, and unregister them in deactivate:

\n
    \n
  1. Add a component to the Thread List column:

    \n
         ComponentRegistry.register ThreadList,\n       location: WorkspaceStore.Location.ThreadList\n
    \n
  2. \n
  3. Add a component to the action bar at the bottom of the Composer:

    \n
         ComponentRegistry.register TemplatePicker,\n       role: 'Composer:ActionButton'\n
    \n
  4. \n
  5. Replace the Participants component that ships with N1 to display thread participants on your own:

    \n
         ComponentRegistry.register ParticipantsWithStatusDots,\n         role: 'Participants'\n
    \n
  6. \n
\n

Tip: Remember to unregister components in the deactivate method of your package.

\n

Using Registered Components

\n

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.

\n

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.

\n\n
<InjectedComponent\n    matching={role:\"Attachment\"}\n    exposedProps={file: file, messageLocalId: @props.localId}/>\n
\n\n
<InjectedComponentSet\n    className=\"message-actions\"\n    matching={role:\"MessageAction\"}\n    exposedProps={thread:@props.thread, message: @props.message}>\n
\n

Unsafe Components

\n

N1 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.

\n

\n

In the future, N1 may automatically disable packages when their React components throw exceptions.

\n", "meta": { "Title": "Interface Components", "Section": "Guides", "Order": 2, "title": "Interface Components", "section": "Guides", "order": 2 }, "name": "Interface Components", "filename": "React.md", "link": "React.html" }, { "html": "

N1 uses Reflux, a slim implementation of Facebook's Flux Application Architecture 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:

\n\n

For more information about the Flux pattern, check out this diagram. For a bit more insight into why we chose Reflux over other Flux implementations, there's a great blog post by the author of Reflux.

\n

There are several core stores in the application:

\n\n

Most packages declare additional stores that subscribe to these Stores, as well as user Actions, and vend data to the package's React components.

\n

Actions

\n

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 N1, the React component for the button fires {Actions::composeNewBlankDraft}. The {DraftStore} listens to this action and opens a new composer window.

\n

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.

\n

For a complete list of available actions, see {Actions}.

\n", "meta": { "Title": "Application Architecture", "Section": "Guides", "Order": 3, "title": "Application Architecture", "section": "Guides", "order": 3 }, "name": "Application Architecture", "filename": "Architecture.md", "link": "Architecture.html" }, { "html": "

Chromium DevTools

\n

N1 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 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.

\n

Here are a few hidden tricks for getting the most out of the Chromium DevTools:

\n\n

Nylas Developer Panel

\n

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.

\n

The Developer Panel provides three views which you can click to activate:

\n\n

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.

\n

The Development Workflow

\n

If you're debugging a package, you'll be modifying your code and re-running N1 over and over again. There are a few things you can do to make this development workflow less time consuming:

\n\n

In the future, we'll support much richer hot-reloading of plugin components and code. Stay tuned!

\n", "meta": { "Title": "Debugging N1", "Section": "Guides", "Order": 4, "title": "Debugging N1", "section": "Guides", "order": 4 }, "name": "Debugging N1", "filename": "Debugging.md", "link": "Debugging.html" }, { "html": "

N1 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:

\n

\n

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.

\n

Declaring Models

\n

In N1, 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:

\n
class Example extends Model\n\n  @attributes:\n    'id': Attributes.String\n      queryable: true\n      modelKey: 'id'\n\n    'object': Attributes.String\n      modelKey: 'object'\n\n    'namespaceId': Attributes.String\n      queryable: true\n      modelKey: 'namespaceId'\n      jsonKey: 'namespace_id'\n\n    'body': Attributes.JoinedData\n      modelTable: 'MessageBody'\n      modelKey: 'body'\n\n    'files': Attributes.Collection\n      modelKey: 'files'\n      itemClass: File\n\n    'unread': Attributes.Boolean\n      queryable: true\n      modelKey: 'unread'\n
\n

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.

\n

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:

\n
Thread.attributes.namespaceId.equals(\"123\")\n// where namespace_id = '123'\n\nThread.attributes.lastMessageTimestamp.greaterThan(123)\n// where last_message_timestamp > 123\n\nThread.attributes.lastMessageTimestamp.descending()\n// order by last_message_timestamp DESC\n
\n

Retrieving Models

\n

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.

\n
DatabaseStore.find(Thread, '123').then (thread) ->\n    # thread is a thread object\n\nDatabaseStore.findBy(Thread, {subject: 'Hello World'}).then (thread) ->\n    # find a single thread by subject\n\nDatabaseStore.findAll(Thread).where([Thread.attributes.tags.contains('inbox')]).then (threads) ->\n    # find threads with the inbox tag\n\nDatabaseStore.count(Thread).where([Thread.attributes.lastMessageTimestamp.greaterThan(120315123)]).then (results) ->\n    # count threads where last message received since 120315123.\n
\n

Retrieving Pages of Models

\n

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.

\n

Saving and Updating Models

\n

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.

\n

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.

\n

Saving Drafts

\n

Drafts in N1 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.

\n

Removing Models

\n

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.

\n

Advanced Model Attributes

\n
Attribute.JoinedData
\n

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.

\n

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:

\n
DatabaseStore.find(Message, '123').then (message) ->\n    // message.body is undefined\n\nDatabaseStore.find(Message, '123').include(Message.attributes.body).then (message) ->\n    // message.body is defined\n
\n

When you call persistModel, JoinedData attributes are automatically written to the secondary table.

\n

JoinedData attributes cannot be queryable.

\n
Attribute.Collection
\n

Collection attributes provide basic support for one-to-many relationships. For example, {Thread}s in N1 have a collection of {Tag}s.

\n

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.

\n

Collection attributes have an additional clause builder, contains:

\n
DatabaseStore.findAll(Thread).where([Thread.attributes.tags.contains('inbox')])\n
\n

This is equivalent to writing the following SQL:

\n
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\n
\n

Listening for Changes

\n

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.

\n

Within Reflux Stores, you can listen to the {DatabaseStore} using the listenTo helper method:

\n
@listenTo(DatabaseStore, @_onDataChanged)\n
\n

Within generic code, you can listen to the {DatabaseStore} using this syntax:

\n
@unlisten = DatabaseStore.listen(@_onDataChanged, @)\n
\n

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:

\n
{\n    \"objectClass\": // string: the name of the class that was changed. ie: \"Thread\"\n    \"objects\": // array: the objects that were persisted or removed\n}\n

But why can't I...?

\n

N1 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:

\n\n", "meta": { "Title": "Accessing the Database", "Section": "Guides", "Order": 5, "title": "Accessing the Database", "section": "Guides", "order": 5 }, "name": "Accessing the Database", "filename": "Database.md", "link": "Database.html" }, { "html": "

The composer lies at the heart of N1, 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.

\n

This API allows your package to:

\n\n

To create your own composer extensions, subclass {DraftStoreExtension} and override the methods your extension needs.

\n

In the sample packages repository, templates is an example of a package which uses a DraftStoreExtension to enhance the composer experience.

\n

Example

\n

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.

\n
{DraftStoreExtension} = require 'nylas-exports'\n\nclass ProductsExtension extends DraftStoreExtension\n\n   @warningsForSending: (draft) ->\n      words = ['acme', 'anvil', 'tunnel', 'rocket', 'dynamite']\n      body = draft.body.toLowercase()\n      for word in words\n        if body.indexOf(word) > 0\n            return [\"with the word '#{word}'?\"]\n      return []\n\n   @finalizeSessionBeforeSending: (session) ->\n      draft = session.draft()\n      if @warningsForSending(draft)\n         bodyWithWarning = draft.body += \"<br>This email \\\n             contains competitor's product names \\\n            or trademarks used in context.\"\n         session.changes.add(body: bodyWithWarning)\n
\n", "meta": { "Title": "Extending the Composer", "Section": "Guides", "Order": 6, "title": "Extending the Composer", "section": "Guides", "order": 6 }, "name": "Extending the Composer", "filename": "DraftStoreExtensions.md", "link": "DraftStoreExtensions.html" }, { "html": "

Nylas uses Jasmine 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 N1 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.

\n

This documentation describes using Jasmine 1.3 to write specs for a Nylas package.

\n

Running Specs

\n

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.

\n

Writing Specs

\n

To create specs, place js, coffee, or cjsx files in the spec directory of your package. Spec files must end with the -spec suffix.

\n

Here's an annotated look at a typical Jasmine spec:

\n
# The `describe` method takes two arguments, a description and a function. If the description\n# explains a behavior it typically begins with `when`; if it is more like a unit test it begins\n# with the method name.\ndescribe \"when a test is written\", ->\n\n  # The `it` method also takes two arguments, a description and a function. Try and make the\n  # description flow with the `it` method. For example, a description of `this should work`\n  # doesn't read well as `it this should work`. But a description of `should work` sounds\n  # great as `it should work`.\n  it \"has some expectations that should pass\", ->\n\n    # The best way to learn about expectations is to read the Jasmine documentation:\n    # http://jasmine.github.io/1.3/introduction.html#section-Expectations\n    # Below is a simple example.\n\n    expect(\"apples\").toEqual(\"apples\")\n    expect(\"oranges\").not.toEqual(\"apples\")\n\ndescribe \"Editor::moveUp\", ->\n    ...\n
\n

Asynchronous Spcs

\n

Writing Asynchronous specs can be tricky at first, but a combination of spec helpers can make things easy. Here are a few quick examples:

\n
Promises
\n

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.

\n
  describe \"when requesting a Draft Session\", ->\n    it \"a session with the correct ID is returned\", ->\n      waitsForPromise ->\n        DraftStore.sessionForLocalId('123').then (session) ->\n          expect(session.id).toBe('123')\n
\n

This method can be used in the describe, it, beforeEach and afterEach functions.

\n
describe \"when we open a file\", ->\n  beforeEach ->\n    waitsForPromise ->\n      atom.workspace.open 'c.coffee'\n\n  it \"should be opened in an editor\", ->\n    expect(atom.workspace.getActiveTextEditor().getPath()).toContain 'c.coffee'\n
\n

If you need to wait for multiple promises use a new waitsForPromise function for each promise. (Caution: Without beforeEach this example will fail!)

\n
describe \"waiting for the packages to load\", ->\n\n  beforeEach ->\n    waitsForPromise ->\n      atom.workspace.open('sample.js')\n    waitsForPromise ->\n      atom.packages.activatePackage('tabs')\n    waitsForPromise ->\n      atom.packages.activatePackage('tree-view')\n\n  it 'should have waited long enough', ->\n    expect(atom.packages.isPackageActive('tabs')).toBe true\n    expect(atom.packages.isPackageActive('tree-view')).toBe true\n
\n

Asynchronous functions with callbacks

\n

Specs for asynchronous functions can be done using the waitsFor and runs functions. A simple example.

\n
describe \"fs.readdir(path, cb)\", ->\n  it \"is async\", ->\n    spy = jasmine.createSpy('fs.readdirSpy')\n\n    fs.readdir('/tmp/example', spy)\n    waitsFor ->\n      spy.callCount > 0\n    runs ->\n      exp = [null, ['example.coffee']]\n      expect(spy.mostRecentCall.args).toEqual exp\n      expect(spy).toHaveBeenCalledWith(null, ['example.coffee'])\n
\n

For a more detailed documentation on asynchronous tests please visit the http://jasmine.github.io/1.3/introduction.html#section-Asynchronous_Support)[Jasmine documentation].

\n

Tips for Debugging Specs

\n

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:

\n
describe \"when a test is written\", ->\n  fit \"has some expectations that should pass\", ->\n    expect(\"apples\").toEqual(\"apples\")\n    expect(\"oranges\").not.toEqual(\"apples\")\n
\n", "meta": { "Title": "Writing Specs", "TitleHidden": true, "Section": "Guides", "Order": 7, "title": "Writing Specs", "titlehidden": true, "section": "Guides", "order": 7 }, "name": "Writing Specs", "filename": "WritingSpecs.md", "link": "WritingSpecs.html" }, { "html": "

Do I have to use React?

\n

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 N1 interface.

\n

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.

\n

Can I write a package that does X?

\n

If you don't find documentation for the part of N1 you want to extend, let us know! We're constantly working to enable new workflows by making more of the application extensible.

\n

Can I distribute my package?

\n

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:

\n
    \n
  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)

    \n
  2. \n
  3. Make the CURL request below to the package manager server to register your package:

    \n
     curl -H \"Content-Type:application/json\" -X POST -d '{\"repository\":\"https://github.com/<username>/<repo>\"}' https://edgehill-packages.nylas.com/api/packages\n
  4. \n
  5. Your package will now appear when users visit the N1 settings page and search for community packages.

    \n
  6. \n
\n

Note: In the near future, we'll be formalizing the process of distributing packages, and packages you publish now may need to be resubmitted.

\n", "meta": { "Title": "FAQ", "Section": "Guides", "Order": 10, "title": "FAQ", "section": "Guides", "order": 10 }, "name": "FAQ", "filename": "FAQ.md", "link": "FAQ.html" } ] }, { "name": "Sample Code", "link": "https://nylas.github.io/N1/examples", "external": true }, { "name": "API Reference", "items": [ { "name": "General", "items": [ { "name": "Actions", "link": "Actions.html" }, { "name": "Atom", "link": "Atom.html" }, { "name": "BufferedNodeProcess", "link": "BufferedNodeProcess.html" }, { "name": "BufferedProcess", "link": "BufferedProcess.html" }, { "name": "ChangeFolderTask", "link": "ChangeFolderTask.html" }, { "name": "ChangeLabelsTask", "link": "ChangeLabelsTask.html" }, { "name": "Config", "link": "Config.html" }, { "name": "DraggableImg", "link": "DraggableImg.html" }, { "name": "FocusTrackingRegion", "link": "FocusTrackingRegion.html" }, { "name": "Switch", "link": "Switch.html" }, { "name": "Task", "link": "Task.html" }, { "name": "TaskQueueStatusStore", "link": "TaskQueueStatusStore.html" } ] }, { "name": "Component Kit", "items": [ { "name": "EventedIFrame", "link": "EventedIFrame.html" }, { "name": "Flexbox", "link": "Flexbox.html" }, { "name": "InjectedComponent", "link": "InjectedComponent.html" }, { "name": "InjectedComponentSet", "link": "InjectedComponentSet.html" }, { "name": "Menu", "link": "Menu.html" }, { "name": "MenuItem", "link": "MenuItem.html" }, { "name": "MenuNameEmailItem", "link": "MenuNameEmailItem.html" }, { "name": "MultiselectActionBar", "link": "MultiselectActionBar.html" }, { "name": "MultiselectList", "link": "MultiselectList.html" }, { "name": "Popover", "link": "Popover.html" }, { "name": "ResizableRegion", "link": "ResizableRegion.html" }, { "name": "RetinaImg", "link": "RetinaImg.html" }, { "name": "Spinner", "link": "Spinner.html" }, { "name": "TimeoutTransitionGroupChild", "link": "TimeoutTransitionGroupChild.html" }, { "name": "UnsafeComponent", "link": "UnsafeComponent.html" } ] }, { "name": "Models", "items": [ { "name": "Account", "link": "Account.html" }, { "name": "Calendar", "link": "Calendar.html" }, { "name": "Contact", "link": "Contact.html" }, { "name": "File", "link": "File.html" }, { "name": "Folder", "link": "Folder.html" }, { "name": "Label", "link": "Label.html" }, { "name": "Message", "link": "Message.html" }, { "name": "Model", "link": "Model.html" }, { "name": "Thread", "link": "Thread.html" } ] }, { "name": "Stores", "items": [ { "name": "AccountStore", "link": "AccountStore.html" }, { "name": "ComponentRegistry", "link": "ComponentRegistry.html" }, { "name": "ContactStore", "link": "ContactStore.html" }, { "name": "EventStore", "link": "EventStore.html" }, { "name": "FocusedContentStore", "link": "FocusedContentStore.html" }, { "name": "MessageStoreExtension", "link": "MessageStoreExtension.html" }, { "name": "TaskQueue", "link": "TaskQueue.html" }, { "name": "WorkspaceStore", "link": "WorkspaceStore.html" } ] }, { "name": "Database", "items": [ { "name": "Attribute", "link": "Attribute.html" }, { "name": "AttributeBoolean", "link": "AttributeBoolean.html" }, { "name": "AttributeCollection", "link": "AttributeCollection.html" }, { "name": "AttributeDateTime", "link": "AttributeDateTime.html" }, { "name": "AttributeJoinedData", "link": "AttributeJoinedData.html" }, { "name": "AttributeNumber", "link": "AttributeNumber.html" }, { "name": "AttributeObject", "link": "AttributeObject.html" }, { "name": "AttributeServerId", "link": "AttributeServerId.html" }, { "name": "AttributeString", "link": "AttributeString.html" }, { "name": "DatabaseStore", "link": "DatabaseStore.html" }, { "name": "DatabaseView", "link": "DatabaseView.html" }, { "name": "Matcher", "link": "Matcher.html" }, { "name": "ModelQuery", "link": "ModelQuery.html" }, { "name": "SortOrder", "link": "SortOrder.html" } ] }, { "name": "Drafts", "items": [ { "name": "DraftChangeSet", "link": "DraftChangeSet.html" }, { "name": "DraftStore", "link": "DraftStore.html" }, { "name": "DraftStoreExtension", "link": "DraftStoreExtension.html" }, { "name": "DraftStoreProxy", "link": "DraftStoreProxy.html" } ] }, { "name": "Atom", "items": [ { "name": "Clipboard", "link": "Clipboard.html" }, { "name": "Color", "link": "Color.html" }, { "name": "CommandRegistry", "link": "CommandRegistry.html" }, { "name": "MenuManager", "link": "MenuManager.html" }, { "name": "PackageManager", "link": "PackageManager.html" }, { "name": "ScopeDescriptor", "link": "ScopeDescriptor.html" }, { "name": "StyleManager", "link": "StyleManager.html" }, { "name": "ThemeManager", "link": "ThemeManager.html" } ] } ] } ] }