├── src-docs ├── html │ ├── $index │ │ ├── meta.yaml │ │ ├── mock.html │ │ ├── noscript.html │ │ ├── sidenav.html │ │ ├── footer.html │ │ ├── banner.html │ │ └── index.md │ ├── todo.html │ ├── class.md │ ├── ref.md │ ├── bootstrapping.md │ ├── on.md │ ├── let.md │ ├── index.html │ ├── if.md │ ├── for.md │ ├── databinding.md │ ├── attribute.md │ ├── component.md │ └── quickstart.md ├── app │ ├── attributes │ │ ├── all.ts │ │ └── autolink.ts │ ├── typings │ │ ├── tsd.d.ts │ │ └── highlightjs │ │ │ └── highlightjs.d.ts │ ├── todo-list │ │ ├── todo-list.html │ │ └── todo-list.ts │ ├── molds │ │ ├── all.ts │ │ ├── mark-href.ts │ │ ├── svg-icon.ts │ │ ├── markdown.ts │ │ ├── doc-demo.ts │ │ ├── markdown-live.ts │ │ └── highlight.ts │ ├── hello-world │ │ ├── hello-world.ts │ │ └── hello-world.html │ ├── tsconfig.json │ ├── inner-component │ │ ├── inner-component.ts │ │ └── inner-component.html │ ├── svg │ │ ├── plus.svg │ │ ├── arrows-h.svg │ │ ├── bolt.svg │ │ ├── paper-plane-o.svg │ │ ├── times.svg │ │ ├── magic.svg │ │ ├── info-circle.svg │ │ ├── sitemap.svg │ │ ├── cubes.svg │ │ └── question-circle.svg │ ├── app.ts │ ├── todo-item │ │ ├── todo-item.ts │ │ └── todo-item.html │ ├── mock-component │ │ ├── mock-component.ts │ │ └── mock-component.html │ ├── utils │ │ └── utils.ts │ ├── lib.d.ts │ └── config.ts ├── styles │ ├── overrides │ │ ├── sf-article.less │ │ ├── sf-jumbo.less │ │ ├── sf-footer.less │ │ └── sf-icon.less │ ├── typography.less │ ├── components │ │ ├── todo-item.less │ │ ├── doc-features.less │ │ ├── doc-noscript.less │ │ ├── doc-sidenav.less │ │ └── doc-banner.less │ ├── layout.less │ ├── app.less │ ├── variables.less │ ├── color-mixes.less │ ├── misc.less │ └── mixins.less └── svg │ ├── info-blue.svg │ ├── info-circle-blue.svg │ ├── external-link.svg │ ├── github.svg │ ├── github-blue.svg │ └── github-light.svg ├── src ├── tsconfig.json ├── index.ts ├── lib.d.ts ├── bindings.ts ├── view.ts ├── decorators.ts ├── boot.ts ├── molds.ts ├── attributes.ts ├── compile.ts └── utils.ts ├── tsd.json ├── readme.md ├── .gitignore ├── bower.json ├── .npmignore ├── system.config.js ├── lib ├── index.js ├── decorators.js ├── view.js ├── bindings.js ├── boot.js ├── molds.js ├── compile.js ├── attributes.js └── utils.js ├── LICENSE ├── package.json └── notes.md /src-docs/html/$index/meta.yaml: -------------------------------------------------------------------------------- 1 | ignore: .* 2 | -------------------------------------------------------------------------------- /src-docs/app/attributes/all.ts: -------------------------------------------------------------------------------- 1 | export * from './autolink'; -------------------------------------------------------------------------------- /src-docs/styles/overrides/sf-article.less: -------------------------------------------------------------------------------- 1 | article {.sf-article()} 2 | -------------------------------------------------------------------------------- /src-docs/html/$index/mock.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src-docs/app/typings/tsd.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src-docs/styles/overrides/sf-jumbo.less: -------------------------------------------------------------------------------- 1 | .sf-jumbo() { 2 | 3 | &.auto { 4 | height: auto; 5 | } 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src-docs/html/todo.html: -------------------------------------------------------------------------------- 1 |

The "hello world" of apps these days. See Quickstart.

2 | 3 | -------------------------------------------------------------------------------- /src-docs/styles/overrides/sf-footer.less: -------------------------------------------------------------------------------- 1 | .sf-footer() { 2 | sf-footer-body { 3 | box-shadow: none; 4 | outline: none; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src-docs/app/todo-list/todo-list.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /src-docs/app/molds/all.ts: -------------------------------------------------------------------------------- 1 | export * from './doc-demo'; 2 | export * from './highlight'; 3 | export * from './mark-href'; 4 | export * from './markdown'; 5 | export * from './markdown-live'; 6 | export * from './svg-icon'; -------------------------------------------------------------------------------- /src-docs/app/hello-world/hello-world.ts: -------------------------------------------------------------------------------- 1 | import {Component} from 'atril'; 2 | 3 | @Component({ 4 | tagName: 'hello-world' 5 | }) 6 | class ViewModel { 7 | name = 'world'; 8 | static viewUrl = 'hello-world/hello-world.html'; 9 | } 10 | -------------------------------------------------------------------------------- /src/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.5.0", 3 | "compilerOptions": { 4 | "target": "es5", 5 | "module": "commonjs", 6 | "noImplicitAny": false, 7 | "experimentalDecorators": true 8 | }, 9 | "compileOnSave": false 10 | } 11 | -------------------------------------------------------------------------------- /src-docs/app/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.5.0", 3 | "compilerOptions": { 4 | "target": "es5", 5 | "module": "commonjs", 6 | "noImplicitAny": false, 7 | "experimentalDecorators": true 8 | }, 9 | "compileOnSave": false 10 | } 11 | -------------------------------------------------------------------------------- /src-docs/app/inner-component/inner-component.ts: -------------------------------------------------------------------------------- 1 | import {Component, bindable} from 'atril'; 2 | 3 | @Component({tagName: 'inner-component'}) 4 | class VM { 5 | @bindable val = null; 6 | @bindable color = 'red'; 7 | 8 | static viewUrl = 'inner-component/inner-component.html'; 9 | } 10 | -------------------------------------------------------------------------------- /src-docs/app/inner-component/inner-component.html: -------------------------------------------------------------------------------- 1 |
2 |

Bound `val` in inner component: {{val}}

3 | 4 |

`color` in inner component: {{color}}

5 | 6 | 7 |
8 | -------------------------------------------------------------------------------- /src-docs/app/svg/plus.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/app/svg/arrows-h.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/app/svg/bolt.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tsd.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "v4", 3 | "repo": "borisyankov/DefinitelyTyped", 4 | "ref": "master", 5 | "path": "src-docs/app/typings", 6 | "bundle": "src-docs/app/typings/tsd.d.ts", 7 | "installed": { 8 | "highlightjs/highlightjs.d.ts": { 9 | "commit": "2d4c4679bc2b509f27435a4f9da5e2de11258571" 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src-docs/app/svg/paper-plane-o.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | [![Join the chat at https://gitter.im/Mitranim/atril](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Mitranim/atril?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 4 | 5 | Experimental, simplistic JavaScript rendering library. 6 | 7 | See the documentation at [http://mitranim.com/atril/](http://mitranim.com/atril/). 8 | -------------------------------------------------------------------------------- /src-docs/app/svg/times.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/styles/typography.less: -------------------------------------------------------------------------------- 1 | html { 2 | font-weight: 300; 3 | } 4 | 5 | .text-monospace { 6 | font-family: @sf-font-family-monospace; 7 | // Normalise monospace font size. 8 | &:not(.size-initial) {font-size: 14/16em} 9 | // Prevent further reduction inside other monospace blocks. 10 | tt, code, kbd, pre, samp { 11 | & {font-size: 1em} 12 | } 13 | & & {font-size: 1em} 14 | } 15 | -------------------------------------------------------------------------------- /src-docs/svg/info-blue.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/html/$index/noscript.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Hello! :)

4 |

This site is a live demo for atril, a JS rendering library. For demo purposes, it's mostly rendered with JavaScript.

5 |

Please enable JavaScript in your browser. Thank you!

6 |
7 |
8 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export {compileExpression} from './bindings'; 4 | export {bootstrap, scheduleReflow} from './boot'; 5 | export {Attribute, Component, Mold, bindable, assign} from './decorators'; 6 | export {Meta} from './tree'; 7 | export {instantiate} from './utils'; 8 | export {viewCache} from './view'; 9 | 10 | // Imported for the side effect of registering these built-ins. 11 | import './attributes'; 12 | import './molds'; 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Numerous always-ignore extensions 2 | *.diff 3 | *.err 4 | *.orig 5 | *.log 6 | *.rej 7 | *.swo 8 | *.swp 9 | *.zip 10 | *.vi 11 | *~ 12 | 13 | # OS or Editor folders 14 | .DS_Store 15 | ._* 16 | Thumbs.db 17 | .cache 18 | .project 19 | .settings 20 | .tmproj 21 | *.esproj 22 | nbproject 23 | *.sublime-project 24 | *.sublime-workspace 25 | .idea 26 | 27 | # Folders to ignore 28 | node_modules 29 | bower_components 30 | jspm_packages 31 | dist 32 | -------------------------------------------------------------------------------- /src-docs/app/app.ts: -------------------------------------------------------------------------------- 1 | import {bootstrap, viewCache} from 'atril'; 2 | 3 | import views from 'views'; 4 | for (let path in views) viewCache.set(path, views[path]); 5 | 6 | import 'config'; 7 | import 'attributes/all'; 8 | import 'molds/all'; 9 | import 'hello-world/hello-world'; 10 | // import 'inner-component/inner-component'; 11 | // import 'mock-component/mock-component'; 12 | import 'todo-item/todo-item'; 13 | import 'todo-list/todo-list'; 14 | 15 | bootstrap(); 16 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "atril", 3 | "version": "0.0.0", 4 | "private": true, 5 | "authors": [ 6 | "Mitranim " 7 | ], 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/Mitranim/atril.git" 11 | }, 12 | "ignore": [ 13 | "**/*" 14 | ], 15 | "overrides": { 16 | "font-awesome-svg-png": { 17 | "main": [] 18 | } 19 | }, 20 | "devDependencies": { 21 | "font-awesome-svg-png": "~1.1.2" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src-docs/app/svg/magic.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/app/todo-item/todo-item.ts: -------------------------------------------------------------------------------- 1 | import {Component, assign, bindable, Meta} from 'atril'; 2 | 3 | @Component({ 4 | tagName: 'todo-item' 5 | }) 6 | class VM { 7 | @assign element: HTMLElement; 8 | 9 | @bindable item = null; 10 | @bindable isNew = false; 11 | 12 | add() { 13 | this.element.dispatchEvent(new CustomEvent('add')); 14 | } 15 | 16 | remove() { 17 | this.element.dispatchEvent(new CustomEvent('remove')); 18 | } 19 | 20 | static viewUrl = 'todo-item/todo-item.html'; 21 | } 22 | -------------------------------------------------------------------------------- /src-docs/styles/components/todo-item.less: -------------------------------------------------------------------------------- 1 | todo-item { 2 | > * { 3 | display: flex; 4 | label { 5 | padding: @sf-common-padding; 6 | } 7 | form { 8 | display: flex; 9 | flex-direction: row; 10 | flex: 1; 11 | input:not([type]), input[type] { 12 | flex: 1; 13 | outline: none; 14 | } 15 | } 16 | button { 17 | padding: @sf-common-padding; 18 | } 19 | } 20 | .strikethrough { 21 | text-decoration: line-through; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src-docs/app/svg/info-circle.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/svg/info-circle-blue.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/svg/external-link.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Numerous always-ignore extensions 2 | *.diff 3 | *.err 4 | *.orig 5 | *.log 6 | *.rej 7 | *.swo 8 | *.swp 9 | *.zip 10 | *.vi 11 | *~ 12 | 13 | # OS or Editor folders 14 | .DS_Store 15 | ._* 16 | Thumbs.db 17 | .cache 18 | .project 19 | .settings 20 | .tmproj 21 | *.esproj 22 | nbproject 23 | *.sublime-project 24 | *.sublime-workspace 25 | .idea 26 | 27 | # Folders to ignore 28 | node_modules 29 | bower_components 30 | jspm_packages 31 | typings 32 | dist 33 | src-docs 34 | 35 | # Files to ignore 36 | notes.md 37 | gulpfile.js 38 | system.config.js 39 | -------------------------------------------------------------------------------- /src-docs/app/attributes/autolink.ts: -------------------------------------------------------------------------------- 1 | import {Attribute, assign} from 'atril'; 2 | 3 | @Attribute({attributeName: 'autolink'}) 4 | class Ctrl { 5 | @assign element: HTMLAnchorElement; 6 | @assign attribute: Attr; 7 | 8 | constructor() { 9 | if (!(this.element instanceof HTMLAnchorElement)) return; 10 | 11 | this.element.id = this.attribute.value; 12 | 13 | let base = document.head.querySelector('base').getAttribute('href'); 14 | let prefix = location.pathname.replace(base, ''); 15 | this.element.href = prefix + '#' + this.attribute.value; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src-docs/app/svg/sitemap.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/app/svg/cubes.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/app/todo-list/todo-list.ts: -------------------------------------------------------------------------------- 1 | import {Component} from 'atril'; 2 | 3 | @Component({ 4 | tagName: 'todo-list' 5 | }) 6 | class VM { 7 | text = ''; 8 | items = [ 9 | {text: 'Learn a new framework', completed: true}, 10 | {text: 'Be awesome'} 11 | ]; 12 | newItem = {text: '', completed: false}; 13 | 14 | add() { 15 | this.items.unshift(this.newItem); 16 | this.newItem = {text: '', completed: false}; 17 | } 18 | 19 | remove(item) { 20 | let index = this.items.indexOf(item); 21 | if (~index) this.items.splice(index, 1); 22 | } 23 | 24 | static viewUrl = 'todo-list/todo-list.html'; 25 | } 26 | -------------------------------------------------------------------------------- /src-docs/app/todo-item/todo-item.html: -------------------------------------------------------------------------------- 1 |
3 | 6 |
7 | 9 | 10 |
11 | 12 |
13 | -------------------------------------------------------------------------------- /src-docs/app/svg/question-circle.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/app/hello-world/hello-world.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Hello, {{name}}!

4 | 5 | 6 | 9 | 10 | 11 | 14 | 15 | 17 | 20 |
21 | -------------------------------------------------------------------------------- /src-docs/styles/layout.less: -------------------------------------------------------------------------------- 1 | /** 2 | * Geometry rules. 3 | */ 4 | 5 | .narrow-inverse {.narrow-inverse()} 6 | 7 | .block {display: block} 8 | 9 | .space-out-h { 10 | > *:not(:last-child) { 11 | margin-right: @sf-common-margin / 2; 12 | } 13 | > *:not(:first-child) { 14 | margin-left: @sf-common-margin / 2; 15 | } 16 | } 17 | .space-out-h-05 { 18 | > *:not(:last-child) { 19 | margin-right: @sf-common-margin / 4; 20 | } 21 | > *:not(:first-child) { 22 | margin-left: @sf-common-margin / 4; 23 | } 24 | } 25 | 26 | .order-1 {order: 1} 27 | .order-2 {order: 2} 28 | .order-3 {order: 3} 29 | .order-4 {order: 4} 30 | .order-5 {order: 5} 31 | .order-6 {order: 6} 32 | -------------------------------------------------------------------------------- /src-docs/app/mock-component/mock-component.ts: -------------------------------------------------------------------------------- 1 | import {Component, assign} from 'atril'; 2 | import {testUrl, ajax, randomString} from 'utils/utils'; 3 | 4 | @Component({tagName: 'mock-component'}) 5 | class VM { 6 | @assign element: HTMLElement; 7 | 8 | value = 'world'; 9 | color = 'blue'; 10 | fetched = ''; 11 | inputValue = ''; 12 | checked = false; 13 | 14 | constructor() { 15 | setTimeout(() => { 16 | this.value = randomString(); 17 | }, 1000); 18 | 19 | ajax(testUrl) 20 | .then(value => { 21 | this.fetched = value; 22 | }); 23 | } 24 | 25 | randomString() {return randomString()} 26 | 27 | static viewUrl = 'mock-component/mock-component.html'; 28 | } 29 | -------------------------------------------------------------------------------- /src-docs/html/class.md: -------------------------------------------------------------------------------- 1 | ## `class.*` 2 | 3 | Used as `class.X`, this adds class `X` when the expression is truthy and removes 4 | it when the expression evaluates to falsy. 5 | 6 | Example: 7 | 8 | ```html 9 |
10 | 14 |
15 | ``` 16 | 17 | 25 | -------------------------------------------------------------------------------- /src-docs/svg/github.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/styles/components/doc-features.less: -------------------------------------------------------------------------------- 1 | doc-features { 2 | /** 3 | * Layout. 4 | */ 5 | display: flex; 6 | justify-content: space-between; 7 | align-items: stretch; 8 | 9 | /** 10 | * Child styling. 11 | */ 12 | > * { 13 | // Layout. 14 | flex: 1; 15 | 16 | // Inner layout. 17 | display: flex; 18 | flex-direction: column; 19 | justify-content: space-around; 20 | 21 | // Whitespace. 22 | .space-out-children(); 23 | 24 | // Cosmetic. 25 | text-align: center; 26 | 27 | // Icon styling. 28 | > sf-icon { 29 | // Layout. 30 | display: block; 31 | margin-left: auto; 32 | margin-right: auto; 33 | font-size: 2em; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src-docs/svg/github-blue.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/svg/github-light.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src-docs/html/ref.md: -------------------------------------------------------------------------------- 1 | ## `ref.*` 2 | 3 | References the target in the current viewmodel or scope. Useful for getting hold 4 | of things in the view. 5 | 6 | ### `ref.="X"` 7 | 8 | Assigns the element as `X`. 9 | 10 | ```html 11 |

Reference me!

12 |

{{p.outerHTML}}

13 | ``` 14 | 15 | 19 | 20 | ### `ref.vm="X"` 21 | 22 | Assigns the element's viewmodel as `X`. 23 | 24 | ```html 25 | 26 |

{{viewmodel.name}}

27 | ``` 28 | 29 | 33 | -------------------------------------------------------------------------------- /system.config.js: -------------------------------------------------------------------------------- 1 | System.config({ 2 | "baseURL": "/", 3 | "transpiler": "traceur", 4 | "paths": { 5 | "*": "app/*.js", 6 | "github:*": "jspm_packages/github/*.js", 7 | "npm:*": "jspm_packages/npm/*.js" 8 | } 9 | }); 10 | 11 | System.config({ 12 | "map": { 13 | "atril": "github:Mitranim/atril@master", 14 | "highlightjs": "github:components/highlightjs@8.5.0", 15 | "marked": "npm:marked@0.3.3", 16 | "text": "github:systemjs/plugin-text@0.0.2", 17 | "traceur": "github:jmcriffey/bower-traceur@0.0.88", 18 | "traceur-runtime": "github:jmcriffey/bower-traceur-runtime@0.0.88", 19 | "zone.js": "github:angular/zone.js@master", 20 | "github:Mitranim/atril@master": { 21 | "zone.js": "github:angular/zone.js@master" 22 | } 23 | } 24 | }); 25 | 26 | -------------------------------------------------------------------------------- /src-docs/html/$index/sidenav.html: -------------------------------------------------------------------------------- 1 | Overview 2 | Quickstart 3 | Component 4 | Attribute 5 | Mold 6 | Databinding 7 | Bootstrapping 8 | if 9 | for 10 | let 11 | on 12 | class 13 | ref 14 | demo 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src-docs/html/bootstrapping.md: -------------------------------------------------------------------------------- 1 | ## Bootstrapping 2 | 3 | After registering all custom elements and attributes, you need to tell the 4 | framework to find and activate them on the page. This is done with the 5 | `bootstrap` method. 6 | 7 | ```typescript 8 | import {bootstrap} from 'atril'; 9 | 10 | import 'my-custom-element'; 11 | import 'my-attributes'; 12 | import 'my-molds'; 13 | 14 | bootstrap(); 15 | ``` 16 | 17 | If the document is already available, `bootstrap` is synchronous. Otherwise it 18 | delays activation until the `DOMContentReady` event. If your scripts are loaded 19 | before the content, activation happens before the content is first rendered by 20 | the browser. 21 | 22 | You can optionally pass a DOM element to limit the scope of the search. By 23 | default, search starts with `document.body`. 24 | 25 | ```typescript 26 | bootstrap(document.querySelector('#limited-section')); 27 | ``` 28 | -------------------------------------------------------------------------------- /src-docs/html/$index/footer.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | <%= (new Date()).getFullYear() > 2015 ? '2015—' + (new Date()).getFullYear() : '2015' %> 6 | Mitranim 7 | (MIT licensed) 8 | 9 |
10 | 16 |
17 | 18 |
19 |
20 |
-------------------------------------------------------------------------------- /src-docs/app/molds/mark-href.ts: -------------------------------------------------------------------------------- 1 | import {Mold, assign} from 'atril'; 2 | 3 | @Mold({attributeName: 'mark-href'}) 4 | class Ctrl { 5 | @assign element: HTMLTemplateElement; 6 | @assign hint: string; 7 | 8 | constructor() { 9 | let content = this.element.content; 10 | 11 | while (content.hasChildNodes()) { 12 | this.element.appendChild(content.removeChild(content.firstChild)); 13 | } 14 | 15 | let anchors = this.element.querySelectorAll('a'); 16 | for (let i = anchors.length - 1; i >= 0; --i) { 17 | let node = anchors[i]; 18 | if (this.isActive(node.getAttribute('href'))) node.classList.add(this.hint); 19 | else node.classList.remove(this.hint); 20 | } 21 | } 22 | 23 | isActive(link: string): boolean { 24 | return ~location.pathname.indexOf(link) && !~location.pathname.indexOf(link + '/') || 25 | location.pathname === '/atril/' && link === ''; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src-docs/styles/overrides/sf-icon.less: -------------------------------------------------------------------------------- 1 | .sf-icon {.sf-icon()} 2 | .sf-icon() { 3 | 4 | &.inline { 5 | vertical-align: middle; 6 | position: relative; 7 | top: -0.08em; 8 | &:not(:first-child) { 9 | margin-left: @sf-common-margin / 5; 10 | } 11 | &:not(:last-child) { 12 | margin-right: @sf-common-margin / 5; 13 | } 14 | } 15 | 16 | /** 17 | * Non-background SVG. 18 | */ 19 | > svg { 20 | display: block; 21 | width: 1em; 22 | height: 1em; 23 | } 24 | 25 | /** 26 | * Register SVG icons. 27 | */ 28 | .svg-colored(github); 29 | .svg-colored(github-light); 30 | .svg-colored(github-blue); 31 | .svg-black(arrow-up); 32 | .svg-black(link); 33 | .svg-black(info-circle); 34 | .svg-colored(external-link); 35 | .svg-colored(info-circle-blue); 36 | .svg-colored(info-blue); 37 | } 38 | 39 | button.sf-icon { 40 | width: auto; 41 | height: auto; 42 | outline: none; 43 | } 44 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var bindings_1 = require('./bindings'); 3 | exports.compileExpression = bindings_1.compileExpression; 4 | var boot_1 = require('./boot'); 5 | exports.bootstrap = boot_1.bootstrap; 6 | exports.scheduleReflow = boot_1.scheduleReflow; 7 | var decorators_1 = require('./decorators'); 8 | exports.Attribute = decorators_1.Attribute; 9 | exports.Component = decorators_1.Component; 10 | exports.Mold = decorators_1.Mold; 11 | exports.bindable = decorators_1.bindable; 12 | exports.assign = decorators_1.assign; 13 | var tree_1 = require('./tree'); 14 | exports.Meta = tree_1.Meta; 15 | var utils_1 = require('./utils'); 16 | exports.instantiate = utils_1.instantiate; 17 | var view_1 = require('./view'); 18 | exports.viewCache = view_1.viewCache; 19 | // Imported for the side effect of registering these built-ins. 20 | require('./attributes'); 21 | require('./molds'); 22 | 23 | Object.defineProperty(exports, '__esModule', { 24 | value: true 25 | }); 26 | -------------------------------------------------------------------------------- /src-docs/app/molds/svg-icon.ts: -------------------------------------------------------------------------------- 1 | import {Mold, assign, viewCache} from 'atril'; 2 | 3 | /** 4 | * SVG icon helper with optional async loading. 5 | */ 6 | @Mold({ 7 | attributeName: 'svg-icon' 8 | }) 9 | class Ctrl { 10 | @assign attribute: Attr; 11 | @assign hint: string; 12 | @assign element: HTMLTemplateElement; 13 | 14 | content: DocumentFragment; 15 | 16 | constructor() { 17 | this.content = this.element.content; 18 | let path = 'svg/' + this.attribute.value + '.svg'; 19 | 20 | let view = viewCache.get(path); 21 | if (typeof view === 'string') this.commit(view); 22 | else { 23 | viewCache.load(path).then(view => {this.commit(view)}); 24 | } 25 | } 26 | 27 | commit(view: string): void { 28 | let child = this.content.firstChild; 29 | this.element.appendChild(this.content.removeChild(child)); 30 | if (child.tagName !== 'SF-ICON') child.classList.add('sf-icon'); 31 | child.innerHTML = view; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src-docs/html/$index/banner.html: -------------------------------------------------------------------------------- 1 |
2 |

atril

3 | 4 |

Experimental JS rendering library

5 | 6 |

Ideas from ReactJS, Polymer, Angular 2, Aurelia, made simple

7 | 8 | 18 |
-------------------------------------------------------------------------------- /src-docs/app/molds/markdown.ts: -------------------------------------------------------------------------------- 1 | import {Mold, assign} from 'atril'; 2 | import marked from 'marked'; 3 | 4 | @Mold({ 5 | attributeName: 'markdown' 6 | }) 7 | class Ctrl { 8 | @assign element: HTMLTemplateElement; 9 | 10 | constructor() { 11 | let content = this.element.content; 12 | 13 | // Convert existing content into text. 14 | let buffer = document.createElement('div'); 15 | while (content.hasChildNodes()) { 16 | buffer.appendChild(content.firstChild); 17 | } 18 | 19 | // Render into markdown. 20 | let result = marked(buffer.innerHTML); 21 | buffer.innerHTML = result; 22 | 23 | // Fix code highlighting classes. 24 | let codeBlocks = buffer.querySelectorAll('pre code'); 25 | for (let i = 0, ii = codeBlocks.length; i < ii; ++i) { 26 | let node = codeBlocks[i]; 27 | if (node instanceof Element) node.classList.add('hljs'); 28 | } 29 | 30 | while (buffer.hasChildNodes()) { 31 | this.element.appendChild(buffer.removeChild(buffer.firstChild)); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src-docs/styles/components/doc-noscript.less: -------------------------------------------------------------------------------- 1 | doc-noscript { 2 | /** 3 | * Variables. 4 | */ 5 | // @bg-color: rgb(38, 34, 47); 6 | // @text-color: @sf-base-background-color; 7 | @bg-color: @sf-base-background-color; 8 | @text-color: @sf-base-text-color; 9 | 10 | /** 11 | * Layout. 12 | */ 13 | position: fixed; 14 | top: 0; 15 | right: 0; 16 | bottom: 0; 17 | left: 0; 18 | z-index: 10000; 19 | 20 | /** 21 | * Cosmetic. 22 | */ 23 | font-size: 200%; 24 | background-color: @bg-color; 25 | color: @text-color; 26 | text-align: center; 27 | 28 | /** 29 | * Inner layout. 30 | */ 31 | display: flex; 32 | align-items: center; 33 | justify-content: space-around; 34 | 35 | /** 36 | * Inner content styling. 37 | */ 38 | > doc-noscript-content { 39 | .narrow-inverse(); 40 | > * { 41 | padding: @sf-common-padding / 2; 42 | } 43 | } 44 | 45 | /** 46 | * Code colours. 47 | */ 48 | code { 49 | background-color: lighten(@bg-color, 10%); 50 | color: @text-color; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Mitranim 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /src-docs/app/molds/doc-demo.ts: -------------------------------------------------------------------------------- 1 | import {Mold, Meta, assign} from 'atril'; 2 | 3 | @Mold({ 4 | attributeName: 'doc-demo' 5 | }) 6 | class Ctrl { 7 | @assign element: HTMLTemplateElement; 8 | @assign hint: string; 9 | @assign scope: any; 10 | 11 | constructor() { 12 | console.assert(!this.hint, `'doc-demo.' doesn't expect any hints, got: ${this.hint}`); 13 | 14 | // Fork the scope. Useful for avoiding `let` conflicts in demos. Not 15 | // recommended for other scenarios. 16 | let meta = Meta.getMeta(this.element); 17 | if (!this.scope) this.scope = null; 18 | if (!meta.scope) { 19 | meta.insertScope(); 20 | this.scope = meta.scope; 21 | } 22 | 23 | // Add a demo wrapper. 24 | let div = document.createElement('div'); 25 | div.classList.add('doc-demo'); 26 | div.innerHTML = 27 | `

28 | 29 | Demo 30 |

`; 31 | 32 | let fragment = this.element.content; 33 | while (fragment.hasChildNodes()) { 34 | div.appendChild(fragment.removeChild(fragment.firstChild)); 35 | } 36 | this.element.appendChild(div); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src-docs/app/mock-component/mock-component.html: -------------------------------------------------------------------------------- 1 |

Hello {{value}}!

2 | 3 |

If you see 'Hello world' or some mumbo-jumbo, the values have been successfully interpolated!

4 | 5 | 6 | 7 |
8 | 9 | 10 |
11 | {{char}} 12 |
13 |
14 | 15 |
16 | 18 | {{inputValue}} 19 |
20 | 21 |
22 | 24 | {{inputValue}} 25 |
26 | 27 |
28 | 32 |
33 | -------------------------------------------------------------------------------- /src-docs/app/utils/utils.ts: -------------------------------------------------------------------------------- 1 | export const testUrl = 'https://incandescent-torch-3438.firebaseio.com/test.json'; 2 | 3 | export function ajax(url: string, options: any = {}) { 4 | return new Promise((resolve, reject) => { 5 | let xhr = new XMLHttpRequest(); 6 | 7 | function fail() { 8 | if (/application\/json/.test(xhr.getResponseHeader('Content-Type'))) { 9 | reject(JSON.parse(xhr.responseText)); 10 | } else { 11 | reject(xhr.responseText); 12 | } 13 | } 14 | 15 | function ok() { 16 | if (/application\/json/.test(xhr.getResponseHeader('Content-Type'))) { 17 | resolve(JSON.parse(xhr.responseText)); 18 | } else { 19 | resolve(xhr.responseText); 20 | } 21 | } 22 | 23 | xhr.addEventListener('abort', fail); 24 | xhr.addEventListener('error', fail); 25 | xhr.addEventListener('timeout', fail); 26 | xhr.addEventListener('load', ok); 27 | 28 | if (options.onprogress) xhr.addEventListener('progress', options.onprogress); 29 | 30 | xhr.open(options.method || 'GET', url, true, options.username || null, options.password || null); 31 | xhr.send(options.data || null); 32 | }); 33 | } 34 | 35 | export function randomString(): string { 36 | return (Math.random() * Math.pow(10, 16)).toString(36); 37 | } 38 | -------------------------------------------------------------------------------- /src-docs/styles/components/doc-sidenav.less: -------------------------------------------------------------------------------- 1 | doc-sidenav, .doc-sidenav { 2 | // Layout. 3 | width: 14em; 4 | 5 | // Inner layout. 6 | display: flex; 7 | flex-direction: column; 8 | 9 | // Child styling. 10 | > * { 11 | padding: @sf-common-padding / 2 @sf-common-padding; 12 | } 13 | 14 | // Link styling. 15 | a { 16 | // Inner layout. 17 | display: flex; 18 | align-items: center; 19 | justify-content: space-between; 20 | 21 | // Interactive colouring. 22 | @color: @sf-base-link-color; 23 | &:hover {background-color: fade(@color, 5%)} 24 | &:focus, &:active {background-color: fade(@color, 10%)} 25 | 26 | // Active styling. 27 | &.active { 28 | background-color: fade(@color, 15%); 29 | &::after { 30 | content: ''; 31 | // Layout. 32 | display: inline-block; 33 | vertical-align: middle; 34 | height: 1em; 35 | width: 1em; 36 | margin-left: @sf-common-margin / 5; 37 | 38 | // Icon. 39 | .bg-svg-black(chevron-right); 40 | background-position-x: 100%; 41 | background-position-y: 50%; 42 | background-size: contain; 43 | background-repeat: no-repeat; 44 | 45 | // Cosmetic. 46 | opacity: 0.3; 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src-docs/app/molds/markdown-live.ts: -------------------------------------------------------------------------------- 1 | import {Mold, assign} from 'atril'; 2 | import marked from 'marked'; 3 | 4 | @Mold({ 5 | attributeName: 'markdown-live' 6 | }) 7 | class Ctrl { 8 | @assign element: HTMLTemplateElement; 9 | @assign expression: Function; 10 | @assign scope: any; 11 | 12 | buffer: HTMLElement; 13 | lastValue: string; 14 | 15 | constructor() { 16 | this.buffer = document.createElement('div'); 17 | this.rewrite(); 18 | } 19 | 20 | onPhase() { 21 | this.rewrite(); 22 | } 23 | 24 | rewrite() { 25 | let value = this.expression(this.scope) || '' + ''; 26 | if (value === this.lastValue) return; 27 | 28 | this.buffer.innerHTML = marked(value); 29 | 30 | // Fix code highlighting classes. 31 | let codeBlocks = this.buffer.querySelectorAll('pre code'); 32 | for (let i = 0, ii = codeBlocks.length; i < ii; ++i) { 33 | let node = codeBlocks[i]; 34 | if (node instanceof Element) node.classList.add('hljs'); 35 | } 36 | 37 | // Remove existing content. 38 | while (this.element.hasChildNodes()) { 39 | this.element.removeChild(this.element.firstChild); 40 | } 41 | 42 | // Add new content. 43 | while (this.buffer.hasChildNodes()) { 44 | this.element.appendChild(this.buffer.removeChild(this.buffer.firstChild)); 45 | } 46 | 47 | this.lastValue = value; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src-docs/html/on.md: -------------------------------------------------------------------------------- 1 | ## `on.*` 2 | 3 | Adds a listener for the given event. Executes the given statement whenever the 4 | event occurs. 5 | 6 | The event name is included as the _hint_ (the part after the dot). You can 7 | listen to any events, not just the standard ones. 8 | 9 | Example: 10 | 11 | 12 | ```html 13 | 14 | 15 | ``` 16 | 17 | ```html 18 | 19 | 20 | ``` 21 | 22 | 23 | When clicked, the outer component will log `r-r-roar`. 24 | 25 | `on.*` is similar to the native `onsomething` handlers. It's also executed with 26 | the element as its context (`this`). The main difference is that it evaluates 27 | the expression or statement against the current _viewmodel_ (component), or 28 | against a local scope that inherits from the viewmodel (`for.*` creates local 29 | scopes for cloned items). Native handlers are always evaluated against the 30 | global scope and don't have access to components. 31 | 32 | Dispatching events and reacting to events as the paradigm for communicating 33 | between components has been adopted by several major frameworks, including 34 | Angular 2, Aurelia, and Polymer, so give it a go. 35 | -------------------------------------------------------------------------------- /src-docs/styles/app.less: -------------------------------------------------------------------------------- 1 | /******************************* Dependencies ********************************/ 2 | 3 | // Core styles. 4 | @import (less) './node_modules/stylific/less/stylific'; 5 | 6 | // Styles used by highlight.js tags generated as a part of markdown compilation. 7 | @import (less) './node_modules/highlight.js/styles/ir_black.css'; 8 | 9 | /********************************** Global ***********************************/ 10 | 11 | // Global variables. 12 | @import (less) './variables'; 13 | 14 | // Misc settings. 15 | @import (less) './misc'; 16 | 17 | // Mixins. 18 | @import (less) './mixins'; 19 | 20 | // Colour mixes. 21 | @import (less) './color-mixes'; 22 | 23 | // Typographic settings. 24 | @import (less) './typography'; 25 | 26 | // Geometry settings 27 | @import (less) './layout'; 28 | 29 | /********************************* Overrides *********************************/ 30 | 31 | @import (less) './overrides/sf-article'; 32 | @import (less) './overrides/sf-footer'; 33 | @import (less) './overrides/sf-jumbo'; 34 | @import (less) './overrides/sf-icon'; 35 | 36 | /******************************** Components *********************************/ 37 | 38 | @import (less) './components/doc-banner'; 39 | @import (less) './components/doc-features'; 40 | @import (less) './components/doc-noscript'; 41 | @import (less) './components/doc-sidenav'; 42 | @import (less) './components/todo-item'; 43 | -------------------------------------------------------------------------------- /src-docs/app/lib.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'views' { 2 | var x: {[path: string]: string}; 3 | export default x; 4 | } 5 | 6 | declare module 'atril' { 7 | export function Component(config: {tagName: string}): any; 8 | export function Attribute(config: {attributeName: string}): any; 9 | export function Mold(config: {attributeName: string}): any; 10 | export function bootstrap(): void; 11 | export function bindable(target: any, propertyName: string): void; 12 | export function assign(targetOrKey: any, propertyNameOrNothing?: string): any; 13 | export const viewCache: { 14 | get(url: string): string|void; 15 | set(url: string, view: string): void; 16 | load(url: string): Promise; 17 | }; 18 | export var Meta: any; 19 | export function compileExpression(expression: string): Function; 20 | } 21 | 22 | declare module 'highlightjs' { 23 | import x = require('highlight.js'); 24 | export default x; 25 | } 26 | 27 | declare module 'marked' { 28 | var x: any; 29 | export default x; 30 | } 31 | 32 | interface Promise { 33 | then: (callback: Function) => any; 34 | catch: (callback: Function) => any; 35 | } 36 | 37 | declare var Promise: { 38 | prototype: Promise; 39 | new(callback: Function): Promise; 40 | resolve(value?: any): Promise; 41 | reject(reason?: any): Promise; 42 | }; 43 | 44 | interface HTMLTemplateElement extends HTMLElement { 45 | content?: DocumentFragment; 46 | } 47 | -------------------------------------------------------------------------------- /src-docs/html/let.md: -------------------------------------------------------------------------------- 1 | ## `let.*` 2 | 3 | Defines a new property in the current scope, assigning the given value. 4 | 5 | The reason you need this is because unlike typical expression parsers in 6 | frameworks like Angular or Polymer, expressions in `atril` don't silently 7 | swallow references to missing properties. If you try to reference a property 8 | that doesn't exist on the viewmodel, it throws an error. 9 | 10 | `let` lets you explicitly define a new property from your view. 11 | 12 | Example: 13 | 14 | 15 | ```typescript 16 | class VM { 17 | constructor() { 18 | console.log("I don't know what eidolon means"); 19 | } 20 | } 21 | ``` 22 | 23 | ```html 24 |
25 | 26 |

{{eidolon}}

27 |
28 | ``` 29 | 30 | 31 | Without `let` or an explicit property definition in the class, this would throw 32 | a missing reference error. 33 | 34 | `let` is implemented as a mold, so you can use it on a `template` tag (only the 35 | contents are included into the DOM). 36 | 37 | ```html 38 | 42 | ``` 43 | 44 | 50 | -------------------------------------------------------------------------------- /src-docs/app/molds/highlight.ts: -------------------------------------------------------------------------------- 1 | import {Mold, assign} from 'atril'; 2 | import hjs from 'highlightjs'; 3 | 4 | @Mold({ 5 | attributeName: 'highlight' 6 | }) 7 | class Ctrl { 8 | @assign element: HTMLTemplateElement; 9 | // Language. 10 | @assign hint: string; 11 | 12 | constructor() { 13 | let content = this.element.content; 14 | 15 | // Reuse or create a
.
16 |     let pre = content.firstChild instanceof HTMLPreElement ?
17 |               content.firstChild : document.createElement('pre');
18 | 
19 |     // Convert existing content into text.
20 |     let result = this.hint ? hjs.highlight(this.hint, pre.innerHTML): hjs.highlightAuto(pre.innerHTML);
21 | 
22 |     // Neuter interpolations. This is necessary because a mold's output is re-
23 |     // compiled, so interpolations would be evaluated.
24 |     result.value = result.value.replace(/\{\{((?:[^}]|}(?=[^}]))*)\}\}/g, '{{$1}}');
25 | 
26 |     // Transfer normal attributes.
27 |     for (let i = 0, ii = this.element.attributes.length; i < ii; ++i) {
28 |       let attr = this.element.attributes[i];
29 |       if (!this.looksLikeCustomAttribute(attr.name)) {
30 |         pre.setAttribute(attr.name, attr.value);
31 |       }
32 |     }
33 | 
34 |     // Render highlighted code.
35 |     pre.innerHTML = `${result.value}`;
36 |     this.element.appendChild(pre);
37 |   }
38 | 
39 |   looksLikeCustomAttribute(attributeName: string): boolean {
40 |     return /^[a-z-]+\./.test(attributeName);
41 |   }
42 | }
43 | 


--------------------------------------------------------------------------------
/src-docs/styles/components/doc-banner.less:
--------------------------------------------------------------------------------
 1 | .doc-banner {
 2 |   // Inheritance.
 3 |   .sf-jumbo();
 4 | 
 5 |   /**
 6 |    * Layout.
 7 |    */
 8 |   height: 8em;
 9 |   position: relative;
10 | 
11 |   /**
12 |    * Inner layout.
13 |    */
14 |   justify-content: space-around;
15 | 
16 |   /**
17 |    * Background.
18 |    * someone shoot me
19 |    */
20 |   background: rgba(82,144,199,1);
21 |   background: linear-gradient(to right, rgba(82,144,199,1) 0%, rgba(4,113,222,1) 100%);
22 | 
23 |   /**
24 |    * Typography.
25 |    */
26 |   text-align: center;
27 |   .sf-media-mix(font-size, 1.6 * @sf-font-size-base);
28 | 
29 |   /**
30 |    * Cosmetic.
31 |    */
32 |   .sf-shadow-minor();
33 | 
34 |   /**
35 |    * Child styles.
36 |    */
37 |   .space-out-children();
38 |   > * {
39 |     // Kill child background inherited from jumbo.
40 |     background-color: transparent;
41 | 
42 |     &.link-section {
43 |       // Layout.
44 |       position: absolute;
45 |       top: @sf-common-padding;
46 |       right: @sf-common-padding;
47 |       bottom: @sf-common-padding;
48 |       width: auto;
49 | 
50 |       // Inner layout.
51 |       display: flex;
52 |       flex-direction: column;
53 | 
54 |       // Whitespace.
55 |       margin: 0;
56 |       padding: 0;
57 | 
58 |       // Cosmetic.
59 |       font-size: 2em;
60 | 
61 |       > iframe {
62 |         font-size: 1em;
63 |         max-width: 2em;
64 |         height: 1em;
65 |         // Can't be bothered to style the insides of the iframed icon to make it
66 |         // responsive, so let's just hide it on narrow displays.
67 |         .sf-xs({display: none});
68 |         .sf-sm({display: none});
69 |       }
70 |     }
71 |   }
72 | }
73 | 


--------------------------------------------------------------------------------
/src-docs/html/index.html:
--------------------------------------------------------------------------------
 1 | 
 2 | 
 3 |   
 4 |     <%= $title || 'atril' %>
 5 |     
 6 |     
 7 |     
 8 |     
 9 |     
10 |     
11 |     
12 |     
13 | 
14 |     
15 |     <% if (prod()) { %>
16 |       
17 |     <% } else { %>
18 |       
19 |       
20 |       
21 |       
24 |     <% } %>
25 |   
26 | 
27 |   
28 |     <%= $include('$index/banner', $) %>
29 | 
30 |     
31 |
32 | <%= $content || $include('$index/index', $) %> 33 |
34 | 35 |
36 | <%= $include('$index/sidenav', $) %> 37 |
38 |
39 | 40 | <%= $include('$index/footer', $) %> 41 | 42 | 43 | 46 | 47 | -------------------------------------------------------------------------------- /src-docs/styles/variables.less: -------------------------------------------------------------------------------- 1 | /** 2 | * Global variables and/or overrides for imported variables. 3 | */ 4 | 5 | /******************************** Independent ********************************/ 6 | 7 | @svg-black: './bower_components/font-awesome-svg-png/black/svg/'; 8 | @svg-white: './bower_components/font-awesome-svg-png/white/svg/'; 9 | @svg-colored: './src-docs/svg/'; 10 | 11 | /********************************** Layout ***********************************/ 12 | 13 | // Use the entire width. 14 | @sf-screen-lg: 100%; 15 | 16 | @sf-enable-global-element-components: true; 17 | 18 | /******************************** Typography *********************************/ 19 | 20 | @sf-font-family-sans-serif: Avenir, PT Sans, Segoe UI, Verdana, sans-serif; 21 | @sf-font-family-monospace: Menlo, Andale Mono, Monaco, Consolas, monospace; 22 | 23 | /********************************** Colours **********************************/ 24 | 25 | @color-brown: brown; 26 | @color-darkorange: darken(@color-orange, 10%); 27 | @color-darkred: darken(@color-red, 10%); 28 | @color-orange: #faa221; 29 | @color-red: #f9515d; 30 | @color-yellow: #f1de1a; 31 | 32 | /** 33 | * Mainpage sketch. 34 | */ 35 | // Background. 36 | @color-beige: #fdf8e9; 37 | // Text. 38 | @color-brown: #916d4c; 39 | // Road. 40 | @color-road: #e9ca98; 41 | 42 | 43 | // Brand-specific colours. Source: http://brandcolors.net. 44 | @color-github-0: #4183c4; // unverified 45 | @color-github-1: #666666; // unverified 46 | 47 | @sf-enable-base-link-style: false; 48 | 49 | /******************************* sf-jumbo.less *******************************/ 50 | 51 | // @sf-jumbo-height: 8em; 52 | 53 | /****************************** sf-tabset.less *******************************/ 54 | 55 | @sf-enable-tabset-default-padding: false; 56 | -------------------------------------------------------------------------------- /src-docs/styles/color-mixes.less: -------------------------------------------------------------------------------- 1 | // Default link styling. 2 | a, :link { 3 | color: @sf-base-link-color; 4 | } 5 | 6 | // Special link decoration in paragraphs. 7 | p, .decorate-links { 8 | a, :link {.sf-common-link-decorations()} 9 | } 10 | 11 | // Versions of colour themes that only affect text colour. 12 | .text-brown {.color-text(@color-brown)} 13 | .text-darkorange {.color-text(@color-darkorange)} 14 | .text-darkred {.color-text(@color-darkred)} 15 | .text-info {.color-text(@sf-color-info)} 16 | .text-orange {.color-text(@color-orange)} 17 | .text-red {.color-text(@color-red)} 18 | .text-success {.color-text(@sf-color-success)} 19 | .text-warning {.color-text(@sf-color-warning)} 20 | .text-yellow {.color-text(@color-yellow)} 21 | 22 | // Defines text colour using the given colour, adjusted to be bright enough to 23 | // contrast the default background colour. Also affects SVG fill. 24 | .color-text(@color) { 25 | @c: hsl(hue(@color), saturation(@color) / 2, 30%); 26 | color: @c; 27 | fill: @c; 28 | } 29 | 30 | // Extend the base color macro to support SVG fill. 31 | .sf-colormix-base(@color, @perc) { 32 | & when not (@color = @sf-base-text-color) { 33 | @c: hsl(hue(@color), saturation(@color), 75% - luma(contrast(@sf-base-text-color)) / 2); 34 | .sf-shift-color(fill, @c, @perc); 35 | // // Disable background for svg-icons. 36 | // &[svg-icon] {background: none} 37 | } 38 | } 39 | 40 | // Add user-defined colours to the global mix. 41 | .sf-colormix-all-classes(@prefix, @affix, @perc) { 42 | &.orange@{prefix}@{affix} {.sf-colormix-base(@color-orange, @perc)} 43 | &.yellow@{prefix}@{affix} {.sf-colormix-base(@color-yellow, @perc)} 44 | // &.darkorange@{prefix}@{affix} {.sf-colormix-base(@color-darkorange, @perc)} 45 | } 46 | -------------------------------------------------------------------------------- /src-docs/app/config.ts: -------------------------------------------------------------------------------- 1 | import marked from 'marked'; 2 | import hjs from 'highlightjs'; 3 | 4 | marked.setOptions({ 5 | gfm: true, 6 | tables: true, 7 | breaks: false, 8 | sanitize: false, 9 | smartypants: false, 10 | pedantic: false, 11 | highlight: (code, lang) => { 12 | let result: hjs.IHighlightResult|hjs.IAutoHighlightResult; 13 | // highlight.js throws an error when highlighting an unknown lang. 14 | if (lang) { 15 | try { 16 | result = hjs.highlight(lang, code); 17 | } catch (err) { 18 | result = hjs.highlightAuto(code); 19 | } 20 | } else { 21 | result = hjs.highlightAuto(code); 22 | } 23 | // Neuter interpolations. This is necessary to prevent atril from 24 | // evaluating them in code blocks. 25 | result.value = result.value.replace(/\{\{((?:[^}]|}(?=[^}]))*)\}\}/g, '{{$1}}'); 26 | return result.value; 27 | } 28 | }); 29 | 30 | /** 31 | * marked rendering enhancements. 32 | */ 33 | 34 | // Default link renderer func. 35 | let renderLink = marked.Renderer.prototype.link; 36 | 37 | // Custom link renderer func that adds target="_blank" to links to other sites. 38 | // Mostly copied from the marked source. 39 | marked.Renderer.prototype.link = function(href, title, text) { 40 | if (this.options.sanitize) { 41 | let prot = ''; 42 | try { 43 | prot = decodeURIComponent(href) 44 | .replace(/[^\w:]/g, '') 45 | .toLowerCase(); 46 | } catch (e) { 47 | return ''; 48 | } 49 | if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) { 50 | return ''; 51 | } 52 | } 53 | let out = ''; 61 | return out; 62 | } 63 | -------------------------------------------------------------------------------- /src/lib.d.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------- Modules ---------------------------------*/ 2 | 3 | declare module 'zone.js' { 4 | var x; 5 | export default x; 6 | } 7 | 8 | declare var zone: any; 9 | 10 | /*-------------------------------- Built-ins --------------------------------*/ 11 | 12 | declare var Symbol: Function; 13 | 14 | interface Element { 15 | innerHTML: string; 16 | cloneNode(): Element; 17 | } 18 | 19 | interface TemplateElement extends Element { 20 | content?: DocumentFragment; 21 | } 22 | 23 | interface Object { 24 | hasOwnProperty(key: symbol): boolean; 25 | hasOwnProperty(key: symbol|string): boolean; 26 | } 27 | 28 | interface Promise { 29 | then: (callback: Function) => any; 30 | catch: (callback: Function) => any; 31 | } 32 | 33 | declare var Promise: { 34 | prototype: Promise; 35 | new(callback: Function): Promise; 36 | resolve(value?: any): Promise; 37 | reject(reason?: any): Promise; 38 | }; 39 | 40 | /*---------------------------------- Local ----------------------------------*/ 41 | 42 | interface ComponentConfig { 43 | tagName: string; 44 | } 45 | 46 | interface AssignableClass extends Function { 47 | assign?: {[propertyName: string]: string}; 48 | } 49 | 50 | interface ComponentClass extends AssignableClass { 51 | view?: string|Function; 52 | viewUrl?: string|Function; 53 | bindable?: string[]; 54 | } 55 | 56 | interface ComponentVM { 57 | element?: Element; 58 | onPhase?(): void; 59 | onDestroy?(): void; 60 | } 61 | 62 | interface AttributeConfig { 63 | attributeName: string; 64 | } 65 | 66 | interface AttributeClass extends AssignableClass {} 67 | 68 | interface AttributeCtrl { 69 | element?: Element; 70 | hint?: string; 71 | expression?: Expression; 72 | scope?: any; 73 | vm?: any; 74 | onPhase?(): void; 75 | onDestroy?(): void; 76 | } 77 | 78 | interface Expression { 79 | (scope: any, locals?: any): any; 80 | } 81 | 82 | interface TextExpression { 83 | (scope: any): string; 84 | } 85 | 86 | interface ArrayLike { 87 | [index: number]: any; 88 | length: number; 89 | } 90 | -------------------------------------------------------------------------------- /src-docs/html/if.md: -------------------------------------------------------------------------------- 1 | ## `if.` 2 | 3 | Adds the element to the DOM when the condition evaluates to truthy, and removes 4 | it when the condition evaluates to falsy. Example: 5 | 6 | ```html 7 |
8 | 9 |
I'm always visible!
10 |
I'm conditionally visible!
11 |
12 | ``` 13 | 14 | 21 | 22 | Internally, the element is cached while hidden, so adding and removing it is 23 | very cheap. 24 | 25 | To hide multiple nodes at once, use it on a `template` tag: 26 | 27 | ```html 28 |
29 | 30 | 34 |
35 | ``` 36 | 37 | 46 | 47 | ### Note 48 | 49 | You can also hide an element without removing it from the DOM by binding to its 50 | `hidden` property: 51 | 52 | ```html 53 |
54 | 55 |
I'm always visible!
56 |
I'm conditionally visible!
57 |
58 | ``` 59 | 60 | 67 | -------------------------------------------------------------------------------- /src-docs/styles/misc.less: -------------------------------------------------------------------------------- 1 | /** 2 | * Misc settings. 3 | */ 4 | 5 | // IE compat 6 | template {display: none !important} 7 | 8 | .fade { 9 | opacity: 0.5; 10 | } 11 | 12 | // Prettier horizontal rule. 13 | hr { 14 | margin-top: 2 * @sf-common-margin; 15 | margin-bottom: 2 * @sf-common-margin; 16 | border: none; 17 | border-top: 1px solid lightgrey; 18 | } 19 | 20 | // Default to circle bullets. 21 | ul { 22 | list-style-type: circle; 23 | } 24 | 25 | /** 26 | * Corrections to monospace styling. 27 | */ 28 | pre, pre code { 29 | background-color: initial; 30 | } 31 | pre {padding: 0} 32 | 33 | // Highlighted styling. 34 | .hljs { 35 | background-color: @sf-base-text-color; 36 | color: @sf-base-background-color; 37 | } 38 | 39 | /** 40 | * Shadow at the top. 41 | */ 42 | body::before { 43 | // Layout. 44 | content: ''; 45 | position: absolute; 46 | display: block; 47 | width: 100%; 48 | height: 2rem; 49 | top: -2rem; 50 | left: 0; 51 | right: 0; 52 | .sf-shadow-minor(); 53 | z-index: @sf-z-index-navbar + 1; 54 | } 55 | 56 | // Checkbox offset. 57 | label > input[type=checkbox] { 58 | display: inline-block; 59 | vertical-align: middle; 60 | position: relative; 61 | top: -0.08em; 62 | &:not(:first-child) { 63 | margin-left: @sf-common-margin / 5; 64 | } 65 | &:not(:last-child) { 66 | margin-right: @sf-common-margin / 5; 67 | } 68 | } 69 | 70 | // Heading anchor icon. 71 | .sf-h({ 72 | .heading-anchor { 73 | margin-left: @sf-common-margin / 2; 74 | visibility: hidden; 75 | opacity: 0; 76 | .sf-common-transitions(~'visibility, opacity'); 77 | } 78 | &:hover .heading-anchor, .heading-anchor:hover { 79 | visibility: visible; 80 | opacity: inherit; 81 | } 82 | }); 83 | 84 | /** 85 | * Misc components. 86 | */ 87 | 88 | todo-list { 89 | display: block; 90 | max-width: 40em; 91 | } 92 | 93 | /** 94 | * Class-based components. 95 | */ 96 | 97 | // A pair of code blocks side by side. 98 | .code-pair { 99 | display: flex; 100 | > pre { 101 | flex: 1; 102 | &:first-child { 103 | padding-left: 0; 104 | padding-right: @sf-common-padding / 2; 105 | } 106 | &:last-child { 107 | padding-left: @sf-common-padding / 2; 108 | padding-right: 0; 109 | } 110 | } 111 | } 112 | 113 | // Demo panel. 114 | .doc-demo { 115 | // Layout. 116 | display: block; 117 | // Whitespace. 118 | padding: @sf-common-padding; 119 | .space-out-children(); 120 | // Cosmetic. 121 | .sf-color(@color-yellow, false, false); 122 | } 123 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "atril", 3 | "version": "0.0.11", 4 | "description": "Experimental JS rendering library. Ideas from ReactJS, Polymer, Angular 2, Aurelia, made simple.", 5 | "main": "lib/index", 6 | "author": "Mitranim", 7 | "license": "MIT", 8 | "repository": { 9 | "type": "git", 10 | "url": "git://github.com/Mitranim/atril.git" 11 | }, 12 | "keywords": [ 13 | "rendering", 14 | "components" 15 | ], 16 | "scripts": { 17 | "jspm": "jspm", 18 | "tsd": "tsd", 19 | "install-all": "npm install && jspm install --dev && bower install && tsd update", 20 | "start": "gulp", 21 | "gulp": "gulp", 22 | "prepublish": "gulp lib:build", 23 | "bundle-sfx-prod": "jspm bundle-sfx app --minify", 24 | "build-prod": "gulp build --prod && npm run bundle-sfx-prod", 25 | "serve-prod": "npm run build-prod && gulp server", 26 | "push": "npm run build-prod && (cd dist && git add -A . && git commit -a -m autocommit && git push origin gh-pages)" 27 | }, 28 | "dependencies": { 29 | "zone.js": "angular/zone.js@master" 30 | }, 31 | "devDependencies": { 32 | "bower": "^1.4.1", 33 | "browser-sync": "^2.7.6", 34 | "gulp": "gulpjs/gulp#4.0", 35 | "gulp-autoprefixer": "^2.3.0", 36 | "gulp-filter": "^2.0.2", 37 | "gulp-html-to-js": "0.0.1", 38 | "gulp-if": "^1.2.5", 39 | "gulp-less": "^3.0.3", 40 | "gulp-load-plugins": "^0.10.0", 41 | "gulp-marked": "^1.0.0", 42 | "gulp-minify-css": "^1.1.1", 43 | "gulp-plumber": "^1.0.1", 44 | "gulp-rename": "^1.2.2", 45 | "gulp-replace": "^0.5.3", 46 | "gulp-rimraf": "^0.1.1", 47 | "gulp-sourcemaps": "^1.5.2", 48 | "gulp-statil": "0.0.4", 49 | "gulp-typescript": "^2.7.5", 50 | "gulp-watch": "^4.2.4", 51 | "highlight.js": "^8.6.0", 52 | "jspm": "^0.15.6", 53 | "stylific": "0.0.12", 54 | "tsd": "^0.6.0", 55 | "typescript": "git://github.com/microsoft/TypeScript.git", 56 | "yargs": "^3.10.0" 57 | }, 58 | "jspm": { 59 | "main": "index", 60 | "format": "cjs", 61 | "directories": { 62 | "baseURL": "dist", 63 | "lib": "lib" 64 | }, 65 | "configFile": "system.config.js", 66 | "dependencies": { 67 | "zone.js": "github:angular/zone.js@master" 68 | }, 69 | "devDependencies": { 70 | "atril": "github:Mitranim/atril@master", 71 | "highlightjs": "github:components/highlightjs@^8.5.0", 72 | "marked": "npm:marked@^0.3.3", 73 | "text": "github:systemjs/plugin-text@^0.0.2", 74 | "traceur": "github:jmcriffey/bower-traceur@0.0.88", 75 | "traceur-runtime": "github:jmcriffey/bower-traceur-runtime@0.0.88" 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src-docs/html/for.md: -------------------------------------------------------------------------------- 1 | ## `for.*` 2 | 3 | Clones an element over an iterable, making individual items available under the 4 | given key. 5 | 6 | ```html 7 |
8 | 9 | 10 | {{num}} 11 |
12 | ``` 13 | 14 | 21 | 22 | Use it on several elements at once with `template`: 23 | 24 | ```html 25 |
26 | 27 | 28 | 32 |
33 | ``` 34 | 35 | 45 | 46 | The individual indices or keys are available under the `$index` identifier. 47 | 48 | By default, this chooses the iteration strategy depending on the type of the 49 | iterable. Arrays and strings are iterated via `for (;;;)`, and hash tables are 50 | iterated via `for..in`. You can enforce one or the other via `for.X.of` and 51 | `for.X.in`. 52 | 53 | ### `for.X.of` 54 | 55 | ```html 56 |
57 | {{word}}@{{$index}} 58 |
59 | ``` 60 | 61 | 66 | 67 | ### `for.X.in` 68 | 69 | ```html 70 |
71 | {{word}}@{{$index}} 72 |
73 | ``` 74 | 75 | 80 | -------------------------------------------------------------------------------- /src-docs/html/databinding.md: -------------------------------------------------------------------------------- 1 | ## Databinding 2 | 3 | The library has one-way and two-way databinding. They're implemented as custom 4 | attributes, and you can add your own binding types. 5 | 6 | ### `bind.*` 7 | 8 | One-way binding. Generally more efficient than [two-way](databinding/#-twoway-) 9 | binding and is therefore recommended for the majority of data bingings outside 10 | inputs. 11 | 12 | Binds a property of the target element, such as `hidden`, to an expression 13 | evaluated against the surrounding scope (usually a [viewmodel](component/)). If 14 | the target element has its own viewmodel (in other words, it's a custom 15 | element), its property is also bound. See [`@bindable`](databinding/#-bindable-) 16 | below. 17 | 18 | This works for nested properties like `style.background-color`. Properties that 19 | are `camelCased` in JS must be `kebab-cased` in the attribute. To sync the value 20 | in the other direction, use an event handler with the built-in `on.*` attribute. 21 | 22 | Example: 23 | 24 | ```html 25 | 26 |

My background color is: {{color}}

27 | 28 | ``` 29 | 30 | 34 | 35 | ### `twoway.*` 36 | 37 | Two-way binding. For known input types, this is equally as efficient as one-way 38 | binding. Recommended for form inputs. 39 | 40 | Binds a property of the target element, such as `hidden` or 41 | `style.background-color`, to a property in the current scope / current 42 | viewmodel. Just like `bind.*`, it also binds the same property of the target 43 | element's [viewmodel](component/), if any; see 44 | [`@bindable`](databinding/#-bindable-). `twoway.*` automatically syncs these 45 | properties between each other. 46 | 47 | ```html 48 |

My name is: {{name}}

49 | 50 | ``` 51 | 52 | 56 | 57 | ### `@bindable` 58 | 59 | Declares a viewmodel property as bindable, so it can be set from the outside 60 | via `bind.*` or `twoway.*`. 61 | 62 | ```typescript 63 | import {Component, bindable} from 'atril'; 64 | 65 | @Component({tagName: 'my-element'}) 66 | class ViewModel { 67 | @bindable myProperty; 68 | } 69 | ``` 70 | 71 | 77 | ```javascript 78 | var Component = require('atril').Component; 79 | 80 | Component({tagName: 'my-element'})(ViewModel); 81 | 82 | function ViewModel() {} 83 | 84 | ViewModel.bindable = ['myProperty']; 85 | ``` 86 | 87 | 88 | Then you can bind that property from the outside: 89 | 90 | ```html 91 | 92 | ``` 93 | -------------------------------------------------------------------------------- /src-docs/styles/mixins.less: -------------------------------------------------------------------------------- 1 | /** 2 | * Produces a background-image rule with a data-encoded black svg with 3 | * the given name for a class with the same name. 4 | * @param String 5 | * @returns . {background-color} 6 | */ 7 | .svg-black(@name) { 8 | &.@{name} {.bg-svg-black(@name)} 9 | } 10 | 11 | /** 12 | * Produces a background-image rule with a data-encoded white svg with 13 | * the given name for a class with the same name. 14 | * @param String 15 | * @returns .-white {background-color} 16 | */ 17 | .svg-white(@name) { 18 | &.@{name}-white {.bg-svg-white(@name)} 19 | } 20 | 21 | /** 22 | * Produces a background-image rule with a data-encoded coloured svg with 23 | * the given name for a class with the same name. 24 | * @param String 25 | * @returns . {background-color} 26 | */ 27 | .svg-colored(@name) { 28 | &.@{name} {.bg-svg-colored(@name)} 29 | } 30 | 31 | /** 32 | * Produces a background-image rule with a data-encoded black svg with the 33 | * given name. 34 | * @param String 35 | * @returns {background-color} 36 | */ 37 | .bg-svg-black(@name) { 38 | @path: ~'@{svg-black}@{name}.svg'; 39 | background-image: data-uri(@path) 40 | } 41 | 42 | /** 43 | * Produces a background-image rule with a data-encoded white svg with the 44 | * given name. 45 | * @param String 46 | * @returns {background-color} 47 | */ 48 | .bg-svg-white(@name) { 49 | @path: ~'@{svg-white}@{name}.svg'; 50 | background-image: data-uri(@path) 51 | } 52 | 53 | /** 54 | * Produces a background-image rule with a data-encoded coloured svg with 55 | * the given name. 56 | * @param String 57 | * @returns {background-color} 58 | */ 59 | .bg-svg-colored(@name) { 60 | @path: ~'@{svg-colored}@{name}.svg'; 61 | background-image: data-uri(@path); 62 | } 63 | 64 | // Wide on narrow displays and narrow on wide displays. Centered across. 65 | // Expects to be a block or a flex child in a vertical flex layout. 66 | .narrow-inverse() { 67 | // Dimensions. 68 | .sf-media-mix-inverse(width, 100%); 69 | // Center as block. 70 | margin-left: auto; 71 | margin-right: auto; 72 | // Center as flex child. 73 | align-self: center; 74 | } 75 | 76 | .space-out-children() { 77 | & > *:not(:last-child) { 78 | margin-bottom: @sf-common-margin; 79 | } 80 | } 81 | 82 | .space-out-children-05() { 83 | & > *:not(:last-child) { 84 | margin-bottom: @sf-common-margin / 2; 85 | } 86 | } 87 | 88 | // Extend link decorators. 89 | .sf-common-link-decorations() { 90 | .sf-link-color(); 91 | 92 | // Indicate _blank links. 93 | &[target*=_blank]:not(.icon)::after { 94 | content: ''; 95 | /** 96 | * Layout. 97 | */ 98 | display: inline-block; 99 | vertical-align: middle; 100 | font-size: 0.8em; 101 | min-height: 1em; 102 | min-width: 1em; 103 | margin-left: @sf-common-margin / 5; 104 | 105 | /** 106 | * Background icon. 107 | */ 108 | .bg-svg-black(external-link); 109 | background-position-x: 100%; 110 | background-position-y: 50%; 111 | background-size: contain; 112 | background-repeat: no-repeat; 113 | 114 | /** 115 | * Cosmetic. 116 | */ 117 | opacity: 0.3; 118 | } 119 | 120 | // Remove link decorations from icon links. 121 | &.icon { 122 | border: none; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/bindings.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import {compileExpression} from './bindings'; 4 | import {Meta} from './tree'; 5 | import * as utils from './utils'; 6 | 7 | export class AttributeBinding { 8 | attr: Attr; 9 | VM: Function; 10 | vm: AttributeCtrl; 11 | 12 | constructor(attr: Attr, VM: Function) { 13 | this.attr = attr; 14 | this.VM = VM; 15 | } 16 | 17 | refreshAndPhase(element: Element, meta: Meta): boolean { 18 | this.refreshState(element, meta); 19 | return this.phase(); 20 | } 21 | 22 | refreshState(element: Element, meta: Meta): void { 23 | if (!this.isNew) return; 24 | let attr = this.attr; 25 | this.vm = utils.instantiate(this.VM, { 26 | attribute: attr, 27 | element: element, 28 | get expression() {return compileExpression(attr.value)}, 29 | get scope() {return meta.getScope()}, 30 | get hint() {return attr.name.match(/^[a-z-]+\.(.*)/)[1]}, 31 | vm: meta.vm 32 | }); 33 | } 34 | 35 | // The return value indicates if the attribute was phased. Used to decide if 36 | // the mold output needs to be recompiled and/or re-rendered. 37 | phase(): boolean { 38 | if (typeof this.vm.onPhase === 'function') { 39 | return this.vm.onPhase(), true; 40 | } 41 | return false; 42 | } 43 | 44 | destroy(): void { 45 | utils.assert(!!this.vm, `unexpected destroy() call on binding without vm:`, this); 46 | if (typeof this.vm.onDestroy === 'function') { 47 | this.vm.onDestroy(); 48 | } 49 | this.vm = null; 50 | } 51 | 52 | get isNew(): boolean {return !this.vm} 53 | } 54 | 55 | export class AttributeInterpolation { 56 | attr: Attr; 57 | expression: TextExpression; 58 | constructor(attr: Attr) { 59 | this.attr = attr; 60 | this.expression = compileInterpolation(attr.value); 61 | } 62 | } 63 | 64 | // Problem: provides access to globals. 65 | export function compileExpression(expression: string): Expression { 66 | if (!expression) return () => undefined; 67 | 68 | let returnPrefix = ~expression.indexOf(';') ? '' : 'return '; 69 | let body = `with (arguments[0]) with (arguments[1]) { 70 | return function() {'use strict'; 71 | ${returnPrefix}${expression} 72 | }.call(this); 73 | }`; 74 | let func = new Function(body); 75 | 76 | return function(scope: any, locals?: any): any { 77 | // Prevent `with` from throwing an error when `scope` and/or `locals` have 78 | // no properties. 79 | if (scope == null) scope = Object.create(null); 80 | if (locals == null) locals = Object.create(null); 81 | 82 | return func.call(this === window ? scope : this, scope, locals); 83 | }; 84 | } 85 | 86 | export function hasInterpolation(text: string): boolean { 87 | return /\{\{((?:[^}]|}(?=[^}]))*)\}\}/g.test(text); 88 | } 89 | 90 | export function compileInterpolation(text: string): TextExpression { 91 | if (!text) return () => ''; 92 | 93 | let reg = /\{\{((?:[^}]|}(?=[^}]))*)\}\}/g; 94 | let result: RegExpExecArray; 95 | let collection: (string|Expression)[] = []; 96 | let lastIndex: number = 0; 97 | 98 | while (result = reg.exec(text)) { 99 | let slice = text.slice(lastIndex, result.index); 100 | if (slice) collection.push(slice); 101 | lastIndex = result.index + result[0].length; 102 | collection.push(compileExpression(result[1])); 103 | } 104 | let slice = text.slice(lastIndex); 105 | if (slice) collection.push(slice); 106 | 107 | return function(scope: any): string { 108 | let total = ''; 109 | for (let item of collection) { 110 | if (typeof item === 'string') total += item; 111 | else { 112 | let result = (item).call(this, scope); 113 | if (result != null) total += result; 114 | } 115 | } 116 | return total; 117 | }; 118 | } 119 | -------------------------------------------------------------------------------- /src/view.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import {compileNode} from './compile'; 4 | import * as utils from './utils'; 5 | 6 | export class View { 7 | VM: ComponentClass; 8 | loading: boolean = false; 9 | failed: boolean = false; 10 | 11 | constructor(VM: ComponentClass) { 12 | this.VM = VM; 13 | } 14 | 15 | tryToCompile(virtual: Element): void { 16 | if (this.loading) return; 17 | 18 | let view: any = this.VM.view; 19 | if (typeof view === 'string') { 20 | this.compileView(view, virtual); 21 | return; 22 | } 23 | 24 | let url: any = this.VM.viewUrl; 25 | if (typeof url === 'string' && url) { 26 | let view = this.getViewByUrl(url, virtual); 27 | if (typeof view === 'string') this.compileView(view, virtual); 28 | return; 29 | } 30 | 31 | this.compileView('', virtual); 32 | } 33 | 34 | compileView(view: string, virtual: Element): void { 35 | virtual.innerHTML = view; 36 | compileNode(virtual); 37 | } 38 | 39 | loadViewFromPromise(promise: Promise, virtual: Element): void { 40 | this.loading = true; 41 | promise 42 | .then((result: any) => { 43 | this.loading = false; 44 | if (typeof result === 'string') { 45 | this.compileView(result, virtual); 46 | return; 47 | } 48 | utils.warn('expected a view promise to resolve to a string, got:', result); 49 | return Promise.reject(`expected a view promise to resolve to a string, got: ${result}`); 50 | }) 51 | .catch(err => { 52 | this.loading = false; 53 | this.failed = true; 54 | return Promise.reject(err); 55 | }); 56 | } 57 | 58 | getViewByUrl(url: string, virtual: Element): string|void { 59 | let view = viewCache.get(url); 60 | if (view) return view; 61 | this.loadViewFromPromise(viewCache.load(url), virtual); 62 | } 63 | } 64 | 65 | export const viewCache = { 66 | private views: <{[url: string]: string}>Object.create(null), 67 | private promises: <{[url: string]: Promise}>Object.create(null), 68 | 69 | get(url: string): string|void { 70 | return viewCache.views[url] || undefined; 71 | }, 72 | 73 | set(url: string, view: string): void { 74 | utils.assert(typeof view === 'string', 75 | 'a view must be a string, received:', view); 76 | viewCache.views[url] = view; 77 | }, 78 | 79 | // zone.js ensures the availability of the global Promise constructor. 80 | load(url: string): Promise { 81 | if (viewCache.promises[url]) return viewCache.promises[url]; 82 | 83 | if (viewCache.views[url]) { 84 | let promise = Promise.resolve(viewCache.views[url]); 85 | viewCache.promises[url] = promise; 86 | return promise; 87 | } 88 | 89 | return viewCache.promises[url] = new Promise((resolve, reject) => { 90 | let xhr = new XMLHttpRequest(); 91 | 92 | function fail(): void { 93 | let msg = `failed to load view for url ${url}`; 94 | utils.warn(msg); 95 | reject(msg); 96 | } 97 | 98 | function ok(): void { 99 | if (!(xhr.status >= 200) || !(xhr.status <= 299)) { 100 | return fail(); 101 | } 102 | 103 | let result = xhr.responseText; 104 | 105 | if (/application\/json/.test(xhr.getResponseHeader('Content-Type'))) { 106 | try { 107 | let value = JSON.parse(result); 108 | if (typeof value === 'string') result = value; 109 | else return fail(); 110 | } catch (err) {return fail()} 111 | } 112 | 113 | viewCache.set(url, result); 114 | resolve(result); 115 | } 116 | 117 | xhr.onabort = xhr.onerror = xhr.ontimeout = fail; 118 | xhr.onload = ok; 119 | 120 | xhr.open('GET', url, true); 121 | xhr.send(); 122 | }); 123 | } 124 | }; 125 | -------------------------------------------------------------------------------- /lib/decorators.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var utils = require('./utils'); 3 | exports.registeredComponents = Object.create(null); 4 | exports.registeredAttributes = Object.create(null); 5 | exports.registeredMolds = Object.create(null); 6 | function Component(config) { 7 | var tagRegex = /^[a-z][a-z-]*[a-z]$/; 8 | // Type checks. 9 | utils.assert(typeof config.tagName === 'string', "expected a string tagname, got:", config.tagName); 10 | utils.assert(tagRegex.test(config.tagName), "the tagname must match regex " + tagRegex + ", got:", config.tagName); 11 | return function (VM) { 12 | utils.assert(typeof VM === 'function', "expected a component class, got:", VM); 13 | utils.assert(!exports.registeredComponents[config.tagName], "unexpected redefinition of component with tagname " + config.tagName); 14 | exports.registeredComponents[config.tagName] = VM; 15 | }; 16 | } 17 | exports.Component = Component; 18 | function Attribute(config) { 19 | var nameRegex = /^[a-z][a-z-]*[a-z]$/; 20 | // Type checks. 21 | utils.assert(typeof config.attributeName === 'string', "expected a string attribute name, got:", config.attributeName); 22 | utils.assert(nameRegex.test(config.attributeName), "the attribute name must match regex " + nameRegex + ", got:", config.attributeName); 23 | utils.assert(!exports.registeredAttributes[config.attributeName], "unexpected redefinition of attribute " + config.attributeName); 24 | return function (VM) { 25 | utils.assert(typeof VM === 'function', "expected an attribute class, got:", VM); 26 | exports.registeredAttributes[config.attributeName] = VM; 27 | }; 28 | } 29 | exports.Attribute = Attribute; 30 | function Mold(config) { 31 | return function (VM) { 32 | Attribute(config)(VM); 33 | exports.registeredMolds[config.attributeName] = true; 34 | }; 35 | } 36 | exports.Mold = Mold; 37 | // Marks a property as bindable for databinding. Example usage: 38 | // class X { 39 | // @bindable myProperty: any; 40 | // } 41 | function bindable(target, propertyName) { 42 | if (!target) 43 | return; 44 | var VM = (target.constructor); 45 | if (!(VM.bindable instanceof Array)) 46 | VM.bindable = []; 47 | if (!~VM.bindable.indexOf(propertyName)) 48 | VM.bindable.push(propertyName); 49 | } 50 | exports.bindable = bindable; 51 | // Utility to check if the given property is bindable on the given VM. 52 | function isBindable(vm, propertyPath) { 53 | var VM = vm.constructor; 54 | var bindable = VM.bindable; 55 | return bindable instanceof Array && !!~bindable.indexOf(propertyPath); 56 | } 57 | exports.isBindable = isBindable; 58 | // Requests contextual autoassignment of the given class property. The value is 59 | // identified either by the property name or by a string passed to the 60 | // decorator. Example usage: 61 | // class X { 62 | // @assign element: Element; 63 | // } 64 | function assign(targetOrKey, keyOrNothing) { 65 | // Usage without parentheses: @assign myProperty 66 | if (targetOrKey != null && typeof targetOrKey === 'object' && typeof keyOrNothing === 'string') { 67 | return assignBase(keyOrNothing)(targetOrKey, keyOrNothing); 68 | } 69 | // Usage with parentheses: @assign('key') myProperty 70 | return assignBase(targetOrKey); 71 | } 72 | exports.assign = assign; 73 | function assignBase(tokenName) { 74 | utils.assert(typeof tokenName === 'string', 'expected a string token, got:', tokenName); 75 | return function (target, propertyName) { 76 | utils.assert(target != null && typeof target === 'object' && 77 | typeof target.constructor === 'function' && typeof propertyName === 'string', "expected a class prototype, got:", target); 78 | var constructor = target.constructor; 79 | if (!constructor.assign) 80 | constructor.assign = {}; 81 | constructor.assign[propertyName] = tokenName; 82 | }; 83 | } 84 | -------------------------------------------------------------------------------- /src/decorators.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import * as utils from './utils'; 4 | 5 | export const registeredComponents: {[tagName: string]: ComponentClass} = Object.create(null); 6 | export const registeredAttributes: {[attributeName: string]: Function} = Object.create(null); 7 | export const registeredMolds: {[attributeName: string]: boolean} = Object.create(null); 8 | 9 | export function Component(config: ComponentConfig) { 10 | let tagRegex = /^[a-z][a-z-]*[a-z]$/; 11 | 12 | // Type checks. 13 | utils.assert(typeof config.tagName === 'string', `expected a string tagname, got:`, config.tagName); 14 | utils.assert(tagRegex.test(config.tagName), `the tagname must match regex ${tagRegex}, got:`, config.tagName); 15 | 16 | return function(VM: ComponentClass) { 17 | utils.assert(typeof VM === 'function', `expected a component class, got:`, VM); 18 | utils.assert(!registeredComponents[config.tagName], 19 | `unexpected redefinition of component with tagname ${config.tagName}`); 20 | registeredComponents[config.tagName] = VM; 21 | }; 22 | } 23 | 24 | export function Attribute(config: AttributeConfig) { 25 | let nameRegex = /^[a-z][a-z-]*[a-z]$/; 26 | 27 | // Type checks. 28 | utils.assert(typeof config.attributeName === 'string', 29 | `expected a string attribute name, got:`, config.attributeName); 30 | utils.assert(nameRegex.test(config.attributeName), 31 | `the attribute name must match regex ${nameRegex}, got:`, config.attributeName); 32 | utils.assert(!registeredAttributes[config.attributeName], 33 | `unexpected redefinition of attribute ${config.attributeName}`); 34 | 35 | return function(VM: AttributeClass) { 36 | utils.assert(typeof VM === 'function', `expected an attribute class, got:`, VM); 37 | registeredAttributes[config.attributeName] = VM; 38 | }; 39 | } 40 | 41 | export function Mold(config: AttributeConfig) { 42 | return function(VM: AttributeClass) { 43 | Attribute(config)(VM); 44 | registeredMolds[config.attributeName] = true; 45 | }; 46 | } 47 | 48 | // Marks a property as bindable for databinding. Example usage: 49 | // class X { 50 | // @bindable myProperty: any; 51 | // } 52 | export function bindable(target: any, propertyName: string): void { 53 | if (!target) return; 54 | let VM = (target.constructor); 55 | if (!(VM.bindable instanceof Array)) VM.bindable = []; 56 | if (!~VM.bindable.indexOf(propertyName)) VM.bindable.push(propertyName); 57 | } 58 | 59 | // Utility to check if the given property is bindable on the given VM. 60 | export function isBindable(vm: ComponentVM, propertyPath: string): boolean { 61 | let VM = vm.constructor; 62 | let bindable = VM.bindable; 63 | return bindable instanceof Array && !!~bindable.indexOf(propertyPath); 64 | } 65 | 66 | // Requests contextual autoassignment of the given class property. The value is 67 | // identified either by the property name or by a string passed to the 68 | // decorator. Example usage: 69 | // class X { 70 | // @assign element: Element; 71 | // } 72 | export function assign(targetOrKey: any, keyOrNothing?: any): any { 73 | // Usage without parentheses: @assign myProperty 74 | if (targetOrKey != null && typeof targetOrKey === 'object' && typeof keyOrNothing === 'string') { 75 | return assignBase(keyOrNothing)(targetOrKey, keyOrNothing); 76 | } 77 | // Usage with parentheses: @assign('key') myProperty 78 | return assignBase(targetOrKey); 79 | } 80 | 81 | function assignBase(tokenName: string) { 82 | utils.assert(typeof tokenName === 'string', 'expected a string token, got:', tokenName); 83 | 84 | return function(target: {}, propertyName: string): void { 85 | utils.assert(target != null && typeof target === 'object' && 86 | typeof target.constructor === 'function' && typeof propertyName === 'string', 87 | `expected a class prototype, got:`, target); 88 | 89 | let constructor: AttributeClass|ComponentClass = target.constructor; 90 | if (!constructor.assign) constructor.assign = {}; 91 | constructor.assign[propertyName] = tokenName; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /lib/view.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var compile_1 = require('./compile'); 3 | var utils = require('./utils'); 4 | var View = (function () { 5 | function View(VM) { 6 | this.loading = false; 7 | this.failed = false; 8 | this.VM = VM; 9 | } 10 | View.prototype.tryToCompile = function (virtual) { 11 | if (this.loading) 12 | return; 13 | var view = this.VM.view; 14 | if (typeof view === 'string') { 15 | this.compileView(view, virtual); 16 | return; 17 | } 18 | var url = this.VM.viewUrl; 19 | if (typeof url === 'string' && url) { 20 | var view_1 = this.getViewByUrl(url, virtual); 21 | if (typeof view_1 === 'string') 22 | this.compileView(view_1, virtual); 23 | return; 24 | } 25 | this.compileView('', virtual); 26 | }; 27 | View.prototype.compileView = function (view, virtual) { 28 | virtual.innerHTML = view; 29 | compile_1.compileNode(virtual); 30 | }; 31 | View.prototype.loadViewFromPromise = function (promise, virtual) { 32 | var _this = this; 33 | this.loading = true; 34 | promise 35 | .then(function (result) { 36 | _this.loading = false; 37 | if (typeof result === 'string') { 38 | _this.compileView(result, virtual); 39 | return; 40 | } 41 | utils.warn('expected a view promise to resolve to a string, got:', result); 42 | return Promise.reject("expected a view promise to resolve to a string, got: " + result); 43 | }) 44 | .catch(function (err) { 45 | _this.loading = false; 46 | _this.failed = true; 47 | return Promise.reject(err); 48 | }); 49 | }; 50 | View.prototype.getViewByUrl = function (url, virtual) { 51 | var view = exports.viewCache.get(url); 52 | if (view) 53 | return view; 54 | this.loadViewFromPromise(exports.viewCache.load(url), virtual); 55 | }; 56 | return View; 57 | })(); 58 | exports.View = View; 59 | exports.viewCache = { 60 | views: Object.create(null), 61 | promises: Object.create(null), 62 | get: function (url) { 63 | return exports.viewCache.views[url] || undefined; 64 | }, 65 | set: function (url, view) { 66 | utils.assert(typeof view === 'string', 'a view must be a string, received:', view); 67 | exports.viewCache.views[url] = view; 68 | }, 69 | // zone.js ensures the availability of the global Promise constructor. 70 | load: function (url) { 71 | if (exports.viewCache.promises[url]) 72 | return exports.viewCache.promises[url]; 73 | if (exports.viewCache.views[url]) { 74 | var promise = Promise.resolve(exports.viewCache.views[url]); 75 | exports.viewCache.promises[url] = promise; 76 | return promise; 77 | } 78 | return exports.viewCache.promises[url] = new Promise(function (resolve, reject) { 79 | var xhr = new XMLHttpRequest(); 80 | function fail() { 81 | var msg = "failed to load view for url " + url; 82 | utils.warn(msg); 83 | reject(msg); 84 | } 85 | function ok() { 86 | if (!(xhr.status >= 200) || !(xhr.status <= 299)) { 87 | return fail(); 88 | } 89 | var result = xhr.responseText; 90 | if (/application\/json/.test(xhr.getResponseHeader('Content-Type'))) { 91 | try { 92 | var value = JSON.parse(result); 93 | if (typeof value === 'string') 94 | result = value; 95 | else 96 | return fail(); 97 | } 98 | catch (err) { 99 | return fail(); 100 | } 101 | } 102 | exports.viewCache.set(url, result); 103 | resolve(result); 104 | } 105 | xhr.onabort = xhr.onerror = xhr.ontimeout = fail; 106 | xhr.onload = ok; 107 | xhr.open('GET', url, true); 108 | xhr.send(); 109 | }); 110 | } 111 | }; 112 | -------------------------------------------------------------------------------- /lib/bindings.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var bindings_1 = require('./bindings'); 3 | var utils = require('./utils'); 4 | var AttributeBinding = (function () { 5 | function AttributeBinding(attr, VM) { 6 | this.attr = attr; 7 | this.VM = VM; 8 | } 9 | AttributeBinding.prototype.refreshAndPhase = function (element, meta) { 10 | this.refreshState(element, meta); 11 | return this.phase(); 12 | }; 13 | AttributeBinding.prototype.refreshState = function (element, meta) { 14 | if (!this.isNew) 15 | return; 16 | var attr = this.attr; 17 | this.vm = utils.instantiate(this.VM, { 18 | attribute: attr, 19 | element: element, 20 | get expression() { return bindings_1.compileExpression(attr.value); }, 21 | get scope() { return meta.getScope(); }, 22 | get hint() { return attr.name.match(/^[a-z-]+\.(.*)/)[1]; }, 23 | vm: meta.vm 24 | }); 25 | }; 26 | // The return value indicates if the attribute was phased. Used to decide if 27 | // the mold output needs to be recompiled and/or re-rendered. 28 | AttributeBinding.prototype.phase = function () { 29 | if (typeof this.vm.onPhase === 'function') { 30 | return this.vm.onPhase(), true; 31 | } 32 | return false; 33 | }; 34 | AttributeBinding.prototype.destroy = function () { 35 | utils.assert(!!this.vm, "unexpected destroy() call on binding without vm:", this); 36 | if (typeof this.vm.onDestroy === 'function') { 37 | this.vm.onDestroy(); 38 | } 39 | this.vm = null; 40 | }; 41 | Object.defineProperty(AttributeBinding.prototype, "isNew", { 42 | get: function () { return !this.vm; }, 43 | enumerable: true, 44 | configurable: true 45 | }); 46 | return AttributeBinding; 47 | })(); 48 | exports.AttributeBinding = AttributeBinding; 49 | var AttributeInterpolation = (function () { 50 | function AttributeInterpolation(attr) { 51 | this.attr = attr; 52 | this.expression = compileInterpolation(attr.value); 53 | } 54 | return AttributeInterpolation; 55 | })(); 56 | exports.AttributeInterpolation = AttributeInterpolation; 57 | // Problem: provides access to globals. 58 | function compileExpression(expression) { 59 | if (!expression) 60 | return function () { return undefined; }; 61 | var returnPrefix = ~expression.indexOf(';') ? '' : 'return '; 62 | var body = "with (arguments[0]) with (arguments[1]) {\n return function() {'use strict';\n " + returnPrefix + expression + "\n }.call(this);\n }"; 63 | var func = new Function(body); 64 | return function (scope, locals) { 65 | // Prevent `with` from throwing an error when `scope` and/or `locals` have 66 | // no properties. 67 | if (scope == null) 68 | scope = Object.create(null); 69 | if (locals == null) 70 | locals = Object.create(null); 71 | return func.call(this === window ? scope : this, scope, locals); 72 | }; 73 | } 74 | exports.compileExpression = compileExpression; 75 | function hasInterpolation(text) { 76 | return /\{\{((?:[^}]|}(?=[^}]))*)\}\}/g.test(text); 77 | } 78 | exports.hasInterpolation = hasInterpolation; 79 | function compileInterpolation(text) { 80 | if (!text) 81 | return function () { return ''; }; 82 | var reg = /\{\{((?:[^}]|}(?=[^}]))*)\}\}/g; 83 | var result; 84 | var collection = []; 85 | var lastIndex = 0; 86 | while (result = reg.exec(text)) { 87 | var slice_1 = text.slice(lastIndex, result.index); 88 | if (slice_1) 89 | collection.push(slice_1); 90 | lastIndex = result.index + result[0].length; 91 | collection.push(bindings_1.compileExpression(result[1])); 92 | } 93 | var slice = text.slice(lastIndex); 94 | if (slice) 95 | collection.push(slice); 96 | return function (scope) { 97 | var total = ''; 98 | for (var _i = 0; _i < collection.length; _i++) { 99 | var item = collection[_i]; 100 | if (typeof item === 'string') 101 | total += item; 102 | else { 103 | var result_1 = item.call(this, scope); 104 | if (result_1 != null) 105 | total += result_1; 106 | } 107 | } 108 | return total; 109 | }; 110 | } 111 | exports.compileInterpolation = compileInterpolation; 112 | -------------------------------------------------------------------------------- /src-docs/app/typings/highlightjs/highlightjs.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for highlight.js v8.2.0 2 | // Project: https://github.com/isagalaev/highlight.js 3 | // Definitions by: Niklas Mollenhauer , Jeremy Hull 4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped 5 | 6 | declare module "highlight.js" 7 | { 8 | module hljs 9 | { 10 | export function highlight( 11 | name: string, 12 | value: string, 13 | ignore_illegals?: boolean, 14 | continuation?: boolean) : IHighlightResult; 15 | export function highlightAuto( 16 | value: string, 17 | languageSubset?: string[]) : IAutoHighlightResult; 18 | 19 | export function fixMarkup(value: string) : string; 20 | 21 | export function highlightBlock(block: Node) : void; 22 | 23 | export function configure(options: IOptions): void; 24 | 25 | export function initHighlighting(): void; 26 | export function initHighlightingOnLoad(): void; 27 | 28 | export function registerLanguage( 29 | name: string, 30 | language: (hljs?: HLJSStatic) => IModeBase): void; 31 | export function listLanguages(): string[]; 32 | export function getLanguage(name: string): IMode; 33 | 34 | export function inherit(parent: Object, obj: Object): Object; 35 | 36 | // Common regexps 37 | export var IDENT_RE: string; 38 | export var UNDERSCORE_IDENT_RE: string; 39 | export var NUMBER_RE: string; 40 | export var C_NUMBER_RE: string; 41 | export var BINARY_NUMBER_RE: string; 42 | export var RE_STARTERS_RE: string; 43 | 44 | // Common modes 45 | export var BACKSLASH_ESCAPE : IMode; 46 | export var APOS_STRING_MODE : IMode; 47 | export var QUOTE_STRING_MODE : IMode; 48 | export var PHRASAL_WORDS_MODE : IMode; 49 | export var C_LINE_COMMENT_MODE : IMode; 50 | export var C_BLOCK_COMMENT_MODE : IMode; 51 | export var HASH_COMMENT_MODE : IMode; 52 | export var NUMBER_MODE : IMode; 53 | export var C_NUMBER_MODE : IMode; 54 | export var BINARY_NUMBER_MODE : IMode; 55 | export var CSS_NUMBER_MODE : IMode; 56 | export var REGEX_MODE : IMode; 57 | export var TITLE_MODE : IMode; 58 | export var UNDERSCORE_TITLE_MODE : IMode; 59 | 60 | export interface IHighlightResultBase 61 | { 62 | relevance: number; 63 | language: string; 64 | value: string; 65 | } 66 | 67 | export interface IAutoHighlightResult extends IHighlightResultBase 68 | { 69 | second_best?: IAutoHighlightResult; 70 | } 71 | 72 | export interface IHighlightResult extends IHighlightResultBase 73 | { 74 | top: ICompiledMode; 75 | } 76 | 77 | export interface HLJSStatic 78 | { 79 | inherit(parent: Object, obj: Object): Object; 80 | 81 | // Common regexps 82 | IDENT_RE: string; 83 | UNDERSCORE_IDENT_RE: string; 84 | NUMBER_RE: string; 85 | C_NUMBER_RE: string; 86 | BINARY_NUMBER_RE: string; 87 | RE_STARTERS_RE: string; 88 | 89 | // Common modes 90 | BACKSLASH_ESCAPE : IMode; 91 | APOS_STRING_MODE : IMode; 92 | QUOTE_STRING_MODE : IMode; 93 | PHRASAL_WORDS_MODE : IMode; 94 | C_LINE_COMMENT_MODE : IMode; 95 | C_BLOCK_COMMENT_MODE : IMode; 96 | HASH_COMMENT_MODE : IMode; 97 | NUMBER_MODE : IMode; 98 | C_NUMBER_MODE : IMode; 99 | BINARY_NUMBER_MODE : IMode; 100 | CSS_NUMBER_MODE : IMode; 101 | REGEX_MODE : IMode; 102 | TITLE_MODE : IMode; 103 | UNDERSCORE_TITLE_MODE : IMode; 104 | } 105 | 106 | // Reference: 107 | // https://github.com/isagalaev/highlight.js/blob/master/docs/reference.rst 108 | export interface IModeBase 109 | { 110 | className?: string; 111 | aliases?: string[]; 112 | begin?: string; 113 | end?: string; 114 | case_insensitive?: boolean; 115 | beginKeyword?: string; 116 | endsWithParent?: boolean; 117 | lexems?: string; 118 | illegal?: string; 119 | excludeBegin?: boolean; 120 | excludeEnd?: boolean; 121 | returnBegin?: boolean; 122 | returnEnd?: boolean; 123 | starts?: string; 124 | subLanguage?: string; 125 | subLanguageMode?: string; 126 | relevance?: number; 127 | variants?: IMode[]; 128 | } 129 | 130 | export interface IMode extends IModeBase 131 | { 132 | keywords?: any; 133 | contains?: IMode[]; 134 | } 135 | 136 | export interface ICompiledMode extends IModeBase 137 | { 138 | compiled: boolean; 139 | contains?: ICompiledMode[]; 140 | keywords?: Object; 141 | terminators: RegExp; 142 | terminator_end?: string; 143 | } 144 | 145 | export interface IOptions 146 | { 147 | classPrefix?: string; 148 | tabReplace?: string; 149 | useBR?: boolean; 150 | languages?: string[]; 151 | } 152 | } 153 | export = hljs; 154 | } 155 | -------------------------------------------------------------------------------- /src/boot.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 'Thou shalt not comment.'; 3 | 4 | import 'zone.js'; 5 | import * as utils from './utils'; 6 | import {View} from './view'; 7 | import {compileNode} from './compile'; 8 | import {registeredComponents, registeredAttributes} from './decorators'; 9 | import {Root, roots, Meta, flushQueue} from './tree'; 10 | 11 | let reflowStackDepth = 0; 12 | const maxRecursiveReflows = 10; 13 | let reflowScheduled: boolean = false; 14 | 15 | const localZone = zone.fork({ 16 | afterTask: function() { 17 | // zone.js automatically reruns a task after ≈1 s if the task throws. It 18 | // also hides all exceptions after the first during these retries. For us, 19 | // if a binding or component consistently throws during a phase, it causes 20 | // continuous reflows. To avoid that, we have to capture the exception. 21 | // try { 22 | reflowStackDepth = 0; 23 | reflow(); 24 | flushQueue(); 25 | // } 26 | // catch (err) {utils.error(err)} 27 | } 28 | }); 29 | 30 | export function scheduleReflow(): void { 31 | reflowScheduled = true; 32 | } 33 | 34 | function reflow() { 35 | reflowStackDepth++; 36 | if (reflowStackDepth >= maxRecursiveReflows) { 37 | throw new Error(`reached ${maxRecursiveReflows} recursive reflow phases, aborting`); 38 | } 39 | reflowWithUnlimitedStack(); 40 | if (reflowScheduled) { 41 | reflowScheduled = false; 42 | reflow(); 43 | } 44 | } 45 | 46 | function reflowWithUnlimitedStack(): void { 47 | for (let i = 0, ii = roots.length; i < ii; ++i) { 48 | let root = roots[i]; 49 | if (!root.real.parentNode) { 50 | destroy(root.virtual); 51 | roots.splice(i, 1); 52 | continue; 53 | } 54 | Meta.getMeta(root.virtual).phase(); 55 | } 56 | } 57 | 58 | function destroy(virtual: Element): void { 59 | let meta = Meta.getMeta(virtual); 60 | meta.destroy(); 61 | let nodes = virtual.childNodes; 62 | for (let i = 0, ii = nodes.length; i < ii; ++i) { 63 | let node = nodes[i]; 64 | if (node instanceof Element) destroy(node); 65 | } 66 | } 67 | 68 | export function bootstrap(): void { 69 | // IE10 compat: doesn't support `apply` for function expressions. Have to 70 | // define it in a statement. 71 | function boot(element: Element = document.body): void { 72 | utils.assert(element instanceof Element, `bootstrap expects an Element, got:`, element); 73 | // Don't register components twice. 74 | for (let root of roots) { 75 | if (root.real === element) return; 76 | } 77 | 78 | let VM = registeredComponents[element.tagName.toLowerCase()]; 79 | if (VM) { 80 | roots.push(createRootAt(element, VM)); 81 | return; 82 | } 83 | 84 | // Child scan must be breadth-first because a child may register the current 85 | // element as a root. If we go depth-first, we may end up with a root that 86 | // is also a descendant of another root. So we need two passes over the 87 | // child list. 88 | let nodes = element.childNodes; 89 | // First pass. 90 | for (let i = 0, ii = nodes.length; i < ii; ++i) { 91 | let node = nodes[i]; 92 | if (node instanceof Element) { 93 | // Check if there's a least one registered custom attribute for this 94 | // element (or a mold, if this is a template). Unlike the normal compile 95 | // process, this doesn't throw an error in case of mismatch. 96 | let attrs = node.attributes; 97 | for (let i = 0, ii = attrs.length; i < ii; ++i) { 98 | let attr = attrs[i]; 99 | if (utils.looksLikeCustomAttribute(attr.name)) { 100 | if (utils.customAttributeName(attr.name) in registeredAttributes) { 101 | let root = createRootAt(element); 102 | compileNode(root.virtual); 103 | roots.push(root); 104 | return; 105 | } 106 | } 107 | } 108 | } 109 | } 110 | // Second pass. 111 | for (let i = 0, ii = nodes.length; i < ii; ++i) { 112 | let node = nodes[i]; 113 | if (node instanceof Element) boot(node); 114 | } 115 | } 116 | utils.onload(() => {localZone.run(boot)}); 117 | } 118 | 119 | function createRootAt(element: Element, VM?: ComponentClass): Root { 120 | let root = new Root(); 121 | root.real = element; 122 | 123 | let virtual = utils.cloneDeep(element); 124 | let meta = Meta.addRootMeta(virtual, element); 125 | 126 | if (VM) { 127 | meta.VM = VM; 128 | meta.view = new View(VM); 129 | // view should take care of transclusion 130 | meta.view.tryToCompile(virtual); 131 | } 132 | 133 | root.virtual = virtual; 134 | return root; 135 | } 136 | -------------------------------------------------------------------------------- /notes.md: -------------------------------------------------------------------------------- 1 | # Possible performance optimisations 2 | 3 | `for.*` keeps references to unused virtual nodes for fast reuse. This is a 4 | potential memory "leak" in a sense that if the viewmodel initially requires a 5 | lot of nodes but later only needs a few, the stashed nodes only gunk up the 6 | memory. Might want to keep track and discard nodes that have been unused for 7 | many phases (keeping an average index as an integer should be enough). 8 | 9 | # Planned transclusion semantics 10 | 11 | Components and molds serve complementary roles. 12 | 13 | A component creates a viewmodel isolated from the outer scope, and a template 14 | that defines how that viewmodel should be rendered. Rendering is managed 15 | automatically by atril, using the virtual DOM, and a component is not allowed 16 | to mess with it, for efficiency and safety reasons. 17 | 18 | A mold doesn't create a viewmodel. Because of that, it doesn't need to be 19 | isolated from the outer DOM, and is allowed to mess with it in arbitrary ways. 20 | For efficiency and stability, this is done through the virtual DOM, so a mold is 21 | not allowed to mess with the real DOM. 22 | 23 | No planned support for `` because it can potentially 24 | break things like `for.="..."` by changing the order of transcluded nodes in the 25 | way uncontrollable by the outer element that relies on this particular order. 26 | 27 | Transclusion with `` is planned for components. The root element of the 28 | transcluded content will receive a reference to the parent of the custom element 29 | into which it was transcluded. When looking for a scope, we'll start from there. 30 | 31 | Also considering the possibility of enabling a view and `` for 32 | molds. If a view is provided, it's parsed using the same mechanics as 33 | component views, with the difference that elemends transcluded with 34 | `` become a part of the local DOM and don't receive references to the 35 | original parents (because a mold doesn't create a new scope). A potential 36 | concern is that the view might reference potentially unavailable 37 | identifiers, making assumptions about locals available in the scope where it's 38 | used. It's the same problem as `ng-include`. Still thinking this over. 39 | 40 | # Planned `` mechanics 41 | 42 | Each root element in the transcluded content keeps a reference to the parent 43 | from which it was taken. The parent may belong to the vanilla DOM (real) or the 44 | virtual atril DOM. 45 | 46 | When diffing a child during rendering, we check if it's transcluded. 47 | 48 | If it's transcluded from the vanilla DOM, we pass it to a special recursive 49 | diffing function outside of the component container. That function diffs the 50 | content ignoring any custom attributes and giving no special treatment to the 51 | template tags. It also has no access to interpolations from the virtual DOM. 52 | 53 | If it's transcluded from the atril DOM, it's phased normally. The scope search 54 | mechanism takes care of maintaining the link to the original viewmodel. It will 55 | check for a link to the original parent, and if it finds one, it will start 56 | scope search from there. This is also how we check if the element comes from the 57 | vanilla DOM (if no viewmodel is found all the way up to ``). 58 | 59 | # Other ToDos 60 | 61 | Consider providing a 'global.atril' export for scenarios without a module 62 | environment. 63 | 64 | Consider adding a "render-once" feature to embed DOM nodes managed by external 65 | code (e.g. third party UI widgets with their own DOM logic). This could be done 66 | by adding a `State` flag to completely skip phasing starting at the given 67 | virtual node and its real counterpart. This needs to be usable without writing 68 | custom molds, so we'll probably add a built-in. 69 | 70 | Review the `this` strategy for expressions. Not convinced the flexibility is 71 | worth having to correctly call them in attribute VMs. 72 | 73 | When an event is bubbling up through multiple listeners registered from within 74 | our zone context (e.g. with `on.*`), zone makes multiple `afterTask` calls. 75 | Consider to either (1) debounce reflows (is event propagation sync or async? if 76 | async, this is a questionable solution), or (2) use a single document-level 77 | event aggregator as the default way of handling events. 78 | 79 | Consider letting components customise their virtual DOM (without access to the 80 | transcluded content, when transclusion is implemented) just before the view is 81 | compiled. It could be an instance lifecycle method, something like `onCompile`. 82 | 83 | When interpolating attributes, must sanitise `href`, wiping any `"javascript:"` 84 | links. Consider if `src` must also be sanitised. Consider if the user can 85 | unwittingly let dangerous HTML into the view, and in which scenarios. 86 | 87 | Instead of always databinding the element's property, only bind it if there's 88 | no `@bindable` property available. 89 | -------------------------------------------------------------------------------- /lib/boot.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 'Thou shalt not comment.'; 3 | require('zone.js'); 4 | var utils = require('./utils'); 5 | var view_1 = require('./view'); 6 | var compile_1 = require('./compile'); 7 | var decorators_1 = require('./decorators'); 8 | var tree_1 = require('./tree'); 9 | var reflowStackDepth = 0; 10 | var maxRecursiveReflows = 10; 11 | var reflowScheduled = false; 12 | var localZone = zone.fork({ 13 | afterTask: function () { 14 | // zone.js automatically reruns a task after ≈1 s if the task throws. It 15 | // also hides all exceptions after the first during these retries. For us, 16 | // if a binding or component consistently throws during a phase, it causes 17 | // continuous reflows. To avoid that, we have to capture the exception. 18 | // try { 19 | reflowStackDepth = 0; 20 | reflow(); 21 | tree_1.flushQueue(); 22 | // } 23 | // catch (err) {utils.error(err)} 24 | } 25 | }); 26 | function scheduleReflow() { 27 | reflowScheduled = true; 28 | } 29 | exports.scheduleReflow = scheduleReflow; 30 | function reflow() { 31 | reflowStackDepth++; 32 | if (reflowStackDepth >= maxRecursiveReflows) { 33 | throw new Error("reached " + maxRecursiveReflows + " recursive reflow phases, aborting"); 34 | } 35 | reflowWithUnlimitedStack(); 36 | if (reflowScheduled) { 37 | reflowScheduled = false; 38 | reflow(); 39 | } 40 | } 41 | function reflowWithUnlimitedStack() { 42 | for (var i = 0, ii = tree_1.roots.length; i < ii; ++i) { 43 | var root = tree_1.roots[i]; 44 | if (!root.real.parentNode) { 45 | destroy(root.virtual); 46 | tree_1.roots.splice(i, 1); 47 | continue; 48 | } 49 | tree_1.Meta.getMeta(root.virtual).phase(); 50 | } 51 | } 52 | function destroy(virtual) { 53 | var meta = tree_1.Meta.getMeta(virtual); 54 | meta.destroy(); 55 | var nodes = virtual.childNodes; 56 | for (var i = 0, ii = nodes.length; i < ii; ++i) { 57 | var node = nodes[i]; 58 | if (node instanceof Element) 59 | destroy(node); 60 | } 61 | } 62 | function bootstrap() { 63 | // IE10 compat: doesn't support `apply` for function expressions. Have to 64 | // define it in a statement. 65 | function boot(element) { 66 | if (element === void 0) { element = document.body; } 67 | utils.assert(element instanceof Element, "bootstrap expects an Element, got:", element); 68 | // Don't register components twice. 69 | for (var _i = 0; _i < tree_1.roots.length; _i++) { 70 | var root = tree_1.roots[_i]; 71 | if (root.real === element) 72 | return; 73 | } 74 | var VM = decorators_1.registeredComponents[element.tagName.toLowerCase()]; 75 | if (VM) { 76 | tree_1.roots.push(createRootAt(element, VM)); 77 | return; 78 | } 79 | // Child scan must be breadth-first because a child may register the current 80 | // element as a root. If we go depth-first, we may end up with a root that 81 | // is also a descendant of another root. So we need two passes over the 82 | // child list. 83 | var nodes = element.childNodes; 84 | // First pass. 85 | for (var i = 0, ii = nodes.length; i < ii; ++i) { 86 | var node = nodes[i]; 87 | if (node instanceof Element) { 88 | // Check if there's a least one registered custom attribute for this 89 | // element (or a mold, if this is a template). Unlike the normal compile 90 | // process, this doesn't throw an error in case of mismatch. 91 | var attrs = node.attributes; 92 | for (var i_1 = 0, ii_1 = attrs.length; i_1 < ii_1; ++i_1) { 93 | var attr = attrs[i_1]; 94 | if (utils.looksLikeCustomAttribute(attr.name)) { 95 | if (utils.customAttributeName(attr.name) in decorators_1.registeredAttributes) { 96 | var root = createRootAt(element); 97 | compile_1.compileNode(root.virtual); 98 | tree_1.roots.push(root); 99 | return; 100 | } 101 | } 102 | } 103 | } 104 | } 105 | // Second pass. 106 | for (var i = 0, ii = nodes.length; i < ii; ++i) { 107 | var node = nodes[i]; 108 | if (node instanceof Element) 109 | boot(node); 110 | } 111 | } 112 | utils.onload(function () { localZone.run(boot); }); 113 | } 114 | exports.bootstrap = bootstrap; 115 | function createRootAt(element, VM) { 116 | var root = new tree_1.Root(); 117 | root.real = element; 118 | var virtual = utils.cloneDeep(element); 119 | var meta = tree_1.Meta.addRootMeta(virtual, element); 120 | if (VM) { 121 | meta.VM = VM; 122 | meta.view = new view_1.View(VM); 123 | // view should take care of transclusion 124 | meta.view.tryToCompile(virtual); 125 | } 126 | root.virtual = virtual; 127 | return root; 128 | } 129 | -------------------------------------------------------------------------------- /src/molds.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import {Mold, assign} from './decorators'; 4 | import {Meta} from './tree'; 5 | import * as utils from './utils'; 6 | 7 | @Mold({attributeName: 'if'}) 8 | class If { 9 | @assign element: TemplateElement; 10 | @assign hint: string; 11 | @assign expression: Expression; 12 | @assign scope: any; 13 | 14 | stash: Node[] = []; 15 | 16 | constructor() { 17 | utils.assert(this.hint === '', `custom attribute 'if' doesn't support hints, got ${this.hint}`); 18 | 19 | let container = this.element.content; 20 | while (container.hasChildNodes()) { 21 | let child = container.removeChild(container.lastChild); 22 | Meta.getOrAddMeta(child).isDomImmutable = true; 23 | this.stash.unshift(child); 24 | } 25 | } 26 | 27 | onPhase(): void { 28 | let ok = !!this.expression(this.scope); 29 | 30 | if (ok) while (this.stash.length) { 31 | this.element.appendChild(this.stash.shift()); 32 | } else while (this.element.hasChildNodes()) { 33 | this.stash.unshift(this.element.removeChild(this.element.lastChild)) 34 | } 35 | } 36 | } 37 | 38 | @Mold({attributeName: 'for'}) 39 | class For { 40 | @assign element: TemplateElement; 41 | @assign hint: string; 42 | @assign expression: Expression; 43 | @assign scope: any; 44 | 45 | mode: string; // 'of' | 'in' | 'any' 46 | key: string; 47 | originals: Node[] = []; 48 | stash: Node[] = []; 49 | 50 | constructor() { 51 | let msg = `the 'for.*' attribute expects a hint in the form of 'X.of', 'X.in', or 'X', where X is a valid JavaScript identifier; received '${this.hint}'`; 52 | 53 | let match = utils.matchValidKebabIdentifier(this.hint); 54 | utils.assert(!!match, msg); 55 | 56 | // Find the variable key. 57 | this.key = utils.normalise(match[1]); 58 | 59 | // Choose the iteration strategy. 60 | if (!match[2]) this.mode = 'any'; 61 | else if (match[2] === '.of') this.mode = 'of'; 62 | else if (match[2] == '.in') this.mode = 'in'; 63 | 64 | utils.assert(!!this.mode, msg); 65 | 66 | // Move the initial content to a safer place. 67 | let container = this.element.content; 68 | while (container.hasChildNodes()) { 69 | this.originals.unshift(container.removeChild(container.lastChild)); 70 | } 71 | } 72 | 73 | onPhase(): void { 74 | let value = this.expression(this.scope); 75 | 76 | let isIterable = value instanceof Array || typeof value === 'string' || 77 | (value != null && typeof value === 'object' && this.mode !== 'of'); 78 | 79 | // Stash existing content. 80 | while (this.element.hasChildNodes()) { 81 | this.stash.unshift(this.element.removeChild(this.element.lastChild)); 82 | } 83 | 84 | if (!isIterable || !this.originals.length) return; 85 | 86 | if (this.mode === 'in' || !utils.isArrayLike(value)) this.iterateIn(value); 87 | else this.iterateOf(value); 88 | } 89 | 90 | iterateOf(value: ArrayLike): void { 91 | for (var i = 0, ii = value.length; i < ii; ++i) { 92 | this.step(value, i); 93 | } 94 | } 95 | 96 | iterateIn(value: {[key: string]: any}): void { 97 | for (let key in value) this.step(value, key); 98 | } 99 | 100 | step(value: any, index: number|string): void { 101 | let nodes: Node[]; 102 | if (this.stash.length >= this.originals.length) { 103 | nodes = this.stash.splice(0, this.originals.length); 104 | } else { 105 | nodes = this.originals.map(node => { 106 | let clone = utils.cloneDeep(node); 107 | Meta.getOrAddMeta(clone).isDomImmutable = true; 108 | return clone; 109 | }); 110 | } 111 | 112 | while (nodes.length) { 113 | let node = nodes.shift(); 114 | this.element.appendChild(node); 115 | Meta.getOrAddMeta(node).insertScope({ 116 | $index: index, 117 | [this.key]: value[index] 118 | }); 119 | } 120 | } 121 | } 122 | 123 | @Mold({attributeName: 'let'}) 124 | class Let { 125 | @assign element: TemplateElement; 126 | @assign hint: string; 127 | @assign expression: Expression; 128 | @assign scope: any; 129 | 130 | constructor() { 131 | utils.assert(utils.isValidKebabIdentifier(this.hint), 132 | `'let.*' expects the hint to be a valid JavaScript identifier in kebab form, got: '${this.hint}'`); 133 | 134 | let identifier = utils.normalise(this.hint); 135 | 136 | // Make sure a scope is available. 137 | if (!this.scope) { 138 | let meta = Meta.getOrAddMeta(this.element); 139 | meta.insertScope(); 140 | this.scope = meta.scope; 141 | } 142 | 143 | // The identifier must not be redeclared in the scope. We're being strict to 144 | // safeguard against elusive errors. 145 | utils.assert(!Object.prototype.hasOwnProperty.call(this.scope, identifier), 146 | `unexpected re-declaration of '${identifier}' with 'let'`); 147 | 148 | // Bring the identifier into scope, assigning the given value. 149 | this.scope[identifier] = this.expression.call(this.scope, this.scope); 150 | 151 | // Pass through any content. 152 | let content = this.element.content; 153 | while (content.hasChildNodes()) { 154 | this.element.appendChild(content.removeChild(content.firstChild)); 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src-docs/html/attribute.md: -------------------------------------------------------------------------------- 1 | ## Attribute 2 | 3 |
11 | 12 | A custom attribute changes how the element behaves in the real DOM. 13 | 14 | Attributes are powerful. One- and two-way databinding in `atril` is implemented 15 | entirely with attributes, with no special treatment from the core engine. 16 | 17 | When using a custom attribute, you have to "opt in" by adding a dot to the name. 18 | You can also add an optional _hint_ after the dot to customise its behaviour, 19 | like `value` in `bind.value`. Most built-ins support various hints. This makes 20 | custom attributes very flexible and ensures no conflict with other attributes. 21 | 22 | ### Basics 23 | 24 | Here's an example attribute. This is the entire implementation of the built-in 25 | `class.*` binding. 26 | 27 | 28 | ```typescript 29 | import {Attribute, assign} from 'atril'; 30 | 31 | @Attribute({attributeName: 'class'}) 32 | class Ctrl { 33 | // Autoassigned by the library. 34 | @assign element: Element; 35 | @assign hint: string; 36 | @assign expression: Function; 37 | @assign scope: any; 38 | 39 | onPhase() { 40 | let result = this.expression(this.scope); 41 | if (result) this.element.classList.add(this.hint); 42 | else this.element.classList.remove(this.hint); 43 | } 44 | } 45 | ``` 46 | 47 | ```html 48 |
49 | 51 | 58 |
59 | ``` 60 | 61 | 62 | 70 | 71 | ### Contextual Dependencies 72 | 73 | The library uses a variant of dependency injection — _dependency assignment_ — 74 | to give you contextual dependencies for each attribute controller. To get hold 75 | of them, use the `@assign` decorator (ES7/TypeScript) or the static `assign` 76 | property on the constructor function (ES5). 77 | 78 | A custom attribute has the following contextual dependencies: 79 | * `element` — the real DOM element; 80 | * `attribute` — the associated 81 | [`Attr`](https://developer.mozilla.org/en-US/docs/Web/API/Attr) object on the 82 | DOM element; 83 | * `hint` — the part in the attribute name after the dot; 84 | * `expression` — the expression automatically compiled from the attribute value; 85 | * `scope` — the abstract data context in which to execute the expression (`null` 86 | if the attribute is not inside a custom element's view); 87 | * `vm` — the viewmodel of the custom element hosting the attribute (`null` if 88 | the element is not custom). 89 | 90 | Example: 91 | 92 | 93 | ```typescript 94 | import {Attribute, assign} from 'atril'; 95 | 96 | @Attribute({attributeName: 'my-attr'}) 97 | class Ctrl { 98 | @assign element: Element; 99 | @assign attribute: Attr; 100 | @assign hint: string; 101 | @assign expression: Function; 102 | @assign scope: any; 103 | @assign vm: any; 104 | 105 | constructor() { 106 | // 107 | console.log(element); 108 | // my-attr.calc="2 + 2" 109 | console.log(attribute); 110 | // 'calc' 111 | console.log(hint); 112 | // function that returns 4 113 | console.log(expression); 114 | // outer viewmodel or null 115 | console.log(scope); 116 | // hello-world's viewmodel 117 | console.log(vm); 118 | } 119 | } 120 | ``` 121 | 122 | ```html 123 | 124 | ``` 125 | 126 | 127 | 133 | ```javascript 134 | var Attribute = require('atril').Attribute; 135 | 136 | Attribute({attributeName: 'my-attr'})(function() { 137 | function Ctrl() {} 138 | 139 | // Property names to the left, dependency tokens to the right. 140 | Ctrl.assign = { 141 | element: 'element', 142 | attribute: 'attribute', 143 | hint: 'hint', 144 | expression: 'expression', 145 | scope: 'scope', 146 | vm: 'vm' 147 | }; 148 | 149 | return Ctrl; 150 | }()); 151 | ``` 152 | 153 | 154 | ### Lifecycle 155 | 156 | An attribute's life begins with a `constructor` call. In addition, it can define 157 | two lifecycle methods: `onPhase` and `onDestroy`. 158 | 159 | * `onPhase` 160 | 161 | This is called whenever the library reflows the tree of components and 162 | bindings in response to user activity. For an example, see the 163 | [`class.*`](attribute/#basics) implementation above. 164 | 165 | * `onDestroy` 166 | 167 | When the root of this virtual DOM branch is irrevocably removed from the 168 | hierarchy, this method is invoked on all components, attributes, and molds. You 169 | can use this as a chance to free memory or perform other cleanup tasks. Example: 170 | 171 | ```typescript 172 | class Ctrl { 173 | constructor() { 174 | createWastefulResource(); 175 | } 176 | 177 | onDestroy() { 178 | deleteWastefulResource(); 179 | } 180 | } 181 | ``` 182 | -------------------------------------------------------------------------------- /src/attributes.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import {scheduleReflow} from './boot'; 4 | import {Attribute, assign, isBindable} from './decorators'; 5 | import * as utils from './utils'; 6 | import {Pathfinder} from './utils'; 7 | 8 | @Attribute({attributeName: 'bind'}) 9 | class Bind { 10 | @assign element: Element; 11 | @assign hint: string; 12 | @assign expression: Expression; 13 | @assign scope: any; 14 | @assign vm: any; 15 | 16 | propertyPath: string; 17 | pathfinder: Pathfinder; 18 | 19 | constructor() { 20 | this.propertyPath = utils.normalise(this.hint); 21 | this.pathfinder = new Pathfinder(this.propertyPath); 22 | } 23 | 24 | onPhase(): void { 25 | let result = this.expression(this.scope); 26 | // Sync the result to the element. Dirty checking avoids setter side effects. 27 | if (!utils.strictEqual(this.pathfinder.read(this.element), result)) { 28 | this.pathfinder.assign(this.element, result); 29 | } 30 | // If the element has a VM that declares this property as bindable, sync 31 | // the result to it. Dirty checking avoids setter side effects. 32 | let vm = this.vm; 33 | if (vm && isBindable(vm, this.propertyPath) && 34 | !utils.strictEqual(this.pathfinder.read(vm), result)) { 35 | this.pathfinder.assign(vm, result); 36 | } 37 | } 38 | } 39 | 40 | @Attribute({attributeName: 'twoway'}) 41 | class TwoWay { 42 | @assign element: Element; 43 | @assign attribute: Attr; 44 | @assign hint: string; 45 | @assign scope: any; 46 | @assign vm: any; 47 | 48 | targetPropertyPath: string; 49 | targetPathfinder: Pathfinder; 50 | ownPathfinder: Pathfinder; 51 | lastOwnValue: any; 52 | lastTargetValue: any; 53 | 54 | constructor() { 55 | utils.assert(utils.isKebabStaticPathAccessor(this.hint), `a 'twoway.*' attribute must be of form 'twoway.X(.X)*', where X is a valid JavaScript identifier in kebab form; got: '${this.attribute.name}'`); 56 | 57 | this.ownPathfinder = new Pathfinder(this.attribute.value); 58 | this.targetPropertyPath = utils.normalise(this.hint); 59 | this.targetPathfinder = new Pathfinder(this.targetPropertyPath); 60 | 61 | // When dealing with native inputs, add event listeners to trigger phases. 62 | // For inputs with known events and value properties, sync the value 63 | // directly in the event listener to avoid double reflow. 64 | if (this.element.tagName === 'INPUT' || this.element.tagName === 'TEXTAREA') { 65 | let elem = this.element; 66 | if (elem.type === 'checkbox') { 67 | elem.addEventListener('change', () => {this.syncBottomUp((elem).checked)}); 68 | } else { 69 | elem.addEventListener('input', () => {this.syncBottomUp(elem.value)}); 70 | } 71 | } else if (this.element.tagName === 'SELECT') { 72 | let elem = this.element; 73 | elem.addEventListener('change', () => {this.syncBottomUp(elem.value)}); 74 | } 75 | } 76 | 77 | onPhase(): void { 78 | let firstPhase = !this.hasOwnProperty('lastOwnValue'); 79 | let ownValue = this.ownPathfinder.read(this.scope); 80 | 81 | if (firstPhase) { 82 | let targetValue = this.getTargetValue(); 83 | if (ownValue && !targetValue) this.syncTopDown(ownValue); 84 | if (targetValue && !ownValue) this.syncBottomUpAndReflow(targetValue); 85 | if (typeof targetValue !== typeof ownValue) this.syncBottomUpAndReflow(targetValue); 86 | else this.syncTopDown(ownValue); 87 | return; 88 | } 89 | 90 | // If own value has changed, overwrite the others. Own takes priority. 91 | if (!utils.strictEqual(ownValue, this.lastOwnValue)) { 92 | this.syncTopDown(ownValue); 93 | return; 94 | } 95 | 96 | // Otherwise sync the data back from the target. Don't bother syncing the 97 | // data between the target element and its VM. 98 | let targetValue = this.getTargetValue(); 99 | if (!utils.strictEqual(targetValue, this.lastTargetValue)) { 100 | this.syncBottomUpAndReflow(targetValue); 101 | } 102 | } 103 | 104 | syncTopDown(newValue: any): void { 105 | this.lastOwnValue = newValue; 106 | this.lastTargetValue = newValue; 107 | 108 | // Sync the result to the element. Dirty checking avoids setter side effects. 109 | if (!utils.strictEqual(this.targetPathfinder.read(this.element), newValue)) { 110 | this.targetPathfinder.assign(this.element, newValue); 111 | } 112 | 113 | // If the element has a VM that declares this property as bindable, sync 114 | // the result to it. Dirty checking avoids setter side effects. 115 | let vm = this.vm; 116 | if (vm && isBindable(vm, this.targetPropertyPath)) { 117 | if (!utils.strictEqual(this.targetPathfinder.read(vm), newValue)) { 118 | this.targetPathfinder.assign(vm, newValue); 119 | } 120 | } 121 | } 122 | 123 | syncBottomUp(newValue: any): boolean { 124 | this.lastOwnValue = newValue; 125 | this.lastTargetValue = newValue; 126 | 127 | if (!utils.strictEqual(this.ownPathfinder.read(this.scope), newValue)) { 128 | this.ownPathfinder.assign(this.scope, newValue); 129 | return true; 130 | } 131 | 132 | return false; 133 | } 134 | 135 | syncBottomUpAndReflow(newValue: any): void { 136 | if (this.syncBottomUp(newValue)) scheduleReflow(); 137 | } 138 | 139 | getTargetValue(): any { 140 | let vm = this.vm; 141 | if (vm && isBindable(vm, this.targetPropertyPath)) { 142 | return this.targetPathfinder.read(vm); 143 | } 144 | return this.targetPathfinder.read(this.element); 145 | } 146 | } 147 | 148 | @Attribute({attributeName: 'on'}) 149 | class On { 150 | @assign element: Element; 151 | @assign hint: string; 152 | @assign expression: Expression; 153 | @assign scope: any; 154 | 155 | constructor() { 156 | this.element.addEventListener(this.hint, event => { 157 | let result = this.expression.call(this.element, this.scope, {$event: event}); 158 | if (result === false) event.preventDefault(); 159 | }); 160 | } 161 | } 162 | 163 | @Attribute({attributeName: 'class'}) 164 | class Class { 165 | @assign element: Element; 166 | @assign hint: string; 167 | @assign expression: Expression; 168 | @assign scope: any; 169 | 170 | onPhase() { 171 | let result = this.expression(this.scope); 172 | if (result) this.element.classList.add(this.hint); 173 | else this.element.classList.remove(this.hint); 174 | } 175 | } 176 | 177 | @Attribute({attributeName: 'ref'}) 178 | class Ref { 179 | @assign element: Element; 180 | @assign attribute: Attr; 181 | @assign hint: string; 182 | @assign scope: any; 183 | @assign vm: any; 184 | 185 | constructor() { 186 | utils.assert(!this.hint || this.hint === 'vm', 187 | `expected 'ref.' or 'ref.vm', got: '${this.attribute.name}'`); 188 | let pathfinder = new Pathfinder(this.attribute.value); 189 | if (this.scope) { 190 | pathfinder.assign(this.scope, this.hint === 'vm' ? this.vm : this.element); 191 | } 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /lib/molds.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); 4 | switch (arguments.length) { 5 | case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); 6 | case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); 7 | case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); 8 | } 9 | }; 10 | var decorators_1 = require('./decorators'); 11 | var tree_1 = require('./tree'); 12 | var utils = require('./utils'); 13 | var If = (function () { 14 | function If() { 15 | this.stash = []; 16 | utils.assert(this.hint === '', "custom attribute 'if' doesn't support hints, got " + this.hint); 17 | var container = this.element.content; 18 | while (container.hasChildNodes()) { 19 | var child = container.removeChild(container.lastChild); 20 | tree_1.Meta.getOrAddMeta(child).isDomImmutable = true; 21 | this.stash.unshift(child); 22 | } 23 | } 24 | If.prototype.onPhase = function () { 25 | var ok = !!this.expression(this.scope); 26 | if (ok) 27 | while (this.stash.length) { 28 | this.element.appendChild(this.stash.shift()); 29 | } 30 | else 31 | while (this.element.hasChildNodes()) { 32 | this.stash.unshift(this.element.removeChild(this.element.lastChild)); 33 | } 34 | }; 35 | __decorate([ 36 | decorators_1.assign 37 | ], If.prototype, "element"); 38 | __decorate([ 39 | decorators_1.assign 40 | ], If.prototype, "hint"); 41 | __decorate([ 42 | decorators_1.assign 43 | ], If.prototype, "expression"); 44 | __decorate([ 45 | decorators_1.assign 46 | ], If.prototype, "scope"); 47 | If = __decorate([ 48 | decorators_1.Mold({ attributeName: 'if' }) 49 | ], If); 50 | return If; 51 | })(); 52 | var For = (function () { 53 | function For() { 54 | this.originals = []; 55 | this.stash = []; 56 | var msg = "the 'for.*' attribute expects a hint in the form of 'X.of', 'X.in', or 'X', where X is a valid JavaScript identifier; received '" + this.hint + "'"; 57 | var match = utils.matchValidKebabIdentifier(this.hint); 58 | utils.assert(!!match, msg); 59 | // Find the variable key. 60 | this.key = utils.normalise(match[1]); 61 | // Choose the iteration strategy. 62 | if (!match[2]) 63 | this.mode = 'any'; 64 | else if (match[2] === '.of') 65 | this.mode = 'of'; 66 | else if (match[2] == '.in') 67 | this.mode = 'in'; 68 | utils.assert(!!this.mode, msg); 69 | // Move the initial content to a safer place. 70 | var container = this.element.content; 71 | while (container.hasChildNodes()) { 72 | this.originals.unshift(container.removeChild(container.lastChild)); 73 | } 74 | } 75 | For.prototype.onPhase = function () { 76 | var value = this.expression(this.scope); 77 | var isIterable = value instanceof Array || typeof value === 'string' || 78 | (value != null && typeof value === 'object' && this.mode !== 'of'); 79 | // Stash existing content. 80 | while (this.element.hasChildNodes()) { 81 | this.stash.unshift(this.element.removeChild(this.element.lastChild)); 82 | } 83 | if (!isIterable || !this.originals.length) 84 | return; 85 | if (this.mode === 'in' || !utils.isArrayLike(value)) 86 | this.iterateIn(value); 87 | else 88 | this.iterateOf(value); 89 | }; 90 | For.prototype.iterateOf = function (value) { 91 | for (var i = 0, ii = value.length; i < ii; ++i) { 92 | this.step(value, i); 93 | } 94 | }; 95 | For.prototype.iterateIn = function (value) { 96 | for (var key in value) 97 | this.step(value, key); 98 | }; 99 | For.prototype.step = function (value, index) { 100 | var nodes; 101 | if (this.stash.length >= this.originals.length) { 102 | nodes = this.stash.splice(0, this.originals.length); 103 | } 104 | else { 105 | nodes = this.originals.map(function (node) { 106 | var clone = utils.cloneDeep(node); 107 | tree_1.Meta.getOrAddMeta(clone).isDomImmutable = true; 108 | return clone; 109 | }); 110 | } 111 | while (nodes.length) { 112 | var node = nodes.shift(); 113 | this.element.appendChild(node); 114 | tree_1.Meta.getOrAddMeta(node).insertScope((_a = { 115 | $index: index 116 | }, 117 | _a[this.key] = value[index], 118 | _a 119 | )); 120 | } 121 | var _a; 122 | }; 123 | __decorate([ 124 | decorators_1.assign 125 | ], For.prototype, "element"); 126 | __decorate([ 127 | decorators_1.assign 128 | ], For.prototype, "hint"); 129 | __decorate([ 130 | decorators_1.assign 131 | ], For.prototype, "expression"); 132 | __decorate([ 133 | decorators_1.assign 134 | ], For.prototype, "scope"); 135 | For = __decorate([ 136 | decorators_1.Mold({ attributeName: 'for' }) 137 | ], For); 138 | return For; 139 | })(); 140 | var Let = (function () { 141 | function Let() { 142 | utils.assert(utils.isValidKebabIdentifier(this.hint), "'let.*' expects the hint to be a valid JavaScript identifier in kebab form, got: '" + this.hint + "'"); 143 | var identifier = utils.normalise(this.hint); 144 | // Make sure a scope is available. 145 | if (!this.scope) { 146 | var meta = tree_1.Meta.getOrAddMeta(this.element); 147 | meta.insertScope(); 148 | this.scope = meta.scope; 149 | } 150 | // The identifier must not be redeclared in the scope. We're being strict to 151 | // safeguard against elusive errors. 152 | utils.assert(!Object.prototype.hasOwnProperty.call(this.scope, identifier), "unexpected re-declaration of '" + identifier + "' with 'let'"); 153 | // Bring the identifier into scope, assigning the given value. 154 | this.scope[identifier] = this.expression.call(this.scope, this.scope); 155 | // Pass through any content. 156 | var content = this.element.content; 157 | while (content.hasChildNodes()) { 158 | this.element.appendChild(content.removeChild(content.firstChild)); 159 | } 160 | } 161 | __decorate([ 162 | decorators_1.assign 163 | ], Let.prototype, "element"); 164 | __decorate([ 165 | decorators_1.assign 166 | ], Let.prototype, "hint"); 167 | __decorate([ 168 | decorators_1.assign 169 | ], Let.prototype, "expression"); 170 | __decorate([ 171 | decorators_1.assign 172 | ], Let.prototype, "scope"); 173 | Let = __decorate([ 174 | decorators_1.Mold({ attributeName: 'let' }) 175 | ], Let); 176 | return Let; 177 | })(); 178 | -------------------------------------------------------------------------------- /src/compile.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import {registeredComponents, registeredAttributes, registeredMolds} from './decorators'; 4 | import {Meta} from './tree'; 5 | import {AttributeBinding, AttributeInterpolation, hasInterpolation, compileInterpolation} from './bindings'; 6 | import {View} from './view'; 7 | import * as utils from './utils'; 8 | 9 | export function compileNode(node: Node): void { 10 | if (node instanceof Text) { 11 | compileTextNode(node); 12 | return; 13 | } 14 | if (node instanceof Element) { 15 | compileElement(node); 16 | return; 17 | } 18 | // A meta should always be made available, even for comments. 19 | Meta.getOrAddMeta(node); 20 | } 21 | 22 | function compileTextNode(node: Text): void { 23 | let meta = Meta.getOrAddMeta(node); 24 | if (meta.compiled) return; 25 | 26 | // Special exception for