diff --git a/.gitignore b/.gitignore index 656f1cda5..a111d5647 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ Properties *~ # test folder +!_infrastructure/*.js !_infrastructure/tests/* !_infrastructure/tests/*.js !_infrastructure/tests/*/*.js diff --git a/README.md b/README.md index 83e4ffbca..2943452fd 100755 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ List of Definitions * [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei)) * [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [FPSMeter](http://darsa.in/fpsmeter/) (by [Aaron Lampros](https://github.com/alampros)) +* [FullCalendar](http://arshaw.com/fullcalendar/) (by [Neil Stalker](https://github.com/nestalk)) * [Gamepad](http://www.w3.org/TR/gamepad/) (by [Kon](http://phyzkit.net/)) * [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dániel Tar](https://github.com/qcz)) * [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt)) @@ -99,6 +100,7 @@ List of Definitions * [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov)) * [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/)) * [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/)) +* [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) * [jQuery.scrollTo](https://github.com/flesler/jquery.scrollTo) (by [Neil Stalker](https://github.com/nestalk/)) * [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/)) * [jQuery.timeago](http://timeago.yarp.com/) (by [François Guillot](http://fguillot.developpez.com/)) @@ -111,6 +113,7 @@ List of Definitions * [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz)) * [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk)) * [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/)) +* [jStorage](http://www.jstorage.info/) (by [Danil Flores](https://github.com/dflor003/)) * [JWPlayer](http://developer.longtailvideo.com/trac/) (by [Martin Duparc](https://github.com/martinduparc/)) * [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/)) * [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit)) @@ -123,8 +126,9 @@ List of Definitions * [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov)) * [Leaflet](https://github.com/Leaflet/Leaflet) (by [Vladimir](https://github.com/rgripper)) * [Libxmljs](https://github.com/polotek/libxmljs) (by [François de Campredon](https://github.com/fdecampredon)) +* [ladda](https://github.com/hakimel/Ladda) (by [Danil Flores](https://github.com/dflor003)) * [linq.js](http://linqjs.codeplex.com/) (by [Marcin Najder](https://github.com/marcinnajder)) -* [Livestamp.js](https://github.com/mattbradley/livestampjs) (by [Vincent Bortone] (https://github.com/vbortone)) +* [Livestamp.js](https://github.com/mattbradley/livestampjs) (by [Vincent Bortone](https://github.com/vbortone)) * [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr)) * [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov) and [Theodore Brown](https://github.com/theodorejb/)) * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) diff --git a/_infrastructure/tests/runner.js b/_infrastructure/tests/runner.js new file mode 100644 index 000000000..8b1ff53dd --- /dev/null +++ b/_infrastructure/tests/runner.js @@ -0,0 +1,1058 @@ +var ExecResult = (function () { + function ExecResult() { + this.stdout = ""; + this.stderr = ""; + } + return ExecResult; +})(); + +var WindowsScriptHostExec = (function () { + function WindowsScriptHostExec() { + } + WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var result = new ExecResult(); + var shell = new ActiveXObject('WScript.Shell'); + try { + var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); + } catch (e) { + result.stderr = e.message; + result.exitCode = 1; + handleResult(result); + return; + } + + while (process.Status != 0) { + } + + result.exitCode = process.ExitCode; + if (!process.StdOut.AtEndOfStream) + result.stdout = process.StdOut.ReadAll(); + if (!process.StdErr.AtEndOfStream) + result.stderr = process.StdErr.ReadAll(); + + handleResult(result); + }; + return WindowsScriptHostExec; +})(); + +var NodeExec = (function () { + function NodeExec() { + } + NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var nodeExec = require('child_process').exec; + + var result = new ExecResult(); + result.exitCode = null; + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); + + var process = nodeExec(cmdLine, function (error, stdout, stderr) { + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + handleResult(result); + }); + }; + return NodeExec; +})(); + +var Exec = (function () { + var global = Function("return this;").call(null); + if (typeof global.ActiveXObject !== "undefined") { + return new WindowsScriptHostExec(); + } else { + return new NodeExec(); + } +})(); +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if (ioHost.directoryExists(dirName)) { + return; + } + + var parentDirectory = ioHost.dirName(dirName); + if (parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + + function createFileAndFolderStructure(ioHost, fileName, useUTF8) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; + + function throwIOError(message, error) { + var errorMessage = message; + if (error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + + function getStreamObject() { + if (streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + + return { + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + streamObj.Charset = 'x-ansi'; + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + streamObj.Position = 0; + if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { + streamObj.Charset = 'unicode'; + } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { + streamObj.Charset = 'utf-8'; + } + + var str = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + writeFile: function (path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + + while (true) { + if (fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + } + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + + if (rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + createFile: function (path, useUTF8) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { + streamObj.WriteText(str, 0); + }, + WriteLine: function (str) { + streamObj.WriteText(str, 1); + }, + Close: function () { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + } finally { + if (streamObj.State != 0) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || {}; + function filesInFolder(folder, root) { + var paths = []; + var fc; + + if (options.recursive) { + fc = new Enumerator(folder.subfolders); + + for (; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + + fc = new Enumerator(folder.files); + + for (; !fc.atEnd(); fc.moveNext()) { + if (!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + + return paths; + } + + var folder = fso.GetFolder(path); + var paths = []; + + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; + + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + + return { + readFile: function (file) { + try { + var buffer = _fs.readFileSync(file); + switch (buffer[0]) { + case 0xFE: + if (buffer[1] == 0xFF) { + var i = 0; + while ((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + case 0xFF: + if (buffer[1] == 0xFE) { + return buffer.toString("ucs2", 2); + } + break; + case 0xEF: + if (buffer[1] == 0xBB) { + return buffer.toString("utf8", 3); + } + } + + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: _fs.writeFileSync, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + createFile: function (path, useUTF8) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 0775); + } + } + + mkdirRecursiveSync(_path.dirname(path)); + + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return { + Write: function (str) { + _fs.writeSync(fd, str); + }, + WriteLine: function (str) { + _fs.writeSync(fd, str + '\r\n'); + }, + Close: function () { + _fs.closeSync(fd); + fd = null; + } + }; + }, + dir: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder, deep) { + var paths = []; + + var files = _fs.readdirSync(folder); + for (var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if (options.recursive && stat.isDirectory()) { + if (deep < (options.deep || 100)) { + paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); + } + } else if (stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + + return paths; + } + + return filesInFolder(path, 0); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + + while (true) { + if (_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + } + } else { + var parentPath = _path.resolve(rootPath, ".."); + + if (rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (filename, callback) { + var firstRun = true; + var processingChange = false; + + var fileChanged = function (curr, prev) { + if (!firstRun) { + if (curr.mtime < prev.mtime) { + return; + } + + _fs.unwatchFile(filename, fileChanged); + if (!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); + }; + + fileChanged(); + return { + filename: filename, + close: function () { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function (source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; + + if (typeof ActiveXObject === "function") + return getWindowsScriptHostIO(); else if (typeof require === "function") + return getNodeIO(); else + return null; +})(); +var DefinitelyTyped; +(function (DefinitelyTyped) { + (function (TestManager) { + var path = require('path'); + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + var Iterator = (function () { + function Iterator(list) { + this.list = list; + this.index = -1; + } + Iterator.prototype.next = function () { + this.index++; + return this.list[this.index]; + }; + + Iterator.prototype.hasNext = function () { + return this.list[1 + this.index] != null; + }; + return Iterator; + })(); + + var Tsc = (function () { + function Tsc() { + } + Tsc.run = function (tsfile, callback) { + Exec.exec('node ./_infrastructure/tests/typescript/tsc.js ', [tsfile], function (ExecResult) { + callback(ExecResult); + }); + }; + return Tsc; + })(); + + var Test = (function () { + function Test(tsfile) { + this.tsfile = tsfile; + } + Test.prototype.run = function (callback) { + Tsc.run(this.tsfile, callback); + }; + return Test; + })(); + + var Typing = (function () { + function Typing(name, baseDir) { + this.name = name; + this.fileHandler = new FileHandler(baseDir + '/' + name + '/', /.\.ts/g); + } + return Typing; + })(); + + var FileHandler = (function () { + function FileHandler(path, pattern) { + this.path = path; + this.files = []; + this.typings = []; + this.files = IO.dir(path, pattern, { recursive: true }); + } + FileHandler.prototype.allTS = function () { + return this.files; + }; + + FileHandler.prototype.allTests = function () { + var tests = []; + + for (var i = 0; i < this.files.length; i++) { + if (endsWith(this.files[i].toUpperCase(), '-TESTS.TS')) { + tests.push(this.files[i]); + } + } + + return tests; + }; + + FileHandler.prototype.allTypings = function () { + var typings = {}; + + for (var i = 0; i < this.files.length; i++) { + var file = this.files[i]; + var firName = path.dirname(file.substr(this.path.length + 1)).replace('\\', '/'); + var dir = firName.split('/')[0]; + + if (!typings[dir]) + typings[dir] = true; + } + + var list = []; + for (var attr in typings) { + list.push(attr); + } + + return list; + }; + return FileHandler; + })(); + + var Timer = (function () { + function Timer() { + this.time = 0; + } + Timer.prettyDate = function (date1, date2) { + var diff = ((date2 - date1) / 1000), day_diff = Math.floor(diff / 86400); + + if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) + return; + + return (day_diff == 0 && (diff < 60 && (diff + " secconds") || diff < 120 && "1 minute" || diff < 3600 && Math.floor(diff / 60) + " minutes" || diff < 7200 && "1 hour" || diff < 86400 && Math.floor(diff / 3600) + " hours") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks"); + }; + + Timer.prototype.start = function () { + this.time = 0; + this.startTime = this.now(); + }; + + Timer.prototype.now = function () { + return Date.now(); + }; + + Timer.prototype.end = function () { + this.time = (this.now() - this.startTime) / 1000; + this.asString = Timer.prettyDate(this.startTime, this.now()); + }; + return Timer; + })(); + + var Print = (function () { + function Print(version, typings, tsFiles) { + this.version = version; + this.typings = typings; + this.tsFiles = tsFiles; + } + Print.prototype.out = function (s) { + process.stdout.write(s); + }; + + Print.prototype.printHeader = function () { + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.2.0\33[0m\n'); + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); + this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); + this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); + }; + + Print.prototype.printSyntaxCheking = function () { + this.out('============================ \33[34m\33[1mSyntax cheking\33[0m =================================\n'); + }; + + Print.prototype.printTypingTests = function () { + this.out('============================= \33[34m\33[1mTyping tests\33[0m ==================================\n'); + }; + + Print.prototype.printSuccess = function () { + this.out('\33[36m\33[1m.\33[0m'); + }; + + Print.prototype.printFailure = function () { + this.out('x'); + }; + + Print.prototype.printDiv = function () { + this.out('-----------------------------------------------------------------------------\n'); + }; + + Print.prototype.printfilesWithSintaxErrorMessage = function () { + this.out(' \33[36m\33[1mFiles with syntax error\33[0m\n'); + }; + + Print.prototype.printFailedTestMessage = function () { + this.out(' \33[36m\33[1mFailed tests\33[0m\n'); + }; + + Print.prototype.printTypingsWithoutTestsMessage = function () { + this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); + }; + + Print.prototype.printTotalMessage = function () { + this.out(' \33[36m\33[1mTotal\33[0m\n'); + }; + + Print.prototype.printErrorFile = function (file) { + this.out(' - ' + file + '\n'); + }; + + Print.prototype.printTypingsWithoutTest = function (file) { + this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); + }; + + Print.prototype.breack = function () { + this.out('\n'); + }; + + Print.prototype.printSuccessCount = function (current, total) { + this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printFailedCount = function (current, total) { + this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printElapsedTime = function (time, s) { + this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); + }; + + Print.prototype.printSyntaxErrorCount = function (current, total) { + this.out(' \33[36m\33[1mSyntaxe error :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printTestErrorCount = function (current, total) { + this.out(' \33[36m\33[1mFailed tests :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printWithoutTestCount = function (current, total) { + this.out(' \33[36m\33[1mWithout tests :\33[0m \33[33m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + return Print; + })(); + + var File = (function () { + function File(name, hasError) { + this.name = name; + this.hasError = hasError; + } + File.prototype.formatName = function (baseDir) { + var dirName = path.dirname(this.name.substr(baseDir.length + 1)).replace('\\', '/'); + var dir = dirName.split('/')[0]; + var file = path.basename(this.name, '.ts'); + var ext = path.extname(this.name); + + return dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + '\33[36m\33[1m' + file + '\33[0m' + ext; + }; + return File; + })(); + + var SyntaxCheking = (function () { + function SyntaxCheking(fielHandler, out) { + this.fielHandler = fielHandler; + this.out = out; + this.files = []; + this.timer = new Timer(); + } + SyntaxCheking.prototype.getFailedFiles = function () { + var list = []; + + for (var i = 0; i < this.files.length; i++) { + if (this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + }; + + SyntaxCheking.prototype.getSuccessFiles = function () { + var list = []; + + for (var i = 0; i < this.files.length; i++) { + if (!this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + }; + + SyntaxCheking.prototype.printStats = function () { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + }; + + SyntaxCheking.prototype.printFailedFiles = function () { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printfilesWithSintaxErrorMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName(this.fielHandler.path)); + } + } + }; + + SyntaxCheking.prototype.run = function (it, file, len, maxLen, callback) { + var _this = this; + if (!endsWith(file, '-tests.ts')) { + new Test(file).run(function (o) { + var failed = false; + + if (o.exitCode === 1) { + _this.out.printFailure(); + failed = true; + len++; + } else { + _this.out.printSuccess(); + len++; + } + + _this.files.push(new File(file, failed)); + + if (len > maxLen) { + len = 0; + _this.out.breack(); + } + + if (it.hasNext()) { + _this.run(it, it.next(), len, maxLen, callback); + } else { + _this.out.breack(); + _this.timer.end(); + _this.printFailedFiles(); + _this.printStats(); + + callback(_this.getFailedFiles().length, _this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printStats(); + this.printFailedFiles(); + + callback(this.getFailedFiles().length, this.files.length); + } + }; + + SyntaxCheking.prototype.start = function (callback) { + this.timer.start(); + + var tsFiles = this.fielHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + }; + return SyntaxCheking; + })(); + + var TestEval = (function () { + function TestEval(fielHandler, out) { + this.fielHandler = fielHandler; + this.out = out; + this.files = []; + this.timer = new Timer(); + } + TestEval.prototype.getFailedFiles = function () { + var list = []; + + for (var i = 0; i < this.files.length; i++) { + if (this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + }; + + TestEval.prototype.getSuccessFiles = function () { + var list = []; + + for (var i = 0; i < this.files.length; i++) { + if (!this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + }; + + TestEval.prototype.printStats = function () { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + }; + + TestEval.prototype.printFailedFiles = function () { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printFailedTestMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName(this.fielHandler.path)); + } + } + }; + + TestEval.prototype.run = function (it, file, len, maxLen, callback) { + var _this = this; + if (endsWith(file, '-tests.ts')) { + new Test(file).run(function (o) { + var failed = false; + + if (o.exitCode === 1) { + _this.out.printFailure(); + failed = true; + len++; + } else { + _this.out.printSuccess(); + len++; + } + + _this.files.push(new File(file, failed)); + + if (len > maxLen) { + len = 0; + _this.out.breack(); + } + + if (it.hasNext()) { + _this.run(it, it.next(), len, maxLen, callback); + } else { + _this.out.breack(); + _this.timer.end(); + _this.printFailedFiles(); + _this.printStats(); + + callback(_this.getFailedFiles().length, _this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + }; + + TestEval.prototype.start = function (callback) { + this.timer.start(); + + var tsFiles = this.fielHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + }; + return TestEval; + })(); + + var TestRunner = (function () { + function TestRunner(dtPath) { + this.dtPath = dtPath; + this.typings = []; + this.fh = new FileHandler(dtPath, /.\.ts/g); + this.out = new Print('0.9.0.0', this.fh.allTypings().length, this.fh.allTS().length); + this.sc = new SyntaxCheking(this.fh, this.out); + this.te = new TestEval(this.fh, this.out); + + var tpgs = this.fh.allTypings(); + for (var i = 0; i < tpgs.length; i++) { + this.typings.push(new Typing(tpgs[i], this.dtPath)); + } + } + TestRunner.prototype.printTypingsWithoutTest = function () { + var count = 0; + + if (this.typings.length > 0) { + this.out.printDiv(); + + this.out.printTypingsWithoutTestsMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.typings.length; i++) { + var typing = this.typings[i]; + if (typing.fileHandler.allTests().length == 0) { + if (typing.name != '_infrastructure' && typing.name != '_ReSharper.DefinitelyTyped' && typing.name != 'obj' && typing.name != 'bin' && typing.name != 'Properties') { + this.out.printTypingsWithoutTest(typing.name); + count++; + } + } + } + } + + return count; + }; + + TestRunner.prototype.run = function () { + var _this = this; + var timer = new Timer(); + timer.start(); + + this.out.printHeader(); + this.out.printSyntaxCheking(); + + this.sc.start(function (syntaxFailedCount, syntaxTotal) { + _this.out.printTypingTests(); + _this.te.start(function (testFailedCount, testTotal) { + var total = _this.printTypingsWithoutTest(); + + timer.end(); + + _this.out.printDiv(); + _this.out.printTotalMessage(); + _this.out.printDiv(); + + _this.out.printElapsedTime(timer.asString, timer.time); + _this.out.printSyntaxErrorCount(syntaxFailedCount, syntaxTotal); + _this.out.printTestErrorCount(testFailedCount, testTotal); + _this.out.printWithoutTestCount(total, _this.fh.allTypings().length); + + _this.out.printDiv(); + + if (syntaxFailedCount > 0 || testFailedCount > 0) { + process.exit(1); + } + }); + }); + }; + return TestRunner; + })(); + TestManager.TestRunner = TestRunner; + })(DefinitelyTyped.TestManager || (DefinitelyTyped.TestManager = {})); + var TestManager = DefinitelyTyped.TestManager; +})(DefinitelyTyped || (DefinitelyTyped = {})); + +var dtPath = __dirname + '/../..'; + +var runner = new DefinitelyTyped.TestManager.TestRunner(dtPath); +runner.run(); diff --git a/_infrastructure/tests/runner.ts b/_infrastructure/tests/runner.ts new file mode 100644 index 000000000..175194755 --- /dev/null +++ b/_infrastructure/tests/runner.ts @@ -0,0 +1,557 @@ +/// +/// + +module DefinitelyTyped { + + export module TestManager { + + var path = require('path'); + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + class Iterator { + index: number = -1; + + constructor(public list: any[]){} + + public next() { + this.index++; + return this.list[this.index]; + } + + public hasNext() { + return this.list[1 + this.index] != null; + } + } + + class Tsc { + public static run(tsfile: string, callback: Function) { + Exec.exec('node ./_infrastructure/tests/typescript/tsc.js ', [tsfile], (ExecResult) => { + callback(ExecResult); + }); + } + } + + class Test { + constructor(public tsfile: string) {} + + public run(callback: Function) { + Tsc.run(this.tsfile , callback); + } + } + + class Typing { + public fileHandler: FileHandler; + + constructor(public name: string, baseDir: string) { + this.fileHandler = new FileHandler(baseDir + '/' + name + '/', /.\.ts/g); + } + } + + class FileHandler { + public files: string[] = []; + public typings: Typing[] = []; + + constructor(public path: string, pattern: any) { + this.files = IO.dir(path, pattern, { recursive: true }); + } + + public allTS(): string[] { + return this.files; + } + + public allTests(): string[] { + var tests = []; + + for(var i = 0; i < this.files.length; i++) { + if (endsWith(this.files[i].toUpperCase(), '-TESTS.TS')) { + tests.push(this.files[i]); + } + } + + return tests; + } + + public allTypings(): string[] { + var typings = {}; + + for(var i = 0; i < this.files.length; i++) { + var file = this.files[i]; + var firName = path.dirname(file.substr(this.path.length + 1)).replace('\\', '/'); + var dir = firName.split('/')[0]; + + if(!typings[dir]) typings[dir] = true; + } + + var list = []; + for(var attr in typings) { + list.push(attr); + } + + return list; + } + } + + class Timer { + public startTime; + public time = 0; + public asString: string; + + private static prettyDate(date1, date2): string { + var diff = ((date2 - date1) / 1000), + day_diff = Math.floor(diff / 86400); + + if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ) + return; + + return (day_diff == 0 && ( + diff < 60 && (diff + " secconds") || + diff < 120 && "1 minute" || + diff < 3600 && Math.floor( diff / 60 ) + " minutes" || + diff < 7200 && "1 hour" || + diff < 86400 && Math.floor( diff / 3600 ) + " hours") || + day_diff == 1 && "Yesterday" || + day_diff < 7 && day_diff + " days" || + day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks"); + } + + public start() { + this.time = 0; + this.startTime = this.now(); + } + + private now() { + return Date.now(); + } + + public end() { + this.time = (this.now() - this.startTime) / 1000; + this.asString = Timer.prettyDate(this.startTime, this.now()); + } + } + + class Print { + constructor(public version: string, public typings: number, public tsFiles: number) { } + + public out(s) { + process.stdout.write(s); + } + + public printHeader() { + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.2.0\33[0m\n'); + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); + this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); + this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); + } + + public printSyntaxCheking() { + this.out('============================ \33[34m\33[1mSyntax cheking\33[0m =================================\n'); + } + + public printTypingTests() { + this.out('============================= \33[34m\33[1mTyping tests\33[0m ==================================\n'); + } + + public printSuccess() { + this.out('\33[36m\33[1m.\33[0m'); + } + + public printFailure() { + this.out('x'); + } + + public printDiv() { + this.out('-----------------------------------------------------------------------------\n'); + } + + public printfilesWithSintaxErrorMessage() { + this.out(' \33[36m\33[1mFiles with syntax error\33[0m\n'); + } + + public printFailedTestMessage() { + this.out(' \33[36m\33[1mFailed tests\33[0m\n'); + } + + public printTypingsWithoutTestsMessage() { + this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); + } + + public printTotalMessage() { + this.out(' \33[36m\33[1mTotal\33[0m\n'); + } + + public printErrorFile(file) { + this.out(' - ' + file + '\n'); + } + + public printTypingsWithoutTest(file) { + this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); + } + + public breack() { + this.out('\n'); + } + + public printSuccessCount(current: number, total: number) { + this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printFailedCount(current: number, total: number) { + this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printElapsedTime(time, s) { + this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); + } + + public printSyntaxErrorCount(current: number, total: number) { + this.out(' \33[36m\33[1mSyntaxe error :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printTestErrorCount(current: number, total: number) { + this.out(' \33[36m\33[1mFailed tests :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printWithoutTestCount(current: number, total: number) { + this.out(' \33[36m\33[1mWithout tests :\33[0m \33[33m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + } + + class File { + + constructor(public name: string, public hasError: boolean) {} + + public formatName(baseDir: string): string { + var dirName = path.dirname(this.name.substr(baseDir.length + 1)).replace('\\', '/'); + var dir = dirName.split('/')[0]; + var file = path.basename(this.name, '.ts'); + var ext = path.extname(this.name); + + return dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + '\33[36m\33[1m' + file + '\33[0m' + ext; + } + } + + class SyntaxCheking { + + private timer: Timer; + + public files: File[] = []; + + private getFailedFiles(): File[] { + var list: File[] = []; + + for(var i = 0; i < this.files.length; i++) { + if(this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + } + + private getSuccessFiles(): File[] { + var list: File[] = []; + + for(var i = 0; i < this.files.length; i++) { + if(!this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + } + + constructor(public fielHandler: FileHandler, public out: Print) { + this.timer = new Timer(); + } + + private printStats() { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + } + + private printFailedFiles() { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printfilesWithSintaxErrorMessage(); + + this.out.printDiv(); + + for(var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName(this.fielHandler.path)); + } + } + } + + private run(it, file, len, maxLen, callback: Function) { + if (!endsWith(file, '-tests.ts')) { + new Test(file).run((o) => { + var failed = false; + + if(o.exitCode === 1) { + this.out.printFailure(); + failed = true; + len++; + } else { + this.out.printSuccess(); + len++; + } + + this.files.push(new File(file, failed)); + + if(len > maxLen) { + len = 0; + this.out.breack(); + } + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printStats(); + this.printFailedFiles(); + + callback(this.getFailedFiles().length, this.files.length); + } + } + + public start(callback: Function) { + this.timer.start(); + + var tsFiles = this.fielHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + } + } + + class TestEval { + + private timer: Timer; + + public files: File[] = []; + + private getFailedFiles(): File[] { + var list: File[] = []; + + for(var i = 0; i < this.files.length; i++) { + if(this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + } + + private getSuccessFiles(): File[] { + var list: File[] = []; + + for(var i = 0; i < this.files.length; i++) { + if(!this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + } + + constructor(public fielHandler: FileHandler, public out: Print) { + this.timer = new Timer(); + } + + private printStats() { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + } + + private printFailedFiles() { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printFailedTestMessage(); + + this.out.printDiv(); + + for(var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName(this.fielHandler.path)); + } + } + } + + private run(it, file, len, maxLen, callback: Function) { + if (endsWith(file, '-tests.ts')) { + new Test(file).run((o) => { + var failed = false; + + if(o.exitCode === 1) { + this.out.printFailure(); + failed = true; + len++; + } else { + this.out.printSuccess(); + len++; + } + + this.files.push(new File(file, failed)); + + if(len > maxLen) { + len = 0; + this.out.breack(); + } + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + } + + public start(callback: Function) { + this.timer.start(); + + var tsFiles = this.fielHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + } + } + + export class TestRunner { + private fh: FileHandler; + private out: Print; + private sc: SyntaxCheking; + private te: TestEval; + private typings: Typing[] = []; + + private printTypingsWithoutTest() { + var count = 0; + + if (this.typings.length > 0) { + this.out.printDiv(); + + this.out.printTypingsWithoutTestsMessage(); + + this.out.printDiv(); + + for(var i = 0; i < this.typings.length; i++) { + var typing = this.typings[i]; + if(typing.fileHandler.allTests().length == 0) { + if (typing.name != '_infrastructure' + && typing.name != '_ReSharper.DefinitelyTyped' + && typing.name != 'obj' + && typing.name != 'bin' + && typing.name != 'Properties') { + this.out.printTypingsWithoutTest(typing.name); + count++; + } + } + } + } + + return count; + } + + constructor(public dtPath: string) { + this.fh = new FileHandler(dtPath, /.\.ts/g); + this.out = new Print('0.9.0.0', this.fh.allTypings().length, this.fh.allTS().length); + this.sc = new SyntaxCheking(this.fh, this.out); + this.te = new TestEval(this.fh, this.out); + + var tpgs = this.fh.allTypings(); + for(var i = 0; i < tpgs.length; i++) { + this.typings.push(new Typing(tpgs[i], this.dtPath)); + } + } + + public run() { + var timer = new Timer(); + timer.start(); + + this.out.printHeader(); + this.out.printSyntaxCheking(); + + this.sc.start((syntaxFailedCount, syntaxTotal) => { + this.out.printTypingTests(); + this.te.start((testFailedCount, testTotal) => { + var total = this.printTypingsWithoutTest(); + + timer.end(); + + this.out.printDiv(); + this.out.printTotalMessage(); + this.out.printDiv(); + + this.out.printElapsedTime(timer.asString, timer.time); + this.out.printSyntaxErrorCount(syntaxFailedCount, syntaxTotal); + this.out.printTestErrorCount(testFailedCount, testTotal); + this.out.printWithoutTestCount(total, this.fh.allTypings().length); + + this.out.printDiv(); + + if (syntaxFailedCount > 0 || testFailedCount > 0) { + process.exit(1); + } + }); + }); + } + } + } +} + +declare var __dirname: any; + +var dtPath = __dirname + '/../..'; + +var runner = new DefinitelyTyped.TestManager.TestRunner(dtPath); +runner.run(); diff --git a/_infrastructure/tests/src/exec.js b/_infrastructure/tests/src/exec.js index 8c18ab42d..f6c3d257c 100644 --- a/_infrastructure/tests/src/exec.js +++ b/_infrastructure/tests/src/exec.js @@ -1,65 +1,65 @@ -var ExecResult = (function () { - function ExecResult() { - this.stdout = ""; - this.stderr = ""; - } - return ExecResult; -})(); - -var WindowsScriptHostExec = (function () { - function WindowsScriptHostExec() { - } - WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var result = new ExecResult(); - var shell = new ActiveXObject('WScript.Shell'); - try { - var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); - } catch (e) { - result.stderr = e.message; - result.exitCode = 1; - handleResult(result); - return; - } - - while (process.Status != 0) { - } - - result.exitCode = process.ExitCode; - if (!process.StdOut.AtEndOfStream) - result.stdout = process.StdOut.ReadAll(); - if (!process.StdErr.AtEndOfStream) - result.stderr = process.StdErr.ReadAll(); - - handleResult(result); - }; - return WindowsScriptHostExec; -})(); - -var NodeExec = (function () { - function NodeExec() { - } - NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var nodeExec = require('child_process').exec; - - var result = new ExecResult(); - result.exitCode = null; - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - - var process = nodeExec(cmdLine, function (error, stdout, stderr) { - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - handleResult(result); - }); - }; - return NodeExec; -})(); - -var Exec = (function () { - var global = Function("return this;").call(null); - if (typeof global.ActiveXObject !== "undefined") { - return new WindowsScriptHostExec(); - } else { - return new NodeExec(); - } -})(); +var ExecResult = (function () { + function ExecResult() { + this.stdout = ""; + this.stderr = ""; + } + return ExecResult; +})(); + +var WindowsScriptHostExec = (function () { + function WindowsScriptHostExec() { + } + WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var result = new ExecResult(); + var shell = new ActiveXObject('WScript.Shell'); + try { + var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); + } catch (e) { + result.stderr = e.message; + result.exitCode = 1; + handleResult(result); + return; + } + + while (process.Status != 0) { + } + + result.exitCode = process.ExitCode; + if (!process.StdOut.AtEndOfStream) + result.stdout = process.StdOut.ReadAll(); + if (!process.StdErr.AtEndOfStream) + result.stderr = process.StdErr.ReadAll(); + + handleResult(result); + }; + return WindowsScriptHostExec; +})(); + +var NodeExec = (function () { + function NodeExec() { + } + NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var nodeExec = require('child_process').exec; + + var result = new ExecResult(); + result.exitCode = null; + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); + + var process = nodeExec(cmdLine, function (error, stdout, stderr) { + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + handleResult(result); + }); + }; + return NodeExec; +})(); + +var Exec = (function () { + var global = Function("return this;").call(null); + if (typeof global.ActiveXObject !== "undefined") { + return new WindowsScriptHostExec(); + } else { + return new NodeExec(); + } +})(); diff --git a/_infrastructure/tests/src/io.js b/_infrastructure/tests/src/io.js index 772e97c02..0058d59f9 100644 --- a/_infrastructure/tests/src/io.js +++ b/_infrastructure/tests/src/io.js @@ -1,443 +1,445 @@ -var IOUtils; -(function (IOUtils) { - function createDirectoryStructure(ioHost, dirName) { - if (ioHost.directoryExists(dirName)) { - return; - } - - var parentDirectory = ioHost.dirName(dirName); - if (parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - - function createFileAndFolderStructure(ioHost, fileName, useUTF8) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; - - function throwIOError(message, error) { - var errorMessage = message; - if (error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } - IOUtils.throwIOError = throwIOError; -})(IOUtils || (IOUtils = {})); - -var IO = (function () { - function getWindowsScriptHostIO() { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - - function getStreamObject() { - if (streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - - function releaseStreamObject(obj) { - streamObjectPool.push(obj); - } - - var args = []; - for (var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - - return { - readFile: function (path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; - streamObj.Charset = 'x-ansi'; - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); - streamObj.Position = 0; - if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { - streamObj.Charset = 'unicode'; - } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { - streamObj.Charset = 'utf-8'; - } - - var str = streamObj.ReadText(-1); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - writeFile: function (path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - fileExists: function (path) { - return fso.FileExists(path); - }, - resolvePath: function (path) { - return fso.GetAbsolutePathName(path); - }, - dirName: function (path) { - return fso.GetParentFolderName(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - - while (true) { - if (fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - } - } else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - - if (rootPath == "") { - return null; - } else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - deleteFile: function (path) { - try { - if (fso.FileExists(path)) { - fso.DeleteFile(path, true); - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - createFile: function (path, useUTF8) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { - streamObj.WriteText(str, 0); - }, - WriteLine: function (str) { - streamObj.WriteText(str, 1); - }, - Close: function () { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - } finally { - if (streamObj.State != 0) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - directoryExists: function (path) { - return fso.FolderExists(path); - }, - createDirectory: function (path) { - try { - if (!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - dir: function (path, spec, options) { - options = options || {}; - function filesInFolder(folder, root) { - var paths = []; - var fc; - - if (options.recursive) { - fc = new Enumerator(folder.subfolders); - - for (; !fc.atEnd(); fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - - fc = new Enumerator(folder.files); - - for (; !fc.atEnd(); fc.moveNext()) { - if (!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - - return paths; - } - - var folder = fso.GetFolder(path); - var paths = []; - - return filesInFolder(folder, path); - }, - print: function (str) { - WScript.StdOut.Write(str); - }, - printLine: function (str) { - WScript.Echo(str); - }, - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function (source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode) { - if (typeof exitCode === "undefined") { exitCode = 0; } - try { - WScript.Quit(exitCode); - } catch (e) { - } - } - }; - } - ; - - function getNodeIO() { - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); - - return { - readFile: function (file) { - try { - var buffer = _fs.readFileSync(file); - switch (buffer[0]) { - case 0xFE: - if (buffer[1] == 0xFF) { - var i = 0; - while ((i + 1) < buffer.length) { - var temp = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - case 0xFF: - if (buffer[1] == 0xFE) { - return buffer.toString("ucs2", 2); - } - break; - case 0xEF: - if (buffer[1] == 0xBB) { - return buffer.toString("utf8", 3); - } - } - - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: _fs.writeFileSync, - deleteFile: function (path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - createFile: function (path, useUTF8) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if (stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else if (stats.isDirectory()) { - return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 0775); - } - } - - mkdirRecursiveSync(_path.dirname(path)); - - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return { - Write: function (str) { - _fs.writeSync(fd, str); - }, - WriteLine: function (str) { - _fs.writeSync(fd, str + '\r\n'); - }, - Close: function () { - _fs.closeSync(fd); - fd = null; - } - }; - }, - dir: function dir(path, spec, options) { - options = options || {}; - - function filesInFolder(folder) { - var paths = []; - - var files = _fs.readdirSync(folder); - for (var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if (options.recursive && stat.isDirectory()) { - paths = paths.concat(filesInFolder(folder + "/" + files[i])); - } else if (stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - - return paths; - } - - return filesInFolder(path); - }, - createDirectory: function (path) { - try { - if (!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function (path) { - return _path.resolve(path); - }, - dirName: function (path) { - return _path.dirname(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = rootPath + "/" + partialFilePath; - - while (true) { - if (_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - } - } else { - var parentPath = _path.resolve(rootPath, ".."); - - if (rootPath === parentPath) { - return null; - } else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); - } - } - } - }, - print: function (str) { - process.stdout.write(str); - }, - printLine: function (str) { - process.stdout.write(str + '\n'); - }, - arguments: process.argv.slice(2), - stderr: { - Write: function (str) { - process.stderr.write(str); - }, - WriteLine: function (str) { - process.stderr.write(str + '\n'); - }, - Close: function () { - } - }, - stdout: { - Write: function (str) { - process.stdout.write(str); - }, - WriteLine: function (str) { - process.stdout.write(str + '\n'); - }, - Close: function () { - } - }, - watchFile: function (filename, callback) { - var firstRun = true; - var processingChange = false; - - var fileChanged = function (curr, prev) { - if (!firstRun) { - if (curr.mtime < prev.mtime) { - return; - } - - _fs.unwatchFile(filename, fileChanged); - if (!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function () { - processingChange = false; - }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); - }; - - fileChanged(); - return { - filename: filename, - close: function () { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function (source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit - }; - } - ; - - if (typeof ActiveXObject === "function") - return getWindowsScriptHostIO(); else if (typeof require === "function") - return getNodeIO(); else - return null; -})(); +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if (ioHost.directoryExists(dirName)) { + return; + } + + var parentDirectory = ioHost.dirName(dirName); + if (parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + + function createFileAndFolderStructure(ioHost, fileName, useUTF8) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; + + function throwIOError(message, error) { + var errorMessage = message; + if (error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + + function getStreamObject() { + if (streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + + return { + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + streamObj.Charset = 'x-ansi'; + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + streamObj.Position = 0; + if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { + streamObj.Charset = 'unicode'; + } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { + streamObj.Charset = 'utf-8'; + } + + var str = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + writeFile: function (path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + + while (true) { + if (fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + } + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + + if (rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + createFile: function (path, useUTF8) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { + streamObj.WriteText(str, 0); + }, + WriteLine: function (str) { + streamObj.WriteText(str, 1); + }, + Close: function () { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + } finally { + if (streamObj.State != 0) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || {}; + function filesInFolder(folder, root) { + var paths = []; + var fc; + + if (options.recursive) { + fc = new Enumerator(folder.subfolders); + + for (; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + + fc = new Enumerator(folder.files); + + for (; !fc.atEnd(); fc.moveNext()) { + if (!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + + return paths; + } + + var folder = fso.GetFolder(path); + var paths = []; + + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; + + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + + return { + readFile: function (file) { + try { + var buffer = _fs.readFileSync(file); + switch (buffer[0]) { + case 0xFE: + if (buffer[1] == 0xFF) { + var i = 0; + while ((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + case 0xFF: + if (buffer[1] == 0xFE) { + return buffer.toString("ucs2", 2); + } + break; + case 0xEF: + if (buffer[1] == 0xBB) { + return buffer.toString("utf8", 3); + } + } + + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: _fs.writeFileSync, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + createFile: function (path, useUTF8) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 0775); + } + } + + mkdirRecursiveSync(_path.dirname(path)); + + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return { + Write: function (str) { + _fs.writeSync(fd, str); + }, + WriteLine: function (str) { + _fs.writeSync(fd, str + '\r\n'); + }, + Close: function () { + _fs.closeSync(fd); + fd = null; + } + }; + }, + dir: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder, deep) { + var paths = []; + + var files = _fs.readdirSync(folder); + for (var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if (options.recursive && stat.isDirectory()) { + if (deep < (options.deep || 100)) { + paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); + } + } else if (stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + + return paths; + } + + return filesInFolder(path, 0); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + + while (true) { + if (_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + } + } else { + var parentPath = _path.resolve(rootPath, ".."); + + if (rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (filename, callback) { + var firstRun = true; + var processingChange = false; + + var fileChanged = function (curr, prev) { + if (!firstRun) { + if (curr.mtime < prev.mtime) { + return; + } + + _fs.unwatchFile(filename, fileChanged); + if (!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); + }; + + fileChanged(); + return { + filename: filename, + close: function () { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function (source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; + + if (typeof ActiveXObject === "function") + return getWindowsScriptHostIO(); else if (typeof require === "function") + return getNodeIO(); else + return null; +})(); diff --git a/_infrastructure/tests/src/io.ts b/_infrastructure/tests/src/io.ts index 3c68154a1..9c5345136 100644 --- a/_infrastructure/tests/src/io.ts +++ b/_infrastructure/tests/src/io.ts @@ -25,11 +25,11 @@ interface IFileWatcher { interface IIO { readFile(path: string): string; writeFile(path: string, contents: string): void; - createFile(path: string, useUTF8?: boolean): ITextWriter; + createFile(path: string, useUTF8?: bool): ITextWriter; deleteFile(path: string): void; - dir(path: string, re?: RegExp, options?: { recursive?: boolean; }): string[]; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; + dir(path: string, re?: RegExp, options?: { recursive?: bool; deep?: number; }): string[]; + fileExists(path: string): bool; + directoryExists(path: string): bool; createDirectory(path: string): void; resolvePath(path: string): string; dirName(path: string): string; @@ -60,7 +60,7 @@ module IOUtils { } // Creates a file including its directory structure if not already present - export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: boolean) { + export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: bool) { var path = ioHost.resolvePath(fileName); var dirName = ioHost.dirName(path); createDirectoryStructure(ioHost, dirName); @@ -78,13 +78,13 @@ module IOUtils { // Declare dependencies needed for all supported hosts declare class Enumerator { - public atEnd(): boolean; + public atEnd(): bool; public moveNext(); public item(): any; constructor (o: any); } declare function setTimeout(callback: () =>void , ms?: number); -declare var require: any; +//declare var require: any; declare module process { export var argv: string[]; export var platform: string; @@ -160,7 +160,7 @@ var IO = (function() { file.Close(); }, - fileExists: function(path: string): boolean { + fileExists: function(path: string): bool { return fso.FileExists(path); }, @@ -236,7 +236,7 @@ var IO = (function() { }, directoryExists: function(path) { - return fso.FolderExists(path); + return fso.FolderExists(path); }, createDirectory: function(path) { @@ -250,7 +250,7 @@ var IO = (function() { }, dir: function(path, spec?, options?) { - options = options || <{ recursive?: boolean; }>{}; + options = options || <{ recursive?: bool; deep?: number; }>{}; function filesInFolder(folder, root): string[]{ var paths = []; var fc: Enumerator; @@ -365,7 +365,7 @@ var IO = (function() { IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); } }, - fileExists: function(path): boolean { + fileExists: function(path): bool { return _fs.existsSync(path); }, createFile: function(path, useUTF8?) { @@ -395,16 +395,18 @@ var IO = (function() { }; }, dir: function dir(path, spec?, options?) { - options = options || <{ recursive?: boolean; }>{}; + options = options || <{ recursive?: bool; deep?: number; }>{}; - function filesInFolder(folder: string): string[]{ + function filesInFolder(folder: string, deep?: number): string[]{ var paths = []; var files = _fs.readdirSync(folder); for (var i = 0; i < files.length; i++) { var stat = _fs.statSync(folder + "/" + files[i]); if (options.recursive && stat.isDirectory()) { - paths = paths.concat(filesInFolder(folder + "/" + files[i])); + if (deep < (options.deep || 100)) { + paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); + } } else if (stat.isFile() && (!spec || files[i].match(spec))) { paths.push(folder + "/" + files[i]); } @@ -413,7 +415,7 @@ var IO = (function() { return paths; } - return filesInFolder(path); + return filesInFolder(path, 0); }, createDirectory: function(path: string): void { try { @@ -425,7 +427,7 @@ var IO = (function() { } }, - directoryExists: function(path: string): boolean { + directoryExists: function(path: string): bool { return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); }, resolvePath: function(path: string): string { diff --git a/_infrastructure/tests/testRunner.js b/_infrastructure/tests/testRunner.js deleted file mode 100644 index a2f54dd5f..000000000 --- a/_infrastructure/tests/testRunner.js +++ /dev/null @@ -1,619 +0,0 @@ -var ExecResult = (function () { - function ExecResult() { - this.stdout = ""; - this.stderr = ""; - } - return ExecResult; -})(); -var WindowsScriptHostExec = (function () { - function WindowsScriptHostExec() { } - WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var result = new ExecResult(); - var shell = new ActiveXObject('WScript.Shell'); - try { - var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); - } catch (e) { - result.stderr = e.message; - result.exitCode = 1; - handleResult(result); - return; - } - while(process.Status != 0) { - } - result.exitCode = process.ExitCode; - if(!process.StdOut.AtEndOfStream) { - result.stdout = process.StdOut.ReadAll(); - } - if(!process.StdErr.AtEndOfStream) { - result.stderr = process.StdErr.ReadAll(); - } - handleResult(result); - }; - return WindowsScriptHostExec; -})(); -var NodeExec = (function () { - function NodeExec() { } - NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var nodeExec = require('child_process').exec; - var result = new ExecResult(); - result.exitCode = null; - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - var process = nodeExec(cmdLine, function (error, stdout, stderr) { - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - handleResult(result); - }); - }; - return NodeExec; -})(); -var Exec = (function () { - var global = Function("return this;").call(null); - if(typeof global.ActiveXObject !== "undefined") { - return new WindowsScriptHostExec(); - } else { - return new NodeExec(); - } -})(); -var IOUtils; -(function (IOUtils) { - function createDirectoryStructure(ioHost, dirName) { - if(ioHost.directoryExists(dirName)) { - return; - } - var parentDirectory = ioHost.dirName(dirName); - if(parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - function createFileAndFolderStructure(ioHost, fileName, useUTF8) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; - function throwIOError(message, error) { - var errorMessage = message; - if(error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } - IOUtils.throwIOError = throwIOError; -})(IOUtils || (IOUtils = {})); - -var IO = (function () { - function getWindowsScriptHostIO() { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - function getStreamObject() { - if(streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - function releaseStreamObject(obj) { - streamObjectPool.push(obj); - } - var args = []; - for(var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - return { - readFile: function (path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; - streamObj.Charset = 'x-ansi'; - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); - streamObj.Position = 0; - if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) { - streamObj.Charset = 'unicode'; - } else if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) { - streamObj.Charset = 'utf-8'; - } - var str = streamObj.ReadText(-1); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - writeFile: function (path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - fileExists: function (path) { - return fso.FileExists(path); - }, - resolvePath: function (path) { - return fso.GetAbsolutePathName(path); - }, - dirName: function (path) { - return fso.GetParentFolderName(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - while(true) { - if(fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { - content: content, - path: path - }; - } catch (err) { - } - } else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - if(rootPath == "") { - return null; - } else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - deleteFile: function (path) { - try { - if(fso.FileExists(path)) { - fso.DeleteFile(path, true); - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - createFile: function (path, useUTF8) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { - streamObj.WriteText(str, 0); - }, - WriteLine: function (str) { - streamObj.WriteText(str, 1); - }, - Close: function () { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - }finally { - if(streamObj.State != 0) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - directoryExists: function (path) { - return fso.FolderExists(path); - }, - createDirectory: function (path) { - try { - if(!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - dir: function (path, spec, options) { - options = options || { - }; - function filesInFolder(folder, root) { - var paths = []; - var fc; - if(options.recursive) { - fc = new Enumerator(folder.subfolders); - for(; !fc.atEnd(); fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - fc = new Enumerator(folder.files); - for(; !fc.atEnd(); fc.moveNext()) { - if(!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - return paths; - } - var folder = fso.GetFolder(path); - var paths = []; - return filesInFolder(folder, path); - }, - print: function (str) { - WScript.StdOut.Write(str); - }, - printLine: function (str) { - WScript.Echo(str); - }, - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function (source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode) { - if (typeof exitCode === "undefined") { exitCode = 0; } - try { - WScript.Quit(exitCode); - } catch (e) { - } - } - }; - } - ; - function getNodeIO() { - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); - return { - readFile: function (file) { - try { - var buffer = _fs.readFileSync(file); - switch(buffer[0]) { - case 254: - if(buffer[1] == 255) { - var i = 0; - while((i + 1) < buffer.length) { - var temp = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - case 255: - if(buffer[1] == 254) { - return buffer.toString("ucs2", 2); - } - break; - case 239: - if(buffer[1] == 187) { - return buffer.toString("utf8", 3); - } - } - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: _fs.writeFileSync, - deleteFile: function (path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - createFile: function (path, useUTF8) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if(stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else if(stats.isDirectory()) { - return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 775); - } - } - mkdirRecursiveSync(_path.dirname(path)); - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return { - Write: function (str) { - _fs.writeSync(fd, str); - }, - WriteLine: function (str) { - _fs.writeSync(fd, str + '\r\n'); - }, - Close: function () { - _fs.closeSync(fd); - fd = null; - } - }; - }, - dir: function dir(path, spec, options) { - options = options || { - }; - function filesInFolder(folder, deep) { - var paths = []; - var files = _fs.readdirSync(folder); - for(var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if(options.recursive && stat.isDirectory()) { - if(deep < (options.deep || 100)) { - paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); - } - } else if(stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - return paths; - } - return filesInFolder(path, 0); - }, - createDirectory: function (path) { - try { - if(!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function (path) { - return _path.resolve(path); - }, - dirName: function (path) { - return _path.dirname(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = rootPath + "/" + partialFilePath; - while(true) { - if(_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { - content: content, - path: path - }; - } catch (err) { - } - } else { - var parentPath = _path.resolve(rootPath, ".."); - if(rootPath === parentPath) { - return null; - } else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); - } - } - } - }, - print: function (str) { - process.stdout.write(str); - }, - printLine: function (str) { - process.stdout.write(str + '\n'); - }, - arguments: process.argv.slice(2), - stderr: { - Write: function (str) { - process.stderr.write(str); - }, - WriteLine: function (str) { - process.stderr.write(str + '\n'); - }, - Close: function () { - } - }, - stdout: { - Write: function (str) { - process.stdout.write(str); - }, - WriteLine: function (str) { - process.stdout.write(str + '\n'); - }, - Close: function () { - } - }, - watchFile: function (filename, callback) { - var firstRun = true; - var processingChange = false; - var fileChanged = function (curr, prev) { - if(!firstRun) { - if(curr.mtime < prev.mtime) { - return; - } - _fs.unwatchFile(filename, fileChanged); - if(!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function () { - processingChange = false; - }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { - persistent: true, - interval: 500 - }, fileChanged); - }; - fileChanged(); - return { - filename: filename, - close: function () { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function (source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit - }; - } - ; - if(typeof ActiveXObject === "function") { - return getWindowsScriptHostIO(); - } else if(typeof require === "function") { - return getNodeIO(); - } else { - return null; - } -})(); -var cfg = { - root: '.', - pattern: /.\-tests\.ts/g, - tsc: 'node ./_infrastructure/tests/typescript/tsc.js ', - exclude: { - '.git': true, - '.gitignore': true, - 'package.json': true, - '_infrastructure': true, - '.travis.yml': true, - 'LICENSE': true, - 'README.md': true, - '_ReSharper.DefinitelyTyped': true, - 'obj': true, - 'bin': true, - 'Properties': true, - 'DefinitelyTyped.csproj': true, - 'DefinitelyTyped.csproj.user': true, - 'DefinitelyTyped.sln': true, - 'DefinitelyTyped.v11.suo': true - } -}; -if(process.argv.length > 2) { - cfg.root = process.argv[2]; -} -var TestFile = (function () { - function TestFile() { - this.errors = []; - } - return TestFile; -})(); -var Test = (function () { - function Test(lib) { - this.lib = lib; - this.files = []; - } - return Test; -})(); -var Tests = (function () { - function Tests() { - this.tests = []; - } - return Tests; -})(); -function getLibDirectory(file) { - return file.substr(cfg.root.length).split('/')[1]; -} -function getErrorList(out) { - var splitContentByNewlines = function (content) { - var lines = content.split('\r\n'); - if(lines.length === 1) { - lines = content.split('\n'); - } - return lines; - }; - var result = []; - var lines = splitContentByNewlines(out); - for(var i = 0; i < lines.length; i++) { - if(lines[i]) { - result.push(lines[i]); - } - } - return result; -} -function runTests(testFiles) { - var tests = new Tests(); - Exec.exec(cfg.tsc, [ - testFiles[testIndex] - ], function (ExecResult) { - var lib = getLibDirectory(testFiles[testIndex]); - cache_visited_libs[lib] = true; - var testFile = new TestFile(); - testFile.name = testFiles[testIndex]; - testFile.errors = getErrorList(ExecResult.stderr); - if(testFile.errors.length == 0) { - total_success++; - } else { - total_failure++; - } - console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length) + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m')); - var test = new Test(lib); - test.files.push(testFile); - tests.tests.push(test); - testIndex++; - if(testIndex < totalTest) { - Exec.exec(cfg.tsc, [ - testFiles[testIndex] - ], arguments.callee); - } else { - var withoutTests = { - }; - for(var k = 0; k < allFiles.length; k++) { - var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1]; - if(!(rootFolder in cfg.exclude)) { - if(!(rootFolder in cache_visited_libs)) { - withoutTests[rootFolder] = true; - } - } - } - var withoutTestsCount = 0; - for(var attr in withoutTests) { - var test = new Test(attr); - tests.tests.push(test); - console.log(' [\033[36m' + attr + '\033[0m] without tests'); - withoutTestsCount++; - } - console.log('\n> ' + (total_failure + total_success + withoutTestsCount) + ' tests. ' + '\033[32m' + total_success + ' tests success\033[0m, ' + '\033[31m' + total_failure + ' tests failed\033[0m and ' + withoutTestsCount + ' definitions without tests.\n'); - if(total_failure > 0) { - process.exit(1); - } - } - }); -} -var testFiles = IO.dir(cfg.root, cfg.pattern, { - recursive: true, - deep: 1 -}); -var allFiles = IO.dir(cfg.root, null, { - recursive: true -}); -var totalTest = testFiles.length; -var testIndex = 0; -var cache_visited_libs = { -}; -var total_failure = 0; -var total_success = 0; -var tscVersion = '?.?.?'; -Exec.exec(cfg.tsc, [ - '-version' -], function (ExecResult) { - tscVersion = ExecResult.stdout; - console.log('$ tsc -version'); - console.log(tscVersion); - runTests(testFiles); -}); diff --git a/_infrastructure/tests/testRunner.ts b/_infrastructure/tests/testRunner.ts deleted file mode 100644 index c70da8d3c..000000000 --- a/_infrastructure/tests/testRunner.ts +++ /dev/null @@ -1,168 +0,0 @@ -/// -/// - -var cfg = { - root: '.', - pattern: /.\-tests\.ts/g, - tsc: 'node ./_infrastructure/tests/typescript/tsc.js ', - exclude: { - '.git': true, - '.gitignore': true, - 'package.json': true, - '_infrastructure': true, - '.travis.yml': true, - 'LICENSE': true, - 'README.md': true, - '_ReSharper.DefinitelyTyped': true, - 'obj': true, - 'bin': true, - 'Properties': true, - 'DefinitelyTyped.csproj': true, - 'DefinitelyTyped.csproj.user': true, - 'DefinitelyTyped.sln': true, - 'DefinitelyTyped.v11.suo': true - } -}; - -if (process.argv.length > 2) { - cfg.root = process.argv[2]; -} - -class TestFile { - public name: string; - public errors: string[] = []; -} - -class Test { - public files: TestFile[] = []; - constructor(public lib: string) { } -} - -class Tests { - public tests: Test[] = []; -} - -function getLibDirectory(file: string) { - return file.substr(cfg.root.length).split('/')[1]; -} - -function getErrorList(out): string[] { - var splitContentByNewlines = function (content: string) { - var lines = content.split('\r\n'); - if (lines.length === 1) { - lines = content.split('\n'); - } - return lines; - } - - var result: string[] = []; - - var lines = splitContentByNewlines(out); - - for (var i = 0; i < lines.length; i++) { - if (lines[i]) { - result.push(lines[i]); - } - } - - return result; -} - -function runTests(testFiles) { - var tests = new Tests(); - - Exec.exec( - cfg.tsc, - [testFiles[testIndex]], - (ExecResult) => { - var lib = getLibDirectory(testFiles[testIndex]); - - cache_visited_libs[lib] = true; - - var testFile = new TestFile(); - testFile.name = testFiles[testIndex]; - testFile.errors = getErrorList(ExecResult.stderr); - - if (testFile.errors.length == 0) { - total_success++; - } else { - total_failure++; - } - - console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length) - + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m')); - - var test = new Test(lib); - test.files.push(testFile); - tests.tests.push(test); - - testIndex++; - if (testIndex < totalTest) { - Exec.exec( - cfg.tsc, - [testFiles[testIndex]], - <(ExecResult) => any>arguments.callee); - } else { - var withoutTests = {}; - for (var k = 0; k < allFiles.length; k++) { - var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1]; - if (!(rootFolder in cfg.exclude)) { - if (!(rootFolder in cache_visited_libs)) { - withoutTests[rootFolder] = true; - } - } - } - - var withoutTestsCount = 0; - for (var attr in withoutTests) { - - var test = new Test(attr); - tests.tests.push(test); - - console.log(' [\033[36m' + attr + '\033[0m] without tests'); - withoutTestsCount++; - } - - console.log('\n> ' + (total_failure + total_success + withoutTestsCount) - + ' tests. ' - + '\033[32m' + total_success + ' tests success\033[0m, ' - + '\033[31m' + total_failure + ' tests failed\033[0m and ' - + withoutTestsCount + ' definitions without tests.\n'); - - if (total_failure > 0) { - process.exit(1); - } - } - }); -} - -////// GLOBAL VARS - -// get all files: "*-tests.ts" -var testFiles = IO.dir(cfg.root, cfg.pattern, { recursive: true, deep: 1 }); - -// get all proect files -var allFiles = IO.dir(cfg.root, null, { recursive: true }); - -var totalTest = testFiles.length; -var testIndex = 0; -var cache_visited_libs = {}; - -// total -var total_failure = 0; -var total_success = 0; - -// var to have current typescript version -var tscVersion = '?.?.?'; - -////// END GLOBAL VARS - -// entry point -Exec.exec(cfg.tsc, ['-version'], (ExecResult) => { - tscVersion = ExecResult.stdout; - - console.log('$ tsc -version'); - console.log(tscVersion); - - runTests(testFiles); -}); \ No newline at end of file diff --git a/ace/ace.d.ts b/ace/ace.d.ts index fe31dcc20..6a8e81625 100644 --- a/ace/ace.d.ts +++ b/ace/ace.d.ts @@ -3,7 +3,7 @@ // Definitions by: Diullei Gomes // Definitions: https://github.com/borisyankov/DefinitelyTyped -module AceAjax { +declare module AceAjax { export interface Delta { action: string; @@ -75,7 +75,7 @@ module AceAjax { onTextInput(text); } - declare var KeyBinding: { + var KeyBinding: { new(editor: Editor): KeyBinding; } @@ -184,7 +184,7 @@ module AceAjax { **/ detach(); } - declare var Anchor: { + var Anchor: { /** * Creates a new `Anchor` and associates it with a document. * @param doc The document to associate with the anchor @@ -248,7 +248,7 @@ module AceAjax { **/ getState(row: number): string; } - declare var BackgroundTokenizer: { + var BackgroundTokenizer: { /** * Creates a new `BackgroundTokenizer` object. * @param tokenizer The tokenizer to use @@ -435,7 +435,7 @@ module AceAjax { **/ positionToIndex(pos: Position, startRow: number): number; } - declare var Document: { + var Document: { /** * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * @param text The starting text @@ -1011,7 +1011,7 @@ module AceAjax { **/ getScreenLength(): number; } - declare var EditSession: { + var EditSession: { /** * Sets up a new `EditSession` and associates it with the given `Document` and `TextMode`. * @param text [If `text` is a `Document`, it associates the `EditSession` with it. Otherwise, a new `Document` is created, with the initial text]{: #textParam} @@ -1702,7 +1702,7 @@ module AceAjax { } - declare var Editor: { + var Editor: { /** * Creates a new `Editor` object. * @param renderer Associated `VirtualRenderer` that draws everything @@ -1761,7 +1761,7 @@ module AceAjax { **/ cancel(); } - declare var PlaceHolder: { + var PlaceHolder: { /** * - @param session (Document): The document to associate with the anchor * - @param length (Number): The starting row position @@ -1995,7 +1995,7 @@ module AceAjax { * @param endRow The ending row * @param endColumn The ending column **/ - declare var Range: { + var Range: { fromPoints(pos1: Position, pos2: Position): Range; new(startRow: number, startColumn: number, endRow: number, endColumn: number): Range; } @@ -2005,7 +2005,7 @@ module AceAjax { //////////////// export interface RenderLoop { } - declare var RenderLoop: { + var RenderLoop: { new(): RenderLoop; } @@ -2047,7 +2047,7 @@ module AceAjax { **/ setScrollTop(scrollTop: number); } - declare var ScrollBar: { + var ScrollBar: { /** * Creates a new `ScrollBar`. `parent` is the owner of the scroll bar. * @param parent A DOM element @@ -2102,7 +2102,7 @@ module AceAjax { **/ replace(input: string, replacement: string): string; } - declare var Search: { + var Search: { /** * Creates a new `Search` object. The following search options are avaliable: * - `needle`: The string or regular expression you're looking for @@ -2371,7 +2371,7 @@ module AceAjax { **/ moveCursorToScreen(row: number, column: number, keepDesiredColumn: boolean); } - declare var Selection: { + var Selection: { /** * Creates a new `Selection` object. * @param session The session to use @@ -2459,7 +2459,7 @@ module AceAjax { **/ resize(); } - declare var Split: { + var Split: { new(): Split; } @@ -2497,7 +2497,7 @@ module AceAjax { **/ getCurrentTokenColumn(): number; } - declare var TokenIterator: { + var TokenIterator: { /** * Creates a new token iterator object. The inital token index is set to the provided row and column coordinates. * @param session The session to associate with @@ -2522,7 +2522,7 @@ module AceAjax { **/ getLineTokens(): any; } - declare var Tokenizer: { + var Tokenizer: { /** * Constructs a new tokenizer based on the given rules and flags. * @param rules The highlighting rules @@ -2576,7 +2576,7 @@ module AceAjax { hasRedo(): boolean; } - declare var UndoManager: { + var UndoManager: { /** * Resets the current undo state and creates a new `UndoManager`. **/ @@ -2924,7 +2924,7 @@ module AceAjax { destroy(); } - declare var VirtualRenderer: { + var VirtualRenderer: { /** * Constructs a new `VirtualRenderer` within the `container` specified, applying the given `theme`. * @param container The root element of the editor diff --git a/ace/tests/ace-anchor-tests.ts b/ace/tests/ace-anchor-tests.ts index 40e81600a..08ca8f43f 100644 --- a/ace/tests/ace-anchor-tests.ts +++ b/ace/tests/ace-anchor-tests.ts @@ -1,6 +1,7 @@ /// -exports = { +var assert: any; +var exports = { "test create anchor" : function() { var doc = new AceAjax.Document("juhu"); diff --git a/ace/tests/ace-background_tokenizer-tests.ts b/ace/tests/ace-background_tokenizer-tests.ts index 8c29358a4..8f54bae51 100644 --- a/ace/tests/ace-background_tokenizer-tests.ts +++ b/ace/tests/ace-background_tokenizer-tests.ts @@ -1,5 +1,7 @@ /// +var assert: any; + function forceTokenize(session) { for (var i = 0, l = session.getLength(); i < l; i++) session.getTokens(i) @@ -11,7 +13,7 @@ function testStates(session, states) { assert.ok(l == states.length) } -exports = { +var exports = { "test background tokenizer update on session change": function() { var doc = new AceAjax.EditSession([ diff --git a/ace/tests/ace-default-tests.ts b/ace/tests/ace-default-tests.ts index dcd1ab103..f8a280c1a 100644 --- a/ace/tests/ace-default-tests.ts +++ b/ace/tests/ace-default-tests.ts @@ -1,5 +1,6 @@ /// +var assert: any; var editor = ace.edit("editor"); editor.setTheme("ace/theme/monokai"); editor.getSession().setMode("ace/mode/javascript"); diff --git a/ace/tests/ace-document-tests.ts b/ace/tests/ace-document-tests.ts index 1f3e0a9a2..7fc342f74 100644 --- a/ace/tests/ace-document-tests.ts +++ b/ace/tests/ace-document-tests.ts @@ -1,6 +1,7 @@ /// -exports = { +var assert: any; +var exports = { "test: insert text in line": function() { var doc = new AceAjax.Document(["12", "34"]); diff --git a/ace/tests/ace-edit_session-tests.ts b/ace/tests/ace-edit_session-tests.ts index 12a3ce5bf..caa2f1729 100644 --- a/ace/tests/ace-edit_session-tests.ts +++ b/ace/tests/ace-edit_session-tests.ts @@ -1,6 +1,7 @@ /// var lang: any; +var assert: any; function createFoldTestSession() { var lines = [ @@ -26,7 +27,7 @@ function assertArray(a, b) { } } -exports = { +var exports = { "test: find matching opening bracket in Text mode": function() { var session = new AceAjax.EditSession(["(()(", "())))"]); diff --git a/ace/tests/ace-editor1-tests.ts b/ace/tests/ace-editor1-tests.ts index ed8b3b3e8..78d3aff04 100644 --- a/ace/tests/ace-editor1-tests.ts +++ b/ace/tests/ace-editor1-tests.ts @@ -1,6 +1,7 @@ /// -exports = { +var assert: any; +var exports = { setUp: function(next) { this.session1 = new AceAjax.EditSession(["abc", "def"]); diff --git a/ace/tests/ace-editor_highlight_selected_word-tests.ts b/ace/tests/ace-editor_highlight_selected_word-tests.ts index 7e06c8c50..e02f32366 100644 --- a/ace/tests/ace-editor_highlight_selected_word-tests.ts +++ b/ace/tests/ace-editor_highlight_selected_word-tests.ts @@ -27,10 +27,13 @@ function callHighlighterUpdate(session: AceAjax.IEditSession, firstRow: number, return rangeCount; } -exports = { +var assert: any; +var renderer: AceAjax.VirtualRenderer; + +var exports = { setUp: function(next) { var session = new AceAjax.EditSession(lipsum); - editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); var selection = session.getSelection(); next(); } , @@ -38,7 +41,7 @@ exports = { "test: highlight selected words by default": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); assert.equal(editor.getHighlightSelectedWord(), true); } , @@ -46,7 +49,7 @@ exports = { "test: highlight a word": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 9); selection.selectWord(); @@ -63,7 +66,7 @@ exports = { "test: highlight a word and clear highlight": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 8); selection.selectWord(); @@ -79,7 +82,7 @@ exports = { "test: highlight another word": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); selection.moveCursorTo(0, 14); selection.selectWord(); @@ -92,7 +95,7 @@ exports = { "test: no selection, no highlight": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); selection.clearSelection(); assert.equal(callHighlighterUpdate(session, 0, 0), 0); @@ -101,7 +104,7 @@ exports = { "test: select a word, no highlight": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); selection.moveCursorTo(0, 14); selection.selectWord(); @@ -116,7 +119,7 @@ exports = { "test: select a word with no matches": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.setHighlightSelectedWord(true); @@ -143,7 +146,7 @@ exports = { "test: partial word selection 1": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); selection.moveCursorTo(0, 14); selection.selectWord(); @@ -157,7 +160,7 @@ exports = { "test: partial word selection 2": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); selection.moveCursorTo(0, 13); selection.selectWord(); @@ -171,7 +174,7 @@ exports = { "test: partial word selection 3": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); selection.moveCursorTo(0, 14); selection.selectWord(); @@ -186,7 +189,7 @@ exports = { "test: select last word": function () { var selection = session.getSelection(); var session = new AceAjax.EditSession(lipsum); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); selection.moveCursorTo(0, 1); diff --git a/ace/tests/ace-editor_navigation-tests.ts b/ace/tests/ace-editor_navigation-tests.ts index c97ee0cd2..b68ae9b9d 100644 --- a/ace/tests/ace-editor_navigation-tests.ts +++ b/ace/tests/ace-editor_navigation-tests.ts @@ -1,6 +1,8 @@ /// -exports = { +var assert: any; +var renderer: AceAjax.VirtualRenderer; +var exports = { createEditSession: function (rows, cols) { var line = new Array(cols + 1).join("a"); var text = new Array(rows).join(line + "\n") + line; @@ -9,7 +11,7 @@ exports = { "test: navigate to end of file should scroll the last line into view": function () { var doc = this.createEditSession(200, 10); - var editor = new AceAjax.Editor(new MockRenderer(), doc); + var editor = new AceAjax.Editor(renderer, doc); editor.navigateFileEnd(); var cursor = editor.getCursorPosition(); @@ -20,7 +22,7 @@ exports = { "test: navigate to start of file should scroll the first row into view": function () { var doc = this.createEditSession(200, 10); - var editor = new AceAjax.Editor(new MockRenderer(), doc); + var editor = new AceAjax.Editor(renderer, doc); editor.moveCursorTo(editor.getLastVisibleRow() + 20); editor.navigateFileStart(); @@ -29,7 +31,7 @@ exports = { }, "test: goto hidden line should scroll the line into the middle of the viewport": function () { - var editor = new AceAjax.Editor(new MockRenderer(), this.createEditSession(200, 5)); + var editor = new AceAjax.Editor(renderer, this.createEditSession(200, 5)); editor.navigateTo(0, 0); editor.gotoLine(101); @@ -63,7 +65,7 @@ exports = { }, "test: goto visible line should only move the cursor and not scroll": function () { - var editor = new AceAjax.Editor(new MockRenderer(), this.createEditSession(200, 5)); + var editor = new AceAjax.Editor(renderer, this.createEditSession(200, 5)); editor.navigateTo(0, 0); editor.gotoLine(12); @@ -77,7 +79,7 @@ exports = { }, "test: navigate from the end of a long line down to a short line and back should maintain the curser column": function () { - var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["123456", "1"])); + var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["123456", "1"])); editor.navigateTo(0, 6); assert.position(editor.getCursorPosition(), 0, 6); @@ -90,7 +92,7 @@ exports = { }, "test: reset desired column on navigate left or right": function () { - var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["123456", "12"])); + var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["123456", "12"])); editor.navigateTo(0, 6); assert.position(editor.getCursorPosition(), 0, 6); @@ -106,7 +108,7 @@ exports = { }, "test: typing text should update the desired column": function () { - var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["1234", "1234567890"])); + var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["1234", "1234567890"])); editor.navigateTo(0, 3); editor.insert("juhu"); diff --git a/ace/tests/ace-editor_text_edit-tests.ts b/ace/tests/ace-editor_text_edit-tests.ts index 9d618acc6..623183016 100644 --- a/ace/tests/ace-editor_text_edit-tests.ts +++ b/ace/tests/ace-editor_text_edit-tests.ts @@ -1,9 +1,12 @@ /// -exports = { +var assert: any; +var renderer: AceAjax.VirtualRenderer; +var mode: any; +var exports = { "test: delete line from the middle": function () { var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 1); editor.removeLines(); @@ -29,7 +32,7 @@ exports = { "test: delete multiple selected lines": function () { var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 1); editor.getSelection().selectDown(); @@ -41,7 +44,7 @@ exports = { "test: delete first line": function () { var session = new AceAjax.EditSession(["a", "b", "c"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.removeLines(); @@ -51,7 +54,7 @@ exports = { "test: delete last should also delete the new line of the previous line": function () { var session = new AceAjax.EditSession(["a", "b", "c", ""].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(3, 0); @@ -66,7 +69,7 @@ exports = { "test: indent block": function () { var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 3); editor.getSelection().selectDown(); @@ -84,7 +87,7 @@ exports = { "test: indent selected lines": function () { var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 0); editor.getSelection().selectDown(); @@ -94,8 +97,8 @@ exports = { }, "test: no auto indent if cursor is before the {": function () { - var session = new AceAjax.EditSession("{", new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession("{",mode); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 0); editor.onTextInput("\n"); @@ -104,7 +107,7 @@ exports = { "test: outdent block": function () { var session = new AceAjax.EditSession([" a12345", " b12345", " c12345"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 5); editor.getSelection().selectDown(); @@ -129,7 +132,7 @@ exports = { "test: outent without a selection should update cursor": function () { var session = new AceAjax.EditSession(" 12"); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 3); editor.blockOutdent(" "); @@ -139,8 +142,8 @@ exports = { }, "test: comment lines should perserve selection": function () { - var session = new AceAjax.EditSession([" abc", "cde"].join("\n"), new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession([" abc", "cde"].join("\n"),mode); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 2); editor.getSelection().selectDown(); @@ -154,8 +157,8 @@ exports = { }, "test: uncomment lines should perserve selection": function () { - var session = new AceAjax.EditSession(["// abc", "//cde"].join("\n"), new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession(["// abc", "//cde"].join("\n"),mode); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 1); editor.getSelection().selectDown(); @@ -169,8 +172,8 @@ exports = { }, "test: toggle comment lines twice should return the original text": function () { - var session = new AceAjax.EditSession([" abc", "cde", "fg"], new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession([" abc", "cde", "fg"], mode); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 0); editor.getSelection().selectDown(); @@ -185,8 +188,8 @@ exports = { "test: comment lines - if the selection end is at the line start it should stay there": function () { //select down - var session = new AceAjax.EditSession(["abc", "cde"].join("\n"), new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession(["abc", "cde"].join("\n"),mode); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 0); editor.getSelection().selectDown(); @@ -195,8 +198,8 @@ exports = { assert.range(editor.getSelectionRange(), 0, 2, 1, 0); // select up - var session = new AceAjax.EditSession(["abc", "cde"].join("\n"), new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession(["abc", "cde"].join("\n"),mode); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 0); editor.getSelection().selectUp(); @@ -207,7 +210,7 @@ exports = { "test: move lines down should select moved lines": function () { var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(0, 1); editor.getSelection().selectDown(); @@ -234,7 +237,7 @@ exports = { "test: move lines up should select moved lines": function () { var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(2, 1); editor.getSelection().selectDown(); @@ -254,7 +257,7 @@ exports = { "test: move line without active selection should not move cursor relative to the moved line": function () { var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 1); editor.clearSelection(); @@ -272,7 +275,7 @@ exports = { "test: copy lines down should select lines and place cursor at the selection start": function () { var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 1); editor.getSelection().selectDown(); @@ -287,7 +290,7 @@ exports = { "test: copy lines up should select lines and place cursor at the selection start": function () { var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 1); editor.getSelection().selectDown(); @@ -302,7 +305,7 @@ exports = { "test: input a tab with soft tab should convert it to spaces": function () { var session = new AceAjax.EditSession(""); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); session.setTabSize(2); session.setUseSoftTabs(true); @@ -317,7 +320,7 @@ exports = { "test: input tab without soft tabs should keep the tab character": function () { var session = new AceAjax.EditSession(""); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); session.setUseSoftTabs(false); @@ -331,7 +334,7 @@ exports = { session.setUndoManager(undoManager); var initialText = session.toString(); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.removeLines(); var step1 = session.toString(); @@ -361,7 +364,7 @@ exports = { "test: remove left should remove character left of the cursor": function () { var session = new AceAjax.EditSession(["123", "456"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 1); editor.remove("left"); assert.equal(session.toString(), "123\n56"); @@ -370,7 +373,7 @@ exports = { "test: remove left should remove line break if cursor is at line start": function () { var session = new AceAjax.EditSession(["123", "456"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 0); editor.remove("left"); assert.equal(session.toString(), "123456"); @@ -381,7 +384,7 @@ exports = { session.setUseSoftTabs(true); session.setTabSize(4); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 8); editor.remove("left"); assert.equal(session.toString(), "123\n 456"); @@ -390,7 +393,7 @@ exports = { "test: transpose at line start should be a noop": function () { var session = new AceAjax.EditSession(["123", "4567", "89"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 0); editor.transposeLetters(); @@ -400,7 +403,7 @@ exports = { "test: transpose in line should swap the charaters before and after the cursor": function () { var session = new AceAjax.EditSession(["123", "4567", "89"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 2); editor.transposeLetters(); @@ -410,7 +413,7 @@ exports = { "test: transpose at line end should swap the last two characters": function () { var session = new AceAjax.EditSession(["123", "4567", "89"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 4); editor.transposeLetters(); @@ -420,7 +423,7 @@ exports = { "test: transpose with non empty selection should be a noop": function () { var session = new AceAjax.EditSession(["123", "4567", "89"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 1); editor.getSelection().selectRight(); editor.transposeLetters(); @@ -431,7 +434,7 @@ exports = { "test: transpose should move the cursor behind the last swapped character": function () { var session = new AceAjax.EditSession(["123", "4567", "89"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 2); editor.transposeLetters(); assert.position(editor.getCursorPosition(), 1, 3); @@ -440,7 +443,7 @@ exports = { "test: remove to line end": function () { var session = new AceAjax.EditSession(["123", "4567", "89"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 2); editor.removeToLineEnd(); assert.equal(session.getValue(), ["123", "45", "89"].join("\n")); @@ -449,7 +452,7 @@ exports = { "test: remove to line end at line end should remove the new line": function () { var session = new AceAjax.EditSession(["123", "4567", "89"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 4); editor.removeToLineEnd(); assert.position(editor.getCursorPosition(), 1, 4); @@ -459,7 +462,7 @@ exports = { "test: transform selection to uppercase": function () { var session = new AceAjax.EditSession(["ajax", "dot", "org"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 0); editor.getSelection().selectLineEnd(); editor.toUpperCase() @@ -469,7 +472,7 @@ exports = { "test: transform word to uppercase": function () { var session = new AceAjax.EditSession(["ajax", "dot", "org"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 0); editor.toUpperCase() assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n")); @@ -479,7 +482,7 @@ exports = { "test: transform selection to lowercase": function () { var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 0); editor.getSelection().selectLineEnd(); editor.toLowerCase() @@ -489,7 +492,7 @@ exports = { "test: transform word to lowercase": function () { var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); editor.moveCursorTo(1, 0); editor.toLowerCase() assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n")); diff --git a/ace/tests/ace-multi_select-tests.ts b/ace/tests/ace-multi_select-tests.ts index ade1493e2..68c7d1af9 100644 --- a/ace/tests/ace-multi_select-tests.ts +++ b/ace/tests/ace-multi_select-tests.ts @@ -1,5 +1,8 @@ /// +var assert: any; +var editor: any; +var renderer: any; var exec = function (name?, times?, args?) { do { editor.commands.exec(name, editor, args); @@ -9,7 +12,7 @@ var testRanges = function (str) { assert.equal(editor.selection.getAllRanges() + "", str + ""); } -exports = { +var exports = { name: "ACE multi_select.js", @@ -19,7 +22,7 @@ exports = { " wtt.w", " wtt.w" ]); - editor = new AceAjax.Editor(new MockRenderer(), doc); + editor = new AceAjax.Editor(renderer, doc); editor.navigateFileEnd(); exec("selectMoreBefore", 3); @@ -45,7 +48,7 @@ exports = { " wtt.w", " wtt.we" ]); - editor = new AceAjax.Editor(new MockRenderer(), doc); + editor = new AceAjax.Editor(renderer, doc); editor.selectMoreLines(1); testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]"); @@ -67,7 +70,7 @@ exports = { " wtt.w", " wtt.w" ]); - editor = new AceAjax.Editor(new MockRenderer(), doc); + editor = new AceAjax.Editor(renderer, doc); editor.selectMoreLines(1) testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]"); @@ -87,7 +90,7 @@ exports = { " wtt.w", " wtt.w" ]); - editor = new AceAjax.Editor(new MockRenderer(), doc); + editor = new AceAjax.Editor(renderer, doc); var selection = editor.selection; diff --git a/ace/tests/ace-placeholder-tests.ts b/ace/tests/ace-placeholder-tests.ts index 124554cf7..b9693da37 100644 --- a/ace/tests/ace-placeholder-tests.ts +++ b/ace/tests/ace-placeholder-tests.ts @@ -1,10 +1,13 @@ /// -exports = { +var assert: any; +var renderer: AceAjax.VirtualRenderer; +var mode: any; +var exports = { "test: simple at the end appending of text": function () { - var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode); + var editor = new AceAjax.Editor(renderer, session); new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); @@ -20,8 +23,8 @@ exports = { }, "test: inserting text outside placeholder": function () { - var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);\n", new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);\n", mode); + var editor = new AceAjax.Editor(renderer, session); new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); @@ -31,8 +34,8 @@ exports = { }, "test: insertion at the beginning": function (next) { - var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode); + var editor = new AceAjax.Editor(renderer, session); var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); @@ -49,8 +52,8 @@ exports = { }, "test: detaching placeholder": function () { - var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode); + var editor = new AceAjax.Editor(renderer, session); var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); @@ -63,8 +66,8 @@ exports = { }, "test: events": function () { - var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode); + var editor = new AceAjax.Editor(renderer, session); var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); var entered = false; @@ -86,9 +89,9 @@ exports = { }, "test: cancel": function (next) { - var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode); session.setUndoManager(new AceAjax.UndoManager()); - var editor = new AceAjax.Editor(new MockRenderer(), session); + var editor = new AceAjax.Editor(renderer, session); var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); editor.moveCursorTo(0, 5); diff --git a/ace/tests/ace-range-tests.ts b/ace/tests/ace-range-tests.ts index 8a1b1ccc6..8e560e8d2 100644 --- a/ace/tests/ace-range-tests.ts +++ b/ace/tests/ace-range-tests.ts @@ -1,6 +1,7 @@ /// -exports = { +var assert: any; +var exports = { name: "ACE range.js", diff --git a/ace/tests/ace-range_list-tests.ts b/ace/tests/ace-range_list-tests.ts index 83f3c8a91..3a531579e 100644 --- a/ace/tests/ace-range_list-tests.ts +++ b/ace/tests/ace-range_list-tests.ts @@ -1,5 +1,6 @@ /// +var assert: any; function flatten(rangeList) { var points = []; rangeList.ranges.forEach(function (r) { @@ -11,7 +12,7 @@ function testRangeList(rangeList, points) { assert.equal("" + flatten(rangeList), "" + points); } -exports = { +var exports = { name: "ACE range_list.js", diff --git a/ace/tests/ace-search-tests.ts b/ace/tests/ace-search-tests.ts index c30139d65..14b53397b 100644 --- a/ace/tests/ace-search-tests.ts +++ b/ace/tests/ace-search-tests.ts @@ -1,6 +1,7 @@ /// -exports = { +var assert: any; +var exports = { "test: configure the search object": function () { var search = new AceAjax.Search(); search.set({ diff --git a/ace/tests/ace-selection-tests.ts b/ace/tests/ace-selection-tests.ts index 030cdff66..884631085 100644 --- a/ace/tests/ace-selection-tests.ts +++ b/ace/tests/ace-selection-tests.ts @@ -1,6 +1,7 @@ /// -exports = { +var assert: any; +var exports = { createSession: function (rows, cols) { var line = new Array(cols + 1).join("a"); var text = new Array(rows).join(line + "\n") + line; diff --git a/ace/tests/ace-token_iterator-tests.ts b/ace/tests/ace-token_iterator-tests.ts index 75260e95a..892d781b9 100644 --- a/ace/tests/ace-token_iterator-tests.ts +++ b/ace/tests/ace-token_iterator-tests.ts @@ -1,6 +1,8 @@ /// -exports = { +var assert: any; +var mode: any; +var exports = { "test: token iterator initialization in JavaScript document": function () { var lines = [ "function foo(items) {", @@ -9,7 +11,7 @@ exports = { " } // Real Tab.", "}" ]; - var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode()); + var session = new AceAjax.EditSession(lines.join("\n"),mode); var iterator = new AceAjax.TokenIterator(session, 0, 0); assert.equal(iterator.getCurrentToken().value, "function"); @@ -96,7 +98,7 @@ exports = { " } // Real Tab.", "}" ]; - var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode()); + var session = new AceAjax.EditSession(lines.join("\n"),mode); var tokens = []; var len = session.getLength(); @@ -118,7 +120,7 @@ exports = { " } // Real Tab.", "}" ]; - var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode()); + var session = new AceAjax.EditSession(lines.join("\n"),mode); var tokens = []; var len = session.getLength(); @@ -140,7 +142,7 @@ exports = { " } // Real Tab.", "}" ]; - var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode()); + var session = new AceAjax.EditSession(lines.join("\n"),mode); var iterator = new AceAjax.TokenIterator(session, 0, 0); diff --git a/ace/tests/ace-virtual_renderer-tests.ts b/ace/tests/ace-virtual_renderer-tests.ts index 83372ad34..51f349dad 100644 --- a/ace/tests/ace-virtual_renderer-tests.ts +++ b/ace/tests/ace-virtual_renderer-tests.ts @@ -1,6 +1,7 @@ /// -exports = { +var assert: any; +var exports = { "test: screen2text the column should be rounded to the next character edge": function () { var el = document.createElement("div"); diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 6354e188c..3ea1371f4 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -142,7 +142,7 @@ module HttpAndRegularPromiseTests { // Test for AngularJS Syntac module My.Namespace { - + export var x; // need to export something for module to kick in } // IModule Registering Test @@ -150,7 +150,7 @@ var mod = angular.module('tests',[]); mod.controller('name', function($scope : ng.IScope) {}) mod.controller('name', ['$scope', function($scope : ng.IScope) {}]) mod.controller(My.Namespace); -mod.directive('name', function($scope : ng.IScope) {}) +mod.directive('name', function ($scope: ng.IScope) {}) mod.directive('name', ['$scope', function($scope : ng.IScope) {}]) mod.directive(My.Namespace); mod.factory('name', function($scope : ng.IScope) {}) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 10fb67a3f..8e5e2a007 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -173,7 +173,7 @@ declare module ng { // see http://docs.angularjs.org/api/ng.$rootScope.Scope /////////////////////////////////////////////////////////////////////////// interface IScope { - // Documentation says exp is optional, but actual implementaton counts on it + $apply(): any; $apply(exp: string): any; $apply(exp: (scope: IScope) => any): any; diff --git a/async/async-tests.ts b/async/async-tests.ts index e7b57a1f8..fefc3fd2a 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -18,10 +18,10 @@ async.series([ function () { } ]); -var data; -function asyncProcess() { } +var data = []; +function asyncProcess(item, callback) { } async.map(data, asyncProcess, function (err, results) { - alert(results); + console.log(results); }); var openFiles = ['file1', 'file2']; diff --git a/async/async.d.ts b/async/async.d.ts index 835c10777..6c06348d5 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -1,67 +1,71 @@ -// Type definitions for Async 0.1 +// Type definitions for Async 0.1.23 // Project: https://github.com/caolan/async // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped +interface AsyncMultipleResultsCallback { (err: string, results: T[]): any; } +interface AsyncSingleResultCallback { (err: string, result: T): any; } +interface AsyncTimesCallback { (n: number, callback: AsyncMultipleResultsCallback): void; } +interface AsyncIterator { (item: T, callback: AsyncMultipleResultsCallback): void; } +interface AsyncMemoIterator { (memo: T, item: T, callback: AsyncSingleResultCallback): void; } +interface AsyncWorker { (task: T, callback: Function): void; } -interface AsyncCallback { (err: string, results: any): any; } -interface AsyncIterator { (item, callback: AsyncCallback): void; } -interface AsyncMemoIterator { (memo: any, item: any, callback: AsyncCallback): void; } -interface AsyncWorker { (task: any, callback: Function): void; } - -interface AsyncQueue { +interface AsyncQueue { length(): number; concurrency: number; - push(task: any, callback: AsyncCallback): void; - saturated: AsyncCallback; - empty: AsyncCallback; - drain: AsyncCallback; + push(task: T, callback: AsyncMultipleResultsCallback): void; + saturated: AsyncMultipleResultsCallback; + empty: AsyncMultipleResultsCallback; + drain: AsyncMultipleResultsCallback; } interface Async { // Collections - forEach(arr: any[], iterator: AsyncIterator, callback: AsyncCallback): void; - forEachSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback): void; - forEachLimit(arr: any[], limit: number, iterator: AsyncIterator, callback: AsyncCallback): void; - map(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - mapSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - filter(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - select(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - filterSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - selectSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - reject(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - rejectSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - reduce(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback); - inject(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback); - foldl(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback); - reduceRight(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback); - foldr(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback); - detect(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - detectSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - sortBy(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - some(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - any(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - every(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - all(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - concat(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); - concatSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback); + forEach(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + forEachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + forEachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + map(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + mapSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + filter(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + select(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + filterSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + selectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + reject(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + rejectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + reduce(arr: T[], memo: T, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); + inject(arr: T[], memo: T, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); + foldl(arr: T[], memo: T, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); + reduceRight(arr: T[], memo: T, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); + foldr(arr: T[], memo: T, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); + detect(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + detectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + sortBy(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + some(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + any(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + every(arr: T[], iterator: AsyncIterator, callback: (result: boolean) => any); + all(arr: T[], iterator: AsyncIterator, callback: (result: boolean) => any); + concat(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + concatSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); // Control Flow - series(tasks: any[], callback?: AsyncCallback): void; - series(tasks: any, callback?: AsyncCallback): void; - parallel(tasks: any[], callback?: AsyncCallback): void; - parallel(tasks: any, callback?: AsyncCallback): void; - whilst(test: Function, fn: Function, callback: AsyncCallback): void; - until(test: Function, fn: Function, callback: AsyncCallback): void; - waterfall(tasks: any[], callback?: AsyncCallback): void; - waterfall(tasks: any, callback?: AsyncCallback): void; - queue(worker: AsyncWorker, concurrency: number): AsyncQueue; - //auto(tasks: any[], callback?: AsyncCallback): void; - auto(tasks: any, callback?: AsyncCallback): void; - iterator(tasks): Function; + series(tasks: T[], callback?: AsyncMultipleResultsCallback): void; + series(tasks: T, callback?: AsyncMultipleResultsCallback): void; + parallel(tasks: T[], callback?: AsyncMultipleResultsCallback): void; + parallel(tasks: T, callback?: AsyncMultipleResultsCallback): void; + whilst(test: Function, fn: Function, callback: Function): void; + until(test: Function, fn: Function, callback: Function): void; + waterfall(tasks: T[], callback?: AsyncMultipleResultsCallback): void; + waterfall(tasks: T, callback?: AsyncMultipleResultsCallback): void; + queue(worker: AsyncWorker, concurrency: number): AsyncQueue; + // auto(tasks: any[], callback?: AsyncMultipleResultsCallback): void; + auto(tasks: any, callback?: AsyncMultipleResultsCallback): void; + iterator(tasks: Function[]): Function; apply(fn: Function, ...arguments: any[]): void; - nextTick(callback: AsyncCallback): void; + nextTick(callback: Function): void; + + times (n: number, callback: AsyncTimesCallback): void; + timesSeries (n: number, callback: AsyncTimesCallback): void; // Utils memoize(fn: Function, hasher?: Function): Function; diff --git a/azure-mobile-services-client/AzureMobileServicesClient-tests.ts b/azure-mobile-services-client/AzureMobileServicesClient-tests.ts index b557a2baf..f381c0809 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient-tests.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient-tests.ts @@ -32,8 +32,8 @@ tableTodoItems.read() //define simple handler used in callback calls for insert/update and delete -function handlerInsUpd(e, i) => { if (!e) data.push( i); }; -function handlerDelErr(e) => { if (e) alert("ERROR: " + e); } +function handlerInsUpd(e, i) { if (!e) data.push( i); }; +function handlerDelErr(e) { if (e) alert("ERROR: " + e); } //insert one data passing info in POST + custom data in QueryString + simple callback handler diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts index 1dcf9e5a6..09d0efb7c 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts @@ -3,7 +3,7 @@ // Definitions by: Morosinotto Daniele // Definitions: https://github.com/borisyankov/DefinitelyTyped -module Microsoft.WindowsAzure { +declare module Microsoft.WindowsAzure { // MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx interface MobileServiceClient { diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 92ff102dc..2a4a60819 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Backbone 0.9.10 +// Type definitions for Backbone 1.0.0 // Project: http://backbonejs.org/ // Definitions by: Boris Yankov +// Definitions by: Natan Vivo // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -8,61 +9,61 @@ declare module Backbone { - export interface AddOptions extends Silenceable { + interface AddOptions extends Silenceable { at: number; } - export interface HistoryOptions extends Silenceable { - pushState?: bool; + interface HistoryOptions extends Silenceable { + pushState?: boolean; root?: string; } - export interface NavigateOptions { - trigger: bool; + interface NavigateOptions { + trigger: boolean; } - export interface RouterOptions { + interface RouterOptions { routes: any; } - export interface Silenceable { - silent?: bool; + interface Silenceable { + silent?: boolean; } interface Validable { - validate?: bool; + validate?: boolean; } interface Waitable { - wait?: bool; + wait?: boolean; } interface Parseable { parse?: any; } - export interface PersistenceOptions { + interface PersistenceOptions { url?: string; beforeSend?: (jqxhr: JQueryXHR) => void; success?: (modelOrCollection?: any, response?: any, options?: any) => void; error?: (modelOrCollection?: any, jqxhr?: JQueryXHR, options?: any) => void; } - export interface ModelSetOptions extends Silenceable extends Validable { + interface ModelSetOptions extends Silenceable, Validable { } - export interface ModelFetchOptions extends PersistenceOptions extends ModelSetOptions extends Parseable { + interface ModelFetchOptions extends PersistenceOptions, ModelSetOptions, Parseable { } - export interface ModelSaveOptions extends Silenceable extends Waitable extends Validable extends Parseable extends PersistenceOptions { - patch?: bool; + interface ModelSaveOptions extends Silenceable, Waitable, Validable, Parseable, PersistenceOptions { + patch?: boolean; } - export interface ModelDestroyOptions extends Waitable extends PersistenceOptions { + interface ModelDestroyOptions extends Waitable, PersistenceOptions { } - export interface CollectionFetchOptions extends PersistenceOptions extends Parseable { - reset?: bool; + interface CollectionFetchOptions extends PersistenceOptions, Parseable { + reset?: boolean; } interface on { (eventName: string, callback: (...args: any[]) => void, context?: any): any; } @@ -71,7 +72,7 @@ declare module Backbone { interface bind { (eventName: string, callback: (...args: any[]) => void, context?: any): any; } interface unbind { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; } - declare class Events { + class Events { on(eventName: string, callback: (...args:any[]) => void, context?: any): any; off(eventName?: string, callback?: (...args:any[]) => void, context?: any): any; trigger(eventName: string, ...args: any[]): any; @@ -84,7 +85,7 @@ declare module Backbone { stopListening(object?: any, events?: string, callback?: (...args: any[]) => void ): any; } - export class ModelBase extends Events { + class ModelBase extends Events { url: any; parse(response, options?: any); toJSON(options?: any): any; @@ -92,7 +93,7 @@ declare module Backbone { } - export class Model extends ModelBase { + class Model extends ModelBase { static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality @@ -120,10 +121,10 @@ declare module Backbone { defaults(): any; destroy(options?: ModelDestroyOptions); escape(attribute: string); - has(attribute: string): bool; - hasChanged(attribute?: string): bool; - isNew(): bool; - isValid(): bool; + has(attribute: string): boolean; + hasChanged(attribute?: string): boolean; + isNew(): boolean; + isValid(): boolean; previous(attribute: string): any; previousAttributes(): any[]; save(attributes?: any, options?: ModelSaveOptions); @@ -131,7 +132,7 @@ declare module Backbone { validate(attributes: any, options?: any): any; } - export class Collection extends ModelBase { + class Collection extends ModelBase { static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality @@ -164,34 +165,34 @@ declare module Backbone { unshift(model: Model, options?: AddOptions); where(properies: any): Model[]; - all(iterator: (element: Model, index: number) => bool, context?: any): bool; - any(iterator: (element: Model, index: number) => bool, context?: any): bool; + all(iterator: (element: Model, index: number) => boolean, context?: any): boolean; + any(iterator: (element: Model, index: number) => boolean, context?: any): boolean; collect(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[]; chain(): any; compact(): Model[]; - contains(value: any): bool; + contains(value: any): boolean; countBy(iterator: (element: Model, index: number) => any): any[]; countBy(attribute: string): any[]; - detect(iterator: (item: any) => bool, context?: any): any; // ??? + detect(iterator: (item: any) => boolean, context?: any): any; // ??? difference(...model: Model[]): Model[]; drop(): Model; drop(n: number): Model[]; each(iterator: (element: Model, index: number, list?: any) => void, context?: any); - every(iterator: (element: Model, index: number) => bool, context?: any): bool; - filter(iterator: (element: Model, index: number) => bool, context?: any): Model[]; - find(iterator: (element: Model, index: number) => bool, context?: any): Model; + every(iterator: (element: Model, index: number) => boolean, context?: any): boolean; + filter(iterator: (element: Model, index: number) => boolean, context?: any): Model[]; + find(iterator: (element: Model, index: number) => boolean, context?: any): Model; first(): Model; first(n: number): Model[]; - flatten(shallow?: bool): Model[]; + flatten(shallow?: boolean): Model[]; foldl(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; forEach(iterator: (element: Model, index: number, list?: any) => void, context?: any); - include(value: any): bool; - indexOf(element: Model, isSorted?: bool): number; + include(value: any): boolean; + indexOf(element: Model, isSorted?: boolean): number; initial(): Model; initial(n: number): Model[]; inject(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; intersection(...model: Model[]): Model[]; - isEmpty(object: any): bool; + isEmpty(object: any): boolean; invoke(methodName: string, arguments?: any[]); last(): Model; last(n: number): Model[]; @@ -204,26 +205,26 @@ declare module Backbone { select(iterator: any, context?: any): any[]; size(): number; shuffle(): any[]; - some(iterator: (element: Model, index: number) => bool, context?: any): bool; + some(iterator: (element: Model, index: number) => boolean, context?: any): boolean; sortBy(iterator: (element: Model, index: number) => number, context?: any): Model[]; sortBy(attribute: string, context?: any): Model[]; sortedIndex(element: Model, iterator?: (element: Model, index: number) => number): number; range(stop: number, step?: number); range(start: number, stop: number, step?: number); reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[]; - reject(iterator: (element: Model, index: number) => bool, context?: any): Model[]; + reject(iterator: (element: Model, index: number) => boolean, context?: any): Model[]; rest(): Model; rest(n: number): Model[]; tail(): Model; tail(n: number): Model[]; toArray(): any[]; union(...model: Model[]): Model[]; - uniq(isSorted?: bool, iterator?: (element: Model, index: number) => bool): Model[]; + uniq(isSorted?: boolean, iterator?: (element: Model, index: number) => boolean): Model[]; without(...values: any[]): Model[]; zip(...model: Model[]): Model[]; } - export class Router extends Events { + class Router extends Events { static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality @@ -233,20 +234,20 @@ declare module Backbone { initialize (options?: RouterOptions); route(route: string, name: string, callback?: (...parameter: any[]) => void); navigate(fragment: string, options?: NavigateOptions); - navigate(fragment: string, trigger?: bool); + navigate(fragment: string, trigger?: boolean); } - export var history: History; - export class History { + var history: History; + class History { start(options?: HistoryOptions); navigate(fragment: string, options: any); pushSate(); - getFragment(fragment?: string, forcePushState?: bool): string; + getFragment(fragment?: string, forcePushState?: boolean): string; getHash(window?: Window): string; - started: bool; + started: boolean; } - export interface ViewOptions { + interface ViewOptions { model?: Backbone.Model; collection?: Backbone.Collection; el?: any; @@ -256,7 +257,7 @@ declare module Backbone { attributes?: any[]; } - export class View extends Events { + class View extends Events { static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality @@ -267,7 +268,7 @@ declare module Backbone { collection: Collection; template: (data?: any) => string; make(tagName: string, attrs?, opts?): View; - setElement(element: HTMLElement, delegate?: bool); + setElement(element: HTMLElement, delegate?: boolean); id: string; className: string; tagName: string; @@ -288,10 +289,16 @@ declare module Backbone { // SYNC function sync(method, model, options?: JQueryAjaxSettings); - var emulateHTTP: bool; - var emulateJSONBackbone: bool; + var emulateHTTP: boolean; + var emulateJSONBackbone: boolean; // Utility - function noConflict(): Backbone; + + // 0.9 cannot return modules anymore, and "typeof " is not compiling for some reason + // returning "any" until this is fixed + + //function noConflict(): typeof Backbone; + function noConflict(): any; + function setDomLibrary(jQueryNew); } diff --git a/chai-jquery/chai-jquery-tests.ts b/chai-jquery/chai-jquery-tests.ts index fbd05480e..97ed7a36a 100644 --- a/chai-jquery/chai-jquery-tests.ts +++ b/chai-jquery/chai-jquery-tests.ts @@ -1,5 +1,5 @@ -///  -///  +/// +/// declare var $; var expect = chai.expect; diff --git a/chai/chai-assert-test.ts b/chai/chai-assert-tests.ts similarity index 99% rename from chai/chai-assert-test.ts rename to chai/chai-assert-tests.ts index b4a5a15be..19429b4c9 100644 --- a/chai/chai-assert-test.ts +++ b/chai/chai-assert-tests.ts @@ -330,7 +330,7 @@ suite('assert', function () { test('isArray', function () { assert.isArray([]); - assert.isArray(new Array); + assert.isArray(new Array()); err(function () { assert.isArray({}); @@ -345,7 +345,7 @@ suite('assert', function () { }, "expected [] not to be an array"); err(function () { - assert.isNotArray(new Array); + assert.isNotArray(new Array()); }, "expected [] not to be an array"); }); diff --git a/chai/chai-assert.d.ts b/chai/chai-assert.d.ts index b31b7bde5..ab1a23d14 100644 --- a/chai/chai-assert.d.ts +++ b/chai/chai-assert.d.ts @@ -107,7 +107,7 @@ declare module chai ifError(val:any, msg?:string); } //node module - declare var assert:Assert; + var assert:Assert; } //browser global declare var assert:chai.Assert; \ No newline at end of file diff --git a/chai/chai.d.ts b/chai/chai.d.ts index df9e12382..6a9010322 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -33,9 +33,9 @@ declare module chai { (expected: RegExp, message?: string); } - interface TypeComparison { + interface TypeComparison { (type: string, message?: string): bool; - instanceof(type: Object, ): bool; + instanceof(type: Object): bool; } interface NumericComparison { @@ -116,7 +116,6 @@ declare module chai { to: To; } - var expect : { - (target: any): ExpectMatchers; - } -} \ No newline at end of file + function expect(target: any): chai.ExpectMatchers; +} + diff --git a/cheerio/cheerio-test.ts b/cheerio/cheerio-tests.ts similarity index 93% rename from cheerio/cheerio-test.ts rename to cheerio/cheerio-tests.ts index b2a5d84f3..00cc95ee8 100644 --- a/cheerio/cheerio-test.ts +++ b/cheerio/cheerio-tests.ts @@ -1,65 +1,65 @@ -/// - -import cheerio = module("cheerio"); - -var $ = cheerio.load(""); -var $el = $('selector'); -var $multiEl = $('seletor', 'selector', 'selector'); - -$el.addClass("class").addClass("test"); -$el.hasClass("test"); -$el.removeClass("class").removeClass("test"); - -$el.attr('class'); -$el.attr('class', 'test'); -$el.removeAttr("class").removeAttr("test"); - -$el.find("ul").find("> li"); - -$el.parent().parent(); -$el.next().next(); -$el.prev().prev(); -$el.siblings().siblings(); - -$el.children().children(); -$el.children("li").children("a"); - -$el.children().each((index, element) => { - $(element).find('t'); -}); - -$el.children().map((index, element) => { - return $(element).find('t'); -}); - -$el.children().filter((index) => { - return $el.children().eq(index).find('t'); -}); - -$el.filter('span').filter('li'); - -$el.first().last().find('t'); - -$('div').eq(0).find('b'); - -$('#id').append("test html", "other html").find('a'); -$('#id').prepend("test html", "other html").find('a'); -$('#id').after("test html", "other html").find('a'); -$('#id').before("test html", "other html").find('a'); - -$el.remove('div').remove('a'); - -$('#id').replaceWith('some html').parent(); -$('#id').empty().parent(); - -$el.html(); -$el.html("").find('div'); - -$el.text(); -$el.text('some text'); - -$el.toArray(); -$el.clone().find('a').parent(); -$el.root().find('a'); - -$el.dom(); +/// + +import cheerio = module("cheerio"); + +var $ = cheerio.load(""); +var $el = $('selector'); +var $multiEl = $('seletor', 'selector', 'selector'); + +$el.addClass("class").addClass("test"); +$el.hasClass("test"); +$el.removeClass("class").removeClass("test"); + +$el.attr('class'); +$el.attr('class', 'test'); +$el.removeAttr("class").removeAttr("test"); + +$el.find("ul").find("> li"); + +$el.parent().parent(); +$el.next().next(); +$el.prev().prev(); +$el.siblings().siblings(); + +$el.children().children(); +$el.children("li").children("a"); + +$el.children().each((index, element) => { + return $(element).find('t'); +}); + +$el.children().map((index, element) => { + return $(element).find('t'); +}); + +$el.children().filter((index) => { + return $el.children().eq(index).find('t'); +}); + +$el.filter('span').filter('li'); + +$el.first().last().find('t'); + +$('div').eq(0).find('b'); + +$('#id').append("test html", "other html").find('a'); +$('#id').prepend("test html", "other html").find('a'); +$('#id').after("test html", "other html").find('a'); +$('#id').before("test html", "other html").find('a'); + +$el.remove('div').remove('a'); + +$('#id').replaceWith('some html').parent(); +$('#id').empty().parent(); + +$el.html(); +$el.html("").find('div'); + +$el.text(); +$el.text('some text'); + +$el.toArray(); +$el.clone().find('a').parent(); +$el.root().find('a'); + +$el.dom(); diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index cbf9e12da..8bb7307c0 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare interface Cheerio { +interface Cheerio { addClass(classNames: string): Cheerio; hasClass(className: string): bool; @@ -65,13 +65,13 @@ declare interface Cheerio { } -declare interface CheerioOptionsInterface { +interface CheerioOptionsInterface { ignoreWhitespace?: bool; xmlMode?: bool; lowerCaseTags?: bool; } -declare interface CheerioStatic { +interface CheerioStatic { (...selectors: any[]): Cheerio; (): Cheerio; } diff --git a/colors/colors.test.ts b/colors/colors-test.ts similarity index 100% rename from colors/colors.test.ts rename to colors/colors-test.ts diff --git a/colors/colors.d.ts b/colors/colors.d.ts index 99388e69d..c87112d7c 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare interface String { +interface String { bold:string; italic:string; underline:string; diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index 1581cdb71..872432f34 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -48,7 +48,7 @@ function testPieChart() { } //Example from http://bl.ocks.org/3887051 -function groupedBarChart() => { +function groupedBarChart() { var margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; @@ -105,7 +105,7 @@ function groupedBarChart() => { .style("text-anchor", "end") .text("Population"); - var state = svg.selectAll(".state") + var state = svg.selectAll(".state") .data(data) .enter().append("g") .attr("class", "g") @@ -487,7 +487,7 @@ function callenderView() { } // example from http://bl.ocks.org/3883245 -function lineChart { +function lineChart() { var margin = { top: 20, right: 20, bottom: 30, left: 50 }, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; @@ -550,7 +550,7 @@ function lineChart { } //example from http://bl.ocks.org/3884914 -function bivariateAreaChart { +function bivariateAreaChart() { var margin = { top: 20, right: 20, bottom: 30, left: 50 }, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; @@ -590,7 +590,7 @@ function bivariateAreaChart { }); x.domain(d3.extent(data, function (d) { return d.date; })); - y.domain([d3.min(data, function (d) { return d.low; }), d3.max(data, function (d) { return d.high; })]); + y.domain([d3.min(data, function (d) { return d.low; }), d3.max(data, function (d) { return d.high; })]); svg.append("path") .datum(data) @@ -610,12 +610,12 @@ function bivariateAreaChart { .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") - .text("Temperature (ºF)"); + .text("Temperature (ºF)"); }); } //Example from http://bl.ocks.org/mbostock/1557377 -function dragMultiples { +function dragMultiples() { var width = 238, height = 123, radius = 20; @@ -644,7 +644,7 @@ function dragMultiples { } //Example from http://bl.ocks.org/mbostock/3892919 -function panAndZoom { +function panAndZoom() { var margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; @@ -729,3 +729,1331 @@ function chainedTransitions() { }; } } + +//Example from http://bl.ocks.org/mbostock/4062085 +function populationPyramid() { + var margin = { top: 20, right: 40, bottom: 30, left: 20 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom, + barWidth = Math.floor(width / 19) - 1; + + var x = d3.scale.linear() + .range([barWidth / 2, width - barWidth / 2]); + + var y = d3.scale.linear() + .range([height, 0]); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("right") + .tickSize(-width) + .tickFormat(function (d) { return Math.round(d / 1e6) + "M"; } ); + + // An SVG element with a bottom-right origin. + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + // A sliding container to hold the bars by birthyear. + var birthyears = svg.append("g") + .attr("class", "birthyears"); + + // A label for the current year. + var title = svg.append("text") + .attr("class", "title") + .attr("dy", ".71em") + .text(2000); + + d3.csv("population.csv", function (error, data) { + + // Convert strings to numbers. + data.forEach(function (d) { + d.people = +d.people; + d.year = +d.year; + d.age = +d.age; + } ); + + // Compute the extent of the data set in age and years. + var age1 = d3.max(data, function (d) { return d.age; } ), + year0 = d3.min(data, function (d) { return d.year; } ), + year1 = d3.max(data, function (d) { return d.year; } ), + year = year1; + + // Update the scale domains. + x.domain([year1 - age1, year1]); + y.domain([0, d3.max(data, function (d) { return d.people; } )]); + + // Produce a map from year and birthyear to [male, female]. + data = d3.nest() + .key(function (d) { return d.year; } ) + .key(function (d) { return d.year - d.age; } ) + .rollup(function (v) { return v.map(function (d) { return d.people; } ); } ) + .map(data); + + // Add an axis to show the population values. + svg.append("g") + .attr("class", "y axis") + .attr("transform", "translate(" + width + ",0)") + .call(yAxis) + .selectAll("g") + .filter(function (value) { return !value; } ) + .classed("zero", true); + + // Add labeled rects for each birthyear (so that no enter or exit is required). + var birthyear = birthyears.selectAll(".birthyear") + .data(d3.range(year0 - age1, year1 + 1, 5)) + .enter().append("g") + .attr("class", "birthyear") + .attr("transform", function (birthyear) { return "translate(" + x(birthyear) + ",0)"; } ); + + birthyear.selectAll("rect") + .data(function (birthyear) { return data[year][birthyear] || [0, 0]; } ) + .enter().append("rect") + .attr("x", -barWidth / 2) + .attr("width", barWidth) + .attr("y", y) + .attr("height", function (value) { return height - y(value); } ); + + // Add labels to show birthyear. + birthyear.append("text") + .attr("y", height - 4) + .text(function (birthyear) { return birthyear; } ); + + // Add labels to show age (separate; not animated). + svg.selectAll(".age") + .data(d3.range(0, age1 + 1, 5)) + .enter().append("text") + .attr("class", "age") + .attr("x", function (age) { return x(year - age); } ) + .attr("y", height + 4) + .attr("dy", ".71em") + .text(function (age) { return age; } ); + + // Allow the arrow keys to change the displayed year. + window.focus(); + d3.select(window).on("keydown", function () { + switch (d3.event.keyCode) { + case 37: year = Math.max(year0, year - 10); break; + case 39: year = Math.min(year1, year + 10); break; + } + update(); + } ); + + function update() { + if (!(year in data)) return; + title.text(year); + + birthyears.transition() + .duration(750) + .attr("transform", "translate(" + (x(year1) - x(year)) + ",0)"); + + birthyear.selectAll("rect") + .data(function (birthyear) { return data[year][birthyear] || [0, 0]; } ) + .transition() + .duration(750) + .attr("y", y) + .attr("height", function (value) { return height - y(value); } ); + } + } ); +} + +//Example from http://bl.ocks.org/MoritzStefaner/1377729 +function forcedBasedLabelPlacemant() { + var w = 960, h = 500; + + var labelDistance = 0; + + var vis = d3.select("body").append("svg:svg").attr("width", w).attr("height", h); + + var nodes = []; + var labelAnchors = []; + var labelAnchorLinks = []; + var links = []; + + for (var i = 0; i < 30; i++) { + var nodeLabel = { + label: "node " + i + }; + nodes.push(nodeLabel); + labelAnchors.push({ + node: nodeLabel + }); + labelAnchors.push({ + node: nodeLabel + }); + }; + + for (var i = 0; i < nodes.length; i++) { + for (var j = 0; j < i; j++) { + if (Math.random() > .95) + links.push({ + source: i, + target: j, + weight: Math.random() + }); + } + labelAnchorLinks.push({ + source: i * 2, + target: i * 2 + 1, + weight: 1 + }); + }; + + var force = d3.layout.force().size([w, h]).nodes(nodes).links(links).gravity(1).linkDistance(50).charge(-3000).linkStrength(function (x) { + return x.weight * 10 + } ); + + + force.start(); + + var force2 = d3.layout.force().nodes(labelAnchors).links(labelAnchorLinks).gravity(0).linkDistance(0).linkStrength(8).charge(-100).size([w, h]); + force2.start(); + + var link = vis.selectAll("line.link").data(links).enter().append("svg:line").attr("class", "link").style("stroke", "#CCC"); + + var node = vis.selectAll("g.node").data(force.nodes()).enter().append("svg:g").attr("class", "node"); + node.append("svg:circle").attr("r", 5).style("fill", "#555").style("stroke", "#FFF").style("stroke-width", 3); + node.call(force.drag); + + + var anchorLink = vis.selectAll("line.anchorLink").data(labelAnchorLinks)//.enter().append("svg:line").attr("class", "anchorLink").style("stroke", "#999"); + + var anchorNode = vis.selectAll("g.anchorNode").data(force2.nodes()).enter().append("svg:g").attr("class", "anchorNode"); + anchorNode.append("svg:circle").attr("r", 0).style("fill", "#FFF"); + anchorNode.append("svg:text").text(function (d, i) { + return i % 2 == 0 ? "" : d.node.label + } ).style("fill", "#555").style("font-family", "Arial").style("font-size", 12); + + var updateLink = function () { + this.attr("x1", function (d) { + return d.source.x; + } ).attr("y1", function (d) { + return d.source.y; + } ).attr("x2", function (d) { + return d.target.x; + } ).attr("y2", function (d) { + return d.target.y; + } ); + + } + + var updateNode = function () { + this.attr("transform", function (d) { + return "translate(" + d.x + "," + d.y + ")"; + } ); + + } + + force.on("tick", function () { + + force2.start(); + + node.call(updateNode); + + anchorNode.each(function (d, i) { + if (i % 2 == 0) { + d.x = d.node.x; + d.y = d.node.y; + } else { + var b = this.childNodes[1].getBBox(); + + var diffX = d.x - d.node.x; + var diffY = d.y - d.node.y; + + var dist = Math.sqrt(diffX * diffX + diffY * diffY); + + var shiftX = b.width * (diffX - dist) / (dist * 2); + shiftX = Math.max(-b.width, Math.min(0, shiftX)); + var shiftY = 5; + this.childNodes[1].setAttribute("transform", "translate(" + shiftX + "," + shiftY + ")"); + } + } ); + + + anchorNode.call(updateNode); + + link.call(updateLink); + anchorLink.call(updateLink); + + } ); +} + +//Example from http://bl.ocks.org/mbostock/1125997 +function forceCollapsable() { + var w = 1280, + h = 800, + node, + link, + root; + + var force = d3.layout.force() + .on("tick", tick) + .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) + .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) + .size([w, h - 160]); + + var vis = d3.select("body").append("svg:svg") + .attr("width", w) + .attr("height", h); + + d3.json("flare.json", function (json) { + root = json; + root.fixed = true; + root.x = w / 2; + root.y = h / 2 - 80; + update(); + } ); + + function update() { + var nodes = flatten(root), + links = d3.layout.tree().links(nodes); + + // Restart the force layout. + force + .nodes(nodes) + .links(links) + .start(); + + // Update the links… + link = vis.selectAll("line.link") + .data(links, function (d) { return d.target.id; } ); + + // Enter any new links. + link.enter().insert("svg:line", ".node") + .attr("class", "link") + .attr("x1", function (d) { return d.source.x; } ) + .attr("y1", function (d) { return d.source.y; } ) + .attr("x2", function (d) { return d.target.x; } ) + .attr("y2", function (d) { return d.target.y; } ); + + // Exit any old links. + link.exit().remove(); + + // Update the nodes… + node = vis.selectAll("circle.node") + .data(nodes, function (d) { return d.id; } ) + .style("fill", color); + + node.transition() + .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ); + + // Enter any new nodes. + node.enter().append("svg:circle") + .attr("class", "node") + .attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ) + .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ) + .style("fill", color) + .on("click", click) + .call(force.drag); + + // Exit any old nodes. + node.exit().remove(); + } + + function tick() { + link.attr("x1", function (d) { return d.source.x; } ) + .attr("y1", function (d) { return d.source.y; } ) + .attr("x2", function (d) { return d.target.x; } ) + .attr("y2", function (d) { return d.target.y; } ); + + node.attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ); + } + + // Color leaf nodes orange, and packages white or blue. + function color(d) { + return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c"; + } + + // Toggle children on click. + function click(d) { + if (d.children) { + d._children = d.children; + d.children = null; + } else { + d.children = d._children; + d._children = null; + } + update(); + } + + // Returns a list of all nodes under the root. + function flatten(root) { + var nodes = [], i = 0; + + function recurse(node) { + if (node.children) node.size = node.children.reduce(function (p, v) { return p + recurse(v); } , 0); + if (!node.id) node.id = ++i; + nodes.push(node); + return node.size; + } + + root.size = recurse(root); + return nodes; + } +} + +//Example from http://bl.ocks.org/mbostock/3757110 +function azimuthalEquidistant() { + var width = 960, + height = 960; + var topojson: any; + + var projection = d3.geo.azimuthalEquidistant() + .scale(150) + .translate([width / 2, height / 2]) + .clipAngle(180 - 1e-3) + .precision(.1); + + var path = d3.geo.path() + .projection(projection); + + var graticule = d3.geo.graticule(); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height); + + svg.append("defs").append("path") + .datum({ type: "Sphere" }) + .attr("id", "sphere") + .attr("d", path); + + svg.append("use") + .attr("class", "stroke") + .attr("xlink:href", "#sphere"); + + svg.append("use") + .attr("class", "fill") + .attr("xlink:href", "#sphere"); + + svg.append("path") + .datum(graticule) + .attr("class", "graticule") + .attr("d", path); + + d3.json("/mbostock/raw/4090846/world-50m.json", function (error, world) { + svg.insert("path", ".graticule") + .datum(topojson.feature(world, world.objects.land)) + .attr("class", "land") + .attr("d", path); + + svg.insert("path", ".graticule") + .datum(topojson.mesh(world, world.objects.countries, function (a, b) { return a !== b; } )) + .attr("class", "boundary") + .attr("d", path); + } ); + + d3.select(self.frameElement).style("height", height + "px"); +} + +//Example from http://bl.ocks.org/mbostock/4060366 +function voroniTesselation() { + var width = 960, + height = 500; + + var vertices = >d3.range(100).map(function (d) { + return [Math.random() * width, Math.random() * height]; + } ); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .attr("class", "PiYG") + .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ); + + var path = svg.append("g").selectAll("path"); + + svg.selectAll("circle") + .data(vertices.slice(1)) + .enter().append("circle") + .attr("transform", function (d) { return "translate(" + d + ")"; } ) + .attr("r", 2); + + redraw(); + + function redraw() { + path = path.data(d3.geom.voronoi(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String); + path.exit().remove(); + path.enter().append("path").attr("class", function (d, i) { return "q" + (i % 9) + "-9"; } ).attr("d", String); + path.order(); + } +} + +//Example from http://bl.ocks.org/mbostock/4341156 +function delaunayTesselation() { + var width = 960, + height = 500; + + var vertices = >d3.range(100).map(function (d) { + return [Math.random() * width, Math.random() * height]; + } ); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .attr("class", "PiYG") + .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ); + + var path = svg.append("g").selectAll("path"); + + svg.selectAll("circle") + .data(vertices.slice(1)) + .enter().append("circle") + .attr("transform", function (d) { return "translate(" + d + ")"; } ) + .attr("r", 2); + + redraw(); + + function redraw() { + path = path.data(d3.geom.delaunay(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String); + path.exit().remove(); + path.enter().append("path").attr("class", function (d, i) { return "q" + (i % 9) + "-9"; } ).attr("d", String); + } +} + +//Example from http://bl.ocks.org/mbostock/4343214 +function quadtree() { + var width = 960, + height = 500; + + var data = d3.range(5000).map(function () { + return { x: Math.random() * width, y: Math.random() * width }; + } ); + + var quadtree = d3.geom.quadtree(data, -1, -1, width + 1, height + 1); + + var brush = d3.svg.brush() + .x(d3.scale.identity().domain([0, width])) + .y(d3.scale.identity().domain([0, height])) + .on("brush", brushed) + .extent([[100, 100], [200, 200]]); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height); + + svg.selectAll(".node") + .data(nodes(quadtree)) + .enter().append("rect") + .attr("class", "node") + .attr("x", function (d) { return d.x; } ) + .attr("y", function (d) { return d.y; } ) + .attr("width", function (d) { return d.width; } ) + .attr("height", function (d) { return d.height; } ); + + var point = svg.selectAll(".point") + .data(data) + .enter().append("circle") + .attr("class", "point") + .attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ) + .attr("r", 4); + + svg.append("g") + .attr("class", "brush") + .call(brush); + + brushed(); + + function brushed() { + var extent = brush.extent(); + point.each(function (d) { d.scanned = d.selected = false; } ); + search(quadtree, extent[0][0], extent[0][1], extent[1][0], extent[1][1]); + point.classed("scanned", function (d) { return d.scanned; } ); + point.classed("selected", function (d) { return d.selected; } ); + } + + // Collapse the quadtree into an array of rectangles. + function nodes(quadtree) { + var nodes = []; + quadtree.visit(function (node, x1, y1, x2, y2) { + nodes.push({ x: x1, y: y1, width: x2 - x1, height: y2 - y1 }); + } ); + return nodes; + } + + // Find the nodes within the specified rectangle. + function search(quadtree, x0, y0, x3, y3) { + quadtree.visit(function (node, x1, y1, x2, y2) { + var p = node.point; + if (p) { + p.scanned = true; + p.selected = (p.x >= x0) && (p.x < x3) && (p.y >= y0) && (p.y < y3); + } + return x1 >= x3 || y1 >= y3 || x2 < x0 || y2 < y0; + } ); + } +} + +//Example from http://bl.ocks.org/mbostock/4341699 +function convexHull() { + var width = 960, + height = 500; + + var randomX = d3.random.normal(width / 2, 60), + randomY = d3.random.normal(height / 2, 60), + vertices = d3.range(100).map(function () { return [randomX(), randomY()]; } ); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ) + .on("click", function () { vertices.push(d3.mouse(this)); redraw(); } ); + + svg.append("rect") + .attr("width", width) + .attr("height", height); + + var hull = svg.append("path") + .attr("class", "hull"); + + var circle = svg.selectAll("circle"); + + redraw(); + + function redraw() { + hull.datum(d3.geom.hull(vertices)).attr("d", function (d) { return "M" + d.join("L") + "Z"; } ); + circle = circle.data(vertices); + circle.enter().append("circle").attr("r", 3); + circle.attr("transform", function (d) { return "translate(" + d + ")"; } ); + } +} + +// example from http://bl.ocks.org/mbostock/1044242 +function hierarchicalEdgeBundling() { + var diameter = 960, + radius = diameter / 2, + innerRadius = radius - 120; + + var cluster = d3.layout.cluster() + .size([360, innerRadius]) + .sort(null) + .value(function (d) { return d.size; } ); + + var bundle = d3.layout.bundle(); + + var line = d3.svg.line.radial() + .interpolate("bundle") + .tension(.85) + .radius(function (d) { return d.y; } ) + .angle(function (d) { return d.x / 180 * Math.PI; } ); + + var svg = d3.select("body").append("svg") + .attr("width", diameter) + .attr("height", diameter) + .append("g") + .attr("transform", "translate(" + radius + "," + radius + ")"); + + d3.json("readme-flare-imports.json", function (error, classes) { + var nodes = cluster.nodes(packages.root(classes)), + links = packages.imports(nodes); + + svg.selectAll(".link") + .data(bundle(links)) + .enter().append("path") + .attr("class", "link") + .attr("d", line); + + svg.selectAll(".node") + .data(nodes.filter(function (n) { return !n.children; } )) + .enter().append("g") + .attr("class", "node") + .attr("transform", function (d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; } ) + .append("text") + .attr("dx", function (d) { return d.x < 180 ? 8 : -8; } ) + .attr("dy", ".31em") + .attr("text-anchor", function (d) { return d.x < 180 ? "start" : "end"; } ) + .attr("transform", function (d) { return d.x < 180 ? null : "rotate(180)"; } ) + .text(function (d) { return d.key; } ); + } ); + + d3.select(self.frameElement).style("height", diameter + "px"); + + var packages = { + + // Lazily construct the package hierarchy from class names. + root: function (classes) { + var map = {}; + + function find(name, data?) { + var node = map[name], i; + if (!node) { + node = map[name] = data || { name: name, children: [] }; + if (name.length) { + node.parent = find(name.substring(0, i = name.lastIndexOf("."))); + node.parent.children.push(node); + node.key = name.substring(i + 1); + } + } + return node; + } + + classes.forEach(function (d) { + find(d.name, d); + } ); + + return map[""]; + } , + + // Return a list of imports for the given array of nodes. + imports: function (nodes) { + var map = {}, + imports = []; + + // Compute a map from name to node. + nodes.forEach(function (d) { + map[d.name] = d; + } ); + + // For each import, construct a link from the source to target node. + nodes.forEach(function (d) { + if (d.imports) d.imports.forEach(function (i) { + imports.push({ source: map[d.name], target: map[i] }); + } ); + } ); + + return imports; + } + }; +} + +// example from http://bl.ocks.org/mbostock/1123639 +function roundedRectangles() { + var mouse = [480, 250], + count = 0; + + var svg = d3.select("body").append("svg:svg") + .attr("width", 960) + .attr("height", 500); + + var g = svg.selectAll("g") + .data(d3.range(25)) + .enter().append("svg:g") + .attr("transform", "translate(" + mouse + ")"); + + g.append("svg:rect") + .attr("rx", 6) + .attr("ry", 6) + .attr("x", -12.5) + .attr("y", -12.5) + .attr("width", 25) + .attr("height", 25) + .attr("transform", function (d, i) { return "scale(" + (1 - d / 25) * 20 + ")"; } ) + .style("fill", d3.scale.category20c()); + + g.map(function (d) { + return { center: [0, 0], angle: 0 }; + } ); + + svg.on("mousemove", function () { + mouse = d3.mouse(this); + } ); + + d3.timer(function () { + count++; + g.attr("transform", function (d, i) { + d.center[0] += (mouse[0] - d.center[0]) / (i + 5); + d.center[1] += (mouse[1] - d.center[1]) / (i + 5); + d.angle += Math.sin((count + i) / 10) * 7; + return "translate(" + d.center + ")rotate(" + d.angle + ")"; + } ); + return true; + } ); +} + +// example from http://bl.ocks.org/mbostock/4060954 +function streamGraph() { + var n = 20, // number of layers + m = 200, // number of samples per layer + stack = d3.layout.stack().offset("wiggle"), + layers0 = stack(d3.range(n).map(function () { return bumpLayer(m); } )), + layers1 = stack(d3.range(n).map(function () { return bumpLayer(m); } )); + + var width = 960, + height = 500; + + var x = d3.scale.linear() + .domain([0, m - 1]) + .range([0, width]); + + var y = d3.scale.linear() + .domain([0, d3.max(layers0.concat(layers1), function (layer) { return d3.max(layer, function (d) { return d.y0 + d.y; } ); } )]) + .range([height, 0]); + + var color = d3.scale.linear() + .range(["#aad", "#556"]); + + var area = d3.svg.area() + .x(function (d) { return x(d.x); } ) + .y0(function (d) { return y(d.y0); } ) + .y1(function (d) { return y(d.y0 + d.y); } ); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height); + + svg.selectAll("path") + .data(layers0) + .enter().append("path") + .attr("d", area) + .style("fill", function () { return color(Math.random()); } ); + + function transition() { + d3.selectAll("path") + .data(function () { + var d = layers1; + layers1 = layers0; + return layers0 = d; + } ) + .transition() + .duration(2500) + .attr("d", area); + } + + // Inspired by Lee Byron's test data generator. + function bumpLayer(n) { + + function bump(a) { + var x = 1 / (.1 + Math.random()), + y = 2 * Math.random() - .5, + z = 10 / (.1 + Math.random()); + for (var i = 0; i < n; i++) { + var w = (i / n - y) * z; + a[i] += x * Math.exp(-w * w); + } + } + + var a = [], i; + for (i = 0; i < n; ++i) a[i] = 0; + for (i = 0; i < 5; ++i) bump(a); + return a.map(function (d, i) { return { x: i, y: Math.max(0, d) }; } ); + } +} + +// example from http://mbostock.github.io/d3/talk/20111116/force-collapsible.html +function forceCollapsable2() { + var w = 1280, + h = 800, + node, + link, + root; + + var force = d3.layout.force() + .on("tick", tick) + .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) + .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) + .size([w, h - 160]); + + var vis = d3.select("body").append("svg:svg") + .attr("width", w) + .attr("height", h); + + d3.json("flare.json", function (json) { + root = json; + root.fixed = true; + root.x = w / 2; + root.y = h / 2 - 80; + update(); + } ); + + function update() { + var nodes = flatten(root), + links = d3.layout.tree().links(nodes); + + // Restart the force layout. + force + .nodes(nodes) + .links(links) + .start(); + + // Update the links… + link = vis.selectAll("line.link") + .data(links, function (d) { return d.target.id; } ); + + // Enter any new links. + link.enter().insert("svg:line", ".node") + .attr("class", "link") + .attr("x1", function (d) { return d.source.x; } ) + .attr("y1", function (d) { return d.source.y; } ) + .attr("x2", function (d) { return d.target.x; } ) + .attr("y2", function (d) { return d.target.y; } ); + + // Exit any old links. + link.exit().remove(); + + // Update the nodes… + node = vis.selectAll("circle.node") + .data(nodes, function (d) { return d.id; } ) + .style("fill", color); + + node.transition() + .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ); + + // Enter any new nodes. + node.enter().append("svg:circle") + .attr("class", "node") + .attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ) + .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ) + .style("fill", color) + .on("click", click) + .call(force.drag); + + // Exit any old nodes. + node.exit().remove(); + } + + function tick() { + link.attr("x1", function (d) { return d.source.x; } ) + .attr("y1", function (d) { return d.source.y; } ) + .attr("x2", function (d) { return d.target.x; } ) + .attr("y2", function (d) { return d.target.y; } ); + + node.attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ); + } + + // Color leaf nodes orange, and packages white or blue. + function color(d) { + return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c"; + } + + // Toggle children on click. + function click(d) { + if (d.children) { + d._children = d.children; + d.children = null; + } else { + d.children = d._children; + d._children = null; + } + update(); + } + + // Returns a list of all nodes under the root. + function flatten(root) { + var nodes = [], i = 0; + + function recurse(node) { + if (node.children) node.size = node.children.reduce(function (p, v) { return p + recurse(v); } , 0); + if (!node.id) node.id = ++i; + nodes.push(node); + return node.size; + } + + root.size = recurse(root); + return nodes; + } +} + +//exapmle from http://bl.ocks.org/mbostock/4062006 +function chordDiagram() { + var matrix = [ + [11975, 5871, 8916, 2868], + [1951, 10048, 2060, 6171], + [8010, 16145, 8090, 8045], + [1013, 990, 940, 6907] + ]; + + var chord = d3.layout.chord() + .padding(.05) + .sortSubgroups(d3.descending) + .matrix(matrix); + + var width = 960, + height = 500, + innerRadius = Math.min(width, height) * .41, + outerRadius = innerRadius * 1.1; + + var fill = d3.scale.ordinal() + .domain(d3.range(4)) + .range(["#000000", "#FFDD89", "#957244", "#F26223"]); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .append("g") + .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); + + svg.append("g").selectAll("path") + .data(chord.groups) + .enter().append("path") + .style("fill", function (d) { return fill(d.index); } ) + .style("stroke", function (d) { return fill(d.index); } ) + .attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius)) + .on("mouseover", fade(.1)) + .on("mouseout", fade(1)); + + var ticks = svg.append("g").selectAll("g") + .data(chord.groups) + .enter().append("g").selectAll("g") + .data(groupTicks) + .enter().append("g") + .attr("transform", function (d) { + return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" + + "translate(" + outerRadius + ",0)"; + } ); + + ticks.append("line") + .attr("x1", 1) + .attr("y1", 0) + .attr("x2", 5) + .attr("y2", 0) + .style("stroke", "#000"); + + ticks.append("text") + .attr("x", 8) + .attr("dy", ".35em") + .attr("transform", function (d) { return d.angle > Math.PI ? "rotate(180)translate(-16)" : null; } ) + .style("text-anchor", function (d) { return d.angle > Math.PI ? "end" : null; } ) + .text(function (d) { return d.label; } ); + + svg.append("g") + .attr("class", "chord") + .selectAll("path") + .data(chord.chords) + .enter().append("path") + .attr("d", d3.svg.chord().radius(innerRadius)) + .style("fill", function (d) { return fill(d.target.index); } ) + .style("opacity", 1); + + // Returns an array of tick angles and labels, given a group. + function groupTicks(d) { + var k = (d.endAngle - d.startAngle) / d.value; + return d3.range(0, d.value, 1000).map(function (v, i) { + return { + angle: v * k + d.startAngle, + label: i % 5 ? null : v / 1000 + "k" + }; + } ); + } + + // Returns an event handler for fading a given chord group. + function fade(opacity) { + return function (g, i) { + svg.selectAll(".chord path") + .filter(function (d) { return d.source.index != i && d.target.index != i; } ) + .transition() + .style("opacity", opacity); + }; + } +} + +//example from http://mbostock.github.io/d3/talk/20111116/iris-parallel.html +function irisParallel() { + var species = ["setosa", "versicolor", "virginica"], + traits = ["sepal length", "petal length", "sepal width", "petal width"]; + + var m = [80, 160, 200, 160], + w = 1280 - m[1] - m[3], + h = 800 - m[0] - m[2]; + + var x = d3.scale.ordinal().domain(traits).rangePoints([0, w]), + y = {}; + + var line = d3.svg.line(), + axis = d3.svg.axis().orient("left"), + foreground; + + var svg = d3.select("body").append("svg:svg") + .attr("width", w + m[1] + m[3]) + .attr("height", h + m[0] + m[2]) + .append("svg:g") + .attr("transform", "translate(" + m[3] + "," + m[0] + ")"); + + d3.csv("iris.csv", function (flowers) { + + // Create a scale and brush for each trait. + traits.forEach(function (d) { + // Coerce values to numbers. + flowers.forEach(function (p) { p[d] = +p[d]; } ); + + y[d] = d3.scale.linear() + .domain(d3.extent(flowers, function (p) { return p[d]; } )) + .range([h, 0]); + + y[d].brush = d3.svg.brush() + .y(y[d]) + .on("brush", brush); + } ); + + // Add a legend. + var legend = svg.selectAll("g.legend") + .data(species) + .enter().append("svg:g") + .attr("class", "legend") + .attr("transform", function (d, i) { return "translate(0," + (i * 20 + 584) + ")"; } ); + + legend.append("svg:line") + .attr("class", String) + .attr("x2", 8); + + legend.append("svg:text") + .attr("x", 12) + .attr("dy", ".31em") + .text(function (d) { return "Iris " + d; } ); + + // Add foreground lines. + foreground = svg.append("svg:g") + .attr("class", "foreground") + .selectAll("path") + .data(flowers) + .enter().append("svg:path") + .attr("d", path) + .attr("class", function (d) { return d.species; } ); + + // Add a group element for each trait. + var g = svg.selectAll(".trait") + .data(traits) + .enter().append("svg:g") + .attr("class", "trait") + .attr("transform", function (d) { return "translate(" + x(d) + ")"; } ) + .call(d3.behavior.drag() + .origin(function (d) { return { x: x(d) }; } ) + .on("dragstart", dragstart) + .on("drag", drag) + .on("dragend", dragend)); + + // Add an axis and title. + g.append("svg:g") + .attr("class", "axis") + .each(function (d) { d3.select(this).call(axis.scale(y[d])); } ) + .append("svg:text") + .attr("text-anchor", "middle") + .attr("y", -9) + .text(String); + + // Add a brush for each axis. + g.append("svg:g") + .attr("class", "brush") + .each(function (d) { d3.select(this).call(y[d].brush); } ) + .selectAll("rect") + .attr("x", -8) + .attr("width", 16); + + function dragstart(d, i?) { + i = traits.indexOf(d); + } + + function drag(d, i?) { + x.range()[i] = d3.event.x; + traits.sort(function (a, b) { return x(a) - x(b); } ); + g.attr("transform", function (d) { return "translate(" + x(d) + ")"; } ); + foreground.attr("d", path); + } + + function dragend(d) { + x.domain(traits).rangePoints([0, w]); + var t = d3.transition().duration(500); + t.selectAll(".trait").attr("transform", function (d) { return "translate(" + x(d) + ")"; } ); + t.selectAll(".foreground path").attr("d", path); + } + } ); + + // Returns the path for a given data point. + function path(d) { + return line(traits.map(function (p) { return [x(p), y[p](d[p])]; } )); + } + + // Handles a brush event, toggling the display of foreground lines. + function brush() { + var actives = traits.filter(function (p) { return !y[p].brush.empty(); } ), + extents = actives.map(function (p) { return y[p].brush.extent(); } ); + foreground.classed("fade", function (d) { + return !actives.every(function (p, i) { + return extents[i][0] <= d[p] && d[p] <= extents[i][1]; + } ); + } ); + } +} + +//example from +function healthAndWealth() { + // Various accessors that specify the four dimensions of data to visualize. + function x(d) { return d.income; } + function y(d) { return d.lifeExpectancy; } + function radius(d) { return d.population; } + function color(d) { return d.region; } + function key(d) { return d.name; } + + // Chart dimensions. + var margin = { top: 19.5, right: 19.5, bottom: 19.5, left: 39.5 }, + width = 960 - margin.right, + height = 500 - margin.top - margin.bottom; + + // Various scales. These domains make assumptions of data, naturally. + var xScale = d3.scale.log().domain([300, 1e5]).range([0, width]), + yScale = d3.scale.linear().domain([10, 85]).range([height, 0]), + radiusScale = d3.scale.sqrt().domain([0, 5e8]).range([0, 40]), + colorScale = d3.scale.category10(); + + // The x & y axes. + var xAxis = d3.svg.axis().orient("bottom").scale(xScale).ticks(12, d3.format(",d")), + yAxis = d3.svg.axis().scale(yScale).orient("left"); + + // Create the SVG container and set the origin. + var svg = d3.select("#chart").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + // Add the x-axis. + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + // Add the y-axis. + svg.append("g") + .attr("class", "y axis") + .call(yAxis); + + // Add an x-axis label. + svg.append("text") + .attr("class", "x label") + .attr("text-anchor", "end") + .attr("x", width) + .attr("y", height - 6) + .text("income per capita, inflation-adjusted (dollars)"); + + // Add a y-axis label. + svg.append("text") + .attr("class", "y label") + .attr("text-anchor", "end") + .attr("y", 6) + .attr("dy", ".75em") + .attr("transform", "rotate(-90)") + .text("life expectancy (years)"); + + // Add the year label; the value is set on transition. + var label = svg.append("text") + .attr("class", "year label") + .attr("text-anchor", "end") + .attr("y", height - 24) + .attr("x", width) + .text(1800); + + // Load the data. + d3.json("nations.json", function (nations) { + + // A bisector since many nation's data is sparsely-defined. + var bisect = d3.bisector(function (d) { return d[0]; } ); + + // Add a dot per nation. Initialize the data at 1800, and set the colors. + var dot = svg.append("g") + .attr("class", "dots") + .selectAll(".dot") + .data(interpolateData(1800)) + .enter().append("circle") + .attr("class", "dot") + .style("fill", function (d) { return colorScale(color(d)); } ) + .call(position) + .sort(order); + + // Add a title. + dot.append("title") + .text(function (d) { return d.name; } ); + + // Add an overlay for the year label. + var box = label.node().getBBox(); + + var overlay = svg.append("rect") + .attr("class", "overlay") + .attr("x", box.x) + .attr("y", box.y) + .attr("width", box.width) + .attr("height", box.height) + .on("mouseover", enableInteraction); + + // Start a transition that interpolates the data based on year. + svg.transition() + .duration(30000) + .ease("linear") + .tween("year", tweenYear) + .each("end", enableInteraction); + + // Positions the dots based on data. + function position(dot) { + dot.attr("cx", function (d) { return xScale(x(d)); } ) + .attr("cy", function (d) { return yScale(y(d)); } ) + .attr("r", function (d) { return radiusScale(radius(d)); } ); + } + + // Defines a sort order so that the smallest dots are drawn on top. + function order(a, b) { + return radius(b) - radius(a); + } + + // After the transition finishes, you can mouseover to change the year. + function enableInteraction() { + var yearScale = d3.scale.linear() + .domain([1800, 2009]) + .range([box.x + 10, box.x + box.width - 10]) + .clamp(true); + + // Cancel the current transition, if any. + svg.transition().duration(0); + + overlay + .on("mouseover", mouseover) + .on("mouseout", mouseout) + .on("mousemove", mousemove) + .on("touchmove", mousemove); + + function mouseover() { + label.classed("active", true); + } + + function mouseout() { + label.classed("active", false); + } + + function mousemove() { + displayYear(yearScale.invert(d3.mouse(this)[0])); + } + } + + // Tweens the entire chart by first tweening the year, and then the data. + // For the interpolated data, the dots and label are redrawn. + function tweenYear() { + var year = d3.interpolateNumber(1800, 2009); + return function (t) { displayYear(year(t)); }; + } + + // Updates the display to show the specified year. + function displayYear(year) { + dot.data(interpolateData(year), key).call(position).sort(order); + label.text(Math.round(year)); + } + + // Interpolates the dataset for the given (fractional) year. + function interpolateData(year) { + return nations.map(function (d) { + return { + name: d.name, + region: d.region, + income: interpolateValues(d.income, year), + population: interpolateValues(d.population, year), + lifeExpectancy: interpolateValues(d.lifeExpectancy, year) + }; + } ); + } + + // Finds (and possibly interpolates) the value for the specified year. + function interpolateValues(values, year) { + var i = bisect.left(values, year, 0, values.length - 1), + a = values[i]; + if (i > 0) { + var b = values[i - 1], + t = (year - a[0]) / (b[0] - a[0]); + return a[1] * (1 - t) + b[1] * t; + } + return a[1]; + } + } ); +} diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 2f60ad1dc..a79bbd8e9 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module D3 { - interface Selectors { + export interface Selectors { /** * Select an element from the current document */ @@ -42,145 +42,7 @@ declare module D3 { }; } - interface Behavior { - /** - * Constructs a new drag behaviour - */ - drag: () => Drag; - /** - * Constructs a new zoom behaviour - */ - zoom: () => Zoom; - } - - interface Zoom { - /** - * Execute zoom method - */ - (): any; - - /** - * Registers a listener to receive events - * - * @param type Enent name to attach the listener to - * @param listener Function to attach to event - */ - on: (type: string, listener: (data: any, index?: number) => any) => Zoom; - - /** - * Gets or set the current zoom scale - */ - scale: { - /** - * Get the current current zoom scale - */ - (): number; - /** - * Set the current current zoom scale - * - * @param origin Zoom scale - */ - (scale: number): Zoom; - }; - - /** - * Gets or set the current zoom translation vector - */ - translate: { - /** - * Get the current zoom translation vector - */ - (): number[]; - /** - * Set the current zoom translation vector - * - * @param translate Tranlation vector - */ - (translate: number[]): Zoom; - }; - - /** - * Gets or set the allowed scale range - */ - scaleExtent: { - /** - * Get the current allowed zoom range - */ - (): number[]; - /** - * Set the allowable zoom range - * - * @param extent Allowed zoom range - */ - (extent: number[]): Zoom; - }; - - /** - * Gets or set the X-Scale that should be adjusted when zooming - */ - x: { - /** - * Get the X-Scale - */ - (): Scale; - /** - * Set the X-Scale to be adjusted - * - * @param x The X Scale - */ - (x: Scale): Zoom; - - }; - - /** - * Gets or set the Y-Scale that should be adjusted when zooming - */ - y: { - /** - * Get the Y-Scale - */ - (): Scale; - /** - * Set the Y-Scale to be adjusted - * - * @param y The Y Scale - */ - (y: Scale): Zoom; - }; - } - - interface Drag { - /** - * Execute drag method - */ - (): any; - - /** - * Registers a listener to receive events - * - * @param type Enent name to attach the listener to - * @param listener Function to attach to event - */ - on: (type: string, listener: (data: any, index?: number) => any) => Drag; - - /** - * Gets or set the current origin accessor function - */ - origin: { - /** - * Get the current origin accessor function - */ - (): any; - /** - * Set the origin accessor function - * - * @param origin Accessor function - */ - (origin?: any): Drag; - }; - } - - interface Event { + export interface Event { dx: number; dy: number; clientX: number; @@ -190,79 +52,78 @@ declare module D3 { sourceEvent: Event; x: number; y: number; + keyCode: number; altKey: any; } - interface Base extends Selectors { + export interface Base extends Selectors { /** * Create a behaviour */ - behavior: Behavior; + behavior: Behaviour.Behavior; /** * Access the current user event for interaction */ event: Event; - + /** * Compare two values for sorting. * Returns -1 if a is less than b, or 1 if a is greater than b, or 0 * - * @param a First number - * @param b Second number + * @param a First value + * @param b Second value */ - ascending: (a: number, b: number) => number; + ascending(a: T, b: T): number; /** * Compare two values for sorting. * Returns -1 if a is greater than b, or 1 if a is less than b, or 0 * - * @param a First number - * @param b Second number + * @param a First value + * @param b Second value */ - descending: (a: number, b: number) => number; + descending(a: T, b: T): number; /** * Find the minimum value in an array * * @param arr Array to search * @param map Accsessor function */ - min: (arr: number[], map?: (v: any) => any) => number; + min(arr: T[], map?: (v: T) => number): number; /** * Find the maximum value in an array * * @param arr Array to search * @param map Accsessor function */ - max: (arr: any[], map?: (v: any) => number) => number; - - + max(arr: T[], map?: (v: T) => number): number; /** * Find the minimum and maximum value in an array * * @param arr Array to search * @param map Accsessor function */ - extent: (arr: number[], map?: (v: any) => any) => number[]; + extent(arr: T[], map?: (v: T) => number): number[]; /** * Compute the sum of an array of numbers * * @param arr Array to search * @param map Accsessor function */ - sum: (arr: number[], map?: (v: any) => any) => number; + sum(arr: T[], map?: (v: T) => number): number; /** * Compute the arithmetic mean of an array of numbers * * @param arr Array to search * @param map Accsessor function */ - mean: (arr: number[], map?: (v: any) => any) => number; + mean(arr: T[], map?: (v: T) => number): number; /** * Compute the median of an array of numbers (the 0.5-quantile). * * @param arr Array to search * @param map Accsessor function */ - median: (arr: number[], map?: (v: any) => any) => number; + median(arr: T[], map?: (v: T) => number): number; /** * Compute a quantile for a sorted array of numbers. * @@ -278,7 +139,7 @@ declare module D3 { * @param low Minimum value of array subset * @param hihg Maximum value of array subset */ - bisect: (arr: any[], x: any, low?: number, high?: number) => number; + bisect(arr: T[], x: T, low?: number, high?: number): number; /** * Locate the insertion point for x in array to maintain sorted order * @@ -287,7 +148,7 @@ declare module D3 { * @param low Minimum value of array subset * @param high Maximum value of array subset */ - bisectLeft: (arr: any[], x: any, low?: number, high?: number) => number; + bisectLeft(arr: T[], x: T, low?: number, high?: number): number; /** * Locate the insertion point for x in array to maintain sorted order * @@ -296,7 +157,7 @@ declare module D3 { * @param low Minimum value of array subset * @param high Maximum value of array subset */ - bisectRight: (arr: any[], x: any, low?: number, high?: number) => number; + bisectRight(arr: T[], x: T, low?: number, high?: number): number; /** * Bisect using an accessor. * @@ -308,7 +169,7 @@ declare module D3 { * * @param arr Array to randomise */ - shuffle(arr: any[]): any[]; + shuffle(arr: T[]): T[]; /** * Reorder an array of elements according to an array of indexes * @@ -376,7 +237,6 @@ declare module D3 { * Create new nest operator */ nest(): Nest; - /** * Request a resource using XMLHttpRequest. */ @@ -423,7 +283,7 @@ declare module D3 { * @param url Url to request * @param callback Function to invoke when resource is loaded or the request fails */ - json: (url: string, callback?: (response: any) => void ) => Xhr; + json: (url: string, callback?: (error: any, data: any) => void ) => Xhr; /** * Request an HTML document fragment. */ @@ -454,163 +314,213 @@ declare module D3 { /** * Request a comma-separated values (CSV) file. */ - csv: { - /** - * Request a comma-separated values (CSV) file. - * - * @param url Url to request - * @param callback Function to invoke when resource is loaded or the request fails - */ - (url: string, callback?: (error: any, response: any[]) => void ): Xhr; - /** - * Parse a CSV string into objects using the header row. - * - * @param string CSV formatted string to parse - */ - parse(string: string): any[]; - /** - * Parse a CSV string into tuples, ignoring the header row. - * - * @param string CSV formatted string to parse - */ - parseRows(string: string, accessor: (row: any[], index: number) => any): any; - /** - * Format an array of tuples into a CSV string. - * - * @param rows Array to convert to a CSV string - */ - format(rows: any[]): string; - }; + csv: Dsv; /** * Request a tab-separated values (TSV) file */ - tsv: { - /** - * Request a tab-separated values (TSV) file - * - * @param url Url to request - * @param callback Function to invoke when resource is loaded or the request fails - */ - (url: string, callback?: (error: any, response: any[]) => void ): Xhr; - /** - * Parse a TSV string into objects using the header row. - * - * @param string TSV formatted string to parse - */ - parse(string: string): any[]; - /** - * Parse a TSV string into tuples, ignoring the header row. - * - * @param string TSV formatted string to parse - */ - parseRows(string: string, accessor: (row: any[], index: number) => any): any; - /** - * Format an array of tuples into a TSV string. - * - * @param rows Array to convert to a TSV string - */ - format(rows: any[]): string; - }; - + tsv: Dsv; /** * Time Functions */ - time: Time; - + time: Time.Time; /** * Scales */ - scale: { - /** - * Construct a linear quantitative scale. - */ - linear(): LinearScale; - /* - * Construct an ordinal scale. - */ - ordinal(): OrdinalScale; - /** - * Construct a linear quantitative scale with a discrete output range. - */ - quantize(): QuantizeScale; - /* - * Construct an ordinal scale with ten categorical colors. - */ - category10(): OrdinalScale; - /* - * Construct an ordinal scale with twenty categorical colors - */ - category20(): OrdinalScale; - /* - * Construct an ordinal scale with twenty categorical colors - */ - category20b(): OrdinalScale; - /* - * Construct an ordinal scale with twenty categorical colors - */ - category20c(): OrdinalScale; - }; + scale: Scale.ScaleBase; /* * Interpolate two values */ - interpolate: BaseInterpolate; + interpolate: Transition.BaseInterpolate; /* * Interpolate two numbers */ - interpolateNumber: BaseInterpolate; + interpolateNumber: Transition.BaseInterpolate; /* * Interpolate two integers */ - interpolateRound: BaseInterpolate; + interpolateRound: Transition.BaseInterpolate; /* * Interpolate two strings */ - interpolateString: BaseInterpolate; + interpolateString: Transition.BaseInterpolate; /* * Interpolate two RGB colours */ - interpolateRgb: BaseInterpolate; + interpolateRgb: Transition.BaseInterpolate; /* * Interpolate two HSL colours */ - interpolateHsl: BaseInterpolate; + interpolateHsl: Transition.BaseInterpolate; + /* + * Interpolate two HCL colours + */ + interpolateHcl: Transition.BaseInterpolate; + /* + * Interpolate two L*a*b* colors + */ + interpolateLab: Transition.BaseInterpolate; /* * Interpolate two arrays of values */ - interpolateArray: BaseInterpolate; + interpolateArray: Transition.BaseInterpolate; /* * Interpolate two arbitary objects */ - interpolateObject: BaseInterpolate; + interpolateObject: Transition.BaseInterpolate; /* * Interpolate two 2D matrix transforms */ - interpolateTransform: BaseInterpolate; - + interpolateTransform: Transition.BaseInterpolate; + /* + * The array of built-in interpolator factories + */ + interpolators: Array; /** * Layouts */ - layout: Layout; - + layout: Layout.Layout; /** * Svg's */ - svg: Svg; - + svg: Svg.Svg; /** * Random number generators */ random: Random; - /** * Create a function to format a number as a string * * @param specifier The format specifier to use */ format(specifier: string): (value: number) => string; + /** + * Returns the SI prefix for the specified value at the specified precision + */ + formatPrefix(value: number, precision?: number): MetricPrefix; + /** + * The version of the d3 library + */ + version: string; + /** + * Returns the root selection + */ + selection(): Selection; + ns: { + /** + * The map of registered namespace prefixes + */ + prefix: { + svg: string; + xhtml: string; + xlink: string; + xml: string; + xmlns: string; + }; + /** + * Qualifies the specified name + */ + qualify(name: string): { space: string; local: string; }; + }; + /** + * Returns a built-in easing function of the specified type + */ + ease: (type: string, ...arrs: any[]) => Transition; + /** + * Constructs a new RGB color. + */ + rgb: { + /** + * Constructs a new RGB color with the specified r, g and b channel values + */ + (r: number, g: number, b: number): D3.Color.RGBColor; + /** + * Constructs a new RGB color by parsing the specified color string + */ + (color: string): D3.Color.RGBColor; + }; + /** + * Constructs a new HCL color. + */ + hcl: { + /** + * Constructs a new HCL color. + */ + (h: number, c: number, l: number): Color.HCLColor; + /** + * Constructs a new HCL color by parsing the specified color string + */ + (color: string): Color.HCLColor; + }; + /** + * Constructs a new HSL color. + */ + hsl: { + /** + * Constructs a new HSL color with the specified hue h, saturation s and lightness l + */ + (h: number, s: number, l: number): Color.HSLColor; + /** + * Constructs a new HSL color by parsing the specified color string + */ + (color: string): Color.HSLColor; + }; + /** + * Constructs a new RGB color. + */ + lab: { + /** + * Constructs a new LAB color. + */ + (l: number, a: number, b: number): Color.LABColor; + /** + * Constructs a new LAB color by parsing the specified color string + */ + (color: string): Color.LABColor; + }; + geo: Geo.Geo; + geom: Geom.Geom; + /** + * gets the mouse position relative to a specified container. + */ + mouse(container: any): Array; + /** + * gets the touch positions relative to a specified container. + */ + touches(container: any): Array; + functor(value: T): T; + functor(value: () => T): T; + map(object?: any): Map; + set(array?: Array): Set; + dispatch(...types: Array): Dispatch; + rebind(target: any, source: any, ...names: Array): any; + requote(str: string): string; + timer: { + (funct: () => boolean, delay?: number, mark?: number): void; + flush(): void; + } + transition(): Transition.Transition; } - interface Xhr { + export interface Dispatch { + [event: string]: any; + on: { + (type: string): any; + (type: string, listener: any): any; + } + } + + export interface MetricPrefix { + /** + * the scale function, for converting numbers to the appropriate prefixed scale. + */ + scale: (d: number) => number; + /** + * the prefix symbol + */ + symbol: string; + } + + export interface Xhr { /** * Get or set request header */ @@ -657,14 +567,14 @@ declare module D3 { * * @param value The function used to map the response to a data value */ - (value: (xhr: XMLHttpRequest) => any ): Xhr; + (value: (xhr: XMLHttpRequest) => any): Xhr; }; /** * Issue the request using the GET method * * @param callback Function to invoke on completion of request */ - get (callback?: (xhr: XMLHttpRequest) => void ): Xhr; + get(callback?: (xhr: XMLHttpRequest) => void ): Xhr; /** * Issue the request using the POST method */ @@ -716,7 +626,35 @@ declare module D3 { on: (type: string, listener: (data: any, index?: number) => any) => Xhr; } - interface Selection extends Selectors { + export interface Dsv { + /** + * Request a delimited values file + * + * @param url Url to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, callback?: (error: any, response: any[]) => void ): Xhr; + /** + * Parse a delimited string into objects using the header row. + * + * @param string delimited formatted string to parse + */ + parse(string: string): any[]; + /** + * Parse a delimited string into tuples, ignoring the header row. + * + * @param string delimited formatted string to parse + */ + parseRows(string: string, accessor: (row: any[], index: number) => any): any; + /** + * Format an array of tuples into a delimited string. + * + * @param rows Array to convert to a delimited string + */ + format(rows: any[]): string; + } + + export interface Selection extends Selectors, Array { attr: { (name: string): string; (name: string, value: any): Selection; @@ -768,617 +706,68 @@ declare module D3 { }; filter: { - (filter: (data: any, index: number) => bool): UpdateSelection; - (filter: string): UpdateSelection; + (filter: (data: any, index: number) => boolean, thisArg?: any): UpdateSelection; + //(filter: string): UpdateSelection; }; call(callback: (selection: Selection) => void ): Selection; each(eachFunction: (data: any, index: number) => any): Selection; on: { (type: string): (data: any, index: number) => any; - (type: string, listener: (data: any, index: number) => any, capture?: bool): Selection; + (type: string, listener: (data: any, index: number) => any, capture?: boolean): Selection; }; - transition: () => Transition; + transition(): Transition.Transition; + /** + * sort elements in the document based on data. + * + * params comparator the specified comparator function + */ + sort(comparator?: (a: T, b: T) => number): Selection; + order: () => Selection; + node: () => SVGLocatable; } - interface EnterSelection { + export interface EnterSelection { append: (name: string) => Selection; insert: (name: string, before: string) => Selection; select: (selector: string) => Selection; empty: () => bool; - node: () => Node; + node: () => HTMLElementSVGLocatable; } - interface UpdateSelection extends Selection { + export interface UpdateSelection extends Selection { enter: () => EnterSelection; update: () => Selection; exit: () => Selection; } - interface Transition { - duration: { - (duration: number): Transition; - (duration: (data: any, index: number) => any): Transition; - }; - delay: { - (delay: number): Transition; - (delay: (data: any, index: number) => any): Transition; - }; - attr: { - (name: string): string; - (name: string, value: any): Transition; - (name: string, valueFunction: (data: any, index: number) => any): Transition; - }; - - style: { - (name: string): string; - (name: string, value: any, priority?: string): Transition; - (name: string, valueFunction: (data: any, index: number) => any, priority?: string): Transition; - }; - - call(callback: (selection: Selection) => void ): Transition; - - select: (selector: string) => Transition; - selectAll: (selector: string) => Transition; - - each: (type?: string, eachFunction?: (data: any, index: number) => any) => Transition; - transition: () => Transition; - ease: (value: string, ...arrs: any[]) => Transition; - remove: () => Transition; - } - - interface Nest { + export interface Nest { key(keyFunction: (data: any, index: number) => any): Nest; rollup(rollupFunction: (data: any, index: number) => any): Nest; map(values: any[]): Nest; } - interface Time { - second: Interval; - minute: Interval; - hour: Interval; - day: Interval; - week: Interval; - sunday: Interval; - monday: Interval; - tuesday: Interval; - wednesday: Interval; - thursday: Interval; - friday: Interval; - saturday: Interval; - month: Interval; - year: Interval; - - seconds: Range; - minutes: Range; - hours: Range; - days: Range; - weeks: Range; - months: Range; - years: Range; - - sundays: Range; - mondays: Range; - tuesdays: Range; - wednesdays: Range; - thursdays: Range; - fridays: Range; - saturdays: Range; - format: { - - (specifier: string): TimeFormat; - utc: (specifier: string) => TimeFormat; - iso: TimeFormat; - }; - - scale(): TimeScale; + export interface Map{ + has(key: string): boolean; + get(key: string): any; + set(key: string, value: T): T; + remove(key: string): boolean; + keys(): Array; + values(): Array; + entries(): Array; + forEach(func: (key: string, value: any) => void ): void; } - interface Range { - (start: Date, end: Date, step?: number): Date[]; + export interface Set{ + has(value: any): boolean; + Add(value: any): any; + remove(value: any): boolean; + values(): Array; + forEach(func: (value: any) => void ): void; } - interface Interval { - (date: Date): Date; - floor: (date: Date) => Date; - round: (date: Date) => Date; - ceil: (date: Date) => Date; - range: Range; - offset: (date: Date, step: number) => Date; - utc: Interval; - } - - interface TimeFormat { - (date: Date): string; - parse: (string: string) => Date; - } - - interface Scale { - (value: any): any; - domain: { - (values: any[]): Scale; - (): any[]; - }; - range: { - (values: any[]): Scale; - (): any[]; - }; - copy(): Scale; - } - - interface LinearScale extends Scale { - (value: number): number; - invert(value: number): number; - domain: { - (values: any[]): LinearScale; - (): any[]; - }; - range: { - (values: any[]): LinearScale; - (): any[]; - }; - rangeRound: (values: any[]) => LinearScale; - interpolate: { - (): Interpolate; - (factory: Interpolate): LinearScale; - }; - clamp(clamp: bool): LinearScale; - nice(): LinearScale; - ticks(count: number): any[]; - tickFormat(count: number): (n: number) => string; - copy(): LinearScale; - } - - interface OrdinalScale extends Scale { - (value: any): any; - domain: { - (values: any[]): OrdinalScale; - (): any[]; - }; - range: { - (values: any[]): OrdinalScale; - (): any[]; - }; - rangePoints(interval: any[], padding?: number): OrdinalScale; - rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; - rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; - rangeBand(): number; - rangeExtent(): any[]; - copy(): OrdinalScale; - } - - interface QuantizeScale extends Scale { - (value: any): any; - domain: { - (values: number[]): QuantizeScale; - (): any[]; - }; - range: { - (values: any[]): QuantizeScale; - (): any[]; - }; - copy(): QuantizeScale; - } - - interface TimeScale extends Scale { - (value: Date): number; - invert(value: number): Date; - domain: { - (values: any[]): TimeScale; - (): any[]; - }; - range: { - (values: any[]): TimeScale; - (): any[]; - }; - rangeRound: (values: any[]) => TimeScale; - interpolate: { - (): Interpolate; - (factory: InterpolateFactory): TimeScale; - }; - clamp(clamp: bool): TimeScale; - ticks: { - (count: number): any[]; - (range: Range, count: number): any[]; - }; - tickFormat(count: number): (n: number) => string; - copy(): TimeScale; - } - - interface InterpolateFactory { - (a: any, b: any): BaseInterpolate; - } - interface BaseInterpolate { - (a: any, b: any): Interpolate; - } - - interface Interpolate { - (t: number): number; - } - - interface Layout { - stack(): StackLayout; - pie(): PieLayout; - force(): ForceLayout; - tree(): TreeLayout; - } - - interface StackLayout { - (layers: any[], index?: number): any[]; - values(accessor?: (d: any) => any): StackLayout; - offset(offset: string): StackLayout; - } - - interface PieLayout { - (values: any[], index?: number): ArcDescriptor[]; - value: { - (): (d: any, index: number) => number; - (accessor: (d: any, index: number) => number): PieLayout; - }; - sort: { - (): (d1: any, d2: any) => number; - (comparator: (d1: any, d2: any) => number): PieLayout; - }; - startAngle: { - (): number; - (angle: number): Arc; - (angle: () => number): Arc; - }; - endAngle: { - (): number; - (angle: number): Arc; - (angle: () => number): Arc; - }; - } - - interface ArcDescriptor { - value: any; - data: any; - startAngle: number; - endAngle: number; - } - - interface Symbol { - type: (string) => Symbol; - size: (number) => Symbol; - } - - - - interface ProjectionPoint - { - x: number; - y: number; - } - - interface Projector - { - (d: ProjectionPoint): ProjectionPoint; - } - - interface Diagonal - { - (): () => Diagonal; - (projectionPoint): Diagonal; - projection: - { - (projector): Diagonal; - (): Projector; - }; - - } - - interface Svg { - /** - * Create a new symbol generator - */ - symbol: () => Symbol; - /** - * Create a new axis generator - */ - axis(): Axis; - /** - * Create a new arc generator - */ - arc(): Arc; - /** - * Create a new line generator - */ - line(): Line; - /** - * Create a new area generator - */ - area(): Area; - /** - * Constructs a new diagonal generator with the default accessor functions - */ - diagonal(): Diagonal; - - } - - interface Axis { - (selection: Selection): void; - scale: { - (): any; - (scale: any): Axis; - }; - - orient: { - (): string; - (orientation: string): Axis; - }; - - ticks: { - (count: number): Axis; - (range: Range, count?: number): Axis; - }; - - tickSubdivide(count: number): Axis; - tickSize(major?: number, minor?: number, end?: number): Axis; - tickFormat(formatter: (value: any) => string): Axis; - } - - interface Arc { - (options?: ArcOptions): string; - innerRadius: { - (): number; - (radius: number): Arc; - (radius: () => number): Arc; - }; - outerRadius: { - (): number; - (radius: number): Arc; - (radius: () => number): Arc; - }; - startAngle: { - (): number; - (angle: number): Arc; - (angle: () => number): Arc; - }; - endAngle: { - (): number; - (angle: number): Arc; - (angle: () => number): Arc; - }; - centroid(options?: ArcOptions): number[]; - } - - interface ArcOptions { - innerRadius?: number; - outerRadius?: number; - startAngle?: number; - endAngle?: number; - } - - interface Line { - /** - * Returns the path data string - * - * @param data Array of data elements - * @param index Optional index - */ - (data: any[], index?: number): string; - /** - * Get or set the x-coordinate accessor. - */ - x: { - /** - * Get the x-coordinate accessor. - */ - (): (data: any) => any; - /** - * Set the x-coordinate accessor. - * - * @param accessor The new accessor function - */ - (accessor: (data: any) => any): Line; - }; - /** - * Get or set the y-coordinate accessor. - */ - y: { - /** - * Get the y-coordinate accessor. - */ - (): (data: any) => any; - /** - * Set the y-coordinate accessor. - * - * @param accessor The new accessor function - */ - (accessor: (data: any) => any): Line; - }; - /** - * Get or set the interpolation mode. - */ - interpolate: { - /** - * Get the interpolation accessor. - */ - (): string; - /** - * Set the interpolation accessor. - * - * @param interpolate The interpolation mode - */ - (interpolate: string): Line; - }; - /** - * Get or set the cardinal spline tension. - */ - tension: { - /** - * Get the cardinal spline accessor. - */ - (): number; - /** - * Set the cardinal spline accessor. - * - * @param tension The Cardinal spline interpolation tension - */ - (tension: number): Line; - }; - /** - * Control whether the line is defined at a given point. - */ - defined: { - /** - * Get the accessor function that controls where the line is defined. - */ - (): (data: any) => any; - /** - * Set the accessor function that controls where the area is defined. - * - * @param defined The new accessor function - */ - (defined: (data: any) => any): Line; - }; - } - - interface Area { - /** - * Generate a piecewise linear area, as in an area chart. - */ - (data: any[], index?: number): string; - /** - * Get or set the x-coordinate accessor. - */ - x: { - /** - * Get the x-coordinate accessor. - */ - (): (data: any) => any; - /** - * Set the x-coordinate accessor. - * - * @param accessor The new accessor function - */ - (accessor: (data: any) => any): Area; - }; - /** - * Get or set the x0-coordinate (baseline) accessor. - */ - x0: { - /** - * Get the x0-coordinate (baseline) accessor. - */ - (): (data: any) => any; - /** - * Set the x0-coordinate (baseline) accessor. - * - * @param accessor The new accessor function - */ - (accessor: (data: any) => any): Area; - }; - /** - * Get or set the x1-coordinate (topline) accessor. - */ - x1: { - /** - * Get the x1-coordinate (topline) accessor. - */ - (): (data: any) => any; - /** - * Set the x1-coordinate (topline) accessor. - * - * @param accessor The new accessor function - */ - (accessor: (data: any) => any): Area; - }; - /** - * Get or set the y-coordinate accessor. - */ - y: { - /** - * Get the y-coordinate accessor. - */ - (): (data: any) => any; - /** - * Set the y-coordinate accessor. - * - * @param accessor The new accessor function - */ - (accessor: (data: any) => any): Area; - }; - /** - * Get or set the y0-coordinate (baseline) accessor. - */ - y0: { - /** - * Get the y0-coordinate (baseline) accessor. - */ - (): (data: any) => any; - /** - * Set the y0-coordinate (baseline) accessor. - * - * @param accessor The new accessor function - */ - (accessor: (data: any) => any): Area; - }; - /** - * Get or set the y1-coordinate (topline) accessor. - */ - y1: { - /** - * Get the y1-coordinate (topline) accessor. - */ - (): (data: any) => any; - /** - * Set the y1-coordinate (topline) accessor. - * - * @param accessor The new accessor function - */ - (accessor: (data: any) => any): Area; - }; - /** - * Get or set the interpolation mode. - */ - interpolate: { - /** - * Get the interpolation accessor. - */ - (): string; - /** - * Set the interpolation accessor. - * - * @param interpolate The interpolation mode - */ - (interpolate: string): Area; - }; - /** - * Get or set the cardinal spline tension. - */ - tension: { - /** - * Get the cardinal spline accessor. - */ - (): number; - /** - * Set the cardinal spline accessor. - * - * @param tension The Cardinal spline interpolation tension - */ - (tension: number): Area; - }; - /** - * Control whether the area is defined at a given point. - */ - defined: { - /** - * Get the accessor function that controls where the area is defined. - */ - (): (data: any) => any; - /** - * Set the accessor function that controls where the area is defined. - * - * @param defined The new accessor function - */ - (defined: (data: any) => any): Area; - }; - } - - interface Random { + export interface Random { /** * Returns a function for generating random numbers with a normal distribution * @@ -1400,167 +789,2234 @@ declare module D3 { */ irwinHall(count: number): () => number; } - - // force layout definitions - export interface TwoDGraphPoint { - id: number; - index: number; - name: string; - px: number; - py: number; - size: number; - weight: number; - x: number; - y: number; - x0: number; - y0: number; + + // Transitions + export module Transition { + export interface Transition { + duration: { + (duration: number): Transition; + (duration: (data: any, index: number) => any): Transition; + }; + delay: { + (delay: number): Transition; + (delay: (data: any, index: number) => any): Transition; + }; + attr: { + (name: string): string; + (name: string, value: any): Transition; + (name: string, valueFunction: (data: any, index: number) => any): Transition; + }; + style: { + (name: string): string; + (name: string, value: any, priority?: string): Transition; + (name: string, valueFunction: (data: any, index: number) => any, priority?: string): Transition; + }; + call(callback: (selection: Selection) => void ): Transition; + /** + * Select an element from the current document + */ + select: { + /** + * Selects the first element that matches the specified selector string + * + * @param selector Selection String to match + */ + (selector: string): Transition; + /** + * Selects the specified node + * + * @param element Node element to select + */ + (element: EventTarget): Transition; + }; + + /** + * Select multiple elements from the current document + */ + selectAll: { + /** + * Selects all elements that match the specified selector + * + * @param selector Selection String to match + */ + (selector: string): Transition; + /** + * Selects the specified array of elements + * + * @param elements Array of node elements to select + */ + (elements: EventTarget[]): Transition; + } + each: (type?: string, eachFunction?: (data: any, index: number) => any) => Transition; + transition: () => Transition; + ease: (value: string, ...arrs: any[]) => Transition; + attrTween(name: string, tween: (d: any, i: number, a: any) => BaseInterpolate): Transition; + styleTween(name: string, tween: (d: any, i: number, a: any) => BaseInterpolate, priority?: string): Transition; + text: { + (text: string): Transition; + (text: (d: any, i: number) => string): Transition; + } + tween(name: string, factory: InterpolateFactory): Transition; + filter: { + (selector: string): Transition; + (selector: (data: any, index: number) => boolean): Transition; + }; + remove(): Transition; + } + + export interface InterpolateFactory { + (a?: any, b?: any): BaseInterpolate; + } + + export interface BaseInterpolate { + (a: any, b?: any): any; + } + + export interface Interpolate { + (t: any): any; + } } - export interface LayoutNode extends TwoDGraphPoint { - fixed: bool; - parent: LayoutNode; - depth: number; - children: LayoutNode[]; - _children: LayoutNode[]; + //Time + export module Time { + export interface Time { + second: Interval; + minute: Interval; + hour: Interval; + day: Interval; + week: Interval; + sunday: Interval; + monday: Interval; + tuesday: Interval; + wednesday: Interval; + thursday: Interval; + friday: Interval; + saturday: Interval; + month: Interval; + year: Interval; + + seconds: Range; + minutes: Range; + hours: Range; + days: Range; + weeks: Range; + months: Range; + years: Range; + + sundays: Range; + mondays: Range; + tuesdays: Range; + wednesdays: Range; + thursdays: Range; + fridays: Range; + saturdays: Range; + format: { + + (specifier: string): TimeFormat; + utc: (specifier: string) => TimeFormat; + iso: TimeFormat; + }; + + scale(): Scale.TimeScale; + } + + export interface Range { + (start: Date, end: Date, step?: number): Date[]; + } + + export interface Interval { + (date: Date): Date; + floor: (date: Date) => Date; + round: (date: Date) => Date; + ceil: (date: Date) => Date; + range: Range; + offset: (date: Date, step: number) => Date; + utc: Interval; + } + + export interface TimeFormat { + (date: Date): string; + parse: (string: string) => Date; + } } - export interface LayoutLink { - source: LayoutNode; - target: LayoutNode; - } + // Layout + export module Layout { + export interface Layout { + /** + * Creates a new Stack layout + */ + stack(): StackLayout; + /** + * Creates a new pie layout + */ + pie(): PieLayout; + /** + * Creates a new force layout + */ + force(): ForceLayout; + /** + * Creates a new tree layout + */ + tree(): TreeLayout; + bundle(): BundleLayout; + chord(): ChordLayout; + cluster(): ClusterLayout; + hierarchy(): HierarchyLayout; + histogram(): HistogramLayout; + pack(): PackLayout; + partition(): PartitionLayout; + treeMap(): TreeMapLayout; + } + export interface StackLayout { + (layers: any[], index?: number): any[]; + values(accessor?: (d: any) => any): StackLayout; + offset(offset: string): StackLayout; + } - export interface ForceLayout { - (): ForceLayout; - size: { - (): number; - (mysize: number[]): ForceLayout; - (accessor: (d: any, index: number) => {}): ForceLayout; + export interface TreeLayout { + /** + * Gets or sets the sort order of sibling nodes for the layout using the specified comparator function + */ + sort: { + /** + * Gets the sort order function of sibling nodes for the layout + */ + (): (d1: any, d2: any) => number; + /** + * Sets the sort order of sibling nodes for the layout using the specified comparator function + */ + (comparator: (d1: any, d2: any) => number): TreeLayout; + }; + /** + * Gets or sets the specified children accessor function + */ + children: { + /** + * Gets the children accessor function + */ + (): (d: any) => any; + /** + * Sets the specified children accessor function + */ + (children: (d: any) => any): TreeLayout; + }; + /** + * Runs the tree layout + */ + nodes(root: GraphNode): TreeLayout; + /** + * Given the specified array of nodes, such as those returned by nodes, returns an array of objects representing the links from parent to child for each node + */ + links(nodes: Array): Array; + /** + * If separation is specified, uses the specified function to compute separation between neighboring nodes. If separation is not specified, returns the current separation function + */ + seperation: { + /** + * Gets the current separation function + */ + (): (a: GraphNode, b: GraphNode) => number; + /** + * Sets the specified function to compute separation between neighboring nodes + */ + (seperation: (a: GraphNode, b: GraphNode) => number): TreeLayout; + }; + /** + * Gets or sets the available layout size + */ + size: { + /** + * Gets the available layout size + */ + (): Array; + /** + * Sets the available layout size + */ + (size: Array): TreeLayout; + }; + } - }; + export interface PieLayout { + (values: any[], index?: number): ArcDescriptor[]; + value: { + (): (d: any, index: number) => number; + (accessor: (d: any, index: number) => number): PieLayout; + }; + sort: { + (): (d1: any, d2: any) => number; + (comparator: (d1: any, d2: any) => number): PieLayout; + }; + startAngle: { + (): number; + (angle: number): D3.Svg.Arc; + (angle: () => number): D3.Svg.Arc; + }; + endAngle: { + (): number; + (angle: number): D3.Svg.Arc; + (angle: () => number): D3.Svg.Arc; + }; + } - linkDistance: { - (): number; - (number): ForceLayout; - (accessor: (d: any, index: number) => number): ForceLayout; - }; + export interface ArcDescriptor { + value: any; + data: any; + startAngle: number; + endAngle: number; + index: number; + } - linkStrength: + export interface GraphNode { + id: number; + index: number; + name: string; + px: number; + py: number; + size: number; + weight: number; + x: number; + y: number; + subindex: number; + startAngle: number; + endAngle: number; + value: number; + fixed: bool; + children: GraphNode[]; + _children: GraphNode[]; + parent: GraphNode; + depth: number; + } + + export interface GraphLink { + source: GraphNode; + target: GraphNode; + } + + export interface ForceLayout { + (): ForceLayout; + size: { + (): number; + (mysize: number[]): ForceLayout; + (accessor: (d: any, index: number) => {}): ForceLayout; + + }; + linkDistance: { + (): number; + (number): ForceLayout; + (accessor: (d: any, index: number) => number): ForceLayout; + }; + linkStrength: { (): number; (number): ForceLayout; (accessor: (d: any, index: number) => number): ForceLayout; }; - - friction: - { - (): number; - (number): ForceLayout; - (accessor: (d: any, index: number) => number): ForceLayout; - }; - - - alpha: { - (): number; - (number): ForceLayout; - (accessor: (d: any, index: number) => number): ForceLayout; - }; - charge: { - (): number; - (number): ForceLayout; - (accessor: (d: any, index: number) => number): ForceLayout; - }; - - theta: { - (): number; - (number): ForceLayout; - (accessor: (d: any, index: number) => number): ForceLayout; - }; - - gravity: { - (): number; - (number): ForceLayout; - (accessor: (d: any, index: number) => number): ForceLayout; - }; - - links: { - (): LayoutLink[]; - (arLinks: LayoutLink[]): ForceLayout; - - }; - nodes: - { - (): LayoutNode[]; - (arNodes: LayoutNode[]): ForceLayout; - - }; - start(): ForceLayout; - resume(): ForceLayout; - stop(): ForceLayout; - tick(): ForceLayout; - on(type: string, listener: () => void ): ForceLayout; - drag(): ForceLayout; - } - - // tree layout - - - interface Comparator - { - (a: LayoutNode, b: LayoutNode): () => any; - - } - - interface ObjectWithChildrenArray - { - children: ObjectWithChildrenArray[]; - } - - interface ChildrenAccessorFunction - { - (d: ObjectWithChildrenArray): ()=> any; - } - - interface CalculateSeparation - { - (a: any, b: any): () => number; - - } - - - export interface TreeLayout - { - (): TreeLayout; - size: { - (): number; - (mysize: number[]): TreeLayout; - (accessor: (d: any, index: number) => {}): TreeLayout; - - }; - nodes: (LayoutNode) => LayoutNode[]; - links: (nodes: LayoutNode[]) => LayoutLink[]; - - - sort: + friction: { - (): () => Comparator; - (Comparator): (comp) => Comparator; + (): number; + (number): ForceLayout; + (accessor: (d: any, index: number) => number): ForceLayout; + }; + alpha: { + (): number; + (number): ForceLayout; + (accessor: (d: any, index: number) => number): ForceLayout; + }; + charge: { + (): number; + (number): ForceLayout; + (accessor: (d: any, index: number) => number): ForceLayout; }; - - children: - { - (): () => ChildrenAccessorFunction; - (ObjectWithChildrenArray): () => ObjectWithChildrenArray; + theta: { + (): number; + (number): ForceLayout; + (accessor: (d: any, index: number) => number): ForceLayout; }; - separation: - { - (): CalculateSeparation; - (CalculateSeparation): () => number; - }; + gravity: { + (): number; + (number): ForceLayout; + (accessor: (d: any, index: number) => number): ForceLayout; + }; + + links: { + (): GraphLink[]; + (arLinks: GraphLink[]): ForceLayout; + + }; + nodes: + { + (): GraphNode[]; + (arNodes: GraphNode[]): ForceLayout; + + }; + start(): ForceLayout; + resume(): ForceLayout; + stop(): ForceLayout; + tick(): ForceLayout; + on(type: string, listener: () => void ): ForceLayout; + drag(): ForceLayout; + } + + export interface BundleLayout{ + (links: Array): Array; + } + + export interface ChordLayout { + matrix: { + (): Array>; + (matrix: Array>): ChordLayout; + } + padding: { + (): number; + (padding: number): ChordLayout; + } + sortGroups: { + (): Array; + (comparator: (a: number, b: number) => number): ChordLayout; + } + sortSubgroups: { + (): Array; + (comparator: (a: number, b: number) => number): ChordLayout; + } + sortChords: { + (): Array; + (comparator: (a: number, b: number) => number): ChordLayout; + } + chords(): Array; + groups(): Array; + } + + export interface ClusterLayout{ + sort: { + (): (a: GraphNode, b: GraphNode) => number; + (comparator: (a: GraphNode, b: GraphNode) => number): ClusterLayout; + } + children: { + (): (d: any, i?: number) => Array; + (children: (d: any, i?: number) => Array): ClusterLayout; + } + nodes(root: GraphNode): Array; + links(nodes: Array): Array; + seperation: { + (): (a: GraphNode, b: GraphNode) => number; + (seperation: (a: GraphNode, b: GraphNode) => number): ClusterLayout; + } + size: { + (): Array; + (size: Array): ClusterLayout; + } + value: { + (): (node: GraphNode) => number; + (value: (node: GraphNode) => number): ClusterLayout; + } + } + + export interface HierarchyLayout { + sort: { + (): (a: GraphNode, b: GraphNode) => number; + (comparator: (a: GraphNode, b: GraphNode) => number): HierarchyLayout; + } + children: { + (): (d: any, i?: number) => Array; + (children: (d: any, i?: number) => Array): HierarchyLayout; + } + nodes(root: GraphNode): Array; + links(nodes: Array): Array; + value: { + (): (node: GraphNode) => number; + (value: (node: GraphNode) => number): HierarchyLayout; + } + reValue(root: GraphNode): HierarchyLayout; + } + + export interface Bin extends Array { + x: number; + dx: number; + y: number; + } + + export interface HistogramLayout { + (values: Array, index?: number): Array; + value: { + (): (value: any) => any; + (accessor: (value: any) => any): HistogramLayout + } + range: { + (): (value: any, index: number) => Array; + (range: (value: any, index: number) => Array): HistogramLayout; + (range: Array): HistogramLayout; + } + bins: { + (): (range: Array, index: number) => Array; + (bins: (range: Array, index: number) => Array): HistogramLayout; + (bins: number): HistogramLayout; + (bins: Array): HistogramLayout; + } + frequency: { + (): boolean; + (frequency: boolean): HistogramLayout; + } + } + + export interface PackLayout { + sort: { + (): (a: GraphNode, b: GraphNode) => number; + (comparator: (a: GraphNode, b: GraphNode) => number): PackLayout; + } + children: { + (): (d: any, i?: number) => Array; + (children: (d: any, i?: number) => Array): PackLayout; + } + nodes(root: GraphNode): Array; + links(nodes: Array): Array; + value: { + (): (node: GraphNode) => number; + (value: (node: GraphNode) => number): PackLayout; + } + size: { + (): Array; + (size: Array): PackLayout; + } + padding: { + (): number; + (padding: number): PackLayout; + } + } + + export interface PartitionLayout { + sort: { + (): (a: GraphNode, b: GraphNode) => number; + (comparator: (a: GraphNode, b: GraphNode) => number): PackLayout; + } + children: { + (): (d: any, i?: number) => Array; + (children: (d: any, i?: number) => Array): PackLayout; + } + nodes(root: GraphNode): Array; + links(nodes: Array): Array; + value: { + (): (node: GraphNode) => number; + (value: (node: GraphNode) => number): PackLayout; + } + size: { + (): Array; + (size: Array): PackLayout; + } + } + + export interface TreeMapLayout { + sort: { + (): (a: GraphNode, b: GraphNode) => number; + (comparator: (a: GraphNode, b: GraphNode) => number): TreeMapLayout; + } + children: { + (): (d: any, i?: number) => Array; + (children: (d: any, i?: number) => Array): TreeMapLayout; + } + nodes(root: GraphNode): Array; + links(nodes: Array): Array; + value: { + (): (node: GraphNode) => number; + (value: (node: GraphNode) => number): TreeMapLayout; + } + size: { + (): Array; + (size: Array): TreeMapLayout; + } + padding: { + (): number; + (padding: number): TreeMapLayout; + } + round: { + (): boolean; + (round: boolean): TreeMapLayout; + } + sticky: { + (): boolean; + (sticky: boolean): TreeMapLayout; + } + mode: { + (): string; + (mode: string): TreeMapLayout; + } + } } + // Colour + export module Color { + export interface Color { + /** + * increase lightness by some exponential factor (gamma) + */ + brighter(k: number): Color; + /** + * decrease lightness by some exponential factor (gamma) + */ + darker(k: number): Color; + /** + * convert the color to a string. + */ + toString(): Color; + } + + export interface RGBColor extends Color{ + /** + * convert from RGB to HSL. + */ + hsl(): HSLColor; + } + + export interface HSLColor extends Color{ + /** + * convert from HSL to RGB. + */ + rgb(): RGBColor; + } + + export interface LABColor extends Color{ + /** + * convert from LAB to RGB. + */ + rgb(): RGBColor; + } + + export interface HCLColor extends Color{ + /** + * convert from HCL to RGB. + */ + rgb(): RGBColor; + } + } + + // SVG + export module Svg { + export interface Svg { + /** + * Create a new symbol generator + */ + symbol(): Symbol; + /** + * Create a new axis generator + */ + axis(): Axis; + /** + * Create a new arc generator + */ + arc(): Arc; + /** + * Create a new line generator + */ + line: { + (): Line; + radial(): LineRadial; + } + /** + * Create a new area generator + */ + area: { + (): Area; + radial(): AreaRadial; + } + /** + * Create a new brush generator + */ + brush(): Brush; + /** + * Create a new chord generator + */ + chord(): Chord; + /** + * Create a new diagonal generator + */ + diagonal: { + (): Diagonal; + radial(): Diagonal; + } + /** + * The array of supported symbol types. + */ + symbolTypes: Array; + } + + export interface Symbol { + type: (string) => Symbol; + size: (number) => Symbol; + } + + export interface Brush { + /** + * Draws or redraws this brush into the specified selection of elements + */ + (selection: Selection): void; + /** + * Gets or sets the x-scale associated with the brush + */ + x: { + /** + * Gets the x-scale associated with the brush + */ + (): D3.Scale.Scale; + /** + * Sets the x-scale associated with the brush + * + * @param accessor The new Scale + */ + (scale: D3.Scale.Scale): Brush; + }; + /** + * Gets or sets the x-scale associated with the brush + */ + y: { + /** + * Gets the x-scale associated with the brush + */ + (): D3.Scale.Scale; + /** + * Sets the x-scale associated with the brush + * + * @param accessor The new Scale + */ + (scale: D3.Scale.Scale): Brush; + }; + /** + * Gets or sets the current brush extent + */ + extent: { + /** + * Gets the current brush extent + */ + (): Array>; + /** + * Sets the current brush extent + */ + (values: Array>): Brush; + }; + /** + * Clears the extent, making the brush extent empty. + */ + clear(): Brush; + /** + * Returns true if and only if the brush extent is empty + */ + empty(): boolean; + /** + * Gets or sets the listener for the specified event type + */ + on: { + /** + * Gets the listener for the specified event type + */ + (type: string): (data: any, index: number) => any; + /** + * Sets the listener for the specified event type + */ + (type: string, listener: (data: any, index: number) => any, capture?: boolean): Brush; + }; + } + + export interface Axis { + (selection: Selection): void; + scale: { + (): any; + (scale: any): Axis; + }; + + orient: { + (): string; + (orientation: string): Axis; + }; + + ticks: { + (): any[]; + (...arguments: any[]): Axis; + }; + + tickSubdivide(count: number): Axis; + tickSize(major?: number, minor?: number, end?: number): Axis; + tickFormat(formatter: (value: any) => string): Axis; + } + + export interface Arc { + (options?: ArcOptions): string; + innerRadius: { + (): number; + (radius: number): Arc; + (radius: () => number): Arc; + }; + outerRadius: { + (): number; + (radius: number): Arc; + (radius: () => number): Arc; + }; + startAngle: { + (): number; + (angle: number): Arc; + (angle: () => number): Arc; + }; + endAngle: { + (): number; + (angle: number): Arc; + (angle: () => number): Arc; + }; + centroid(options?: ArcOptions): number[]; + } + + export interface ArcOptions { + innerRadius?: number; + outerRadius?: number; + startAngle?: number; + endAngle?: number; + } + + export interface Line { + /** + * Returns the path data string + * + * @param data Array of data elements + * @param index Optional index + */ + (data: any[], index?: number): string; + /** + * Get or set the x-coordinate accessor. + */ + x: { + /** + * Get the x-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the x-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Line; + }; + /** + * Get or set the y-coordinate accessor. + */ + y: { + /** + * Get the y-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the y-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Line; + }; + /** + * Get or set the interpolation mode. + */ + interpolate: { + /** + * Get the interpolation accessor. + */ + (): string; + /** + * Set the interpolation accessor. + * + * @param interpolate The interpolation mode + */ + (interpolate: string): Line; + }; + /** + * Get or set the cardinal spline tension. + */ + tension: { + /** + * Get the cardinal spline accessor. + */ + (): number; + /** + * Set the cardinal spline accessor. + * + * @param tension The Cardinal spline interpolation tension + */ + (tension: number): Line; + }; + /** + * Control whether the line is defined at a given point. + */ + defined: { + /** + * Get the accessor function that controls where the line is defined. + */ + (): (data: any) => any; + /** + * Set the accessor function that controls where the area is defined. + * + * @param defined The new accessor function + */ + (defined: (data: any) => any): Line; + }; + } + + export interface LineRadial { + /** + * Returns the path data string + * + * @param data Array of data elements + * @param index Optional index + */ + (data: any[], index?: number): string; + /** + * Get or set the x-coordinate accessor. + */ + x: { + /** + * Get the x-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the x-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): LineRadial; + }; + /** + * Get or set the y-coordinate accessor. + */ + y: { + /** + * Get the y-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the y-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): LineRadial; + }; + /** + * Get or set the interpolation mode. + */ + interpolate: { + /** + * Get the interpolation accessor. + */ + (): string; + /** + * Set the interpolation accessor. + * + * @param interpolate The interpolation mode + */ + (interpolate: string): LineRadial; + }; + /** + * Get or set the cardinal spline tension. + */ + tension: { + /** + * Get the cardinal spline accessor. + */ + (): number; + /** + * Set the cardinal spline accessor. + * + * @param tension The Cardinal spline interpolation tension + */ + (tension: number): LineRadial; + }; + /** + * Control whether the line is defined at a given point. + */ + defined: { + /** + * Get the accessor function that controls where the line is defined. + */ + (): (data: any) => any; + /** + * Set the accessor function that controls where the area is defined. + * + * @param defined The new accessor function + */ + (defined: (data: any) => any): LineRadial; + }; + radius: { + (): (d: any, i: any) => number; + (radius: number): LineRadial; + (radius: (d: any, i: any) => number): LineRadial; + } + angle: { + (): (d: any, i: any) => number; + (angle: number): LineRadial; + (angle: (d: any, i: any) => number): LineRadial; + } + } + + export interface Area { + /** + * Generate a piecewise linear area, as in an area chart. + */ + (data: any[], index?: number): string; + /** + * Get or set the x-coordinate accessor. + */ + x: { + /** + * Get the x-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the x-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the x0-coordinate (baseline) accessor. + */ + x0: { + /** + * Get the x0-coordinate (baseline) accessor. + */ + (): (data: any) => any; + /** + * Set the x0-coordinate (baseline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the x1-coordinate (topline) accessor. + */ + x1: { + /** + * Get the x1-coordinate (topline) accessor. + */ + (): (data: any) => any; + /** + * Set the x1-coordinate (topline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the y-coordinate accessor. + */ + y: { + /** + * Get the y-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the y-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the y0-coordinate (baseline) accessor. + */ + y0: { + /** + * Get the y0-coordinate (baseline) accessor. + */ + (): (data: any) => any; + /** + * Set the y0-coordinate (baseline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the y1-coordinate (topline) accessor. + */ + y1: { + /** + * Get the y1-coordinate (topline) accessor. + */ + (): (data: any) => any; + /** + * Set the y1-coordinate (topline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the interpolation mode. + */ + interpolate: { + /** + * Get the interpolation accessor. + */ + (): string; + /** + * Set the interpolation accessor. + * + * @param interpolate The interpolation mode + */ + (interpolate: string): Area; + }; + /** + * Get or set the cardinal spline tension. + */ + tension: { + /** + * Get the cardinal spline accessor. + */ + (): number; + /** + * Set the cardinal spline accessor. + * + * @param tension The Cardinal spline interpolation tension + */ + (tension: number): Area; + }; + /** + * Control whether the area is defined at a given point. + */ + defined: { + /** + * Get the accessor function that controls where the area is defined. + */ + (): (data: any) => any; + /** + * Set the accessor function that controls where the area is defined. + * + * @param defined The new accessor function + */ + (defined: (data: any) => any): Area; + }; + } + + export interface AreaRadial { + /** + * Generate a piecewise linear area, as in an area chart. + */ + (data: any[], index?: number): string; + /** + * Get or set the x-coordinate accessor. + */ + x: { + /** + * Get the x-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the x-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): AreaRadial; + }; + /** + * Get or set the x0-coordinate (baseline) accessor. + */ + x0: { + /** + * Get the x0-coordinate (baseline) accessor. + */ + (): (data: any) => any; + /** + * Set the x0-coordinate (baseline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): AreaRadial; + }; + /** + * Get or set the x1-coordinate (topline) accessor. + */ + x1: { + /** + * Get the x1-coordinate (topline) accessor. + */ + (): (data: any) => any; + /** + * Set the x1-coordinate (topline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): AreaRadial; + }; + /** + * Get or set the y-coordinate accessor. + */ + y: { + /** + * Get the y-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the y-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): AreaRadial; + }; + /** + * Get or set the y0-coordinate (baseline) accessor. + */ + y0: { + /** + * Get the y0-coordinate (baseline) accessor. + */ + (): (data: any) => any; + /** + * Set the y0-coordinate (baseline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): AreaRadial; + }; + /** + * Get or set the y1-coordinate (topline) accessor. + */ + y1: { + /** + * Get the y1-coordinate (topline) accessor. + */ + (): (data: any) => any; + /** + * Set the y1-coordinate (topline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): AreaRadial; + }; + /** + * Get or set the interpolation mode. + */ + interpolate: { + /** + * Get the interpolation accessor. + */ + (): string; + /** + * Set the interpolation accessor. + * + * @param interpolate The interpolation mode + */ + (interpolate: string): AreaRadial; + }; + /** + * Get or set the cardinal spline tension. + */ + tension: { + /** + * Get the cardinal spline accessor. + */ + (): number; + /** + * Set the cardinal spline accessor. + * + * @param tension The Cardinal spline interpolation tension + */ + (tension: number): AreaRadial; + }; + /** + * Control whether the area is defined at a given point. + */ + defined: { + /** + * Get the accessor function that controls where the area is defined. + */ + (): (data: any) => any; + /** + * Set the accessor function that controls where the area is defined. + * + * @param defined The new accessor function + */ + (defined: (data: any) => any): AreaRadial; + }; + radius: { + (): number; + (radius: number): AreaRadial; + (radius: () => number): AreaRadial; + }; + innerRadius: { + (): number; + (radius: number): AreaRadial; + (radius: () => number): AreaRadial; + }; + outerRadius: { + (): number; + (radius: number): AreaRadial; + (radius: () => number): AreaRadial; + }; + angle: { + (): number; + (angle: number): AreaRadial; + (angle: () => number): AreaRadial; + }; + startAngle: { + (): number; + (angle: number): AreaRadial; + (angle: () => number): AreaRadial; + }; + endAngle: { + (): number; + (angle: number): AreaRadial; + (angle: () => number): AreaRadial; + }; + } + + export interface Chord { + (datum: any, index?: number): string; + radius: { + (): number; + (radius: number): Chord; + (radius: () => number): Chord; + }; + startAngle: { + (): number; + (angle: number): Chord; + (angle: () => number): Chord; + }; + endAngle: { + (): number; + (angle: number): Chord; + (angle: () => number): Chord; + }; + source: { + (): any; + (angle: any): Chord; + (angle: (d: any, i?: number) => any): Chord; + }; + target: { + (): any; + (angle: any): Chord; + (angle: (d: any, i?: number) => any): Chord; + }; + } + + export interface Diagonal { + (datum: any, index?: number): string; + projection: { + (): Array; + (radius: (d: any, i?: number) => Array): Diagonal; + }; + source: { + (): any; + (angle: any): Diagonal; + (angle: (d: any, i?: number) => any): Diagonal; + }; + target: { + (): any; + (angle: any): Diagonal; + (angle: (d: any, i?: number) => any): Diagonal; + }; + } + } + + // Scales + export module Scale { + export interface ScaleBase { + /** + * Construct a linear quantitative scale. + */ + linear(): LinearScale; + /* + * Construct an ordinal scale. + */ + ordinal(): OrdinalScale; + /** + * Construct a linear quantitative scale with a discrete output range. + */ + quantize(): QuantizeScale; + /* + * Construct an ordinal scale with ten categorical colors. + */ + category10(): OrdinalScale; + /* + * Construct an ordinal scale with twenty categorical colors + */ + category20(): OrdinalScale; + /* + * Construct an ordinal scale with twenty categorical colors + */ + category20b(): OrdinalScale; + /* + * Construct an ordinal scale with twenty categorical colors + */ + category20c(): OrdinalScale; + /* + * Construct a linear identity scale. + */ + identity(): IdentityScale; + /* + * Construct a quantitative scale with an logarithmic transform. + */ + log(): LogScale; + /* + * Construct a quantitative scale with an exponential transform. + */ + pow(): PowScale; + /* + * Construct a quantitative scale mapping to quantiles. + */ + quantile(): QuantileScale; + /* + * Construct a quantitative scale with a square root transform. + */ + sqrt(): SqrtScale; + /* + * Construct a threshold scale with a discrete output range. + */ + theshold(): ThresholdScale; + } + + export interface Scale { + (value: any): any; + domain: { + (values: any[]): Scale; + (): any[]; + }; + range: { + (values: any[]): Scale; + (): any[]; + }; + copy(): Scale; + } + + export interface QuantitiveScale extends Scale { + /** + * Get the range value corresponding to a given domain value. + * + * @param value Domain Value + */ + (value: number): number; + /** + * Get the domain value corresponding to a given range value. + * + * @param value Range Value + */ + invert(value: number): number; + /** + * Get or set the scale's input domain. + */ + domain: { + /** + * Set the scale's input domain. + * + * @param value The input domain + */ + (values: any[]): QuantitiveScale; + /** + * Get the scale's input domain. + */ + (): any[]; + }; + /** + * get or set the scale's output range. + */ + range: { + /** + * Set the scale's output range. + * + * @param value The output range. + */ + (values: any[]): QuantitiveScale; + /** + * Get the scale's output range. + */ + (): any[]; + }; + /** + * Set the scale's output range, and enable rounding. + * + * @param value The output range. + */ + rangeRound: (values: any[]) => QuantitiveScale; + /** + * get or set the scale's output interpolator. + */ + interpolate: { + (): D3.Transition.Interpolate; + (factory: D3.Transition.Interpolate): QuantitiveScale; + }; + /** + * enable or disable clamping of the output range. + * + * @param clamp Enable or disable + */ + clamp(clamp: boolean): QuantitiveScale; + /** + * extend the scale domain to nice round numbers. + */ + nice(): QuantitiveScale; + /** + * get representative values from the input domain. + * + * @param count Aproximate representative values to return. + */ + ticks(count: number): any[]; + /** + * get a formatter for displaying tick values + * + * @param count Aproximate representative values to return + */ + tickFormat(count: number): (n: number) => string; + /** + * create a new scale from an existing scale.. + */ + copy(): QuantitiveScale; + } + + export interface LinearScale extends QuantitiveScale { + /** + * Get the range value corresponding to a given domain value. + * + * @param value Domain Value + */ + (value: number): number; + } + + export interface IdentityScale extends QuantitiveScale { + /** + * Get the range value corresponding to a given domain value. + * + * @param value Domain Value + */ + (value: number): number; + } + + export interface SqrtScale extends QuantitiveScale { + /** + * Get the range value corresponding to a given domain value. + * + * @param value Domain Value + */ + (value: number): number; + } + + export interface PowScale extends QuantitiveScale { + /** + * Get the range value corresponding to a given domain value. + * + * @param value Domain Value + */ + (value: number): number; + } + + export interface LogScale extends QuantitiveScale { + /** + * Get the range value corresponding to a given domain value. + * + * @param value Domain Value + */ + (value: number): number; + } + + export interface OrdinalScale extends Scale { + /** + * Get the range value corresponding to a given domain value. + * + * @param value Domain Value + */ + (value: any): any; + /** + * Get or set the scale's input domain. + */ + domain: { + /** + * Set the scale's input domain. + * + * @param value The input domain + */ + (values: any[]): OrdinalScale; + /** + * Get the scale's input domain. + */ + (): any[]; + }; + /** + * get or set the scale's output range. + */ + range: { + /** + * Set the scale's output range. + * + * @param value The output range. + */ + (values: any[]): OrdinalScale; + /** + * Get the scale's output range. + */ + (): any[]; + }; + rangePoints(interval: any[], padding?: number): OrdinalScale; + rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; + rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; + rangeBand(): number; + rangeExtent(): any[]; + /** + * create a new scale from an existing scale.. + */ + copy(): OrdinalScale; + } + + export interface QuantizeScale extends Scale { + (value: any): any; + domain: { + (values: number[]): QuantizeScale; + (): any[]; + }; + range: { + (values: any[]): QuantizeScale; + (): any[]; + }; + copy(): QuantizeScale; + } + + export interface ThresholdScale extends Scale { + (value: any): any; + domain: { + (values: number[]): ThresholdScale; + (): any[]; + }; + range: { + (values: any[]): ThresholdScale; + (): any[]; + }; + copy(): ThresholdScale; + } + + export interface QuantileScale extends Scale { + (value: any): any; + domain: { + (values: number[]): QuantileScale; + (): any[]; + }; + range: { + (values: any[]): QuantileScale; + (): any[]; + }; + quantiles(): any[]; + copy(): QuantileScale; + } + + export interface TimeScale extends Scale { + (value: Date): number; + invert(value: number): Date; + domain: { + (values: any[]): TimeScale; + (): any[]; + }; + range: { + (values: any[]): TimeScale; + (): any[]; + }; + rangeRound: (values: any[]) => TimeScale; + interpolate: { + (): D3.Transition.Interpolate; + (factory: D3.Transition.InterpolateFactory): TimeScale; + }; + clamp(clamp: boolean): TimeScale; + ticks: { + (count: number): any[]; + (range: Range, count: number): any[]; + }; + tickFormat(count: number): (n: number) => string; + copy(): TimeScale; + } + } + + // Behaviour + export module Behaviour { + export interface Behavior{ + /** + * Constructs a new drag behaviour + */ + drag(): Drag; + /** + * Constructs a new zoom behaviour + */ + zoom(): Zoom; + } + + export interface Zoom { + /** + * Execute zoom method + */ + (): any; + + /** + * Registers a listener to receive events + * + * @param type Enent name to attach the listener to + * @param listener Function to attach to event + */ + on: (type: string, listener: (data: any, index?: number) => any) => Zoom; + + /** + * Gets or set the current zoom scale + */ + scale: { + /** + * Get the current current zoom scale + */ + (): number; + /** + * Set the current current zoom scale + * + * @param origin Zoom scale + */ + (scale: number): Zoom; + }; + + /** + * Gets or set the current zoom translation vector + */ + translate: { + /** + * Get the current zoom translation vector + */ + (): number[]; + /** + * Set the current zoom translation vector + * + * @param translate Tranlation vector + */ + (translate: number[]): Zoom; + }; + + /** + * Gets or set the allowed scale range + */ + scaleExtent: { + /** + * Get the current allowed zoom range + */ + (): number[]; + /** + * Set the allowable zoom range + * + * @param extent Allowed zoom range + */ + (extent: number[]): Zoom; + }; + + /** + * Gets or set the X-Scale that should be adjusted when zooming + */ + x: { + /** + * Get the X-Scale + */ + (): D3.Scale.Scale; + /** + * Set the X-Scale to be adjusted + * + * @param x The X Scale + */ + (x: D3.Scale.Scale): Zoom; + + }; + + /** + * Gets or set the Y-Scale that should be adjusted when zooming + */ + y: { + /** + * Get the Y-Scale + */ + (): D3.Scale.Scale; + /** + * Set the Y-Scale to be adjusted + * + * @param y The Y Scale + */ + (y: D3.Scale.Scale): Zoom; + }; + } + + export interface Drag { + /** + * Execute drag method + */ + (): any; + + /** + * Registers a listener to receive events + * + * @param type Enent name to attach the listener to + * @param listener Function to attach to event + */ + on: (type: string, listener: (data: any, index?: number) => any) => Drag; + + /** + * Gets or set the current origin accessor function + */ + origin: { + /** + * Get the current origin accessor function + */ + (): any; + /** + * Set the origin accessor function + * + * @param origin Accessor function + */ + (origin?: any): Drag; + }; + } + } + + // Geography + export module Geo { + export interface Geo { + /** + * create a new geographic path generator + */ + path(): Path; + /** + * create a circle generator. + */ + circle(): Circle; + /** + * compute the spherical area of a given feature. + */ + area(feature: any): number; + /** + * compute the latitude-longitude bounding box for a given feature. + */ + bounds(feature: any): Array>; + /** + * compute the spherical centroid of a given feature. + */ + centroid(feature: any): Array; + /** + * compute the great-arc distance between two points. + */ + distance(a: Array, b: Array): number; + /** + * interpolate between two points along a great arc. + */ + interpolate(a: Array, b: Array): (t: number) => Array; + /** + * compute the length of a line string or the circumference of a polygon. + */ + length(feature: any): number; + /** + * create a standard projection from a raw projection. + */ + projection(raw: (lambda: any, phi: any) => any): Projection; + /** + * create a standard projection from a mutable raw projection. + */ + projectionMutator(rawFactory: (lambda: number, phi: number) => Array): Projection; + /** + * the Albers equal-area conic projection. + */ + albers(): Projection; + /** + * a composite Albers projection for the United States. + */ + albersUsa(): Projection; + /** + * the azimuthal equal-area projection. + */ + azimuthalEqualArea: { + (): Projection; + raw(): Projection; + } + /** + * the azimuthal equidistant projection. + */ + azimuthalEquidistant: { + (): Projection; + raw(): Projection; + } + /** + * the conic conformal projection. + */ + conicConformal: { + (): Projection; + raw(): Projection; + } + /** + * the conic equidistant projection. + */ + conicEquidistant: { + (): Projection; + raw(): Projection; + } + /** + * the conic equal-area (a.k.a. Albers) projection. + */ + conicEqualArea: { + (): Projection; + raw(): Projection; + } + /** + * the equirectangular (plate carreé) projection. + */ + equirectangular: { + (): Projection; + raw(): Projection; + } + /** + * the gnomonic projection. + */ + gnomonic: { + (): Projection; + raw(): Projection; + } + /** + * the spherical Mercator projection. + */ + mercator: { + (): Projection; + raw(): Projection; + } + /** + * the azimuthal orthographic projection. + */ + othographic: { + (): Projection; + raw(): Projection; + } + /** + * the azimuthal stereographic projection. + */ + stereographic: { + (): Projection; + raw(): Projection; + } + /** + * the transverse Mercator projection. + */ + transverseMercator: { + (): Projection; + raw(): Projection; + } + /** + * convert a GeoJSON object to a geometry stream. + */ + stream(object: GeoJSON, listener: any): Stream; + /** + * + */ + graticule(): Graticule; + /** + * + */ + greatArc: GreatArc; + /** + * + */ + rotation(rotation: Array): Rotation; + } + + export interface Path { + /** + * Returns the path data string for the given feature + */ + (feature: any, index?: any): string; + /** + * get or set the geographic projection. + */ + projection: { + /** + * get the geographic projection. + */ + (): Projection; + /** + * set the geographic projection. + */ + (projection: Projection): Path; + } + /** + * get or set the render context. + */ + context: { + /** + * return an SVG path string invoked on the given feature. + */ + (): string; + /** + * sets the render context and returns the path generator + */ + (context: Context): Path; + } + /** + * Computes the projected area + */ + area(feature: any); + /** + * Computes the projected centroid + */ + centroid(feature: any); + /** + * Computes the projected bounding box + */ + bounds(feature: any); + /** + * get or set the radius to display point features. + */ + pointRadius: { + /** + * returns the current radius + */ + (): number; + /** + * sets the radius used to display Point and MultiPoint features to the specified number + */ + (radius: number): Path; + /** + * sets the radius used to display Point and MultiPoint features to the specified number + */ + (radius: (feature: any, index: number) => number): Path; + } + } + + export interface Context { + beginPath(): any; + moveTo(x: number, y: number): any; + lineTo(x: number, y: number): any; + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number): any; + closePath(): any; + } + + export interface Circle { + (...args: Array): GeoJSON; + origin: { + (): Array; + (origin: Array): Circle; + (origin: (...args: Array) => Array): Circle; + } + angle: { + (): number; + (angle: number): Circle; + } + precision: { + (): number; + (precision: number): Circle; + } + } + + export interface Graticule{ + (): GeoJSON; + lines(): GeoJSON; + outline(): GeoJSON; + extent: { + (): Array>; + (extent: Array>): Graticule; + } + minorExtent: { + (): Array>; + (extent: Array>): Graticule; + } + majorExtent: { + (): Array>; + (extent: Array>): Graticule; + } + step: { + (): Array>; + (extent: Array>): Graticule; + } + minorStep: { + (): Array>; + (extent: Array>): Graticule; + } + majorStep: { + (): Array>; + (extent: Array>): Graticule; + } + precision: { + (): number; + (precision: number): Graticule; + } + } + + export interface GreatArc { + (): GeoJSON; + distance(): number; + source: { + (): any; + (source: any): GreatArc; + } + target: { + (): any; + (target: any): GreatArc; + } + precision: { + (): number; + (precision: number): GreatArc; + } + } + + export interface GeoJSON { + coordinates: Array>; + type: string; + } + + export interface Projection { + (coordinates: Array): Array; + invert(point: Array): Array; + rotate: { + (): Array; + (rotation: Array): Projection; + }; + center: { + (): Array; + (location: Array): Projection; + }; + translate: { + (): Array; + (point: Array): Projection; + }; + scale: { + (): number; + (scale: number): Projection; + }; + clipAngle: { + (): number; + (angle: number): Projection; + }; + clipExtent: { + (): Array>; + (extent: Array>): Projection; + }; + precision: { + (): number; + (precision: number): Projection; + }; + stream(listener?: any): Stream; + } + + export interface Stream { + point(x: number, y: number, z?: number): void; + lineStart(): void; + lineEnd(): void; + polygonStart(): void; + polygonEnd(): void; + sphere(): void; + } + + export interface Rotation extends Array { + (location: Array): Rotation; + invert(location: Array): Rotation; + } + } + + // Geometry + export module Geom { + export interface Geom { + /** + * compute the Voronoi diagram for the specified points. + */ + voronoi: Voronoi + /** + * compute the Delaunay triangulation for the specified points. + */ + delaunay(vertices?: Array): Array; + /** + * constructs a quadtree for an array of points. + */ + quadtree: Quadtree; + /** + * constructs a polygon + */ + polygon: Polygon; + /** + * creates a new hull layout with the default settings. + */ + hull: Hull; + } + + export interface Vertice extends Array { + /** + * Returns the angle of the vertice + */ + angle?: number; + } + + export interface Polygon extends Array { + /** + * Returns the input array of vertices with additional methods attached + */ + (vertices: Array): Polygon; + /** + * Returns the signed area of this polygon + */ + area(): number; + /** + * Returns a two-element array representing the centroid of this polygon. + */ + centroid(): Array; + /** + * Clips the subject polygon against this polygon + */ + clip(subject: Polygon): Polygon; + } + + export interface Quadtree { + /** + * Constructs a new quadtree for the specified array of points. + */ + (): Quadtree; + /** + * Constructs a new quadtree for the specified array of points. + */ + (points: Array, x1: number, y1: number, x2: number, y2: number): Quadtree; + /** + * Constructs a new quadtree for the specified array of points. + */ + (points: Array, width: number, height: number): Quadtree; + /** + * Adds a new point to the quadtree. + */ + add(point: Point): Quadtree; + visit(callback: any): Quadtree; + x: { + (): (d: any) => any; + (accesor: (d: any) => any): Quadtree; + + } + y: { + (): (d: any) => any; + (accesor: (d: any) => any): Quadtree; + + } + size(size: Array): Quadtree; + } + + export interface Point { + x: number; + y: number; + } + + export interface Voronoi { + (vertices?: Array): Array; + x: { + (): (d: any) => any; + (accesor: (d: any) => any): any; + } + y: { + (): (d: any) => any; + (accesor: (d: any) => any): any; + } + } + + export interface Hull { + (vertices: Array): Hull; + x: { + (): (d: any) => any; + (accesor: (d: any) => any): any; + } + y: { + (): (d: any) => any; + (accesor: (d: any) => any): any; + } + } + } } declare var d3: D3.Base; diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index 33dd732f7..98cdcd536 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -18,11 +18,11 @@ declare module "durandal/system" { /** * Call this function to enable or disable Durandal's debug mode. Calling it with no parameters will return true if the framework is currently in debug mode, false otherwise. */ - export var debug: (debug?: bool) => bool; + export var debug: (debug?: boolean) => boolean; /** * Checks if the obj is an array */ - export var isArray: (obj: any) => bool; + export var isArray: (obj: any) => boolean; /** * Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode. */ @@ -91,7 +91,7 @@ declare module "durandal/composition" { /** * sets activate: true on every compose binding */ - export var activateDuringComposition: bool; + export var activateDuringComposition: boolean; /** * changes the convention for finding where transitions are located */ @@ -161,7 +161,7 @@ declare module "durandal/modalDialog" { /** * This is a helper function which will tell you if any modals are currently open. */ - export var isModalOpen: () => bool; + export var isModalOpen: () => boolean; /** * You may wish to customize modal displays or add additional contexts in order to display modals in different ways. To alter the default context, you would acquire it by calling getContext() and then alter it's pipeline. If you don't provide a value for name it returns the default context. */ @@ -192,7 +192,7 @@ declare module "durandal/viewEngine" { /** * Returns true if the potential string is a url for a view, according to the view engine. */ - export var isViewUrl: (url: string) => bool; + export var isViewUrl: (url: string) => boolean; /** * Converts a view url into a view id. */ @@ -267,15 +267,15 @@ interface IViewModelDefaults { /** * When the activator attempts to activate an item as described below, it will only activate the new item, by default, if it is a different instance than the current. Overwrite this function to change that behavior. */ - areSameItem(currentItem, newItem, activationData): bool; + areSameItem(currentItem, newItem, activationData): boolean; /** * default is true */ - closeOnDeactivate: bool; + closeOnDeactivate: boolean; /** * Interprets values returned from guard methods like canActivate and canDeactivate by transforming them into bools. The default implementation translates string values "Yes" and "Ok" as true...and all other string values as false. Non string values evaluate according to the truthy/falsey values of JavaScript. Replace this function with your own to expand or set up different values. This transformation is used by the activator internally and allows it to work smoothly in the common scenario where a deactivated item needs to show a message box to prompt the user before closing. Since the message box returns a promise that resolves to the button option the user selected, it can be automatically processed as part of the activator's guard check. */ - interpretResponse(value: any): bool; + interpretResponse(value: any): boolean; /** * called before activating a module */ @@ -284,7 +284,7 @@ interface IViewModelDefaults { * called after deactivating a module */ afterDeactivate(): any; -}; +} interface IDurandalViewModelActiveItem { /** @@ -298,7 +298,7 @@ interface IDurandalViewModelActiveItem { /** * This observable is set internally by the activator during the activation process. It can be used to determine if an activation is currently happening. */ - isActivating(val?: bool): bool; + isActivating(val?: boolean): boolean; /** * Pass a specific item as well as an indication of whether it should be closed, and this function will tell you the answer. */ @@ -339,7 +339,7 @@ interface IDurandalViewModelActiveItem { * Sets up a collection representing a pool of objects which the activator will activate. See below for details. Activators without an item bool always close their values on deactivate. Activators with an items pool only deactivate, but do not close them. */ forItems(items): IDurandalViewModelActiveItem; -}; +} /** * A router plugin, currently based on SammyJS. The router abstracts away the core configuration of Sammy and re-interprets it in terms of durandal's composition and activation mechanism. To use the router, you must require it, configure it and bind it in the UI. @@ -360,12 +360,12 @@ declare module "durandal/plugins/router" { /** used to set the document title */ caption: string; /** determines whether or not to include it in the router's visibleRoutes array for easy navigation UI binding */ - visible: bool; + visible: boolean; settings: Object; hash: string; /** only present on visible routes to track if they are active in the nav */ - isActive?: KnockoutComputed; - }; + isActive?: KnockoutComputed; + } /** * Parameters to the map function. e only required parameter is url the rest can be derived. The derivation * happens by stripping parameters from the url and casing where appropriate. You can always explicitly provide @@ -383,25 +383,25 @@ declare module "durandal/plugins/router" { /** used to set the document title */ caption?: string; /** determines whether or not to include it in the router's visibleRoutes array for easy navigation UI binding */ - visible?: bool; + visible?: boolean; settings?: Object; } /** * observable that is called when the router is ready */ - export var ready: KnockoutObservableBool; + export var ready: KnockoutObservable; /** * An observable array containing all route info objects. */ - export var allRoutes: KnockoutObservableArray; + export var allRoutes: KnockoutObservableArray; /** * An observable array containing route info objects configured with visible:true (or by calling the mapNav function). */ - export var visibleRoutes: KnockoutObservableArray; + export var visibleRoutes: KnockoutObservableArray; /** * An observable boolean which is true while navigation is in process; false otherwise. */ - export var isNavigating: KnockoutObservableBool; + export var isNavigating: KnockoutObservable; /** * An observable whose value is the currently active item/module/page. */ @@ -409,7 +409,7 @@ declare module "durandal/plugins/router" { /** * An observable whose value is the currently active route. */ - export var activeRoute: KnockoutObservableAny; + export var activeRoute: KnockoutObservable; /** * called after an a new module is composed */ @@ -467,7 +467,7 @@ declare module "durandal/plugins/router" { */ export var mapRoute: { (route: IRouteInfoParameters): IRouteInfo; - (url: string, moduleId?: string, name?: string, visible?: bool): IRouteInfo; + (url: string, moduleId?: string, name?: string, visible?: boolean): IRouteInfo; } /** * This function takes an array of routeInfo objects or a single routeInfo object and uses it to configure the router. The finalized routeInfo (or array of infos) is returned. diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index e643382c3..a8f49f83c 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -11,7 +11,7 @@ */ -/// +/// // rename the native MouseEvent, to avoid conflit with createjs's MouseEvent interface NativeMouseEvent extends MouseEvent { diff --git a/expect.js/expect.js.d.ts b/expect.js/expect.js.d.ts index c4884f07d..c943f4e4f 100644 --- a/expect.js/expect.js.d.ts +++ b/expect.js/expect.js.d.ts @@ -5,7 +5,7 @@ declare function expect(target?: any): Expect.Root; -module Expect { +declare module Expect { interface Assertion { /** * Check if the value is truthy diff --git a/express/express-tests.ts b/express/express-tests.ts index 53dfc1143..a8d373467 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1277,7 +1277,7 @@ function test_general() { app.enabled('trust proxy'); - app.configure(function () => { + app.configure(() => { app.set('title', 'My Application'); }); diff --git a/express/express.d.ts b/express/express.d.ts index ea7ebdf38..d7ac6efd9 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -1312,643 +1312,648 @@ interface Express extends ExpressApplication { response: ExpressServerResponse; } + declare module "express" { - export function (): Express; + function express(): Express; - /** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param options - */ - export function bodyParser(options?: any): Handler; + module express { + /** + * Body parser: + * + * Parse request bodies, supports _application/json_, + * _application/x-www-form-urlencoded_, and _multipart/form-data_. + * + * This is equivalent to: + * + * app.use(connect.json()); + * app.use(connect.urlencoded()); + * app.use(connect.multipart()); + * + * Examples: + * + * connect() + * .use(connect.bodyParser()) + * .use(function(req, res) { + * res.end('viewing user ' + req.body.user.name); + * }); + * + * $ curl -d 'user[name]=tj' http://local/ + * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ + * + * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. + * + * @param options + */ + export function bodyParser(options?: any): Handler; - /** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - */ - export function errorHandler(opts?: any): Handler; + /** + * Error handler: + * + * Development error handler, providing stack traces + * and error message responses for requests accepting text, html, + * or json. + * + * Text: + * + * By default, and when _text/plain_ is accepted a simple stack trace + * or error message will be returned. + * + * JSON: + * + * When _application/json_ is accepted, connect will respond with + * an object in the form of `{ "error": error }`. + * + * HTML: + * + * When accepted connect will output a nice html stack trace. + */ + export function errorHandler(opts?: any): Handler; - /** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param key - */ - export function methodOverride(key?: string): Handler; + /** + * Method Override: + * + * Provides faux HTTP method support. + * + * Pass an optional `key` to use when checking for + * a method override, othewise defaults to _\_method_. + * The original method is available via `req.originalMethod`. + * + * @param key + */ + export function methodOverride(key?: string): Handler; - /** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param secret - */ - export function cookieParser(secret?: string): Handler; + /** + * Cookie parser: + * + * Parse _Cookie_ header and populate `req.cookies` + * with an object keyed by the cookie names. Optionally + * you may enabled signed cookie support by passing + * a `secret` string, which assigns `req.secret` so + * it may be used by other middleware. + * + * Examples: + * + * connect() + * .use(connect.cookieParser('optional secret string')) + * .use(function(req, res, next){ + * res.end(JSON.stringify(req.cookies)); + * }) + * + * @param secret + */ + export function cookieParser(secret?: string): Handler; - /** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

views: ' + sess.views + '

'); - * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param options - */ - export function session(options?: any): Handler; + /** + * Session: + * + * Setup session store with the given `options`. + * + * Session data is _not_ saved in the cookie itself, however + * cookies are used, so we must use the [cookieParser()](cookieParser.html) + * middleware _before_ `session()`. + * + * Examples: + * + * connect() + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) + * + * Options: + * + * - `key` cookie name defaulting to `connect.sid` + * - `store` session store instance + * - `secret` session cookie is signed with this secret to prevent tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Cookie option: + * + * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set + * so the cookie becomes a browser-session cookie. When the user closes the + * browser the cookie (and session) will be removed. + * + * ## req.session + * + * To store or access session data, simply use the request property `req.session`, + * which is (generally) serialized as JSON by the store, so nested objects + * are typically fine. For example below is a user-specific view counter: + * + * connect() + * .use(connect.favicon()) + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) + * .use(function(req, res, next){ + * var sess = req.session; + * if (sess.views) { + * res.setHeader('Content-Type', 'text/html'); + * res.write('

views: ' + sess.views + '

'); + * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); + * res.end(); + * sess.views++; + * } else { + * sess.views = 1; + * res.end('welcome to the session demo. refresh!'); + * } + * } + * )).listen(3000); + * + * ## Session#regenerate() + * + * To regenerate the session simply invoke the method, once complete + * a new SID and `Session` instance will be initialized at `req.session`. + * + * req.session.regenerate(function(err){ + * // will have a new session here + * }); + * + * ## Session#destroy() + * + * Destroys the session, removing `req.session`, will be re-generated next request. + * + * req.session.destroy(function(err){ + * // cannot access session here + * }); + * + * ## Session#reload() + * + * Reloads the session data. + * + * req.session.reload(function(err){ + * // session updated + * }); + * + * ## Session#save() + * + * Save the session. + * + * req.session.save(function(err){ + * // session saved + * }); + * + * ## Session#touch() + * + * Updates the `.maxAge` property. Typically this is + * not necessary to call, as the session middleware does this for you. + * + * ## Session#cookie + * + * Each session has a unique cookie object accompany it. This allows + * you to alter the session cookie per visitor. For example we can + * set `req.session.cookie.expires` to `false` to enable the cookie + * to remain for only the duration of the user-agent. + * + * ## Session#maxAge + * + * Alternatively `req.session.cookie.maxAge` will return the time + * remaining in milliseconds, which we may also re-assign a new value + * to adjust the `.expires` property appropriately. The following + * are essentially equivalent + * + * var hour = 3600000; + * req.session.cookie.expires = new Date(Date.now() + hour); + * req.session.cookie.maxAge = hour; + * + * For example when `maxAge` is set to `60000` (one minute), and 30 seconds + * has elapsed it will return `30000` until the current request has completed, + * at which time `req.session.touch()` is called to reset `req.session.maxAge` + * to its original value. + * + * req.session.cookie.maxAge; + * // => 30000 + * + * Session Store Implementation: + * + * Every session store _must_ implement the following methods + * + * - `.get(sid, callback)` + * - `.set(sid, session, callback)` + * - `.destroy(sid, callback)` + * + * Recommended methods include, but are not limited to: + * + * - `.length(callback)` + * - `.clear(callback)` + * + * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. + * + * @param options + */ + export function session(options?: any): Handler; - /** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param sess - */ - export function hash(sess: string): string; + /** + * Hash the given `sess` object omitting changes + * to `.cookie`. + * + * @param sess + */ + export function hash(sess: string): string; - /** - * Static: - * - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect() - * .use(connect.static(__dirname + '/public')) - * - * connect() - * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true - * - * @param root - * @param options - */ - export function static (root: string, options?: any): Handler; + /** + * Static: + * + * Static file server with the given `root` path. + * + * Examples: + * + * var oneDay = 86400000; + * + * connect() + * .use(connect.static(__dirname + '/public')) + * + * connect() + * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) + * + * Options: + * + * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 + * - `hidden` Allow transfer of hidden files. defaults to false + * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true + * + * @param root + * @param options + */ + export function static(root: string, options?: any): Handler; - /** - * Basic Auth: - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param callback or username - * @param realm - */ - export function basicAuth(callback: Function, realm: string); + /** + * Basic Auth: + * + * Enfore basic authentication by providing a `callback(user, pass)`, + * which must return `true` in order to gain access. Alternatively an async + * method is provided as well, invoking `callback(user, pass, callback)`. Populates + * `req.user`. The final alternative is simply passing username / password + * strings. + * + * Simple username and password + * + * connect(connect.basicAuth('username', 'password')); + * + * Callback verification + * + * connect() + * .use(connect.basicAuth(function(user, pass){ + * return 'tj' == user & 'wahoo' == pass; + * })) + * + * Async callback verification, accepting `fn(err, user)`. + * + * connect() + * .use(connect.basicAuth(function(user, pass, fn){ + * User.authenticate({ user: user, pass: pass }, fn); + * })) + * + * @param callback or username + * @param realm + */ + export function basicAuth(callback: Function, realm: string); - export function basicAuth(callback: string, realm: string); + export function basicAuth(callback: string, realm: string); - export function basicAuth(callback: Function); + export function basicAuth(callback: Function); - /** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param options - */ - export function compress(options?: any): Handler; + /** + * Compress: + * + * Compress response data with gzip/deflate. + * + * Filter: + * + * A `filter` callback function may be passed to + * replace the default logic of: + * + * exports.filter = function(req, res){ + * return /json|text|javascript/.test(res.getHeader('Content-Type')); + * }; + * + * Options: + * + * All remaining options are passed to the gzip/deflate + * creation functions. Consult node's docs for additional details. + * + * - `chunkSize` (default: 16*1024) + * - `windowBits` + * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression + * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more + * - `strategy`: compression strategy + * + * @param options + */ + export function compress(options?: any): Handler; - /** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * @param options - */ - export function cookieSession(options?: any): Handler; + /** + * Cookie Session: + * + * Cookie session middleware. + * + * var app = connect(); + * app.use(connect.cookieParser()); + * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); + * + * Options: + * + * - `key` cookie name defaulting to `connect.sess` + * - `secret` prevents cookie tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Clearing sessions: + * + * To clear the session simply set its value to `null`, + * `cookieSession()` will then respond with a 1970 Set-Cookie. + * + * req.session = null; + * + * @param options + */ + export function cookieSession(options?: any): Handler; - /** - * Anti CSRF: - * - * CRSF protection middleware. - * - * By default this middleware generates a token named "_csrf" - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's `req.session._csrf` - * property. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param options - */ - export function csrf(options: any); + /** + * Anti CSRF: + * + * CRSF protection middleware. + * + * By default this middleware generates a token named "_csrf" + * which should be added to requests which mutate + * state, within a hidden form field, query-string etc. This + * token is validated against the visitor's `req.session._csrf` + * property. + * + * The default `value` function checks `req.body` generated + * by the `bodyParser()` middleware, `req.query` generated + * by `query()`, and the "X-CSRF-Token" header field. + * + * This middleware requires session support, thus should be added + * somewhere _below_ `session()` and `cookieParser()`. + * + * Options: + * + * - `value` a function accepting the request, returning the token + * + * @param options + */ + export function csrf(options: any); - /** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param root - * @param options - */ - export function directory(root: string, options?: any): Handler; + /** + * Directory: + * + * Serve directory listings with the given `root` path. + * + * Options: + * + * - `hidden` display hidden (dot) files. Defaults to false. + * - `icons` display icons. Defaults to false. + * - `filter` Apply this filter function to files. Defaults to false. + * + * @param root + * @param options + */ + export function directory(root: string, options?: any): Handler; - /** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico)) - * - * @param path - * @param options - */ - export function favicon(path?: string, options?: any); + /** + * Favicon: + * + * By default serves the connect favicon, or the favicon + * located by the given `path`. + * + * Options: + * + * - `maxAge` cache-control max-age directive, defaulting to 1 day + * + * Examples: + * + * Serve default favicon: + * + * connect() + * .use(connect.favicon()) + * + * Serve favicon before logging for brevity: + * + * connect() + * .use(connect.favicon()) + * .use(connect.logger('dev')) + * + * Serve custom favicon: + * + * connect() + * .use(connect.favicon('public/favicon.ico)) + * + * @param path + * @param options + */ + export function favicon(path?: string, options?: any); - /** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit disabled by default - * - * @param options - */ - export function json(options?: any): Handler; + /** + * JSON: + * + * Parse JSON request bodies, providing the + * parsed object as `req.body`. + * + * Options: + * + * - `strict` when `false` anything `JSON.parse()` accepts will be parsed + * - `reviver` used as the second "reviver" argument for JSON.parse + * - `limit` byte limit disabled by default + * + * @param options + */ + export function json(options?: any): Handler; - /** - * Limit: - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - */ - export function limit(bytes: number): Handler; + /** + * Limit: + * + * Limit request bodies to the given size in `bytes`. + * + * A string representation of the bytesize may also be passed, + * for example "5mb", "200kb", "1gb", etc. + * + * connect() + * .use(connect.limit('5.5mb')) + * .use(handleImageUpload) + */ + export function limit(bytes: number): Handler; - export function limit(bytes: string): Handler; + export function limit(bytes: string): Handler; - /** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - */ - export function logger(options: string): Handler; + /** + * Logger: + * + * Log requests with the given `options` or a `format` string. + * + * Options: + * + * - `format` Format string, see below for tokens + * - `stream` Output stream, defaults to _stdout_ + * - `buffer` Buffer duration, defaults to 1000ms when _true_ + * - `immediate` Write log line on request instead of response (for response times) + * + * Tokens: + * + * - `:req[header]` ex: `:req[Accept]` + * - `:res[header]` ex: `:res[Content-Length]` + * - `:http-version` + * - `:response-time` + * - `:remote-addr` + * - `:date` + * - `:method` + * - `:url` + * - `:referrer` + * - `:user-agent` + * - `:status` + * + * Formats: + * + * Pre-defined formats that ship with connect: + * + * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' + * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' + * - `tiny` ':method :url :status :res[content-length] - :response-time ms' + * - `dev` concise output colored by response status for development use + * + * Examples: + * + * connect.logger() // default + * connect.logger('short') + * connect.logger('tiny') + * connect.logger({ immediate: true, format: 'dev' }) + * connect.logger(':method :url - :referrer') + * connect.logger(':req[content-type] -> :res[content-type]') + * connect.logger(function(tokens, req, res){ return 'some format string' }) + * + * Defining Tokens: + * + * To define a token, simply invoke `connect.logger.token()` with the + * name and a callback function. The value returned is then available + * as ":type" in this case. + * + * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) + * + * Defining Formats: + * + * All default formats are defined this way, however it's public API as well: + * + * connect.logger.format('name', 'string or function') + */ + export function logger(options: string): Handler; - export function logger(options: Function): Handler; + export function logger(options: Function): Handler; - export function logger(options?: any): Handler; + export function logger(options?: any): Handler; - /** - * Compile `fmt` into a function. - * - * @param fmt - */ - export function compile(fmt: string): Handler; + /** + * Compile `fmt` into a function. + * + * @param fmt + */ + export function compile(fmt: string): Handler; - /** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param name - * @param fn - */ - export function token(name: string, fn: Function): any; + /** + * Define a token function with the given `name`, + * and callback `fn(req, res)`. + * + * @param name + * @param fn + */ + export function token(name: string, fn: Function): any; - /** - * Define a `fmt` with the given `name`. - */ - export function format(name: string, str: string): any; + /** + * Define a `fmt` with the given `name`. + */ + export function format(name: string, str: string): any; - export function format(name: string, str: Function): any; + export function format(name: string, str: Function): any; - /** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - */ - export function query(options: any): Handler; + /** + * Query: + * + * Automatically parse the query-string when available, + * populating the `req.query` object. + * + * Examples: + * + * connect() + * .use(connect.query()) + * .use(function(req, res){ + * res.end(JSON.stringify(req.query)); + * }); + * + * The `options` passed are provided to qs.parse function. + */ + export function query(options: any): Handler; - /** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - */ - export function responseTime(): Handler; + /** + * Reponse time: + * + * Adds the `X-Response-Time` header displaying the response + * duration in milliseconds. + */ + export function responseTime(): Handler; - /** - * Static cache: - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - */ - export function staticCache(options: any): Handler; + /** + * Static cache: + * + * Enables a memory cache layer on top of + * the `static()` middleware, serving popular + * static files. + * + * By default a maximum of 128 objects are + * held in cache, with a max of 256k each, + * totalling ~32mb. + * + * A Least-Recently-Used (LRU) cache algo + * is implemented through the `Cache` object, + * simply rotating cache objects as they are + * hit. This means that increasingly popular + * objects maintain their positions while + * others get shoved out of the stack and + * garbage collected. + * + * Benchmarks: + * + * static(): 2700 rps + * node-static: 5300 rps + * static() + staticCache(): 7500 rps + * + * Options: + * + * - `maxObjects` max cache objects [128] + * - `maxLength` max cache object length 256kb + */ + export function staticCache(options: any): Handler; - /** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 408`. - */ - export function timeout(ms: number): Handler; + /** + * Timeout: + * + * Times out the request in `ms`, defaulting to `5000`. The + * method `req.clearTimeout()` is added to revert this behaviour + * programmatically within your application's middleware, routes, etc. + * + * The timeout error is passed to `next()` so that you may customize + * the response behaviour. This error has the `.timeout` property as + * well as `.status == 408`. + */ + export function timeout(ms: number): Handler; - /** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param hostname - * @param server - */ - export function vhost(hostname: string, server: any): Handler; + /** + * Vhost: + * + * Setup vhost for the given `hostname` and `server`. + * + * connect() + * .use(connect.vhost('foo.com', fooApp)) + * .use(connect.vhost('bar.com', barApp)) + * .use(connect.vhost('*.com', mainApp)) + * + * The `server` may be a Connect server or + * a regular Node `http.Server`. + * + * @param hostname + * @param server + */ + export function vhost(hostname: string, server: any): Handler; - export function urlencoded(): any; + export function urlencoded(): any; - export function multipart(): any; + export function multipart(): any; + } + + export = express; } diff --git a/flot/jquery.flot.d.ts b/flot/jquery.flot.d.ts index 3041966cd..a9d2171b9 100644 --- a/flot/jquery.flot.d.ts +++ b/flot/jquery.flot.d.ts @@ -6,7 +6,7 @@ /// -module jquery.flot { +declare module jquery.flot { interface plotOptions { colors?: any[]; series?: seriesOptions; diff --git a/fullCalendar/fullCalendar-tests.ts b/fullCalendar/fullCalendar-tests.ts new file mode 100644 index 000000000..a85dd1d6e --- /dev/null +++ b/fullCalendar/fullCalendar-tests.ts @@ -0,0 +1,832 @@ +/// +/// +/// + +// All examples from http://arshaw.com/fullcalendar/docs/ + +$('#calendar').fullCalendar({ +}) + +$('#calendar').fullCalendar({ + weekends: false +}); + +$('#calendar').fullCalendar({ + dayClick: function () { + alert('a day has been clicked!'); + } +}); + +$('#calendar').fullCalendar('next'); + +$('#calendar').fullCalendar({ + events: 'http://www.google.com/your_feed_url/' +}); + +$('#calendar').fullCalendar({ + events: { + url: 'http://www.google.com/your_feed_url/', + className: 'gcal-event', // an option! + currentTimezone: 'America/Chicago' // an option! + } +}); + +$('#calendar').fullCalendar({ + eventSources: [ + + // source with no options + "http://www.google.com/your_feed_url1/", + + // source with no options + "http://www.google.com/your_feed_url2/", + + // source WITH options + { + url: "http://www.google.com/your_feed_url3/", + className: 'nice-event' + } + ] +}); + +$('#calendar').fullCalendar({ + height: 650 +}); + +$('#calendar').fullCalendar('option', 'height', 700); + +$('#calendar').fullCalendar({ + contentHeight: 600 +}); + +$('#calendar').fullCalendar('option', 'contentHeight', 650); + +$('#calendar').fullCalendar({ + aspectRatio: 2 +}); + +$('#calendar').fullCalendar('option', 'aspectRatio', 1.8); + +$('#calendar').fullCalendar({ + viewDisplay: function (view) { + alert('The new title of the view is ' + view.title); + } +}); + +$('#calendar').fullCalendar({ + windowResize: function (view) { + alert('The calendar has adjusted to a window resize'); + } +}); + +$('#calendar').fullCalendar('render'); + +$('#calendar').fullCalendar({ + dragOpacity: { + month: .2, + '': .5 + } +}); + +var view: FullCalendar.View = $('#calendar').fullCalendar('getView'); +alert("The view's title is " + view.title); + +$(document).ready(function () { + + var date = new Date(); + var d = date.getDate(); + var m = date.getMonth(); + var y = date.getFullYear(); + + $('#calendar').fullCalendar({ + header: { + left: 'prev,next today', + center: 'title', + right: 'month,basicWeek,basicDay' + }, + editable: true, + events: [ + { + title: 'All Day Event', + start: new Date(y, m, 1) + }, + { + title: 'Long Event', + start: new Date(y, m, d - 5), + end: new Date(y, m, d - 2) + }, + { + id: 999, + title: 'Repeating Event', + start: new Date(y, m, d - 3, 16, 0), + allDay: false + }, + { + id: 999, + title: 'Repeating Event', + start: new Date(y, m, d + 4, 16, 0), + allDay: false + }, + { + title: 'Meeting', + start: new Date(y, m, d, 10, 30), + allDay: false + }, + { + title: 'Lunch', + start: new Date(y, m, d, 12, 0), + end: new Date(y, m, d, 14, 0), + allDay: false + }, + { + title: 'Birthday Party', + start: new Date(y, m, d + 1, 19, 0), + end: new Date(y, m, d + 1, 22, 30), + allDay: false + }, + { + title: 'Click for Google', + start: new Date(y, m, 28), + end: new Date(y, m, 29), + url: 'http://google.com/' + } + ] + }); + +}); + +$(document).ready(function () { + + var date = new Date(); + var d = date.getDate(); + var m = date.getMonth(); + var y = date.getFullYear(); + + $('#calendar').fullCalendar({ + header: { + left: 'prev,next today', + center: 'title', + right: 'month,basicWeek,basicDay' + }, + defaultView: 'basicWeek', + editable: true, + events: [ + { + title: 'All Day Event', + start: new Date(y, m, 1) + }, + { + title: 'Long Event', + start: new Date(y, m, d - 5), + end: new Date(y, m, d - 2) + }, + { + id: 999, + title: 'Repeating Event', + start: new Date(y, m, d - 3, 16, 0), + allDay: false + }, + { + id: 999, + title: 'Repeating Event', + start: new Date(y, m, d + 4, 16, 0), + allDay: false + }, + { + title: 'Meeting', + start: new Date(y, m, d, 10, 30), + allDay: false + }, + { + title: 'Lunch', + start: new Date(y, m, d, 12, 0), + end: new Date(y, m, d, 14, 0), + allDay: false + }, + { + title: 'Birthday Party', + start: new Date(y, m, d + 1, 19, 0), + end: new Date(y, m, d + 1, 22, 30), + allDay: false + }, + { + title: 'Click for Google', + start: new Date(y, m, 28), + end: new Date(y, m, 29), + url: 'http://google.com/' + } + ] + }); + +}); + +$(document).ready(function () { + + var date = new Date(); + var d = date.getDate(); + var m = date.getMonth(); + var y = date.getFullYear(); + + $('#calendar').fullCalendar({ + header: { + left: 'prev,next today', + center: 'title', + right: 'month,basicWeek,basicDay' + }, + defaultView: 'basicDay', + editable: true, + events: [ + { + id: 1, + title: "Long Event", + start: new Date(y, m, d, 14, 0), + end: new Date(y, m, d + 3), + allDay: false + }, + { + id: 2, + title: "Repeating Event", + start: new Date(y, m, d - 1), + allDay: true + }, + { + id: 2, + title: "Repeating Event", + start: new Date(y, m, d + 6), + allDay: true + }, + { + id: 3, + title: "Meeting", + start: new Date(y, m, d, 9, 0), + allDay: false + }, + { + id: 4, + title: "Click for Facebook", + start: new Date(y, m, d, 16), + end: new Date(y, m, d), + url: "http://facebook.com/", + allDay: false + } + ] + }); + +}); + +$(document).ready(function () { + + var date = new Date(); + var d = date.getDate(); + var m = date.getMonth(); + var y = date.getFullYear(); + + $('#calendar').fullCalendar({ + editable: true, + header: { + left: 'prev,next today', + center: 'title', + right: 'month,agendaWeek,agendaDay' + }, + defaultView: 'agendaWeek', + events: [ + { + title: 'All Day Event', + start: new Date(y, m, 1) + }, + { + title: 'Long Event', + start: new Date(y, m, d - 5), + end: new Date(y, m, d - 2) + }, + { + id: 999, + title: 'Repeating Event', + start: new Date(y, m, d - 3, 16, 0), + allDay: false + }, + { + id: 999, + title: 'Repeating Event', + start: new Date(y, m, d + 4, 16, 0), + allDay: false + }, + { + title: 'Meeting', + start: new Date(y, m, d, 10, 30), + allDay: false + }, + { + title: 'Lunch', + start: new Date(y, m, d, 12, 0), + end: new Date(y, m, d, 14, 0), + allDay: false + }, + { + title: 'Birthday Party', + start: new Date(y, m, d + 1, 19, 0), + end: new Date(y, m, d + 1, 22, 30), + allDay: false + }, + { + title: 'Click for Google', + start: new Date(y, m, 28), + end: new Date(y, m, 29), + url: 'http://google.com/' + } + ] + }); + +}); + +$(document).ready(function () { + + var date = new Date(); + var d = date.getDate(); + var m = date.getMonth(); + var y = date.getFullYear(); + + $('#calendar').fullCalendar({ + header: { + left: 'prev,next today', + center: 'title', + right: 'month,agendaWeek,agendaDay' + }, + defaultView: 'agendaDay', + editable: true, + events: [ + { + id: 1, + title: "Long Event", + start: new Date(y, m, d), + end: new Date(y, m, d + 3), + allDay: true + }, + { + id: 2, + title: "Repeating Event", + start: new Date(y, m, d - 1), + allDay: true + }, + { + id: 2, + title: "Repeating Event", + start: new Date(y, m, d + 6), + allDay: true + }, + { + id: 3, + title: "Meeting", + start: new Date(y, m, d, 10, 0), + allDay: false + }, + { + id: 4, + title: "Click for Facebook", + start: new Date(y, m, d, 11, 30), + end: new Date(y, m, d), + url: "http://facebook.com/", + allDay: false + } + ] + }); + +}); + +$('#my-prev-button').click(function () { + $('#calendar').fullCalendar('prev'); +}); + +$('#my-next-button').click(function () { + $('#calendar').fullCalendar('next'); +}); + +$('#my-today-button').click(function () { + $('#calendar').fullCalendar('today'); +}); + +$('#calendar').fullCalendar('gotoDate', 1, 0, 1); + +$('#my-button').click(function () { + var d: Date = $('#calendar').fullCalendar('getDate'); + alert("The current date of the calendar is " + d); +}); + +$('#calendar').fullCalendar({ + events: [ + { + title: 'My Event', + start: '2010-01-01T14:30:00', + allDay: false + } + // other events here... + ], + timeFormat: 'H(:mm)' // uppercase H for 24-hour clock +}); + +$('#calendar').fullCalendar({ + buttonText: { + prev: '<', + next: '>' + } +}); + +$('#calendar').fullCalendar({ + dayClick: function (date, allDay, jsEvent, view) { + + if (allDay) { + alert('Clicked on the entire day: ' + date); + } else { + alert('Clicked on the slot: ' + date); + } + + alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); + + alert('Current view: ' + view.name); + + // change the day's background color just for fun + $(this).css('background-color', 'red'); + + } +}); + +$('#calendar').fullCalendar({ + eventClick: function (calEvent, jsEvent, view) { + + alert('Event: ' + calEvent.title); + alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); + alert('View: ' + view.name); + + // change the border color just for fun + $(this).css('border-color', 'red'); + + } +}); + +$('#calendar').fullCalendar({ + events: [ + { + title: 'My Event', + start: '2010-01-01', + url: 'http://google.com/' + } + // other events here + ], + eventClick: function (event) { + if (event.url) { + window.open(event.url); + return false; + } + } +}); + +$('#calendar').fullCalendar({ + + eventSources: [ + + // your event source + { + url: '/myfeed.php', + type: 'POST', + data: { + custom_param1: 'something', + custom_param2: 'somethingelse' + }, + error: function () { + alert('there was an error while fetching events!'); + }, + color: 'yellow', // a non-ajax option + textColor: 'black' // a non-ajax option + } + + // any other sources... + + ] + +}); + +$('#calendar').fullCalendar({ + + events: { + url: '/myfeed.php', + type: 'POST', + data: { + custom_param1: 'something', + custom_param2: 'somethingelse' + }, + error: function () { + alert('there was an error while fetching events!'); + }, + color: 'yellow', // a non-ajax option + textColor: 'black' // a non-ajax option + } + +}); + +$('#calendar').fullCalendar({ + + events: { + url: '/myfeed.php', + cache: true + } + +}); + +$('#calendar').fullCalendar({ + + eventSources: [ + + // your event source + { + url: '/myfeed.php', // use the `url` property + color: 'yellow', // an option! + textColor: 'black' // an option! + } + + // any other sources... + + ] + +}); + +$('#calendar').fullCalendar({ + events: '/myfeed.php' +}); + +$('#calendar').fullCalendar({ + events: [ + { + title: 'event1', + start: '2010-01-01' + }, + { + title: 'event2', + start: '2010-01-05', + end: '2010-01-07' + }, + { + title: 'event3', + start: '2010-01-09 12:30:00', + allDay: false // will make the time show + } + ] +}); + +$('#calendar').fullCalendar({ + + eventSources: [ + + // your event source + { + events: [ // put the array in the `events` property + { + title: 'event1', + start: '2010-01-01' + }, + { + title: 'event2', + start: '2010-01-05', + end: '2010-01-07' + }, + { + title: 'event3', + start: '2010-01-09 12:30:00', + } + ], + color: 'black', // an option! + textColor: 'yellow' // an option! + } + + // any other event sources... + + ] + +}); + +$('#calendar').fullCalendar({ + events: function (start, end, callback) { + $.ajax({ + url: 'myxmlfeed.php', + dataType: 'xml', + data: { + // our hypothetical feed requires UNIX timestamps + start: Math.round(start.getTime() / 1000), + end: Math.round(end.getTime() / 1000) + }, + success: function (doc) { + var events = []; + $(doc).find('event').each(function () { + events.push({ + title: $(this).attr('title'), + start: $(this).attr('start') // will be parsed + }); + }); + callback(events); + } + }); + } +}); + +$('#calendar').fullCalendar({ + + eventSources: [ + + // your event source + { + events: function (start, end, callback) { + // ... + }, + color: 'yellow', // an option! + textColor: 'black' // an option! + } + + // any other sources... + + ] + +}); + +$('#calendar').fullCalendar({ + eventSources: [ + '/feed1.php', + '/feed2.php' + ] +}); + +$('#calendar').fullCalendar({ + eventClick: function (event, element) { + + event.title = "CLICKED!"; + + $('#calendar').fullCalendar('updateEvent', event); + + } +}); + +$('#calendar').fullCalendar({ + events: [ + // my event data + ], + eventColor: '#378006' +}); + +$('#calendar').fullCalendar({ + events: [ + { + title: 'My Event', + start: '2010-01-01', + description: 'This is a cool event' + } + // more events here + ], + eventRender: function (event, element) { + element.qtip({ + content: event.description + }); + } +}); +$('#my-draggable').draggable({ + revert: true, // immediately snap back to original position + revertDuration: 0 // +}); + +$('#calendar').fullCalendar({ + droppable: true, + drop: function (date, allDay) { + alert("Dropped on " + date + " with allDay=" + allDay); + } +}); + +$('#calendar').fullCalendar({ + droppable: true, + dropAccept: '.cool-event', + drop: function () { + alert('dropped!'); + } +}); + +$('#draggable1').draggable(); +$('#draggable2').draggable(); + +$(document).ready(function () { + + var date = new Date(); + var d = date.getDate(); + var m = date.getMonth(); + var y = date.getFullYear(); + + $('#calendar').fullCalendar({ + theme: true, + header: { + left: 'prev,next today', + center: 'title', + right: 'month,agendaWeek,agendaDay' + }, + editable: true, + events: [ + { + title: 'All Day Event', + start: new Date(y, m, 1) + }, + { + title: 'Long Event', + start: new Date(y, m, d - 5), + end: new Date(y, m, d - 2) + }, + { + id: 999, + title: 'Repeating Event', + start: new Date(y, m, d - 3, 16, 0), + allDay: false + }, + { + id: 999, + title: 'Repeating Event', + start: new Date(y, m, d + 4, 16, 0), + allDay: false + }, + { + title: 'Meeting', + start: new Date(y, m, d, 10, 30), + allDay: false + }, + { + title: 'Lunch', + start: new Date(y, m, d, 12, 0), + end: new Date(y, m, d, 14, 0), + allDay: false + }, + { + title: 'Birthday Party', + start: new Date(y, m, d + 1, 19, 0), + end: new Date(y, m, d + 1, 22, 30), + allDay: false + }, + { + title: 'Click for Google', + start: new Date(y, m, 28), + end: new Date(y, m, 29), + url: 'http://google.com/' + } + ] + }); + +}); + +$(document).ready(function () { + /* initialize the external events + -----------------------------------------------------------------*/ + $('#external-events div.external-event').each(function () { + + // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) + // it doesn't need to have a start or end + var eventObject = { + title: $.trim($(this).text()) // use the element's text as the event title + }; + + // store the Event Object in the DOM element so we can get to it later + $(this).data('eventObject', eventObject); + + // make the event draggable using jQuery UI + $(this).draggable({ + zIndex: 999, + revert: true, // will cause the event to go back to its + revertDuration: 0 // original position after the drag + }); + + }); + /* initialize the calendar + -----------------------------------------------------------------*/ + + $('#calendar').fullCalendar({ + header: { + left: 'prev,next today', + center: 'title', + right: 'month,agendaWeek,agendaDay' + }, + editable: true, + droppable: true, // this allows things to be dropped onto the calendar !!! + drop: function (date, allDay) { // this function is called when something is dropped + + // retrieve the dropped element's stored Event Object + var originalEventObject = $(this).data('eventObject'); + + // we need to copy it, so that multiple events don't have a reference to the same object + var copiedEventObject: any = $.extend({}, originalEventObject); + + // assign it the date that was reported + copiedEventObject.start = date; + copiedEventObject.allDay = allDay; + + // render the event on the calendar + // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/) + $('#calendar').fullCalendar('renderEvent', copiedEventObject, true); + + // is the "remove after drop" checkbox checked? + if ($('#drop-remove').is(':checked')) { + // if so, remove the element from the "Draggable Events" list + $(this).remove(); + } + + } + }); +}); \ No newline at end of file diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts new file mode 100644 index 000000000..d11c68e04 --- /dev/null +++ b/fullCalendar/fullCalendar.d.ts @@ -0,0 +1,188 @@ +// Type definitions for FullCalendar 1.6.1 +// Project: http://arshaw.com/fullcalendar/ (http://arshaw.com/fullcalendar/) +// Definitions by: Neil Stalker +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module FullCalendar { + export interface Calendar { + formatDate(date: Date, format: string, options?: Options): string; + formatDates(date1: Date, date2: Date, format: string, options?: Options): string; + parseDate(dateString: string, ignoreTimezone?: boolean): Date; + parseISO8601(dateString: string, ignoreTimezone?: boolean): Date; + version: string; + } + + export interface Options { + header?: { + left: string; + center: string; + right: string; + } + theme?: boolean + buttonIcons?: { + prev: string; + next: string; + } + firstDay?: number; + isRTL?: boolean; + weekends?: boolean; + weekMode?: string; + weekNumbers?: boolean; + weekNumberCalculation?: any; // String/Function + height?: number; + contentHeight?: number; + aspectRation?: number; + viewDisplay?: (view: View) => void; + windowResize?: (view: View) => void; + dayRender?: (date: Date, cell: HTMLTableDataCellElement) => void; + + defaultView?: string; + + year?: number; + month?: number; + date?: number; + + timeFormat?: any; // String/ViewOptionHash + columnFormat?: any; // String/ViewOptionHash + titleFormat?: any; // String/ViewOptionHash + buttonText?: ButtonTextObject; + monthNames?: Array; + monthNamesShort?: Array; + dayNames?: Array; + dayNamesShort?: Array; + weekNumberTitle?: number; + + dayClick?: (date: Date, allDay: boolean, jsEvent: Event, view: View) => void; + eventClick?: (event: EventObject, jsEvent: Event, view: View) => any; // return type boolean or void + eventMouseover?: (event: EventObject, jsEvent: Event, view: View) => void; + eventMouseout?: (event: EventObject, jsEvent: Event, view: View) => void; + + selectable?: any; // Boolean/ViewOptionHash + selectHelper?: any; // Boolean/Function + unselectAuto?: boolean; + unselectCancel?: string; + select?: (startDate: Date, endDate: Date, allDay: boolean, jsEvent: Event, view: View) => void; + unselect?: (view: View, jsEvent: Event) => void; + + eventSources?: Array; + allDayDefault?: boolean; + ignoreTimezone?: boolean; + eventDataTransform?: (eventData: any) => EventObject; + startParam?: string; + endParam?: string + lazyFetching?: boolean; + loading?: (isLoading: boolean, view: View) => void; + + eventColor?: string; + eventBackgroundColor?: string; + eventBorderColor?: string; + eventTextColor?: string; + eventRender?: (event: EventObject, element: HTMLDivElement, view: View) => void; + eventAfterRender?: (event: EventObject, element: HTMLDivElement, view: View) => void; + eventAllAfterRender?: (view: View) => void; + + editable?: boolean; + disableDragging?: boolean; + disableResizing?: boolean; + dragRevertDuration?: number; + dragOpacity?: any; // Float/ViewOptionHash + eventDragStart?: (event: EventObject, jsEvent: Event, ui: any, view: View) => void; + eventDragStop?: (event: EventObject, jsEvent: Event, ui: any, view: View) => void; + eventDrop?: (event: EventObject, dayDelta: number, minuteDelta: number, revertFunc: Function, jsEvent: Event, ui: any, view: View) => void; + eventResizeStart?: (event: EventObject, jsEvent: Event, ui: any, view: View) => void; + eventResizeStop?: (event: EventObject, jsEvent: Event, ui: any, view: View) => void; + eventResize?: (event: EventObject, dayDelta: number, minuteDelta: number, revertFunc: Function, jsEvent: Event, ui: any, view: View) => void; + + droppable?: boolean; + dropAccept?: any; // String/Function + drop?: (date: Date, allDay: boolean, jsEvent: Event, ui: any) => void; + } + + export interface View { + name: string; + title: string; + start: Date; + End: Date; + visStart: Date; + visEnd: Date; + } + + export interface ViewOptionHash { + month?: any; + week?: any; + day?: any; + agenda?: any; + agendaDay?: any; + agendaWeek?: any; + basic?: any; + basicDay?: any; + basicWeek?: any; + ''?: any; + } + + export interface AgendaOptions { + allDaySlot?: boolean; + allDayText?: string; + axisFormat?: string; + slotMinutes?: number; + snapMinutes?: number; + defaultEventMinutes?: number; + firstHour?: number; + minTime?: any; // Integer/String + maxTime?: any; // Integer/String + } + + export interface ButtonTextObject { + prev?: string; + next?: string; + prevYear?: string; + nextYear?: string; + today?: string; + month?: string; + week?: string; + day?: string; + } + + export interface EventObject { + id?: any // String/number + title: string; + allDay?: boolean; + start: Date; + end?: Date; + url?: string; + className?: any; // string/Array + editable?: boolean; + source?: EventSource; + color?: string; + backgroundColor?: string; + borderColor?: string; + textColor?: string; + } + + export interface EventSource extends JQueryAjaxSettings { + events?: any; + color?: string; + backgroundColor?: string; + borderColor?: string; + textColor?: string; + className?: any; // string/Array + editable?: boolean; + allDayDefault?: boolean; + ignoreTimezone?: boolean; + eventTransform?: any; + startParam?: string; + endParam?: string + } + +} + +interface JQuery { + fullCalendar(options: FullCalendar.Options): JQuery; + fullCalendar(method: string, ...args: Array): JQuery; +} + +interface JQueryStatic { + fullCalendar: FullCalendar.Calendar; +} \ No newline at end of file diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 711f25a25..677155130 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -34,7 +34,6 @@ declare module google.maps { notify(key: string): void; set(key: string, value: any): void; setValues(values: any): void; - setValues(values: undefined); unbind(key: string): void; unbindAll(): void; } @@ -1582,4 +1581,4 @@ declare module google.maps { } } -} \ No newline at end of file +} diff --git a/i18next/tests/i18next.d.tests.ts b/i18next/i18next-tests.ts similarity index 96% rename from i18next/tests/i18next.d.tests.ts rename to i18next/i18next-tests.ts index 2feb294b1..a0fbd4332 100644 --- a/i18next/tests/i18next.d.tests.ts +++ b/i18next/i18next-tests.ts @@ -1,15 +1,12 @@ -/// -/// +/// +/// +/// +/// /// -/// - -// declarations for expect.js -declare var expect: (actual: string) => any; -declare var expect: (actual: number) => any; - -// declarations for jsfixtures.js -declare var setFixtures: (html) => void; +/// +declare function done(): void; + describe('i18next', function () { var i18n = $.i18n @@ -1221,9 +1218,7 @@ describe('i18next', function () { }; beforeEach(function (done) { - setFixtures(' - -'); + fixtures.set(''); i18n.init($.extend(opts, { resStore: resStore }), function (t) { done(); }); @@ -1250,9 +1245,7 @@ describe('i18next', function () { }; beforeEach(function (done) { - setFixtures(' - -'); + fixtures.set(''); i18n.init($.extend(opts, { resStore: resStore }), function (t) { done(); }); @@ -1279,9 +1272,7 @@ describe('i18next', function () { }; beforeEach(function (done) { - setFixtures(' - -'); + fixtures.set(''); i18n.init($.extend(opts, { resStore: resStore }), function (t) { done(); }); @@ -1299,14 +1290,11 @@ describe('i18next', function () { var resStore = { dev: { translation: {} }, en: { translation: {} }, - 'en-US': { translation: { 'simpleTest': ' -test -' } } + 'en-US': { translation: { 'simpleTest': 'test' } } }; beforeEach(function (done) { - setFixtures(' -'); + fixtures.set(''); i18n.init($.extend(opts, { resStore: resStore }), function (t) { done(); }); @@ -1329,9 +1317,7 @@ test }; beforeEach(function (done) { - setFixtures(' - -'); + fixtures.set(''); i18n.init($.extend(opts, { resStore: resStore, diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index cd85d7104..a1b843640 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -13,7 +13,7 @@ interface IResourceStoreLanguage { [namespace: string]: IResourceStoreKey; } interface IResourceStoreKey { - [key: string]; + [key: string]: any; } interface I18nextOptions { diff --git a/i18next/lib/jquery.d.ts b/i18next/lib/jquery.d.ts deleted file mode 100644 index 25e2aa626..000000000 --- a/i18next/lib/jquery.d.ts +++ /dev/null @@ -1,758 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -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 - -THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -// Typing for the jQuery library, version 1.7.x - -/* - Interface for the AJAX setting that will configure the AJAX request -*/ -interface JQueryAjaxSettings { - accepts?: any; - async?: bool; - beforeSend?(jqXHR: JQueryXHR, settings: JQueryAjaxSettings); - cache?: bool; - complete?(jqXHR: JQueryXHR, textStatus: string); - contents?: { [key: string]: any; }; - contentType?: string; - context?: any; - converters?: { [key: string]: any; }; - crossDomain?: bool; - data?: any; - dataFilter?(data: any, ty: any): any; - dataType?: string; - error?(jqXHR: JQueryXHR, textStatus: string, errorThrow: string): any; - global?: bool; - headers?: { [key: string]: any; }; - ifModified?: bool; - isLocal?: bool; - jsonp?: string; - jsonpCallback?: any; - mimeType?: string; - password?: string; - processData?: bool; - scriptCharset?: string; - statusCode?: { [key: string]: any; }; - success?(data: any, textStatus: string, jqXHR: JQueryXHR); - timeout?: number; - traditional?: bool; - type?: string; - url?: string; - username?: string; - xhr?: any; - xhrFields?: { [key: string]: any; }; -} - -/* - Interface for the jqXHR object -*/ -interface JQueryXHR extends XMLHttpRequest, JQueryPromise { - overrideMimeType(mimeType: string); -} - -/* - Interface for the JQuery callback -*/ -interface JQueryCallback { - add(...callbacks: any[]): any; - disable(): any; - empty(): any; - fire(...arguments: any[]): any; - fired(): bool; - fireWith(context: any, ...args: any[]): any; - has(callback: any): bool; - lock(): any; - locked(): bool; - remove(...callbacks: any[]): any; -} - -/* - Interface for the JQuery promise, part of callbacks -*/ -interface JQueryPromise { - always(...alwaysCallbacks: any[]): JQueryDeferred; - done(...doneCallbacks: any[]): JQueryDeferred; - fail(...failCallbacks: any[]): JQueryDeferred; - progress(...progressCallbacks: any[]): JQueryDeferred; - state(): string; - pipe(doneFilter?: (...args: any[]) => any, failFilter?: (...args: any[]) => any, progressFilter?: (...args: any[]) => any): JQueryPromise; - then(doneCallbacks: any, failCallbacks: any, progressCallbacks?: any): JQueryDeferred; -} - -/* - Interface for the JQuery deferred, part of callbacks -*/ -interface JQueryDeferred extends JQueryPromise { - notify(...args: any[]): JQueryDeferred; - notifyWith(context: any, ...args: any[]): JQueryDeferred; - - pipe(doneFilter?: any, failFilter?: any, progressFilter?: any): JQueryPromise; - progress(...progressCallbacks: any[]): JQueryDeferred; - promise(target? ): JQueryDeferred; - reject(...args: any[]): JQueryDeferred; - rejectWith(context:any, ...args: any[]): JQueryDeferred; - resolve(...args: any[]): JQueryDeferred; - resolveWith(context:any, ...args: any[]): JQueryDeferred; - state(): string; - then(doneCallbacks: any, failCallbacks: any, progressCallbacks?: any): JQueryDeferred; -} - -/* - Interface of the JQuery extension of the W3C event object -*/ -interface JQueryEventObject extends Event { - data: any; - delegateTarget: Element; - isDefaultPrevented(): bool; - isImmediatePropogationStopped(): bool; - isPropogationStopped(): bool; - namespace: string; - preventDefault(): any; - relatedTarget: Element; - result: any; - stopImmediatePropagation(); - stopPropagation(); - pageX: number; - pageY: number; - which: number; - metaKey: any; -} - -/* - Collection of properties of the current browser -*/ -interface JQueryBrowserInfo { - safari:bool; - opera:bool; - msie:bool; - mozilla:bool; - webkit:bool; - version:string; -} - -interface JQuerySupport { - ajax?: bool; - boxModel?: bool; - changeBubbles?: bool; - checkClone?: bool; - checkOn?: bool; - cors?: bool; - cssFloat?: bool; - hrefNormalized?: bool; - htmlSerialize?: bool; - leadingWhitespace?: bool; - noCloneChecked?: bool; - noCloneEvent?: bool; - opacity?: bool; - optDisabled?: bool; - optSelected?: bool; - scriptEval?(): bool; - style?: bool; - submitBubbles?: bool; - tbody?: bool; -} - -/* - Static members of jQuery (those on $ and jQuery themselves) -*/ -interface JQueryStatic { - - /**** - AJAX - *****/ - ajax(settings: JQueryAjaxSettings): JQueryXHR; - ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; - - ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: any, jqXHR: JQueryXHR) => any): any; - ajaxPrefilter(handler: (opts: any, originalOpts: any, jqXHR: JQueryXHR) => any): any; - - ajaxSettings: JQueryAjaxSettings; - - ajaxSetup(options: any); - - get(url: string, data?: any, success?: any, dataType?: any): JQueryXHR; - getJSON(url: string, data?: any, success?: any): JQueryXHR; - getScript(url: string, success?: any): JQueryXHR; - - param(obj: any): string; - param(obj: any, traditional: bool): string; - - post(url: string, data?: any, success?: any, dataType?: any): JQueryXHR; - - /********* - CALLBACKS - **********/ - Callbacks(flags?: string): JQueryCallback; - - /**** - CORE - *****/ - holdReady(hold: bool): any; - - (selector: string, context?: any): JQuery; - (element: Element): JQuery; - (object: { }): JQuery; - (elementArray: Element[]): JQuery; - (object: JQuery): JQuery; - (func: Function): JQuery; - (array: any[]): JQuery; - (): JQuery; - - noConflict(removeAll?: bool): Object; - - when(...deferreds: any[]): JQueryPromise; - - /*** - CSS - ****/ - css(e: any, propertyName: string, value?: any); - css(e: any, propertyName: any, value?: any); - cssHooks: { [key: string]: any; }; - cssNumber: any; - - /**** - DATA - *****/ - data(element: Element, key: string, value: any): any; - data(element: Element, key: string): any; - data(element: Element): any; - - dequeue(element: Element, queueName?: string): any; - - hasData(element: Element): bool; - - queue(element: Element, queueName?: string): any[]; - queue(element: Element, queueName: string, newQueueOrCallback: any): JQuery; - - removeData(element: Element, name?: string): JQuery; - - /******* - EFFECTS - ********/ - fx: { tick: () => void; interval: number; stop: () => void; speeds: { slow: number; fast: number; }; off: bool; step: any; }; - - /****** - EVENTS - *******/ - proxy(fn: Function, context: any): any; - proxy(context: any, name: any): any; - Deferred(): JQueryDeferred; - - /********* - INTERNALS - **********/ - error(message: any); - - /************* - MISCELLANEOUS - **************/ - expr: any; - fn: any; //TODO: Decide how we want to type this - isReady: bool; - - /********** - PROPERTIES - ***********/ - browser: JQueryBrowserInfo; - support: JQuerySupport; - - /********* - UTILITIES - **********/ - contains(container: Element, contained: Element): bool; - - each(collection: any, callback: (indexInArray: any, valueOfElement: any) => any): any; - - extend(target: any, ...objs: any[]): Object; - extend(deep: bool, target: any, ...objs: any[]): Object; - - globalEval(code: string): any; - - grep(array: any[], func: any, invert?: bool): any[]; - - inArray(value: any, array: any[], fromIndex?: number): number; - - isArray(obj: any): bool; - isEmptyObject(obj: any): bool; - isFunction(obj: any): bool; - isNumeric(value: any): bool; - isPlainObject(obj: any): bool; - isWindow(obj: any): bool; - isXMLDoc(node: Node): bool; - - makeArray(obj: any): any[]; - - map(array: any[], callback: (elementOfArray: any, indexInArray: any) =>any): any[]; - - merge(first: any[], second: any[]): any[]; - - noop(): any; - - now(): number; - - parseJSON(json: string): Object; - - //FIXME: This should return an XMLDocument - parseXML(data: string): any; - - queue(element: Element, queueName: string, newQueue: any[]): JQuery; - - trim(str: string): string; - - type(obj: any): string; - - unique(arr: any[]): any[]; -} - -/* - The jQuery instance members -*/ -interface JQuery { - /**** - AJAX - *****/ - ajaxComplete(handler: any): JQuery; - ajaxError(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; - ajaxSend(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; - ajaxStart(handler: () => any): JQuery; - ajaxStop(handler: () => any): JQuery; - ajaxSuccess(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; - - load(url: string, data?: any, complete?: any): JQuery; - - serialize(): string; - serializeArray(): any[]; - - /********** - ATTRIBUTES - ***********/ - addClass(classNames: string): JQuery; - addClass(func: (index: any, currentClass: any) => string): JQuery; - - attr(attributeName: string): string; - attr(attributeName: string, value: any): JQuery; - attr(map: { [key: string]: any; }): JQuery; - attr(attributeName: string, func: (index: any, attr: any) => any): JQuery; - - hasClass(className: string): bool; - - html(): string; - html(htmlString: string): JQuery; - html(htmlContent: (index: number, oldhtml: string) => string): JQuery; - - prop(propertyName: string): any; - prop(propertyName: string, value: any): JQuery; - prop(map: any): JQuery; - prop(propertyName: string, func: (index: any, oldPropertyValue: any) => any): JQuery; - - removeAttr(attributeName: any): JQuery; - - removeClass(className?: any): JQuery; - removeClass(func: (index: any, cls: any) => any): JQuery; - - removeProp(propertyName: any): JQuery; - - toggleClass(className: any, swtch?: bool): JQuery; - toggleClass(swtch?: bool): JQuery; - toggleClass(func: (index: any, cls: any, swtch: any) => any): JQuery; - - val(): any; - val(value: string[]): JQuery; - val(value: string): JQuery; - val(value: number): JQuery; - val(func: (index: any, value: any) => any): JQuery; - - /*** - CSS - ****/ - css(propertyName: string, value?: any): any; - css(propertyName: any, value?: any): any; - - height(): number; - height(value: number): JQuery; - height(value: string): JQuery; - height(func: (index: any, height: any) => any): JQuery; - - innerHeight(): number; - innerWidth(): number; - - offset(): { left: number; top: number; }; - offset(coordinates: any): JQuery; - offset(func: (index: any, coords: any) => any): JQuery; - - outerHeight(includeMargin?: bool): number; - outerWidth(includeMargin?: bool): number; - - position(): { top: number; left: number; }; - - scrollLeft(): number; - scrollLeft(value: number): JQuery; - - scrollTop(): number; - scrollTop(value: number): JQuery; - - width(): number; - width(value: number): JQuery; - width(value: string): JQuery; - width(func: (index: any, height: any) => any): JQuery; - - /**** - DATA - *****/ - clearQueue(queueName?: string): JQuery; - - data(key: string, value: any): JQuery; - data(obj: { [key: string]: any; }): JQuery; - data(key?: string): any; - - dequeue(queueName?: string): JQuery; - - removeData(nameOrList?: any): JQuery; - - /******** - DEFERRED - *********/ - promise(type?: any, target?: any): JQueryPromise; - - /******* - EFFECTS - ********/ - animate(properties: any, duration?: any, complete?: Function): JQuery; - animate(properties: any, duration?: any, easing?: string, complete?: Function): JQuery; - animate(properties: any, options: { duration?: any; easing?: string; complete?: Function; step?: Function; queue?: bool; specialEasing?: any; }); - - delay(duration: number, queueName?: string): JQuery; - - fadeIn(duration?: any, callback?: any): JQuery; - fadeIn(duration?: any, easing?: string, callback?: any): JQuery; - - fadeOut(duration?: any, callback?: any): JQuery; - fadeOut(duration?: any, easing?: string, callback?: any): JQuery; - - fadeTo(duration: any, opacity: number, callback?: any): JQuery; - fadeTo(duration: any, opacity: number, easing?: string, callback?: any): JQuery; - - fadeToggle(duration?: any, callback?: any): JQuery; - fadeToggle(duration?: any, easing?: string, callback?: any): JQuery; - - hide(duration?: any, callback?: any): JQuery; - hide(duration?: any, easing?: string, callback?: any): JQuery; - - show(duration?: any, callback?: any): JQuery; - show(duration?: any, easing?: string, callback?: any): JQuery; - - slideDown(duration?: any, callback?: any): JQuery; - slideDown(duration?: any, easing?: string, callback?: any): JQuery; - - slideToggle(duration?: any, callback?: any): JQuery; - slideToggle(duration?: any, easing?: string, callback?: any): JQuery; - - slideUp(duration?: any, callback?: any): JQuery; - slideUp(duration?: any, easing?: string, callback?: any): JQuery; - - stop(clearQueue?: bool, jumpToEnd?: bool): JQuery; - stop(queue?:any, clearQueue?: bool, jumpToEnd?: bool): JQuery; - - toggle(duration?: any, callback?: any): JQuery; - toggle(duration?: any, easing?: string, callback?: any): JQuery; - toggle(showOrHide: bool): JQuery; - - /****** - EVENTS - *******/ - bind(eventType: string, eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - bind(eventType: string, eventData: any, preventBubble:bool): JQuery; - bind(eventType: string, preventBubble:bool): JQuery; - bind(...events: any[]); - - blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - blur(handler: (eventObject: JQueryEventObject) => any): JQuery; - - change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - change(handler: (eventObject: JQueryEventObject) => any): JQuery; - - click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - click(handler: (eventObject: JQueryEventObject) => any): JQuery; - - dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; - - delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - - focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - focus(handler: (eventObject: JQueryEventObject) => any): JQuery; - - focusin(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; - - focusout(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; - - hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; - hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; - - keydown(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - keydown(handler: (eventObject: JQueryEventObject) => any): JQuery; - - keypress(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - keypress(handler: (eventObject: JQueryEventObject) => any): JQuery; - - keyup(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - keyup(handler: (eventObject: JQueryEventObject) => any): JQuery; - - load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - load(handler: (eventObject: JQueryEventObject) => any): JQuery; - - mousedown(): JQuery; - mousedown(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - mousedown(handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseevent(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseevent(handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseenter(): JQuery; - mouseenter(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseenter(handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseleave(): JQuery; - mouseleave(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseleave(handler: (eventObject: JQueryEventObject) => any): JQuery; - - mousemove(): JQuery; - mousemove(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - mousemove(handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseout(): JQuery; - mouseout(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseout(handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseover(): JQuery; - mouseover(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseover(handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseup(): JQuery; - mouseup(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseup(handler: (eventObject: JQueryEventObject) => any): JQuery; - - off(events?: string, selector?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - off(eventsMap: { [key: string]: any; }, selector?: any): JQuery; - - on(events: string, selector?: any, data?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - on(eventsMap: { [key: string]: any; }, selector?: any, data?: any): JQuery; - - one(events: string, selector?: any, data?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - one(eventsMap: { [key: string]: any; }, selector?: any, data?: any): JQuery; - - ready(handler: any): JQuery; - - resize(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - resize(handler: (eventObject: JQueryEventObject) => any): JQuery; - - scroll(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; - - select(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - select(handler: (eventObject: JQueryEventObject) => any): JQuery; - - submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - submit(handler: (eventObject: JQueryEventObject) => any): JQuery; - - trigger(eventType: string, ...extraParameters: any[]): JQuery; - trigger(event: JQueryEventObject): JQuery; - - triggerHandler(eventType: string, ...extraParameters: any[]): Object; - - unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - unbind(eventType: string, fls: bool): JQuery; - unbind(evt: any): JQuery; - - undelegate(): JQuery; - undelegate(selector: any, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - undelegate(selector: any, events: any): JQuery; - undelegate(namespace: string): JQuery; - - unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - unload(handler: (eventObject: JQueryEventObject) => any): JQuery; - - /********* - INTERNALS - **********/ - - context: Element; - jquery: string; - - error(handler: (eventObject: JQueryEventObject) => any): JQuery; - error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - pushStack(elements: any[]): JQuery; - pushStack(elements: any[], name: any, arguments: any): JQuery; - - /************ - MANIPULATION - *************/ - after(...content: any[]): JQuery; - after(func: (index: any) => any); - - append(...content: any[]): JQuery; - append(func: (index: any, html: any) => any); - - appendTo(target: any): JQuery; - - before(...content: any[]): JQuery; - before(func: (index: any) => any); - - clone(withDataAndEvents?: bool, deepWithDataAndEvents?: bool): JQuery; - - detach(selector?: any): JQuery; - - empty(): JQuery; - - insertAfter(target: any): JQuery; - insertBefore(target: any): JQuery; - - prepend(...content: any[]): JQuery; - prepend(func: (index: any, html: any) =>any): JQuery; - - prependTo(target: any): JQuery; - - remove(selector?: any): JQuery; - - replaceAll(target: any): JQuery; - - replaceWith(func: any): JQuery; - - text(): string; - text(textString: any): JQuery; - text(textString: (index: number, text: string) => string): JQuery; - - toArray(): any[]; - - unwrap(): JQuery; - - wrap(wrappingElement: any): JQuery; - wrap(func: (index: any) =>any): JQuery; - - wrapAll(wrappingElement: any): JQuery; - - wrapInner(wrappingElement: any): JQuery; - wrapInner(func: (index: any) =>any): JQuery; - - /************* - MISCELLANEOUS - **************/ - each(func: (index: any, elem: Element) => any); - - get(index?: number): any; - - index(): number; - index(selector: string): number; - index(element: any): number; - - /********** - PROPERTIES - ***********/ - length: number; - [x: string]: HTMLElement; - [x: number]: HTMLElement; - - /********** - TRAVERSING - ***********/ - add(selector: string, context?: any): JQuery; - add(...elements: any[]): JQuery; - add(html: string): JQuery; - add(obj: JQuery): JQuery; - - andSelf(): JQuery; - - children(selector?: any): JQuery; - - closest(selector: string): JQuery; - closest(selector: string, context?: Element): JQuery; - closest(obj: JQuery): JQuery; - closest(element: any): JQuery; - closest(selectors: any, context?: Element): any[]; - - contents(): JQuery; - - end(): JQuery; - - eq(index: number): JQuery; - - filter(selector: string): JQuery; - filter(func: (index: any) =>any): JQuery; - filter(element: any): JQuery; - filter(obj: JQuery): JQuery; - - find(selector: string): JQuery; - find(element: any): JQuery; - find(obj: JQuery): JQuery; - - first(): JQuery; - - has(selector: string): JQuery; - has(contained: Element): JQuery; - - is(selector: string): bool; - is(func: (index: any) =>any): bool; - is(element: any): bool; - is(obj: JQuery): bool; - - last(): JQuery; - - map(callback: (index: any, domElement: Element) =>any): JQuery; - - next(selector?: string): JQuery; - - nextAll(selector?: string): JQuery; - - nextUntil(selector?: string, filter?: string): JQuery; - nextUntil(element?: Element, filter?: string): JQuery; - - not(selector: string): JQuery; - not(func: (index: any) =>any): JQuery; - not(element: any): JQuery; - not(obj: JQuery): JQuery; - - offsetParent(): JQuery; - - parent(selector?: string): JQuery; - - parents(selector?: string): JQuery; - - parentsUntil(selector?: string, filter?: string): JQuery; - parentsUntil(element?: Element, filter?: string): JQuery; - - prev(selector?: string): JQuery; - - prevAll(selector?: string): JQuery; - - prevUntil(selector?: string, filter?:string): JQuery; - prevUntil(element?: Element, filter?:string): JQuery; - - siblings(selector?: string): JQuery; - - slice(start: number, end?: number): JQuery; - - /********* - UTILITIES - **********/ - - queue(queueName?: string): any[]; - queue(queueName: string, newQueueOrCallback: any): JQuery; - queue(newQueueOrCallback: any): JQuery; -} - -declare var jQuery: JQueryStatic; -declare var $: JQueryStatic; diff --git a/i18next/lib/mocha.d.ts b/i18next/lib/mocha.d.ts deleted file mode 100644 index ee31e689d..000000000 --- a/i18next/lib/mocha.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -// BDD -declare function describe(cb: () => void); -declare function describe(cb: (done:() => void) => void); -declare function describe(title: string, cb: () => void); -declare function describe(title: string, cb: (done:() => void) => void); - -declare function it(cb: () => void); -declare function it(cb: (done:() => void) => void); -declare function it(title: string, cb: () => void); -declare function it(title: string, cb: (done:() => void) => void); - -declare function before(cb: () => void); -declare function before(cb: (done:() => void) => void); -declare function before(title: string, cb: () => void); -declare function before(title: string, cb: (done:() => void) => void); - -declare function after(cb: () => void); -declare function after(cb: (done:() => void) => void); -declare function after(title: string, cb: () => void); -declare function after(title: string, cb: (done:() => void) => void); - -declare function beforeEach(cb: () => void); -declare function beforeEach(cb: (done:() => void) => void); -declare function beforeEach(title: string, cb: () => void); -declare function beforeEach(title: string, cb: (done:() => void) => void); - -declare function afterEach(cb: () => void); -declare function afterEach(cb: (done:() => void) => void); -declare function afterEach(title: string, cb: () => void); -declare function afterEach(title: string, cb: (done:() => void) => void); - - -// TDD -declare function suite(title: string, cb: () => void); -declare function test(title: string, cb: () => void); -declare function test(title: string, cb: (done:() => void) => void); -declare function setup(title: string, cb: () => void); -declare function teardown(title: string, cb: () => void); - -declare function suite(cb: () => void); -declare function test(cb: () => void); -declare function test(cb: (done:() => void) => void); -declare function setup(cb: () => void); -declare function teardown(cb: () => void); diff --git a/i18next/lib/sinon.d.ts b/i18next/lib/sinon.d.ts deleted file mode 100644 index 25198e3b3..000000000 --- a/i18next/lib/sinon.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -/// - -interface spy { - called: bool; - getCall(x: number): any; - fakeServer: ISinonFakeServer; - calledOnce: bool; - calledWith(x: any, message: string): bool; -} - -interface IJsonReponse { - responseCode: number; - responseHeaders: any; - responseString: string; -} - -interface ISinonFakeServer { - create(): any; - restore(): void; - respondWith(postType: string, relativeUrl: string, x: any): any; - respond(): any; -} - -declare module sinon { - export function spy(): spy; - export function spy(fn: Function): spy; - //export function spy(jquery: JQueryStatic , x: string): spy; - export function spy(jquery: JQueryStatic , x: any): spy; - export function spy(obj: Object , methodName: string): spy; - export var fakeServer: ISinonFakeServer; - export function stub(x: any, name: string); - export function useFakeTimers(): void; -} \ No newline at end of file diff --git a/jquery.bbq/jquery.bbq-tests.ts b/jquery.bbq/jquery.bbq-tests.ts index 1543ae63c..c9a337d71 100644 --- a/jquery.bbq/jquery.bbq-tests.ts +++ b/jquery.bbq/jquery.bbq-tests.ts @@ -149,7 +149,7 @@ test( 'jQuery.param.sorted', function() { expect( tests.length * 2 + 6 ); - $.each( tests, function(i,test){ + $.each( tests, function(i,test: any){ var unsorted = $.param( test.obj, test.traditional ), sorted = $.param.sorted( test.obj, test.traditional ); diff --git a/jquery.bbq/jquery.bbq.d.ts b/jquery.bbq/jquery.bbq.d.ts index 5e94efea9..488b1b6c7 100644 --- a/jquery.bbq/jquery.bbq.d.ts +++ b/jquery.bbq/jquery.bbq.d.ts @@ -5,7 +5,7 @@ /// -module JQueryBbq { +declare module JQueryBbq { interface JQuery { /** diff --git a/jquery.pickadate/jquery.pickadate-tests.ts b/jquery.pickadate/jquery.pickadate-tests.ts new file mode 100644 index 000000000..ac6a161c6 --- /dev/null +++ b/jquery.pickadate/jquery.pickadate-tests.ts @@ -0,0 +1,400 @@ +/// + +/* +* Date picker tests +* From http://amsul.ca/pickadate.js/date.htm +*/ + +$('.datepicker').pickadate(); + +$('.datepicker').pickadate({ + weekdaysShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + showMonthsShort: true +}); + +$('.datepicker').pickadate({ + today: '', + clear: 'Clear selection' +}); + +// Extend the default picker options for all instances. +$.extend($.fn.pickadate.defaults, { + monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], + weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], + today: 'aujourd\'hui', + clear: 'effacer', + formatSubmit: 'yyyy/mm/dd' +}); + +// Or, pass the months and weekdays as an array for each invocation. +$('.datepicker').pickadate({ + monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], + weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], + today: 'aujourd\'hui', + clear: 'effacer', + formatSubmit: 'yyyy/mm/dd' +}); + +$('.datepicker').pickadate({ + // Escape any "rule" characters with an exclamation mark (!). + format: 'You selecte!d: dddd, dd mmm, yyyy', + formatSubmit: 'yyyy/mm/dd', + hiddenSuffix: '--submit' +}); + +$('.datepicker').pickadate({ + selectYears: true, + selectMonths: true +}); + +$('.datepicker').pickadate({ + // `true` defaults to 10. + selectYears: 4 +}); + +$('.datepicker').pickadate({ + firstDay: 1 +}); + +$('.datepicker').pickadate({ + min: new Date(2013, 3, 20), + max: new Date(2013, 7, 14) +}); + +$('.datepicker').pickadate({ + min: [2013, 3, 20], + max: [2013, 7, 14] +}); + +$('.datepicker').pickadate({ + // An integer (positive/negative) sets it relative to today. + min: -15, + // `true` sets it to today. `false` removes any limits. + max: true +}); + +$('.datepicker').pickadate({ + disable: [ + [2013, 3, 3], + [2013, 3, 12], + [2013, 3, 20], + [2013, 3, 29] + ] +}); + +$('.datepicker').pickadate({ + disable: [ + 1, 4, 7 + ] +}); + +$('.datepicker').pickadate({ + disable: [ + true, + 1, 4, 7, + [2013, 3, 3], + [2013, 3, 12], + [2013, 3, 20], + [2013, 3, 29] + ] +}); + +$('.datepicker').pickadate({ + onStart: function () { + console.log('Hello there :)') + }, + onRender: function () { + console.log('Whoa.. rendered anew') + }, + onOpen: function () { + console.log('Opened up') + }, + onClose: function () { + console.log('Closed now') + }, + onStop: function () { + console.log('See ya.') + }, + onSet: function (event) { + console.log('Just set stuff:', event) + } +}); + +/* +* Time picker tests +* From http://amsul.ca/pickadate.js/time.htm +*/ + +$('.timepicker').pickatime(); + +$('.timepicker').pickatime({ + clear: '' +}); + +$('.timepicker').pickatime({ + // Escape any "rule" characters with an exclamation mark (!). + format: 'T!ime selected: h:i a', + formatLabel: 'h:i a', + formatSubmit: 'HH:i', + hiddenSuffix: '--submit' +}); + +$('.timepicker').pickatime({ + formatLabel: function (time: TimePickerItemObject) { + var hours = (time.pick - this.get('now').pick) / 60, + label = hours < 0 ? ' !hours to now' : hours > 0 ? ' !hours from now' : 'now' + return 'h:i a ' + (hours ? Math.abs(hours).toString() : '') + label + '' + } +}); + +$('.datepicker').pickadate({ + interval: 150 +}); + +$('.timepicker').pickatime({ + min: [7, 30], + max: [14, 0] +}); + +$('.timepicker').pickatime({ + // An integer (positive/negative) sets it as intervals relative from now. + min: -5, + // `true` sets it to now. `false` removes any limits. + max: true +}); + +$('.timepicker').pickatime({ + disable: [ + [0, 30], + [2, 0], + [8, 30], + [9, 0] + ] +}); + +$('.timepicker').pickatime({ + disable: [ + 3, 5, 7 + ] +}); + +$('.timepicker').pickatime({ + disable: [ + true, + 3, 5, 7, + [0, 30], + [2, 0], + [8, 30], + [9, 0] + ] +}); + +$('.timepicker').pickatime({ + onStart: function () { + console.log('Hello there :)') + }, + onRender: function () { + console.log('Whoa.. rendered anew') + }, + onOpen: function () { + console.log('Opened up') + }, + onClose: function () { + console.log('Closed now') + }, + onStop: function () { + console.log('See ya.') + }, + onSet: function (event) { + console.log('Just set stuff:', event) + } +}); + +/* +* API tests +* From http://amsul.ca/pickadate.js/api.htm +*/ + +var $input = $('.datepicker').pickadate(); + +// Use the picker object directly. +var picker = $input.pickadate('picker'); + +picker.open().clear().close(); + +picker.open(); +picker.close(); +picker.close(true); + +picker.open(false) +$(document).on('click', function () { + picker.close() +}); + +picker.start(); +picker.stop(); +picker.render(); +picker.clear(); + +picker.get() // Short for `picker.get('value')` + +picker.get('select'); +picker.get('select', 'yyyy/mm/dd'); + +picker.get('highlight'); +picker.get('highlight', 'yyyy/mm/dd'); + +picker.get('view'); + +picker.get('min'); +picker.get('min', 'yyyy/mm/dd'); +picker.get('max'); +picker.get('max', 'yyyy/mm/dd'); + +picker.get('open'); +picker.get('start'); +picker.get('id'); +picker.get('disable'); + +picker.set('clear'); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('select', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('select', new Date(2013,03,20)); + +// Using positive integers as UNIX timestamps. +picker.set('select', 1365961912346); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('select', [3, 0]); + +// Using positive integers as minutes. +picker.set('select', 540); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('highlight', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('highlight', new Date(2013,7,14)); + +// Using positive integers as UNIX timestamps. +picker.set('highlight', 1365961912346); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('highlight', [15, 30]); + +// Using positive integers as minutes. +picker.set('highlight', 1080); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('view', [2000, 3, 20]); + +// Using JavaScript Date objects. +picker.set('view', new Date(1988,7,14)); + +// Using positive integers as UNIX timestamps. +picker.set('view', 1587355200000); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('view', [15, 30]); + +// Using positive integers as minutes. +picker.set('view', 1080); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('min', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('min', new Date(2013,7,14)); + +// Using integers as days relative to today. +picker.set('min', -4); + +// Using `true` for "today". +picker.set('min', true); + +// Using `false` to remove. +picker.set('min', false); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('min', [15, 30]); + +// Using integers as intervals relative from now. +picker.set('min', -4); + +// Using `true` for "now". +picker.set('min', true); + +// Using `false` to remove. +picker.set('min', false); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('max', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('max', new Date(2013,7,14)); + +// Using integers as days relative to today. +picker.set('max', 4); + +// Using `true` for "today". +picker.set('max', true); + +// Using `false` to remove. +picker.set('max', false); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('max', [15, 30]); + +// Using integers as intervals relative from now. +picker.set('max', 4); + +// Using `true` for "now". +picker.set('max', true); + +// Using `false` to remove. +picker.set('max', false); + +picker.on('open', function () { + console.log('Opened.. and here I am!'); +}); + +picker.on({ + open: function () { + console.log('Opened.. and here I am!'); + }, + close: function () { + console.log('Closed.. and here I am!'); + } +}); + +$('.datepicker').pickadate({ + onOpen: function () { + console.log('Opened up!') + }, + onClose: function () { + console.log('Closed now') + }, + onRender: function () { + console.log('Just rendered anew') + }, + onStart: function () { + console.log('Hello there :)') + }, + onStop: function () { + console.log('See ya') + }, + onSet: function (event) { + console.log('Set stuff:', event) + } +}); + +picker.on('open', function () { + console.log('Didn\'t open.. yet here I am!'); +}) +picker.trigger('open'); + +picker.$node; +picker.$root; \ No newline at end of file diff --git a/jquery.pickadate/jquery.pickadate.d.ts b/jquery.pickadate/jquery.pickadate.d.ts new file mode 100644 index 000000000..d0825c770 --- /dev/null +++ b/jquery.pickadate/jquery.pickadate.d.ts @@ -0,0 +1,375 @@ +// Type definitions for pickadate.js 3.0.5 +// Project: https://github.com/amsul/pickadate.js +// Definitions by: Theodore Brown +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface pickadateOptions { + // Strings and translations + monthsFull?: string[]; // default 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' + monthsShort?: string[]; // default 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + weekdaysFull?: string[]; // default 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' + weekdaysShort?: string[]; // default 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' + showMonthsShort?: boolean; + showWeekdaysFull?: boolean; + + // Buttons + today?: string; // default 'Today' + clear?: string; // default 'Clear' + + // Formats + format?: string; // default 'd mmmm, yyyy' + formatSubmit?: string; // e.g. 'yyyy/mm/dd' + hiddenSuffix?: string; // default '_submit' + + // Dropdown selectors + selectYears?: any; // Specify the number of years selectable using an even integer - half before and half after the year in focus: + selectMonths?: boolean; + + // First day of the week + firstDay?: any; // The first day of the week can be set to either Sunday or Monday. Anything truth-y sets it as Monday and anything false-y as Sunday + + // Date limits + min?: any; // date object, array formatted as [YEAR,MONTH,DATE], or dates relative to today using integers or a boolean (`true` sets it to today. `false` removes any limits). + max?: any; + + // Disable dates + disable?: any[]; // arrays formatted as [YEAR,MONTH,DATE] or integers representing days of the week (from 1 to 7). Switch to whitelist by setting first item in collection to `true`. + + // Events + onStart?: (event: any) => void; + onRender?: (event: any) => void; + onOpen?: (event: any) => void; + onClose?: (event: any) => void; + onSet?: (event: any) => void; + onStop?: (event: any) => void; + + // Classes + klass?: { + + // The element states + input?: string; // default 'picker__input' + active?: string; // default 'picker__input--active' + + // The root picker and states + picker?: string; // default 'picker' + opened?: string; // default 'picker--opened' + focused?: string; // default 'picker--focused' + + // The picker holder + holder?: string; // default 'picker__holder' + + // The picker frame, wrapper, and box + frame?: string; // default 'picker__frame' + wrap?: string; // default 'picker__wrap' + box?: string; // default 'picker__box' + + // The picker header + header?: string; // default 'picker__header' + + // Month navigation + navPrev?: string; // default 'picker__nav--prev' + navNext?: string; // default 'picker__nav--next' + navDisabled?: string; // default 'picker__nav--disabled' + + // Month & year labels + month?: string; // default 'picker__month' + year?: string; // default 'picker__year' + + // Month & year dropdowns + selectMonth?: string; // default 'picker__select--month' + selectYear?: string; // default 'picker__select--year' + + // Table of dates + table?: string; // default 'picker__table' + + // Weekday labels + weekdays?: string; // default 'picker__weekday' + + // Day states + day?: string; // default 'picker__day' + disabled?: string; // default 'picker__day--disabled' + selected?: string // default 'picker__day--selected' + highlighted?: string // default 'picker__day--highlighted' + now?: string; // default 'picker__day--today' + infocus?: string; // default 'picker__day--infocus' + outfocus?: string; // default 'picker__day--outfocus' + + // The picker footer + footer?: string; // default 'picker__footer' + + // Today & clear buttons + buttonClear?: string; // default 'picker__button--clear' + buttonToday?: string; // default 'picker__button--today' + } +} + +interface pickatimeOptions { + // Translations and clear button + clear?: string; // default 'Clear' + + // Formats + format?: string; // default 'h:i A' + formatLabel?: any; + formatSubmit?: string; + hiddenSuffix?: string; // default '_submit' + + // Time intervals + interval?: number; // interval in minutes. default 30. + + // Time limits + min?: any; // array formatted as [HOUR,MINUTE], or as times relative to now using integers or a boolean (`true` sets it to now, `false` removes any limits). + max?: any; + + // Disable times + disable?: any[]; // arrays formatted as [HOUR,MINUTE] or integers representing hours (from 0 to 23). Switch to whitelist by setting true as the first item in the collection. + + // Events + onStart?: (event: any) => void; + onRender?: (event: any) => void; + onOpen?: (event: any) => void; + onClose?: (event: any) => void; + onSet?: (event: any) => void; + onStop?: (event: any) => void; + + // Classes + klass?: { + + // The element states + input?: string; // default 'picker__input' + active?: string; // default 'picker__input--active' + + // The root picker and states + picker?: string; // default 'picker picker--time' + opened?: string; // default 'picker--opened' + focused?: string; // default 'picker--focused' + + // The picker holder + holder?: string; // default 'picker__holder' + + // The picker frame, wrapper, and box + frame?: string; // default 'picker__frame' + wrap?: string; // default 'picker__wrap' + box?: string; // default 'picker__box' + + // List of times + list?: string; // default 'picker__list' + listItem?: string; // default 'picker__list-item' + + // Time states + disabled?: string; // default 'picker__list-item--disabled' + selected?: string; // default 'picker__list-item--selected' + highlighted?: string; // default 'picker__list-item--highlighted' + viewset?: string; // default 'picker__list-item--viewset' + now?: string; // default 'picker__list-item--now' + + // Clear button + buttonClear?: string; // default 'picker__button--clear' + } +} + +interface PickerItemObject { + /** The "pick" value used for comparisons. */ + pick: number; +} + +interface DatePickerItemObject extends PickerItemObject { + /** The full year. */ + year: number; + + /** The month with zero-as-index. */ + month: number; + + /** The date of the month. */ + date: number; + + /** The day of the week with zero-as-index. */ + day: number; + + /** The underlying JavaScript Date object. */ + obj: Date; +} + +interface TimePickerItemObject extends PickerItemObject { + /** Hour of the day from 0 to 23. */ + hour: number; + + /** The minutes of the hour from 0 to 59 (based on the interval). */ + mins: number; +} + +interface CallbackObject { + open?: () => void; + close?: () => void; + render?: () => void; + start?: () => void; + stop?: () => void; + set?: () => void; +} + +interface SetThings { + clear?; + select?: any; + highlight?: any; + view?: any; + min?: any; + max?: any; + disable?: any; + enable?: any; +} + +interface TimePickerSetThings extends SetThings { + interval?: any; +} + +interface PickerObject { + /** The picker's relative input element wrapped as a jQuery object. */ + $node: JQuery; + + /** The picker's relative root holder element wrapped as a jQuery object. */ + $root: JQuery; +} + +interface DatePickerObject extends PickerObject { + open(withoutFocus?: boolean): DatePickerObject; + close(withFocus?: boolean): DatePickerObject; + + /** Rebuild the picker. */ + start(): DatePickerObject; + + /** Destroy the picker. */ + stop(): DatePickerObject; + + /** Refresh the picker after adding something to the holder. */ + render(): DatePickerObject; + + /** Clear the value in the picker's input element. */ + clear(): DatePickerObject; + + /** Get the properties, objects, and states that make up the current state of the picker. */ + get(thing: string): any; + + /** Returns the string value of the picker's input element. */ + get(thing?: 'value'): string; + + /** Returns the item object that is visually selected. */ + get(thing: 'select'): DatePickerItemObject; + + /** Returns the item object that is visually highlighted. */ + get(thing: 'highlight'): DatePickerItemObject; + + /** Returns the item object that sets the current view. */ + get(thing: 'view'): DatePickerItemObject; + + /** Returns the item object that limits the picker's lower range. */ + get(thing: 'min'): DatePickerItemObject; + + /** Returns the item object that limits the picker's upper range. */ + get(thing: 'max'): DatePickerItemObject; + + /** Returns a boolean value of whether the picker is open or not. */ + get(thing: 'open'): boolean; + + /** Returns a boolean value of whether the picker has started or not. */ + get(thing: 'start'): boolean; + + /** Returns a unique 9-digit integer that is the ID of the picker. */ + get(thing: 'id'): number; + + /** Returns an array of items that determine which item objects to disable on the picker. */ + get(thing: 'disable'): any[]; + + /** Returns a formatted string for the item object specified by `thing` */ + get(thing: string, format: string): string; + + /** Set the properties, objects, and states to change the state of the picker. */ + set(thing: string, value?: any): DatePickerObject; + set(things: SetThings): DatePickerObject; + + /** Bind callbacks to get fired off when the relative picker method is called. */ + on(methodName, callback: () => void ): DatePickerObject; + + /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ + on(callbackObject: CallbackObject): DatePickerObject; + + /** Trigger callbacks that have been queued up using the the on method. */ + trigger(event: string): DatePickerObject; +} + +interface TimePickerObject extends PickerObject { + open(withoutFocus?: boolean): TimePickerObject; + close(withFocus?: boolean): TimePickerObject; + + /** Rebuild the picker. */ + start(): TimePickerObject; + + /** Destroy the picker. */ + stop(): TimePickerObject; + + /** Refresh the picker after adding something to the holder. */ + render(): TimePickerObject; + + /** Clear the value in the picker's input element. */ + clear(): TimePickerObject; + + /** Get the properties, objects, and states that make up the current state of the picker. */ + get(thing: string): any; + + /** Returns the string value of the picker's input element. */ + get(thing?: 'value'): string; + + /** Returns the item object that is visually selected. */ + get(thing: 'select'): TimePickerItemObject; + + /** Returns the item object that is visually highlighted. */ + get(thing: 'highlight'): TimePickerItemObject; + + /** Returns the item object that sets the current view. */ + get(thing: 'view'): TimePickerItemObject; + + /** Returns the item object that limits the picker's lower range. */ + get(thing: 'min'): TimePickerItemObject; + + /** Returns the item object that limits the picker's upper range. */ + get(thing: 'max'): TimePickerItemObject; + + /** Returns a boolean value of whether the picker is open or not. */ + get(thing: 'open'): boolean; + + /** Returns a boolean value of whether the picker has started or not. */ + get(thing: 'start'): boolean; + + /** Returns a unique 9-digit integer that is the ID of the picker. */ + get(thing: 'id'): number; + + /** Returns an array of items that determine which item objects to disable on the picker. */ + get(thing: 'disable'): any[]; + + /** Returns a formatted string for the item object specified by `thing` */ + get(thing: string, format: string): string; + + /** Set the properties, objects, and states to change the state of the picker. */ + set(thing: string, value?: any): TimePickerObject; + set(things: TimePickerSetThings): TimePickerObject; + + /** Bind callbacks to get fired off when the relative picker method is called. */ + on(methodName, callback: () => void ): TimePickerObject; + + /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ + on(callbackObject: CallbackObject): TimePickerObject; + + /** Trigger callbacks that have been queued up using the the on method. */ + trigger(event: string): TimePickerObject; +} + +interface JQuery { + pickadate(options?: pickadateOptions): HTMLInputElement; + pickatime(options?: pickatimeOptions): HTMLInputElement; +} + +interface HTMLInputElement { + pickadate(picker: string): DatePickerObject; + pickatime(picker: string): TimePickerObject; + +} \ No newline at end of file diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 1513959a8..c175d25f5 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -86,7 +86,7 @@ interface JQueryPromise { done(...doneCallbacks: any[]): JQueryDeferred; fail(...failCallbacks: any[]): JQueryDeferred; pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; - then(doneCallbacks: any, failCallbacks: any, progressCallbacks?: any): JQueryDeferred; + then(doneCallbacks: any, failCallbacks?: any, progressCallbacks?: any): JQueryDeferred; } /* diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index bb77d14f1..120945550 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -601,7 +601,7 @@ function test_accordion() { var heightStyle = $(".selector").accordion("option", "heightStyle"); $(".selector").accordion("option", "heightStyle", "fill"); $(".selector").accordion({ icons: { "header": "ui-icon-plus", "headerSelected": "ui-icon-minus" } }); - var icons = $(".selector").accordion("option", "icons"); + icons = $(".selector").accordion("option", "icons"); $(".selector").accordion("option", "icons", { "header": "ui-icon-plus", "headerSelected": "ui-icon-minus" }); var isDisabled = $(".selector").accordion("option", "disabled"); $(".selector").accordion("option", { disabled: true }); diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index e0ee81ded..ba6bf05fd 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -6,895 +6,897 @@ /// +declare module JQueryUI { + // Accordion ////////////////////////////////////////////////// + + interface AccordionOptions { + active?: any; // bool or number + animate?: any; // bool, number, string or object + collapsible?: bool; + disabled?: bool; + event?: string; + header?: string; + heightStyle?: string; + icons?: any; + } + + interface AccordionUIParams { + newHeader: JQuery; + oldHeader: JQuery; + newPanel: JQuery; + oldPanel: JQuery; + } + + interface AccordionEvent { + (event: Event, ui: AccordionUIParams): void; + } + + interface AccordionEvents { + activate?: AccordionEvent; + beforeActivate?: AccordionEvent; + create?: AccordionEvent; + } + + interface Accordion extends Widget, AccordionOptions, AccordionEvents { + } + + + // Autocomplete ////////////////////////////////////////////////// + + interface AutocompleteOptions { + appendTo?: any; //Selector; + autoFocus?: bool; + delay?: number; + disabled?: bool; + minLength?: number; + position?: string; + source?: any; // [], string or () + } + + interface AutocompleteUIParams { + + } + + interface AutocompleteEvent { + (event: Event, ui: AutocompleteUIParams): void; + } + + interface AutocompleteEvents { + change?: AutocompleteEvent; + close?: AutocompleteEvent; + create?: AutocompleteEvent; + focus?: AutocompleteEvent; + open?: AutocompleteEvent; + response?: AutocompleteEvent; + search?: AutocompleteEvent; + select?: AutocompleteEvent; + } + + interface Autocomplete extends Widget, AutocompleteOptions, AutocompleteEvents { + escapeRegex: (string) => string; + } + + + // Button ////////////////////////////////////////////////// + + interface ButtonOptions { + disabled?: bool; + icons?: any; + label?: string; + text?: bool; + } + + interface Button extends Widget, ButtonOptions { + } + + + // Datepicker ////////////////////////////////////////////////// + + interface DatepickerOptions { + altFieldType?: any; // Selecotr, jQuery or Element + altFormat?: string; + appendText?: string; + autoSize?: bool; + beforeShow?: (input: Element, inst: any) => void; + beforeShowDay?: (date: Date) => void; + buttonImage?: string; + buttonImageOnly?: bool; + buttonText?: string; + calculateWeek?: () => any; + changeMonth?: bool; + changeYear?: bool; + closeText?: string; + constrainInput?: bool; + currentText?: string; + dateFormat?: string; + dayNames?: string[]; + dayNamesMin?: string[]; + dayNamesShort?: string[]; + defaultDateType?: any; // Date, number or string + duration?: string; + firstDay?: number; + gotoCurrent?: bool; + hideIfNoPrevNext?: bool; + isRTL?: bool; + maxDate?: any; // Date, number or string + minDate?: any; // Date, number or string + monthNames?: string[]; + monthNamesShort?: string[]; + navigationAsDateFormat?: bool; + nextText?: string; + numberOfMonths?: any; // number or [] + onChangeMonthYear?: (year: number, month: number, inst: any) => void; + onClose?: (dateText: string, inst: any) => void; + onSelect?: (dateText: string, inst: any) => void; + prevText?: string; + selectOtherMonths?: bool; + shortYearCutoff?: any; // number or string + showAnim?: string; + showButtonPanel?: bool; + showCurrentAtPos?: number; + showMonthAfterYear?: bool; + showOn?: string; + showOptions?: any; // TODO + showOtherMonths?: bool; + showWeek?: bool; + stepMonths?: number; + weekHeader?: string; + yearRange?: string; + yearSuffix?: string; + } + + interface DatepickerFormatDateOptions { + dayNamesShort?: string[]; + dayNames?: string[]; + monthNamesShort?: string[]; + monthNames?: string[]; + } + + interface Datepicker extends Widget, DatepickerOptions { + regional: { [languageCod3: string]: any; }; + setDefaults(defaults: DatepickerOptions); + formatDate(format: string, date: Date, settings?: DatepickerFormatDateOptions): string; + parseDate(format: string, date: string, settings?: DatepickerFormatDateOptions): Date; + iso8601Week(date: Date): void; + noWeekends(): void; + } + + + // Dialog ////////////////////////////////////////////////// + + interface DialogOptions { + autoOpen?: bool; + buttons?: any; // object or [] + closeOnEscape?: bool; + closeText?: string; + dialogClass?: string; + disabled?: bool; + draggable?: bool; + height?: any; // number or string + maxHeight?: number; + maxWidth?: number; + minHeight?: number; + minWidth?: number; + modal?: bool; + position?: any; // object, string or [] + resizable?: bool; + show?: any; // number, string or object + stack?: bool; + title?: string; + width?: any; // number or string + zIndex?: number; + } + + interface DialogUIParams { + } + + interface DialogEvent { + (event: Event, ui: DialogUIParams): void; + } + + interface DialogEvents { + beforeClose?: DialogEvent; + close?: DialogEvent; + create?: DialogEvent; + drag?: DialogEvent; + dragStart?: DialogEvent; + dragStop?: DialogEvent; + focus?: DialogEvent; + open?: DialogEvent; + resize?: DialogEvent; + resizeStart?: DialogEvent; + resizeStop?: DialogEvent; + } + + interface Dialog extends Widget, DialogOptions, DialogEvents { + } + + + // Draggable ////////////////////////////////////////////////// + + interface DraggableEventUIParams { + helper: JQuery; + position: { top: number; left: number; }; + offset: { top: number; left: number; }; + } + + interface DraggableEvent { + (event: Event, ui: DraggableEventUIParams): void; + } + + interface DraggableOptions { + disabled?: bool; + addClasses?: bool; + appendTo?: any; + axis?: string; + cancel?: string; + connectToSortable?: string; + containment?: any; + cursor?: string; + cursorAt?: any; + delay?: number; + distance?: number; + grid?: number[]; + handle?: any; + helper?: any; + iframeFix?: any; + opacity?: number; + refreshPositions?: bool; + revert?: any; + revertDuration?: number; + scope?: string; + scroll?: bool; + scrollSensitivity?: number; + scrollSpeed?: number; + snap?: any; + snapMode?: string; + snapTolerance?: number; + stack?: string; + zIndex?: number; + } + + interface DraggableEvents { + create?: DraggableEvent; + start?: DraggableEvent; + drag?: DraggableEvent; + stop?: DraggableEvent; + } + + interface Draggable extends Widget, DraggableOptions, DraggableEvent { + } + + + // Droppable ////////////////////////////////////////////////// + + interface DroppableEventUIParam { + draggable: JQuery; + helper: JQuery; + position: { top: number; left: number; }; + offset: { top: number; left: number; }; + } + + interface DroppableEvent { + (event: Event, ui: DroppableEventUIParam): void; + } + + interface DroppableOptions { + disabled?: bool; + accept?: any; + activeClass?: string; + greedy?: bool; + hoverClass?: string; + scope?: string; + tolerance?: string; + } + + interface DroppableEvents { + create?: DroppableEvent; + activate?: DroppableEvent; + deactivate?: DroppableEvent; + over?: DroppableEvent; + out?: DroppableEvent; + drop?: DroppableEvent; + } + + interface Droppable extends Widget, DroppableOptions, DroppableEvents { + } + + // Menu ////////////////////////////////////////////////// + + interface MenuOptions { + disabled?: bool; + icons?: any; + menus?: string; + position?: any; // TODO + role?: string; + } + + interface MenuUIParams { + } + + interface MenuEvent { + (event: Event, ui: MenuUIParams): void; + } + + interface MenuEvents { + blur?: MenuEvent; + create?: MenuEvent; + focus?: MenuEvent; + select?: MenuEvent; + } + + interface Menu extends Widget, MenuOptions, MenuEvents { + } + + + // Progressbar ////////////////////////////////////////////////// + + interface ProgressbarOptions { + disabled?: bool; + value?: number; + } + + interface ProgressbarUIParams { + } + + interface ProgressbarEvent { + (event: Event, ui: ProgressbarUIParams): void; + } + + interface ProgressbarEvents { + change?: ProgressbarEvent; + complete?: ProgressbarEvent; + create?: ProgressbarEvent; + } + + interface Progressbar extends Widget, ProgressbarOptions, ProgressbarEvents { + } + + + // Resizable ////////////////////////////////////////////////// + + interface ResizableOptions { + alsoResize?: any; // Selector, JQuery or Element + animate?: bool; + animateDuration?: any; // number or string + animateEasing?: string; + aspectRatio?: any; // bool or number + autoHide?: bool; + cancel?: string; + containment?: any; // Selector, Element or string + delay?: number; + disabled?: bool; + distance?: number; + ghost?: bool; + grid?: any; + handles?: any; // string or object + helper?: string; + maxHeight?: number; + maxWidth?: number; + minHeight?: number; + minWidth?: number; + } + + interface ResizableUIParams { + element: JQuery; + helper: JQuery; + originalElement: JQuery; + originalPosition: any; + originalSize: any; + position: any; + size: any; + } + + interface ResizableEvent { + (event: Event, ui: ResizableUIParams): void; + } + + interface ResizableEvents { + resize?: ResizableEvent; + start?: ResizableEvent; + stop?: ResizableEvent; + } + + interface Resizable extends Widget, ResizableOptions, ResizableEvents { + } + + + // Selectable ////////////////////////////////////////////////// + + interface SelectableOptions { + autoRefresh?: bool; + cancel?: string; + delay?: number; + disabled?: bool; + distance?: number; + filter?: string; + tolerance?: string; + } + + interface SelectableEvents { + selected? (event: Event, ui: { selected?: Element; }): void; + selecting? (event: Event, ui: { selecting?: Element; }): void; + start? (event: Event, ui: any): void; + stop? (event: Event, ui: any): void; + unselected? (event: Event, ui: { unselected: Element; }): void; + unselecting? (event: Event, ui: { unselecting: Element; }): void; + } + + interface Selectable extends Widget, SelectableOptions, SelectableEvents { + } + + // Slider ////////////////////////////////////////////////// + + interface SliderOptions { + animate?: any; // bool, string or number + disabled?: bool; + max?: number; + min?: number; + orientation?: string; + range?: any; // bool or string + step?: number; + // value?: number; + // values?: number[]; + } + + interface SliderUIParams { + } + + interface SliderEvent { + (event: Event, ui: SliderUIParams): void; + } + + interface SliderEvents { + change?: SliderEvent; + create?: SliderEvent; + slide?: SliderEvent; + start?: SliderEvent; + stop?: SliderEvent; + } + + interface Slider extends Widget, SliderOptions, SliderEvents { + } + + + // Sortable ////////////////////////////////////////////////// + + interface SortableOptions { + appendTo?: any; // jQuery, Element, Selector or string + axis?: string; + cancel?: string; + connectWith?: string; + containment?: any; // Element, Selector or string + cursor?: string; + cursorAt?: any; + delay?: number; + disabled?: bool; + distance?: number; + dropOnEmpty?: bool; + forceHelperSize?: bool; + forcePlaceholderSize?: bool; + grid?: number[]; + handle?: any; // Selector or Element + items?: any; // Selector + opacity?: number; + placeholder?: string; + revert?: any; // bool or number + scroll?: bool; + scrollSensitivity?: number; + scrollSpeed?: number; + tolerance?: string; + zIndex?: number; + } + + interface SortableUIParams { + helper: JQuery; + item: JQuery; + offset: any; + position: any; + originalPosition: any; + sender: JQuery; + placeholder: JQuery; + } + + interface SortableEvent { + (event: Event, ui: SortableUIParams): void; + } + + interface SortableEvents { + activate?: SortableEvent; + beforeStop?: SortableEvent; + change?: SortableEvent; + deactivate?: SortableEvent; + out?: SortableEvent; + over?: SortableEvent; + receive?: SortableEvent; + remove?: SortableEvent; + sort?: SortableEvent; + start?: SortableEvent; + stop?: SortableEvent; + update?: SortableEvent; + } + + interface Sortable extends Widget, SortableOptions, SortableEvents { + } + + + // Spinner ////////////////////////////////////////////////// + + interface SpinnerOptions { + culture?: string; + disabled?: bool; + icons?: any; + incremental?: any; // bool or () + max?: any; // number or string + min?: any; // number or string + numberFormat?: string; + page?: number; + step?: any; // number or string + } + + interface SpinnerUIParams { + } + + interface SpinnerEvent { + (event: Event, ui: SpinnerUIParams): void; + } + + interface SpinnerEvents { + spin?: SpinnerEvent; + start?: SpinnerEvent; + stop?: SpinnerEvent; + } + + interface Spinner extends Widget, SpinnerOptions, SpinnerEvents { + } + + + // Tabs ////////////////////////////////////////////////// + + interface TabsOptions { + active?: any; // bool or number + collapsible?: bool; + disabled?: any; // bool or [] + event?: string; + heightStyle?: string; + hide?: any; // bool, number, string or object + show?: any; // bool, number, string or object + } + + interface TabsUIParams { + } + + interface TabsEvent { + (event: Event, ui: TabsUIParams): void; + } + + interface TabsEvents { + activate?: TabsEvent; + beforeActivate?: TabsEvent; + beforeLoad?: TabsEvent; + load?: TabsEvent; + } + + interface Tabs extends Widget, TabsOptions, TabsEvents { + } + + + // Tooltip ////////////////////////////////////////////////// + + interface TooltipOptions { + content?: any; // () or string + disabled?: bool; + hide?: any; // bool, number, string or object + items?: string; + position?: any; // TODO + show?: any; // bool, number, string or object + tooltipClass?: string; + track?: bool; + } + + interface TooltipUIParams { + } + + interface TooltipEvent { + (event: Event, ui: TooltipUIParams): void; + } + + interface TooltipEvents { + close?: TooltipEvent; + open?: TooltipEvent; + } + + interface Tooltip extends Widget, TooltipOptions, TooltipEvents { + } + + + // Effects ////////////////////////////////////////////////// + + interface EffectOptions { + effect: string; + easing?: string; + duration: any; + complete: Function; + } + + interface BlindEffect { + direction?: string; + } + + interface BounceEffect { + distance?: number; + times?: number; + } + + interface ClipEffect { + direction?: number; + } + + interface DropEffect { + direction?: number; + } + + interface ExplodeEffect { + pieces?: number; + } + + interface FadeEffect { } + + interface FoldEffect { + size?: any; + horizFirst?: bool; + } + + interface HighlightEffect { + color?: string; + } + + interface PuffEffect { + percent?: number; + } + + interface PulsateEffect { + times?: number; + } + + interface ScaleEffect { + direction?: string; + origin?: string[]; + percent?: number; + scale?: string; + } + + interface ShakeEffect { + direction?: string; + distance?: number; + times?: number; + } + + interface SizeEffect { + to?: any; + origin?: string[]; + scale?: string; + } + + interface SlideEffect { + direction?: string; + distance?: number; + } + + interface TransferEffect { + className?: string; + to?: string; + } + + interface JQueryPositionOptions { + my?: string; + at?: string; + of?: any; + collision?: string; + using?: Function; + within?: any; + } + + + // UI ////////////////////////////////////////////////// + + interface MouseOptions { + cancel?: string; + delay?: number; + distance?: number; + } + + interface keyCode { + BACKSPACE: number; + COMMA: number; + DELETE: number; + DOWN: number; + END: number; + ENTER: number; + ESCAPE: number; + HOME: number; + LEFT: number; + NUMPAD_ADD: number; + NUMPAD_DECIMAL: number; + NUMPAD_DIVIDE: number; + NUMPAD_ENTER: number; + NUMPAD_MULTIPLY: number; + NUMPAD_SUBTRACT: number; + PAGE_DOWN: number; + PAGE_UP: number; + PERIOD: number; + RIGHT: number; + SPACE: number; + TAB: number; + UP: number; + } + + interface UI { + mouse(method: string): JQuery; + mouse(options: MouseOptions): JQuery; + mouse(optionLiteral: string, optionName: string, optionValue: any): JQuery; + mouse(optionLiteral: string, optionValue: any): any; + + accordion: Accordion; + autocomplete: Autocomplete; + button: Button; + buttonset: Button; + datepicker: Datepicker; + dialog: Dialog; + keyCode: keyCode; + menu: Menu; + progressbar: Progressbar; + slider: Slider; + spinner: Spinner; + tabs: Tabs; + tooltip: Tooltip; + version: string; + } + + + // Widget ////////////////////////////////////////////////// + + interface WidgetOptions { + disabled?: bool; + hide?: any; + show?: any; + } + + interface Widget { + (methodName: string): JQuery; + (options: WidgetOptions): JQuery; + (options: AccordionOptions): JQuery; + (optionLiteral: string, optionName: string): any; + (optionLiteral: string, options: WidgetOptions): any; + (optionLiteral: string, optionName: string, optionValue: any): JQuery; + + (name: string, prototype: any): JQuery; + (name: string, base: Function, prototype: any): JQuery; + } + + //////////////////////////////////////////////////////////////////////////////////////////////////// -// Accordion ////////////////////////////////////////////////// - -interface AccordionOptions { - active?: any; // bool or number - animate?: any; // bool, number, string or object - collapsible?: bool; - disabled?: bool; - event?: string; - header?: string; - heightStyle?: string; - icons?: any; } -interface AccordionUIParams { - newHeader: JQuery; - oldHeader: JQuery; - newPanel: JQuery; - oldPanel: JQuery; -} - -interface AccordionEvent { - (event: Event, ui: AccordionUIParams): void; -} - -interface AccordionEvents { - activate?: AccordionEvent; - beforeActivate?: AccordionEvent; - create?: AccordionEvent; -} - -interface Accordion extends Widget, AccordionOptions, AccordionEvents { -} - - -// Autocomplete ////////////////////////////////////////////////// - -interface AutocompleteOptions { - appendTo?: any; //Selector; - autoFocus?: bool; - delay?: number; - disabled?: bool; - minLength?: number; - position?: string; - source?: any; // [], string or () -} - -interface AutocompleteUIParams { - -} - -interface AutocompleteEvent { - (event: Event, ui: AutocompleteUIParams): void; -} - -interface AutocompleteEvents { - change?: AutocompleteEvent; - close?: AutocompleteEvent; - create?: AutocompleteEvent; - focus?: AutocompleteEvent; - open?: AutocompleteEvent; - response?: AutocompleteEvent; - search?: AutocompleteEvent; - select?: AutocompleteEvent; -} - -interface Autocomplete extends Widget, AutocompleteOptions, AutocompleteEvents { - escapeRegex: (string) => string; -} - - -// Button ////////////////////////////////////////////////// - -interface ButtonOptions { - disabled?: bool; - icons?: any; - label?: string; - text?: bool; -} - -interface Button extends Widget, ButtonOptions { -} - - -// Datepicker ////////////////////////////////////////////////// - -interface DatepickerOptions { - altFieldType?: any; // Selecotr, jQuery or Element - altFormat?: string; - appendText?: string; - autoSize?: bool; - beforeShow?: (input: Element, inst: any) => void; - beforeShowDay?: (date: Date) => void; - buttonImage?: string; - buttonImageOnly?: bool; - buttonText?: string; - calculateWeek?: () => any; - changeMonth?: bool; - changeYear?: bool; - closeText?: string; - constrainInput?: bool; - currentText?: string; - dateFormat?: string; - dayNames?: string[]; - dayNamesMin?: string[]; - dayNamesShort?: string[]; - defaultDateType?: any; // Date, number or string - duration?: string; - firstDay?: number; - gotoCurrent?: bool; - hideIfNoPrevNext?: bool; - isRTL?: bool; - maxDate?: any; // Date, number or string - minDate?: any; // Date, number or string - monthNames?: string[]; - monthNamesShort?: string[]; - navigationAsDateFormat?: bool; - nextText?: string; - numberOfMonths?: any; // number or [] - onChangeMonthYear?: (year: number, month: number, inst: any) => void; - onClose?: (dateText: string, inst: any) => void; - onSelect?: (dateText: string, inst: any) => void; - prevText?: string; - selectOtherMonths?: bool; - shortYearCutoff?: any; // number or string - showAnim?: string; - showButtonPanel?: bool; - showCurrentAtPos?: number; - showMonthAfterYear?: bool; - showOn?: string; - showOptions?: any; // TODO - showOtherMonths?: bool; - showWeek?: bool; - stepMonths?: number; - weekHeader?: string; - yearRange?: string; - yearSuffix?: string; -} - -interface DatepickerFormatDateOptions { - dayNamesShort?: string[]; - dayNames?: string[]; - monthNamesShort?: string[]; - monthNames?: string[]; -} - -interface Datepicker extends Widget, DatepickerOptions { - regional: { [languageCod3: string]: any; }; - setDefaults(defaults: DatepickerOptions); - formatDate(format: string, date: Date, settings?: DatepickerFormatDateOptions): string; - parseDate(format: string, date: string, settings?: DatepickerFormatDateOptions): Date; - iso8601Week(date: Date): void; - noWeekends(): void; -} - - -// Dialog ////////////////////////////////////////////////// - -interface DialogOptions { - autoOpen?: bool; - buttons?: any; // object or [] - closeOnEscape?: bool; - closeText?: string; - dialogClass?: string; - disabled?: bool; - draggable?: bool; - height?: any; // number or string - maxHeight?: number; - maxWidth?: number; - minHeight?: number; - minWidth?: number; - modal?: bool; - position?: any; // object, string or [] - resizable?: bool; - show?: any; // number, string or object - stack?: bool; - title?: string; - width?: any; // number or string - zIndex?: number; -} - -interface DialogUIParams { -} - -interface DialogEvent { - (event: Event, ui: DialogUIParams): void; -} - -interface DialogEvents { - beforeClose?: DialogEvent; - close?: DialogEvent; - create?: DialogEvent; - drag?: DialogEvent; - dragStart?: DialogEvent; - dragStop?: DialogEvent; - focus?: DialogEvent; - open?: DialogEvent; - resize?: DialogEvent; - resizeStart?: DialogEvent; - resizeStop?: DialogEvent; -} - -interface Dialog extends Widget, DialogOptions, DialogEvents { -} - - -// Draggable ////////////////////////////////////////////////// - -interface DraggableEventUIParams { - helper: JQuery; - position: { top: number; left: number; }; - offset: { top: number; left: number; }; -} - -interface DraggableEvent { - (event: Event, ui: DraggableEventUIParams): void; -} - -interface DraggableOptions { - disabled?: bool; - addClasses?: bool; - appendTo?: any; - axis?: string; - cancel?: string; - connectToSortable?: string; - containment?: any; - cursor?: string; - cursorAt?: any; - delay?: number; - distance?: number; - grid?: number[]; - handle?: any; - helper?: any; - iframeFix?: any; - opacity?: number; - refreshPositions?: bool; - revert?: any; - revertDuration?: number; - scope?: string; - scroll?: bool; - scrollSensitivity?: number; - scrollSpeed?: number; - snap?: any; - snapMode?: string; - snapTolerance?: number; - stack?: string; - zIndex?: number; -} - -interface DraggableEvents { - create?: DraggableEvent; - start?: DraggableEvent; - drag?: DraggableEvent; - stop?: DraggableEvent; -} - -interface Draggable extends Widget, DraggableOptions, DraggableEvent { -} - - -// Droppable ////////////////////////////////////////////////// - -interface DroppableEventUIParam { - draggable: JQuery; - helper: JQuery; - position: { top: number; left: number; }; - offset: { top: number; left: number; }; -} - -interface DroppableEvent { - (event: Event, ui: DroppableEventUIParam): void; -} - -interface DroppableOptions { - disabled?: bool; - accept?: any; - activeClass?: string; - greedy?: bool; - hoverClass?: string; - scope?: string; - tolerance?: string; -} - -interface DroppableEvents { - create?: DroppableEvent; - activate?: DroppableEvent; - deactivate?: DroppableEvent; - over?: DroppableEvent; - out?: DroppableEvent; - drop?: DroppableEvent; -} - -interface Droppable extends Widget, DroppableOptions, DroppableEvents { -} - -// Menu ////////////////////////////////////////////////// - -interface MenuOptions { - disabled?: bool; - icons?: any; - menus?: string; - position?: any; // TODO - role?: string; -} - -interface MenuUIParams { -} - -interface MenuEvent { - (event: Event, ui: MenuUIParams): void; -} - -interface MenuEvents { - blur?: MenuEvent; - create?: MenuEvent; - focus?: MenuEvent; - select?: MenuEvent; -} - -interface Menu extends Widget, MenuOptions, MenuEvents { -} - - -// Progressbar ////////////////////////////////////////////////// - -interface ProgressbarOptions { - disabled?: bool; - value?: number; -} - -interface ProgressbarUIParams { -} - -interface ProgressbarEvent { - (event: Event, ui: ProgressbarUIParams): void; -} - -interface ProgressbarEvents { - change?: ProgressbarEvent; - complete?: ProgressbarEvent; - create?: ProgressbarEvent; -} - -interface Progressbar extends Widget, ProgressbarOptions, ProgressbarEvents { -} - - -// Resizable ////////////////////////////////////////////////// - -interface ResizableOptions { - alsoResize?: any; // Selector, JQuery or Element - animate?: bool; - animateDuration?: any; // number or string - animateEasing?: string; - aspectRatio?: any; // bool or number - autoHide?: bool; - cancel?: string; - containment?: any; // Selector, Element or string - delay?: number; - disabled?: bool; - distance?: number; - ghost?: bool; - grid?: any; - handles?: any; // string or object - helper?: string; - maxHeight?: number; - maxWidth?: number; - minHeight?: number; - minWidth?: number; -} - -interface ResizableUIParams { - element: JQuery; - helper: JQuery; - originalElement: JQuery; - originalPosition: any; - originalSize: any; - position: any; - size: any; -} - -interface ResizableEvent { - (event: Event, ui: ResizableUIParams): void; -} - -interface ResizableEvents { - resize?: ResizableEvent; - start?: ResizableEvent; - stop?: ResizableEvent; -} - -interface Resizable extends Widget, ResizableOptions, ResizableEvents { -} - - -// Selectable ////////////////////////////////////////////////// - -interface SelectableOptions { - autoRefresh?: bool; - cancel?: string; - delay?: number; - disabled?: bool; - distance?: number; - filter?: string; - tolerance?: string; -} - -interface SelectableEvents { - selected? (event: Event, ui: { selected?: Element; }): void; - selecting? (event: Event, ui: { selecting?: Element; }): void; - start? (event: Event, ui: any): void; - stop? (event: Event, ui: any): void; - unselected? (event: Event, ui: { unselected: Element; }): void; - unselecting? (event: Event, ui: { unselecting: Element; }): void; -} - -interface Selectable extends Widget, SelectableOptions, SelectableEvents { -} - -// Slider ////////////////////////////////////////////////// - -interface SliderOptions { - animate?: any; // bool, string or number - disabled?: bool; - max?: number; - min?: number; - orientation?: string; - range?: any; // bool or string - step?: number; - // value?: number; - // values?: number[]; -} - -interface SliderUIParams { -} - -interface SliderEvent { - (event: Event, ui: SliderUIParams): void; -} - -interface SliderEvents { - change?: SliderEvent; - create?: SliderEvent; - slide?: SliderEvent; - start?: SliderEvent; - stop?: SliderEvent; -} - -interface Slider extends Widget, SliderOptions, SliderEvents { -} - - -// Sortable ////////////////////////////////////////////////// - -interface SortableOptions { - appendTo?: any; // jQuery, Element, Selector or string - axis?: string; - cancel?: string; - connectWith?: string; - containment?: any; // Element, Selector or string - cursor?: string; - cursorAt?: any; - delay?: number; - disabled?: bool; - distance?: number; - dropOnEmpty?: bool; - forceHelperSize?: bool; - forcePlaceholderSize?: bool; - grid?: number[]; - handle?: any; // Selector or Element - items?: any; // Selector - opacity?: number; - placeholder?: string; - revert?: any; // bool or number - scroll?: bool; - scrollSensitivity?: number; - scrollSpeed?: number; - tolerance?: string; - zIndex?: number; -} - -interface SortableUIParams { - helper: JQuery; - item: JQuery; - offset: any; - position: any; - originalPosition: any; - sender: JQuery; - placeholder: JQuery; -} - -interface SortableEvent { - (event: Event, ui: SortableUIParams): void; -} - -interface SortableEvents { - activate?: SortableEvent; - beforeStop?: SortableEvent; - change?: SortableEvent; - deactivate?: SortableEvent; - out?: SortableEvent; - over?: SortableEvent; - receive?: SortableEvent; - remove?: SortableEvent; - sort?: SortableEvent; - start?: SortableEvent; - stop?: SortableEvent; - update?: SortableEvent; -} - -interface Sortable extends Widget, SortableOptions, SortableEvents { -} - - -// Spinner ////////////////////////////////////////////////// - -interface SpinnerOptions { - culture?: string; - disabled?: bool; - icons?: any; - incremental?: any; // bool or () - max?: any; // number or string - min?: any; // number or string - numberFormat?: string; - page?: number; - step?: any; // number or string -} - -interface SpinnerUIParams { -} - -interface SpinnerEvent { - (event: Event, ui: SpinnerUIParams): void; -} - -interface SpinnerEvents { - spin?: SpinnerEvent; - start?: SpinnerEvent; - stop?: SpinnerEvent; -} - -interface Spinner extends Widget, SpinnerOptions, SpinnerEvents { -} - - -// Tabs ////////////////////////////////////////////////// - -interface TabsOptions { - active?: any; // bool or number - collapsible?: bool; - disabled?: any; // bool or [] - event?: string; - heightStyle?: string; - hide?: any; // bool, number, string or object - show?: any; // bool, number, string or object -} - -interface TabsUIParams { -} - -interface TabsEvent { - (event: Event, ui: TabsUIParams): void; -} - -interface TabsEvents { - activate?: TabsEvent; - beforeActivate?: TabsEvent; - beforeLoad?: TabsEvent; - load?: TabsEvent; -} - -interface Tabs extends Widget, TabsOptions, TabsEvents { -} - - -// Tooltip ////////////////////////////////////////////////// - -interface TooltipOptions { - content?: any; // () or string - disabled?: bool; - hide?: any; // bool, number, string or object - items?: string; - position?: any; // TODO - show?: any; // bool, number, string or object - tooltipClass?: string; - track?: bool; -} - -interface TooltipUIParams { -} - -interface TooltipEvent { - (event: Event, ui: TooltipUIParams): void; -} - -interface TooltipEvents { - close?: TooltipEvent; - open?: TooltipEvent; -} - -interface Tooltip extends Widget, TooltipOptions, TooltipEvents { -} - - -// Effects ////////////////////////////////////////////////// - -interface EffectOptions { - effect: string; - easing?: string; - duration: any; - complete: Function; -} - -interface BlindEffect { - direction?: string; -} - -interface BounceEffect { - distance?: number; - times?: number; -} - -interface ClipEffect { - direction?: number; -} - -interface DropEffect { - direction?: number; -} - -interface ExplodeEffect { - pieces?: number; -} - -interface FadeEffect { } - -interface FoldEffect { - size?: any; - horizFirst?: bool; -} - -interface HighlightEffect { - color?: string; -} - -interface PuffEffect { - percent?: number; -} - -interface PulsateEffect { - times?: number; -} - -interface ScaleEffect { - direction?: string; - origin?: string[]; - percent?: number; - scale?: string; -} - -interface ShakeEffect { - direction?: string; - distance?: number; - times?: number; -} - -interface SizeEffect { - to?: any; - origin?: string[]; - scale?: string; -} - -interface SlideEffect { - direction?: string; - distance?: number; -} - -interface TransferEffect { - className?: string; - to?: string; -} - -interface JQueryPositionOptions { - my?: string; - at?: string; - of?: any; - collision?: string; - using?: Function; - within?: any; -} - - -// UI ////////////////////////////////////////////////// - -interface MouseOptions { - cancel?: string; - delay?: number; - distance?: number; -} - -interface keyCode { - BACKSPACE: number; - COMMA: number; - DELETE: number; - DOWN: number; - END: number; - ENTER: number; - ESCAPE: number; - HOME: number; - LEFT: number; - NUMPAD_ADD: number; - NUMPAD_DECIMAL: number; - NUMPAD_DIVIDE: number; - NUMPAD_ENTER: number; - NUMPAD_MULTIPLY: number; - NUMPAD_SUBTRACT: number; - PAGE_DOWN: number; - PAGE_UP: number; - PERIOD: number; - RIGHT: number; - SPACE: number; - TAB: number; - UP: number; -} - -interface UI { - mouse(method: string): JQuery; - mouse(options: MouseOptions): JQuery; - mouse(optionLiteral: string, optionName: string, optionValue: any): JQuery; - mouse(optionLiteral: string, optionValue: any): any; - - accordion: Accordion; - autocomplete: Autocomplete; - button: Button; - buttonset: Button; - datepicker: Datepicker; - dialog: Dialog; - keyCode: keyCode ; - menu: Menu; - progressbar: Progressbar; - slider: Slider; - spinner: Spinner; - tabs: Tabs; - tooltip: Tooltip; - version: string; -} - - -// Widget ////////////////////////////////////////////////// - -interface WidgetOptions { - disabled?: bool; - hide?: any; - show?: any; -} - -interface Widget { - (methodName: string): JQuery; - (options: WidgetOptions): JQuery; - (options: AccordionOptions): JQuery; - (optionLiteral: string, optionName: string): any; - (optionLiteral: string, options: WidgetOptions): any; - (optionLiteral: string, optionName: string, optionValue: any): JQuery; - - (name: string, prototype: any): JQuery; - (name: string, base: Function, prototype: any): JQuery; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - interface JQuery { accordion(): JQuery; accordion(methodName: string): JQuery; - accordion(options: AccordionOptions): JQuery; + accordion(options: JQueryUI.AccordionOptions): JQuery; accordion(optionLiteral: string, optionName: string): any; - accordion(optionLiteral: string, options: AccordionOptions): any; + accordion(optionLiteral: string, options: JQueryUI.AccordionOptions): any; accordion(optionLiteral: string, optionName: string, optionValue: any): JQuery; autocomplete(): JQuery; autocomplete(methodName: string): JQuery; - autocomplete(options: AutocompleteOptions): JQuery; + autocomplete(options: JQueryUI.AutocompleteOptions): JQuery; autocomplete(optionLiteral: string, optionName: string): any; - autocomplete(optionLiteral: string, options: AutocompleteOptions): any; + autocomplete(optionLiteral: string, options: JQueryUI.AutocompleteOptions): any; autocomplete(optionLiteral: string, optionName: string, optionValue: any): JQuery; button(): JQuery; button(methodName: string): JQuery; - button(options: ButtonOptions): JQuery; + button(options: JQueryUI.ButtonOptions): JQuery; button(optionLiteral: string, optionName: string): any; - button(optionLiteral: string, options: ButtonOptions): any; + button(optionLiteral: string, options: JQueryUI.ButtonOptions): any; button(optionLiteral: string, optionName: string, optionValue: any): JQuery; buttonset(): JQuery; buttonset(methodName: string): JQuery; - buttonset(options: ButtonOptions): JQuery; + buttonset(options: JQueryUI.ButtonOptions): JQuery; buttonset(optionLiteral: string, optionName: string): any; - buttonset(optionLiteral: string, options: ButtonOptions): any; + buttonset(optionLiteral: string, options: JQueryUI.ButtonOptions): any; buttonset(optionLiteral: string, optionName: string, optionValue: any): JQuery; datepicker(): JQuery; datepicker(methodName: string): JQuery; - datepicker(options: DatepickerOptions): JQuery; + datepicker(options: JQueryUI.DatepickerOptions): JQuery; datepicker(optionLiteral: string, optionName: string): any; - datepicker(optionLiteral: string, options: DatepickerOptions): any; + datepicker(optionLiteral: string, options: JQueryUI.DatepickerOptions): any; datepicker(optionLiteral: string, optionName: string, optionValue: any): JQuery; dialog(): JQuery; dialog(methodName: string): JQuery; - dialog(options: DialogOptions): JQuery; + dialog(options: JQueryUI.DialogOptions): JQuery; dialog(optionLiteral: string, optionName: string): any; - dialog(optionLiteral: string, options: DialogOptions): any; + dialog(optionLiteral: string, options: JQueryUI.DialogOptions): any; dialog(optionLiteral: string, optionName: string, optionValue: any): JQuery; draggable(): JQuery; draggable(methodName: string): JQuery; - draggable(options: DraggableOptions): JQuery; + draggable(options: JQueryUI.DraggableOptions): JQuery; draggable(optionLiteral: string, optionName: string): any; - draggable(optionLiteral: string, options: DraggableOptions): any; + draggable(optionLiteral: string, options: JQueryUI.DraggableOptions): any; draggable(optionLiteral: string, optionName: string, optionValue: any): JQuery; droppable(): JQuery; droppable(methodName: string): JQuery; - droppable(options: DroppableOptions): JQuery; + droppable(options: JQueryUI.DroppableOptions): JQuery; droppable(optionLiteral: string, optionName: string): any; - droppable(optionLiteral: string, options: DraggableOptions): any; + droppable(optionLiteral: string, options: JQueryUI.DraggableOptions): any; droppable(optionLiteral: string, optionName: string, optionValue: any): JQuery; menu(): JQuery; menu(methodName: string): JQuery; - menu(options: MenuOptions): JQuery; + menu(options: JQueryUI.MenuOptions): JQuery; menu(optionLiteral: string, optionName: string): any; - menu(optionLiteral: string, options: MenuOptions): any; + menu(optionLiteral: string, options: JQueryUI.MenuOptions): any; menu(optionLiteral: string, optionName: string, optionValue: any): JQuery; progressbar(): JQuery; progressbar(methodName: string): JQuery; - progressbar(options: ProgressbarOptions): JQuery; + progressbar(options: JQueryUI.ProgressbarOptions): JQuery; progressbar(optionLiteral: string, optionName: string): any; - progressbar(optionLiteral: string, options: ProgressbarOptions): any; + progressbar(optionLiteral: string, options: JQueryUI.ProgressbarOptions): any; progressbar(optionLiteral: string, optionName: string, optionValue: any): JQuery; resizable(): JQuery; resizable(methodName: string): JQuery; - resizable(options: ResizableOptions): JQuery; + resizable(options: JQueryUI.ResizableOptions): JQuery; resizable(optionLiteral: string, optionName: string): any; - resizable(optionLiteral: string, options: ResizableOptions): any; + resizable(optionLiteral: string, options: JQueryUI.ResizableOptions): any; resizable(optionLiteral: string, optionName: string, optionValue: any): JQuery; selectable(): JQuery; selectable(methodName: string): JQuery; - selectable(options: SelectableOptions): JQuery; + selectable(options: JQueryUI.SelectableOptions): JQuery; selectable(optionLiteral: string, optionName: string): any; - selectable(optionLiteral: string, options: SelectableOptions): any; + selectable(optionLiteral: string, options: JQueryUI.SelectableOptions): any; selectable(optionLiteral: string, optionName: string, optionValue: any): JQuery; slider(): JQuery; slider(methodName: string): JQuery; - slider(options: SliderOptions): JQuery; + slider(options: JQueryUI.SliderOptions): JQuery; slider(optionLiteral: string, optionName: string): any; - slider(optionLiteral: string, options: SliderOptions): any; + slider(optionLiteral: string, options: JQueryUI.SliderOptions): any; slider(optionLiteral: string, optionName: string, optionValue: any): JQuery; sortable(): JQuery; sortable(methodName: string): JQuery; - sortable(options: SortableOptions): JQuery; + sortable(options: JQueryUI.SortableOptions): JQuery; sortable(optionLiteral: string, optionName: string): any; - sortable(optionLiteral: string, options: SortableOptions): any; + sortable(optionLiteral: string, options: JQueryUI.SortableOptions): any; sortable(optionLiteral: string, optionName: string, optionValue: any): JQuery; spinner(): JQuery; spinner(methodName: string): JQuery; - spinner(options: SpinnerOptions): JQuery; + spinner(options: JQueryUI.SpinnerOptions): JQuery; spinner(optionLiteral: string, optionName: string): any; - spinner(optionLiteral: string, options: SpinnerOptions): any; + spinner(optionLiteral: string, options: JQueryUI.SpinnerOptions): any; spinner(optionLiteral: string, optionName: string, optionValue: any): JQuery; tabs(): JQuery; tabs(methodName: string): JQuery; - tabs(options: TabsOptions): JQuery; + tabs(options: JQueryUI.TabsOptions): JQuery; tabs(optionLiteral: string, optionName: string): any; - tabs(optionLiteral: string, options: TabsOptions): any; + tabs(optionLiteral: string, options: JQueryUI.TabsOptions): any; tabs(optionLiteral: string, optionName: string, optionValue: any): JQuery; tooltip(): JQuery; tooltip(methodName: string): JQuery; - tooltip(options: TooltipOptions): JQuery; + tooltip(options: JQueryUI.TooltipOptions): JQuery; tooltip(optionLiteral: string, optionName: string): any; - tooltip(optionLiteral: string, options: TooltipOptions): any; + tooltip(optionLiteral: string, options: JQueryUI.TooltipOptions): any; tooltip(optionLiteral: string, optionName: string, optionValue: any): JQuery; @@ -932,7 +934,7 @@ interface JQuery { toggle(effect: string, options?: any, duration?: number, complete?: Function): JQuery; toggle(effect: string, options?: any, duration?: string, complete?: Function): JQuery; - position(options: JQueryPositionOptions): JQuery; + position(options: JQueryUI.JQueryPositionOptions): JQuery; enableSelection(): JQuery; disableSelection(): JQuery; @@ -943,14 +945,14 @@ interface JQuery { zIndex(): JQuery; zIndex(zIndex: number): JQuery; - widget: Widget; + widget: JQueryUI.Widget; jQuery: JQueryStatic; } interface JQueryStatic { - ui: UI; - datepicker: Datepicker; - widget: Widget; - Widget: Widget; + ui: JQueryUI.UI; + datepicker: JQueryUI.Datepicker; + widget: JQueryUI.Widget; + Widget: JQueryUI.Widget; } \ No newline at end of file diff --git a/js-fixtures/fixtures.d.ts b/js-fixtures/fixtures.d.ts index 912bc693c..92bd548e0 100644 --- a/js-fixtures/fixtures.d.ts +++ b/js-fixtures/fixtures.d.ts @@ -3,7 +3,7 @@ // Definitions by: Kazi Manzur Rashid // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped -declare interface Fixtures { +interface Fixtures { path: string; containerId: string; body(): string; diff --git a/jstorage/jstorage-tests.ts b/jstorage/jstorage-tests.ts new file mode 100644 index 000000000..a8bd01af4 --- /dev/null +++ b/jstorage/jstorage-tests.ts @@ -0,0 +1,74 @@ +/// + +// Test set first overload +var storedValue = $.jStorage.set("testObj", { foo: 'bar' }); +console.assert(storedValue.foo === "bar"); + +// Test set second overload +$.jStorage.set("testNum", 42, { TTL: 65535 }); +var readValue = $.jStorage.get("testNum"); +console.assert(readValue + 5 === 47); + +// Test deleteKey +if ($.jStorage.deleteKey("testObj") === true) { + console.log('deleted'); +} + +// Test setTTL/getTTL +$.jStorage.setTTL("testNum", 100); +console.assert($.jStorage.getTTL("testNum") === 100); + +// Test flush +console.assert($.jStorage.flush() === true); + +// Test storageObj +var storeObj = $.jStorage.storageObj(); +console.assert(storeObj["testNum"] !== null); + +// Test index +var keys = $.jStorage.index(); +console.assert(keys.length > 0); + +// Test storageSize +var size = $.jStorage.storageSize(); +console.assert(size > 0); + +// Test currentBackend +var currentBackend = $.jStorage.currentBackend(); +console.assert(currentBackend != null && typeof currentBackend.getItem !== "undefined"); + +// Test storageAvailable +var isStorageAvailable = $.jStorage.storageAvailable(); +console.assert(isStorageAvailable === true); + +// Test listenKeyChange +$.jStorage.listenKeyChange("testNum", (key, value) => { + console.assert(key.length > 0); + console.assert(value != null); +} ); + +$.jStorage.listenKeyChange("testNum", (key, value) => { + console.assert(key === "testNum"); + console.assert(value + 10 > 0); +} ); + +// Test stopListening +$.jStorage.stopListening("testNum"); +$.jStorage.stopListening("testNum", () => { console.assert(); } ); + +// Test subscribe +$.jStorage.subscribe("ESPN", (channel, value) => { + console.assert(channel !== "ABC"); + console.assert(value !== null); +} ); + +$.jStorage.subscribe("ESPN", (channel, value) => { + console.assert(channel === "ESPN"); + console.assert(value.getDate() > Date.now()); +} ); + +// Test publish +$.jStorage.publish("ESPN", { date: new Date(2013, 4, 26, 7), game: "Miami Heat" }); + +// Test reinit +$.jStorage.reInit(); \ No newline at end of file diff --git a/jstorage/jstorage.d.ts b/jstorage/jstorage.d.ts new file mode 100644 index 000000000..0acc93fbd --- /dev/null +++ b/jstorage/jstorage.d.ts @@ -0,0 +1,159 @@ +// Type definitions for jStorage 0.3.0 +// Project: http://www.jstorage.info/ +// Definitions by: Danil Flores +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module $.jStorage { + + class IStorageOptions { + TTL: number; + } + + interface IJStorage { + [key: string]: any; + } + + /** + * Sets a key's value. + * + * @param key Key to set. If this value is not set or not + * a string an exception is raised. + * @param value Value to set. This can be any value that is JSON + * compatible (Numbers, Strings, Objects etc.). + * @param [options] - possible options to use + * @param [options.TTL] - optional TTL value + * @return the used value + */ + function set (key: string, value: TValue, options?: IStorageOptions): TValue; + + /** + * Looks up a key in cache + * + * @param key - Key to look up. + * @param defaultIfNotFound - Default value to return, if key didn't exist. + * @return the key value, default value or null + */ + function get (key: string, defaultIfNotFound?: TValue): TValue; + + /** + * Deletes a key from cache. + * + * @param key - Key to delete. + * @return true if key existed or false if it didn't + */ + function deleteKey(key: string): boolean; + + /** + * Sets a TTL for a key, or remove it if ttl value is 0 or below + * + * @param key - key to set the TTL for + * @param ttl - TTL timeout in milliseconds + * @return true if key existed or false if it didn't + */ + function setTTL(key: string, ttl: number): boolean; + + /** + * Gets remaining TTL (in milliseconds) for a key or 0 when no TTL has been set + * + * @param key Key to check + * @return Remaining TTL in milliseconds + */ + function getTTL(key: string): number; + + /** + * Deletes everything in cache. + * + * @return Always true + */ + function flush(): boolean; + + /** + * Returns a read-only copy of _storage + * + * @return Read-only copy of _storage + */ + function storageObj(): IJStorage + + /** + * Returns an index of all used keys as an array + * ['key1', 'key2',..'keyN'] + * + * @return Used keys + */ + function index(): string[]; + + /** + * How much space in bytes does the storage take? + * + * @return Storage size in chars (not the same as in bytes, + * since some chars may take several bytes) + */ + function storageSize(): number; + + /** + * Which backend is currently in use? + * + * @return Backend name + */ + function currentBackend(): Storage; + + /** + * Test if storage is available + * + * @return True if storage can be used + */ + function storageAvailable(): boolean; + + /** + * Register change listeners + * + * @param key Key name + * @param callback Function to run when the key changes + */ + function listenKeyChange(key: string, callback: (key: string, value: any) => void ): void; + + /** + * Register change listeners + * + * @param key Key name + * @param callback Function to run when the key changes + */ + function listenKeyChange(key: string, callback: (key: string, value: TValue) => void ): void; + + /** + * Remove change listeners + * + * @param key Key name to unregister listeners against + * @param [callback] If set, unregister the callback, if not - unregister all + */ + function stopListening(key: string, callback?: Function): void; + + /** + * Subscribe to a Publish/Subscribe event stream + * + * @param channel Channel name + * @param callback Function to run when the something is published to the channel + */ + function subscribe(channel: string, callback: (channel: string, value: any) => void ): void; + + /** + * Subscribe to a Publish/Subscribe event stream + * + * @param channel Channel name + * @param callback Function to run when the something is published to the channel + */ + function subscribe(channel: string, callback: (channel: string, value: TValue) => void ): void; + + /** + * Publish data to an event stream + * + * @param channel Channel name + * @param payload Payload to deliver + */ + function publish(channel: string, payload: any): void; + + /** + * Reloads the data from browser storage + */ + function reInit(): void; +} \ No newline at end of file diff --git a/knockback/knockback.d.ts b/knockback/knockback.d.ts index 0bb9e4a9d..12592f46f 100644 --- a/knockback/knockback.d.ts +++ b/knockback/knockback.d.ts @@ -2,37 +2,37 @@ /// declare module Knockback { - export interface EventWatcherOptions { + interface EventWatcherOptions { emitter: (newEmitter) => void; update: (newValue) => void; event_selector: string; key?: string; } - export interface FactoryOptions { + interface FactoryOptions { factories: any; } - export interface StoreOptions { + interface StoreOptions { creator: any; path: string; store: Store; factory: Factory; } - export class Destroyable { + class Destroyable { destroy(); } - export class ViewModel extends Destroyable { + class ViewModel extends Destroyable { constructor (model?: Backbone.Model, options?: ViewModelOptions, viewModel?: ViewModel); shareOptions(): ViewModelOptions; extend(source: any); model(): Backbone.Model; } - export class EventWatcher extends Destroyable { - static useOptionsOrCreate(options, emitter: KnockoutObservableAny, obj: Backbone.Model, callback_options: any); + class EventWatcher extends Destroyable { + static useOptionsOrCreate(options, emitter: KnockoutObservable, obj: Backbone.Model, callback_options: any); emitter(): Backbone.Model; emitter(newEmitter: Backbone.Model); @@ -40,7 +40,7 @@ declare module Knockback { releaseCallbacks(obj: any); } - export class Factory { + class Factory { static useOptionsOrCreate(options: FactoryOptions, obj: any, owner_path: string); constructor (parent_factory: any); @@ -51,39 +51,39 @@ declare module Knockback { creatorForPath(obj: any, path: string); } - export class Store extends Destroyable { - static useOptionsOrCreate(options: StoreOptions, obj: any, observable: KnockoutObservableAny); + class Store extends Destroyable { + static useOptionsOrCreate(options: StoreOptions, obj: any, observable: KnockoutObservable); constructor (model:Backbone.Model, options: StoreOptions); clear(); - register(obj: Backbone.Model, observable: KnockoutObservableAny, options: StoreOptions); + register(obj: Backbone.Model, observable: KnockoutObservable, options: StoreOptions); findOrCreate(obj: Backbone.Model, options: StoreOptions); } - export class DefaultObservable extends Destroyable { - constructor (targetObservable: KnockoutObservableAny, defaultValue: any); + class DefaultObservable extends Destroyable { + constructor (targetObservable: KnockoutObservable, defaultValue: any); setToDefault(); } - export class FormattedObservable extends Destroyable { + class FormattedObservable extends Destroyable { constructor (format: string, args: any[]); - constructor (format: KnockoutObservableAny, args: any[]); + constructor (format: KnockoutObservable, args: any[]); } - export interface LocalizedObservable { + interface LocalizedObservable { constructor (value: any, options: any, vm: any); destroy(); resetToCurrent(); observedValue(value: any); } - export class TriggeredObservable extends Destroyable { + class TriggeredObservable extends Destroyable { constructor (emitter: Backbone.ModelBase, event: string); emitter(): Backbone.ModelBase; emitter(newEmitter: Backbone.ModelBase); } - export class Statistics { + class Statistics { constructor (); clear(); addModelEvent(event: string); @@ -94,14 +94,14 @@ declare module Knockback { registeredStatsString(success_message: string): string; } - export interface OptionsBase { + interface OptionsBase { path?: string; // the path to the value (used to create related observables from the factory). store?: Store; // a store used to cache and share view models. factory?: Factory; // a factory used to create view models. options?: any; // a set of options merge into these options using _.defaults. Useful for extending options when deriving classes rather than merging them by hand. } - export interface ViewModelOptions extends OptionsBase { + interface ViewModelOptions extends OptionsBase { internals?: string[]; // an array of atttributes that should be scoped with an underscore, eg. name -> _name requires?: string[]; // an array of atttributes that will have kb.Observables created even if they do not exist on the Backbone.Model. Useful for binding Views that require specific observables to exist keys?: string[]; // restricts the keys used on a model. Useful for reducing the number of kb.Observables created from a limited set of Backbone.Model attributes @@ -110,7 +110,7 @@ declare module Knockback { factories?: any; // a map of dot-deliminated paths; for example {'models.name': kb.ViewModel} to either constructors or create functions. Signature: {'some.path': function(object, options)} } - export interface CollectionOptions extends OptionsBase { + interface CollectionOptions extends OptionsBase { models_only?: bool; // flag for skipping the creation of view models. The collection observable will be populated with (possibly sorted) models. view_model?: any; // (Constructor) — the view model constructor used for models in the collection. Signature: constructor(model, options) create?: any; // a function used to create a view model for models in the collection. Signature: create(model, options) @@ -120,7 +120,7 @@ declare module Knockback { filters?: any; // filters can be individual ids (observable or simple) or arrays of ids, functions, or arrays of functions. } - export interface CollectionObservable extends KnockoutObservableArray { + interface CollectionObservable extends KnockoutObservableArray { collection(colleciton: Backbone.Collection); collection(): Backbone.Collection; destroy(); @@ -134,7 +134,7 @@ declare module Knockback { hasViewModels(): bool; } - export interface Utils { + interface Utils { wrappedObservable(obj: any): any; wrappedObservable(obj: any, value: any); wrappedObject(obj: any): any; @@ -148,7 +148,7 @@ declare module Knockback { wrappedEventWatcher(obj: any): any; wrappedEventWatcher(obj: any, value: any); wrappedDestroy(obj: any); - valueType(observable: KnockoutObservableAny): any; + valueType(observable: KnockoutObservable): any; pathJoin(path1: string, path2: string): string; optionsPathJoin(options: any, path: string): any; inferCreator(value: any, factory: Factory, path: string, owner: any, key: string); @@ -157,7 +157,7 @@ declare module Knockback { hasCollectionSignature(obj: any): bool; } - export interface Static extends Utils { + interface Static extends Utils { collectionObservable(model?: Backbone.Collection, options?: CollectionOptions): CollectionObservable; /** Base class for observing model attributes. */ observable( @@ -166,19 +166,19 @@ declare module Knockback { /** the create options. String is a single attribute name, Array is an array of attribute names. */ options: IObservableOptions, /** the viewModel */ - vm?: ViewModel): KnockoutObservableAny; + vm?: ViewModel): KnockoutObservable; observable( /** the model to observe (can be null) */ model: Backbone.Model, /** the create options. String is a single attribute name, Array is an array of attribute names. */ options_attributeName: string, /** the viewModel */ - vm?: ViewModel): KnockoutObservableAny; - viewModel(model?: Backbone.Model, options?: any): KnockoutObservableAny; - defaultObservable(targetObservable: KnockoutObservableAny, defaultValue: any): KnockoutObservableAny; - formattedObservable(format: string, args: any[]): KnockoutObservableAny; - formattedObservable(format: KnockoutObservableAny, args: any[]): KnockoutObservableAny; - localizedObservable(data: any, options: any): KnockoutObservableAny; + vm?: ViewModel): KnockoutObservable; + viewModel(model?: Backbone.Model, options?: any): KnockoutObservable; + defaultObservable(targetObservable: KnockoutObservable, defaultValue: any): KnockoutObservable; + formattedObservable(format: string, args: any[]): KnockoutObservable; + formattedObservable(format: KnockoutObservable, args: any[]): KnockoutObservable; + localizedObservable(data: any, options: any): KnockoutObservable; release(object: any, pre_release?: () => void ); releaseKeys(object: any); releaseOnNodeRemove(viewmodel: ViewModel, node: Element); @@ -204,7 +204,7 @@ declare module Knockback { key: string; read?: () => any; write?: (value: any) => void; - args?: KnockoutObservableAny[]; + args?: KnockoutObservable[]; localizer?: LocalizedObservable; default?: any; path?: string; @@ -213,6 +213,6 @@ declare module Knockback { options?: any; } -}; +} declare var kb: Knockback.Static; \ No newline at end of file diff --git a/knockout.mapping/knockout.mapping.d.ts b/knockout.mapping/knockout.mapping.d.ts index 69b6ccaff..010f18801 100644 --- a/knockout.mapping/knockout.mapping.d.ts +++ b/knockout.mapping/knockout.mapping.d.ts @@ -13,7 +13,7 @@ interface KnockoutMappingCreateOptions { interface KnockoutMappingUpdateOptions { data: any; parent: any; - observable: KnockoutObservableAny; + observable: KnockoutObservable; } interface KnockoutMappingOptions { diff --git a/knockout.postbox/knockout-postbox.d.ts b/knockout.postbox/knockout-postbox.d.ts index 0910ab5f5..3e6698851 100644 --- a/knockout.postbox/knockout-postbox.d.ts +++ b/knockout.postbox/knockout-postbox.d.ts @@ -1,53 +1,22 @@ // Type definitions for knockout-postbox // Project: https://github.com/rniemeyer/knockout-postbox -// Definitions by: Judah Gabriel +// Definitions by: Judah Gabriel Himango // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// interface KnockoutPostBox { - subscribe: (topic: string, handler: (value) => void, target?: any) => KnockoutObservableAny; - publish: (topic: string, value?: any) => KnockoutObservableAny; - defaultComparer: (newValue: any, oldValue: any) => bool; + subscribe(topic: string, handler: (value: T) => void , target?: any): KnockoutSubscription; + publish(topic: string, value?: T): void; + defaultComparer(newValue: T, oldValue: T): boolean; } -interface KnockoutObservableString { - subscribeTo: (topic: string, useLastPublishedValueToInitialize?: bool, transform?: (val: any) => string) => KnockoutObservableString; - unsubscribeFrom: (topic: string) => KnockoutObservableString; - publishOn: (topic: string, skipInitialPublish?: bool, equalityComparer?: (newValue: string, oldValue: string) => bool) => KnockoutObservableString; - stopPublishingOn: (topic: string) => KnockoutObservableString; - syncWith: (topic: string, initializeWithLatestValue?: bool, skipInitialPublish?: bool, equalityComparer?: (newValue: string, oldValue: string) => bool) => KnockoutObservableString; -} - -interface KnockoutObservableDate { - subscribeTo: (topic: string, useLastPublishedValueToInitialize?: bool, transform?: (val: any) => Date) => KnockoutObservableDate; - unsubscribeFrom: (topic: string) => KnockoutObservableDate; - publishOn: (topic: string, skipInitialPublish?: bool, equalityComparer?: (newValue: Date, oldValue: Date) => bool) => KnockoutObservableDate; - stopPublishingOn: (topic: string) => KnockoutObservableDate; - syncWith: (topic: string, initializeWithLatestValue?: bool, skipInitialPublish?: bool, equalityComparer?: (newValue: Date, oldValue: Date) => bool) => KnockoutObservableDate; -} - -interface KnockoutObservableNumber { - subscribeTo: (topic: string, useLastPublishedValueToInitialize?: bool, transform?: (val: any) => number) => KnockoutObservableNumber; - unsubscribeFrom: (topic: string) => KnockoutObservableNumber; - publishOn: (topic: string, skipInitialPublish?: bool, equalityComparer?: (newValue: Number, oldValue: Number) => bool) => KnockoutObservableNumber; - stopPublishingOn: (topic: string) => KnockoutObservableNumber; - syncWith: (topic: string, initializeWithLatestValue?: bool, skipInitialPublish?: bool, equalityComparer?: (newValue: Number, oldValue: Number) => bool) => KnockoutObservableNumber; -} - -interface KnockoutObservableBool { - subscribeTo: (topic: string, useLastPublishedValueToInitialize?: bool, transform?: (val: any) => bool) => KnockoutObservableBool; - unsubscribeFrom: (topic: string) => KnockoutObservableBool; - publishOn: (topic: string, skipInitialPublish?: bool, equalityComparer?: (newValue: bool, oldValue: bool) => bool) => KnockoutObservableBool; - stopPublishingOn: (topic: string) => KnockoutObservableBool; - syncWith: (topic: string, initializeWithLatestValue?: bool, skipInitialPublish?: bool, equalityComparer?: (newValue: bool, oldValue: bool) => bool) => KnockoutObservableBool; -} - -interface KnockoutObservableAny { - subscribeTo: (topic: string, useLastPublishedValueToInitialize?: bool, transform?: (val: any) => any) => KnockoutObservableAny; - unsubscribeFrom: (topic: string) => KnockoutObservableAny; - publishOn: (topic: string, skipInitialPublish?: bool, equalityComparer?: (newValue: any, oldValue: any) => bool) => KnockoutObservableAny; - stopPublishingOn: (topic: string) => KnockoutObservableAny; - syncWith: (topic: string, initializeWithLatestValue?: bool, skipInitialPublish?: bool, equalityComparer?: (newValue: any, oldValue: any) => bool) => KnockoutObservableAny; +interface KnockoutObservable { + subscribeTo(topic: string, useLastPublishedValueToInitialize?: boolean, transform?: (val: any) => T): KnockoutObservable; + unsubscribeFrom(topic: string): KnockoutObservable; + publishOn(topic: string, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservable; + stopPublishingOn(topic: string): KnockoutObservable; + syncWith(topic: string, initializeWithLatestValue?: boolean, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservable; } interface KnockoutStatic { diff --git a/knockout.validation/knockout.validation.d.ts b/knockout.validation/knockout.validation.d.ts index 88c1cc59d..725902e60 100644 --- a/knockout.validation/knockout.validation.d.ts +++ b/knockout.validation/knockout.validation.d.ts @@ -1,145 +1,146 @@ -// Type definitions for Knockout Validation -// Project: https://github.com/ericmbarnard/Knockout-Validation -// Definitions by: Dan Ludwig -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -interface KnockoutValidationGroupingOptions { - deep?: bool; - observable?: bool; -} - -interface KnockoutValidationConfiguration { - registerExtenders?: bool; - messagesOnModified?: bool; - messageTemplate?: string; - insertMessages?: bool; - parseInputAttributes?: bool; - writeInputAttributes?: bool; - decorateElement?: bool; - errorClass?: string; - errorElementClass?: string; - errorMessageClass?: string; - grouping?: KnockoutValidationGroupingOptions; -} - -interface KnockoutValidationUtils { - isArray(o: any): bool; - isObject(o: any): bool; - values(o: any): any[]; - getValue(o: any): any; - hasAttribute(node: Element, attr: string): bool; - isValidatable(o: any): bool; - insertAfter(node: Element, newNode: Element): void; - newId(): number; - getConfigOptions(element: Element): KnockoutValidationConfiguration; - setDomData(node: Element, data: KnockoutValidationConfiguration): void; - getDomData(node: Element): KnockoutValidationConfiguration; - contextFor(node: Element): KnockoutValidationConfiguration; - isEmptyVal(val: any): bool; -} - -interface KnockoutValidationAsyncCallbackArgs { - isValid: bool; - message: string; -} - -interface KnockoutValidationAsyncCallback { - (result: bool): void; - (result: KnockoutValidationAsyncCallbackArgs): void; -} - -interface KnockoutValidationRuleDefinition { - message: string; - validator(value: any, params: any): bool; -} - -interface KnockoutValidationAsyncRuleDefinition extends KnockoutValidationRuleDefinition { - async: bool; - validator(value: any, params: any, callback: KnockoutValidationAsyncCallback): void; -} - -interface KnockoutValidationAnonymousRuleDefinition { - validation: KnockoutValidationRuleDefinition; -} - -interface KnockoutValidationRuleDefinitions { - date: KnockoutValidationRuleDefinition; - dateISO: KnockoutValidationRuleDefinition; - digit: KnockoutValidationRuleDefinition; - email: KnockoutValidationRuleDefinition; - equal: KnockoutValidationRuleDefinition; - max: KnockoutValidationRuleDefinition; - maxLength: KnockoutValidationRuleDefinition; - min: KnockoutValidationRuleDefinition; - minLength: KnockoutValidationRuleDefinition; - notEqual: KnockoutValidationRuleDefinition; - number: KnockoutValidationRuleDefinition; - pattern: KnockoutValidationRuleDefinition; - phoneUS: KnockoutValidationRuleDefinition; - required: KnockoutValidationRuleDefinition; - step: KnockoutValidationRuleDefinition; - unique: KnockoutValidationRuleDefinition; -} - -interface KnockoutValidationRule { - rule: string; - params: any; - message?: string; - condition?: () => bool; -} - -interface KnockoutValidationErrors { - (): string[]; - showAllMessages(): void; - showAllMessages(show: bool): void; -} - -interface KnockoutValidationGroup { - errors?: KnockoutValidationErrors; - isValid?: () => bool; - isAnyMessageShown?: () => bool; -} - -interface KnockoutValidationStatic { - init(options?: KnockoutValidationConfiguration, force?: bool): void; - configure(options: KnockoutValidationConfiguration): void; - reset(): void; - - group(obj: any, options?: any): KnockoutValidationErrors; - - formatMessage(message: string, params: string): string; - - addRule(observable: KnockoutObservableAny, rule: KnockoutValidationRule): KnockoutObservableAny; - addRule(observable: KnockoutObservableString, rule: KnockoutValidationRule): KnockoutObservableString; - addRule(observable: KnockoutObservableNumber, rule: KnockoutValidationRule): KnockoutObservableNumber; - addRule(observable: KnockoutObservableBool, rule: KnockoutValidationRule): KnockoutObservableBool; - addRule(observable: KnockoutObservableDate, rule: KnockoutValidationRule): KnockoutObservableDate; - addAnonymousRule(observable: KnockoutObservableBase, ruleObj: KnockoutValidationAnonymousRuleDefinition): void; - - insertValidationMessage(element: Element): Element; - parseInputValidationAttributes(element: Element, valueAccessor: () => KnockoutObservableBase): void; - - rules: KnockoutValidationRuleDefinitions; - - addExtender(ruleName: string): void; - registerExtenders(): void; - utils: KnockoutValidationUtils; - - localize(msgTranslations: any): void; - validateObservable(observable: KnockoutObservableBase): bool; -} - -interface KnockoutStatic { - validation: KnockoutValidationStatic; - validatedObservable(initialValue: any): KnockoutObservableBase; - applyBindingsWithValidation(viewModel: any, rootNode?: any, options?: KnockoutValidationConfiguration): void; -} - -interface KnockoutSubscribableFunctions { - isValid: KnockoutComputed; - isValidating: KnockoutObservableBool; - rules: KnockoutObservableArray; -} - +// Type definitions for Knockout Validation +// Project: https://github.com/ericmbarnard/Knockout-Validation +// Definitions by: Dan Ludwig +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface KnockoutValidationGroupingOptions { + deep?: boolean; + observable?: boolean; +} + +interface KnockoutValidationConfiguration { + registerExtenders?: boolean; + messagesOnModified?: boolean; + messageTemplate?: string; + insertMessages?: boolean; + parseInputAttributes?: boolean; + writeInputAttributes?: boolean; + decorateElement?: boolean; + errorClass?: string; + errorElementClass?: string; + errorMessageClass?: string; + grouping?: KnockoutValidationGroupingOptions; +} + +interface KnockoutValidationUtils { + isArray(o: any): boolean; + isObject(o: any): boolean; + values(o: any): any[]; + getValue(o: any): any; + hasAttribute(node: Element, attr: string): boolean; + isValidatable(o: any): boolean; + insertAfter(node: Element, newNode: Element): void; + newId(): number; + getConfigOptions(element: Element): KnockoutValidationConfiguration; + setDomData(node: Element, data: KnockoutValidationConfiguration): void; + getDomData(node: Element): KnockoutValidationConfiguration; + contextFor(node: Element): KnockoutValidationConfiguration; + isEmptyVal(val: any): boolean; +} + +interface KnockoutValidationAsyncCallbackArgs { + isValid: boolean; + message: string; +} + +interface KnockoutValidationAsyncCallback { + (result: boolean): void; + (result: KnockoutValidationAsyncCallbackArgs): void; +} + +interface KnockoutValidationRuleBase +{ + message: string; +} + +interface KnockoutValidationRuleDefinition extends KnockoutValidationRuleBase { + validator(value: any, params: any): boolean; +} + +interface KnockoutValidationAsyncRuleDefinition extends KnockoutValidationRuleBase { + async: boolean; + validator(value: any, params: any, callback: KnockoutValidationAsyncCallback): void; +} + +interface KnockoutValidationAnonymousRuleDefinition { + validation: KnockoutValidationRuleDefinition; +} + +interface KnockoutValidationRuleDefinitions { + date: KnockoutValidationRuleDefinition; + dateISO: KnockoutValidationRuleDefinition; + digit: KnockoutValidationRuleDefinition; + email: KnockoutValidationRuleDefinition; + equal: KnockoutValidationRuleDefinition; + max: KnockoutValidationRuleDefinition; + maxLength: KnockoutValidationRuleDefinition; + min: KnockoutValidationRuleDefinition; + minLength: KnockoutValidationRuleDefinition; + notEqual: KnockoutValidationRuleDefinition; + number: KnockoutValidationRuleDefinition; + pattern: KnockoutValidationRuleDefinition; + phoneUS: KnockoutValidationRuleDefinition; + required: KnockoutValidationRuleDefinition; + step: KnockoutValidationRuleDefinition; + unique: KnockoutValidationRuleDefinition; +} + +interface KnockoutValidationRule { + rule: string; + params: any; + message?: string; + condition?: () => boolean; +} + +interface KnockoutValidationErrors { + (): string[]; + showAllMessages(): void; + showAllMessages(show: boolean): void; +} + +interface KnockoutValidationGroup { + errors?: KnockoutValidationErrors; + isValid?: () => boolean; + isAnyMessageShown?: () => boolean; +} + +interface KnockoutValidationStatic { + init(options?: KnockoutValidationConfiguration, force?: boolean): void; + configure(options: KnockoutValidationConfiguration): void; + reset(): void; + + group(obj: any, options?: any): KnockoutValidationErrors; + + formatMessage(message: string, params: string): string; + + addRule(observable: KnockoutObservable, rule: KnockoutValidationRule): KnockoutObservable; + + addAnonymousRule(observable: KnockoutObservableBase, ruleObj: KnockoutValidationAnonymousRuleDefinition): void; + + insertValidationMessage(element: Element): Element; + parseInputValidationAttributes(element: Element, valueAccessor: () => KnockoutObservableBase): void; + + rules: KnockoutValidationRuleDefinitions; + + addExtender(ruleName: string): void; + registerExtenders(): void; + utils: KnockoutValidationUtils; + + localize(msgTranslations: any): void; + validateObservable(observable: KnockoutObservableBase): boolean; +} + +interface KnockoutStatic { + validation: KnockoutValidationStatic; + validatedObservable(initialValue: any): KnockoutObservableBase; + applyBindingsWithValidation(viewModel: any, rootNode?: any, options?: KnockoutValidationConfiguration): void; +} + +interface KnockoutSubscribableFunctions { + isValid: KnockoutComputed; + isValidating: KnockoutObservable; + rules: KnockoutObservableArray; +} + diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index ba9e74303..6016a6598 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -15,7 +15,7 @@ interface KnockoutSubscribableFunctions { interface KnockoutComputedFunctions extends KnockoutSubscribableFunctions { getDependenciesCount(): number; - hasWriteFunction(): bool; + hasWriteFunction(): boolean; } interface KnockoutObservableFunctions extends KnockoutSubscribableFunctions { @@ -62,7 +62,7 @@ interface KnockoutComputedStatic { fn: KnockoutComputedFunctions; (): KnockoutComputed; - (func: () => T, context?: any): KnockoutComputed; + (func: () => T, context?: any, options?: any): KnockoutComputed; (def: KnockoutComputedDefine): KnockoutComputed; (options?: any): KnockoutComputed; } @@ -72,15 +72,15 @@ interface KnockoutComputed extends KnockoutComputedFunctions { (value: T): void; subscribe(callback: (newValue: T) => void, target?:any, topic?: string): KnockoutSubscription; - notifySubscribers(valueToWrite: T, topic?: string); + notifySubscribers(valueToWrite: T, topic?: string); } interface KnockoutObservableArrayStatic { fn: KnockoutObservableArrayFunctions; - + (): KnockoutObservableArray; - (value: T[]): KnockoutObservableArray; + (value: T[]): KnockoutObservableArray; } interface KnockoutObservableArray extends KnockoutObservableArrayFunctions { @@ -94,17 +94,18 @@ interface KnockoutObservableArray extends KnockoutObservableArrayFunctions interface KnockoutObservableStatic { fn: KnockoutObservableFunctions; - (value: T): KnockoutObservable; + (value?: T): KnockoutObservable; + (): KnockoutObservable; } /** use as method to get/set the value */ interface KnockoutObservableBase extends KnockoutObservableFunctions { getSubscriptionsCount(): number; } - + interface KnockoutObservable extends KnockoutObservableBase { (): T; - (value: T): void; + (value: T): void; subscribe(callback: (newValue: T) => void, target?:any, topic?: string): KnockoutSubscription; notifySubscribers(valueToWrite: T, topic?: string); @@ -175,7 +176,7 @@ interface KnockoutMemoization { interface KnockoutVirtualElement {} interface KnockoutVirtualElements { - allowedBindings: { [bindingName: string]: bool; }; + allowedBindings: { [bindingName: string]: boolean; }; emptyNode( e: KnockoutVirtualElement ); firstChild( e: KnockoutVirtualElement ); insertAfter( container: KnockoutVirtualElement, nodeToInsert: HTMLElement, insertAfter: HTMLElement ); @@ -215,7 +216,7 @@ interface KnockoutUtils { set (node: Element, key: string, value: any); - getAll(node: Element, createIfNotFound: bool); + getAll(node: Element, createIfNotFound: boolean); clear(node: Element); }; @@ -244,7 +245,7 @@ interface KnockoutUtils { arrayIndexOf(array: any[], item: any): number; - arrayFirst(array: any[], predicate: (item) => bool, predicateOwner?: any): any; + arrayFirst(array: any[], predicate: (item) => boolean, predicateOwner?: any): any; arrayRemoveItem(array: any[], itemToRemove: any): void; @@ -252,7 +253,7 @@ interface KnockoutUtils { arrayMap(array: any[], mapping: (item) => any): any[]; - arrayFilter(array: any[], predicate: (item) => bool): any[]; + arrayFilter(array: any[], predicate: (item) => boolean): any[]; arrayPushAll(array: any[], valuesToPush: any[]): any[]; @@ -262,13 +263,13 @@ interface KnockoutUtils { moveCleanedNodesToContainerElement(nodes: any[]): HTMLElement; - cloneNodes(nodesArray: any[], shouldCleanNodes: bool): any[]; + cloneNodes(nodesArray: any[], shouldCleanNodes: boolean): any[]; setDomNodeChildren(domNode: any, childNodes: any[]): void; replaceDomNodes(nodeToReplaceOrNodeArray: any, newNodesArray: any[]): void; - setOptionNodeSelectionState(optionNode: any, isSelected: bool): void; + setOptionNodeSelectionState(optionNode: any, isSelected: boolean): void; stringTrim(str: string): string; @@ -276,9 +277,9 @@ interface KnockoutUtils { stringStartsWith(str: string, startsWith: string): string; - domNodeIsContainedBy(node: any, containedByNode: any): bool; + domNodeIsContainedBy(node: any, containedByNode: any): boolean; - domNodeIsAttachedToDocument(node: any): bool; + domNodeIsAttachedToDocument(node: any): boolean; tagNameLower(element: any): string; @@ -288,7 +289,7 @@ interface KnockoutUtils { unwrapObservable(value: any): any; - toggleDomNodeCssClass(node: any, className: string, shouldHaveClass: bool): void; + toggleDomNodeCssClass(node: any, className: string, shouldHaveClass: boolean): void; //setTextContent(element: any, textContent: string): void; // NOT PART OF THE MINIFIED API SURFACE (ONLY IN knockout-{version}.debug.js) https://github.com/SteveSanderson/knockout/issues/670 @@ -314,9 +315,9 @@ interface KnockoutUtils { ieVersion: number; - isIe6: bool; + isIe6: boolean; - isIe7: bool; + isIe7: boolean; } ////////////////////////////////// @@ -364,7 +365,7 @@ interface KnockoutTemplateEngine extends KnockoutNativeTemplateEngine { renderTemplate(template, bindingContext, options, templateDocument); - isTemplateRewritten(template, templateDocument): bool; + isTemplateRewritten(template, templateDocument): boolean; rewriteTemplate(template, rewriterCallback, templateDocument); } @@ -388,11 +389,11 @@ interface KnockoutStatic { observableArray: KnockoutObservableArrayStatic; contextFor(node: any): any; - isSubscribable(instance: any): bool; + isSubscribable(instance: any): boolean; toJSON(viewModel: any, replacer?: Function, space?: any): string; toJS(viewModel: any): any; - isObservable(instance: any): bool; - isComputed(instance: any): bool; + isObservable(instance: any): boolean; + isComputed(instance: any): boolean; dataFor(node: any): any; removeNode(node: Element); cleanNode(node: Element); diff --git a/knockout/tests/knockout-templatingBehaviors-tests.ts b/knockout/tests/knockout-templatingBehaviors-tests.ts index b000015f2..7be02d4cd 100644 --- a/knockout/tests/knockout-templatingBehaviors-tests.ts +++ b/knockout/tests/knockout-templatingBehaviors-tests.ts @@ -2,8 +2,6 @@ /// /// -declare var $; - var dummyTemplateEngine = function (templates?) { var inMemoryTemplates = templates || {}; var inMemoryTemplateData = {}; @@ -137,7 +135,7 @@ describe('Templating', function() { }); it('Should automatically rerender into DOM element when dependencies change', function () { - var dependency = new ko.observable("A"); + var dependency = ko.observable("A"); ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: function () { return "Value = " + dependency(); } @@ -153,7 +151,7 @@ describe('Templating', function() { }); it('Should not rerender DOM element if observable accessed in \'afterRender\' callaback is changed', function () { - var observable = new ko.observable("A"), count = 0; + var observable = ko.observable("A"), count = 0; var myCallback = function(elementsArray, dataItem) { observable(); // access observable in callback }; @@ -171,7 +169,7 @@ describe('Templating', function() { }); it('If the supplied data item is observable, evaluates it and has subscription on it', function () { - var observable = new ko.observable("A"); + var observable = ko.observable("A"); ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: function (data) { return "Value = " + data; } @@ -184,7 +182,7 @@ describe('Templating', function() { }); it('Should stop updating DOM nodes when the dependency next changes if the DOM node has been removed from the document', function () { - var dependency = new ko.observable("A"); + var dependency = ko.observable("A"); var template = { someTemplate: function () { return "Value = " + dependency() } }; ko.setTemplateEngine(new dummyTemplateEngine(template)); @@ -275,7 +273,7 @@ describe('Templating', function() { }); it('Should rerender chained templates when their dependencies change, without rerendering parent templates', function () { - var observable = new ko.observable("ABC"); + var observable = ko.observable("ABC"); var timesRenderedOuter = 0, timesRenderedInner = 0; ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: function () { timesRenderedOuter++; return "outer template output, [renderTemplate:innerTemplate]" }, // [renderTemplate:...] is special syntax supported by dummy template engine @@ -390,7 +388,7 @@ describe('Templating', function() { }); it('Data binding syntax should support \'foreach\' option, whereby it renders for each item in an array but doesn\'t rerender everything if you push or splice', function () { - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "
The item is [js: personName]
" })); testNode.innerHTML = "
"; @@ -406,7 +404,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should apply bindings within the context of each item in the array', function () { - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is " })); testNode.innerHTML = "
"; @@ -479,7 +477,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should apply bindings with an $index in the context', function () { - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item # is " })); testNode.innerHTML = "
"; @@ -488,7 +486,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should update bindings that reference an $index if the list changes', function () { - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is " })); testNode.innerHTML = "
"; @@ -504,7 +502,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should accept array with "undefined" and "null" items', function () { - var myArray = new ko.observableArray([undefined, null]); + var myArray = ko.observableArray([undefined, null]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is " })); testNode.innerHTML = "
"; @@ -513,8 +511,8 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should update DOM nodes when a dependency of their mapping function changes', function() { - var myObservable = new ko.observable("Steve"); - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: myObservable }, { personName: "Another" }]); + var myObservable = ko.observable("Steve"); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: myObservable }, { personName: "Another" }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "
The item is [js: ko.utils.unwrapObservable(personName)]
" })); testNode.innerHTML = "
"; @@ -535,7 +533,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should treat a null parameter as meaning \'no items\'', function() { - var myArray = new ko.observableArray(["A", "B"]); + var myArray = ko.observableArray(["A", "B"]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "hello" })); testNode.innerHTML = "
"; @@ -551,7 +549,7 @@ describe('Templating', function() { it('Data binding \'foreach\' option should accept an \"as\" option to define an alias for the iteration variable', function() { // Note: There are more detailed specs (e.g., covering nesting) associated with the "foreach" binding which // uses this templating functionality internally. - var myArray = new ko.observableArray(["A", "B"]); + var myArray = ko.observableArray(["A", "B"]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "[js:myAliasedItem]" })); testNode.innerHTML = "
"; @@ -561,7 +559,7 @@ describe('Templating', function() { it('Data binding \'foreach\' option should stop tracking inner observables when the container node is removed', function() { var innerObservable = ko.observable("some value"); - var myArray = new ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); + var myArray = ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is [js: ko.utils.unwrapObservable(obsVal)]" })); testNode.innerHTML = "
"; @@ -574,7 +572,7 @@ describe('Templating', function() { it('Data binding \'foreach\' option should stop tracking inner observables related to each array item when that array item is removed', function() { var innerObservable = ko.observable("some value"); - var myArray = new ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); + var myArray = ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is [js: ko.utils.unwrapObservable(obsVal)]" })); testNode.innerHTML = "
"; @@ -588,7 +586,7 @@ describe('Templating', function() { }); it('Data binding syntax should omit any items whose \'_destroy\' flag is set (unwrapping the flag if it is observable)', function() { - var myArray = new ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }, { someProp: 4, _destroy: ko.observable(false) }]); + var myArray = ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }, { someProp: 4, _destroy: ko.observable(false) }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "
someProp=[js: someProp]
" })); testNode.innerHTML = "
"; @@ -597,7 +595,7 @@ describe('Templating', function() { }); it('Data binding syntax should include any items whose \'_destroy\' flag is set if you use includeDestroyed', function() { - var myArray = new ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }]); + var myArray = ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "
someProp=[js: someProp]
" })); testNode.innerHTML = "
"; @@ -677,7 +675,7 @@ describe('Templating', function() { }); it('Should be able to render a different template for each array entry by passing a function as template name, with the array entry\'s binding context available as a second parameter', function() { - var myArray = new ko.observableArray([ + var myArray = ko.observableArray([ { preferredTemplate: 1, someProperty: 'firstItemValue' }, { preferredTemplate: 2, someProperty: 'secondItemValue' } ]); @@ -700,7 +698,7 @@ describe('Templating', function() { it('Data binding \'templateOptions\' should be passed to template', function() { var myModel = { someAdditionalData: { myAdditionalProp: "someAdditionalValue" }, - people: new ko.observableArray([ + people: ko.observableArray([ { name: "Alpha" }, { name: "Beta" } ]) diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 6682eb363..e2fbf4c02 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -53,7 +53,7 @@ function test_computed() { }); } - function MyViewModel() { + function MyViewModel1() { this.price = ko.observable(25.99); this.formattedPrice = ko.computed({ @@ -68,7 +68,7 @@ function test_computed() { }); } - function MyViewModel() { + function MyViewModel2() { this.acceptedNumericValue = ko.observable(123); this.lastInputWasValid = ko.observable(true); @@ -90,13 +90,13 @@ function test_computed() { } class GetterViewModel { - private _selectedRange: KnockoutObservableAny; + private _selectedRange: KnockoutObservable; constructor() { this._selectedRange = ko.observable(); } - public range: KnockoutObservableAny; + public range: KnockoutObservable; } function testGetter() { @@ -333,12 +333,12 @@ function test_more() { return target; }; - function AppViewModel(first, last) { + function AppViewModel2(first, last) { this.firstName = ko.observable(first).extend({ required: "Please enter a first name" }); this.lastName = ko.observable(last).extend({ required: "" }); } - ko.applyBindings(new AppViewModel("Bob", "Smith")); + ko.applyBindings(new AppViewModel2("Bob", "Smith")); var first; this.firstName = ko.observable(first).extend({ required: "Please enter a first name", logChange: "first name" }); @@ -347,7 +347,7 @@ function test_more() { return name.toUpperCase(); }).extend({ throttle: 500 }); - function AppViewModel() { + function AppViewModel3() { this.instantaneousValue = ko.observable(); this.throttledValue = ko.computed(this.instantaneousValue) .extend({ throttle: 400 }); @@ -420,7 +420,7 @@ function test_more() { this.done = ko.observable(done); } - function AppViewModel() { + function AppViewModel4() { this.tasks = ko.observableArray([ new Task('Find new desktop background', true), new Task('Put shiny stickers on laptop', false), @@ -430,7 +430,7 @@ function test_more() { this.doneTasks = this.tasks.filterByProperty("done", true); } - ko.applyBindings(new AppViewModel()); + ko.applyBindings(new AppViewModel4()); this.doneTasks = ko.computed(function () { var all = this.tasks(), done = []; for (var i = 0; i < all.length; i++) @@ -441,7 +441,7 @@ function test_more() { } function test_mappingplugin() { - var viewModel = { + var viewModel0 = { serverTime: ko.observable(), numUsers: ko.observable() } @@ -449,8 +449,8 @@ function test_mappingplugin() { serverTime: '2010-01-07', numUsers: 3 }; - viewModel.serverTime(data.serverTime); - viewModel.numUsers(data.numUsers); + viewModel0.serverTime(data.serverTime); + viewModel0.numUsers(data.numUsers); var viewModel = ko.mapping.fromJS(data); ko.mapping.fromJS(data, viewModel); @@ -526,7 +526,7 @@ function test_misc() { return this; }; - this.myObservable = ko.observable("myValue").publishOn("myTopic"); + this.myObservable = >ko.observable("myValue").publishOn("myTopic"); ko.subscribable.fn.subscribeTo = function (topic) { postbox.subscribe(this, null, topic); @@ -534,7 +534,7 @@ function test_misc() { return this; }; - this.observableFromAnotherVM = ko.observable().subscribeTo("myTopic"); + this.observableFromAnotherVM = >ko.observable().subscribeTo("myTopic"); postbox.subscribe(function (newValue) { this(newValue); diff --git a/ladda/ladda-tests.ts b/ladda/ladda-tests.ts new file mode 100644 index 000000000..9707534cc --- /dev/null +++ b/ladda/ladda-tests.ts @@ -0,0 +1,20 @@ +/// + +// Test bind +Ladda.bind('button.ladda-button', { timeout: 42, callback: btn => alert('Clicked!!!') }); +Ladda.bind('button.ladda-button'); +Ladda.bind(document.createElement('button'), {}); +Ladda.bind(document.createElement('button')); + +// Test stop all +Ladda.stopAll(); + +// Test create +var btnElement = document.createElement('button'); +var laddaBtn = Ladda.create(btnElement); + +// Test operations via chaining +laddaBtn.start().stop().toggle().setProgress(42).enable().disable().start(); + +// Test isLoading +console.assert(laddaBtn.isLoading() === true); \ No newline at end of file diff --git a/ladda/ladda.d.ts b/ladda/ladda.d.ts new file mode 100644 index 000000000..278f00379 --- /dev/null +++ b/ladda/ladda.d.ts @@ -0,0 +1,35 @@ +// Type definitions for jStorage 0.4.0 +// Project: https://github.com/hakimel/Ladda +// Definitions by: Danil Flores +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Ladda { + + interface ILaddaButton { + start(): ILaddaButton; + + stop(): ILaddaButton; + + toggle(): ILaddaButton; + + setProgress(progress: number): ILaddaButton; + + enable(): ILaddaButton; + + disable(): ILaddaButton; + + isLoading(): boolean; + } + + interface ILaddaOptions { + timeout?: number; + callback?: (instance: ILaddaButton) => void; + } + + function bind(target: HTMLElement, options?: ILaddaOptions): void; + function bind(cssSelector: string, options?: ILaddaOptions): void; + + function create(button: HTMLElement): ILaddaButton; + + function stopAll(): void; +} \ No newline at end of file diff --git a/node/node.d.ts b/node/node.d.ts index 565263d03..2fbd81e55 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -312,7 +312,7 @@ declare module "cluster" { } export interface Worker { id: string; - process: child_process; + process: child_process.ChildProcess; suicide: boolean; send(message: any, sendHandle?: any): void; destroy(): void; @@ -1019,19 +1019,23 @@ declare module "util" { } declare module "assert" { - export function (booleanValue: boolean, message?: string); - export function fail(actual: any, expected: any, message: string, operator: string): void; - export function assert(value: any, message: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function throws(block: any, error?: any, messsage?: string): void; - export function doesNotThrow(block: any, error?: any, messsage?: string): void; - export function ifError(value: any): void; + function internal (booleanValue: boolean, message?: string): void; + module internal { + export function fail(actual: any, expected: any, message: string, operator: string): void; + export function assert(value: any, message: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function throws(block: any, error?: any, messsage?: string): void; + export function doesNotThrow(block: any, error?: any, messsage?: string): void; + export function ifError(value: any): void; + } + + export = internal; } declare module "tty" { diff --git a/package.json b/package.json index e2b00d192..8044c470a 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,6 @@ "name": "DefinitelyTyped", "version": "0.0.0", "scripts": { - "test": "node ./_infrastructure/tests/testRunner.js" + "test": "node ./_infrastructure/tests/runner.js" } } diff --git a/q/Q-tests.ts b/q/Q-tests.ts index 34cde9341..f982ae8d6 100644 --- a/q/Q-tests.ts +++ b/q/Q-tests.ts @@ -1,6 +1,10 @@ /// -var delay = function (delay) { +import q = module('q'); + +Q(8).then(x => console.log(x.toExponential())); + +var delay = function (delay: number) { var d = Q.defer(); setTimeout(d.resolve, delay); return d.promise; @@ -10,6 +14,14 @@ Q.when(delay(1000), function () { console.log('Hello, World!'); }); +Q.delay(Q(8), 1000).then(x => x.toExponential()); +Q.delay(8, 1000).then(x => x.toExponential()); +Q.delay(Q("asdf"), 1000).then(x => x.length); +Q.delay("asdf", 1000).then(x => x.length); + +var eventualAdd = Q.promised((a: number, b: number) => a + b); +eventualAdd(Q(1), Q(2)).then(x => x.toExponential()); + var eventually = function (eventually) { return Q.delay(eventually, 1000); }; @@ -22,11 +34,11 @@ Q.when(x, function (x) { Q.all([ eventually(10), eventually(20) -]) -.spread(function (x, y) { +]).spread(function (x, y) { console.log(x, y); }); + Q.fcall(function () { }) .then(function () { }) .then(function () { }) @@ -38,7 +50,7 @@ Q.fcall(function () { }) }).done(); Q.allResolved([]) -.then(function (promises: Qpromise[]) { +.then(function (promises: Q.Promise[]) { promises.forEach(function (promise) { if (promise.isFulfilled()) { var value = promise.valueOf(); @@ -46,11 +58,4 @@ Q.allResolved([]) var exception = promise.valueOf().exception; } }) -}); - -var initialVal: any; -var funcs = ['foo', 'bar', 'baz', 'qux']; -var result = Q.resolve(initialVal); -funcs.forEach(function (f) { - result = result.then(f); }); \ No newline at end of file diff --git a/q/Q.d.ts b/q/Q.d.ts index 15f3fdea7..9fd4518f2 100644 --- a/q/Q.d.ts +++ b/q/Q.d.ts @@ -1,64 +1,75 @@ // Type definitions for Q // Project: https://github.com/kriskowal/q -// Definitions by: Barrie Nemetchek +// Definitions by: Barrie Nemetchek, Andrew Gaspar // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface Qdeferred { - promise: Qpromise; - resolve(value: any): any; - reject(reason: any); - notify(value: any); - makeNodeResolver(): () => void; +declare function Q(value): Q.Promise; + +declare module Q { + interface Deferred { + promise: Promise; + resolve(value: T): any; + reject(reason: any); + notify(value: any); + makeNodeResolver(): (reason, value: T) => void; + } + + interface Promise { + fail(errorCallback: Function): Promise; + fin(finallyCallback: Function): Promise; + finally(finallyCallback: Function): Promise; + then(onFulfilled?: (value: T) => any, onRejected?: (reason) => any, onProgress?: Function): Promise; + spread(onFulfilled: Function, onRejected?: Function): Promise; + catch(onRejected: Function): Promise; + progress(onProgress: Function): Promise; + done(onFulfilled?: Function, onRejected?: Function, onProgress?: Function): void; + get(propertyName: String): Promise; + set(propertyName: String, value: any): Promise; + delete(propertyName: String): Promise; + post(methodName: String, args: any[]): Promise; + invoke(methodName: String, ...args: any[]): Promise; + keys(): Promise; + fapply(args: any[]): Promise; + fcall(method: Function, ...args: any[]): Promise; + timeout(ms: number, message?): Promise; + delay(ms: number): Promise; + isFulfilled(): boolean; + isRejected(): boolean; + isPending(): boolean; + valueOf(): any; + } + + export function when(value: any, onFulfilled: Function, onRejected?: Function): Promise; + //export function try(method: Function, ...args: any[]): Promise; // <- This is broken currently - not sure how to fix. + export function fbind(method: Function, ...args: any[]): Promise; + export function fcall(method: Function, ...args: any[]): Promise; + export function nfbind(nodeFunction: Function): (...args: any[]) => Promise; + export function nfcall(nodeFunction: Function, ...args: any[]): Promise; + export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; + export function all(promises: Promise[]): Promise; + export function allResolved(promises: Promise[]): Promise; + export function spread(onFulfilled: Function, onRejected: Function): Promise; + export function timeout(promise: Promise, ms: number, message?): Promise; + export function delay(promise: Promise, ms: number): Promise; + export function delay(value: T, ms: number): Promise; + export function isFulfilled(promise: Promise): boolean; + export function isRejected(promise: Promise): boolean; + export function isPending(promise: Promise): boolean; + export function valueOf(promise: Promise): T; + export function defer(): Deferred; + export function reject(reason?): Promise; + export function promise(factory: { resolve: Function; reject: Function; notify: Function; }): Promise; + export function promised(callback: (...any) => T): (...any) => Promise; + export function isPromise(object): boolean; + export function isPromiseAlike(object): boolean; + export function isPending(object): boolean; + export function async(generatorFunction: any): (...args) => Promise; + export function nextTick(callback: Function): void; + export var oneerror: () => void; + export var longStackSupport: boolean; + export function resolve(object): Promise; } -interface Qpromise { - fail(errorCallback: Function): Qpromise; - fin(finallyCallback: Function): Qpromise; - then(onFulfilled?: Function, onRejected?: Function, onProgress?: Function): Qpromise; - spread(onFulfilled: Function, onRejected?: Function): Qpromise; - catch(onRejected: Function): Qpromise; - progress(onProgress: Function): Qpromise; - done(onFulfilled?: Function, onRejected?: Function, onProgress?: Function): Qpromise; - get (propertyName: String): Qpromise; - set (propertyName: String, value: any): Qpromise; - delete (propertyName: String): Qpromise; - post(methodName: String, args: any[]): Qpromise; - invoke(methodName: String, ...args: any[]): Qpromise; - keys(): Qpromise; - fapply(args: any[]): Qpromise; - fcall(method: Function, ...args: any[]): Qpromise; - timeout(ms: number): Qpromise; - delay(ms: number): Qpromise; - isFulfilled(): bool; - isRejected(): bool; - isPending(): bool; - valueOf(): any; -} - -interface QStatic { - when(value: any, onFulfilled?: Function, onRejected?: Function): Qpromise; - try(method: Function, ...args: any[]): Qpromise; - fbind(method: Function, ...args: any[]): Qpromise; - fcall(method: Function, ...args: any[]): Qpromise; - all(promises: Qpromise[]): Qpromise; - allResolved(promises: Qpromise[]): Qpromise; - resolve(object:any):Qpromise; - spread(onFulfilled: Function, onRejected: Function): Qpromise; - timeout(ms: number): Qpromise; - delay(ms: number): Qpromise; - delay(value: any, ms: number): Qpromise; - isFulfilled(): bool; - isRejected(): bool; - isPending(): bool; - valueOf(): any; - defer(): Qdeferred; - (value: any): Qpromise; - reject(): Qpromise; - promise(factory: { resolve: Function; reject: Function; notify: Function; }): Qpromise; - isPromise(value: any): bool; - async(generatorFunction: any): Qdeferred; - nextTick(callback: Function); - oneerror: any; - longStackJumpLimit: number; -} -declare var Q: QStatic; +declare module "q" { + export = Q; +} \ No newline at end of file diff --git a/q/q.module-tests.ts b/q/q.module-tests.ts deleted file mode 100644 index 4f9039d23..000000000 --- a/q/q.module-tests.ts +++ /dev/null @@ -1,74 +0,0 @@ -/// -/// -/// - -import Q = module("q"); -import fs = module("fs"); - -var delay = function (delay) { - var d = Q.defer(); - setTimeout(d.resolve, delay); - return d.promise; -}; - -Q.when(delay(1000), function () { - console.log('Hello, World!'); -}); - -var eventually = function (eventually) { - return Q.delay(eventually, 1000); -}; - -var x = Q.all([1, 2, 3].map(eventually)); -Q.when(x, function (x) { - console.log(x); -}); - -Q.all([ - eventually(10), - eventually(20) -]) -.spread(function (x, y) { - console.log(x, y); -}); - -Q.fcall(function () { }) -.then(function () { }) -.then(function () { }) -.then(function () { }) -.then(function (value4) { - // Do something with value4 -}, function (error) { - // Handle any error from step1 through step4 -}).done(); - -Q.allResolved([]) -.then(function (promises: Qpromise[]) { - promises.forEach(function (promise) { - if (promise.isFulfilled()) { - var value = promise.valueOf(); - } else { - var exception = promise.valueOf().exception; - } - }) -}); - -var initialVal: any; -var funcs = ['foo', 'bar', 'baz', 'qux']; -var result = Q.resolve(initialVal); -funcs.forEach(function (f) { - result = result.then(f); -}); - -var replaceText = (text: string) => text.replace("a", "b"); - -Q.nfcall(fs.readFile, "foo.txt", "utf-8").then(replaceText); - -Q.ninvoke(fs, "readFile", "foo.txt", "utf-8").then(replaceText); - -var deferred = Q.defer(); -fs.readFile("foo.txt", "utf-8", deferred.makeNodeResolver()); -deferred.promise.then(replaceText); - -var readFile = Q.nfbind(fs.readFile); -readFile("foo.txt", "utf-8").then(replaceText); \ No newline at end of file diff --git a/q/q.module.d.ts b/q/q.module.d.ts deleted file mode 100644 index 98e1dd9dc..000000000 --- a/q/q.module.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// - -declare module "q" { - export function when(value: any, onFulfilled: Function, onRejected?: Function): Qpromise; - export function try(method: Function, ...args: any[]): Qpromise; - export function fbind(method: Function, ...args: any[]): Qpromise; - export function fcall(method: Function, ...args: any[]): Qpromise; - export function nfbind(nodeFunction: Function): (...args: any[]) => Qpromise; - export function nfcall(nodeFunction: Function, ...args: any[]): Qpromise; - export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Qpromise; - export function all(promises: Qpromise[]): Qpromise; - export function allResolved(promises: Qpromise[]): Qpromise; - export function spread(onFulfilled: Function, onRejected: Function): Qpromise; - export function timeout(ms: number): Qpromise; - export function delay(ms: number): Qpromise; - export function delay(value: any, ms: number): Qpromise; - export function isFulfilled(): bool; - export function isRejected(): bool; - export function isPending(): bool; - export function valueOf(): any; - export function defer(): Qdeferred; - export function (value: any): Qpromise; - export function reject(): Qpromise; - export function promise(factory: { resolve: Function; reject: Function; notify: Function; }): Qpromise; - export function isPromise(value: any): bool; - export function async(generatorFunction: any): Qdeferred; - export function nextTick(callback: Function); - export var oneerror: any; - export var longStackJumpLimit: number; - export function resolve(object?:Qpromise); -} \ No newline at end of file diff --git a/qunit/qunit-tests.ts b/qunit/qunit-tests.ts index 9a4849379..abc1af8c7 100644 --- a/qunit/qunit-tests.ts +++ b/qunit/qunit-tests.ts @@ -122,7 +122,7 @@ test("a test", function () { QUnit.config.autostart = false; QUnit.start(); -QUnit.config.urlConfig.push({ +QUnit.config.urlConfig.push({ id: "min", label: "Minified source", tooltip: "Load minified source files instead of the regular unminified ones." @@ -729,13 +729,7 @@ test("just a test", function() { // ************** BUG ? ****************** // TODO disable reordering for this suite! -var begin = 0, - moduleStart = 0, - moduleDone = 0, - testStart = 0, - testDone = 0, - log = 0, - moduleContext, +var moduleContext, moduleDoneContext, testContext, testDoneContext, diff --git a/qunit/qunit.d.ts b/qunit/qunit.d.ts index b8ba3bb4a..afc2645e0 100644 --- a/qunit/qunit.d.ts +++ b/qunit/qunit.d.ts @@ -134,6 +134,7 @@ interface Config { current: Object; reorder: bool; requireExpects: bool; + testTimeout: number; urlConfig: Array; done: any; } diff --git a/raphael/raphael.d.ts b/raphael/raphael.d.ts index c17a8d4fa..fc8503cd3 100644 --- a/raphael/raphael.d.ts +++ b/raphael/raphael.d.ts @@ -245,7 +245,6 @@ interface RaphaelStatic { format(token: string, ...parameters: any[]): string; fullfill(token: string, json: JSON): string; getColor(value?: number): string; - getColor: { reset(); }; getPointAtLength(path: string, length: number): { x: number; y: number; alpha: number; }; getRGB(colour: string): { r: number; g: number; b: number; hex: string; error: bool; }; getSubpath(path: string, from: number, to: number): string; diff --git a/sinon-chai/sinon-chai-tests.ts b/sinon-chai/sinon-chai-tests.ts index 1ada034de..e4de0f5a4 100644 --- a/sinon-chai/sinon-chai-tests.ts +++ b/sinon-chai/sinon-chai-tests.ts @@ -1,5 +1,5 @@ -///  -///  +/// +/// var expect = chai.expect; diff --git a/sinon/sinon-1.5.d.ts b/sinon/sinon-1.5.d.ts index cb776563a..ed423515e 100644 --- a/sinon/sinon-1.5.d.ts +++ b/sinon/sinon-1.5.d.ts @@ -387,4 +387,4 @@ interface SinonStatic { log: (message: string) => void; } -var sinon: SinonStatic; +declare var sinon: SinonStatic; diff --git a/toastr/toastr-tests.ts b/toastr/toastr-tests.ts index 31a09e609..d973731a5 100644 --- a/toastr/toastr-tests.ts +++ b/toastr/toastr-tests.ts @@ -16,7 +16,6 @@ function test_basic() { toastr.options.onclick = function () { } } -declare var $; function test_fromdemo() { var i = -1, toastCount = 0, diff --git a/tweenjs/tweenjs.d.ts b/tweenjs/tweenjs.d.ts index 7ab5cf350..256098254 100644 --- a/tweenjs/tweenjs.d.ts +++ b/tweenjs/tweenjs.d.ts @@ -10,7 +10,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -module createjs { +declare module createjs { export class TweenJS { // properties