QuantumJS
Edit Page
quantum-core
The CLI and low level apis for parsing, manipulating AST, and watching quantum source files.
About
The core quantum module (quantum-core) consists of a cli (command line interface), a parser for the markup language, a selection api for working with the parsed AST (abstract syntax tree) and an api for watching quantum files for changes.
This is module contains all the low level stuff that makes everything else work.
Command Line Interface
The best way to use quantum is with the command line interface (CLI). There are more details on how to use it on these pages:
The CLI is bundled with this module - so if you install this globally, you should have access to the quantum command. Or you can install it for a npm project and then your npm scripts will have access to the quantum command.
One way to find out more about the cli is to run quantum help
.
Api
Note
Most of this page goes into low level apis that you most likely won't have to worry about if you are just using quantum as a tool. This page documents some of the parts of quantum that are interesting when developing your own entity transforms.
Below are all the properties of the object returned from require('quantum-core'). For information about different versions, see the Changelog
Prototypes
Fileadded
An object which represents a html page, css file or javascript file (or any other file type that a transform decides to export)
Constructors
FileoptionsObject
Creates a new file. The preferred method for creating a file is to use the file.clone() method of an existing file.
Arguments
options
The options to use when creating the new file
Properties
contentAny
Contains the contents of the file - this depends on the type of the file. So this could be a string, or could be quantum AST, or could be virtual dom. It depends on which bit of the pipeline you are in.
errorsArray[Object]
An array of objects that describe errors that occurred when transforming the page. New errors can be added with the error() method.
Errors are issued when the page is not able to be rendered for some reason.
The error objects take the following form:
{
  module: 'quantum-core',
  problem: 'Parse error: unexpected dedent',
  resolution: 'Fix indentation'
}
A FileInfo instance which contains filename information for this file, including where the file was read from, and where it is going to be written to once fully transformed.
This property can be manipulated by FileTransform functions (for instance in quantum-html using the htmlRenamer transform)
meta
An object that can contain extra information that a file transform wants to export. For example, the version transform adds the current `version` to this object after processing the file - so that other transforms can make use of that information.
This property should not be used in any quantum libraries and is designed to be used in custom entity transforms.
warningsArray[Object]
An array of objects that describe warnings for issues found on the page. New warnings can be added with the warning() method.
Warnings are issued when the page still is able to be rendered, but likely has some issues with it, like misuse of an entity that will cause content not to appear as expected.
The warning objects take the following form:
{
  module: 'quantum-changelog',
  problem: 'An @updated entity found with description content, but no @description section was found',
  resolution: 'use a @description block inside the @updated tag'
}
Properties
contentAny
Contains the contents of the file - this depends on the type of the file. So this could be a string, or could be quantum AST, or could be virtual dom. It depends on which bit of the pipeline you are in.
errorsArray[Object]
An array of objects that describe errors that occurred when transforming the page. New errors can be added with the error() method.
Errors are issued when the page is not able to be rendered for some reason.
The error objects take the following form:
{
  module: 'quantum-core',
  problem: 'Parse error: unexpected dedent',
  resolution: 'Fix indentation'
}
A FileInfo instance which contains filename information for this file, including where the file was read from, and where it is going to be written to once fully transformed.
This property can be manipulated by FileTransform functions (for instance in quantum-html using the htmlRenamer transform)
meta
An object that can contain extra information that a file transform wants to export. For example, the version transform adds the current `version` to this object after processing the file - so that other transforms can make use of that information.
This property should not be used in any quantum libraries and is designed to be used in custom entity transforms.
warningsArray[Object]
An array of objects that describe warnings for issues found on the page. New warnings can be added with the warning() method.
Warnings are issued when the page still is able to be rendered, but likely has some issues with it, like misuse of an entity that will cause content not to appear as expected.
The warning objects take the following form:
{
  module: 'quantum-changelog',
  problem: 'An @updated entity found with description content, but no @description section was found',
  resolution: 'use a @description block inside the @updated tag'
}
Methods
clonechangesObjectFile
Creates a new File instance with some or all of the properties changed.
Arguments
changes
Provide any properties to override
Properties
contentAny
Contains the contents of the file - this depends on the type of the file. So this could be a string, or could be quantum AST, or could be virtual dom. It depends on which bit of the pipeline you are in.
errorsArray[Object]
An array of objects that describe errors that occurred when transforming the page. New errors can be added with the error() method.
Errors are issued when the page is not able to be rendered for some reason.
The error objects take the following form:
{
  module: 'quantum-core',
  problem: 'Parse error: unexpected dedent',
  resolution: 'Fix indentation'
}
A FileInfo instance which contains filename information for this file, including where the file was read from, and where it is going to be written to once fully transformed.
This property can be manipulated by FileTransform functions (for instance in quantum-html using the htmlRenamer transform)
meta
An object that can contain extra information that a file transform wants to export. For example, the version transform adds the current `version` to this object after processing the file - so that other transforms can make use of that information.
This property should not be used in any quantum libraries and is designed to be used in custom entity transforms.
warningsArray[Object]
An array of objects that describe warnings for issues found on the page. New warnings can be added with the warning() method.
Warnings are issued when the page still is able to be rendered, but likely has some issues with it, like misuse of an entity that will cause content not to appear as expected.
The warning objects take the following form:
{
  module: 'quantum-changelog',
  problem: 'An @updated entity found with description content, but no @description section was found',
  resolution: 'use a @description block inside the @updated tag'
}
Returns
A new File instance with the specified properties changed.
errorerrorObjectFile
Errors are issued when the page is not able to be rendered for some reason.
The error object takes the following form:
{
  module: 'quantum-core',
  problem: 'Parse error: unexpected dedent',
  resolution: 'Fix indentation'
}
Arguments
error
Properties
moduleString
The module that raised the error
problemString
A description of the issue
resolutionString
How to fix the issue
Returns
This File instance
warningwarningObjectFile
Warnings are issued when the page still is able to be rendered, but likely has some issues with it, like misuse of an entity that will cause content not to appear as expected.
The warning object takes the following form:
{
  module: 'quantum-changelog',
  problem: 'An @updated entity found with description content, but no @description section was found',
  resolution: 'use a @description block inside the @updated tag'
}
Arguments
warning
Properties
moduleString
The module that raised the warning
problemString
A description of the issue
resolutionString
How to fix the issue
Returns
This File instance
FileInfoadded
An object which holds filename information. Chances are this object is something you'll never have to use, unless writing a file transform which needs to modify the output filename.
Every File instance has a info property, which is one of these guys.
Creating a FileInfo instance
const quantum = require('quantum-core')

const info = new quantum.FileInfo({
  src: "src/content/about.um",
  resolved: "about.um",
  base: "src/content",
  dest: "target/about.um",
  destBase: "target",
  watch: true
})
Constructors
FileInfooptionsObject
Constructs a new FileInfo
Arguments
options
An object with the properties to populate the FileInfo with
Properties
baseString
The base directory used to extract the resolved filename
destString
The destBase directory + the resolved filename
destBaseString
The directory where files are output to
resolvedString
The filename of the source file, relative the the base directory. Can be specified relative to the cwd or as an absolute path
The filename of the source file for this page. Can be specified relative to the cwd or as an absolute path
watchBoolean
Whether or not this file should be watched for changes. This is only used by the cli when in watch mode.
Properties
baseString
The base directory used to extract the resolved filename
destString
The destBase directory + the resolved filename
destBaseString
The directory where files are output to
resolvedString
The filename of the source file, relative the the base directory. Can be specified relative to the cwd or as an absolute path
The filename of the source file for this page. Can be specified relative to the cwd or as an absolute path
watchBoolean
Whether or not this file should be watched for changes. This is only used by the cli when in watch mode.
Methods
clonechangesObjectFileInfo
Creates a clone of this FileInfo, with some or all of the properties replaced. The value returned from this function is a new FileInfo instance.
const quantum = require('quantum-core')

const info = new quantum.FileInfo({
  src: "src/content/about.um",
  resolved: "about.um",
  base: "src/content",
  dest: "target/about.um",
  destBase: "target",
  watch: true
})

const newFileInfo = info.clone({
  watch: false,
  dest: "target/about/index.html"
})

// newFileInfo.src === "src/content/about.um",
// newFileInfo.resolved === "about.um",
// newFileInfo.base === "src/content",
// newFileInfo.dest === "target/about/index.html",
// newFileInfo.destBase === "target",
// newFileInfo.watch === false
Arguments
changes
Provide any properties to override
Properties
baseString
The base directory used to extract the resolved filename
destString
The destBase directory + the resolved filename
destBaseString
The directory where files are output to
resolvedString
The filename of the source file, relative the the base directory. Can be specified relative to the cwd or as an absolute path
The filename of the source file for this page. Can be specified relative to the cwd or as an absolute path
watchBoolean
Whether or not this file should be watched for changes. This is only used by the cli when in watch mode.
Returns
A new instance with the changes applied.
withExtensionextensionStringFileInfo
Returns a new FileInfo instance with the extension changed for the dest property:
Example
const quantum = require('quantum-core')

const info = new quantum.FileInfo({
  src: "src/content/about.um",
  resolved: "about.um",
  base: "src/content",
  dest: "target/about.um",
  destBase: "target",
  watch: true
})

const newFileInfo = info.withExtension('.html')

console.log(newFileInfo.dest) // prints "target/about.html"
Arguments
extensionString
The new extension the FileInfo should have. This should include the preceding period:
info.withExtension('.html') // This is correct
info.withExtension('html')  // This is (probably) not correct
Returns
A new FileInfo instance with the updated dest property.
Selectionadded
An object that wraps an entity. This object has useful methods for extracting information from, and updating entities.
Do not create one of these directly; instead use quantum.select()
Example
const quantum = require('quantum-core')

const entity = {
  type: 'fruit',
  params: ['apple'],
  content: []
}

const sel = quantum.select(entity)
// sel is an instance of Selection
Methods
Adds a new entry to the entities content array
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)
selection.content() // ['Blah blah blah']

selection.add('Second line')
selection.content() // ['Blah blah blah', 'Second line']

// Entities can also be added
selection.add({
  type: 'tagline',
  params: [],
  content: []
})
Arguments
contentString / Entity
The content to add to the end of the content array. Can either be a string, or an AST entity object.
Returns
This Selection instance
addAftercontentString / EntitySelection
If this selection has a parent, this method can be used to add content after this one in the parent's content.
Example

const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    {
      type: "child",
      params: [],
      content: []
},
"End content"
]
}

const selection = quantum.select(entity)
selection.content()
/*
  [
    {
      type: "child",
      params: [],
      content: []
},
"End content"
]
*/

const child = selection.select('child')
child.addAfter('New line')

selection.content()
/*
  [
    {
      type: "child",
      params: [],
      content: []
},
"New line",
"End content"
]
*/
Arguments
contentString / Entity
The content to add to the end of the content array. Can either be a string, or an AST entity object.
Returns
This Selection instance
addParamparamStringSelection
Adds a new parameter to the end of the parameters list
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

selection.params() // ['param1', 'param2']

selection.addParam(['param3'])
selection.params() // ['param1', 'param2', 'param3']
Arguments
paramString
The parameter value to add
Returns
This Selection instance
contentSelection
Gets the content of this entity as an array
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Blah blah blah'
]
}
const selection = quantum.select(entity) selection.content() // ['Blah blah blah']
Returns
This Selection instance
contentcontentArray[String / Entity]Selection
Sets the content of this entity as an array
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)
selection.content() // ['Blah blah blah']

selection.content(['New Content', 'Second line'])
selection.content() // ['New Content', 'Second line']
Arguments
contentArray[String / Entity]
The content to give the selected entity
Returns
This Selection instance
Gets the parameters as a string
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Line 1',
    'Line 2'
]
}

const selection = quantum.select(entity)

selection.cs() // 'Line1\nLine2'
Returns
The content array joined with newline characters into a single string. Any entity objects will be ignored.
Sets the content as a string
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Line 1',
    'Line 2'
]
}

const selection = quantum.select(entity)

selection.cs() // 'Line1\nLine2'

selection.cs('Line1\nLine2\nLine3')
selection.content() // ['Line 1', 'Line 2', 'Line 3']
Arguments
A string that should be split on new lines, the result of which will become the content array for the entity.
Returns
The content joined with new line characters into a single string
entityEntity
Returns the underlying entity this Selection wraps
Example
const quantum = require('quantum-core')

const basketEntity = {
  type: 'basket',
  params: [],
  content: [
    {
      type: 'fruit',
      params: ['lemon'],
      content: []
}
]
}

const selection = quantum.select(basketEntity)

selection.entity() // returns basketEntity
Returns
The AST entity this selection wraps
Creates a new Selection with some of the child entities filtered out. Only entities with the types provided are kept.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: [],
  content: [
    {
      type: 'childA',
      params: [],
      content: []
},
{
  type: 'childA',
  params: [],
  content: []
},
{
  type: 'childB',
  params: [],
  content: []
},
{
  type: 'childC',
  params: [],
  content: []
}
]
}

const selection = quantum.select(entity)
const filteredSelection = selection.filter(['childA', 'childB'])

// filteredSelection does not have 'childC' as a child
Arguments
The children types to keep.
Returns
A new Selection that only has childen of the types specified.
filtertypeStringSelection
Creates a new Selection with some of the child entities filtered out. Only entities with the type provided are kept.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: [],
  content: [
    {
      type: 'childA',
      params: [],
      content: []
},
{
  type: 'childA',
  params: [],
  content: []
},
{
  type: 'childB',
  params: [],
  content: []
},
{
  type: 'childC',
  params: [],
  content: []
}
]
}

const selection = quantum.select(entity)
const filteredSelection = selection.filter('childA')

// filteredSelection does not have 'childB' or 'childC' type entities as
// children
Arguments
typeString
The type of children to keep.
Returns
A new Selection that only has childen of the type specified.
filtertypeLookupFunctionSelection
Creates a new Selection with some of the child entities filtered out. Only entities with the types provided are kept.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: [],
  content: [
    {
      type: 'childA',
      params: [],
      content: []
},
{
  type: 'childA',
  params: [],
  content: []
},
{
  type: 'childB',
  params: [],
  content: []
},
{
  type: 'childC',
  params: [],
  content: []
}
]
}

const selection = quantum.select(entity)
const filteredSelection = selection.filter(entity => entity.type !== 'childA')

// filteredSelection does not have any 'childA' type children
Arguments
typeLookupentityEntityBoolean
An indicator function which should return true for the childen to keep in the filtered selection, false for children that should be excluded.
Arguments
entityEntity
The child entity to check
Returns
Return true to keep the child in the filtered selection, false to exclude.
Returns
A new filtered Selection that only has some of the children.
hastypeStringoptionsObjectBoolean
Checks if an entity has a child entity of a particular type
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    {
      type: 'child1',
      params: [],
      content: []
},
{
  type: 'child2',
  params: [],
  content: [
    type: 'child3',
    params: [],
    content: [

    ]
]
}
]
}

const selection = quantum.select(entity)

selection.has('child1') // true
selection.has('child2') // true
selection.has('child3') // false
selection.has('child3', {recursive: true}) // true
selection.has('child4', {recursive: true}) // false
Arguments
typeString
The entity type to look for
options
Properties
recursiveBoolean
true to do a recursive search down the tree for the type
Default: false
Returns
Returns true if the selected entity has a child entity of type type
hasContentBoolean
Returns true if the selected entity has any content
Example
const quantum = require('quantum-core')

const entity1 = {
  type: 'example',
  params: [],
  content: []
}

const entity2 = {
  type: 'example',
  params: [],
  content: [
    'Line 1',
    {
      type: 'child',
      params: [],
      content: []
}
]
}

const selection1 = quantum.select(entity1)
selection1.hasContent() // false

const selection2 = quantum.select(entity2)
selection2.hasContent() // true
Returns
Returns true if the entity has content, false otherwise
hasParamsBoolean
Returns true if the selected entity has any parameters
Example
const quantum = require('quantum-core')

const entity1 = {
  type: 'example',
  params: [],
  content: []
}

const entity2 = {
  type: 'example',
  params: ['param1', 'param2'],
  content: []
}

const selection1 = quantum.select(entity1)
selection1.hasParams() // false

const selection2 = quantum.select(entity2)
selection2.hasParams() // true
Returns
Returns true if the entity has 1 or more parameters, false otherwise
isEmptyBoolean
Returns true if the selected component has either no content or all the content line are empty strings.
Example
const quantum = require('quantum-core')

const entity1 = {
  type: 'example',
  params: [],
  content: []
}

const entity2 = {
  type: 'example',
  params: [],
  content: [
    "",
    ""
]
}

const entity3 = {
  type: 'example',
  params: [],
  content: [
    'Line 1',
    {
      type: 'child',
      params: [],
      content: []
}
]
}

const selection1 = quantum.select(entity1)
selection1.isEmpty() // true

const selection2 = quantum.select(entity2)
selection2.isEmpty() // true

const selection3 = quantum.select(entity3)
selection3.isEmpty() // false
Returns
Returns true if there is no content, the content is made up of empty strings.
paramindexNumberString
Gets the nth entity parameter.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'blogEntry',
  params: ['10/12/17'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

selection.param(0) // '10/12/17'
selection.param(1) // undefined
Arguments
indexNumber
The index of the parameter to get
Returns
The parameter that was as position index. Will be undefined if an out of bounds parameter is accessed.
paramindexNumberparamStringSelection
Sets the nth entity parameter.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'blogEntry',
  params: ['10/12/17'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

// get the current parameter value
selection.param(0) // '10/12/17'

// set the parameter and observe the change
selection.param(0, "11/12/17")
selection.param(0) // "11/12/17"
Arguments
indexNumber
The index of the parameter to get
paramString
The parameter value to set
Returns
This Selection instance
paramsArray[String]
Gets the parameters as an array.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

selection.params() // ['param1', 'param2']
Returns
The parameters of the selected entity
paramsparametersArray[String]Selection
Sets the parameters as an array.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

selection.params() // ['param1', 'param2']

selection.params(['p1', 'p2'])
selection.params() // ['p1', 'p2']
Arguments
parametersArray[String]
The parameters to set for the entity
Returns
This Selection instance
parentSelection
Gets the parent entity wrapped in a selection. This only works if Selection::select has been used to select 'down' the tree:
Example
const quantum = require('quantum-core')

const entity = {
  type: 'parent',
  params: [],
  content: [
    {
      type: 'childExample',
      params: [],
      content: [

      ]
}
]
}

const parentSelection = quantum.select(entity)
const childSelection = quantum.select('childExample')

parentSelection.parent() // undefined
childSelection.parent() // == parentSelection
Returns
Returns the parent Selection if it exists, otherwise undefined
Sets the parameters as a string
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

selection.ps() // param1 param2

selection.ps('p1 p2')
selection.params() // ['p1', 'p2']
Arguments
A string that should be split on spaces, the result of which will become the params array for the entity.
Returns
The parameters joined with spaces into a single string
Gets the parameters as a string
Example
const quantum = require('quantum-core')

const entity = {
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

selection.ps() // param1 param2
Returns
The parameters joined with spaces into a single string
remove
Removes the selected entity from its parent.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'parent',
  params: [],
  content: [
    {
      type: 'childExample',
      params: [],
      content: [

      ]
}
]
}

const parentSelection = quantum.select(entity)
const childSelection = quantum.select('childExample')

childSelection.remove()

parentSelection.entity()
/*
  {
    type: 'parent',
    params: [],
    content: []
}
*/
removeAllChildrenOfTypetypeStringoptionsObjectArray[Selection]
Removes all the children of the type provided from the selected entity.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'parent',
  params: [],
  content: [
    {
      type: 'child1',
      params: [],
      content: []
},
{
  type: 'child1',
  params: [],
  content: []
},
{
  type: 'child2',
  params: [],
  content: []
}
]
}

const parentSelection = quantum.select(entity)
parentSelection.removeAllChildrenOfType('child1') // removes all the child1 entities

parentSelection.entity()
/*
  {
    type: 'parent',
    params: [],
    content: [
      {
        type: 'child2',
        params: [],
        content: []
}
]
}
*/
Arguments
typeString
The entity type to remove
options
Properties
recursiveBoolean
Set to true to recurse down the children to find
Default: false
Returns
An array of the removed entities wrapped in Selection
removeAllChildrenOfTypetypesArray[String]optionsObjectArray[Selection]
Removes all the children of the types provided from the selected entity.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'parent',
  params: [],
  content: [
    {
      type: 'child1',
      params: [],
      content: []
},
{
  type: 'child1',
  params: [],
  content: []
},
{
  type: 'child2',
  params: [],
  content: []
}
]
}

const parentSelection = quantum.select(entity)

// removes the first child1 type entity and the first child2 type entity
parentSelection.removeAllChildrenOfType(['child1', 'child2'])

parentSelection.entity()
/*
  {
    type: 'parent',
    params: [],
    content: []
}
*/
Arguments
The entity types to remove
options
Properties
recursiveBoolean
Set to true to recurse down the children to find
Default: false
Returns
An array of the removed entities wrapped in Selection s
removeChildchildEntityEntityBoolean
Removes a child entity from this entity
Example
const quantum = require('quantum-core')

const entity = {
  type: 'parent',
  params: [],
  content: [
    {
      type: 'childExample',
      params: [],
      content: []
}
]
}

const parentSelection = quantum.select(entity)
const childEntity = entity.content[0]

parentSelection.removeChild(childEntity) // removes the child and returns true
Arguments
childEntityEntity
The entity to remove from the children
Returns
true if the child was removed, false if it was not a child and could not be removed.
removeChildOfTypetypeStringoptionsObjectSelection
Removes the first child of the type provided from the selected entity.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'parent',
  params: [],
  content: [
    {
      type: 'child1',
      params: [],
      content: []
},
{
  type: 'child1',
  params: [],
  content: []
},
{
  type: 'child2',
  params: [],
  content: []
}
]
}

const parentSelection = quantum.select(entity)
parentSelection.removeChildOfType('child1') // removes the first child1 type entity

parentSelection.entity()
/*
  {
    type: 'parent',
    params: [],
    content: [
      {
        type: 'child1',
        params: [],
        content: []
},
{
  type: 'child2',
  params: [],
  content: []
}
]
}
*/
Arguments
typeString
The entity type to remove
options
Properties
recursiveBoolean
Set to true to recurse down the children to find
Default: false
Returns
The removed entity wraped in a Selection, or undefined if nothing was removed.
removeChildOfTypetypesArray[String]optionsObjectArray[Selection]
Removes the first child of each of the types provided from the selected entity.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'parent',
  params: [],
  content: [
    {
      type: 'child1',
      params: [],
      content: []
},
{
  type: 'child1',
  params: [],
  content: []
},
{
  type: 'child2',
  params: [],
  content: []
}
]
}

const parentSelection = quantum.select(entity)

// removes the first child1 type entity and the first child2 type entity
parentSelection.removeChildOfType(['child1', 'child2'])

parentSelection.entity()
/*
  {
    type: 'parent',
    params: [],
    content: [
      {
        type: 'child1',
        params: [],
        content: []
}
]
}
*/
Arguments
The entity types to remove
options
Properties
recursiveBoolean
Set to true to recurse down the children to find
Default: false
Returns
An array containing each removed entity wrapped in a Selection
selecttypeStringoptionsObjectSelection
Selects a child entity from the selected entity.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'parent',
  params: [],
  content: [
    {
      type: 'childExample',
      params: [],
      content: []
}
]
}

const selection = quantum.select(entity)
selection.select('childExample') // returns a new selection wrapping the 'childExample' entity
Arguments
typeString
The type of entity to select
options
Properties
recursiveBoolean
Set to true to search recursively down the child entities to search for this type. It will do a depth first search.
Default: false
requiredBoolean
Set to true to throw an error when this type is not found
Default: false
Returns
Returns a new selection that wraps the first entity of type type that was found. If there was no entity of type type found, a Selection will still be returned, but will contain an empty entity that looks like this
{
  type: '',
  params: [],
  content: []
}
selectAlltypeStringoptionsObjectArray[Selection]
Selects all children of a particular type.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'recipe',
  params: ['Omelette'],
  content: [
    {
      type: 'ingredient',
      params: ['Eggs'],
      content: []
},
{
  type: 'ingredient',
  params: ['Milk'],
  content: []
},
{
  type: 'ingredient',
  params: ['Salt'],
  content: []
},
{
  type: 'ingredient',
  params: ['Pepper'],
  content: []
}
]
}

const selection = quantum.select(entity)
const ingredients = selection.selectAll('ingredient') // returns an array of 4 Selections
Arguments
typeString
The type of entity to select
options
Properties
recursiveBoolean
Set to true to search recursively down the child entities to search for this type. It will do a depth first search.
Default: false
requiredBoolean
Set to true to throw an error when this type is not found
Default: false
Returns
Returns the entities that were found, each wraped in a Selection If no results are found an empty array will be returned.
selectAlltypesArray[String]optionsObjectArray[Selection]
Selects all children of a particular type.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'recipe',
  params: ['Omelette'],
  content: [
    {
      type: 'ingredient',
      params: ['Eggs'],
      content: []
},
{
  type: 'ingredient',
  params: ['Milk'],
  content: []
},
{
  type: 'ingredient',
  params: ['Salt'],
  content: []
},
{
  type: 'ingredient',
  params: ['Pepper'],
  content: []
},
{
  type: 'step',
  params: [],
  content: ['Beat eggs and milk to gether in a bowl and add salt and pepper']
},
{
  type: 'step',
  params: [],
  content: ['Melt some butter in a frying pan']
},
{
  type: 'step',
  params: [],
  content: ['Pour egg mixture into the frying pan and cook.']
}
]
}

const selection = quantum.select(entity)
const ingredients = selection.selectAll('ingredient') // returns an array of 4 Selections
const steps = selection.selectAll('step') // returns an array of 3 Selections
const ingredientsAndSteps = selection.selectAll(['ingredient', 'step']) // returns an array of 7 Selections
Arguments
The types of entities to select
options
Properties
recursiveBoolean
Set to true to search recursively down the child entities to search for this type. It will do a depth first search.
Default: false
requiredBoolean
Set to true to throw an error when no results are found
Default: false
Returns
Returns the entities that were found, each wraped in a Selection If no results are found an empty array will be returned.
selectUpwardstypeStringSelection
Traverses up the tree until it finds an entity of type type. If no entity is found, undefined will be returned.
Example
const quantum = require('quantum-core')

const entity = {
  type: 'basket',
  params: [],
  content: [
    {
      type: 'item',
      params: ['lemon'],
      content: [
        {
          type: 'price',
          params: ['1.20'],
          content: []
}
]
}
]
}

const selection = quantum.select(entity)
const priceSelection = selection.select('item').select('price')

// returns the basket entity wrapped in a Selection
priceSelection.selectUpwards('basket')

// returns the item entity wrapped in a Selection
priceSelection.selectUpwards('item')

// returns an empty selection - there is no parent entity of type 'trolley'
priceSelection.selectUpwards('trolley')
Arguments
typeString
The entity type to look for.
Returns
Returns a new selection that wraps the parent entity of type type that was found. If there was no entity of type type found, a Selection will still be returned, but will contain an empty entity that looks like this
{
  type: '',
  params: [],
  content: []
}
transformtransformerFunctionArray[Any] / Promise[Array[Any]]
Transforms the selected entity using a transformer function. It is rare that you should need to use this method.
const quantum = require('quantum-core')

const entity = {
  type: 'basket',
  params: [],
  content: [
    {
      type: 'item',
      params: ['lemons'],
      content: []
},
{
  type: 'item',
  params: ['apples'],
  content: []
},
{
  type: 'item',
  params: ['limes'],
  content: []
}
]
}

const selection = quantum.select(entity)

selection.transform((itemSelection) => {
    return dom.create('div')
      .class('basket-item')
      .text(itemSelection.ps())
})
Arguments
transformerselectionSelection / StringAny / Promise[Any]
A function that transforms a piece of text, or an entity into a new format. Normally this is outputs pieces of quantum dom.
Arguments
selectionSelection / String
The item to transform
Returns
Any / Promise[Any]
The transformed content.
Returns
Array[Any] / Promise[Array[Any]]
The transformed content for the entire entity.
transformContextcontextObjectSelection
Sets an object that can be used to pass extra information to another transformer that this seletion is passed to.
If writing a plugin for quantum, be careful about how this is used. It should never be used for the public api - it should only be used to pass information around within your plugin.
const quantum = require('quantum-core')

const entity = {
  type: 'basket',
  params: [],
  content: [
    {
      type: 'item',
      params: ['lemons'],
      content: []
}
]
}

const selection = quantum.select(entity)

selection.transformContext({
  someInformation: "somthing useful"
})

selection.transformContext() // returns { someInformation: "somthing useful" }
Arguments
context
The context object to store on the selection.
Returns
transformContextObject
Get the context object, which is sometimes used to pass extra information to another transformer by storing it on this Selection. If writing a plugin for quantum, be careful about how this is used. It should never be used for the public api - it should only be used to pass information around within your plugin.
const quantum = require('quantum-core')

const entity = {
  type: 'basket',
  params: [],
  content: [
    {
      type: 'item',
      params: ['lemons'],
      content: []
}
]
}

const selection = quantum.select(entity)

selection.transformContext({
  someInformation: "somthing useful"
})

selection.transformContext() // returns { someInformation: "somthing useful" }
Returns
Object
The context object, or undefined if it is not set.
typeString
Gets the type property from the underlying entity
Example
const quantum = require('quantum-core')

const entity = {
  type: 'blogEntry',
  params: ['10/12/17'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

console.log(selection.type()) // Prints "blogEntry"
Returns
Returns the underlying entity's type property
Sets the type property for the underlying entity
Example
const quantum = require('quantum-core')

const entity = {
  type: 'blogEntry',
  params: ['10/12/17'],
  content: [
    'Blah blah blah'
]
}

const selection = quantum.select(entity)

console.log(selection.type()) // Prints "blogEntry"
console.log(entity.type)      // Prints "blogEntry"

// Change the entity type
selection.type('myBlogEntry')

console.log(selection.type()) // Prints "myBlogEntry"
console.log(entity.type)      // Prints "myBlogEntry"
Arguments
typeString
The new type
Returns
This Selection for further chaining
WatcherextendsEventEmitteradded
An instance of one of these is returned by quantum.watcher. It provides a way to stop watching the files. Do not create one of these directly; instead use the quantum.watcher function.
Events
Emitted when a new file is added / starts being watched. The data with the event is a FileInfo instance with information about the file being watched.
changeFileInfo
Emitted when a file is changed. The data with the event is a FileInfo instance with information about the file that was changed.
removeFileInfo
Emitted when a file is removed. The data with the event is a FileInfo instance with information about the file that was removed.
Methods
Gets a list of the watched files
Returns
All the files currently being watched by this Watcher
stop
Stops watching the files
Objects
apiadded
This object exposes the functionality that the CLI provides as an api that can be called from within your own code.
The running the build() function results in the same thing as running quantum build and the watch() function builds the site and watches for changes, in the same way that quantum watch does.
Functions
buildconfigObjectPromiseadded
Build a quantum site using the config passed in.
Arguments
config
Properties
concurrencyNumberadded
How many pages that can be processed in parallel.
Default: 1
destStringadded
The target directory to output the built site files to.
Default: 'target'
fileReaderfileInfoFileInfooptionsObjectadded
The function used to load a file from disk and then convert it to a File object for use in a pipeline.
Arguments
fileInfoFileInfo
The FileInfo of the File to read.
options
The options to use when reading a file.
Properties
loader
The loader to use to read a file from disk.
resolveRootString
The path to resolve absolute files from.
Default: '.' (The current working directory)
loaderfileNameStringparentFilenameStringadded
The function to use for loading file content from disk.
Default:
function (filename) {
  return fs.readFileAsync(filename, 'utf-8')
}
Arguments
fileNameString
parentFilenameString
logLevelStringadded
The level of logging to use when running the command.
The available options are:
  • 'none'
  • 'error'
  • 'all'
Default: 'all'
loggereventObjectadded
The logger to use when building and watching files.
It will be passed an event object from different stages of the pipeline.
Arguments
event
The object describing the event to log.
Every event has a type property, the events types used in Quantum are:
  • 'header'
  • 'message'
  • 'build-page'
  • 'page-load-error'
  • 'copy-resource'
  • 'error'
  • 'end'
  • 'error'
Properties for all events
typeString
The event type. This can be used to switch the behaviour of the logger.
Properties for event type 'header'
Events that should be logged as a header, e.g. 'Building Pages'
messageString
The header message to display.
Properties for event type 'message'
Informational events, e.g. 'Starting server on http://localhost:8080'
messageString
The message to display
Properties for event type 'build-page'
Events logged when building each page included in the pipeline.
destFilesArray[File]
The list of output files, including asset files such as CSS and JS
sourceFileFile
The source used when building a file
timeTakenNumber
The time taken to build the output file(s)
Properties for event type 'page-load-error'
Events logged for each file with an error
errorError
The error that was thrown
fileInfoFileInfo
The FileInfo object for the file that is in error
Properties for event type 'copy-resource'
Event logged when copying resources to the output directory.
fileInfoFileInfo
The resource file that has been copied
timeTakenNumber
The time taken to copy the resource (in milliseconds)
Properties for event type 'error'
Events logged when there are errors in the pipeline, excluding events that have explicit event loggers (e.g. 'page-load-error')
errorError
The error that was thrown
Properties for event type 'end'
The event logged at the end of a complete pipeline.
builtCountNumber
The total number of pages built in the pipeline
timeTakenNumber
The total time taken (in milliseconds)
pagesString / Array[String] / Array[Object]added
This property should describe the files that should be processed by quantum as pages.
pipelineArray[FileTransform]added
An array of FileTransform functions that take a page as the input and return a page (or array of pages) that have been transformed.
Here is the most basic pipeline you can define:
const html = require('quantum-html')

const pipeline = [
  html()
]
portNumberadded
The port to start the site on so it can be accessed in the browser (e.g. http://localhost:port ).
This is only used when watching.
Default: 8080
resolveRootStringadded
The path to resolve absolute files from.
Default: '.' (The current working directory)
Returns
A promise that resolves when the pipeline is complete.
It does not contain a value but can be used when chaining items in a build (e.g. build the site and then run the deployment script)
watchconfigObjectadded
Build a quantum site and watch for changes using the config passed in.
This function does not return anything as it watches files for changes and must be killed by ending the current process.
Arguments
config
Properties
concurrencyNumberadded
How many pages that can be processed in parallel.
Default: 1
destStringadded
The target directory to output the built site files to.
Default: 'target'
fileReaderfileInfoFileInfooptionsObjectadded
The function used to load a file from disk and then convert it to a File object for use in a pipeline.
Arguments
fileInfoFileInfo
The FileInfo of the File to read.
options
The options to use when reading a file.
Properties
loader
The loader to use to read a file from disk.
resolveRootString
The path to resolve absolute files from.
Default: '.' (The current working directory)
loaderfileNameStringparentFilenameStringadded
The function to use for loading file content from disk.
Default:
function (filename) {
  return fs.readFileAsync(filename, 'utf-8')
}
Arguments
fileNameString
parentFilenameString
logLevelStringadded
The level of logging to use when running the command.
The available options are:
  • 'none'
  • 'error'
  • 'all'
Default: 'all'
loggereventObjectadded
The logger to use when building and watching files.
It will be passed an event object from different stages of the pipeline.
Arguments
event
The object describing the event to log.
Every event has a type property, the events types used in Quantum are:
  • 'header'
  • 'message'
  • 'build-page'
  • 'page-load-error'
  • 'copy-resource'
  • 'error'
  • 'end'
  • 'error'
Properties for all events
typeString
The event type. This can be used to switch the behaviour of the logger.
Properties for event type 'header'
Events that should be logged as a header, e.g. 'Building Pages'
messageString
The header message to display.
Properties for event type 'message'
Informational events, e.g. 'Starting server on http://localhost:8080'
messageString
The message to display
Properties for event type 'build-page'
Events logged when building each page included in the pipeline.
destFilesArray[File]
The list of output files, including asset files such as CSS and JS
sourceFileFile
The source used when building a file
timeTakenNumber
The time taken to build the output file(s)
Properties for event type 'page-load-error'
Events logged for each file with an error
errorError
The error that was thrown
fileInfoFileInfo
The FileInfo object for the file that is in error
Properties for event type 'copy-resource'
Event logged when copying resources to the output directory.
fileInfoFileInfo
The resource file that has been copied
timeTakenNumber
The time taken to copy the resource (in milliseconds)
Properties for event type 'error'
Events logged when there are errors in the pipeline, excluding events that have explicit event loggers (e.g. 'page-load-error')
errorError
The error that was thrown
Properties for event type 'end'
The event logged at the end of a complete pipeline.
builtCountNumber
The total number of pages built in the pipeline
timeTakenNumber
The total time taken (in milliseconds)
pagesString / Array[String] / Array[Object]added
This property should describe the files that should be processed by quantum as pages.
pipelineArray[FileTransform]added
An array of FileTransform functions that take a page as the input and return a page (or array of pages) that have been transformed.
Here is the most basic pipeline you can define:
const html = require('quantum-html')

const pipeline = [
  html()
]
portNumberadded
The port to start the site on so it can be accessed in the browser (e.g. http://localhost:port ).
This is only used when watching.
Default: 8080
resolveRootStringadded
The path to resolve absolute files from.
Default: '.' (The current working directory)
Functions
cloneentityEntityObjectadded
Creates a deep clone of some AST:
Example
const quantum = require('quantum-core')

const entity = {
  type: 'fruit',
  params: [],
  content: ['Strawberry', 'Kiwi', 'Cherry']
}

const cloned = quantum.clone(entity)
// cloned will look exactly the same as entity (but will be a copy,
// so changes made to the clone will not affect the original)
Arguments
entityEntity
The AST entity to clone.
Returns
Object
The cloned AST entity
jsonFileTransformadded
A file transform that converts a file with AST content into one with a JSON string as its content. This is mainly useful for debugging.
quantum.config.js
const quantum = require('quantum-core')

module.exports = {
  pipeline: [
    quantum.json()
],
pages: '**/index.um'
}
Returns
A file transform function.
parseinputStringEntityadded
A function for parsing string containing quantum markup into JavaScript objects. The parser always returns a single entity with no type, called the root entity. The contents property of the root entity contains the content parsed content.
Example
const quantum = require('quantum-core')

const markup = `
  @example param1 params2
    Content 1
    Content 2
`

console.log(quantum.parse(markup))
/*
  {
    type: '',
    params: [],
    content: [
      {
        type: 'example',
        params: ['param1', 'param2'],
        content: ['Content 1', 'Content 2']
}
]
}
*/
The parser returns an entity so that the results can be wrapped directly in a Selection using quantum.select()
Arguments
inputString
A string containing markup to parse. i.e. something that looks like this:
@example param1 params2
  Content 1
  Content 2
Returns
The parsed AST entity. Looks something like this:
{
  type: '',
  params: [],
  content: [
    {
      type: 'example',
      params: ['param1', 'param2'],
      content: ['Content 1', 'Content 2']
}
]
}
readfilenameStringoptionsObjectPromise[Entity]added
Reads and parses the contents of a file
Example
const quantum = require('quantum-core')

quantum.read('some/file.um').then(parsed => {
  console.log(parsed)
})
Arguments
filenameString
The filename of the file to load and parse.
options
Properties
baseString
The base of the glob path that should be ignored when writing to the target.
inlineBoolean
When inline mode is on, the inlineEntityType ( @inline by default) will be replaced with the content of the specified files.
Default: true
inlineEntityTypeString
The entity type to use for inlining other files.
Default: "inline"
loaderfilenameStringPromise[String]
A function for loading a file from disk, returning a Promise that contains the contents of the file as a string that can be passed to the parser.
Arguments
filenameString
The file/resource to load.
Returns
A promise that yields the contents of the file as a string.
resolveRootString
The path to resolve absolute files from.
Default: '.' (The current working directory)
Returns
A promise that yields the parsed AST entity.
readAsFilefileString / FileInfooptionsObjectPromise[File]added
Reads and parses the contents of a file
Example 1: Read using filename
const quantum = require('quantum-core')

quantum.readAsFile('some/file.um').then(file => {
  console.log(file)
})
Example 2: Read using FileInfo
const quantum = require('quantum-core')

const info = new quantum.FileInfo({
  src: "src/content/about.um",
  resolved: "about.um",
  base: "src/content",
  dest: "target/about.um",
  destBase: "target",
  watch: true
})

quantum.readAsFile(info).then(file => {
  console.log(file)
})
Arguments
The filename string or FileInfo to load. If a FileInfo is passed in, the returned File instance will use the FileInfo for its info property.
options
Properties
baseString
The base of the glob path that should be ignored when writing to the target.
inlineBoolean
When inline mode is on, the inlineEntityType ( @inline by default) will be replaced with the content of the specified files.
Default: true
inlineEntityTypeString
The entity type to use for inlining other files.
Default: "inline"
loaderfilenameStringPromise[String]
A function for loading a file from disk, returning a Promise that contains the contents of the file as a string that can be passed to the parser.
Arguments
filenameString
The file/resource to load.
Returns
A promise that yields the contents of the file as a string.
resolveRootString
The path to resolve absolute files from.
Default: '.' (The current working directory)
Returns
A promise that yields the parsed AST wrapped up into a File.
selectentityEntitySelectionadded
A helper api for extracting values from parsed AST. Pass in parsed AST, and use the methods on Selection to make working with the AST easier.
Example
const quantum = require('quantum-core')

const ast = {
  type: 'params',
  params: ['param1', 'param2'],
  content: [
    'Some Content'
]
}

quantum.select(ast) // returns a Selection
Arguments
entityEntity
An entity object to select.
Returns
A Selection instance which wraps the passed in AST
stringifyentityEntityStringadded
Converts AST back into quantum markdown. Does the opposite to parse
Example
const quantum = require('quantum-core')

quantum.stringify({
  type: 'example',
  params: ['param1', 'param2'],
  content: [
    'Some Content',
    {
      type: 'child',
      params: ['child-param'],
      content: []
}
]
})

/*
  Returns this string:

  @example param1 param2
    Some content
    @child child-param
*/
Arguments
entityEntity
The quantum AST entities to turn into a markup string.
Returns
The markup string
watchspecsString / Object / ArrayhandlerFunctionoptionsObjectPromise[Object]added
Watches a collection of files for changes. This also detects changes when inlined files are changed.
Example
quantum.watch("src/**/*.um", (err, file, cause) => {
  // Example use: apply some transformation and write the file to disk
  return transformAndWrite(file)
})
Arguments
This describes the files to watch.
It can be a single file:
quantum.watch("src/file.um", handler, options)
Or a glob:
quantum.watch("src/**/*.um", handler, options)
Or an array of globs:
quantum.watch(["src/**/*.um", "src2/**/index.um"], handler, options)
Or a more structured object:
quantum.watch({
  files: 'src/**/*.um',
  base: 'src'
}, handler, options)
Or an array of these objects:
quantum.watch([
  {
    files: 'src/**/*.um',
    base: 'src'
},
{
  files: 'src2/**/index.um',
  base: 'src2'
}
], handler, options)
handlererrorErrorfileFilecauseStringFile
A callback that transforms a file. If this does anything asynchronous, it should return a Promise
Arguments
errorError
This will be defined if there was an error when parsing the file. The handler has the option to handle this case if it wants to.
fileFile
The file that has been loaded. This is the file that the handler should process / transform.
causeString
The reason this file is being transformed. Can be one of 'build' 'add' or 'change'
Returns
The transformed file
options
.
Properties
concurrencyNumber
The number of files to build concurrently
Default: 1
destString
The default destination directory to write the files to
Default: 'target'
The working directory for the watcher to work in
Default: '.' (The current working directory)
fileReaderinfoFileInfooptionsObjectPromise[File]
The function for reading a file and converting it to a File
Default: readAsFile
Arguments
This describes which file to load. The file that is loaded should use this FileInfo as it's info property.
options
The options to pass to the reader.
Properties
loaderfilenameStringPromise[String]
Important
This loader must be used to read quantum files, in order for watch to function properly. If you want to use an alternative method for loading up files, use the loader option for the watch function.
A function for loading a file from disk, returning a Promise that contains the contents of the file as a string that can be passed to the parser.
Arguments
filenameString
The file/resource to load.
Returns
A promise that yields the contents of the file as a string.
Returns
A promise that yields the parsed AST wrapped up into a File
loaderfilenameStringparentFilenameStringPromise[String]
A function which loads files from disk, returning a Promise
Default:
const fs = require('fs')

function (filename, parentFilename) {
  return new Promise((resolve, reject) => {
    return fs.readFile(filename, 'utf-8', (err, data) => {
      err ? reject(err) : resolve(data)
})
})
}
Arguments
filenameString
The filename of the file to load
parentFilenameString
The filename of the parent file - ie if this file is being loaded as the result of an @inline include, the parent file will be the one doing the inlining.
Returns
A promise yielding the contents of the file
resolveRootString
The path to resolve absolute files from.
Default: '.' (The current working directory)
Returns
Returns a Promise that contains an object. The promise will settle once all the watchers have been set up.
The object the Promise yields looks like this:
{
  build: Function,
  events: EventEmitter
}
The build function will trigger a full build of the watched files when called.
events gives you a way to listen for changes that are made to files.
The possible events that can be emitted by this event emitter are: 'error', 'add', 'change', 'delete'.
watcherspecsString / Object / ArrayoptionsObjectWatcheradded
Creates a new Watcher instance that watches files for changes.
Arguments
This describes the files to watch.
It can be a single file:
quantum.watcher("src/file.um", options)
Or a glob:
quantum.watcher("src/**/*.um", options)
Or an array of globs:
quantum.watcher(["src/**/*.um", "src2/**/index.um"], options)
Or an array of globs:
quantum.watcher(["src/**/*.um", "src2/**/index.um"], options)
Or a more structured object:
quantum.watcher({
  files: 'src/**/*.um',
  base: 'src'
}, options)
Or an array of these objects:
quantum.watcher([
  {
    files: 'src/**/*.um',
    base: 'src'
},
{
  files: 'src2/**/index.um',
  base: 'src2'
}
], options)
options
Properties
destString
The default destination directory to write the files to
Default: 'target'
The working directory for the watcher to work in
Default: '.' (The current working directory)
Returns
writefileFilePromise[File]added
Writes a File to disk.
Example
const quantum = require('quantum-core')

quantum.readAsFile('some/file.um')
  .then(file => {
    return file.clone({
      info: file.info.clone({ dest: 'target/file.um'
      })
})
})
.then(quantum.write)
Arguments
fileFile
The File to write to disk. file.dest is the location where the file will be saved
Returns
A promise that settles once the contents of the file has been written
writefileArray[File]Promise[Array[File]]added
Writes an array of File to disk.
Example
const quantum = require('quantum-core')

const files = Promise.all([
  quantum.readAsFile('some/file1.um'),
  quantum.readAsFile('some/file2.um'),
  quantum.readAsFile('some/file3.um')
])

files.then(files => {
  return files.map(file => {
    return file.clone({
      info: file.info.clone({
        dest: file.info.target.replace('some', 'target')
})
})
})
})
.then(quantum.write)
Arguments
fileArray[File]
The File s to save. file.info.dest is the location where the file will be saved
Returns
A promise that settles once the contents of all the files have been written to disk
Parsing
Parsing is the act of converting a quantum markup string into a collection of JavaScript objects. Using quantum-core, this can be done in a single function call.
String Parsing
Quantum markup can be parsed as a string using the quantum.parse() function:
Example Markup
example.js (Javascript)
const quantum = require('quantum-core')

const markup = `
  @example param1 params2
    Content 1
    Content 2
`

console.log(quantum.parse(markup))
Example Result
{
  type: '',
  params: [],
  content: [
    {
      type: 'example',
      params: ['param1', 'param2'],
      content: ['Content 1', 'Content 2']
}
]
}
File Parsing
Quantum markup can be read and parsed from a file using the quantum.read() function:
Example Markup
example.um (Quantum)
@example param1 params2
  Content 1
  Content 2
example.js (Javascript)
const quantum = require('quantum-core')

quantum.read('example.um').then(parsed => {
  console.log(parsed)
})
Example Result
{
  type: '',
  params: [],
  content: [
    {
      type: 'example',
      params: ['param1', 'param2'],
      content: ['Content 1', 'Content 2']
}
]
}
Selection Api
The selection api allows the selection and manipulation of quantum AST:
const quantum = require('quantum-core')

quantum.read('example.um').then(parsed => {
  const selection = quantum.select(parsed)
  selection.ps()                      // extract the parameter string from an entity
  selection.cs()                      // extract the content string from an entity (ignores all sub-entities)
  selection.select('banana')          // selects the first child entity called banana
  selection.selectAll('kiwi')         // selects all the child entities called kiwi (returns an array)
  selection.select('lemon').param(2)  // gets the second parameter from the first lemon entity in the selection
})
Lets go into more detail to explain various parts of the selection api.
Selecting, querying and modifying an entity
An entity, when parsed looks like this:
{
  type: 'fruits',
  params: ['kiwi', 'lime', 'grapes'],
  content: ['Some fruits that are green']
}
An entity can be wrapped in a selection to make it easier to query:
const entity = {
  type: 'fruits',
  params: ['kiwi', 'lime', 'grapes'],
  content: [
    'Some fruits that are green'
]
}

const selection = quantum.select(entity)

selection.type()   // 'fruits'
selection.params() // ['kiwi', 'lime', 'grapes']
selection.param(1) // 'lime'
selection.param(2) // 'grapes'
selection.ps()     // 'kiwi lime grapes'

selection.content() // ['Some fruits that are green']
selection.cs()      // 'Some fruits that are green'
A selection can also be used to modify an entity:
const entity = {
  type: 'fruits',
  params: ['kiwi', 'lime', 'grapes'],
  content: [
    'Some fruits that are green'
]
}

const selection = quantum.select(entity)

selection.type('fruitSalad')       // sets entity.type to 'fruitSalad'
selection.param(1, 'apple')        // changes the 2nd parameter to 'apple'
selection.content(['New content']) // replaces entity.content
selection.add('More content')      // pushes more content into entity.content
Of course, you can also poke around the entity object instead of wrapping it in a selection if you prefer. The selection api is merely a simple wrapper that makes some tasks easier.
Selecting child entities
Child entities can be selected by type:
const entity = {
  type: 'fruits',
  params: [],
  content: [
    { type: 'apple', params: ['red'], content: [] },
    { type: 'banana', params: ['yellow'], content: [] },
    { type: 'banana', params: ['brown'], content: [] }
]
}

const selection = quantum.select(entity)

// select the first child of type 'apple' and get it's first parameter
selection.select('apple').param(0) // is 'red'

// selecting multiple children of the same type
const bananas = selection.selectAll('banana')
bananas[0].param(0) // is 'yellow'
bananas[1].param(0) // is 'brown'
Recursively selecting child entities
Sometimes you need to select all the entities of a particular type recursively down the tree. To do that just set the resursive option to true:
const entity = {
  type: 'fruits',
  params: [],
  content: [
    {
      type: 'tag',
      params: ['red'],
      content: [
        {
          type: 'tag',
          params: ['orange'],
          content: [
            {
              type: 'tag',
              params: ['yellow'],
              content: []
}
]
}
]
},
{ type: 'tag', params: ['green'], content: [] },
{ type: 'tag', params: ['blue'], content: [] }
]
}

const selection = quantum.select(entity)

// returns three 'tag' selections ('red', 'green' and 'blue')
selection.selectAll('tag')

// returns five 'tag' selections ('red', 'orange', 'yellow', 'green', 'blue')
selection.selectAll('tag', {recursive: true})