diff --git a/build/Gruntfile.coffee b/build/Gruntfile.coffee index ac1faf873..418119690 100644 --- a/build/Gruntfile.coffee +++ b/build/Gruntfile.coffee @@ -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) diff --git a/build/tasks/docs-task.coffee b/build/tasks/docs-task.coffee index 2e3bf1262..27ebb1d59 100644 --- a/build/tasks/docs-task.coffee +++ b/build/tasks/docs-task.coffee @@ -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], "#{label}") + 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, "#{label}") + 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") diff --git a/docs-templates/_footer.html b/docs-templates/_footer.html new file mode 100644 index 000000000..f2c77e8af --- /dev/null +++ b/docs-templates/_footer.html @@ -0,0 +1,11 @@ + + + + + + diff --git a/docs-templates/_header.html b/docs-templates/_header.html new file mode 100644 index 000000000..9cfc10ee2 --- /dev/null +++ b/docs-templates/_header.html @@ -0,0 +1,17 @@ + + + +Nylas Mail — {{name}} + + + + + + + +
diff --git a/docs-templates/_sidebar.html b/docs-templates/_sidebar.html new file mode 100644 index 000000000..e51312674 --- /dev/null +++ b/docs-templates/_sidebar.html @@ -0,0 +1,3 @@ +{{#each sidebar.sections}} + {{>_sidebarSection}} +{{/each}} diff --git a/docs-templates/_sidebarSection.html b/docs-templates/_sidebarSection.html new file mode 100644 index 000000000..a129901fb --- /dev/null +++ b/docs-templates/_sidebarSection.html @@ -0,0 +1,10 @@ +
{{name}}
+ diff --git a/docs-templates/article.html b/docs-templates/article.html new file mode 100644 index 000000000..49e6c6f67 --- /dev/null +++ b/docs-templates/article.html @@ -0,0 +1,15 @@ +{{>_header}} + +{{#if meta.TitleHidden}} +{{else}} +
{{meta.title}}
+{{/if}} + + +
+{{{html}}} +
+ +{{>_footer}} diff --git a/docs-templates/class.html b/docs-templates/class.html index fbe15b24c..7fd6bc196 100644 --- a/docs-templates/class.html +++ b/docs-templates/class.html @@ -1,3 +1,5 @@ +{{>_header}} +
{{name}} {{#if documentation.superClass}} @@ -5,44 +7,51 @@ {{/if}}
- -

Summary

- -
-

{{{documentation.description}}}

+ - +
+

Summary

+ +
+

{{{documentation.description}}}

+
+ +
    + {{#each documentation.sections}} +
  • {{name}}
  • + {{/each}} +
-{{#if documentation.classProperties.length}} -

Class Properties

+ {{#if documentation.classProperties.length}} +

Class Properties

- {{#each documentation.classProperties}} - {{>_property}} - {{/each}} + {{#each documentation.classProperties}} + {{>_property}} + {{/each}} -{{/if}} + {{/if}} -{{#if documentation.classMethods.length}} -

Class Methods

+ {{#if documentation.classMethods.length}} +

Class Methods

- {{#each documentation.classMethods}} - {{>_function}} - {{/each}} + {{#each documentation.classMethods}} + {{>_function}} + {{/each}} -{{/if}} + {{/if}} -{{#if documentation.instanceMethods.length}} -

Instance Methods

+ {{#if documentation.instanceMethods.length}} +

Instance Methods

- {{#each documentation.instanceMethods}} - {{>_function}} - {{/each}} + {{#each documentation.instanceMethods}} + {{>_function}} + {{/each}} -{{/if}} + {{/if}} +
+ +{{>_footer}} diff --git a/docs/Architecture.md b/docs/Architecture.md new file mode 100644 index 000000000..1b9c62078 --- /dev/null +++ b/docs/Architecture.md @@ -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}. diff --git a/docs/Database.md b/docs/Database.md new file mode 100644 index 000000000..9628d2a61 --- /dev/null +++ b/docs/Database.md @@ -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: + + + +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 diff --git a/docs/Debugging.md b/docs/Debugging.md new file mode 100644 index 000000000..f10af8639 --- /dev/null +++ b/docs/Debugging.md @@ -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! diff --git a/docs/DraftStoreExtensions.md b/docs/DraftStoreExtensions.md new file mode 100644 index 000000000..5458ddcca --- /dev/null +++ b/docs/DraftStoreExtensions.md @@ -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 += "
This email \ + contains competitor's product names \ + or trademarks used in context." + session.changes.add(body: bodyWithWarning) +``` diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 000000000..f0c276fc3 --- /dev/null +++ b/docs/FAQ.md @@ -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//"}' 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. diff --git a/docs/First steps.md b/docs/First steps.md new file mode 100644 index 000000000..6ea3bda7d --- /dev/null +++ b/docs/First steps.md @@ -0,0 +1,337 @@ +--- +Title: First Steps +TitleHidden: True +Section: Getting Started +Order: 2 +--- + +
+
+

Start building on top of Nylas in minutes:

+

1
Install Nylas Mail

+

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

+
+
+ +
+
+

2
Start a Package

+

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 Create a Package... and name your new package.

+
+
+ +
+
+ +
+
+

3
See it in Action

+

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 Nylas Mail.

+
+
+ +
+ + + +
+ +
+
+

A
Explore the source

+ +

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.

+
+
+

B
Run the specs

+ +

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

+
+
+ + + + + +

Step 2: Building your first package

+ +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: + + + +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: => +
+

Hi, {@state.contact.name} ({@state.contact.email})!

+
+``` + +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 => +
+ {md5(@state.contact.email)} +
+``` + +> 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): + + + +### Let's Render! + +Turning the MD5 hash into a Gravatar image is simple. We need to add an `` tag to the rendered HTML: + +```coffee +_renderContent => +
+ +
+``` + +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. + + + + +### 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: + +
stylesheets/main.less
+```css +.gravatar { + border-radius: 45px; + border: 2px solid #ccc; +} +``` + +
lib/my-message-sidebar.cjsx
+```coffee +_renderContent => + gravatar = "http://www.gravatar.com/avatar/" + md5(@state.contact.email) + +
+ +
+``` + +> React Tip: Remember to use DOM property names, i.e. `className` instead of `class`. + +You'll see these styles reflected in your sidebar. + + + +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. + +
+ +

Continue this guide: adding a data store to your package

+ +
+ + +

Step 3: Adding a Data Store

+ +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: + +
lib/github-user-store.coffee
+```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: => + GitHub +``` + +## 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). diff --git a/docs/Index.md b/docs/Index.md new file mode 100644 index 000000000..fe195ea43 --- /dev/null +++ b/docs/Index.md @@ -0,0 +1,68 @@ +--- +Title: Welcome +TitleHidden: true +Section: Getting Started +Order: 1 +--- + + +

Nylas Package API

+

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

+ + + + + +
+ +

Installing Nylas Mail

+

+Nylas Mail is available for Mac, Windows, and Linux. Download the latest build for your platform below: +

+ + +
+ +

Package Architecture

+

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

+ + +
+ +

Dive Deeper

+ + + +
+ +

Debugging Packages

+

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

+ + +
+

Questions?

+

+Need help? Check out the [FAQ](./FAQ.html) or post a question in the [Nylas Mail Facebook Group](facebook.com/groups/nylas.mail) +

+ +
diff --git a/docs/InterfaceConcepts.md b/docs/InterfaceConcepts.md new file mode 100644 index 000000000..e2b403273 --- /dev/null +++ b/docs/InterfaceConcepts.md @@ -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. + + + +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. + + + +```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. + + + +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. + + + +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: + +- `.Toolbar`: This component will always appear in the toolbar above the column named ``. + + (Example: Compose button which appears above the Left Sidebar column, regardless of what else is there.) + +- `.Toolbar`: This component will appear in the toolbar above ``. + + (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) diff --git a/docs/Overview.md b/docs/Overview.md new file mode 100644 index 000000000..90309d2b4 --- /dev/null +++ b/docs/Overview.md @@ -0,0 +1,62 @@ + +

Nylas SDK

+

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.
+Get Started +

+ + + + + +
+ +

Installing Nylas Mail

+

+Nylas Mail is available for Mac, Windows, and Linux. Download the latest build for your platform below: +

+ + +
+ +

Package Architecture

+

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

+ + +
+ +

Dive Deeper

+ + + +
+ +

Debugging Packages

+

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

+ + +
+

Questions?

+

+Need help? Check out the FAQ or post a question in the slack channel. +

+ +
diff --git a/docs/PackageOverview.md b/docs/PackageOverview.md new file mode 100644 index 000000000..38ef07c74 --- /dev/null +++ b/docs/PackageOverview.md @@ -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: + +``` + + +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. diff --git a/docs/React.md b/docs/React.md new file mode 100644 index 000000000..39fd361b9 --- /dev/null +++ b/docs/React.md @@ -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. + +

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.

+ + +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 `` 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 `` and takes function props for tokenizing input values and displaying autocompletion suggestions. + +- **{EventedIFrame}**: Replacement for the standard `