12 Commits

Author SHA1 Message Date
Arnavion 0c0f250473 Link to archived-repos-issues repo. 2022-02-06 01:36:44 -08:00
Arnavion 7287f286d7 RIP o7 part 2
Remove IRC channel, contribution request and Travis CI badge,
and minor http->https cleanup.
2020-03-26 00:04:58 -07:00
Arnavion ee97d1d0f3 RIP o7 2019-01-08 01:11:42 -08:00
DoomTay 6b405e65c1 Don't generate overlapping keyframes if \fad has 0ms start or 0ms end
Fixes #111
Closes #112
2018-07-23 02:23:48 -07:00
Nick Fujita 436fa10544 Added support for \n
Fixes #103
Closes #104
2017-10-16 18:43:47 -07:00
Arnavion 8098b70c70 Added tslint file and suppressions. 2017-04-12 01:22:40 -07:00
Arnavion d1593e7f1f Updated IE bug URLs. 2017-04-11 19:56:29 -07:00
Arnavion 8259a5a3d1 Fixed issues detected by tslint. 2017-04-11 19:30:43 -07:00
Arnavion e0c630038b Updated node versions in .travis.yml 2017-04-08 23:24:38 -07:00
Arnavion a39140db8e Updated npm to v4.x 2017-04-08 23:24:38 -07:00
Arnavion 9bfac13171 Updated TypeScript to v2.0.10 2017-04-08 23:24:06 -07:00
Arnavion 21cf48a44c Fixed return type annotation on calculateFontMetrics 2016-09-22 09:52:26 -07:00
46 changed files with 1861 additions and 1825 deletions
+1 -4
View File
@@ -1,10 +1,7 @@
language: node_js
node_js:
- "0.10"
- "0.12"
- "4"
- "5"
- "6"
- "7"
before_script:
- "node ./build.js doc"
sudo: false
+34 -24
View File
@@ -1,6 +1,24 @@
[![Build Status](https://travis-ci.org/Arnavion/libjass.png?branch=master)](https://travis-ci.org/Arnavion/libjass)
This project is no longer being worked on.
libjass is a JavaScript library written in TypeScript to render ASS subs in the browser. [Check out the demo.](http://arnavion.github.io/libjass/demo/index.xhtml)
You should probably use something else, like https://github.com/Dador/JavascriptSubtitlesOctopus
When I started libjass in 2011, I made a bet that offloading rendering to the DOM would eventually be the way to get fast and accurate rendering. CSS filter effects were about to be standardized. Regular JavaScript would've been too slow to do the fancy rendering that ASS requires. Surely letting the browser render text would be faster than parsing fonts in JS, computing the dimensions and margins for every rendered character, and blitting individual outline and shadow pixels to a canvas.
However CSS filter effects by themselves turned out to be inadequate to accurately render even the basics of ASS. SVG filters are more accurate, but are unoptimized or unsupported in all browsers since nobody really uses them (a vicious cycle). As such, both of them are unable to efficiently render the simplest and most common ASS feature - the elliptical border. The `feMorphology` SVG filter can only dilate to rectangles, so libjass has to stack many such rectangles of different sizes to approximate an ellipse. Big borders end up needing tens of such rectangles and a large gaussian blur, which brings even the mightiest browser's renderer to its single-threaded knees.
Layout also has problems. CSS doesn't provide an easy to way for a subtitle to push another subtitle away so that they don't overlap. It doesn't provide a line-breaking strategy that tries to equalize the lengths of the broken lines (what ASS calls smart line wrapping). Vertically centering things is still a nightmare - flexbox and CSS grid don't help because subtitles don't follow grids - so `\an4-6` were never properly implemented. These things *could* be solved by positioning the text manually, but this would've brought us back to the problem of parsing fonts and measuring text dimensions in JavaScript instead of letting the DOM handle it.
In 2013, asm.js became a way to use the original C renderers like libass, compiled to something that's not as fast as native C but still faster than regular JavaScript rendering. More recently, WASM has emerged as a more cross-platform and strongly-guaranteed way of doing this. Parsing fonts and computing dimensions is now a feasible prospect.
Because of this, I believe libjass's strategy of relying on the browser DOM is a dead end.
I'm happy to continue providing support and answering questions about the code on Github. Since this repository is archived, please ask by opening an issue at https://github.com/Arnavion/archived-repos-issues instead. The code in this repository is still available under APL-2.0. The ASS parser is functional regardless of the browser renderer. Feel free to fork this project, or incorporate its code into your own projects, under the terms of the license.
Thank you, the users who used libjass on your websites, opened issues, and contributed fixes. libjass was my first OSS project that I intended to be used by more people than me. I had fun working on it and learning about web dev.
----
libjass is a JavaScript library written in TypeScript to render ASS subs in the browser. [Check out the demo.](https://arnavion.github.io/libjass/demo/index.xhtml)
### What's special about libjass?
@@ -42,37 +60,37 @@ Only libjass.js and libjass.css are needed to use libjass on your website. The o
The API documentation is linked in the Links section below. Here's an overview:
* The [ASS.fromUrl()](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromUrl) function takes in a URL to an ASS script and returns a promise that resolves to an [ASS](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS) object. This ASS object represents the script properties, the line styles and dialogue lines in it. Alternatively, you can use [ASS.fromString()](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromString) to convert a string of the script contents into an ASS object.
* The [ASS.fromUrl()](https://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromUrl) function takes in a URL to an ASS script and returns a promise that resolves to an [ASS](https://arnavion.github.io/libjass/api.xhtml#libjass.ASS) object. This ASS object represents the script properties, the line styles and dialogue lines in it. Alternatively, you can use [ASS.fromString()](https://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromString) to convert a string of the script contents into an ASS object.
* Next, you initialize a renderer to render the subtitles. libjass ships with an easy-to-use renderer, the [DefaultRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer). It uses information from the ASS object to build up a series of div elements around the video tag. There is a wrapper (.libjass-subs) containing div's corresponding to the layers in the ASS script, and each layer has div's corresponding to the 9 alignment directions. libjass.css contains styles for these div's to render them at the correct location.
* Next, you initialize a renderer to render the subtitles. libjass ships with an easy-to-use renderer, the [DefaultRenderer](https://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer). It uses information from the ASS object to build up a series of div elements around the video tag. There is a wrapper (.libjass-subs) containing div's corresponding to the layers in the ASS script, and each layer has div's corresponding to the 9 alignment directions. libjass.css contains styles for these div's to render them at the correct location.
* The renderer uses [window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame) as a source of timer ticks. In each tick, it determines the set of dialogues to be shown at the current video time, renders each of them as a div, and appendChild's the div into the appropriate layer+alignment div.
* The renderer can be told to dynamically change the size of the subtitles based on user input by calling [WebRenderer.resize()](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.WebRenderer.resize)
* The renderer can be told to dynamically change the size of the subtitles based on user input by calling [WebRenderer.resize()](https://arnavion.github.io/libjass/api.xhtml#libjass.renderers.WebRenderer.resize)
* Lastly, the renderer contains an implementation of preloading fonts before playing the video. It uses a map of font names to URLs - this map can be conveniently created from a CSS file containing @font-face rules using [RendererSettings.makeFontMapFromStyleElement()](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.RendererSettings.makeFontMapFromStyleElement)
* Lastly, the renderer contains an implementation of preloading fonts before playing the video. It uses a map of font names to URLs - this map can be conveniently created from a CSS file containing @font-face rules using [RendererSettings.makeFontMapFromStyleElement()](https://arnavion.github.io/libjass/api.xhtml#libjass.renderers.RendererSettings.makeFontMapFromStyleElement)
* For an example of using libjass, check out [the demo.](http://arnavion.github.io/libjass/demo/index.xhtml) It has comments explaining basic usage and pointers to some advanced usage.
* For an example of using libjass, check out [the demo.](https://arnavion.github.io/libjass/demo/index.xhtml) It has comments explaining basic usage and pointers to some advanced usage.
### What browser and JavaScript features does libjass need?
* libjass uses some ES5 features like getters and setters (via Object.defineProperty), and assumptions like the behavior of parseInt with leading zeros. It cannot be used with an ES3 environment.
* libjass will use ES6 Set, Map and Promise if they're available on the global object. If they're not present, it will use its own minimal internal implementations. If you have implementations of these that you would like libjass to use but don't want to register them on the global object, you can provide them to libjass specifically by setting the [libjass.Set](http://arnavion.github.io/libjass/api.xhtml#libjass.Set), [libjass.Map](http://arnavion.github.io/libjass/api.xhtml#libjass.Map) and [libjass.Promise](http://arnavion.github.io/libjass/api.xhtml#libjass.Promise) properties.
* libjass will use ES6 Set, Map and Promise if they're available on the global object. If they're not present, it will use its own minimal internal implementations. If you have implementations of these that you would like libjass to use but don't want to register them on the global object, you can provide them to libjass specifically by setting the [libjass.Set](https://arnavion.github.io/libjass/api.xhtml#libjass.Set), [libjass.Map](https://arnavion.github.io/libjass/api.xhtml#libjass.Map) and [libjass.Promise](https://arnavion.github.io/libjass/api.xhtml#libjass.Promise) properties.
* [AutoClock](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.AutoClock) and [VideoClock](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.VideoClock) use [window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) to generate clock ticks.
* [AutoClock](https://arnavion.github.io/libjass/api.xhtml#libjass.renderers.AutoClock) and [VideoClock](https://arnavion.github.io/libjass/api.xhtml#libjass.renderers.VideoClock) use [window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) to generate clock ticks.
* [WebRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.WebRenderer) and [DefaultRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer) use [SVG filter effects for HTML](http://caniuse.com/#feat=svg-html) to render outlines and blur. This feature is not available on all browsers, so you can tell them to fall back to more widely available CSS methods by setting the [RendererSettings.enableSvg](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.RendererSettings.enableSvg) property to false.
* [WebRenderer](https://arnavion.github.io/libjass/api.xhtml#libjass.renderers.WebRenderer) and [DefaultRenderer](https://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer) use [SVG filter effects for HTML](https://caniuse.com/#feat=svg-html) to render outlines and blur. This feature is not available on all browsers, so you can tell them to fall back to more widely available CSS methods by setting the [RendererSettings.enableSvg](https://arnavion.github.io/libjass/api.xhtml#libjass.renderers.RendererSettings.enableSvg) property to false.
* WebRenderer and DefaultRenderer use [CSS3 animations](http://caniuse.com/#feat=css-animation) for effects like \mov and \fad.
* WebRenderer and DefaultRenderer use [CSS3 animations](https://caniuse.com/#feat=css-animation) for effects like \mov and \fad.
* Using fonts attached to the script requires [ES6 typed arrays](http://caniuse.com/#feat=typedarrays) (ArrayBuffer, DataView, Uint8Array, etc).
* Using fonts attached to the script requires [ES6 typed arrays](https://caniuse.com/#feat=typedarrays) (ArrayBuffer, DataView, Uint8Array, etc).
### Can I use libjass in node?
libjass's parser works in node. Entire scripts can be parsed via [ASS.fromString()](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromString)
libjass's parser works in node. Entire scripts can be parsed via [ASS.fromString()](https://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromString)
```javascript
> var libjass = require("libjass")
@@ -95,7 +113,7 @@ true
'Fade { start: 0.2, end: 0 }'
```
[libjass.parser.parse](http://arnavion.github.io/libjass/api.xhtml#libjass.parser.parse) parses the first parameter using the second parameter as the rule name. For example, the [dialogueParts](http://arnavion.github.io/libjass/api.xhtml#./parser/parse.ParserRun.parse_dialogueParts) rule can be used to get an array of [libjass.parts](http://arnavion.github.io/libjass/api.xhtml#libjass.parts) objects that represent the parts of an ASS dialogue line.
[libjass.parser.parse](https://arnavion.github.io/libjass/api.xhtml#libjass.parser.parse) parses the first parameter using the second parameter as the rule name. For example, the [dialogueParts](https://arnavion.github.io/libjass/api.xhtml#./parser/parse.ParserRun.parse_dialogueParts) rule can be used to get an array of [libjass.parts](https://arnavion.github.io/libjass/api.xhtml#libjass.parts) objects that represent the parts of an ASS dialogue line.
```javascript
> var parts = libjass.parser.parse("{\\an8}Are {\\i1}you{\\i0} the one who stole the clock?!", "dialogueParts")
@@ -112,18 +130,11 @@ true
8
```
The rule names are derived from the methods on the [ParserRun class](http://arnavion.github.io/libjass/api.xhtml#./parser/parse.ParserRun).
The rule names are derived from the methods on the [ParserRun class](https://arnavion.github.io/libjass/api.xhtml#./parser/parse.ParserRun).
See the tests, particularly the ones in tests/unit/miscellaneous.js, for examples.
### Can I contribute?
Yes! Feature requests, suggestions, bug reports and pull requests are welcome! I'm especially looking for details and edge-cases of the ASS syntax that libjass doesn't support.
You can also join the IRC channel in the links section below and ask any questions.
### Supported features
* Styles: Italic, Bold, Underline, StrikeOut, FontName, FontSize, ScaleX, ScaleY, Spacing, PrimaryColor, OutlineColor, BackColor, Outline, Shadow, Alignment, MarginL, MarginR, MarginV
@@ -143,8 +154,7 @@ You can also join the IRC channel in the links section below and ask any questio
### Links
* [GitHub](https://github.com/Arnavion/libjass/)
* IRC channel - #libjass on irc.rizon.net
* [API documentation](http://arnavion.github.io/libjass/api.xhtml)
* [API documentation](https://arnavion.github.io/libjass/api.xhtml)
* [Aegisub's documentation on ASS](http://docs.aegisub.org/3.0/ASS_Tags/)
+2
View File
@@ -82,6 +82,8 @@ task("version.ts", function (callback) {
var versionString = packageJson.version;
var versionParts = versionString.split(".").map(function (num) { return parseInt(num); });
var versionFileContents =
"/* tslint:disable */\n" +
"\n" +
"/**\n" +
" * The version of libjass. An array like\n" +
" *\n" +
+60 -68
View File
@@ -18,17 +18,14 @@
* limitations under the License.
*/
import * as fs from "fs";
import * as path from "path";
import { File, FileTransform } from "async-build";
import { FileTransform } from "async-build";
import * as AST from "./typescript/ast";
import { Compiler } from "./typescript/compiler";
import { walk } from "./typescript/walker";
function flatten<T>(arr: T[][]): T[] {
var result: T[] = [];
let result: T[] = [];
for (const a of arr) {
result = result.concat(a);
@@ -37,7 +34,7 @@ function flatten<T>(arr: T[][]): T[] {
return result;
}
var sorter = (() => {
const sorter = (() => {
function visibilitySorter(value1: { isPrivate?: boolean; isProtected?: boolean; }, value2: { isPrivate?: boolean; isProtected?: boolean; }) {
if (value1.isPrivate === value2.isPrivate && value1.isProtected === value2.isProtected) {
return 0;
@@ -62,10 +59,10 @@ var sorter = (() => {
return 0;
}
var types = [AST.Property, AST.Function, AST.Interface, AST.Class, AST.Enum];
const types = [AST.Property, AST.Function, AST.Interface, AST.Class, AST.Enum];
function typeSorter(value1: AST.ModuleMember | AST.NamespaceMember, value2: AST.ModuleMember | AST.NamespaceMember) {
var type1Index = -1;
var type2Index = -1;
let type1Index = -1;
let type2Index = -1;
types.every((type, index) => {
if (value1 instanceof type) {
@@ -84,11 +81,11 @@ var sorter = (() => {
return value1.name.localeCompare(value2.name);
}
var sorters: ((value1: AST.ModuleMember, value2: AST.ModuleMember) => number)[] = [visibilitySorter, typeSorter, nameSorter];
const sorters: ((value1: AST.ModuleMember, value2: AST.ModuleMember) => number)[] = [visibilitySorter, typeSorter, nameSorter];
return (value1: AST.ModuleMember, value2: AST.ModuleMember) => {
for (var i = 0; i < sorters.length; i++) {
var result = sorters[i](value1, value2);
for (const sorter of sorters) {
const result = sorter(value1, value2);
if (result !== 0) {
return result;
@@ -110,10 +107,10 @@ function sanitize(str: string) {
function toVariableName(item: { name: string }) {
// TODO: Handle non-letters (are both their toLowerCase() and toUpperCase())
var name = item.name;
var result = "";
const name = item.name;
let result = "";
for (var i = 0; i < name.length; i++) {
for (let i = 0; i < name.length; i++) {
if (name[i] === name[i].toLowerCase()) {
// This is lower case. Write it as lower case.
result += name[i];
@@ -168,15 +165,15 @@ function toUsageName(item: AST.Class | AST.Interface | AST.Function | AST.Proper
}
if (item.parent instanceof AST.Namespace) {
if ((<AST.Class | AST.Interface | AST.Function | AST.Enum>item).isPrivate) {
if ((item as AST.CanBePrivate).isPrivate) {
return item.name;
}
return item.fullName;
}
if ((<AST.Function>item).isStatic) {
return toUsageName(<AST.Class | AST.Interface>item.parent) + '.' + item.name;
if ((item as AST.CanBeStatic).isStatic) {
return toUsageName(item.parent as AST.Class | AST.Interface) + '.' + item.name;
}
return toVariableName(item.parent) + '.' + item.name;
@@ -187,13 +184,12 @@ function toId(item: { fullName?: string; name: string; }): string {
}
function toLink(item: AST.ModuleMember | AST.EnumMember | AST.TypeReference): string {
var result = `<a href="#${ toId(item) }">${ sanitize(item.name) }`;
let result = `<a href="#${ toId(item) }">${ sanitize(item.name) }`;
var itemWithGenerics = <AST.HasGenerics>item;
if (itemWithGenerics.generics !== undefined && itemWithGenerics.generics.length > 0) {
var generics = <(string | AST.TypeReference | AST.IntrinsicTypeReference)[]>itemWithGenerics.generics;
if (AST.hasGenerics(item) && item.generics.length > 0) {
const generics = item.generics as (string | AST.TypeReference | AST.IntrinsicTypeReference)[];
result += sanitize(`.<${ generics.map(generic =>
(generic instanceof AST.TypeReference || generic instanceof AST.IntrinsicTypeReference) ? generic.name : <string>generic
(generic instanceof AST.TypeReference || generic instanceof AST.IntrinsicTypeReference) ? generic.name : generic
).join(', ') }>`);
}
@@ -203,9 +199,9 @@ function toLink(item: AST.ModuleMember | AST.EnumMember | AST.TypeReference): st
}
function writeDescription(text: string): string {
var result = sanitize(text).replace(/\{@link ([^} ]+)\}/g, (substring, linkTarget) => `<a href="#${ linkTarget }">${ linkTarget }</a>`);
let result = sanitize(text).replace(/\{@link ([^} ]+)\}/g, (substring, linkTarget) => `<a href="#${ linkTarget }">${ linkTarget }</a>`);
var inCodeBlock = false;
let inCodeBlock = false;
result = result.split("\n").map(line => {
if (line.substr(0, " ".length) === " ") {
line = line.substr(" ".length);
@@ -288,7 +284,7 @@ function functionToHtml(func: AST.Function): string[] {
}
function interfaceToHtml(interfase: AST.Interface): string[] {
var members: AST.InterfaceMember[] = [];
const members: AST.InterfaceMember[] = [];
Object.keys(interfase.members).forEach(memberName => members.push(interfase.members[memberName]));
members.sort(sorter);
@@ -310,7 +306,7 @@ function interfaceToHtml(interfase: AST.Interface): string[] {
return functionToHtml(member).map(indenter(2));
}
else {
throw new Error(`Unrecognized member type: ${ (<any>member.constructor).name }`);
throw new Error(`Unrecognized member type: ${ (member as any).constructor.name }`);
}
}))).concat([
' </dd>',
@@ -320,7 +316,7 @@ function interfaceToHtml(interfase: AST.Interface): string[] {
}
function classToHtml(clazz: AST.Class): string[] {
var members: AST.InterfaceMember[] = [];
const members: AST.InterfaceMember[] = [];
Object.keys(clazz.members).forEach(memberName => members.push(clazz.members[memberName]));
members.sort(sorter);
@@ -330,7 +326,7 @@ function classToHtml(clazz: AST.Class): string[] {
clazz.isAbstract ? ' abstract' : ''}${
clazz.isPrivate ? ' private' : ''}">`,
` <dt class="name">class ${ toLink(clazz) }${
(clazz.baseType !== null) ? ` extends ${ (clazz.baseType instanceof AST.TypeReference) ? toLink(<AST.TypeReference>clazz.baseType) : clazz.baseType.name }` : '' }${
(clazz.baseType !== null) ? ` extends ${ (clazz.baseType instanceof AST.TypeReference) ? toLink(clazz.baseType) : clazz.baseType.name }` : '' }${
(clazz.interfaces.length > 0) ? ` implements ${ clazz.interfaces.map(interfase => interfase instanceof AST.TypeReference ? toLink(interfase) : interfase.name).join(', ') }` : ''}</dt>`,
' <dd class="description">',
` ${ writeDescription(clazz.description) }`,
@@ -350,7 +346,7 @@ function classToHtml(clazz: AST.Class): string[] {
return functionToHtml(member).map(indenter(2));
}
else {
throw new Error(`Unrecognized member type: ${ (<any>member.constructor).name }`);
throw new Error(`Unrecognized member type: ${ (member as any).constructor.name }`);
}
}))).concat([
' </dd>',
@@ -406,30 +402,26 @@ function propertyToHtml(property: AST.Property): string[] {
}
export function build(outputFilePath: string, root: string, rootNamespaceName: string): FileTransform {
var compiler = new Compiler();
return new FileTransform(function (file: File): void {
var self: FileTransform = this;
const compiler = new Compiler();
return new FileTransform(function (file): void {
// Compile
compiler.compile(file);
// Walk
var walkResult = walk(compiler, root, rootNamespaceName);
var namespaces = walkResult.namespaces;
var modules = walkResult.modules;
const walkResult = walk(compiler, root, rootNamespaceName);
const namespaces = walkResult.namespaces;
const modules = walkResult.modules;
// Make HTML
var namespaceNames = Object.keys(namespaces)
const namespaceNames = Object.keys(namespaces)
.filter(namespaceName => namespaceName.substr(0, rootNamespaceName.length) === rootNamespaceName)
.sort((ns1, ns2) => ns1.localeCompare(ns2));
var moduleNames = Object.keys(modules).sort((ns1, ns2) => ns1.localeCompare(ns2));
const moduleNames = Object.keys(modules).sort((ns1, ns2) => ns1.localeCompare(ns2)).filter(moduleName => Object.keys(modules[moduleName].members).length > 0);
moduleNames = moduleNames.filter(moduleName => Object.keys(modules[moduleName].members).length > 0);
self.push({
this.push({
path: outputFilePath,
contents: Buffer.concat([new Buffer(
`<?xml version="1.0" encoding="utf-8" ?>
@@ -589,9 +581,9 @@ export function build(outputFilePath: string, root: string, rootNamespaceName: s
<label><input type="checkbox" id="show-private" />Show private</label>
`
)].concat(namespaceNames.map(namespaceName => {
var namespace = namespaces[namespaceName];
const namespace = namespaces[namespaceName];
var namespaceMembers: AST.NamespaceMember[] = [];
const namespaceMembers: AST.NamespaceMember[] = [];
for (const memberName of Object.keys(namespace.members)) {
namespaceMembers.push(namespace.members[memberName]);
}
@@ -613,13 +605,13 @@ export function build(outputFilePath: string, root: string, rootNamespaceName: s
`
)]));
})).concat(moduleNames.map(moduleName => {
var module = modules[moduleName];
const module = modules[moduleName];
var moduleMembers: AST.ModuleMemberWithoutReference[] = [];
const moduleMembers: AST.ModuleMemberWithoutReference[] = [];
for (const memberName of Object.keys(module.members)) {
var member = module.members[memberName];
if ((<AST.HasParent><any>member).parent === module) {
moduleMembers.push(<AST.ModuleMemberWithoutReference>member);
const member = module.members[memberName];
if ((member as AST.HasParent).parent === module) {
moduleMembers.push(member as AST.ModuleMemberWithoutReference);
}
}
@@ -649,22 +641,22 @@ export function build(outputFilePath: string, root: string, rootNamespaceName: s
<div class="content">
`
)]).concat(flatten(namespaceNames.map(namespaceName => {
var namespace = namespaces[namespaceName];
const namespace = namespaces[namespaceName];
var namespaceMembers: AST.NamespaceMember[] = [];
const namespaceMembers: AST.NamespaceMember[] = [];
for (const memberName of Object.keys(namespace.members)) {
namespaceMembers.push(namespace.members[memberName]);
}
namespaceMembers.sort(sorter);
var properties = <AST.Property[]>namespaceMembers.filter(member => member instanceof AST.Property);
var functions = <AST.Function[]>namespaceMembers.filter(member => member instanceof AST.Function);
var interfaces = <AST.Interface[]>namespaceMembers.filter(member => member instanceof AST.Interface);
var classes = <AST.Class[]>namespaceMembers.filter(member => member instanceof AST.Class);
var enums = <AST.Enum[]>namespaceMembers.filter(member => member instanceof AST.Enum);
const properties = namespaceMembers.filter(member => member instanceof AST.Property) as AST.Property[];
const functions = namespaceMembers.filter(member => member instanceof AST.Function) as AST.Function[];
const interfaces = namespaceMembers.filter(member => member instanceof AST.Interface) as AST.Interface[];
const classes = namespaceMembers.filter(member => member instanceof AST.Class) as AST.Class[];
const enums = namespaceMembers.filter(member => member instanceof AST.Enum) as AST.Enum[];
var result = [new Buffer(
const result = [new Buffer(
` <section class="namespace">
<h1 id="${ sanitize(namespaceName) }">Namespace ${ sanitize(namespaceName) }</h1>
`
@@ -762,13 +754,13 @@ export function build(outputFilePath: string, root: string, rootNamespaceName: s
return result;
}))).concat(flatten(moduleNames.map(moduleName => {
var module = modules[moduleName];
const module = modules[moduleName];
var moduleMembers: AST.ModuleMember[] = [];
const moduleMembers: AST.ModuleMember[] = [];
for (const memberName of Object.keys(module.members)) {
var member = module.members[memberName];
if ((<AST.HasParent><any>member).parent === module) {
moduleMembers.push(<AST.ModuleMember>member);
const member = module.members[memberName];
if ((member as AST.HasParent).parent === module) {
moduleMembers.push(member);
}
}
@@ -778,13 +770,13 @@ export function build(outputFilePath: string, root: string, rootNamespaceName: s
moduleMembers.sort(sorter);
var properties = <AST.Property[]>moduleMembers.filter(member => member instanceof AST.Property);
var functions = <AST.Function[]>moduleMembers.filter(member => member instanceof AST.Function);
var interfaces = <AST.Interface[]>moduleMembers.filter(member => member instanceof AST.Interface);
var classes = <AST.Class[]>moduleMembers.filter(member => member instanceof AST.Class);
var enums = <AST.Enum[]>moduleMembers.filter(member => member instanceof AST.Enum);
const properties = moduleMembers.filter(member => member instanceof AST.Property) as AST.Property[];
const functions = moduleMembers.filter(member => member instanceof AST.Function) as AST.Function[];
const interfaces = moduleMembers.filter(member => member instanceof AST.Interface) as AST.Interface[];
const classes = moduleMembers.filter(member => member instanceof AST.Class) as AST.Class[];
const enums = moduleMembers.filter(member => member instanceof AST.Enum) as AST.Enum[];
var result = [new Buffer(
const result = [new Buffer(
` <section class="module">
<h1 id="${ sanitize(moduleName) }">Module ${ sanitize(moduleName) }</h1>
`
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"strictNullChecks": false,
"target": "es5",
"module": "commonjs",
"moduleResolution": "classic",
"noImplicitUseStrict": false,
"types": []
},
"files": [
"./typescript/index.ts",
"./doc.ts",
"./node.d.ts",
"./typescript/typescript.d.ts",
"../node_modules/async-build/typings.d.ts"
]
}
+12 -2
View File
@@ -18,7 +18,7 @@
* limitations under the License.
*/
import * as ts from "typescript";
import ts = require("typescript");
export class HasParent {
public parent: HasParent = null;
@@ -30,7 +30,7 @@ export class HasParent {
return this.name;
}
var parent = this.parent;
const parent = this.parent;
if (parent instanceof Namespace) {
return parent.getMemberFullName(this);
}
@@ -188,7 +188,17 @@ export class UnresolvedType {
}
export type HasStringGenerics = Class | Interface | Function;
export function hasStringGenerics(item: NamespaceMember): item is HasStringGenerics {
return (item as HasGenerics).generics !== undefined;
}
export type HasGenerics = HasStringGenerics | TypeReference;
export function hasGenerics(item: ModuleMember | EnumMember | TypeReference): item is HasGenerics {
return (item as HasGenerics).generics !== undefined;
}
export type CanBePrivate = Class | Interface | Function | Getter | Setter | Enum | Reference;
export type CanBeProtected = Function;
export type CanBeStatic = Function;
+51 -176
View File
@@ -18,33 +18,52 @@
* limitations under the License.
*/
import * as fs from "fs";
import * as path from "path";
import * as ts from "typescript";
import path = require("path");
import ts = require("typescript");
import { File, FileTransform, FileWatcher } from "async-build";
import { File, FileTransform } from "async-build";
import * as AST from "./ast";
import { walk } from "./walker";
export interface StreamingCompilerHost extends ts.CompilerHost, ts.ParseConfigHost {
export interface StreamingCompilerHost extends ts.CompilerHost {
setOutputStream(outputStream: FileTransform): void;
}
function createCompilerHost(options: ts.CompilerOptions): StreamingCompilerHost {
const host = ts.createCompilerHost(options) as StreamingCompilerHost;
let _outputStream: FileTransform = null;
host.setOutputStream = outputStream => _outputStream = outputStream;
host.writeFile = (fileName, data, writeByteOrderMark, onError?, sourceFiles?): void => {
_outputStream.push({
path: fileName,
contents: new Buffer(data)
});
};
host.useCaseSensitiveFileNames = () => true;
host.getNewLine = () => "\n";
return host;
}
export class Compiler {
private _projectRoot: string = null;
private _host: StreamingCompilerHost;
private _program: ts.Program = null;
constructor(private _host: StreamingCompilerHost = new CompilerHost()) { }
compile(projectConfigFile: File) {
this._projectRoot = path.dirname(projectConfigFile.path);
var projectConfig = ts.parseJsonConfigFileContent(JSON.parse(projectConfigFile.contents.toString()), this._host, this._projectRoot);
const projectConfig = ts.parseJsonConfigFileContent(JSON.parse(projectConfigFile.contents.toString()), ts.sys, this._projectRoot);
this._host = createCompilerHost(projectConfig.options);
this._program = ts.createProgram(projectConfig.fileNames, projectConfig.options, this._host);
var syntacticDiagnostics = this._program.getSyntacticDiagnostics();
const syntacticDiagnostics = this._program.getSyntacticDiagnostics();
if (syntacticDiagnostics.length > 0) {
this._reportDiagnostics(syntacticDiagnostics);
throw new Error("There were one or more syntactic diagnostics.");
@@ -56,13 +75,13 @@ export class Compiler {
throw new Error("There were one or more options diagnostics.");
}
var globalDiagnostics = this._program.getGlobalDiagnostics();
const globalDiagnostics = this._program.getGlobalDiagnostics();
if (globalDiagnostics.length > 0) {
this._reportDiagnostics(globalDiagnostics);
throw new Error("There were one or more global diagnostics.");
}
var semanticDiagnostics = this._program.getSemanticDiagnostics();
const semanticDiagnostics = this._program.getSemanticDiagnostics();
if (semanticDiagnostics.length > 0) {
this._reportDiagnostics(semanticDiagnostics);
throw new Error("There were one or more semantic diagnostics.");
@@ -72,7 +91,7 @@ export class Compiler {
writeFiles(outputStream: FileTransform) {
this._host.setOutputStream(outputStream);
var emitDiagnostics = this._program.emit().diagnostics;
const emitDiagnostics = this._program.emit().diagnostics;
if (emitDiagnostics.length > 0) {
this._reportDiagnostics(emitDiagnostics);
throw new Error("There were one or more emit diagnostics.");
@@ -93,10 +112,10 @@ export class Compiler {
private _reportDiagnostics(diagnostics: ts.Diagnostic[]) {
for (const diagnostic of diagnostics) {
var message = "";
let message = "";
if (diagnostic.file) {
var location = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
const location = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
message = `${ diagnostic.file.fileName }(${ location.line + 1 },${ location.character }): `;
}
@@ -110,168 +129,23 @@ export class Compiler {
};
}
const typeScriptModulePath = path.dirname(require.resolve("typescript"));
class CompilerHost implements StreamingCompilerHost {
protected _sourceFiles = Object.create(null);
private _outputStream: FileTransform = null;
setOutputStream(outputStream: FileTransform): void {
this._outputStream = outputStream;
}
// ts.ModuleResolutionHost members
fileExists(fileName: string): boolean {
return fs.existsSync(fileName);
}
readFile(fileName: string): string {
if (!this.fileExists(fileName)) {
return undefined;
}
return fs.readFileSync(fileName, { encoding: "utf8" });
}
// ts.CompilerHost members
getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError: (message: string) => void): ts.SourceFile {
if (fileName in this._sourceFiles) {
return this._sourceFiles[fileName];
}
try {
var text = fs.readFileSync(fileName, { encoding: "utf8" });
var result = ts.createSourceFile(fileName, text, ts.ScriptTarget.ES5);
this._sourceFiles[fileName] = result;
}
catch (ex) {
if (onError) {
onError(ex.message);
}
}
return result;
}
getDefaultLibFileName(): string {
return path.join(typeScriptModulePath, "lib.dom.d.ts");
}
writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError: (message?: string) => void): void {
this._outputStream.push({
path: fileName,
contents: new Buffer(data)
});
}
getCurrentDirectory(): string {
return path.resolve(".");
}
getCanonicalFileName(fileName: string): string {
return ts.normalizeSlashes(path.resolve(fileName));
}
useCaseSensitiveFileNames(): boolean {
return true;
}
getNewLine(): string {
return "\n";
}
// ts.ParseConfigHost members
readDirectory(rootDir: string, extension: string, exclude: string[]): string[] {
return ts.sys.readDirectory(rootDir, extension, exclude).map(fileName => this.getCanonicalFileName(fileName));
}
}
class WatchCompilerHost extends CompilerHost {
private _fileWatcher = new FileWatcher(fileNames => this._onFilesChanged(fileNames));
private _filesChangedSinceLast: string[] = [];
constructor(private _onChangeCallback: () => void) {
super();
}
getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError: (message: string) => void): ts.SourceFile {
var result = super.getSourceFile(fileName, languageVersion, onError);
if (result !== undefined) {
this._fileWatcher.watchFile(fileName);
}
return result;
};
private _onFilesChanged(fileNames: string[]) {
for (const fileName of fileNames) {
delete this._sourceFiles[fileName];
}
this._onChangeCallback();
}
}
export function build(root: string, rootNamespaceName: string): FileTransform {
var compiler = new Compiler();
return new FileTransform(function (projectConfigFile: File): void {
var self: FileTransform = this;
const compiler = new Compiler();
return new FileTransform(function (projectConfigFile): void {
console.log("Compiling " + projectConfigFile.path + "...");
compiler.compile(projectConfigFile);
var walkResult = walk(compiler, root, rootNamespaceName);
const walkResult = walk(compiler, root, rootNamespaceName);
addJSDocComments(walkResult.modules);
compiler.writeFiles(self);
compiler.writeFiles(this);
console.log("Compile succeeded.");
});
}
export function watch(root: string, rootNamespaceName: string): FileTransform {
return new FileTransform(function (projectConfigFile: File): void {
var self: FileTransform = this;
function compile() {
console.log("Compiling " + projectConfigFile.path + "...");
compiler.compile(projectConfigFile);
compiler.writeFiles(self);
console.log("Compile succeeded.");
self.push({
path: "END",
contents: ""
});
};
var compilerHost = new WatchCompilerHost(() => {
try {
compile();
}
catch (ex) {
console.error("Compile failed." + ex.stack);
}
});
var compiler = new Compiler(compilerHost);
compile();
console.log("Listening for changes...");
}, callback => { });
}
function addJSDocComments(modules: { [name: string]: AST.Module }): void {
function visitor(current: AST.Module | AST.ModuleMember | AST.InterfaceMember) {
if (current instanceof AST.Module) {
@@ -282,18 +156,18 @@ function addJSDocComments(modules: { [name: string]: AST.Module }): void {
return;
}
var newComments: string[] = [];
const newComments: string[] = [];
if (current instanceof AST.Class) {
newComments.push("@constructor");
if (current.baseType !== null) {
var baseType = current.baseType;
const baseType = current.baseType;
newComments.push(
"@extends {" +
baseType.fullName + (
(baseType instanceof AST.TypeReference && baseType.generics.length) > 0 ?
(".<" + (<AST.TypeReference>baseType).generics.map(generic => generic.fullName).join(", ") + ">") :
(".<" + (baseType as AST.TypeReference).generics.map(generic => generic.fullName).join(", ") + ">") :
""
) +
"}"
@@ -323,37 +197,37 @@ function addJSDocComments(modules: { [name: string]: AST.Module }): void {
return;
}
if ((<AST.HasParent><any>current).parent instanceof AST.Namespace) {
newComments.push("@memberOf " + (<AST.HasParent><any>current).parent.fullName);
if (current.parent instanceof AST.Namespace) {
newComments.push("@memberOf " + current.parent.fullName);
}
if ((<AST.HasStringGenerics>current).generics !== undefined && (<AST.HasStringGenerics>current).generics.length > 0) {
newComments.push("@template " + (<AST.HasStringGenerics>current).generics.join(", "));
if (AST.hasStringGenerics(current) && current.generics.length > 0) {
newComments.push("@template " + current.generics.join(", "));
}
if ((<AST.CanBePrivate><any>current).isPrivate) {
if ((current as AST.CanBePrivate).isPrivate) {
newComments.push("@private");
}
if ((<AST.CanBeProtected>current).isProtected) {
if ((current as AST.CanBeProtected).isProtected) {
newComments.push("@protected");
}
if ((<AST.CanBeStatic>current).isStatic) {
if ((current as AST.CanBeStatic).isStatic) {
newComments.push("@static");
}
if (newComments.length > 0) {
if (current instanceof AST.Property) {
var nodes: ts.Node[] = [];
const nodes: ts.Node[] = [];
if (current.getter !== null) { nodes.push(current.getter.astNode); }
if (current.setter !== null && nodes[0] !== current.setter.astNode) { nodes.push(current.setter.astNode); }
for (const node of nodes) {
(<any>node)["typescript-new-comment"] = newComments;
(node as any)["typescript-new-comment"] = newComments;
}
}
else {
(<any>(<AST.Class | AST.Interface | AST.Function | AST.Enum>current).astNode)["typescript-new-comment"] = newComments;
(current.astNode as any)["typescript-new-comment"] = newComments;
}
}
}
@@ -405,6 +279,7 @@ class FakeSourceFile {
var fakeSourceFiles: { [name: string]: FakeSourceFile } = Object.create(null);
export const oldGetLeadingCommentRangesOfNodeFromText: typeof ts.getLeadingCommentRangesOfNodeFromText = ts.getLeadingCommentRangesOfNodeFromText.bind(ts);
ts.getLeadingCommentRangesOfNodeFromText = (node: ts.Node, text: string) => {
const originalComments = oldGetLeadingCommentRangesOfNodeFromText(node, text);
+13 -13
View File
@@ -1,22 +1,22 @@
declare namespace ts {
export interface EmitTextWriter { }
interface EmitTextWriter { }
export interface IntrinsicType extends Type {
interface IntrinsicType extends Type {
intrinsicName: string;
}
export interface SourceFile {
interface SourceFile {
lineMap: number[];
}
export function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U;
export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration): ExpressionWithTypeArguments;
export function getClassImplementsHeritageClauseElements(node: ClassDeclaration): NodeArray<ExpressionWithTypeArguments>;
export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray<ExpressionWithTypeArguments>;
export function getLeadingCommentRangesOfNodeFromText(node: Node, text: string): CommentRange[];
export function getLineStarts(sourceFile: SourceFile): number[];
export function getSourceFileOfNode(node: Node): SourceFile;
export function getTextOfNode(node: Node, includeTrivia?: boolean): string;
export function normalizeSlashes(path: string): string;
export function writeCommentRange(text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string): void;
function forEachProperty<T, U>(map: Map<T>, callback: (value: T, key: string) => U): U;
function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments;
function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration): ExpressionWithTypeArguments[];
function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): ExpressionWithTypeArguments[];
function getLeadingCommentRangesOfNodeFromText(node: Node, text: string): CommentRange[];
function getLineStarts(sourceFile: SourceFile): number[];
function getSourceFileOfNode(node: Node): SourceFile;
function getTextOfNode(node: Node, includeTrivia?: boolean): string;
function normalizeSlashes(path: string): string;
function writeCommentRange(text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string): void;
}
+1 -1
View File
@@ -18,4 +18,4 @@
* limitations under the License.
*/
export { build, watch } from "./compiler";
export { build } from "./compiler";
+195 -177
View File
@@ -18,13 +18,17 @@
* limitations under the License.
*/
import * as path from "path";
import * as ts from "typescript";
import path = require("path");
import ts = require("typescript");
import { Compiler, oldGetLeadingCommentRangesOfNodeFromText } from "./compiler";
import * as AST from "./ast";
function hasModifier(node: ts.Node, flags: ts.NodeFlags): boolean {
return (node.flags & flags) !== 0;
}
interface JSDoc {
description: string;
isAbstract: boolean;
@@ -68,13 +72,13 @@ class Walker {
}
walk(sourceFile: ts.SourceFile): void {
var moduleName = this._moduleNameFromFileName(sourceFile.fileName);
const moduleName = this._moduleNameFromFileName(sourceFile.fileName);
if (!(moduleName in this.modules)) {
this.modules[moduleName] = new AST.Module(moduleName);
}
var module = this._scope.enter(this.modules[moduleName]);
const module = this._scope.enter(this.modules[moduleName]);
this._currentSourceFile = sourceFile;
for (const statement of sourceFile.statements) {
@@ -87,31 +91,31 @@ class Walker {
private _walk(node: ts.Node, parent: AST.Module): void {
switch (node.kind) {
case ts.SyntaxKind.VariableStatement:
this._visitVariableStatement(<ts.VariableStatement>node, parent);
this._visitVariableStatement(node as ts.VariableStatement, parent);
break;
case ts.SyntaxKind.FunctionDeclaration:
this._visitFunctionDeclaration(<ts.FunctionDeclaration>node, parent);
this._visitFunctionDeclaration(node as ts.FunctionDeclaration, parent);
break;
case ts.SyntaxKind.ClassDeclaration:
this._visitClassDeclaration(<ts.ClassDeclaration>node, parent);
this._visitClassDeclaration(node as ts.ClassDeclaration, parent);
break;
case ts.SyntaxKind.InterfaceDeclaration:
this._visitInterfaceDeclaration(<ts.InterfaceDeclaration>node, parent);
this._visitInterfaceDeclaration(node as ts.InterfaceDeclaration, parent);
break;
case ts.SyntaxKind.EnumDeclaration:
this._visitEnumDeclaration(<ts.EnumDeclaration>node, parent);
this._visitEnumDeclaration(node as ts.EnumDeclaration, parent);
break;
case ts.SyntaxKind.ImportDeclaration:
this._visitImportDeclaration(<ts.ImportDeclaration>node, parent);
this._visitImportDeclaration(node as ts.ImportDeclaration, parent);
break;
case ts.SyntaxKind.ExportDeclaration:
this._visitExportDeclaration(<ts.ExportDeclaration>node, parent);
this._visitExportDeclaration(node as ts.ExportDeclaration, parent);
break;
case ts.SyntaxKind.ExpressionStatement:
@@ -121,7 +125,7 @@ class Walker {
break;
default:
console.error(node.kind, (<any>ts).SyntaxKind[node.kind], node);
console.error(node.kind, ts.SyntaxKind[node.kind], node);
throw new Error("Unrecognized node.");
}
}
@@ -130,20 +134,20 @@ class Walker {
switch (node.kind) {
case ts.SyntaxKind.PropertySignature:
case ts.SyntaxKind.PropertyDeclaration:
this._visitProperty(<ts.PropertyDeclaration>node, clazz);
this._visitProperty(node as ts.PropertyDeclaration, clazz);
break;
case ts.SyntaxKind.MethodSignature:
case ts.SyntaxKind.MethodDeclaration:
this._visitMethod(<ts.MethodDeclaration>node, clazz);
this._visitMethod(node as ts.MethodDeclaration, clazz);
break;
case ts.SyntaxKind.GetAccessor:
this._visitGetAccessor(<ts.AccessorDeclaration>node, clazz);
this._visitGetAccessor(node as ts.AccessorDeclaration, clazz);
break;
case ts.SyntaxKind.SetAccessor:
this._visitSetAccessor(<ts.AccessorDeclaration>node, clazz);
this._visitSetAccessor(node as ts.AccessorDeclaration, clazz);
break;
case ts.SyntaxKind.TypeParameter:
@@ -152,7 +156,7 @@ class Walker {
break;
default:
console.error(node.kind, (<any>ts).SyntaxKind[node.kind], node);
console.error(node.kind, ts.SyntaxKind[node.kind], node);
throw new Error("Unrecognized node.");
}
}
@@ -161,12 +165,12 @@ class Walker {
switch (node.kind) {
case ts.SyntaxKind.PropertySignature:
case ts.SyntaxKind.PropertyDeclaration:
this._visitProperty(<ts.PropertyDeclaration>node, interfase);
this._visitProperty(node as ts.PropertyDeclaration, interfase);
break;
case ts.SyntaxKind.MethodSignature:
case ts.SyntaxKind.MethodDeclaration:
this._visitMethod(<ts.MethodDeclaration>node, interfase);
this._visitMethod(node as ts.MethodDeclaration, interfase);
break;
case ts.SyntaxKind.TypeParameter:
@@ -176,24 +180,24 @@ class Walker {
break;
default:
console.error(node.kind, (<any>ts).SyntaxKind[node.kind], node);
console.error(node.kind, ts.SyntaxKind[node.kind], node);
throw new Error("Unrecognized node.");
}
}
private _visitProperty(node: ts.PropertyDeclaration, parent: AST.Class | AST.Interface) {
if ((node.flags & ts.NodeFlags.Private) === ts.NodeFlags.Private) {
if (hasModifier(node, ts.NodeFlags.Private)) {
return;
}
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
if (jsDoc.typeAnnotation === null) {
this._notifyIncorrectJsDoc(`Field ${ ts.getTextOfNode(node.name) } has no @type annotation.`);
jsDoc.typeAnnotation = "*";
}
var property = this._scope.enter(new AST.Property(ts.getTextOfNode(node.name)));
const property = this._scope.enter(new AST.Property(ts.getTextOfNode(node.name)));
parent.members[property.name] = property;
property.getter = new AST.Getter(node, jsDoc.description, jsDoc.typeAnnotation, false);
property.setter = new AST.Setter(node, jsDoc.description, jsDoc.typeAnnotation, false);
@@ -201,9 +205,9 @@ class Walker {
}
private _visitMethod(node: ts.MethodDeclaration, parent: AST.Class | AST.Interface) {
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
var parameters = this._connectParameters(node.parameters, jsDoc.parameters,
const parameters = this._connectParameters(node.parameters, jsDoc.parameters,
parameterName => `Could not find @param annotation for ${ parameterName } on method ${ ts.getTextOfNode(node.name) }`
);
@@ -212,25 +216,25 @@ class Walker {
jsDoc.returnType = new AST.ReturnType("", "*");
}
var isPrivate = (node.flags & ts.NodeFlags.Private) === ts.NodeFlags.Private;
var isProtected = (node.flags & ts.NodeFlags.Protected) === ts.NodeFlags.Protected;
var isStatic = (node.flags & ts.NodeFlags.Static) === ts.NodeFlags.Static;
const isPrivate = hasModifier(node, ts.NodeFlags.Private);
const isProtected = hasModifier(node, ts.NodeFlags.Protected);
const isStatic = hasModifier(node, ts.NodeFlags.Static);
var generics = this._getGenericsOfSignatureDeclaration(node);
const generics = this._getGenericsOfSignatureDeclaration(node);
var method = this._scope.enter(new AST.Function(ts.getTextOfNode(node.name), node, jsDoc.description, generics, parameters, jsDoc.returnType, jsDoc.isAbstract, isPrivate, isProtected, isStatic));
const method = this._scope.enter(new AST.Function(ts.getTextOfNode(node.name), node, jsDoc.description, generics, parameters, jsDoc.returnType, jsDoc.isAbstract, isPrivate, isProtected, isStatic));
parent.members[method.name] = method;
this._scope.leave();
}
private _visitGetAccessor(node: ts.AccessorDeclaration, clazz: AST.Class): void {
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
var name = ts.getTextOfNode(node.name);
const name = ts.getTextOfNode(node.name);
var isPrivate = (node.flags & ts.NodeFlags.Private) === ts.NodeFlags.Private;
const isPrivate = hasModifier(node, ts.NodeFlags.Private);
var property = <AST.Property>clazz.members[name];
let property = clazz.members[name] as AST.Property;
if (property === undefined) {
this._scope.enter(property = new AST.Property(name));
@@ -247,13 +251,13 @@ class Walker {
}
private _visitSetAccessor(node: ts.AccessorDeclaration, clazz: AST.Class): void {
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
var name = ts.getTextOfNode(node.name);
const name = ts.getTextOfNode(node.name);
var isPrivate = (node.flags & ts.NodeFlags.Private) === ts.NodeFlags.Private;
const isPrivate = hasModifier(node, ts.NodeFlags.Private);
var property = <AST.Property>clazz.members[name];
let property = clazz.members[name] as AST.Property;
if (property === undefined) {
this._scope.enter(property = new AST.Property(name));
@@ -274,17 +278,17 @@ class Walker {
return;
}
var declaration = node.declarationList.declarations[0];
if ((declaration.flags & ts.NodeFlags.Ambient) === ts.NodeFlags.Ambient) {
const declaration = node.declarationList.declarations[0];
if (hasModifier(declaration, ts.NodeFlags.Ambient)) {
return;
}
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
if (jsDoc.typeAnnotation === null) {
return;
}
var property = this._scope.enter(new AST.Property(ts.getTextOfNode(declaration.name)));
const property = this._scope.enter(new AST.Property(ts.getTextOfNode(declaration.name)));
property.getter = new AST.Getter(node, jsDoc.description, jsDoc.typeAnnotation, false);
parent.members[property.name] = property;
@@ -293,13 +297,13 @@ class Walker {
}
private _visitFunctionDeclaration(node: ts.FunctionDeclaration, parent: AST.Module): void {
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
var isPrivate = (node.flags & ts.NodeFlags.Export) !== ts.NodeFlags.Export;
const isPrivate = !hasModifier(node, ts.NodeFlags.Export);
var generics = this._getGenericsOfSignatureDeclaration(node);
const generics = this._getGenericsOfSignatureDeclaration(node);
var parameters = this._connectParameters(node.parameters, jsDoc.parameters,
const parameters = this._connectParameters(node.parameters, jsDoc.parameters,
parameterName => `Could not find @param annotation for ${ parameterName } on function ${ node.name.text }`
);
@@ -312,7 +316,7 @@ class Walker {
jsDoc.returnType = new AST.ReturnType("", "*");
}
var freeFunction = this._scope.enter(new AST.Function(node.name.text, node, jsDoc.description, generics, parameters, jsDoc.returnType, jsDoc.isAbstract, isPrivate, false, false));
const freeFunction = this._scope.enter(new AST.Function(node.name.text, node, jsDoc.description, generics, parameters, jsDoc.returnType, jsDoc.isAbstract, isPrivate, false, false));
parent.members[freeFunction.name] = freeFunction;
@@ -320,32 +324,32 @@ class Walker {
}
private _visitClassDeclaration(node: ts.ClassDeclaration, parent: AST.Module): void {
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
var baseTypeHeritageClauseElement = ts.getClassExtendsHeritageClauseElement(node) || null;
var baseType: AST.UnresolvedType = null;
const type = this._typeChecker.getTypeAtLocation(node) as ts.InterfaceType;
const generics = this._getGenericsOfInterfaceType(type);
const baseTypeHeritageClauseElement = ts.getClassExtendsHeritageClauseElement(node) || null;
let baseType: AST.UnresolvedType = null;
if (baseTypeHeritageClauseElement !== null) {
baseType = new AST.UnresolvedType(
this._typeChecker.getTypeAtLocation(baseTypeHeritageClauseElement).symbol,
this._getGenericsOfTypeReferenceNode(baseTypeHeritageClauseElement)
this._getGenericsOfTypeReferenceNode(baseTypeHeritageClauseElement, generics)
);
}
var interfaces = (ts.getClassImplementsHeritageClauseElements(node) || []).map(type => new AST.UnresolvedType(
const interfaces = (ts.getClassImplementsHeritageClauseElements(node) || []).map(type => new AST.UnresolvedType(
this._typeChecker.getTypeAtLocation(type).symbol,
this._getGenericsOfTypeReferenceNode(type)
this._getGenericsOfTypeReferenceNode(type, generics)
));
var isPrivate = (node.flags & ts.NodeFlags.Export) !== ts.NodeFlags.Export;
const isPrivate = !hasModifier(node, ts.NodeFlags.Export);
var type = <ts.InterfaceType>this._typeChecker.getTypeAtLocation(node);
var generics = this._getGenericsOfInterfaceType(type);
var parameters: AST.Parameter[] = [];
let parameters: AST.Parameter[] = [];
if (type.symbol.members["__constructor"] !== undefined) {
parameters = this._connectParameters((<ts.ConstructorDeclaration>type.symbol.members["__constructor"].declarations[0]).parameters, jsDoc.parameters,
parameters = this._connectParameters((type.symbol.members["__constructor"].declarations[0] as ts.ConstructorDeclaration).parameters, jsDoc.parameters,
parameterName => `Could not find @param annotation for ${ parameterName } on constructor in class ${ node.name.text }`
);
}
@@ -353,11 +357,11 @@ class Walker {
this._notifyIncorrectJsDoc("There are @param annotations on this class but it has no constructors.");
}
var clazz = this._scope.enter(new AST.Class(node.name.text, node, jsDoc.description, generics, parameters, baseType, interfaces, jsDoc.isAbstract, isPrivate));
const clazz = this._scope.enter(new AST.Class(node.name.text, node, jsDoc.description, generics, parameters, baseType, interfaces, jsDoc.isAbstract, isPrivate));
parent.members[clazz.name] = clazz;
ts.forEachValue(type.symbol.exports, symbol => {
ts.forEachProperty(type.symbol.exports, symbol => {
if (symbol.name === "prototype") {
return;
}
@@ -367,7 +371,7 @@ class Walker {
}
});
ts.forEachValue(type.symbol.members, symbol => {
ts.forEachProperty(type.symbol.members, symbol => {
for (const declaration of symbol.declarations) {
this._walkClassMember(declaration, clazz);
}
@@ -377,28 +381,28 @@ class Walker {
}
private _visitInterfaceDeclaration(node: ts.InterfaceDeclaration, parent: AST.Module): void {
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
var baseTypes = (ts.getInterfaceBaseTypeNodes(node) || []).map(type => new AST.UnresolvedType(
const type = this._typeChecker.getTypeAtLocation(node) as ts.InterfaceType;
const generics = this._getGenericsOfInterfaceType(type);
const baseTypes = (ts.getInterfaceBaseTypeNodes(node) || []).map(type => new AST.UnresolvedType(
this._typeChecker.getTypeAtLocation(type).symbol,
this._getGenericsOfTypeReferenceNode(type)
this._getGenericsOfTypeReferenceNode(type, generics)
));
var existingInterfaceType = parent.members[node.name.text];
const existingInterfaceType = parent.members[node.name.text];
if (existingInterfaceType !== undefined) {
return;
}
var isPrivate = (node.flags & ts.NodeFlags.Export) !== ts.NodeFlags.Export;
const isPrivate = !hasModifier(node, ts.NodeFlags.Export);
var type = <ts.InterfaceType>this._typeChecker.getTypeAtLocation(node);
var generics = this._getGenericsOfInterfaceType(type);
var interfase = this._scope.enter(new AST.Interface(node.name.text, node, jsDoc.description, generics, baseTypes, isPrivate));
const interfase = this._scope.enter(new AST.Interface(node.name.text, node, jsDoc.description, generics, baseTypes, isPrivate));
parent.members[interfase.name] = interfase;
ts.forEachValue(type.symbol.members, symbol => {
ts.forEachProperty(type.symbol.members, symbol => {
for (const declaration of symbol.declarations) {
this._walkInterfaceMember(declaration, interfase);
}
@@ -408,33 +412,33 @@ class Walker {
}
private _visitEnumDeclaration(node: ts.EnumDeclaration, parent: AST.Module): void {
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
var existingEnumType = parent.members[node.name.text];
const existingEnumType = parent.members[node.name.text];
if (existingEnumType !== undefined) {
return;
}
var isPrivate = (node.flags & ts.NodeFlags.Export) !== ts.NodeFlags.Export;
const isPrivate = !hasModifier(node, ts.NodeFlags.Export);
var type = this._typeChecker.getTypeAtLocation(node);
const type = this._typeChecker.getTypeAtLocation(node);
var enumType = this._scope.enter(new AST.Enum(node.name.text, node, jsDoc.description, isPrivate));
const enumType = this._scope.enter(new AST.Enum(node.name.text, node, jsDoc.description, isPrivate));
parent.members[enumType.name] = enumType;
ts.forEachValue(type.symbol.exports, symbol => {
this._visitEnumMember(<ts.EnumMember>symbol.declarations[0], enumType);
ts.forEachProperty(type.symbol.exports, symbol => {
this._visitEnumMember(symbol.declarations[0] as ts.EnumMember, enumType);
});
this._scope.leave();
}
private _visitEnumMember(node: ts.EnumMember, parent: AST.Enum): void {
var jsDoc = this._parseJSDoc(node);
const jsDoc = this._parseJSDoc(node);
var value = (node.initializer === undefined) ? null : parseInt((<ts.LiteralExpression>node.initializer).text);
const value = (node.initializer === undefined) ? null : parseInt((node.initializer as ts.LiteralExpression).text);
var enumMember = this._scope.enter(new AST.EnumMember(ts.getTextOfNode(node.name), (jsDoc === null) ? "" : jsDoc.description, value));
const enumMember = this._scope.enter(new AST.EnumMember(ts.getTextOfNode(node.name), (jsDoc === null) ? "" : jsDoc.description, value));
parent.members.push(enumMember);
@@ -451,16 +455,16 @@ class Walker {
throw new Error("Default import is not supported.");
}
var moduleName = this._resolve((<ts.LiteralExpression>node.moduleSpecifier).text, parent);
const moduleName = this._resolve((node.moduleSpecifier as ts.LiteralExpression).text, parent);
if ((<ts.NamespaceImport>node.importClause.namedBindings).name !== undefined) {
if ((node.importClause.namedBindings as ts.NamespaceImport).name !== undefined) {
// import * as foo from "baz";
parent.members[(<ts.NamespaceImport>node.importClause.namedBindings).name.text] = new AST.Reference(moduleName, "*", true);
parent.members[(node.importClause.namedBindings as ts.NamespaceImport).name.text] = new AST.Reference(moduleName, "*", true);
}
else if ((<ts.NamedImports>node.importClause.namedBindings).elements !== undefined) {
else if ((node.importClause.namedBindings as ts.NamedImports).elements !== undefined) {
// import { foo, bar } from "baz";
for (const element of (<ts.NamedImports>node.importClause.namedBindings).elements) {
var importedName = element.propertyName && element.propertyName.text || element.name.text;
for (const element of (node.importClause.namedBindings as ts.NamedImports).elements) {
const importedName = element.propertyName && element.propertyName.text || element.name.text;
parent.members[element.name.text] = new AST.Reference(moduleName, importedName, true);
}
}
@@ -472,22 +476,22 @@ class Walker {
private _visitExportDeclaration(node: ts.ExportDeclaration, parent: AST.Module): void {
if (node.moduleSpecifier !== undefined) {
// export { foo } from "bar";
var moduleName = this._resolve((<ts.LiteralExpression>node.moduleSpecifier).text, parent);
const moduleName = this._resolve((node.moduleSpecifier as ts.LiteralExpression).text, parent);
for (const element of node.exportClause.elements) {
var importedName = element.propertyName && element.propertyName.text || element.name.text;
const importedName = element.propertyName && element.propertyName.text || element.name.text;
parent.members[element.name.text] = new AST.Reference(moduleName, importedName, false);
}
}
else {
// export { foo };
for (const element of node.exportClause.elements) {
(<AST.CanBePrivate><any>parent.members[element.name.text]).isPrivate = false;
(parent.members[element.name.text] as AST.CanBePrivate).isPrivate = false;
}
}
}
private _resolve(relativeModuleName: string, currentModule: AST.Module): string {
var result = ts.normalizeSlashes(path.join(currentModule.name, `../${ relativeModuleName }`));
let result = ts.normalizeSlashes(path.join(currentModule.name, `../${ relativeModuleName }`));
if (result[0] !== ".") {
result = `./${ result }`;
@@ -497,7 +501,7 @@ class Walker {
}
private _parseJSDoc(node: ts.Node): JSDoc {
var comments = oldGetLeadingCommentRangesOfNodeFromText(node, this._currentSourceFile.text);
let comments = oldGetLeadingCommentRangesOfNodeFromText(node, this._currentSourceFile.text);
if (comments === undefined) {
comments = [];
@@ -507,41 +511,41 @@ class Walker {
comments = [comments[comments.length - 1]];
}
var comment =
const comment =
(comments.length === 0) ?
"" :
this._currentSourceFile.text.substring(comments[0].pos, comments[0].end);
var commentStartIndex = comment.indexOf("/**");
var commentEndIndex = comment.lastIndexOf("*/");
const commentStartIndex = comment.indexOf("/**");
const commentEndIndex = comment.lastIndexOf("*/");
var lines =
const lines =
(commentStartIndex === -1 || commentEndIndex === -1) ?
[] :
comment.substring(commentStartIndex + 2, commentEndIndex).split("\n").map(line => {
var match = line.match(/^[ \t]*\* (.*)/);
const match = line.match(/^[ \t]*\* (.*)/);
if (match === null) {
return "";
}
return match[1];
});
var rootDescription = "";
let rootDescription = "";
var parameters: { [name: string]: AST.Parameter } = Object.create(null);
const parameters: { [name: string]: AST.Parameter } = Object.create(null);
var typeAnnotation: string = null;
let typeAnnotation: string = null;
var returnType: AST.ReturnType = null;
let returnType: AST.ReturnType = null;
var isAbstract = false;
let isAbstract = false;
var lastRead: { description: string } = null;
let lastRead: { description: string } = null;
for (const line of lines) {
var firstWordMatch = line.match(/^\s*(\S+)(\s*)/);
var firstWord = (firstWordMatch !== null) ? firstWordMatch[1] : "";
var remainingLine = (firstWordMatch !== null) ? line.substring(firstWordMatch[0].length) : "";
const firstWordMatch = line.match(/^\s*(\S+)(\s*)/);
const firstWord = (firstWordMatch !== null) ? firstWordMatch[1] : "";
let remainingLine = (firstWordMatch !== null) ? line.substring(firstWordMatch[0].length) : "";
if (firstWord[0] === "@") {
lastRead = null;
@@ -552,30 +556,33 @@ class Walker {
isAbstract = true;
break;
case "@param":
var type: string;
case "@param": {
let type: string;
[type, remainingLine] = this._readType(remainingLine);
var [, name, description] = remainingLine.match(/(\S+)\s*(.*)/);
const [, name, description] = remainingLine.match(/(\S+)\s*(.*)/);
var subParameterMatch = name.match(/^(?:(.+)\.([^\.]+))|(?:(.+)\[("[^\[\]"]+")\])$/);
const subParameterMatch = name.match(/^(?:(.+)\.([^\.]+))|(?:(.+)\[("[^\[\]"]+")\])$/);
if (subParameterMatch === null) {
parameters[name] = lastRead = new AST.Parameter(name, description, type);
}
else {
var parentName = subParameterMatch[1] || subParameterMatch[3];
var childName = subParameterMatch[2] || subParameterMatch[4];
var parentParameter = parameters[parentName];
const parentName = subParameterMatch[1] || subParameterMatch[3];
const childName = subParameterMatch[2] || subParameterMatch[4];
const parentParameter = parameters[parentName];
parentParameter.subParameters.push(lastRead = new AST.Parameter(childName, description, type));
}
break;
case "@return":
var [type, description] = this._readType(remainingLine);
break;
}
case "@return": {
const [type, description] = this._readType(remainingLine);
returnType = lastRead = new AST.ReturnType(description, type);
break;
}
case "@type":
[typeAnnotation] = this._readType(remainingLine);
@@ -606,9 +613,9 @@ class Walker {
return ["*", remainingLine];
}
var index = -1;
var numberOfUnterminatedBraces = 0;
for (var i = 0; i < remainingLine.length; i++) {
let index = -1;
let numberOfUnterminatedBraces = 0;
for (let i = 0; i < remainingLine.length; i++) {
if (remainingLine[i] === "{") {
numberOfUnterminatedBraces++;
}
@@ -626,7 +633,7 @@ class Walker {
throw new Error("Unterminated type specifier.");
}
var type = remainingLine.substr(1, index - 1);
const type = remainingLine.substr(1, index - 1);
remainingLine = remainingLine.substr(index + 1).replace(/^\s+/, "");
return [type, remainingLine];
@@ -640,16 +647,24 @@ class Walker {
return signatureDeclaration.typeParameters.map(typeParameter => typeParameter.name.text);
}
private _getGenericsOfTypeReferenceNode(typeReferenceNode: ts.ExpressionWithTypeArguments): (AST.UnresolvedType | AST.IntrinsicTypeReference)[] {
private _getGenericsOfTypeReferenceNode(typeReferenceNode: ts.ExpressionWithTypeArguments, intrinsicGenerics: string[]): (AST.UnresolvedType | AST.IntrinsicTypeReference)[] {
if (typeReferenceNode.typeArguments === undefined) {
return [];
}
var typeReference = <ts.TypeReference>this._typeChecker.getTypeAtLocation(typeReferenceNode);
const typeReference = this._typeChecker.getTypeAtLocation(typeReferenceNode) as ts.TypeReference;
return typeReference.typeArguments.map(typeArgument => {
if ((<ts.IntrinsicType>typeArgument).intrinsicName !== undefined) {
return new AST.IntrinsicTypeReference((<ts.IntrinsicType>typeArgument).intrinsicName);
if ((typeArgument as ts.IntrinsicType).intrinsicName !== undefined) {
return new AST.IntrinsicTypeReference((typeArgument as ts.IntrinsicType).intrinsicName);
}
if (typeArgument.flags & ts.TypeFlags.TypeParameter) {
if (intrinsicGenerics.indexOf(typeArgument.symbol.name) !== -1) {
return new AST.IntrinsicTypeReference(typeArgument.symbol.name);
}
throw new Error(`Unbound type parameter ${ typeArgument.symbol.name }`);
}
return new AST.UnresolvedType(typeArgument.symbol, []);
@@ -668,12 +683,12 @@ class Walker {
private _connectParameters(astParameters: ts.ParameterDeclaration[], jsDocParameters: { [name: string]: AST.Parameter }, onMissingMessageCallback: (parameterName: string) => string) {
return astParameters.map(parameter => {
var parameterName = (<ts.Identifier>parameter.name).text;
let parameterName = (parameter.name as ts.Identifier).text;
if (parameterName[0] === "_") {
parameterName = parameterName.substr(1);
}
var jsDocParameter = jsDocParameters[parameterName];
let jsDocParameter = jsDocParameters[parameterName];
if (jsDocParameter === undefined) {
this._notifyIncorrectJsDoc(onMissingMessageCallback.call(this, parameterName));
@@ -685,8 +700,8 @@ class Walker {
}
private _notifyIncorrectJsDoc(message: string): void {
var fileName = path.basename(this._currentSourceFile.fileName);
if (fileName === "lib.core.d.ts" || fileName === "lib.dom.d.ts") {
const fileName = path.basename(this._currentSourceFile.fileName);
if (fileName === "lib.es5.d.ts" || fileName === "lib.dom.d.ts") {
return;
}
@@ -695,17 +710,17 @@ class Walker {
link(rootNamespaceName: string): void {
for (const moduleName of Object.keys(this.modules)) {
var module = this.modules[moduleName];
const module = this.modules[moduleName];
for (const memberName of Object.keys(module.members)) {
var member = module.members[memberName];
const member = module.members[memberName];
if (member instanceof AST.Class) {
if (member.unresolvedBaseType instanceof AST.UnresolvedType) {
member.baseType = this._resolveTypeReference(<AST.UnresolvedType>member.unresolvedBaseType);
member.baseType = this._resolveTypeReference(member.unresolvedBaseType);
}
else {
member.baseType = <AST.TypeReference | AST.IntrinsicTypeReference>member.unresolvedBaseType;
member.baseType = member.unresolvedBaseType;
}
member.interfaces = member.unresolvedInterfaces.map(interfase => {
@@ -713,7 +728,7 @@ class Walker {
return this._resolveTypeReference(interfase);
}
return <AST.TypeReference | AST.IntrinsicTypeReference>interfase;
return interfase;
});
}
@@ -723,12 +738,12 @@ class Walker {
return this._resolveTypeReference(baseType);
}
return <AST.TypeReference | AST.IntrinsicTypeReference>baseType;
return baseType;
});
}
else if (member instanceof AST.Enum) {
var value = 0;
let value = 0;
for (const enumMember of member.members) {
if (enumMember.value === null) {
enumMember.value = value;
@@ -750,17 +765,17 @@ class Walker {
private _moduleToNamespace(module: AST.Module): void {
for (const memberName of Object.keys(module.members)) {
var member = module.members[memberName];
let member = module.members[memberName];
if (member instanceof AST.Reference) {
if ((<AST.Reference>member).isPrivate) {
if (member.isPrivate) {
continue;
}
if (member.name === "*") {
var newNamespace = this._scope.enter(new AST.Namespace(memberName));
const newNamespace = this._scope.enter(new AST.Namespace(memberName));
var existingNamespace = this.namespaces[newNamespace.fullName];
const existingNamespace = this.namespaces[newNamespace.fullName];
if (existingNamespace !== undefined) {
this._scope.leave();
this._scope.enter(existingNamespace);
@@ -769,10 +784,10 @@ class Walker {
this.namespaces[newNamespace.fullName] = newNamespace;
}
var referencedModuleName = (<AST.Reference>member).moduleName;
var referencedModule = this.modules[referencedModuleName];
let referencedModuleName = member.moduleName;
let referencedModule = this.modules[referencedModuleName];
if (referencedModule === undefined && ((referencedModuleName + "/index") in this.modules)) {
(<AST.Reference>member).moduleName = referencedModuleName = referencedModuleName + "/index";
member.moduleName = referencedModuleName = referencedModuleName + "/index";
referencedModule = this.modules[referencedModuleName];
}
this._moduleToNamespace(referencedModule);
@@ -781,56 +796,61 @@ class Walker {
}
else {
while (member instanceof AST.Reference) {
member = this.modules[(<AST.Reference>member).moduleName].members[member.name];
member = this.modules[member.moduleName].members[member.name];
}
this._scope.enter(<AST.NamespaceMember><any>member);
this._scope.enter(member);
this._scope.leave();
(<AST.Namespace>this._scope.current).members[member.name] = <AST.NamespaceMember>member;
(this._scope.current as AST.Namespace).members[member.name] = member;
}
}
else if (!(<AST.CanBePrivate><any>member).isPrivate) {
this._scope.enter(<AST.NamespaceMember>member);
else if (!(member as AST.CanBePrivate).isPrivate) {
this._scope.enter(member);
this._scope.leave();
(<AST.Namespace>this._scope.current).members[member.name] = <AST.NamespaceMember>member;
(this._scope.current as AST.Namespace).members[member.name] = member;
}
}
}
private _resolveTypeReference(unresolvedType: AST.UnresolvedType): AST.TypeReference {
var node: ts.Node = unresolvedType.symbol.declarations[0];
private _resolveTypeReference(unresolvedType: AST.UnresolvedType): AST.TypeReference | AST.IntrinsicTypeReference {
let node: ts.Node = unresolvedType.symbol.declarations[0];
while (node.kind !== ts.SyntaxKind.SourceFile) {
node = node.parent;
}
var sourceFile = <ts.SourceFile>node;
const sourceFile = node as ts.SourceFile;
var moduleName = this._moduleNameFromFileName(sourceFile.fileName);
var module = this.modules[moduleName];
var result = module.members[unresolvedType.symbol.name];
if (result === undefined) {
throw new Error(`Type ${ unresolvedType.symbol.name } could not be resolved.`);
if (sourceFile.fileName.substr(-"globals.d.ts".length) === "globals.d.ts") {
return new AST.IntrinsicTypeReference(unresolvedType.symbol.name);
}
else {
const moduleName = this._moduleNameFromFileName(sourceFile.fileName);
const module = this.modules[moduleName];
while (result instanceof AST.Reference) {
result = this.modules[(<AST.Reference>result).moduleName].members[result.name];
}
let result = module.members[unresolvedType.symbol.name];
var resultGenerics = unresolvedType.generics.map(generic => {
if (generic instanceof AST.UnresolvedType) {
return this._resolveTypeReference(generic);
if (result === undefined) {
throw new Error(`Type ${unresolvedType.symbol.name} could not be resolved.`);
}
return <AST.IntrinsicTypeReference>generic;
});
while (result instanceof AST.Reference) {
result = this.modules[result.moduleName].members[result.name];
}
return new AST.TypeReference(<AST.NamespaceMember><any>result, resultGenerics);
const resultGenerics = unresolvedType.generics.map(generic => {
if (generic instanceof AST.UnresolvedType) {
return this._resolveTypeReference(generic);
}
return generic;
});
return new AST.TypeReference(result, resultGenerics);
}
}
private _moduleNameFromFileName(fileName: string): string {
var result = ts.normalizeSlashes(path.relative(this._compiler.projectRoot, fileName));
let result = ts.normalizeSlashes(path.relative(this._compiler.projectRoot, fileName));
result = result.substr(0, result.length - ".ts".length);
@@ -843,18 +863,16 @@ class Walker {
}
export function walk(compiler: Compiler, root: string, rootNamespaceName: string) {
var sourceFiles = compiler.sourceFiles;
var rootFileName = ts.normalizeSlashes(path.resolve(root));
var rootSourceFile = sourceFiles.filter(sourceFile => sourceFile.fileName === rootFileName)[0];
const sourceFiles = compiler.sourceFiles;
var walker = new Walker(compiler);
const walker = new Walker(compiler);
// Walk
for (const sourceFile of sourceFiles) {
if (
path.basename(sourceFile.fileName) === "lib.core.d.ts" ||
path.basename(sourceFile.fileName) === "lib.es5.d.ts" ||
path.basename(sourceFile.fileName) === "lib.dom.d.ts" ||
sourceFile.fileName.substr(-"references.d.ts".length) === "references.d.ts"
sourceFile.fileName.substr(-"globals.d.ts".length) === "globals.d.ts"
) {
continue;
}
+3 -1
View File
@@ -277,7 +277,9 @@ var Run = (function () {
source_map: this._rootSourceMap,
ascii_only: true,
beautify: true,
comments: true,
comments: function (node, comment) {
return comment.value.indexOf("tslint") === -1;
},
};
var stream = UglifyJS.OutputStream(output);
+5 -5
View File
@@ -17,7 +17,7 @@
"main": "lib/libjass.js",
"scripts": {
"prepublish": "node ./build.js clean default",
"build": "tsc ./build/typescript/index.ts ./build/doc.ts ./build/node.d.ts ./build/typescript/typescript.d.ts ./node_modules/async-build/typings.d.ts -m commonjs -t es5 -noImplicitAny --moduleResolution classic",
"build": "tsc -p ./build/tsconfig.json",
"test": "node ./build.js test",
"test-lib": "intern-client config=tests/intern reporters=Pretty",
"test-minified": "intern-client config=tests/intern reporters=Pretty minified=true",
@@ -26,12 +26,12 @@
},
"devDependencies": {
"async": "1.x >=1.4",
"async-build": "0.3.0",
"async-build": "0.3.1",
"intern": "3.x >=3.2.0",
"npm": "3.x",
"pngjs": "2.3.1",
"npm": "4.x",
"pngjs": "3.x",
"sax": "1.x",
"typescript": "1.8.10",
"typescript": "2.0.10",
"uglify-js": "2.x >=2.4.24"
},
"private": true
+163
View File
@@ -0,0 +1,163 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface Array<T> {
filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
}
interface WorkerGlobalScope {
postMessage(message: any): void;
addEventListener(type: string, listener: (message: any) => void, useCapture: boolean): void;
}
interface FontFace {
family: string;
load(): Promise<FontFace>;
}
interface FontFaceSet {
add(fontFace: FontFace): FontFaceSet;
forEach(callbackfn: (fontFace: FontFace, index: FontFace, set: FontFaceSet) => void, thisArg?: any): void;
}
interface Map<K, V> {
size: number;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
delete(key: K): boolean;
clear(): void;
forEach(callbackfn: (value: V, index: K, map: this) => void, thisArg?: any): void;
}
interface Node {
cloneNode(deep?: boolean): this;
}
interface Promise<T> extends Thenable<T> {
then<U>(onFulfilled: (value: T) => Thenable<U>, onRejected?: (reason: any) => U | Thenable<U>): Promise<U>;
/* tslint:disable-next-line:unified-signatures */
then<U>(onFulfilled: (value: T) => U, onRejected?: (reason: any) => U | Thenable<U>): Promise<U>;
catch(onRejected: (reason: any) => T | Thenable<T>): Promise<T>;
}
interface ReadableStream {
getReader(): ReadableStreamReader;
}
interface ReadableStreamReader {
read(): Promise<{ value: Uint8Array; done: boolean; }>;
}
interface Set<T> {
size: number;
add(value: T): this;
clear(): void;
has(value: T): boolean;
forEach(callbackfn: (value: T, index: T, set: this) => void, thisArg?: any): void;
}
interface SVGFEComponentTransferElement {
appendChild(newChild: SVGFEFuncAElement): SVGFEFuncAElement;
appendChild(newChild: SVGFEFuncBElement): SVGFEFuncBElement;
appendChild(newChild: SVGFEFuncGElement): SVGFEFuncGElement;
appendChild(newChild: SVGFEFuncRElement): SVGFEFuncRElement;
}
interface SVGFEMergeElement {
appendChild(newChild: SVGFEMergeNodeElement): SVGFEMergeNodeElement;
}
interface TextDecoder {
decode(input: ArrayBuffer | ArrayBufferView, options: { stream: boolean }): string;
}
interface Thenable<T> {
then: ThenableThen<T>;
}
type ThenableThen<T> = (this: Thenable<T>, resolve: ((resolution: T | Thenable<T>) => void) | undefined, reject: ((reason: any) => void) | undefined) => void;
/**
* The interface implemented by a communication channel to the other side.
*/
interface WorkerCommunication {
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
postMessage(message: any): void;
}
declare const exports: any;
declare const global: (WorkerGlobalScope) & {
FontFace?: {
new (family: string, source: string): FontFace;
};
Map?: {
new <K, V>(iterable?: [K, V][]): Map<K, V>;
/* tslint:disable-next-line:member-ordering */
prototype: Map<any, any> | { forEach: undefined };
};
MutationObserver?: typeof MutationObserver;
Promise?: {
new <T>(init: (resolve: (value: T | Thenable<T>) => void, reject: (reason: any) => void) => void): Promise<T>;
/* tslint:disable-next-line:member-ordering */
prototype: Promise<any>;
resolve<T>(value: T | Thenable<T>): Promise<T>;
reject<T>(reason: any): Promise<T>;
all<T>(values: (T | Thenable<T>)[]): Promise<T[]>;
race<T>(values: (T | Thenable<T>)[]): Promise<T>;
};
ReadableStream?: {
prototype: ReadableStream | { getReader: undefined; };
};
Set?: {
new <T>(iterable?: T[]): Set<T>;
/* tslint:disable-next-line:member-ordering */
prototype: Set<any> | { forEach: undefined };
};
TextDecoder?: { new (encoding: string, options: { ignoreBOM: boolean }): TextDecoder };
WebkitMutationObserver?: typeof MutationObserver;
Worker?: typeof Worker,
WorkerGlobalScope?: {
prototype: WorkerGlobalScope;
new (): WorkerGlobalScope;
};
document?: {
currentScript?: HTMLScriptElement;
fonts?: FontFaceSet;
};
fetch?(url: string): Promise<{ body: ReadableStream; ok?: boolean; status?: number; }>;
process?: {
nextTick?(callback: () => void): void;
}
};
+8 -10
View File
@@ -67,33 +67,31 @@ export { version } from "./version";
export function configure(newConfig: {
debugMode?: boolean,
verboseMode?: boolean,
Set?: typeof set.Set,
Map?: typeof map.Map,
Promise?: typeof promise.Promise,
Set?: typeof set.Set | null,
Map?: typeof map.Map | null,
Promise?: typeof promise.Promise | null,
}): void {
if ("debugMode" in newConfig) {
if (typeof newConfig.debugMode === "boolean") {
settings.setDebugMode(newConfig.debugMode);
}
if ("verboseMode" in newConfig) {
if (typeof newConfig.verboseMode === "boolean") {
settings.setVerboseMode(newConfig.verboseMode);
}
if ("Set" in newConfig) {
if (typeof newConfig.Set === "function" || newConfig.Set === null) {
set.setImplementation(newConfig.Set);
}
if ("Map" in newConfig) {
if (typeof newConfig.Map === "function" || newConfig.Map === null) {
map.setImplementation(newConfig.Map);
}
if ("Promise" in newConfig) {
if (typeof newConfig.Promise === "function" || newConfig.Promise === null) {
promise.setImplementation(newConfig.Promise);
}
}
declare const exports: any;
// Getters below are to work around https://github.com/Microsoft/TypeScript/issues/6366
Object.defineProperties(exports, {
+2 -2
View File
@@ -28,7 +28,7 @@ import { Map } from "../utility/map";
* @param {string} line
* @return {Property}
*/
export function parseLineIntoProperty(line: string): Property {
export function parseLineIntoProperty(line: string): Property | null {
const colonPos = line.indexOf(":");
if (colonPos === -1) {
return null;
@@ -47,7 +47,7 @@ export function parseLineIntoProperty(line: string): Property {
* @param {!Array.<string>} formatSpecifier
* @return {TypedTemplate}
*/
export function parseLineIntoTypedTemplate(line: string, formatSpecifier: string[]): TypedTemplate {
export function parseLineIntoTypedTemplate(line: string, formatSpecifier: string[]): TypedTemplate | null {
const property = parseLineIntoProperty(line);
if (property === null) {
return null;
+281 -267
View File
File diff suppressed because it is too large Load Diff
+16 -11
View File
@@ -21,13 +21,13 @@
import { debugMode } from "../settings";
import { ASS } from "../types/ass";
import { Style } from "../types/style";
import { Dialogue } from "../types/dialogue";
import { Attachment, AttachmentType } from "../types/attachment";
import { Dialogue } from "../types/dialogue";
import { Style } from "../types/style";
import { Map } from "../utility/map";
import { Promise, DeferredPromise } from "../utility/promise";
import { DeferredPromise } from "../utility/promise";
import { parseLineIntoProperty } from "./misc";
import { Stream } from "./streams";
@@ -54,9 +54,10 @@ export class StreamParser {
private _shouldSwallowBom: boolean = true;
private _currentSection: Section = Section.ScriptInfo;
private _currentAttachment: Attachment = null;
private _currentAttachment: Attachment | null = null;
constructor(private _stream: Stream) {
/* tslint:disable-next-line:no-floating-promises */
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
this._minimalDeferred.reject(reason);
this._deferred.reject(reason);
@@ -101,6 +102,7 @@ export class StreamParser {
if (value === Section.EOF) {
const scriptProperties = this._ass.properties;
/* tslint:disable-next-line:strict-type-predicates */
if (scriptProperties.resolutionX === undefined || scriptProperties.resolutionY === undefined) {
// Malformed script.
this._minimalDeferred.reject("Malformed ASS script.");
@@ -118,7 +120,7 @@ export class StreamParser {
/**
* @param {string} line
*/
private _onNextLine(line: string): void {
private _onNextLine(line: string | null): void {
if (line === null) {
this.currentSection = Section.EOF;
return;
@@ -272,6 +274,7 @@ export class StreamParser {
}
}
/* tslint:disable-next-line:no-floating-promises */
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
this._minimalDeferred.reject(reason);
this._deferred.reject(reason);
@@ -290,12 +293,13 @@ export class SrtStreamParser {
private _shouldSwallowBom: boolean = true;
private _currentDialogueNumber: string = null;
private _currentDialogueStart: string = null;
private _currentDialogueEnd: string = null;
private _currentDialogueText: string = null;
private _currentDialogueNumber: string | null = null;
private _currentDialogueStart: string | null = null;
private _currentDialogueEnd: string | null = null;
private _currentDialogueText: string | null = null;
constructor(private _stream: Stream) {
/* tslint:disable-next-line:no-floating-promises */
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
this._deferred.reject(reason);
});
@@ -319,7 +323,7 @@ export class SrtStreamParser {
/**
* @param {string} line
*/
private _onNextLine(line: string): void {
private _onNextLine(line: string | null): void {
if (line === null) {
if (this._currentDialogueNumber !== null && this._currentDialogueStart !== null && this._currentDialogueEnd !== null && this._currentDialogueText !== null) {
this._ass.dialogues.push(new Dialogue(new Map([
@@ -379,7 +383,7 @@ export class SrtStreamParser {
.replace(/<\/u>/g, "{\\u0}").replace(/\{\/u\}/g, "{\\u0}")
.replace(
/<font color="#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})">/g,
(/* ujs:unreferenced */ substring: string, red: string, green: string, blue: string) => `{\c&H${ blue }${ green }${ red }&}`
(/* ujs:unreferenced */ _substring: string, red: string, green: string, blue: string) => `{\c&H${ blue }${ green }${ red }&}`,
).replace(/<\/font>/g, "{\\c}");
if (this._currentDialogueText !== null) {
@@ -391,6 +395,7 @@ export class SrtStreamParser {
}
}
/* tslint:disable-next-line:no-floating-promises */
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
this._deferred.reject(reason);
});
+29 -59
View File
@@ -18,45 +18,7 @@
* limitations under the License.
*/
import { Promise, DeferredPromise } from "../utility/promise";
export interface ReadableStream {
/**
* @return {!ReadableStreamReader}
*/
getReader(): ReadableStreamReader;
}
export interface ReadableStreamReader {
/**
* @return {!Promise.<{ value?: Uint8Array, done: boolean }>}
*/
read(): Promise<{ value: Uint8Array; done: boolean; }>;
}
export interface TextDecoder {
/**
* @param {!ArrayBuffer|!ArrayBufferView} input
* @param {{ stream: boolean }} options
* @return {string}
*/
decode(input: ArrayBuffer | ArrayBufferView, options: { stream: boolean }): string;
}
export interface TextDecoderConstructor {
new (encoding: string, options: { ignoreBOM: boolean }): TextDecoder;
/**
* @type {!TextDecoder}
*/
prototype: TextDecoder;
}
declare const global: {
/**
* @type {!TextDecoderConstructor}
*/
TextDecoder?: TextDecoderConstructor;
};
import { DeferredPromise, Promise } from "../utility/promise";
/**
* An interface for a stream.
@@ -65,7 +27,7 @@ export interface Stream {
/**
* @return {!Promise.<?string>} A promise that will be resolved with the next line, or null if the stream is exhausted.
*/
nextLine(): Promise<string>;
nextLine(): Promise<string | null>;
}
/**
@@ -81,8 +43,8 @@ export class StringStream implements Stream {
/**
* @return {!Promise.<?string>} A promise that will be resolved with the next line, or null if the string has been completely read.
*/
nextLine(): Promise<string> {
let result: Promise<string>;
nextLine(): Promise<string | null> {
let result: Promise<string | null>;
if (this._readTill < this._str.length) {
const nextNewLinePos = this._str.indexOf("\n", this._readTill);
@@ -96,7 +58,7 @@ export class StringStream implements Stream {
}
}
else {
result = Promise.resolve<string>(null);
result = Promise.resolve<string | null>(null);
}
return result;
@@ -111,8 +73,8 @@ export class StringStream implements Stream {
*/
export class XhrStream implements Stream {
private _readTill: number = 0;
private _pendingDeferred: DeferredPromise<string> = null;
private _failedError: ErrorEvent = null;
private _pendingDeferred: DeferredPromise<string | null> | null = null;
private _failedError: ErrorEvent | null = null;
constructor(private _xhr: XMLHttpRequest) {
_xhr.addEventListener("progress", () => this._onXhrProgress(), false);
@@ -181,7 +143,7 @@ export class XhrStream implements Stream {
*/
private _tryResolveNextLine(): void {
if (this._failedError !== null) {
this._pendingDeferred.reject(this._failedError);
this._pendingDeferred!.reject(this._failedError);
return;
}
@@ -189,23 +151,19 @@ export class XhrStream implements Stream {
const nextNewLinePos = response.indexOf("\n", this._readTill);
if (nextNewLinePos !== -1) {
this._pendingDeferred.resolve(response.substring(this._readTill, nextNewLinePos));
this._pendingDeferred!.resolve(response.substring(this._readTill, nextNewLinePos));
this._readTill = nextNewLinePos + 1;
this._pendingDeferred = null;
}
else if (this._xhr.readyState === XMLHttpRequest.DONE) {
if (this._failedError !== null) {
this._pendingDeferred.reject(this._failedError);
}
// No more data. This is the last line.
else if (this._readTill < response.length) {
this._pendingDeferred.resolve(response.substr(this._readTill));
if (this._readTill < response.length) {
this._pendingDeferred!.resolve(response.substr(this._readTill));
this._readTill = response.length;
}
else {
this._pendingDeferred.resolve(null);
this._pendingDeferred!.resolve(null);
}
this._pendingDeferred = null;
@@ -220,14 +178,25 @@ export class XhrStream implements Stream {
* @param {string} encoding
*/
export class BrowserReadableStream implements Stream {
/**
* @return {boolean} Whether BrowserReadableStream is supported in this environment.
*/
static isSupported(): boolean {
return (
global.ReadableStream !== undefined &&
typeof global.ReadableStream.prototype.getReader === "function" &&
typeof global.TextDecoder === "function"
);
}
private _reader: ReadableStreamReader;
private _decoder: TextDecoder;
private _buffer: string = "";
private _pendingDeferred: DeferredPromise<string> = null;
private _pendingDeferred: DeferredPromise<string | null> | null = null;
constructor(stream: ReadableStream, encoding: string) {
this._reader = stream.getReader();
this._decoder = new global.TextDecoder(encoding, { ignoreBOM: true });
this._decoder = new global.TextDecoder!(encoding, { ignoreBOM: true });
}
/**
@@ -250,12 +219,13 @@ export class BrowserReadableStream implements Stream {
private _tryResolveNextLine(): void {
const nextNewLinePos = this._buffer.indexOf("\n");
if (nextNewLinePos !== -1) {
this._pendingDeferred.resolve(this._buffer.substr(0, nextNewLinePos));
this._pendingDeferred!.resolve(this._buffer.substr(0, nextNewLinePos));
this._buffer = this._buffer.substr(nextNewLinePos + 1);
this._pendingDeferred = null;
}
else {
/* tslint:disable-next-line:no-floating-promises */
this._reader.read().then(next => {
const { value, done } = next;
@@ -266,10 +236,10 @@ export class BrowserReadableStream implements Stream {
else {
// No more data.
if (this._buffer.length === 0) {
this._pendingDeferred.resolve(null);
this._pendingDeferred!.resolve(null);
}
else {
this._pendingDeferred.resolve(this._buffer);
this._pendingDeferred!.resolve(this._buffer);
this._buffer = "";
}
+19 -15
View File
@@ -37,19 +37,22 @@ const fieldDecorators = new Map<DataType, (proto: any, field: string) => void>()
@struct
class OffsetTable {
/** @type {function(!{ dataView: DataView, position: number }): OffsetTable} */
static read: (reader: DataReader) => OffsetTable;
/** @type {number} */ @field(DataType.Uint16) majorVersion: number;
/** @type {number} */ @field(DataType.Uint16) minorVersion: number;
/** @type {number} */ @field(DataType.Uint16) numTables: number;
/** @type {number} */ @field(DataType.Uint16) searchRange: number;
/** @type {number} */ @field(DataType.Uint16) entrySelector: number;
/** @type {number} */ @field(DataType.Uint16) rangeShift: number;
/** @type {function(!{ dataView: DataView, position: number }): OffsetTable} */
static read: (reader: DataReader) => OffsetTable;
}
@struct
class TableRecord {
/** @type {function(!{ dataView: DataView, position: number }): TableRecord} */
static read: (reader: DataReader) => TableRecord;
/** @type {string} */ @field(DataType.Char) c1: string;
/** @type {string} */ @field(DataType.Char) c2: string;
/** @type {string} */ @field(DataType.Char) c3: string;
@@ -57,32 +60,29 @@ class TableRecord {
/** @type {number} */ @field(DataType.Uint32) checksum: number;
/** @type {number} */ @field(DataType.Uint32) offset: number;
/** @type {number} */ @field(DataType.Uint32) length: number;
/** @type {function(!{ dataView: DataView, position: number }): TableRecord} */
static read: (reader: DataReader) => TableRecord;
}
@struct
class NameTableHeader {
/** @type {function(!{ dataView: DataView, position: number }): NameTableHeader} */
static read: (reader: DataReader) => NameTableHeader;
/** @type {number} */ @field(DataType.Uint16) formatSelector: number;
/** @type {number} */ @field(DataType.Uint16) count: number;
/** @type {number} */ @field(DataType.Uint16) stringOffset: number;
/** @type {function(!{ dataView: DataView, position: number }): NameTableHeader} */
static read: (reader: DataReader) => NameTableHeader;
}
@struct
class NameRecord {
/** @type {function(!{ dataView: DataView, position: number }): NameRecord} */
static read: (reader: DataReader) => NameRecord;
/** @type {number} */ @field(DataType.Uint16) platformId: number;
/** @type {number} */ @field(DataType.Uint16) encodingId: number;
/** @type {number} */ @field(DataType.Uint16) languageId: number;
/** @type {number} */ @field(DataType.Uint16) nameId: number;
/** @type {number} */ @field(DataType.Uint16) length: number;
/** @type {number} */ @field(DataType.Uint16) offset: number;
/** @type {function(!{ dataView: DataView, position: number }): NameRecord} */
static read: (reader: DataReader) => NameRecord;
}
/**
@@ -103,7 +103,7 @@ export function getTtfNames(attachment: Attachment): Set<string> {
const reader = { dataView: new DataView(bytes.buffer), position: 0 };
const offsetTable = OffsetTable.read(reader);
let nameTableRecord: TableRecord = null;
let nameTableRecord: TableRecord | null = null;
for (let i = 0; i < offsetTable.numTables; i++) {
const tableRecord = TableRecord.read(reader);
if (tableRecord.c1 + tableRecord.c2 + tableRecord.c3 + tableRecord.c4 === "name") {
@@ -133,24 +133,28 @@ export function getTtfNames(attachment: Attachment): Set<string> {
case 1: {
let name = "";
/* tslint:disable-next-line:prefer-for-of */
for (let j = 0; j < nameBytes.length; j++) {
name += String.fromCharCode(nameBytes[j]);
}
result.add(name);
}
break;
}
case 3: {
let name = "";
for (let j = 0; j < nameBytes.length; j += 2) {
/* tslint:disable-next-line:no-bitwise */
name += String.fromCharCode((nameBytes[j] << 8) + nameBytes[j + 1]);
}
result.add(name);
}
break;
}
}
break;
+83 -88
View File
@@ -77,11 +77,7 @@ export class Color {
* @return {!libjass.parts.Color} Returns a new Color instance with the same color but the provided alpha.
*/
withAlpha(value: number): Color {
if (value !== null) {
return new Color(this._red, this._green, this._blue, value);
}
return this;
return new Color(this._red, this._green, this._blue, value);
}
/**
@@ -103,7 +99,7 @@ export class Color {
this._red + progression * (final.red - this._red),
this._green + progression * (final.green - this._green),
this._blue + progression * (final.blue - this._blue),
this._alpha + progression * (final.alpha - this._alpha)
this._alpha + progression * (final.alpha - this._alpha),
);
}
}
@@ -162,20 +158,26 @@ export class Text {
export class NewLine {
}
/**
* A soft newline character \n.
*/
export class SoftNewLine {
}
/**
* An italic tag {\i}
*
* @param {?boolean} value {\i1} -> true, {\i0} -> false, {\i} -> null
*/
export class Italic {
constructor(private _value: boolean) { }
constructor(private _value: boolean | null) { }
/**
* The value of this italic tag.
*
* @type {?boolean}
*/
get value(): boolean {
get value(): boolean | null {
return this._value;
}
}
@@ -186,14 +188,14 @@ export class Italic {
* @param {?boolean|?number} value {\b1} -> true, {\b0} -> false, {\b###} -> weight of the bold (number), {\b} -> null
*/
export class Bold {
constructor(private _value: boolean | number) { }
constructor(private _value: boolean | number | null) { }
/**
* The value of this bold tag.
*
* @type {?boolean|?number}
*/
get value(): boolean | number {
get value(): boolean | number | null {
return this._value;
}
}
@@ -204,14 +206,14 @@ export class Bold {
* @param {?boolean} value {\u1} -> true, {\u0} -> false, {\u} -> null
*/
export class Underline {
constructor(private _value: boolean) { }
constructor(private _value: boolean | null) { }
/**
* The value of this underline tag.
*
* @type {?boolean}
*/
get value(): boolean {
get value(): boolean | null {
return this._value;
}
}
@@ -222,14 +224,14 @@ export class Underline {
* @param {?boolean} value {\s1} -> true, {\s0} -> false, {\s} -> null
*/
export class StrikeThrough {
constructor(private _value: boolean) { }
constructor(private _value: boolean | null) { }
/**
* The value of this strike-through tag.
*
* @type {?boolean}
*/
get value(): boolean {
get value(): boolean | null {
return this._value;
}
}
@@ -240,14 +242,14 @@ export class StrikeThrough {
* @param {?number} value {\bord###} -> width (number), {\bord} -> null
*/
export class Border {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this border tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -258,14 +260,14 @@ export class Border {
* @param {?number} value {\xbord###} -> width (number), {\xbord} -> null
*/
export class BorderX {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this horizontal border tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -276,14 +278,14 @@ export class BorderX {
* @param {?number} value {\ybord###} -> height (number), {\ybord} -> null
*/
export class BorderY {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this vertical border tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -294,14 +296,14 @@ export class BorderY {
* @param {?number} value {\shad###} -> depth (number), {\shad} -> null
*/
export class Shadow {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this shadow tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -312,14 +314,14 @@ export class Shadow {
* @param {?number} value {\xshad###} -> depth (number), {\xshad} -> null
*/
export class ShadowX {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this horizontal shadow tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -330,14 +332,14 @@ export class ShadowX {
* @param {?number} value {\yshad###} -> depth (number), {\yshad} -> null
*/
export class ShadowY {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this vertical shadow tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -348,14 +350,14 @@ export class ShadowY {
* @param {?number} value {\be###} -> strength (number), {\be} -> null
*/
export class Blur {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this blur tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -366,14 +368,14 @@ export class Blur {
* @param {?number} value {\blur###} -> strength (number), {\blur} -> null
*/
export class GaussianBlur {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this Gaussian blur tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -384,14 +386,14 @@ export class GaussianBlur {
* @param {?string} value {\fn###} -> name (string), {\fn} -> null
*/
export class FontName {
constructor(private _value: string) { }
constructor(private _value: string | null) { }
/**
* The value of this font name tag.
*
* @type {?string}
*/
get value(): string {
get value(): string | null {
return this._value;
}
}
@@ -402,14 +404,14 @@ export class FontName {
* @param {?number} value {\fs###} -> size (number), {\fs} -> null
*/
export class FontSize {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this font size tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -456,14 +458,14 @@ export class FontSizeMinus {
* @param {?number} value {\fscx###} -> scale (number), {\fscx} -> null
*/
export class FontScaleX {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this horizontal font scaling tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -474,14 +476,14 @@ export class FontScaleX {
* @param {?number} value {\fscy###} -> scale (number), {\fscy} -> null
*/
export class FontScaleY {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this vertical font scaling tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -492,14 +494,14 @@ export class FontScaleY {
* @param {?number} value {\fsp###} -> spacing (number), {\fsp} -> null
*/
export class LetterSpacing {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this letter-spacing tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -510,14 +512,14 @@ export class LetterSpacing {
* @param {?number} value {\frx###} -> angle (number), {\frx} -> null
*/
export class RotateX {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this X-axis rotation tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -528,14 +530,14 @@ export class RotateX {
* @param {?number} value {\fry###} -> angle (number), {\fry} -> null
*/
export class RotateY {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this Y-axis rotation tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -546,14 +548,14 @@ export class RotateY {
* @param {?number} value {\frz###} -> angle (number), {\frz} -> null
*/
export class RotateZ {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this Z-axis rotation tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -564,14 +566,14 @@ export class RotateZ {
* @param {?number} value {\fax###} -> angle (number), {\fax} -> null
*/
export class SkewX {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this X-axis shearing tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -582,14 +584,14 @@ export class SkewX {
* @param {?number} value {\fay###} -> angle (number), {\fay} -> null
*/
export class SkewY {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this Y-axis shearing tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -600,14 +602,14 @@ export class SkewY {
* @param {libjass.parts.Color} value {\1c###} -> color (Color), {\1c} -> null
*/
export class PrimaryColor {
constructor(private _value: Color) { }
constructor(private _value: Color | null) { }
/**
* The value of this primary color tag.
*
* @type {libjass.parts.Color}
*/
get value(): Color {
get value(): Color | null {
return this._value;
}
}
@@ -618,14 +620,14 @@ export class PrimaryColor {
* @param {libjass.parts.Color} value {\2c###} -> color (Color), {\2c} -> null
*/
export class SecondaryColor {
constructor(private _value: Color) { }
constructor(private _value: Color | null) { }
/**
* The value of this secondary color tag.
*
* @type {libjass.parts.Color}
*/
get value(): Color {
get value(): Color | null {
return this._value;
}
}
@@ -636,14 +638,14 @@ export class SecondaryColor {
* @param {libjass.parts.Color} value {\3c###} -> color (Color), {\3c} -> null
*/
export class OutlineColor {
constructor(private _value: Color) { }
constructor(private _value: Color | null) { }
/**
* The value of this outline color tag.
*
* @type {libjass.parts.Color}
*/
get value(): Color {
get value(): Color | null {
return this._value;
}
}
@@ -654,14 +656,14 @@ export class OutlineColor {
* @param {libjass.parts.Color} value {\4c###} -> color (Color), {\4c} -> null
*/
export class ShadowColor {
constructor(private _value: Color) { }
constructor(private _value: Color | null) { }
/**
* The value of this shadow color tag.
*
* @type {libjass.parts.Color}
*/
get value(): Color {
get value(): Color | null {
return this._value;
}
}
@@ -672,14 +674,14 @@ export class ShadowColor {
* @param {?number} value {\alpha###} -> alpha (number), {\alpha} -> null
*/
export class Alpha {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this alpha tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -690,14 +692,14 @@ export class Alpha {
* @param {?number} value {\1a###} -> alpha (number), {\1a} -> null
*/
export class PrimaryAlpha {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this primary alpha tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -708,14 +710,14 @@ export class PrimaryAlpha {
* @param {?number} value {\2a###} -> alpha (number), {\2a} -> null
*/
export class SecondaryAlpha {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this secondary alpha tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -726,14 +728,14 @@ export class SecondaryAlpha {
* @param {?number} value {\3a###} -> alpha (number), {\3a} -> null
*/
export class OutlineAlpha {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this outline alpha tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -744,14 +746,14 @@ export class OutlineAlpha {
* @param {?number} value {\4a###} -> alpha (number), {\4a} -> null
*/
export class ShadowAlpha {
constructor(private _value: number) { }
constructor(private _value: number | null) { }
/**
* The value of this shadow alpha tag.
*
* @type {?number}
*/
get value(): number {
get value(): number | null {
return this._value;
}
}
@@ -852,14 +854,14 @@ export class WrappingStyle {
* @param {?string} value {\r###} -> style name (string), {\r} -> null
*/
export class Reset {
constructor(private _value: string) { }
constructor(private _value: string | null) { }
/**
* The value of this style reset tag.
*
* @type {?string}
*/
get value(): string {
get value(): string | null {
return this._value;
}
}
@@ -903,7 +905,7 @@ export class Position {
* @param {?number} t2
*/
export class Move {
constructor(private _x1: number, private _y1: number, private _x2: number, private _y2: number, private _t1: number, private _t2: number) { }
constructor(private _x1: number, private _y1: number, private _x2: number, private _y2: number, private _t1: number | null, private _t2: number | null) { }
/**
* The starting x value of this move tag.
@@ -946,7 +948,7 @@ export class Move {
*
* @type {?number}
*/
get t1(): number {
get t1(): number | null {
return this._t1;
}
@@ -955,7 +957,7 @@ export class Move {
*
* @type {?number}
*/
get t2(): number {
get t2(): number | null {
return this._t2;
}
}
@@ -1030,7 +1032,7 @@ export class Fade {
export class ComplexFade {
constructor(
private _a1: number, private _a2: number, private _a3: number,
private _t1: number, private _t2: number, private _t3: number, private _t4: number
private _t1: number, private _t2: number, private _t3: number, private _t4: number,
) { }
/**
@@ -1106,14 +1108,14 @@ export class ComplexFade {
* @param {!Array.<!libjass.parts.Tag>} tags
*/
export class Transform {
constructor(private _start: number, private _end: number, private _accel: number, private _tags: Part[]) { }
constructor(private _start: number | null, private _end: number | null, private _accel: number | null, private _tags: Part[]) { }
/**
* The starting time of this transform tag.
*
* @type {?number}
*/
get start(): number {
get start(): number | null {
return this._start;
}
@@ -1122,7 +1124,7 @@ export class Transform {
*
* @type {?number}
*/
get end(): number {
get end(): number | null {
return this._end;
}
@@ -1131,7 +1133,7 @@ export class Transform {
*
* @type {?number}
*/
get accel(): number {
get accel(): number | null {
return this._accel;
}
@@ -1295,25 +1297,18 @@ export class DrawingInstructions {
}
}
const addToString = function (ctor: Function, ctorName: string) {
const addToString = function (ctor: Function, ctorName: string): void {
if (!ctor.prototype.hasOwnProperty("toString")) {
const propertyNames = Object.getOwnPropertyNames(ctor.prototype).filter(property => property !== "constructor");
ctor.prototype.toString = function () {
return (
ctorName + " { " +
propertyNames.map(name => `${ name }: ${ (this as any)[name] }`).join(", ") +
((propertyNames.length > 0) ? " " : "") +
"}"
);
ctor.prototype.toString = function (this: any): string {
return `${ ctorName } { ${ propertyNames.map(name => `${ name }: ${ this[name] }`).join(", ") }${ (propertyNames.length > 0) ? " " : "" }}`;
};
}
};
import { registerClass } from "../serialization";
declare const exports: any;
for (const key of Object.keys(exports)) {
const value: any = exports[key];
if (value instanceof Function) {
+5 -5
View File
@@ -41,10 +41,10 @@ import { ManualClock } from "./manual";
export class AutoClock implements Clock {
private _manualClock: ManualClock = new ManualClock();
private _nextAnimationFrameRequestId: number = null;
private _nextAnimationFrameRequestId: number | null = null;
private _lastKnownExternalTime: number = null;
private _lastKnownExternalTimeObtainedAt: number = null;
private _lastKnownExternalTime: number | null = null;
private _lastKnownExternalTimeObtainedAt: number = 0;
constructor(private _getCurrentTime: () => number, private _autoPauseAfter: number) { }
@@ -193,7 +193,7 @@ export class AutoClock implements Clock {
*/
addEventListener(type: ClockEvent, listener: Function): void {
this._manualClock.addEventListener(type, listener);
};
}
/**
* @param {number} timeStamp
@@ -213,7 +213,7 @@ export class AutoClock implements Clock {
if (!this._manualClock.paused) {
if (this._lastKnownExternalTime !== null && currentExternalTime === this._lastKnownExternalTime) {
if (timeStamp - this._lastKnownExternalTimeObtainedAt > this._autoPauseAfter) {
this._lastKnownExternalTimeObtainedAt = null;
this._lastKnownExternalTimeObtainedAt = 0;
this._manualClock.seek(currentExternalTime);
}
else {
-2
View File
@@ -18,8 +18,6 @@
* limitations under the License.
*/
import { Map } from "../../utility/map";
/**
* A mixin class that represents an event source.
*/
+5 -1
View File
@@ -18,8 +18,8 @@
* limitations under the License.
*/
import { mixin } from "../../utility/mixin";
import { Map } from "../../utility/map";
import { mixin } from "../../utility/mixin";
import { Clock, ClockEvent, EventSource } from "./base";
@@ -226,6 +226,8 @@ export class ManualClock implements Clock, EventSource<ClockEvent> {
}
}
/* tslint:disable:member-ordering */
// EventSource members
/**
@@ -242,5 +244,7 @@ export class ManualClock implements Clock, EventSource<ClockEvent> {
* @type {function(number, Array.<*>)}
*/
_dispatchEvent: (type: ClockEvent, args: Object[]) => void;
/* tslint:enable:member-ordering */
}
mixin(ManualClock, [EventSource]);
+1 -1
View File
@@ -35,7 +35,7 @@ export class DefaultRenderer extends WebRenderer {
constructor(private _video: HTMLVideoElement, ass: ASS, settings?: RendererSettings) {
super(ass, new VideoClock(_video), document.createElement("div"), settings);
this._video.parentElement.replaceChild(this.libjassSubsWrapper, this._video);
this._video.parentElement!.replaceChild(this.libjassSubsWrapper, this._video);
this.libjassSubsWrapper.insertBefore(this._video, this.libjassSubsWrapper.firstElementChild);
}
+7 -7
View File
@@ -18,15 +18,15 @@
* limitations under the License.
*/
import { Clock, ClockEvent } from "./clocks/base";
import { RendererSettings } from "./settings";
import { debugMode, verboseMode } from "../settings";
import { ASS } from "../types/ass";
import { Dialogue } from "../types/dialogue";
import { Clock, ClockEvent } from "./clocks/base";
import { RendererSettings } from "./settings";
/**
* A renderer implementation that doesn't output anything.
*
@@ -35,7 +35,7 @@ import { Dialogue } from "../types/dialogue";
* @param {libjass.renderers.RendererSettings} settings
*/
export class NullRenderer {
private static _lastRendererId = -1;
private static _lastRendererId: number = -1;
private _id: number;
@@ -88,14 +88,14 @@ export class NullRenderer {
*
* @param {!libjass.Dialogue} dialogue
*/
preRender(dialogue: Dialogue): void { }
preRender(_dialogue: Dialogue): void { }
/**
* Draw a dialogue. This is a no-op for this type.
*
* @param {!libjass.Dialogue} dialogue
*/
draw(dialogue: Dialogue): void { }
draw(_dialogue: Dialogue): void { }
/**
* Enable the renderer.
+76 -75
View File
@@ -25,6 +25,78 @@ import { Map } from "../utility/map";
* Settings for the renderer.
*/
export class RendererSettings {
/**
* A convenience method to create a font map from a <style> or <link> element that contains @font-face rules. There should be one @font-face rule for each font name, mapping to a font file URL.
*
* For example:
*
* @font-face {
* font-family: "Helvetica";
* src: url("/fonts/helvetica.ttf"), local("Arial");
* }
*
* More complicated @font-face syntax like format() or multi-line src are not supported.
*
* @param {!LinkStyle} linkStyle
* @return {!Map.<string, string>}
*/
static makeFontMapFromStyleElement(linkStyle: LinkStyle): Map<string, string> {
const fontMap = new Map<string, string>();
const styleSheet = linkStyle.sheet as CSSStyleSheet;
/* tslint:disable-next-line:prefer-for-of */
for (let i = 0; i < styleSheet.cssRules.length; i++) {
const rule = styleSheet.cssRules[i];
if (isFontFaceRule(rule)) {
const name = rule.style.getPropertyValue("font-family").match(/^["']?(.*?)["']?$/)![1];
let src = rule.style.getPropertyValue("src");
if (!src) {
src = rule.cssText.split("\n")
.map(line => line.match(/src:\s*([^;]+?)\s*;/))
.filter((matches): matches is RegExpMatchArray => matches !== null)
.map(matches => matches[1])[0];
}
fontMap.set(name, src);
}
}
return fontMap;
}
/**
* Converts an arbitrary object into a {@link libjass.renderers.RendererSettings} object.
*
* @param {*} object
* @return {!libjass.renderers.RendererSettings}
*/
static from(object?: any): RendererSettings {
if (object === undefined || object === null) {
object = {};
}
const {
fontMap = null,
preRenderTime = 5,
preciseOutlines = false,
enableSvg = testSupportsSvg(),
fallbackFonts = 'Arial, Helvetica, sans-serif, "Segoe UI Symbol"',
useAttachedFonts = false,
} = object as RendererSettings;
const result = new RendererSettings();
result.fontMap = fontMap;
result.preRenderTime = preRenderTime;
result.preciseOutlines = preciseOutlines;
result.enableSvg = enableSvg;
result.fallbackFonts = fallbackFonts;
result.useAttachedFonts = useAttachedFonts;
return result;
}
/**
* A map of font name to one or more URLs of that font. If provided, the fonts in this map are pre-loaded by the WebRenderer when it's created.
*
@@ -45,7 +117,7 @@ export class RendererSettings {
*
* @type {Map.<string, (string|!Array.<string>)>}
*/
fontMap: Map<string, string | string[]>;
fontMap: Map<string, string | string[]> | null;
/**
* Subtitles will be pre-rendered for this amount of time (seconds).
@@ -97,77 +169,6 @@ export class RendererSettings {
* @type {boolean}
*/
useAttachedFonts: boolean;
/**
* A convenience method to create a font map from a <style> or <link> element that contains @font-face rules. There should be one @font-face rule for each font name, mapping to a font file URL.
*
* For example:
*
* @font-face {
* font-family: "Helvetica";
* src: url("/fonts/helvetica.ttf"), local("Arial");
* }
*
* More complicated @font-face syntax like format() or multi-line src are not supported.
*
* @param {!LinkStyle} linkStyle
* @return {!Map.<string, string>}
*/
static makeFontMapFromStyleElement(linkStyle: LinkStyle): Map<string, string> {
const fontMap = new Map<string, string>();
const styleSheet = linkStyle.sheet as CSSStyleSheet;
for (let i = 0; i < styleSheet.cssRules.length; i++) {
const rule = styleSheet.cssRules[i];
if (isFontFaceRule(rule)) {
const name = rule.style.getPropertyValue("font-family").match(/^["']?(.*?)["']?$/)[1];
let src = rule.style.getPropertyValue("src");
if (!src) {
src = rule.cssText.split("\n")
.map(line => line.match(/src:\s*([^;]+?)\s*;/))
.filter(matches => matches !== null)
.map(matches => matches[1])[0];
}
fontMap.set(name, src);
}
}
return fontMap;
}
/**
* Converts an arbitrary object into a {@link libjass.renderers.RendererSettings} object.
*
* @param {*} object
* @return {!libjass.renderers.RendererSettings}
*/
static from(object?: any): RendererSettings {
if (object === undefined || object === null) {
object = {};
}
const {
fontMap = null,
preRenderTime = 5,
preciseOutlines = false,
enableSvg = testSupportsSvg(),
fallbackFonts = 'Arial, Helvetica, sans-serif, "Segoe UI Symbol"',
useAttachedFonts = false,
} = object as RendererSettings;
const result = new RendererSettings();
result.fontMap = fontMap;
result.preRenderTime = preRenderTime;
result.preciseOutlines = preciseOutlines;
result.enableSvg = enableSvg;
result.fallbackFonts = fallbackFonts;
result.useAttachedFonts = useAttachedFonts;
return result;
}
}
/**
@@ -188,7 +189,7 @@ function testSupportsSvg(): boolean {
console.log("Testing whether SVG filter effects are supported.");
}
if (typeof document === "undefined") {
if (global.document === undefined) {
if (debugMode) {
console.log("This doesn't look like a browser. Assuming it doesn't support SVG filter effects.");
}
@@ -198,7 +199,7 @@ function testSupportsSvg(): boolean {
const morphologyFilter = document.createElementNS("http://www.w3.org/2000/svg", "feMorphology");
// https://connect.microsoft.com/IE/feedback/details/2375800
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6618301/
try {
morphologyFilter.radiusX.baseVal = 1;
}
@@ -221,7 +222,7 @@ function testSupportsSvg(): boolean {
return false;
}
// https://connect.microsoft.com/IE/feedback/details/2375757
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6618454/
morphologyFilter.setAttribute("radius", "1");
if (morphologyFilter.cloneNode().getAttribute("radius") !== "1") {
if (debugMode) {
+6 -6
View File
@@ -71,12 +71,8 @@ export class AnimationCollection {
* @param {!Array.<!libjass.renderers.Keyframe>} keyframes
*/
add(timingFunction: string, keyframes: Keyframe[]): void {
if (keyframes.length < 1) {
throw new Error("Atleast one keyframe must be provided.");
}
let start: number = null;
let end: number = null;
let start: number | null = null;
let end: number | null = null;
for (const keyframe of keyframes) {
if (start === null) {
@@ -86,6 +82,10 @@ export class AnimationCollection {
end = keyframe.time;
}
if (start === null || end === null) {
throw new Error("Atleast one keyframe must be provided.");
}
let ruleCssText = "";
for (const keyframe of keyframes) {
+3 -6
View File
@@ -18,7 +18,6 @@
* limitations under the License.
*/
import { Map } from "../../utility/map";
import { Promise } from "../../utility/promise";
/**
@@ -47,7 +46,7 @@ function prepareFontSizeElement(fontFamily: string, fontSize: number, fallbackFo
function lineHeightForFontSize(fontFamily: string, fontSize: number, fallbackFonts: string, fontSizeElement: HTMLDivElement): Promise<number> {
prepareFontSizeElement(fontFamily, fontSize, fallbackFonts, fontSizeElement);
return new Promise(resolve => setTimeout(() => resolve(fontSizeElement.offsetHeight), 1000));
return new Promise<number>(resolve => setTimeout(() => resolve(fontSizeElement.offsetHeight), 1000));
}
/**
@@ -78,14 +77,12 @@ function fontMetricsFromLineHeights(lowerLineHeight: number, upperLineHeight: nu
* @param {string} fontFamily
* @param {string} fallbackFonts
* @param {!HTMLDivElement} fontSizeElement
* @return {!Promise.<number>}
* @return {!Promise.<[number, number]>}
*/
export function calculateFontMetrics(fontFamily: string, fallbackFonts: string, fontSizeElement: HTMLDivElement): Promise<[number, number]> {
return lineHeightForFontSize(fontFamily, 180, fallbackFonts, fontSizeElement).then(lowerLineHeight =>
lineHeightForFontSize(fontFamily, 360, fallbackFonts, fontSizeElement).then(upperLineHeight =>
fontMetricsFromLineHeights(lowerLineHeight, upperLineHeight)
)
);
fontMetricsFromLineHeights(lowerLineHeight, upperLineHeight)));
}
/**
-2
View File
@@ -18,8 +18,6 @@
* limitations under the License.
*/
import { Map } from "../../utility/map";
/**
* This class represents a single keyframe. It has a list of CSS properties (names and values) associated with a point in time. Multiple keyframes make up an animation.
*
+150 -166
View File
@@ -18,17 +18,6 @@
* limitations under the License.
*/
import { AnimationCollection } from "./animation-collection";
import { DrawingStyles } from "./drawing-styles";
import { calculateFontMetrics } from "./font-size";
import { Keyframe } from "./keyframe";
import { SpanStyles } from "./span-styles";
import { Clock, EventSource } from "../clocks/base";
import { NullRenderer } from "../null";
import { RendererSettings } from "../settings";
import { getTtfNames } from "../../parser/ttf";
import * as parts from "../../parts";
@@ -40,44 +29,20 @@ import { AttachmentType } from "../../types/attachment";
import { Dialogue } from "../../types/dialogue";
import { WrappingStyle } from "../../types/misc";
import { mixin } from "../../utility/mixin";
import { Map } from "../../utility/map";
import { Promise, any as Promise_any, first as Promise_first, lastly as Promise_finally } from "../../utility/promise";
import { Set } from "../../utility/set";
import { mixin } from "../../utility/mixin";
import { any as Promise_any, first as Promise_first, lastly as Promise_finally, Promise } from "../../utility/promise";
declare const global: {
document: {
fonts?: FontFaceSet;
};
};
import { Clock, EventSource } from "../clocks/base";
interface FontFaceSet {
/**
* @param {!FontFace} fontFace
* @return {!FontFaceSet}
*/
add(fontFace: FontFace): FontFaceSet;
import { NullRenderer } from "../null";
import { RendererSettings } from "../settings";
/**
* @param {function(!FontFace, !FontFace, !FontFaceSet)} callbackfn A function that is called with each value in the set.
* @param {*} thisArg
*/
forEach(callbackfn: (fontFace: FontFace, index: FontFace, set: FontFaceSet) => void, thisArg?: any): void;
}
interface FontFace {
/** @type {string} */
family: string;
/**
* @return {!Promise.<!FontFace>}
*/
load(): Promise<FontFace>;
}
declare var FontFace: {
new (family: string, source: string): FontFace;
};
import { AnimationCollection } from "./animation-collection";
import { DrawingStyles } from "./drawing-styles";
import { calculateFontMetrics } from "./font-size";
import { Keyframe } from "./keyframe";
import { SpanStyles } from "./span-styles";
const fontSrcUrlRegex = /^(url|local)\(["']?(.+?)["']?\)$/;
@@ -92,11 +57,18 @@ const fontSrcUrlRegex = /^(url|local)\(["']?(.+?)["']?\)$/;
* @param {!libjass.renderers.RendererSettings} settings
*/
export class WebRenderer extends NullRenderer implements EventSource<string> {
private static _transformOrigins: number[][] = [
[],
[0, 100], [50, 100], [100, 100],
[0, 50], [50, 50], [100, 50],
[0, 0], [50, 0], [100, 0],
];
private _subsWrapper: HTMLDivElement;
private _subsWrapperWidth: number; // this._subsWrapper.offsetWidth is expensive, so cache this.
private _layerWrappers: HTMLDivElement[] = [];
private _layerAlignmentWrappers: HTMLDivElement[][] = [];
private _layerWrappers: (HTMLDivElement | undefined)[] = [];
private _layerAlignmentWrappers: (HTMLDivElement | undefined)[][] = [];
private _fontSizeElement: HTMLDivElement;
private _fontMetricsCache: Map<string, [number, number]> = new Map<string, [number, number]>();
@@ -161,7 +133,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
const attachmentUrl = `data:application/x-font-ttf;base64,${ attachment.contents }`;
ttfNames.forEach(name => {
let correspondingFontMapEntry = fontMap.get(name);
const correspondingFontMapEntry = fontMap.get(name);
if (correspondingFontMapEntry !== undefined) {
// Also defined in fontMap.
if (typeof correspondingFontMapEntry !== "string") {
@@ -191,7 +163,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
fontMap.forEach((srcs, fontFamily) => {
let fontFamilyMetricsPromise: Promise<[number, number]>;
if (global.document.fonts && global.document.fonts.add) {
if (global.document && global.document.fonts && global.document.fonts!.add) {
// value should be string. If it's string[], combine it into string
let source =
(typeof srcs === "string") ?
@@ -208,17 +180,17 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
}
}
let existingFontFaces: FontFace[] = [];
const existingFontFaces: FontFace[] = [];
global.document.fonts.forEach(fontFace => {
if (fontFace.family === fontFamily || fontFace.family === `"${ fontFamily }"`) {
existingFontFaces.push(fontFace);
}
});
let fontFetchPromise: Promise<FontFace>;
let fontFetchPromise: Promise<FontFace | null>;
if (existingFontFaces.length === 0) {
const fontFace = new FontFace(fontFamily, source);
const quotedFontFace = new FontFace(`"${ fontFamily }"`, source);
const fontFace = new global.FontFace!(fontFamily, source);
const quotedFontFace = new global.FontFace!(`"${ fontFamily }"`, source);
global.document.fonts.add(fontFace);
global.document.fonts.add(quotedFontFace);
@@ -254,7 +226,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
// A url() URL. Extract the raw URL.
return match[2];
}).filter(url => url !== null);
}).filter((url): url is string => url !== null);
const attachedFontUrls = attachedFontsMap.get(fontFamily);
if (attachedFontUrls !== undefined) {
@@ -266,7 +238,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
let fontFetchPromise = fontFetchPromisesCache.get(url);
if (fontFetchPromise === undefined) {
fontFetchPromise =
new Promise<void>((resolve, reject) => {
new Promise<null>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", () => {
if (debugMode) {
@@ -290,7 +262,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
const allFontsFetchedPromise =
(thisFontFamilysFetchPromises.length === 0) ?
Promise.resolve<void>(null) :
Promise.resolve(null) :
Promise_first(thisFontFamilysFetchPromises).catch(reason => {
console.warn(`Fetching fonts for ${ fontFamily } at ${ urls.join(", ") } failed: %o`, reason);
return null;
@@ -302,6 +274,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
preloadFontPromises.push(fontFamilyMetricsPromise.then(metrics => this._fontMetricsCache.set(fontFamily, metrics)));
});
/* tslint:disable-next-line:no-floating-promises */
Promise.all(preloadFontPromises).then(() => {
if (debugMode) {
console.log("All fonts have been preloaded.");
@@ -354,7 +327,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
* @param {!libjass.Dialogue} dialogue
* @return {PreRenderedSub}
*/
preRender(dialogue: Dialogue): PreRenderedSub {
preRender(dialogue: Dialogue): PreRenderedSub | null {
const currentTimeRelativeToDialogueStart = this.clock.currentTime - dialogue.start;
if (dialogue.containsTransformTag && currentTimeRelativeToDialogueStart < 0) {
@@ -389,15 +362,15 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
const svgDefsElement = document.createElementNS("http://www.w3.org/2000/svg", "defs");
svgElement.appendChild(svgDefsElement);
let currentSpan: HTMLSpanElement = null;
let currentSpan: HTMLSpanElement | null = null;
const currentSpanStyles = new SpanStyles(this, dialogue, this._scaleX, this._scaleY, this.settings, this._fontSizeElement, svgDefsElement, this._fontMetricsCache);
let currentAnimationCollection: AnimationCollection = null;
let currentAnimationCollection: AnimationCollection | null = null;
let previousAddNewLine = false; // If two or more \N's are encountered in sequence, then all but the first will be created using currentSpanStyles.makeNewLine() instead
const startNewSpan = (addNewLine: boolean): void => {
if (currentSpan !== null && currentSpan.hasChildNodes()) {
sub.appendChild(currentSpanStyles.setStylesOnSpan(currentSpan, currentAnimationCollection));
sub.appendChild(currentSpanStyles.setStylesOnSpan(currentSpan, currentAnimationCollection!));
}
if (currentAnimationCollection !== null) {
@@ -428,7 +401,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
for (const part of dialogue.parts) {
if (part instanceof parts.Italic) {
currentSpanStyles.italic = part.value;
currentSpanStyles.italic = part.value as boolean;
}
else if (part instanceof parts.Bold) {
@@ -436,45 +409,45 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
}
else if (part instanceof parts.Underline) {
currentSpanStyles.underline = part.value;
currentSpanStyles.underline = part.value as boolean;
}
else if (part instanceof parts.StrikeThrough) {
currentSpanStyles.strikeThrough = part.value;
currentSpanStyles.strikeThrough = part.value as boolean;
}
else if (part instanceof parts.Border) {
currentSpanStyles.outlineWidth = part.value;
currentSpanStyles.outlineHeight = part.value;
currentSpanStyles.outlineWidth = part.value as number;
currentSpanStyles.outlineHeight = part.value as number;
}
else if (part instanceof parts.BorderX) {
currentSpanStyles.outlineWidth = part.value;
currentSpanStyles.outlineWidth = part.value as number;
}
else if (part instanceof parts.BorderY) {
currentSpanStyles.outlineHeight = part.value;
currentSpanStyles.outlineHeight = part.value as number;
}
else if (part instanceof parts.Shadow) {
currentSpanStyles.shadowDepthX = part.value;
currentSpanStyles.shadowDepthY = part.value;
currentSpanStyles.shadowDepthX = part.value as number;
currentSpanStyles.shadowDepthY = part.value as number;
}
else if (part instanceof parts.ShadowX) {
currentSpanStyles.shadowDepthX = part.value;
currentSpanStyles.shadowDepthX = part.value as number;
}
else if (part instanceof parts.ShadowY) {
currentSpanStyles.shadowDepthY = part.value;
currentSpanStyles.shadowDepthY = part.value as number;
}
else if (part instanceof parts.Blur) {
currentSpanStyles.blur = part.value;
currentSpanStyles.blur = part.value as number;
}
else if (part instanceof parts.GaussianBlur) {
currentSpanStyles.gaussianBlur = part.value;
currentSpanStyles.gaussianBlur = part.value as number;
}
else if (part instanceof parts.FontName) {
@@ -482,7 +455,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
}
else if (part instanceof parts.FontSize) {
currentSpanStyles.fontSize = part.value;
currentSpanStyles.fontSize = part.value as number;
}
else if (part instanceof parts.FontSizePlus) {
@@ -494,74 +467,74 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
}
else if (part instanceof parts.FontScaleX) {
currentSpanStyles.fontScaleX = part.value;
currentSpanStyles.fontScaleX = part.value as number;
}
else if (part instanceof parts.FontScaleY) {
currentSpanStyles.fontScaleY = part.value;
currentSpanStyles.fontScaleY = part.value as number;
}
else if (part instanceof parts.LetterSpacing) {
currentSpanStyles.letterSpacing = part.value;
currentSpanStyles.letterSpacing = part.value as number;
}
else if (part instanceof parts.RotateX) {
currentSpanStyles.rotationX = part.value;
currentSpanStyles.rotationX = part.value as number;
}
else if (part instanceof parts.RotateY) {
currentSpanStyles.rotationY = part.value;
currentSpanStyles.rotationY = part.value as number;
}
else if (part instanceof parts.RotateZ) {
currentSpanStyles.rotationZ = part.value;
currentSpanStyles.rotationZ = part.value as number;
}
else if (part instanceof parts.SkewX) {
currentSpanStyles.skewX = part.value;
currentSpanStyles.skewX = part.value as number;
}
else if (part instanceof parts.SkewY) {
currentSpanStyles.skewY = part.value;
currentSpanStyles.skewY = part.value as number;
}
else if (part instanceof parts.PrimaryColor) {
currentSpanStyles.primaryColor = part.value;
currentSpanStyles.primaryColor = part.value as parts.Color;
}
else if (part instanceof parts.SecondaryColor) {
currentSpanStyles.secondaryColor = part.value;
currentSpanStyles.secondaryColor = part.value as parts.Color;
}
else if (part instanceof parts.OutlineColor) {
currentSpanStyles.outlineColor = part.value;
currentSpanStyles.outlineColor = part.value as parts.Color;
}
else if (part instanceof parts.ShadowColor) {
currentSpanStyles.shadowColor = part.value;
currentSpanStyles.shadowColor = part.value as parts.Color;
}
else if (part instanceof parts.Alpha) {
currentSpanStyles.primaryAlpha = part.value;
currentSpanStyles.secondaryAlpha = part.value;
currentSpanStyles.outlineAlpha = part.value;
currentSpanStyles.shadowAlpha = part.value;
currentSpanStyles.primaryAlpha = part.value as number;
currentSpanStyles.secondaryAlpha = part.value as number;
currentSpanStyles.outlineAlpha = part.value as number;
currentSpanStyles.shadowAlpha = part.value as number;
}
else if (part instanceof parts.PrimaryAlpha) {
currentSpanStyles.primaryAlpha = part.value;
currentSpanStyles.primaryAlpha = part.value as number;
}
else if (part instanceof parts.SecondaryAlpha) {
currentSpanStyles.secondaryAlpha = part.value;
currentSpanStyles.secondaryAlpha = part.value as number;
}
else if (part instanceof parts.OutlineAlpha) {
currentSpanStyles.outlineAlpha = part.value;
currentSpanStyles.outlineAlpha = part.value as number;
}
else if (part instanceof parts.ShadowAlpha) {
currentSpanStyles.shadowAlpha = part.value;
currentSpanStyles.shadowAlpha = part.value as number;
}
else if (part instanceof parts.Alignment) {
@@ -571,12 +544,12 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
else if (part instanceof parts.ColorKaraoke) {
startNewSpan(false);
currentAnimationCollection.add("step-end", [
currentAnimationCollection!.add("step-end", [
new Keyframe(0, new Map([
["color", currentSpanStyles.secondaryColor.withAlpha(currentSpanStyles.secondaryAlpha).toString()],
])), new Keyframe(karaokeTimesAccumulator, new Map([
["color", currentSpanStyles.primaryColor.withAlpha(currentSpanStyles.primaryAlpha).toString()],
]))
])),
]);
karaokeTimesAccumulator += part.duration;
@@ -607,10 +580,10 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
dialogueAnimationCollection.add("linear", [new Keyframe(0, new Map([
["left", `${ (this._scaleX * part.x1).toFixed(3) }px`],
["top", `${ (this._scaleY * part.y1).toFixed(3) }px`],
])), new Keyframe(part.t1, new Map([
])), new Keyframe(part.t1!, new Map([
["left", `${ (this._scaleX * part.x1).toFixed(3) }px`],
["top", `${ (this._scaleY * part.y1).toFixed(3) }px`],
])), new Keyframe(part.t2, new Map([
])), new Keyframe(part.t2!, new Map([
["left", `${ (this._scaleX * part.x2).toFixed(3) }px`],
["top", `${ (this._scaleY * part.y2).toFixed(3) }px`],
])), new Keyframe(dialogue.end - dialogue.start, new Map([
@@ -620,15 +593,23 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
}
else if (part instanceof parts.Fade) {
dialogueAnimationCollection.add("linear", [new Keyframe(0, new Map([
["opacity", "0"],
])), new Keyframe(part.start, new Map([
const keyframes: Keyframe[] = [];
if (part.start !== 0) {
keyframes.push(new Keyframe(0, new Map([
["opacity", "0"],
])));
}
keyframes.push(new Keyframe(part.start, new Map([
["opacity", "1"],
])), new Keyframe(dialogue.end - dialogue.start - part.end, new Map([
["opacity", "1"],
])), new Keyframe(dialogue.end - dialogue.start, new Map([
["opacity", "0"],
]))]);
])));
if (part.end !== 0) {
keyframes.push(new Keyframe(dialogue.end - dialogue.start, new Map([
["opacity", "0"],
])));
}
dialogueAnimationCollection.add("linear", keyframes);
}
else if (part instanceof parts.ComplexFade) {
@@ -649,9 +630,9 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
else if (part instanceof parts.Transform) {
const progression =
(currentTimeRelativeToDialogueStart <= part.start) ? 0 :
(currentTimeRelativeToDialogueStart >= part.end) ? 1 :
Math.pow((currentTimeRelativeToDialogueStart - part.start) / (part.end - part.start), part.accel);
(currentTimeRelativeToDialogueStart <= part.start!) ? 0 :
(currentTimeRelativeToDialogueStart >= part.end!) ? 1 :
Math.pow((currentTimeRelativeToDialogueStart - part.start!) / (part.end! - part.start!), part.accel!);
for (const tag of part.tags) {
if (tag instanceof parts.Border) {
@@ -660,8 +641,8 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.outlineHeight += progression * (tag.value - currentSpanStyles.outlineHeight);
}
else {
currentSpanStyles.outlineWidth = null;
currentSpanStyles.outlineHeight = null;
currentSpanStyles.outlineWidth = null as any as number;
currentSpanStyles.outlineHeight = null as any as number;
}
}
@@ -670,7 +651,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.outlineWidth += progression * (tag.value - currentSpanStyles.outlineWidth);
}
else {
currentSpanStyles.outlineWidth = null;
currentSpanStyles.outlineWidth = null as any as number;
}
}
@@ -679,7 +660,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.outlineHeight += progression * (tag.value - currentSpanStyles.outlineHeight);
}
else {
currentSpanStyles.outlineHeight = null;
currentSpanStyles.outlineHeight = null as any as number;
}
}
@@ -689,8 +670,8 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.shadowDepthY += progression * (tag.value - currentSpanStyles.shadowDepthY);
}
else {
currentSpanStyles.shadowDepthX = null;
currentSpanStyles.shadowDepthY = null;
currentSpanStyles.shadowDepthX = null as any as number;
currentSpanStyles.shadowDepthY = null as any as number;
}
}
@@ -699,7 +680,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.shadowDepthX += progression * (tag.value - currentSpanStyles.shadowDepthX);
}
else {
currentSpanStyles.shadowDepthX = null;
currentSpanStyles.shadowDepthX = null as any as number;
}
}
@@ -708,7 +689,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.shadowDepthY += progression * (tag.value - currentSpanStyles.shadowDepthY);
}
else {
currentSpanStyles.shadowDepthY = null;
currentSpanStyles.shadowDepthY = null as any as number;
}
}
@@ -717,7 +698,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.blur += progression * (tag.value - currentSpanStyles.blur);
}
else {
currentSpanStyles.blur = null;
currentSpanStyles.blur = null as any as number;
}
}
@@ -726,7 +707,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.gaussianBlur += progression * (tag.value - currentSpanStyles.gaussianBlur);
}
else {
currentSpanStyles.gaussianBlur = null;
currentSpanStyles.gaussianBlur = null as any as number;
}
}
@@ -735,7 +716,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.fontSize += progression * (tag.value - currentSpanStyles.fontSize);
}
else {
currentSpanStyles.fontSize = null;
currentSpanStyles.fontSize = null as any as number;
}
}
@@ -752,7 +733,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.fontScaleX += progression * (tag.value - currentSpanStyles.fontScaleX);
}
else {
currentSpanStyles.fontScaleX = null;
currentSpanStyles.fontScaleX = null as any as number;
}
}
@@ -761,7 +742,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.fontScaleY += progression * (tag.value - currentSpanStyles.fontScaleY);
}
else {
currentSpanStyles.fontScaleY = null;
currentSpanStyles.fontScaleY = null as any as number;
}
}
@@ -770,7 +751,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.letterSpacing += progression * (tag.value - currentSpanStyles.letterSpacing);
}
else {
currentSpanStyles.letterSpacing = null;
currentSpanStyles.letterSpacing = null as any as number;
}
}
@@ -779,7 +760,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.rotationX += progression * (tag.value - currentSpanStyles.rotationX);
}
else {
currentSpanStyles.rotationX = null;
currentSpanStyles.rotationX = null as any as number;
}
}
@@ -788,7 +769,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.rotationY += progression * (tag.value - currentSpanStyles.rotationY);
}
else {
currentSpanStyles.rotationY = null;
currentSpanStyles.rotationY = null as any as number;
}
}
@@ -797,7 +778,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.rotationZ += progression * (tag.value - currentSpanStyles.rotationZ);
}
else {
currentSpanStyles.rotationZ = null;
currentSpanStyles.rotationZ = null as any as number;
}
}
@@ -806,7 +787,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.skewX += progression * (tag.value - currentSpanStyles.skewX);
}
else {
currentSpanStyles.skewX = null;
currentSpanStyles.skewX = null as any as number;
}
}
@@ -815,7 +796,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.skewY += progression * (tag.value - currentSpanStyles.skewY);
}
else {
currentSpanStyles.skewY = null;
currentSpanStyles.skewY = null as any as number;
}
}
@@ -824,7 +805,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.primaryColor = currentSpanStyles.primaryColor.interpolate(tag.value, progression);
}
else {
currentSpanStyles.primaryColor = null;
currentSpanStyles.primaryColor = null as any as parts.Color;
}
}
@@ -833,7 +814,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.secondaryColor = currentSpanStyles.secondaryColor.interpolate(tag.value, progression);
}
else {
currentSpanStyles.secondaryColor = null;
currentSpanStyles.secondaryColor = null as any as parts.Color;
}
}
@@ -842,7 +823,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.outlineColor = currentSpanStyles.outlineColor.interpolate(tag.value, progression);
}
else {
currentSpanStyles.outlineColor = null;
currentSpanStyles.outlineColor = null as any as parts.Color;
}
}
@@ -851,7 +832,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.shadowColor = currentSpanStyles.shadowColor.interpolate(tag.value, progression);
}
else {
currentSpanStyles.shadowColor = null;
currentSpanStyles.shadowColor = null as any as parts.Color;
}
}
@@ -863,10 +844,10 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.shadowAlpha += progression * (tag.value - currentSpanStyles.shadowAlpha);
}
else {
currentSpanStyles.primaryAlpha = null;
currentSpanStyles.secondaryAlpha = null;
currentSpanStyles.outlineAlpha = null;
currentSpanStyles.shadowAlpha = null;
currentSpanStyles.primaryAlpha = null as any as number;
currentSpanStyles.secondaryAlpha = null as any as number;
currentSpanStyles.outlineAlpha = null as any as number;
currentSpanStyles.shadowAlpha = null as any as number;
}
}
@@ -875,7 +856,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.primaryAlpha += progression * (tag.value - currentSpanStyles.primaryAlpha);
}
else {
currentSpanStyles.primaryAlpha = null;
currentSpanStyles.primaryAlpha = null as any as number;
}
}
@@ -884,7 +865,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.secondaryAlpha += progression * (tag.value - currentSpanStyles.secondaryAlpha);
}
else {
currentSpanStyles.secondaryAlpha = null;
currentSpanStyles.secondaryAlpha = null as any as number;
}
}
@@ -893,7 +874,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.outlineAlpha += progression * (tag.value - currentSpanStyles.outlineAlpha);
}
else {
currentSpanStyles.outlineAlpha = null;
currentSpanStyles.outlineAlpha = null as any as number;
}
}
@@ -902,7 +883,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
currentSpanStyles.shadowAlpha += progression * (tag.value - currentSpanStyles.shadowAlpha);
}
else {
currentSpanStyles.shadowAlpha = null;
currentSpanStyles.shadowAlpha = null as any as number;
}
}
}
@@ -919,23 +900,32 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
}
else if (part instanceof parts.DrawingInstructions) {
currentSpan.appendChild(currentDrawingStyles.toSVG(part, currentSpanStyles.primaryColor.withAlpha(currentSpanStyles.primaryAlpha)));
currentSpan!.appendChild(currentDrawingStyles.toSVG(part, currentSpanStyles.primaryColor.withAlpha(currentSpanStyles.primaryAlpha)));
startNewSpan(false);
}
else if (part instanceof parts.Text) {
currentSpan.appendChild(document.createTextNode(part.value + "\u200C"));
currentSpan!.appendChild(document.createTextNode(part.value + "\u200C"));
startNewSpan(false);
}
else if (debugMode && part instanceof parts.Comment) {
currentSpan.appendChild(document.createTextNode(part.value));
currentSpan!.appendChild(document.createTextNode(part.value));
startNewSpan(false);
}
else if (part instanceof parts.NewLine) {
startNewSpan(true);
}
else if (part instanceof parts.SoftNewLine) {
if (wrappingStyle === WrappingStyle.NoLineWrapping) {
startNewSpan(true);
}
else {
currentSpan!.appendChild(document.createTextNode(" "));
}
}
}
let divTransformStyle = "";
@@ -1029,16 +1019,18 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
console.log(dialogue.toString());
}
let preRenderedSub = this._preRenderedSubs.get(dialogue.id);
let thePreRenderedSub = this._preRenderedSubs.get(dialogue.id);
if (preRenderedSub === undefined) {
preRenderedSub = this.preRender(dialogue);
if (thePreRenderedSub === undefined) {
thePreRenderedSub = this.preRender(dialogue)!;
if (debugMode) {
console.log(dialogue.toString());
}
}
const preRenderedSub = thePreRenderedSub;
const result = preRenderedSub.sub.cloneNode(true);
const applyAnimationDelays = (node: HTMLElement) => {
@@ -1046,7 +1038,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
if (animationNames !== "") {
const animationDelays = animationNames.split(",").map(name => {
name = name.trim();
const delay = preRenderedSub.animationDelays.get(name);
const delay = preRenderedSub.animationDelays.get(name)!;
return `${ ((delay + dialogue.start - this.clock.currentTime) / this.clock.rate).toFixed(3) }s`;
}).join(", ");
@@ -1056,6 +1048,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
};
applyAnimationDelays(result);
const animatedDescendants = result.querySelectorAll('[style*="animation:"]');
/* tslint:disable-next-line:prefer-for-of */
for (let i = 0; i < animatedDescendants.length; i++) {
applyAnimationDelays(animatedDescendants[i] as HTMLElement);
}
@@ -1069,10 +1062,10 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
layerWrapper.className = `layer layer${ layer }`;
// Find the next greater layer div and insert this div before that one
let insertBeforeElement: HTMLDivElement = null;
let insertBeforeElement: HTMLDivElement | null = null;
for (let insertBeforeLayer = layer + 1; insertBeforeLayer < this._layerWrappers.length && insertBeforeElement === null; insertBeforeLayer++) {
if (this._layerWrappers[insertBeforeLayer] !== undefined) {
insertBeforeElement = this._layerWrappers[insertBeforeLayer];
insertBeforeElement = this._layerWrappers[insertBeforeLayer]!;
}
}
@@ -1088,11 +1081,11 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
layerAlignmentWrapper.className = `an an${ alignment }`;
// Find the next greater layer,alignment div and insert this div before that one
const layerWrapper = this._layerWrappers[layer];
let insertBeforeElement: HTMLDivElement = null;
const layerWrapper = this._layerWrappers[layer]!;
let insertBeforeElement: HTMLDivElement | null = null;
for (let insertBeforeAlignment = alignment + 1; insertBeforeAlignment < this._layerAlignmentWrappers[layer].length && insertBeforeElement === null; insertBeforeAlignment++) {
if (this._layerAlignmentWrappers[layer][insertBeforeAlignment] !== undefined) {
insertBeforeElement = this._layerAlignmentWrappers[layer][insertBeforeAlignment];
insertBeforeElement = this._layerAlignmentWrappers[layer][insertBeforeAlignment]!;
}
}
@@ -1110,10 +1103,11 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
// Workaround for IE
const dialogueAnimationStylesElement = result.getElementsByTagName("style")[0];
/* tslint:disable-next-line:strict-type-predicates */
if (dialogueAnimationStylesElement !== undefined) {
const sheet = dialogueAnimationStylesElement.sheet as CSSStyleSheet;
if (sheet.cssRules.length === 0) {
sheet.cssText = dialogueAnimationStylesElement.textContent;
sheet.cssText = dialogueAnimationStylesElement.textContent!;
}
}
@@ -1138,7 +1132,7 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
this._currentSubs.forEach((sub: HTMLDivElement, dialogue: Dialogue) => {
if (dialogue.start > currentTime || dialogue.end < currentTime || dialogue.containsTransformTag) {
this._currentSubs.delete(dialogue);
this._removeSub(sub);
sub.parentNode!.removeChild(sub);
}
});
@@ -1183,24 +1177,12 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
});
}
/**
* @param {!HTMLDivElement} sub
*/
private _removeSub(sub: HTMLDivElement): void {
sub.parentNode.removeChild(sub);
}
private _removeAllSubs(): void {
this._currentSubs.forEach((sub: HTMLDivElement) => this._removeSub(sub));
this._currentSubs.forEach((sub: HTMLDivElement) => sub.parentNode!.removeChild(sub));
this._currentSubs.clear();
}
private static _transformOrigins: number[][] = [
[],
[0, 100], [50, 100], [100, 100],
[0, 50], [50, 50], [100, 50],
[0, 0], [50, 0], [100, 0]
];
/* tslint:disable:member-ordering */
// EventSource members
@@ -1218,6 +1200,8 @@ export class WebRenderer extends NullRenderer implements EventSource<string> {
* @type {function(number, Array.<*>)}
*/
_dispatchEvent: (type: string, args: Object[]) => void;
/* tslint:enable:member-ordering */
}
mixin(WebRenderer, [EventSource]);
+33 -37
View File
@@ -18,20 +18,16 @@
* limitations under the License.
*/
import { AnimationCollection } from "./animation-collection";
import { Color } from "../../parts";
import { fontSizeForLineHeight } from "./font-size";
import { WebRenderer } from "./renderer";
import { Dialogue } from "../../types/dialogue";
import { Style } from "../../types/style";
import { RendererSettings } from "../settings";
import { Color } from "../../parts";
import { Style } from "../../types/style";
import { Dialogue } from "../../types/dialogue";
import { Map } from "../../utility/map";
import { AnimationCollection } from "./animation-collection";
import { fontSizeForLineHeight } from "./font-size";
import { WebRenderer } from "./renderer";
/**
* This class represents the style attribute of a span.
@@ -89,7 +85,7 @@ export class SpanStyles {
private _blur: number;
private _gaussianBlur: number;
private _nextFilterId = 0;
private _nextFilterId: number = 0;
constructor(renderer: WebRenderer, dialogue: Dialogue, private _scaleX: number, private _scaleY: number, private _settings: RendererSettings, private _fontSizeElement: HTMLDivElement, private _svgDefsElement: SVGDefsElement, private _fontMetricsCache: Map<string, [number, number]>) {
this._id = `${ renderer.id }-${ dialogue.id }`;
@@ -103,7 +99,7 @@ export class SpanStyles {
*
* @param {libjass.Style} newStyle The new defaults to reset the style to. If null, the styles are reset to the default style of the Dialogue.
*/
reset(newStyle: Style): void {
reset(newStyle: Style | undefined | null): void {
if (newStyle === undefined || newStyle === null) {
newStyle = this._defaultStyle;
}
@@ -144,8 +140,8 @@ export class SpanStyles {
this.outlineAlpha = newStyle.outlineColor.alpha;
this.shadowAlpha = newStyle.shadowColor.alpha;
this.blur = null;
this.gaussianBlur = null;
this.blur = null as any as number;
this.gaussianBlur = null as any as number;
}
/**
@@ -166,7 +162,7 @@ export class SpanStyles {
fontStyleOrWeight += "bold ";
}
else if (this._bold !== false) {
fontStyleOrWeight += this._bold + " ";
fontStyleOrWeight += this._bold.toFixed(0) + " ";
}
const lineHeight = this._scaleY * (isTextOnlySpan ? this._fontScaleX : 1) * this._fontSize;
@@ -257,14 +253,14 @@ export class SpanStyles {
this._svg(
span,
outlineWidth, outlineHeight, outlineColor,
shadowDepthX, shadowDepthY, shadowColor
shadowDepthX, shadowDepthY, shadowColor,
);
}
else {
this._textShadow(
span,
outlineWidth, outlineHeight, outlineColor,
shadowDepthX, shadowDepthY, shadowColor
shadowDepthX, shadowDepthY, shadowColor,
);
}
@@ -279,6 +275,15 @@ export class SpanStyles {
return span;
}
/**
* @return {!HTMLBRElement}
*/
makeNewLine(): HTMLBRElement {
const result = document.createElement("br");
result.style.lineHeight = `${ (this._scaleY * this._fontSize).toFixed(3) }px`;
return result;
}
/**
* @param {!HTMLSpanElement} span
* @param {number} outlineWidth
@@ -291,7 +296,7 @@ export class SpanStyles {
private _svg(
span: HTMLSpanElement,
outlineWidth: number, outlineHeight: number, outlineColor: Color,
shadowDepthX: number, shadowDepthY: number, shadowColor: Color
shadowDepthX: number, shadowDepthY: number, shadowColor: Color,
): void {
const filterElement = document.createElementNS("http://www.w3.org/2000/svg", "filter");
@@ -528,7 +533,7 @@ export class SpanStyles {
private _textShadow(
span: HTMLSpanElement,
outlineWidth: number, outlineHeight: number, outlineColor: Color,
shadowDepthX: number, shadowDepthY: number, shadowColor: Color
shadowDepthX: number, shadowDepthY: number, shadowColor: Color,
): void {
if (outlineWidth > 0 || outlineHeight > 0) {
let outlineCssString = "";
@@ -584,15 +589,6 @@ export class SpanStyles {
}
}
/**
* @return {!HTMLBRElement}
*/
makeNewLine(): HTMLBRElement {
const result = document.createElement("br");
result.style.lineHeight = `${ (this._scaleY * this._fontSize).toFixed(3) }px`;
return result;
}
/**
* Sets the italic property. null defaults it to the default style's value.
*
@@ -607,7 +603,7 @@ export class SpanStyles {
*
* @type {(?boolean|?number)}
*/
set bold(value: boolean | number) {
set bold(value: boolean | number | null) {
this._bold = valueOrDefault(value, this._defaultStyle.bold);
}
@@ -716,7 +712,7 @@ export class SpanStyles {
* @type {?number}
*/
set blur(value: number) {
this._blur = valueOrDefault(value, 0);
this._blur = valueOrDefault<number>(value, 0);
}
/**
@@ -734,7 +730,7 @@ export class SpanStyles {
* @type {?number}
*/
set gaussianBlur(value: number) {
this._gaussianBlur = valueOrDefault(value, 0);
this._gaussianBlur = valueOrDefault<number>(value, 0);
}
/**
@@ -742,7 +738,7 @@ export class SpanStyles {
*
* @type {?string}
*/
set fontName(value: string) {
set fontName(value: string | null) {
this._fontName = valueOrDefault(value, this._defaultStyle.fontName);
}
@@ -833,7 +829,7 @@ export class SpanStyles {
* @type {?number}
*/
set rotationX(value: number) {
this._rotationX = valueOrDefault(value, 0);
this._rotationX = valueOrDefault<number>(value, 0);
}
/**
@@ -851,7 +847,7 @@ export class SpanStyles {
* @type {?number}
*/
set rotationY(value: number) {
this._rotationY = valueOrDefault(value, 0);
this._rotationY = valueOrDefault<number>(value, 0);
}
/**
@@ -887,7 +883,7 @@ export class SpanStyles {
* @type {?number}
*/
set skewX(value: number) {
this._skewX = valueOrDefault(value, 0);
this._skewX = valueOrDefault<number>(value, 0);
}
/**
@@ -905,7 +901,7 @@ export class SpanStyles {
* @type {?number}
*/
set skewY(value: number) {
this._skewY = valueOrDefault(value, 0);
this._skewY = valueOrDefault<number>(value, 0);
}
/**
@@ -1092,6 +1088,6 @@ function createComponentTransferFilter(color: Color): SVGFEComponentTransferElem
* @param {!T} defaultValue
* @return {!T}
*/
function valueOrDefault<T>(newValue: T, defaultValue: T): T {
function valueOrDefault<T>(newValue: T | null, defaultValue: T): T {
return ((newValue !== null) ? newValue : defaultValue);
}
-34
View File
@@ -1,34 +0,0 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface Node {
cloneNode(deep?: boolean): this;
}
interface SVGFEComponentTransferElement {
appendChild(newChild: SVGFEFuncAElement): SVGFEFuncAElement;
appendChild(newChild: SVGFEFuncBElement): SVGFEFuncBElement;
appendChild(newChild: SVGFEFuncGElement): SVGFEFuncGElement;
appendChild(newChild: SVGFEFuncRElement): SVGFEFuncRElement;
}
interface SVGFEMergeElement {
appendChild(newChild: SVGFEMergeNodeElement): SVGFEMergeNodeElement;
}
+4 -4
View File
@@ -20,14 +20,14 @@
import { Map } from "./utility/map";
const classes = new Map<number, Function & { fromJSON?: (obj: any) => any }>();
const classes = new Map<number, Function & { fromJSON?(obj: any): any }>();
/**
* Registers a class as a serializable type.
*
* @param {function(new:*)} clazz
*/
export function registerClass(clazz: Function & { fromJSON?: (obj: any) => any }): void {
export function registerClass(clazz: Function & { fromJSON?(obj: any): any }): void {
clazz.prototype._classTag = classes.size;
classes.set(clazz.prototype._classTag, clazz);
}
@@ -39,7 +39,7 @@ export function registerClass(clazz: Function & { fromJSON?: (obj: any) => any }
* @return {string}
*/
export function serialize(obj: any): string {
return JSON.stringify(obj, (/* ujs:unreferenced */ key: string, value: any) => {
return JSON.stringify(obj, (/* ujs:unreferenced */ _key: string, value: any) => {
if (value && (value._classTag !== undefined) && !Object.prototype.hasOwnProperty.call(value, "_classTag")) {
// Copy the _classTag from this object's prototype to itself, so that it will be serialized.
value._classTag = value._classTag;
@@ -54,7 +54,7 @@ export function serialize(obj: any): string {
* @return {*}
*/
export function deserialize(str: string): any {
return JSON.parse(str, (/* ujs:unreferenced */ key: string, value: any) => {
return JSON.parse(str, (/* ujs:unreferenced */ _key: string, value: any) => {
if (value && (value._classTag !== undefined)) {
const clazz = classes.get(value._classTag);
if (clazz === undefined) {
+9 -1
View File
@@ -1,9 +1,16 @@
{
"compilerOptions": {
"lib": ["es5", "dom"],
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"strictNullChecks": true,
"target": "es5",
"module": "amd",
@@ -11,6 +18,7 @@
"outFile": "../lib/libjass.js",
"noImplicitUseStrict": true,
"sourceMap": true,
"inlineSources": true
"inlineSources": true,
"types": []
}
}
+164
View File
@@ -0,0 +1,164 @@
{
"$schema": "http://json.schemastore.org/tslint",
"rules": {
"adjacent-overload-signatures": true,
"ban-types": false,
"member-access": false,
"member-ordering": [true, { "order": [
"public-static-field",
"public-static-method",
"protected-static-field",
"protected-static-method",
"private-static-field",
"private-static-method",
"public-instance-field",
"protected-instance-field",
"private-instance-field",
"public-constructor",
"public-instance-method",
"protected-constructor",
"protected-instance-method",
"private-constructor",
"private-instance-method"
]}],
"no-any": false,
"no-empty-interface": false,
"no-import-side-effect": true,
"no-inferrable-types": false,
"no-internal-module": true,
"no-magic-numbers": false,
"no-namespace": true,
"no-non-null-assertion": false,
"no-reference": true,
"no-var-requires": true,
"only-arrow-functions": false,
"prefer-for-of": true,
"promise-function-async": false,
"typedef": [true, "call-signature", "parameter", "property-declaration", "member-variable-declaration"],
"typedef-whitespace": [true, {
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}, {
"call-signature": "space",
"index-signature": "space",
"parameter": "space",
"property-declaration": "space",
"variable-declaration": "space"
}],
"unified-signatures": true,
"await-promise": true,
"ban": false,
"curly": true,
"forin": true,
"import-blacklist": false,
"label-position": true,
"no-arg": true,
"no-bitwise": true,
"no-conditional-assignment": true,
"no-console": false,
"no-construct": true,
"no-debugger": true,
"no-duplicate-super": true,
"no-duplicate-variable": true,
"no-empty": false,
"no-eval": true,
"no-floating-promises": true,
"no-for-in-array": true,
"no-inferred-empty-object-type": true,
"no-invalid-template-strings": true,
"no-invalid-this": false,
"no-misused-new": true,
"no-null-keyword": false,
"no-shadowed-variable": false,
"no-sparse-arrays": true,
"no-string-literal": true,
"no-string-throw": true,
"no-switch-case-fall-through": true,
"no-unbound-method": false,
"no-unsafe-any": false,
"no-unsafe-finally": true,
"no-unused-expression": true,
"no-unused-variable": [true, "check-parameters"],
"no-use-before-declare": false,
"no-var-keyword": true,
"no-void-expression": [true, "ignore-arrow-function-shorthand"],
"radix": false,
"restrict-plus-operands": true,
"strict-boolean-expressions": false,
"strict-type-predicates": true,
"switch-default": false,
"triple-equals": true,
"typeof-compare": true,
"use-isnan": true,
"cyclomatic-complexity": false,
"eofline": true,
"indent": [true, "tabs"],
"linebreak-style": [true, "LF"],
"max-classes-per-file": false,
"max-file-line-count": false,
"max-line-length": false,
"no-default-export": true,
"no-mergeable-namespace": true,
"no-require-imports": true,
"object-literal-sort-keys": false,
"prefer-const": [true, { "destructuring": "all" }],
"trailing-comma": [true, { "multiline": "always", "singleline": "never" }],
"align": [true, "statements"],
"array-type": [true, "array"],
"arrow-parens": [true, "ban-single-arg-parens"],
"arrow-return-shorthand": true,
"callable-types": true,
"class-name": true,
"comment-format": [true, "check-space"],
"completed-docs": false,
"file-header": ["true", "Copyright \\d{4}"],
"import-spacing": true,
"interface-name": [true, "never-prefix"],
"interface-over-type-literal": false,
"jsdoc-format": true,
"match-default-export-name": true,
"newline-before-return": false,
"new-parens": true,
"no-angle-bracket-type-assertion": true,
"no-boolean-literal-compare": true,
"no-consecutive-blank-lines": true,
"no-parameter-properties": false,
"no-reference-import": true,
"no-trailing-whitespace": true,
"no-unnecessary-callback-wrapper": true,
"no-unnecessary-initializer": true,
"no-unnecessary-qualifier": true,
"object-literal-key-quotes": [true, "as-needed"],
"object-literal-shorthand": true,
"one-line": [true, "check-open-brace", "check-whitespace"],
"one-variable-per-declaration": true,
"ordered-imports": [true, { "import-sources-order": "case-insensitive", "named-imports-order": "case-insensitive" }],
"prefer-function-over-method": [true, "allow-public", "allow-protected"],
"prefer-method-signature": true,
"prefer-template": [true, "allow-single-concat"],
"quotemark": [true, "double", "avoid-escape"],
"return-undefined": true,
"space-before-function-paren": [true, {
"anonymous": "always",
"named": "never",
"asyncArrow": "always",
"method": "never",
"constructor": "never"
}],
"semicolon": [true, "always"],
"variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore"],
"whitespace": [true, "check-branch", "check-decl", "check-operator", "check-module", "check-separator", "check-type", "check-typecast", "check-preblock"]
}
}
+127 -138
View File
@@ -18,42 +18,139 @@
* limitations under the License.
*/
import { Attachment } from "./attachment";
import { Dialogue } from "./dialogue";
import { Style } from "./style";
import { ScriptProperties } from "./script-properties";
import { parseLineIntoTypedTemplate } from "../parser/misc";
import { SrtStreamParser, StreamParser } from "../parser/stream-parsers";
import { BrowserReadableStream, Stream, StringStream, XhrStream } from "../parser/streams";
import { Format } from "./misc";
import { registerClass as serializable } from "../serialization";
import { debugMode, verboseMode } from "../settings";
import * as parser from "../parser";
import { parseLineIntoTypedTemplate } from "../parser/misc";
import { ReadableStream, TextDecoderConstructor } from "../parser/streams";
import { Map } from "../utility/map";
import { Promise } from "../utility/promise";
import { registerClass as serializable } from "../serialization";
declare const global: {
fetch?(url: string): Promise<{ body: ReadableStream; ok?: boolean; status?: number; }>;
ReadableStream?: { prototype: ReadableStream; };
TextDecoder?: TextDecoderConstructor;
};
import { Attachment } from "./attachment";
import { Dialogue } from "./dialogue";
import { Format } from "./misc";
import { ScriptProperties } from "./script-properties";
import { Style } from "./style";
/**
* This class represents an ASS script. It contains the {@link libjass.ScriptProperties}, an array of {@link libjass.Style}s, and an array of {@link libjass.Dialogue}s.
*/
@serializable
export class ASS {
/**
* Creates an ASS object from the raw text of an ASS script.
*
* @param {string} raw The raw text of the script.
* @param {(number|string)=0} type The type of the script. One of the {@link libjass.Format} constants, or one of the strings "ass" and "srt".
* @return {!Promise.<!libjass.ASS>}
*/
static fromString(raw: string, type: Format | "ass" | "srt" = Format.ASS): Promise<ASS> {
return ASS.fromStream(new StringStream(raw), type);
}
/**
* Creates an ASS object from the given {@link libjass.parser.Stream}.
*
* @param {!libjass.parser.Stream} stream The stream to parse the script from
* @param {(number|string)=0} type The type of the script. One of the {@link libjass.Format} constants, or one of the strings "ass" and "srt".
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
*/
static fromStream(stream: Stream, type: Format | "ass" | "srt" = Format.ASS): Promise<ASS> {
switch (type) {
case Format.ASS:
case "ass":
return new StreamParser(stream).ass;
case Format.SRT:
case "srt":
return new SrtStreamParser(stream).ass;
default:
throw new Error(`Invalid value of type: ${ type }`);
}
}
/**
* Creates an ASS object from the given URL.
*
* @param {string} url The URL of the script.
* @param {(number|string)=0} type The type of the script. One of the {@link libjass.Format} constants, or one of the strings "ass" and "srt".
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
*/
static fromUrl(url: string, type: Format | "ass" | "srt" = Format.ASS): Promise<ASS> {
let fetchPromise: Promise<ASS>;
if (typeof global.fetch === "function" && BrowserReadableStream.isSupported()) {
fetchPromise = global.fetch(url).then(response => {
if (response.ok === false || (response.ok === undefined && (response.status === undefined || response.status < 200 || response.status > 299))) {
throw new Error(`HTTP request for ${ url } failed with status code ${ response.status }`);
}
return ASS.fromReadableStream(response.body, "utf-8", type);
});
}
else {
fetchPromise = Promise.reject<ASS>(new Error("Not supported."));
}
return fetchPromise.catch(reason => {
if (debugMode) {
console.log("fetch() failed, falling back to XHR: %o", reason);
}
const xhr = new XMLHttpRequest();
const result = ASS.fromStream(new XhrStream(xhr), type);
xhr.open("GET", url, true);
xhr.send();
return result;
});
}
/**
* Creates an ASS object from the given ReadableStream.
*
* @param {!ReadableStream} stream
* @param {string="utf-8"} encoding
* @param {(number|string)=0} type The type of the script. One of the {@link libjass.Format} constants, or one of the strings "ass" and "srt".
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
*/
static fromReadableStream(stream: ReadableStream, encoding: string = "utf-8", type: Format | "ass" | "srt" = Format.ASS): Promise<ASS> {
return ASS.fromStream(new BrowserReadableStream(stream, encoding), type);
}
/**
* Custom deserialization for ASS objects.
*
* @param {!*} obj
* @return {!libjass.ASS}
*/
static fromJSON(obj: any): ASS {
const result: ASS = Object.create(ASS.prototype);
result._properties = obj._properties;
result._styles = new Map<string, Style>();
for (const name of Object.keys(obj._styles)) {
const style = obj._styles[name];
result._styles.set(name, style);
}
result._dialogues = obj._dialogues;
result._attachments = obj._attachments;
result._stylesFormatSpecifier = obj._stylesFormatSpecifier;
result._dialoguesFormatSpecifier = obj._dialoguesFormatSpecifier;
return result;
}
private _properties: ScriptProperties = new ScriptProperties();
private _styles: Map<string, Style> = new Map<string, Style>();
private _dialogues: Dialogue[] = [];
private _attachments: Attachment[] = [];
private _stylesFormatSpecifier: string[] = null;
private _dialoguesFormatSpecifier: string[] = null;
private _stylesFormatSpecifier: string[] | null = null;
private _dialoguesFormatSpecifier: string[] | null = null;
/**
* The properties of this script.
@@ -96,16 +193,25 @@ export class ASS {
*
* @type {Array.<string>}
*/
get stylesFormatSpecifier(): string[] {
get stylesFormatSpecifier(): string[] | null {
return this._stylesFormatSpecifier;
}
/**
* The format specifier for the events section.
*
* @type {Array.<string>}
*/
set stylesFormatSpecifier(value: string[] | null) {
this._stylesFormatSpecifier = value;
}
/**
* The format specifier for the styles section.
*
* @type {Array.<string>}
*/
get dialoguesFormatSpecifier(): string[] {
get dialoguesFormatSpecifier(): string[] | null {
return this._dialoguesFormatSpecifier;
}
@@ -114,16 +220,7 @@ export class ASS {
*
* @type {Array.<string>}
*/
set stylesFormatSpecifier(value: string[]) {
this._stylesFormatSpecifier = value;
}
/**
* The format specifier for the events section.
*
* @type {Array.<string>}
*/
set dialoguesFormatSpecifier(value: string[]) {
set dialoguesFormatSpecifier(value: string[] | null) {
this._dialoguesFormatSpecifier = value;
}
@@ -222,112 +319,4 @@ export class ASS {
return result;
}
/**
* Creates an ASS object from the raw text of an ASS script.
*
* @param {string} raw The raw text of the script.
* @param {(number|string)=0} type The type of the script. One of the {@link libjass.Format} constants, or one of the strings "ass" and "srt".
* @return {!Promise.<!libjass.ASS>}
*/
static fromString(raw: string, type: Format | "ass" | "srt" = Format.ASS): Promise<ASS> {
return ASS.fromStream(new parser.StringStream(raw), type);
}
/**
* Creates an ASS object from the given {@link libjass.parser.Stream}.
*
* @param {!libjass.parser.Stream} stream The stream to parse the script from
* @param {(number|string)=0} type The type of the script. One of the {@link libjass.Format} constants, or one of the strings "ass" and "srt".
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
*/
static fromStream(stream: parser.Stream, type: Format | "ass" | "srt" = Format.ASS): Promise<ASS> {
switch (type) {
case Format.ASS:
case "ass":
return new parser.StreamParser(stream).ass;
case Format.SRT:
case "srt":
return new parser.SrtStreamParser(stream).ass;
default:
throw new Error(`Invalid value of type: ${ type }`);
}
}
/**
* Creates an ASS object from the given URL.
*
* @param {string} url The URL of the script.
* @param {(number|string)=0} type The type of the script. One of the {@link libjass.Format} constants, or one of the strings "ass" and "srt".
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
*/
static fromUrl(url: string, type: Format | "ass" | "srt" = Format.ASS): Promise<ASS> {
let fetchPromise: Promise<ASS>;
if (
typeof global.fetch === "function" &&
typeof global.ReadableStream === "function" && typeof global.ReadableStream.prototype.getReader === "function" &&
typeof global.TextDecoder === "function"
) {
fetchPromise = global.fetch(url).then(response => {
if (response.ok === false || (response.ok === undefined && (response.status < 200 || response.status > 299))) {
throw new Error(`HTTP request for ${ url } failed with status code ${ response.status }`);
}
return ASS.fromReadableStream(response.body, "utf-8", type);
});
}
else {
fetchPromise = Promise.reject<ASS>(new Error("Not supported."));
}
return fetchPromise.catch(reason => {
if (debugMode) {
console.log("fetch() failed, falling back to XHR: %o", reason);
}
const xhr = new XMLHttpRequest();
const result = ASS.fromStream(new parser.XhrStream(xhr), type);
xhr.open("GET", url, true);
xhr.send();
return result;
});
}
/**
* Creates an ASS object from the given ReadableStream.
*
* @param {!ReadableStream} stream
* @param {string="utf-8"} encoding
* @param {(number|string)=0} type The type of the script. One of the {@link libjass.Format} constants, or one of the strings "ass" and "srt".
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
*/
static fromReadableStream(stream: ReadableStream, encoding: string = "utf-8", type: Format | "ass" | "srt" = Format.ASS): Promise<ASS> {
return ASS.fromStream(new parser.BrowserReadableStream(stream, encoding), type);
}
/**
* Custom deserialization for ASS objects.
*
* @param {!*} obj
* @return {!libjass.ASS}
*/
static fromJSON(obj: any): ASS {
const result: ASS = Object.create(ASS.prototype);
result._properties = obj._properties;
result._styles = new Map<string, Style>();
for (const name of Object.keys(obj._styles)) {
const style = obj._styles[name];
result._styles.set(name, style);
}
result._dialogues = obj._dialogues;
result._attachments = obj._attachments;
result._stylesFormatSpecifier = obj._stylesFormatSpecifier;
result._dialoguesFormatSpecifier = obj._dialoguesFormatSpecifier;
return result;
}
}
+8 -8
View File
@@ -46,7 +46,7 @@ import { Map } from "../utility/map";
*/
@serializable
export class Dialogue {
private static _lastDialogueId = -1;
private static _lastDialogueId: number = -1;
private _id: number;
@@ -59,7 +59,7 @@ export class Dialogue {
private _alignment: number;
private _rawPartsString: string;
private _parts: parts.Part[] = null;
private _parts: parts.Part[] | null = null;
private _containsTransformTag: boolean = false;
@@ -184,7 +184,7 @@ export class Dialogue {
this._parsePartsString();
}
return this._parts;
return this._parts!;
}
/**
@@ -221,21 +221,21 @@ export class Dialogue {
}
else if (part instanceof parts.Move) {
if (part.t1 === null || part.t2 === null) {
this._parts[index] =
this._parts![index] =
new parts.Move(
part.x1, part.y1, part.x2, part.y2,
0, this._end - this._start
0, this._end - this._start,
);
}
}
else if (part instanceof parts.Transform) {
if (part.start === null || part.end === null || part.accel === null) {
this._parts[index] =
this._parts![index] =
new parts.Transform(
(part.start === null) ? 0 : part.start,
(part.end === null) ? (this._end - this._start) : part.end,
(part.accel === null) ? 1 : part.accel,
part.tags
part.tags,
);
}
@@ -252,7 +252,7 @@ ${ this._rawPartsString }
was parsed as
${ this.toString() }
The possibly incorrect parses are:
${ possiblyIncorrectParses.join("\n") }`
${ possiblyIncorrectParses.join("\n") }`,
);
}
}
+1 -3
View File
@@ -18,8 +18,6 @@
* limitations under the License.
*/
import { Map } from "../utility/map";
/**
* The format of the string passed to {@link libjass.ASS.fromString}
*/
@@ -84,7 +82,7 @@ export interface TypedTemplate {
* @param {T} defaultValue
* @return {T}
*/
export function valueOrDefault<T>(template: Map<string, string>, key: string, converter: (str: string) => T, validator: (value: T) => boolean, defaultValue: string): T {
export function valueOrDefault<T>(template: Map<string, string>, key: string, converter: (str: string) => T, validator: ((value: T) => boolean) | null, defaultValue: string): T {
const value = template.get(key);
if (value === undefined) {
return converter(defaultValue);
+2 -2
View File
@@ -18,8 +18,6 @@
* limitations under the License.
*/
import { valueOrDefault, BorderStyle } from "./misc";
import { parse } from "../parser/parse";
import { Color } from "../parts";
@@ -28,6 +26,8 @@ import { registerClass as serializable } from "../serialization";
import { Map } from "../utility/map";
import { BorderStyle, valueOrDefault } from "./misc";
/**
* This class represents a single global style declaration in a {@link libjass.ASS} script. The styles can be obtained via the {@link libjass.ASS.styles} property.
*
+54 -85
View File
@@ -18,52 +18,6 @@
* limitations under the License.
*/
declare const global: {
Map?: typeof Map;
};
export interface Map<K, V> {
/**
* @param {K} key
* @return {?V}
*/
get(key: K): V;
/**
* @param {K} key
* @return {boolean}
*/
has(key: K): boolean;
/**
* @param {K} key
* @param {V} value
* @return {libjass.Map.<K, V>} This map
*/
set(key: K, value?: V): Map<K, V>;
/**
* @param {K} key
* @return {boolean} true if the key was present before being deleted, false otherwise
*/
delete(key: K): boolean;
/**
*/
clear(): void;
/**
* @param {function(V, K, libjass.Map.<K, V>)} callbackfn A function that is called with each key and value in the map.
* @param {*} thisArg
*/
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
/**
* @type {number}
*/
size: number;
}
/**
* Map implementation for browsers that don't support it. Only supports keys which are of Number or String type, or which have a property called "id".
*
@@ -71,7 +25,7 @@ export interface Map<K, V> {
*
* @param {!Array.<!Array.<*>>=} iterable Only an array of elements (where each element is a 2-tuple of key and value) is supported.
*/
class SimpleMap<K, V> {
class SimpleMap<K, V> implements Map<K, V> {
private _keys: { [key: string]: K };
private _values: { [key: string]: V };
private _size: number;
@@ -96,8 +50,8 @@ class SimpleMap<K, V> {
* @param {K} key
* @return {?V}
*/
get(key: K): V {
const property = this._keyToProperty(key);
get(key: K): V | undefined {
const property = keyToProperty(key);
if (property === null) {
return undefined;
@@ -111,7 +65,7 @@ class SimpleMap<K, V> {
* @return {boolean}
*/
has(key: K): boolean {
const property = this._keyToProperty(key);
const property = keyToProperty(key);
if (property === null) {
return false;
@@ -125,8 +79,8 @@ class SimpleMap<K, V> {
* @param {V} value
* @return {libjass.Map.<K, V>} This map
*/
set(key: K, value: V): Map<K, V> {
const property = this._keyToProperty(key);
set(key: K, value: V): this {
const property = keyToProperty(key);
if (property === null) {
throw new Error("This Map implementation only supports Number and String keys, or keys with an id property.");
@@ -147,7 +101,7 @@ class SimpleMap<K, V> {
* @return {boolean} true if the key was present before being deleted, false otherwise
*/
delete(key: K): boolean {
const property = this._keyToProperty(key);
const property = keyToProperty(key);
if (property === null) {
return false;
@@ -176,7 +130,7 @@ class SimpleMap<K, V> {
* @param {function(V, K, libjass.Map.<K, V>)} callbackfn A function that is called with each key and value in the map.
* @param {*} thisArg
*/
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void {
forEach(callbackfn: (value: V, index: K, map: this) => void, thisArg?: any): void {
for (const property of Object.keys(this._keys)) {
callbackfn.call(thisArg, this._values[property], this._keys[property], this);
}
@@ -188,30 +142,10 @@ class SimpleMap<K, V> {
get size(): number {
return this._size;
}
/**
* Converts the given key into a property name for the internal map.
*
* @param {K} key
* @return {?string}
*/
private _keyToProperty(key: K): string {
if (typeof key === "number") {
return `#${ key }`;
}
if (typeof key === "string") {
return `'${ key }`;
}
if ((key as any).id !== undefined) {
return `!${ (key as any).id }`;
}
return null;
}
}
/* tslint:disable:variable-name */
/**
* Set to the global implementation of Map if the environment has one, else set to {@link ./utility/map.SimpleMap}
*
@@ -221,28 +155,41 @@ class SimpleMap<K, V> {
*
* @type {function(new:Map, !Array.<!Array.<*>>=)}
*/
export var Map: {
export let Map: {
new <K, V>(iterable?: [K, V][]): Map<K, V>;
/* tslint:disable-next-line:member-ordering */
prototype: Map<any, any>;
} = global.Map || SimpleMap;
} = (() => {
const globalMap = global.Map;
if (globalMap === undefined) {
return SimpleMap;
}
if (typeof globalMap.prototype.forEach !== "function") {
return SimpleMap;
}
if (typeof Map.prototype.forEach !== "function" || (() => {
try {
return new Map([[1, "foo"], [2, "bar"]]).size !== 2;
if (new globalMap([[1, "foo"], [2, "bar"]]).size !== 2) {
return SimpleMap;
}
}
catch (ex) {
return true;
return SimpleMap;
}
})()) {
Map = SimpleMap;
}
return globalMap as any;
})();
/* tslint:enable:variable-name */
/**
* Sets the Map implementation used by libjass to the provided one. If null, {@link ./utility/map.SimpleMap} is used.
*
* @param {?function(new:Map, !Array.<!Array.<*>>=)} value
*/
export function setImplementation(value: typeof Map): void {
export function setImplementation(value: typeof Map | null): void {
if (value !== null) {
Map = value;
}
@@ -250,3 +197,25 @@ export function setImplementation(value: typeof Map): void {
Map = SimpleMap;
}
}
/**
* Converts the given key into a property name for the internal map.
*
* @param {*} key
* @return {?string}
*/
function keyToProperty(key: any): string | null {
if (typeof key === "number") {
return `#${ key }`;
}
if (typeof key === "string") {
return `'${ key }`;
}
if ((key as any).id !== undefined) {
return `!${ (key as any).id }`;
}
return null;
}
+141 -178
View File
@@ -18,53 +18,15 @@
* limitations under the License.
*/
declare const global: {
Promise?: typeof Promise;
MutationObserver?: typeof MutationObserver;
WebkitMutationObserver?: typeof MutationObserver;
process?: {
nextTick(callback: () => void): void;
}
};
export interface Thenable<T> {
/** @type {function(this:!Thenable.<T>, function(T|!Thenable.<T>), function(*))} */
then: ThenableThen<T>;
}
export interface ThenableThen<T> {
/** @type {function(this:!Thenable.<T>, function(T|!Thenable.<T>), function(*))} */
(resolve: (resolution: T | Thenable<T>) => void, reject: (reason: any) => void): void;
}
export interface Promise<T> extends Thenable<T> {
/**
* @param {?function(T):!Thenable.<U>} onFulfilled
* @param {?function(*):(U|!Thenable.<U>)} onRejected
* @return {!Promise.<U>}
*/
then<U>(onFulfilled?: (value: T) => Thenable<U>, onRejected?: (reason: any) => U | Thenable<U>): Promise<U>;
/**
* @param {?function(T):U} onFulfilled
* @param {?function(*):(U|!Thenable.<U>)} onRejected
* @return {!Promise.<U>}
*/
then<U>(onFulfilled?: (value: T) => U, onRejected?: (reason: any) => U | Thenable<U>): Promise<U>;
/**
* @param {function(*):(T|!Thenable.<T>)} onRejected
* @return {!Promise.<T>}
*/
catch(onRejected?: (reason: any) => T | Thenable<T>): Promise<T>;
}
// Based on https://github.com/petkaantonov/bluebird/blob/1b1467b95442c12378d0ea280ede61d640ab5510/src/schedule.js
const enqueueJob: (callback: () => void) => void = (function () {
const enqueueJob = (function (): (callback: () => void) => void {
/* tslint:disable-next-line:variable-name */
const MutationObserver = global.MutationObserver || global.WebkitMutationObserver;
if (global.process !== undefined && typeof global.process.nextTick === "function") {
const nextTick = global.process.nextTick;
return (callback: () => void) => {
global.process.nextTick(callback);
nextTick(callback);
};
}
else if (MutationObserver !== undefined) {
@@ -110,80 +72,6 @@ const enqueueJob: (callback: () => void) => void = (function () {
* @param {function(function(T|!Thenable.<T>), function(*))} executor
*/
class SimplePromise<T> {
private _state: SimplePromiseState = SimplePromiseState.PENDING;
private _fulfillReactions: FulfilledPromiseReaction<T, any>[] = [];
private _rejectReactions: RejectedPromiseReaction<any>[] = [];
private _fulfilledValue: T = null;
private _rejectedReason: any = null;
constructor(executor: (resolve: (resolution: T | Thenable<T>) => void, reject: (reason: any) => void) => void) {
if (typeof executor !== "function") {
throw new TypeError(`typeof executor !== "function"`);
}
const { resolve, reject } = this._createResolvingFunctions();
try {
executor(resolve, reject);
}
catch (ex) {
reject(ex);
}
}
/**
* @param {?function(T):(U|!Thenable.<U>)} onFulfilled
* @param {?function(*):(U|!Thenable.<U>)} onRejected
* @return {!Promise.<U>}
*/
then<U>(onFulfilled: (value: T) => U | Thenable<U>, onRejected: (reason: any) => U | Thenable<U>): Promise<U> {
const resultCapability = new DeferredPromise<U>();
if (typeof onFulfilled !== "function") {
onFulfilled = (value: T) => value as any as U;
}
if (typeof onRejected !== "function") {
onRejected = (reason: any): U => { throw reason; };
}
const fulfillReaction: FulfilledPromiseReaction<T, U> = {
capabilities: resultCapability,
handler: onFulfilled,
};
const rejectReaction: RejectedPromiseReaction<U> = {
capabilities: resultCapability,
handler: onRejected,
};
switch (this._state) {
case SimplePromiseState.PENDING:
this._fulfillReactions.push(fulfillReaction);
this._rejectReactions.push(rejectReaction);
break;
case SimplePromiseState.FULFILLED:
this._enqueueFulfilledReactionJob(fulfillReaction, this._fulfilledValue);
break;
case SimplePromiseState.REJECTED:
this._enqueueRejectedReactionJob(rejectReaction, this._rejectedReason);
break;
}
return resultCapability.promise;
}
/**
* @param {function(*):(T|!Thenable.<T>)} onRejected
* @return {!Promise.<T>}
*/
catch(onRejected?: (reason: any) => T | Thenable<T>): Promise<T> {
return this.then(null, onRejected);
}
/**
* @param {T|!Thenable.<T>} value
* @return {!Promise.<T>}
@@ -201,7 +89,7 @@ class SimplePromise<T> {
* @return {!Promise.<T>}
*/
static reject<T>(reason: any): Promise<T> {
return new Promise<T>((/* ujs:unreferenced */ resolve, reject) => reject(reason));
return new Promise<T>((/* ujs:unreferenced */ _resolve, reject) => reject(reason));
}
/**
@@ -236,11 +124,83 @@ class SimplePromise<T> {
static race<T>(values: (T | Thenable<T>)[]): Promise<T> {
return new Promise<T>((resolve, reject) => {
for (const value of values) {
/* tslint:disable-next-line:no-floating-promises */
Promise.resolve(value).then(resolve, reject);
}
});
}
private _state: SimplePromiseState<T> = { state: "pending" };
private _fulfillReactions: FulfilledPromiseReaction<T, any>[] = [];
private _rejectReactions: RejectedPromiseReaction<any>[] = [];
constructor(executor: (resolve: (resolution: T | Thenable<T>) => void, reject: (reason: any) => void) => void) {
/* tslint:disable-next-line:strict-type-predicates */
if (typeof executor !== "function") {
throw new TypeError(`typeof executor !== "function"`);
}
const { resolve, reject } = this._createResolvingFunctions();
try {
executor(resolve, reject);
}
catch (ex) {
reject(ex);
}
}
/**
* @param {?function(T):(U|!Thenable.<U>)} onFulfilled
* @param {?function(*):(U|!Thenable.<U>)} onRejected
* @return {!Promise.<U>}
*/
then<U>(onFulfilled: ((value: T) => U | Thenable<U>) | undefined, onRejected?: (reason: any) => U | Thenable<U>): Promise<U> {
const resultCapability = new DeferredPromise<U>();
if (typeof onFulfilled !== "function") {
onFulfilled = (value: T) => value as any as U;
}
if (typeof onRejected !== "function") {
onRejected = (reason: any): U => { throw reason; };
}
const fulfillReaction: FulfilledPromiseReaction<T, U> = {
capabilities: resultCapability,
handler: onFulfilled,
};
const rejectReaction: RejectedPromiseReaction<U> = {
capabilities: resultCapability,
handler: onRejected,
};
switch (this._state.state) {
case "pending":
this._fulfillReactions.push(fulfillReaction);
this._rejectReactions.push(rejectReaction);
break;
case "fulfilled":
enqueueFulfilledReactionJob(fulfillReaction, this._state.value);
break;
case "rejected":
enqueueRejectedReactionJob(rejectReaction, this._state.reason);
break;
}
return resultCapability.promise;
}
/**
* @param {function(*):(T|!Thenable.<T>)} onRejected
* @return {!Promise.<T>}
*/
catch(onRejected: (reason: any) => T | Thenable<T>): Promise<T> {
return this.then(undefined, onRejected);
}
/**
* @return {{ resolve(T|!Thenable.<T>), reject(*) }}
*/
@@ -259,19 +219,23 @@ class SimplePromise<T> {
return;
}
/* tslint:disable-next-line:strict-type-predicates */
if (resolution === null || (typeof resolution !== "object" && typeof resolution !== "function")) {
this._fulfill(resolution as T);
return;
}
let then: ThenableThen<T>;
try {
var then = (resolution as Thenable<T>).then;
then = (resolution as Thenable<T>).then;
}
catch (ex) {
this._reject(ex);
return;
}
/* tslint:disable-next-line:strict-type-predicates */
if (typeof then !== "function") {
this._fulfill(resolution as T);
return;
@@ -314,13 +278,12 @@ class SimplePromise<T> {
private _fulfill(value: T): void {
const reactions = this._fulfillReactions;
this._fulfilledValue = value;
this._state = { state: "fulfilled", value };
this._fulfillReactions = [];
this._rejectReactions = [];
this._state = SimplePromiseState.FULFILLED;
for (const reaction of reactions) {
this._enqueueFulfilledReactionJob(reaction, value);
enqueueFulfilledReactionJob(reaction, value);
}
}
@@ -330,61 +293,18 @@ class SimplePromise<T> {
private _reject(reason: any): void {
const reactions = this._rejectReactions;
this._rejectedReason = reason;
this._state = { state: "rejected", reason };
this._fulfillReactions = [];
this._rejectReactions = [];
this._state = SimplePromiseState.REJECTED;
for (const reaction of reactions) {
this._enqueueRejectedReactionJob(reaction, reason);
enqueueRejectedReactionJob(reaction, reason);
}
}
/**
* @param {!FulfilledPromiseReaction.<T, *>} reaction
* @param {T} value
*/
private _enqueueFulfilledReactionJob(reaction: FulfilledPromiseReaction<T, any>, value: T): void {
enqueueJob(() => {
const { capabilities: { resolve, reject }, handler } = reaction;
let handlerResult: any | Thenable<any>;
try {
handlerResult = handler(value);
}
catch (ex) {
reject(ex);
return;
}
resolve(handlerResult);
});
}
/**
* @param {!RejectedPromiseReaction.<*>} reaction
* @param {*} reason
*/
private _enqueueRejectedReactionJob(reaction: RejectedPromiseReaction<any>, reason: any): void {
enqueueJob(() => {
const { capabilities: { resolve, reject }, handler } = reaction;
let handlerResult: any | Thenable<any>;
try {
handlerResult = handler(reason);
}
catch (ex) {
reject(ex);
return;
}
resolve(handlerResult);
});
}
}
/* tslint:disable:variable-name */
/**
* Set to the global implementation of Promise if the environment has one, else set to {@link ./utility/promise.SimplePromise}
*
@@ -394,8 +314,9 @@ class SimplePromise<T> {
*
* @type {function(new:Promise)}
*/
export var Promise: {
export let Promise: {
new <T>(init: (resolve: (value: T | Thenable<T>) => void, reject: (reason: any) => void) => void): Promise<T>;
/* tslint:disable-next-line:member-ordering */
prototype: Promise<any>;
resolve<T>(value: T | Thenable<T>): Promise<T>;
reject<T>(reason: any): Promise<T>;
@@ -403,6 +324,8 @@ export var Promise: {
race<T>(values: (T | Thenable<T>)[]): Promise<T>;
} = global.Promise || SimplePromise;
/* tslint:enable:variable-name */
interface FulfilledPromiseReaction<T, U> {
/** @type {!libjass.DeferredPromise.<U>} */
capabilities: DeferredPromise<U>;
@@ -428,18 +351,14 @@ interface RejectedPromiseReaction<U> {
/**
* The state of the {@link ./utility/promise.SimplePromise}
*/
enum SimplePromiseState {
PENDING = 0,
FULFILLED = 1,
REJECTED = 2,
}
type SimplePromiseState<T> = { state: "pending" } | { state: "fulfilled"; value: T; } | { state: "rejected"; reason: any; };
/**
* Sets the Promise implementation used by libjass to the provided one. If null, {@link ./utility/promise.SimplePromise} is used.
*
* @param {?function(new:Promise)} value
*/
export function setImplementation(value: typeof Promise): void {
export function setImplementation(value: typeof Promise | null): void {
if (value !== null) {
Promise = value;
}
@@ -452,8 +371,6 @@ export function setImplementation(value: typeof Promise): void {
* A deferred promise.
*/
export class DeferredPromise<T> {
private _promise: Promise<T>;
/**
* @type {function(T|!Thenable.<T>)}
*/
@@ -464,6 +381,8 @@ export class DeferredPromise<T> {
*/
reject: (reason: any) => void;
private _promise: Promise<T>;
constructor() {
this._promise = new Promise<T>((resolve, reject) => {
Object.defineProperties(this, {
@@ -532,3 +451,47 @@ export function lastly<T>(promise: Promise<T>, body: () => void): Promise<T> {
throw reason;
});
}
/**
* @param {!FulfilledPromiseReaction.<T, *>} reaction
* @param {T} value
*/
function enqueueFulfilledReactionJob<T>(reaction: FulfilledPromiseReaction<T, any>, value: T): void {
enqueueJob(() => {
const { capabilities: { resolve, reject }, handler } = reaction;
let handlerResult: any | Thenable<any>;
try {
handlerResult = handler(value);
}
catch (ex) {
reject(ex);
return;
}
resolve(handlerResult);
});
}
/**
* @param {!RejectedPromiseReaction.<*>} reaction
* @param {*} reason
*/
function enqueueRejectedReactionJob(reaction: RejectedPromiseReaction<any>, reason: any): void {
enqueueJob(() => {
const { capabilities: { resolve, reject }, handler } = reaction;
let handlerResult: any | Thenable<any>;
try {
handlerResult = handler(reason);
}
catch (ex) {
reject(ex);
return;
}
resolve(handlerResult);
});
}
+47 -65
View File
@@ -18,39 +18,6 @@
* limitations under the License.
*/
declare const global: {
Set?: typeof Set;
};
export interface Set<T> {
/**
* @param {T} value
* @return {libjass.Set.<T>} This set
*/
add(value: T): Set<T>;
/**
*/
clear(): void;
/**
* @param {T} value
* @return {boolean}
*/
has(value: T): boolean;
/**
* @param {function(T, T, libjass.Set.<T>)} callbackfn A function that is called with each value in the set.
* @param {*} thisArg
*/
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
/**
* @type {number}
*/
size: number;
}
/**
* Set implementation for browsers that don't support it. Only supports Number and String elements.
*
@@ -58,7 +25,7 @@ export interface Set<T> {
*
* @param {!Array.<T>=} iterable Only an array of values is supported.
*/
class SimpleSet<T> {
class SimpleSet<T> implements Set<T> {
private _elements: { [key: string]: T };
private _size: number;
@@ -82,8 +49,8 @@ class SimpleSet<T> {
* @param {T} value
* @return {libjass.Set.<T>} This set
*/
add(value: T): Set<T> {
const property = this._toProperty(value);
add(value: T): this {
const property = toProperty(value);
if (property === null) {
throw new Error("This Set implementation only supports Number and String values.");
@@ -110,7 +77,7 @@ class SimpleSet<T> {
* @return {boolean}
*/
has(value: T): boolean {
const property = this._toProperty(value);
const property = toProperty(value);
if (property === null) {
return false;
@@ -123,7 +90,7 @@ class SimpleSet<T> {
* @param {function(T, T, libjass.Set.<T>)} callbackfn A function that is called with each value in the set.
* @param {*} thisArg
*/
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void {
forEach(callbackfn: (value: T, index: T, set: this) => void, thisArg?: any): void {
for (const property of Object.keys(this._elements)) {
const element = this._elements[property];
callbackfn.call(thisArg, element, element, this);
@@ -136,26 +103,10 @@ class SimpleSet<T> {
get size(): number {
return this._size;
}
/**
* Converts the given value into a property name for the internal map.
*
* @param {T} value
* @return {?string}
*/
private _toProperty(value: T): string {
if (typeof value === "number") {
return `#${ value }`;
}
if (typeof value === "string") {
return `'${ value }`;
}
return null;
}
}
/* tslint:disable:variable-name */
/**
* Set to the global implementation of Set if the environment has one, else set to {@link ./utility/set.SimpleSet}
*
@@ -165,28 +116,41 @@ class SimpleSet<T> {
*
* @type {function(new:Set, !Array.<T>=)}
*/
export var Set: {
export let Set: {
new <T>(iterable?: T[]): Set<T>;
/* tslint:disable-next-line:member-ordering */
prototype: Set<any>;
} = global.Set || SimpleSet;
} = (() => {
const globalSet = global.Set;
if (globalSet === undefined) {
return SimpleSet;
}
if (typeof globalSet.prototype.forEach !== "function") {
return SimpleSet;
}
if (typeof Set.prototype.forEach !== "function" || (() => {
try {
return new Set([1, 2]).size !== 2;
if ((new globalSet([1, 2])).size !== 2) {
return SimpleSet;
}
}
catch (ex) {
return true;
return SimpleSet;
}
})()) {
Set = SimpleSet;
}
return globalSet as any;
})();
/* tslint:enable:variable-name */
/**
* Sets the Set implementation used by libjass to the provided one. If null, {@link ./utility/set.SimpleSet} is used.
*
* @param {?function(new:Set, !Array.<T>=)} value
*/
export function setImplementation(value: typeof Set): void {
export function setImplementation(value: typeof Set | null): void {
if (value !== null) {
Set = value;
}
@@ -194,3 +158,21 @@ export function setImplementation(value: typeof Set): void {
Set = SimpleSet;
}
}
/**
* Converts the given value into a property name for the internal map.
*
* @param {*} value
* @return {?string}
*/
function toProperty(value: any): string | null {
if (typeof value === "number") {
return `#${ value }`;
}
if (typeof value === "string") {
return `'${ value }`;
}
return null;
}
+7 -32
View File
@@ -18,11 +18,11 @@
* limitations under the License.
*/
import { serialize, deserialize } from "../serialization";
import { deserialize, serialize } from "../serialization";
import { Map } from "../utility/map";
import { Promise, DeferredPromise } from "../utility/promise";
import { DeferredPromise, Promise } from "../utility/promise";
import { WorkerCommands } from "./commands";
import { getWorkerCommandHandler, registerWorkerCommand } from "./misc";
@@ -44,33 +44,7 @@ export interface WorkerChannel {
/**
* The signature of a handler registered to handle a particular command in {@link libjass.webworker.WorkerCommands}
*/
export interface WorkerCommandHandler {
(parameters: any): Promise<any>;
}
/**
* The interface implemented by a communication channel to the other side.
*/
export interface WorkerCommunication {
/**
* @param {"message"} type
* @param {function(!MessageEvent): *} listener
* @param {?boolean} useCapture
*/
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
/**
* @param {string} type
* @param {!EventListener} listener
* @param {?boolean} useCapture
*/
addEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
/**
* @param {*} message
*/
postMessage(message: any): void;
}
export type WorkerCommandHandler = (parameters: any) => Promise<any>;
/**
* The interface implemented by a request sent to the other side of the communication channel.
@@ -133,7 +107,7 @@ interface WorkerResponseMessage {
export class WorkerChannelImpl implements WorkerChannel {
private static _lastRequestId: number = -1;
private _pendingRequests = new Map<number, DeferredPromise<any>>();
private _pendingRequests: Map<number, DeferredPromise<any>> = new Map<number, DeferredPromise<any>>();
constructor(private _comm: WorkerCommunication) {
this._comm.addEventListener("message", ev => this._onMessage(ev.data as string), false);
@@ -209,12 +183,13 @@ export class WorkerChannelImpl implements WorkerChannel {
return;
}
/* tslint:disable-next-line:no-floating-promises */
commandCallback(requestMessage.parameters).then<WorkerResponseMessage>(
result => ({ requestId, error: null, result }),
error => ({ requestId, error, result: null })
error => ({ requestId, error, result: null }),
).then(responseMessage => this._respond(responseMessage));
}
}
}
registerWorkerCommand(WorkerCommands.Ping, parameters => Promise.resolve<void>(null));
registerWorkerCommand(WorkerCommands.Ping, () => Promise.resolve(null));
+5 -5
View File
@@ -28,9 +28,9 @@ export { WorkerCommands } from "./commands";
*
* @type {boolean}
*/
export const supported = typeof Worker !== "undefined";
export const supported = global.Worker !== undefined;
const _scriptNode = (typeof document !== "undefined" && document.currentScript !== undefined) ? document.currentScript : null;
const _scriptNode = (global.document !== undefined && global.document.currentScript !== undefined) ? global.document.currentScript : null;
/**
* Create a new web worker and returns a {@link libjass.webworker.WorkerChannel} to it.
@@ -51,9 +51,9 @@ export function createWorker(scriptPath?: string): WorkerChannel {
return new WorkerChannelImpl(new Worker(scriptPath));
}
declare const global: any;
if (typeof WorkerGlobalScope !== "undefined" && global instanceof WorkerGlobalScope) {
if (global.WorkerGlobalScope !== undefined && global instanceof global.WorkerGlobalScope) {
// This is a web worker. Set up a channel to talk back to the main thread.
/* tslint:disable-next-line:no-unused-expression */
new WorkerChannelImpl(global);
}
+2 -2
View File
@@ -20,8 +20,8 @@
import { Map } from "../utility/map";
import { WorkerCommands } from "./commands";
import { WorkerCommandHandler } from "./channel";
import { WorkerCommands } from "./commands";
const workerCommands = new Map<WorkerCommands, WorkerCommandHandler>();
@@ -41,6 +41,6 @@ export function registerWorkerCommand(command: WorkerCommands, handler: WorkerCo
* @param {number} command
* @return {?function(*, function(*, *))}
*/
export function getWorkerCommandHandler(command: WorkerCommands): WorkerCommandHandler {
export function getWorkerCommandHandler(command: WorkerCommands): WorkerCommandHandler | undefined {
return workerCommands.get(command);
}
-37
View File
@@ -1,37 +0,0 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface WorkerGlobalScope {
/**
* @param {*} message
*/
postMessage(message: any): void;
/**
* @param {string} type
* @param {function(*)} listener
* @param {boolean} useCapture
*/
addEventListener(type: string, listener: (message: any) => void, useCapture: boolean): void;
}
declare var WorkerGlobalScope: {
prototype: WorkerGlobalScope;
new (): WorkerGlobalScope;
};