diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index 7272d88f7e..81e96861d2 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -6,7 +6,6 @@ const result: Database.RunResult = { changes: 1, lastInsertRowid: 1 }; const options: Database.Options = { fileMustExist: true, memory: true, readonly: true }; const registrationOptions: Database.RegistrationOptions = { deterministic: true, - name: '', safeIntegers: true, varargs: true }; @@ -15,26 +14,49 @@ let db = Database('.'); db = new Database('.', { memory: true }); db.exec('CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL);'); db.exec('INSERT INTO test(name) VALUES("name");'); -db.pragma('data_version', true); +db.pragma('data_version', { simple: true }); db.checkpoint(); db.checkpoint('main'); -db.register(() => { }); -db.register({ name: 'noop', deterministic: true, varargs: true }, () => { }); +db.function('noop', () => { }); +db.function('noop', { deterministic: true, varargs: true }, () => { }); +db.aggregate('add', { + start: 0, + step: (t, n) => t + n, + deterministic: true, + varargs: true +}); +db.aggregate('getAverage', { + start: () => [], + step: (array, nextValue) => { + array.push(nextValue); + }, + result: array => array.reduce((t: any, v: any) => t + v) / array.length, +}); +db.aggregate('addAll', { + start: 0, + step: (total, nextValue) => total + nextValue, + inverse: (total, droppedValue) => total - droppedValue, + result: total => Math.round(total), +}); db.defaultSafeIntegers(); db.defaultSafeIntegers(true); const stmt = db.prepare('SELECT * FROM test WHERE name == ?;'); stmt.get(['name']); stmt.all({ name: 'name' }); -stmt.each('name', (row: { name: string }) => { }); -stmt.each((row: { name: string }) => { }); +for (const row of stmt.iterate('name')) { +} stmt.pluck(); stmt.pluck(true); +stmt.expand(); +stmt.expand(true); stmt.bind('name'); stmt.safeIntegers(); stmt.safeIntegers(true); -const trans = db.transaction(['INSERT INTO test(name) VALUES(?);']); -trans.run('name'); -trans.bind('name'); -trans.run(); +const trans = db.transaction((param) => stmt.all(param)); +trans('name'); +trans.default('name'); +trans.deferred('name'); +trans.immediate('name'); +trans.exclusive('name'); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index 5a4859e21f..32383e1337 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -3,35 +3,32 @@ // Definitions by: Ben Davies // Mathew Rumsey // Santiago Aguilar +// Alessandro Vergani // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import Integer = require("integer"); -declare class Statement { +interface Statement { database: Database; source: string; - returnsData: boolean; - constructor(db: Database, sources: string[]); + reader: boolean; run(...params: any[]): Database.RunResult; get(...params: any[]): any; all(...params: any[]): any[]; - each(params: any, cb: (row: any) => void): void; - each(cb: (row: any) => void): void; - each(...params: any[]): void; + iterate(...params: any[]): IterableIterator; pluck(toggleState?: boolean): this; + expand(toggleState?: boolean): this; bind(...params: any[]): this; safeIntegers(toggleState?: boolean): this; } -declare class Transaction { - database: Database; - source: string; - constructor(db: Database, sources: string[]); - - run(...params: any[]): Database.RunResult; - bind(...params: any[]): this; - safeIntegers(toggleState?: boolean): this; +interface Transaction { + (...params: any[]): any; + default(...params: any[]): any; + deferred(...params: any[]): any; + immediate(...params: any[]): any; + exclusive(...params: any[]): any; } interface Database { @@ -42,15 +39,14 @@ interface Database { inTransaction: boolean; prepare(source: string): Statement; - transaction(sources: string[]): Transaction; + transaction(fn: (...params: any[]) => any): Transaction; exec(source: string): this; - pragma(source: string, simplify?: boolean): any; + pragma(source: string, options?: Database.PragmaOptions): any; checkpoint(databaseName?: string): this; - register(cb: (...params: any[]) => any): this; - register( - options: Database.RegistrationOptions, - cb: (...params: any[]) => any - ): this; + function(name: string, cb: (...params: any[]) => any): this; + function(name: string, options: Database.RegistrationOptions, cb: (...params: any[]) => any): this; + aggregate(name: string, options: Database.AggregateOptions): this; + loadExtension(path: string): this; close(): this; defaultSafeIntegers(toggleState?: boolean): this; } @@ -81,14 +77,25 @@ declare namespace Database { memory?: boolean; readonly?: boolean; fileMustExist?: boolean; + timeout?: number; + } + + interface PragmaOptions { + simple?: boolean; } interface RegistrationOptions { - name?: string; varargs?: boolean; deterministic?: boolean; safeIntegers?: boolean; } + + interface AggregateOptions extends RegistrationOptions { + start?: any; + step: (total: any, next: any) => any; + inverse?: (total: any, dropped: any) => any; + result?: (total: any) => any; + } } declare const Database: DatabaseConstructor; diff --git a/types/better-sqlite3/tsconfig.json b/types/better-sqlite3/tsconfig.json index 30a480355b..19cd56ac36 100644 --- a/types/better-sqlite3/tsconfig.json +++ b/types/better-sqlite3/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], @@ -20,4 +21,4 @@ "index.d.ts", "better-sqlite3-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/bluebird/index.d.ts b/types/bluebird/index.d.ts index 091dbe6e7a..24c2b79a32 100644 --- a/types/bluebird/index.d.ts +++ b/types/bluebird/index.d.ts @@ -35,7 +35,8 @@ * THE SOFTWARE. */ -type CatchFilter = (new (...args: any[]) => E) | ((error: E) => boolean) | (object & E); +type Constructor = new (...args: any[]) => E; +type CatchFilter = ((error: E) => boolean) | (object & E); type IterableItem = R extends Iterable ? U : never; type IterableOrNever = Extract>; type Resolvable = R | PromiseLike; @@ -85,69 +86,74 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ - catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, - onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, - ): Bluebird; catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + filter5: Constructor, onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, ): Bluebird; - catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - onReject: (error: E1 | E2 | E3 | E4) => Resolvable, - ): Bluebird; + catch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, + filter5: Constructor | CatchFilter, + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, + ): Bluebird; catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + onReject: (error: E1 | E2 | E3 | E4) => Resolvable, + ): Bluebird; + + catch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3 | E4) => Resolvable, ): Bluebird; - catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - onReject: (error: E1 | E2 | E3) => Resolvable, - ): Bluebird; catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + onReject: (error: E1 | E2 | E3) => Resolvable, + ): Bluebird; + + catch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3) => Resolvable, ): Bluebird; - catch( - filter1: CatchFilter, - filter2: CatchFilter, - onReject: (error: E1 | E2) => Resolvable, - ): Bluebird; catch( - filter1: CatchFilter, - filter2: CatchFilter, + filter1: Constructor, + filter2: Constructor, + onReject: (error: E1 | E2) => Resolvable, + ): Bluebird; + + catch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, onReject: (error: E1 | E2) => Resolvable, ): Bluebird; - catch( - filter1: CatchFilter, - onReject: (error: E1) => Resolvable, - ): Bluebird; catch( - filter1: CatchFilter, + filter1: Constructor, + onReject: (error: E1) => Resolvable, + ): Bluebird; + + catch( + // tslint:disable-next-line:unified-signatures + filter1: Constructor | CatchFilter, onReject: (error: E1) => Resolvable, ): Bluebird; @@ -201,33 +207,64 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { tapCatch(onReject: (error?: any) => Resolvable): Bluebird; tapCatch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + filter5: Constructor, + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, + ): Bluebird; + tapCatch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, + filter5: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, ): Bluebird; tapCatch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + onReject: (error: E1 | E2 | E3 | E4) => Resolvable, + ): Bluebird; + tapCatch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3 | E4) => Resolvable, ): Bluebird; tapCatch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + onReject: (error: E1 | E2 | E3) => Resolvable, + ): Bluebird; + tapCatch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3) => Resolvable, ): Bluebird; tapCatch( - filter1: CatchFilter, - filter2: CatchFilter, + filter1: Constructor, + filter2: Constructor, + onReject: (error: E1 | E2) => Resolvable, + ): Bluebird; + tapCatch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, onReject: (error: E1 | E2) => Resolvable, ): Bluebird; tapCatch( - filter1: CatchFilter, + filter1: Constructor, + onReject: (error: E1) => Resolvable, + ): Bluebird; + tapCatch( + // tslint:disable-next-line:unified-signatures + filter1: Constructor | CatchFilter, onReject: (error: E1) => Resolvable, ): Bluebird; @@ -376,33 +413,64 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { // No need to be specific about Error types in these overrides, since there's no handler function catchReturn( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + filter5: Constructor, value: U, ): Bluebird; catchReturn( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, + filter5: Constructor | CatchFilter, value: U, ): Bluebird; catchReturn( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, value: U, ): Bluebird; catchReturn( - filter1: CatchFilter, - filter2: CatchFilter, + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, value: U, ): Bluebird; catchReturn( - filter1: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + value: U, + ): Bluebird; + catchReturn( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + value: U, + ): Bluebird; + catchReturn( + filter1: Constructor, + filter2: Constructor, + value: U, + ): Bluebird; + catchReturn( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + value: U, + ): Bluebird; + catchReturn( + filter1: Constructor, + value: U, + ): Bluebird; + catchReturn( + // tslint:disable-next-line:unified-signatures + filter1: Constructor | CatchFilter, value: U, ): Bluebird; @@ -420,33 +488,64 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { // No need to be specific about Error types in these overrides, since there's no handler function catchThrow( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + filter5: Constructor, reason: Error, ): Bluebird; catchThrow( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, + filter5: Constructor | CatchFilter, reason: Error, ): Bluebird; catchThrow( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, reason: Error, ): Bluebird; catchThrow( - filter1: CatchFilter, - filter2: CatchFilter, + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, reason: Error, ): Bluebird; catchThrow( - filter1: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + reason: Error, + ): Bluebird; + catchThrow( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + reason: Error, + ): Bluebird; + catchThrow( + filter1: Constructor, + filter2: Constructor, + reason: Error, + ): Bluebird; + catchThrow( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + reason: Error, + ): Bluebird; + catchThrow( + filter1: Constructor, + reason: Error, + ): Bluebird; + catchThrow( + // tslint:disable-next-line:unified-signatures + filter1: Constructor | CatchFilter, reason: Error, ): Bluebird; diff --git a/types/ckeditor__ckeditor5-core/ckeditor__ckeditor5-core-tests.ts b/types/ckeditor__ckeditor5-core/ckeditor__ckeditor5-core-tests.ts new file mode 100644 index 0000000000..68a20aff51 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/ckeditor__ckeditor5-core-tests.ts @@ -0,0 +1,328 @@ +import * as utils from "ckeditor__ckeditor5-utils"; +import * as core from "ckeditor__ckeditor5-core"; +import * as engine from "ckeditor__ckeditor5-engine"; + +declare let bool: boolean; +declare let command: core.Command; +declare let commandCollection: core.CommandCollection; +declare let commands: core.Command[]; +declare let componentFactory: core.ComponentFactory; +declare let config: utils.Config; +declare let conversion: engine.conversion.Conversion; +declare let dataController: engine.controller.DataController; +declare let editingController: engine.controller.EditingController; +declare let editingKeystrokeHandler: core.EditingKeystrokeHandler; +declare let editor: core.editor.Editor; +declare let focusTracker: utils.FocusTracker; +declare let htmlElement: HTMLElement; +declare let keystrokes: core.EditingKeystrokeHandler; +declare let locale: utils.Locale; +declare let model: engine.model.Model; +declare let num: number; +declare let pendingActions: core.PendingActions; +declare let plugin: core.Plugin; +declare let pluginCollection: core.PluginCollection; +declare let pluginCollectionStr: core.PluginCollection>; +declare let pluginStr: core.Plugin; +declare let myPlugin: MyPlugin; +declare let myPluginMaybe: MyPlugin | undefined; +declare let myPlugins: MyPlugin[]; +declare let str: string; +declare let strOrUndef: string | undefined; +declare let strs: string[]; +declare let ui: core.editor.EditorUI; +declare let undef: undefined; +declare let view: core.EditorUIView; + +class MyPlugin extends core.Plugin { + constructor(editor: core.editor.Editor) { + super(editor); + } + + static get pluginName() { + return "A"; + } + + myMethod() { + return "this is MyPlugin method"; + } +} + +class SomeCommand extends core.Command { + execute() {} +} + +// core/editor/utils/dataapimixin ============================================= + +class DataApiEditor extends core.editor.Editor implements core.editor.utils.DataApi { + // mixin by DataApiMixin + getData: () => string; + setData: (data: string) => void; +} +utils.mix(DataApiEditor, core.editor.utils.DataApiMixin); +const dataApiEditor = new DataApiEditor(); + +dataApiEditor.setData("foo"); +str = dataApiEditor.getData(); + +// core/editor/utils/elementapimixin ========================================== + +class ElementApiEditor extends core.editor.Editor implements core.editor.utils.ElementApi { + // mixin by ElementApiMixin + readonly sourceElement: HTMLElement; + updateSourceElement: () => void; +} +utils.mix(ElementApiEditor, core.editor.utils.ElementApiMixin); +const elementApiEditor = new ElementApiEditor(); + +htmlElement = elementApiEditor.sourceElement; +elementApiEditor.updateSourceElement(); + +// core/editor/utils/attachtoform ============================================= + +// $ExpectError +core.editor.utils.attachToForm(editor); +core.editor.utils.attachToForm(elementApiEditor); + +// core/editor/editor ========================================================= + +commandCollection = editor.commands; +config = editor.config; +editingController = editor.editing; +conversion = editor.conversion; +dataController = editor.data; +editor.isReadOnly = bool; +editingKeystrokeHandler = editor.keystrokes; +locale = editor.locale; +model = editor.model; +pluginCollection = editor.plugins; + +if (editor.state === "initializing") { + console.log("new Editor()"); +} else if (editor.state === "ready") { + console.log("Editor.create()"); +} else if (editor.state === "destroyed") { + console.log("editor.destroy"); +} else { + const n: never = editor.state; +} + +editor.state = "ready"; + +core.editor.Editor.builtinPlugins = [plugin, pluginStr, plugin]; +const plugins: Array> = core.editor.Editor.builtinPlugins; + +core.editor.Editor.defaultConfig = { + foo: { + a: 1, + b: 2 + } +}; + +editor = new core.editor.Editor(); +editor = new core.editor.Editor({language: "pl"}); + +editor.destroy(); +editor.destroy().then(() => { + console.log(`${editor.state} == destroyed`); +}); + +editor.execute("someCommand"); +editor.execute("someCommand2", "arg1", 2); + +editor.initPlugins(); +editor.initPlugins().then(() => { + console.log(`init ${Array.from(editor.plugins).length} plugins`); +}); + +locale.t = editor.t; +str = editor.t("Label"); +str = editor.t('Created file "%0" in %1ms.', ["fileName", "100"]); + +// core/editor/editorui ======================================================= + +componentFactory = ui.componentFactory; +editor = ui.editor; +focusTracker = ui.focusTracker; +view = ui.view; + +ui = new core.editor.EditorUI(editor, view); +ui.destroy(); +ui.update(); + +// core/editor/editorwithui =================================================== + +declare let ewui: core.editor.EditorWithUI; +htmlElement = ewui.element!; +ui = ewui.ui; + +// core/command =============================================================== + +editor = command.editor; + +bool = command.isEnabled; + +undef = command.value; +strOrUndef = new core.Command(editor).value; + +command = new core.Command(editor); + +command.destroy(); + +command.execute(); + +command.refresh(); + +// core/commandcollection ===================================================== + +commandCollection = new core.CommandCollection(); + +const collectionsPairs = Array.from(commandCollection); +const collectionsPair = collectionsPairs[0]; +str = collectionsPair[0]; +command = collectionsPair[1]; + +commandCollection.add("foo", new SomeCommand(editor)); + +command = commandCollection.commands().next().value; +commands = Array.from(commandCollection.commands()); + +commandCollection.destroy(); + +commandCollection.execute("foo"); +commandCollection.execute("bar", 1, "param"); + +command = commandCollection.get("foo"); + +str = commandCollection.names().next().value; +strs = Array.from(commandCollection.names()); + +// core/editingkeystrokehandler =============================================== + +keystrokes = new core.EditingKeystrokeHandler(editor); + +editor = keystrokes.editor; + +keystrokes.press({keyCode: 123}); + +keystrokes.set("Ctrl+A", "foo"); +keystrokes.set(["shift", "33"], "foo"); +keystrokes.set(["ctrl", "A"], "foo", {priority: 10}); +keystrokes.set(["ctrl", "A"], "foo", {priority: "high"}); +keystrokes.set(["ctrl", "A"], () => console.log("key")); +keystrokes.set(["ctrl", "A"], (keyEvtData, cancel) => { + console.log(keyEvtData.keyCode); + cancel(); +}); + +// core/pendingactions ======================================================== + +pendingActions = new core.PendingActions(editor); + +str = core.PendingActions.pluginName; + +const firstAction = pendingActions.first; + +bool = pendingActions.hasAny; + +strs = Array.from(pendingActions, action => action.message); + +const action1 = pendingActions.add("Action 1"); + +pendingActions.remove(action1); + +firstAction!.fire("I'm an Observable with a message"); +str = firstAction!.message; +str = action1.message; + +// core/plugin ================================================================ + +class MyPluginMini extends core.Plugin { + constructor(editor: core.editor.Editor) { + super(editor); + } +} + +class MyPluginAll extends core.Plugin { + constructor(editor: core.editor.Editor) { + super(editor); + } + + static get pluginName() { + return "All"; + } + + static get requires() { + return [MyPlugin, MyPluginMini]; + } + + afterInit() {return Math.random() ? null : Promise.resolve("resolved"); } + destroy() {return Math.random() ? null : Promise.resolve("destroy"); } + init() {return Math.random() ? null : Promise.resolve("init"); } +} + +plugin = new MyPlugin(editor); +plugin = new MyPluginMini(editor); +pluginStr = new MyPluginAll(editor); + +const Plugin: MyPlugin = new MyPlugin(editor); +const pluginMini: MyPluginMini = new MyPluginMini(editor); +const pluginAll: MyPluginAll = new MyPluginAll(editor); + +editor = myPlugin.editor; + +str = MyPluginAll.pluginName; +strOrUndef = MyPluginMini.pluginName; // Todo: should be undefined. + +plugin = new MyPluginAll.requires[0](editor); + +const fs: Function[] = MyPluginAll.requires; +const fsOrUndef = MyPluginMini.requires; // Todo: should be undefined. + +// $ExpectError +pluginMini.afterInit(); +pluginAll.afterInit(); + +// $ExpectError +pluginMini.destroy(); +pluginAll.destroy(); + +// $ExpectError +pluginMini.init(); +pluginAll.init(); + +// core/plugincollection ====================================================== + +pluginCollectionStr = new core.PluginCollection(editor, [MyPluginAll]); +// $ExpectError +pluginCollectionStr = new core.PluginCollection(editor, [MyPlugin]); + +const aColl = new core.PluginCollection(editor, [MyPluginAll, MyPluginMini]); + +const myColl = new core.PluginCollection(editor, [MyPlugin]); + +const myCollArray = Array.from(myColl); +myPlugins = myCollArray.map(entry => entry[1]); +myPlugin = new (myCollArray[0][0])(editor); + +myColl.destroy() + .then(destroyedPlugins => { + num = destroyedPlugins.length; + const plugin = destroyedPlugins[0]; + editor = plugin.editor; + plugin.init!(); + plugin.destroy(); + str = plugin.myMethod(); + }); + +myPluginMaybe = myColl.get("A"); +myPluginMaybe = myColl.get(MyPlugin); + +myColl.load([MyPlugin, "A"]) + .then((loadedPlugins) => { + const plugin = loadedPlugins[0]; + editor = plugin.editor; + str = plugin.myMethod(); + }); + +myColl.load([MyPlugin, "A"], [MyPlugin, "A"]); diff --git a/types/ckeditor__ckeditor5-core/index.d.ts b/types/ckeditor__ckeditor5-core/index.d.ts new file mode 100644 index 0000000000..63ae237739 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/index.d.ts @@ -0,0 +1,269 @@ +// Type definitions for @ckeditor/ckeditor5-core 11.0 +// Project: https://github.com/ckeditor/ckeditor5-core +// Definitions by: denisname +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as engine from "ckeditor__ckeditor5-engine"; +import * as ckutils from "ckeditor__ckeditor5-utils"; + +// TODO: depends on other libraries +export interface AlignmentConfig {} +export interface AutosaveConfig {} +export interface CKFinderAdapterConfig {} +export interface CloudServicesConfig {} +export interface FontFamilyConfig {} +export interface FontSizeConfig {} +export interface HeadingConfig {} +export interface HighlightConfig {} +export interface ImageConfig {} +export interface MediaEmbedConfig {} +export interface TypingConfig {} +export interface ComponentFactory {} // CKEditor 5 UI +export interface EditorUIView {} // CKEditor 5 UI + +export namespace editor { + namespace utils { + // core/editor/utils/attachtoform + + function attachToForm(editor: Editor & ElementApi): void; + + // core/editor/utils/dataapimixin + + const DataApiMixin: DataApi; + + interface DataApi { + getData(): string; + setData(data: string): void; + } + + // core/editor/utils/elementapimixin + + const ElementApiMixin: ElementApi; + + interface ElementApi { + readonly sourceElement: HTMLElement; + updateSourceElement(): void; + } + } + + // core/editor/editor + + class Editor implements ckutils.Emitter, ckutils.Observable { + readonly commands: CommandCollection; + readonly config: ckutils.Config; + readonly conversion: engine.conversion.Conversion; + readonly data: engine.controller.DataController; + readonly editing: engine.controller.EditingController; + isReadOnly: boolean; + readonly keystrokes: EditingKeystrokeHandler; + readonly locale: ckutils.Locale; + readonly model: engine.model.Model; + readonly plugins: PluginCollection>; + state: "initializing" | "ready" | "destroyed"; + + static builtinPlugins: Array>; + static defaultConfig: object; + + constructor(config?: object); + destroy(): Promise; + execute(commandName: string, ...commandParams: any[]): void; + initPlugins(): Promise; + t(str: string, values?: string[]): string; + + static create(config: object): Promise; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + // core/editor/editorconfig + + interface EditorConfig { + alignment: AlignmentConfig; + autosave: AutosaveConfig; + balloonToolbar: string[]; + blockToolbar: string[]; + ckfinder: CKFinderAdapterConfig; + cloudServices: CloudServicesConfig; + fontFamily: FontFamilyConfig; + fontSize: FontSizeConfig; + heading: HeadingConfig; + highlight: HighlightConfig; + image: ImageConfig; + language: string; + mediaEmbed: MediaEmbedConfig; + plugins: Array; + removePlugins: string[]; + toolbar: string[] | {items: string[]; viewportTopOffset: number; }; + typing: TypingConfig; + } + + // core/editor/editorui + + class EditorUI implements ckutils.Emitter { + readonly componentFactory: ComponentFactory; + readonly editor: Editor; + readonly focusTracker: ckutils.FocusTracker; + readonly view: EditorUIView; + + constructor(editor: Editor, view: EditorUIView); + destroy(): void; + update(): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + } + + // core/editor/editorwithui + + interface EditorWithUI { + readonly element: HTMLElement | null; + readonly ui: EditorUI; + } +} + +// core/command + +export class Command implements ckutils.Emitter, ckutils.Observable { + readonly editor: editor.Editor; + readonly isEnabled: boolean; + readonly value: T | undefined; + + constructor(editor: editor.Editor); + destroy(): void; + execute(): void; + refresh(): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; +} + +// core/commandcollection + +export class CommandCollection { + constructor(); + [Symbol.iterator](): Iterator<[string, Command]>; + add(commandName: string, command: Command): void; + commands(): IterableIterator; + destroy(): void; + execute(commandName: string, ...commandParams: any[]): void; + get(commandName: string): Command; + names(): IterableIterator; +} + +// core/editingkeystrokehandler + +export class EditingKeystrokeHandler extends ckutils.KeystrokeHandler { + readonly editor: editor.Editor; + + constructor(editor: editor.Editor); + set( + keystroke: string | Array, + callback: string | ((keyEvtData: engine.view.observer.KeyEventData, cancel: () => void) => void), + options?: {priority: ckutils.PriorityString | number} + ): void; +} + +// core/pendingactions + +export class PendingActions extends Plugin { + static readonly pluginName: "PendingActions"; + + first: null | ckutils.Observable & {message: string}; + readonly hasAny: boolean; + + [Symbol.iterator](): Iterator; + add(message: string): ckutils.Observable & {message: string}; + remove(action: ckutils.Observable & {message: string}): void; +} + +// core/plugin + +export abstract class Plugin implements ckutils.Emitter, ckutils.Observable { + readonly editor: editor.Editor; + + static readonly pluginName?: string; + static readonly requires?: Array Plugin>; + + constructor(editor: editor.Editor); + afterInit?(): null | Promise; + destroy?(): null | Promise; + init?(): null | Promise; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; +} + +// PluginInterface, see Plugin + +// core/plugincollection + +export class PluginCollection

> { + constructor( + editor: editor.Editor, + availablePlugins?: Array P> + ); + + [Symbol.iterator](): Iterator<[new(editor: editor.Editor) => P, P]>; + + destroy(): Promise}>>; + + get( + key: string | (new(editor: editor.Editor) => P) + ): P | undefined; + + load( + plugins: Array P)>, + removePlugins?: Array P)> + ): Promise; +} diff --git a/types/ckeditor__ckeditor5-core/tsconfig.json b/types/ckeditor__ckeditor5-core/tsconfig.json new file mode 100644 index 0000000000..5f53bb9035 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom", + "es2015.promise" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ckeditor__ckeditor5-core-tests.ts" + ] +} diff --git a/types/ckeditor__ckeditor5-core/tslint.json b/types/ckeditor__ckeditor5-core/tslint.json new file mode 100644 index 0000000000..b4dd998211 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/tslint.json @@ -0,0 +1,22 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": { + "options": [ + ["Object", "Avoid using the `Object` type. Did you mean `object`?"], + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + }, + "no-empty-interface": false, + "prefer-switch": false, + "quotemark": [ + true, + "double", + "avoid-escape", + "avoid-template" + ] + } +} diff --git a/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts b/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts new file mode 100644 index 0000000000..676f30ac3b --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts @@ -0,0 +1,81 @@ +import * as engine from "ckeditor__ckeditor5-engine"; + +declare let pattern: engine.view.MatcherPattern; + +pattern = {name: /^p/}; + +pattern = { + attributes: { + title: "foobar", + foo: /^\w+/, + bar: true, + } +}; + +pattern = { + classes: "foobar" +}; + +pattern = { + classes: /foo.../ +}; + +pattern = { + classes: ["baz", "bar", /foo.../] +}; + +pattern = { + styles: { + position: "absolute", + color: /^\w*blue$/ + } +}; + +pattern = { + name: "span", + styles: { + "font-weight": "bold" + }, + classes: "highlighted" +}; + +pattern = (element: engine.view.Element) => { + if (element.name === "div" && element.childCount > 0) { + return {name: true}; + } + + return null; +}; + +pattern = (element: engine.view.Element) => { + if (element.name === "p") { + const fontSize = element.getStyle("font-size")!; + const size = fontSize.match(/(\d+)/px); + + if (size && Number(size[1]) > 26) { + return {name: true, attribute: ["font-size"]}; + } + } + + return null; +}; + +declare let viewDefinition: engine.view.ElementDefinition; + +viewDefinition = "p"; + +viewDefinition = { + name: "h1", + classes: ["foo", "bar"], +}; + +viewDefinition = { + name: "span", + styles: { + "font-size": "12px", + "font-weight": "bold", + }, + attributes: { + "data-id": "123", + } +}; diff --git a/types/ckeditor__ckeditor5-engine/index.d.ts b/types/ckeditor__ckeditor5-engine/index.d.ts new file mode 100644 index 0000000000..280b6ea213 --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/index.d.ts @@ -0,0 +1,1368 @@ +// Type definitions for @ckeditor/ckeditor5-engine 11.0 +// Project: https://github.com/ckeditor/ckeditor5-engine +// Definitions by: denisname +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as ckutils from "ckeditor__ckeditor5-utils"; + +export namespace controller { + // engine/controller/datacontroller + + class DataController implements ckutils.Emitter, ckutils.Observable { + readonly downcastDispatcher: conversion.DowncastDispatcher; + readonly mapper: conversion.Mapper; + readonly model: model.Model; + readonly processor: dataprocessor.DataProcessor; + readonly upcastDispatcher: conversion.UpcastDispatcher; + + constructor(model: model.Model, dataProcessor?: dataprocessor.DataProcessor); + destroy(): void; + get(rootName?: string): string; + init(data: string, rootName?: string): Promise; + parse(data: string, context?: model.SchemaContextDefinition): model.DocumentFragment; + stringify(modelElementOrFragment: Element | model.DocumentFragment): string; + toModel(viewElementOrFragment: Element | model.DocumentFragment, context?: model.SchemaContextDefinition): model.DocumentFragment; + toView(modelElementOrFragment: Element | model.DocumentFragment): model.DocumentFragment; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + // engine/controller/editingcontroller + + class EditingController implements ckutils.Emitter, ckutils.Observable { + readonly downcastDispatcher: conversion.DowncastDispatcher; + readonly mapper: conversion.Mapper; + readonly model: model.Model; + readonly view: view.View; + + constructor(model: model.Model); + destroy(): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } +} + +export namespace conversion { + // engine/conversion/conversion + + class Conversion { + constructor(); + attributeToAttribute(definition?: {model: string | Object, view?: string | Object, upcastAlso?: view.MatcherPattern | view.MatcherPattern[]}): void; + attributeToElement(definition: ConverterDefinition): void; + elementToElement(definition: ConverterDefinition): void; + for(groupName: string): {add: () => void}; + register(groupName: string, dispatchers: Array): void; + } + + interface ConverterDefinition { + converterPriority: ckutils.PriorityString; + model: any; + upcastAlso: view.MatcherPattern | view.MatcherPattern[]; + view: view.ElementDefinition | Object; + } + + // engine/conversion/downcast-converters + + interface HighlightDescriptor { + attributes: Object; + classes: string | string[]; + id: string; + priority: number; + } + + // engine/conversion/downcast-selection-converters + + function clearAttributes(): Function; + + function convertCollapsedSelection(): Function; + + function convertRangeSelection(): Function; + + // engine/conversion/downcastdispatcher + + class DowncastDispatcher { + // TODO + } + + // engine/conversion/mapper + + class Mapper { + constructor(); + bindElementToMarker(element: view.Element, name: string): void; + bindElements(modelElement: model.Element, viewElement: view.Element): void; + clearBindings(): void; + getModelLength(viewNode: view.Element): number; + markerNameToElements(name: string): Set | null; + registerViewToModelLength(viewElementName: string, lengthCallback: Function): void; + toModelElement(viewElement: view.Element): model.Element | undefined; + toModelPosition(viewPosition: view.Position): model.Position; + toModelRange(viewRange: view.Range): model.Range; + toViewElement(modelElement: model.Element): view.Element | undefined; + toViewPosition(modelPosition: model.Position, options?: {isPhantom: boolean}): view.Position; + toViewRange(modelRange: model.Range): view.Range; + unbindElementsFromMarkerName(name: string): void; + unbindModelElement(modelElement: model.Element): void; + unbindViewElement(viewElement: view.Element): void; + } + + // engine/conversion/modelconsumable + + class ModelConsumable { + constructor(); + add(item: model.Item | model.Selection | model.Range, type: string): void; + consume(item: model.Item | model.Selection | model.Range, type: string): boolean; + revert(item: model.Item | model.Selection | model.Range, type: string): null | boolean; + test(item: model.Item | model.Selection | model.Range, type: string): null | boolean; + } + + // engine/conversion/upcast-converters + + function convertText(): Function; + + function convertToModelFragment(): Function; + + function upcastAttributeToAttribute( + config: {view: string | {key: string, name: string, value: string | RegExp | Function}, + model: string | {key: string, value: string | Function}, + converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToAttribute( + config: {view: view.MatcherPattern, model: string | {key: string, value: string | Function}, converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToElement( + config: {view: view.MatcherPattern, model: string | Element | Function, converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToMarker( + config: {view: view.MatcherPattern, model: string | Function, converterPriority?: ckutils.PriorityString} + ): Function; + + // engine/conversion/upcast-selection-converters + + function convertSelectionChange(model: model.Model, mapper: Mapper): Function; + + // engine/conversion/upcastdispatcher + + class UpcastDispatcher { + // TODO + } + + interface ViewConversionApi { + // TODO + } + + // engine/conversion/viewconsumable + + class ViewConsumable { + // TODO + } +} + +export namespace dataprocessor { + // engine/dataprocessor/basichtmlwriter + + class BasicHtmlWriter implements HtmlWriter { + getHtml(fragment: model.DocumentFragment): string; + } + + // engine/dataprocessor/dataprocessor + + interface DataProcessor { + // TODO + } + + // engine/dataprocessor/htmldataprocessor + + class HtmlDataProcessor implements DataProcessor { + // TODO + } + + // engine/dataprocessor/htmlwriter + + interface HtmlWriter { + getHtml(fragment: model.DocumentFragment): string; + } + + // engine/dataprocessor/xmldataprocessor + + class XmlDataProcessor implements DataProcessor { + // TODO + } +} + +export namespace devUtils { + // engine/dev-utils/enableenginedebug + + class DebugPlugin {} + + function disableEngineDebug(): void; + + function enableEngineDebug(_logger: {log: (...arg: any[]) => string, error: (...arg: any[]) => string}): DebugPlugin; + + // engine/dev-utils/model + + namespace devmodel { + function getData( + model: model.Model, + options?: { + withoutSelection?: boolean, + rootName?: string, + convertMarkers?: boolean + } + ): string; + + function parse( + data: string, + schema: model.Schema, + batch: model.Batch, + options?: { + selectionAttributes?: Object[], + lastRangeBackward?: boolean, + context?: model.SchemaContextDefinition + } + ): model.Element | model.Text | model.DocumentFragment | Object; + + function setData(model: string, data: Object, options: {rootName?: string, selectionAttributes?: Object[], lastRangeBackward?: boolean, batchType?: string}): void; + + function stringify( + node: model.RootElement | model.Element | model.Text | model.DocumentFragment, + selectionOrPositionOrRange: model.Selection | model.Position | model.Range, // TODO optional + markers: Iterable | null + ): string; + } + + // engine/dev-utils/operationreplayer + + class OperationReplayer { + // TODO + } + + // engine/dev-utils/view + + function getData( + view: view.View, + options?: { + withoutSelection?: boolean, + rootName?: boolean, + showType?: boolean, + showPriority?: boolean, + showAttributeElementId?: boolean, + renderUIElements?: boolean, + } + ): string; + + function parse( + data: string, + options: { + order?: number[], + lastRangeBackward?: boolean, + rootElement?: view.Element | view.DocumentFragment, + sameSelectionCharacters?: boolean + } + ): view.Text | view.Element | view.DocumentFragment | Object; + + function setData( + view: view.View, + data: string, + options: {rootName?: string} + ): void; + + function stringify( + node: view.Text | view.Element | view.DocumentFragment, + selectionOrPositionOrRange?: view.DocumentSelection | view.Position | view.Range, + options?: { + showType?: boolean, + showPriority?: boolean, + showAttributeElementId?: boolean, + ignoreRoot?: boolean, + sameSelectionCharacters?: boolean, + renderUIElements?: boolean, + } + ): string; +} + +export namespace model { + namespace operation { + // engine/model/operation/attributeoperation + + class AttributeOperation { + // TODO + } + + // engine/model/operation/detachoperation + + class DetachOperation { + // TODO + } + + // engine/model/operation/insertoperation + + class InsertOperation { + // TODO + } + + // engine/model/operation/markeroperation + + class MarkerOperation { + // TODO + } + + // engine/model/operation/mergeoperation + + class MergeOperation { + // TODO + } + + // engine/model/operation/moveoperation + + class MoveOperation { + // TODO + } + + // engine/model/operation/nooperation + + class NoOperation { + // TODO + } + + // engine/model/operation/operation + + class Operation { + // TODO + } + + // engine/model/operation/operationfactory + + class OperationFactory { + // TODO + } + + // engine/model/operation/renameoperation + + class RenameOperation { + // TODO + } + + // engine/model/operation/rootattributeoperation + + class RootAttributeOperation { + // TODO + } + + // engine/model/operation/splitoperation + + class SplitOperation { + // TODO + } + + // engine/model/operation/transform + + class TransformationContext { + // TODO + } + + function transform(a: Operation, b: Operation, context: TransformationContext): Operation[]; + + function transformSets(operationsA: Operation[], operationsB: Operation[], options: {document: Document | null, useRelations: boolean, padWithNoOps: boolean}): object; + } + + namespace utils { + function deleteContent( + model: Model, + selection: Selection | DocumentSelection, + batch: Batch, + options?: {leaveUnmerged: boolean, doNotResetEntireContent: boolean} + ): void; + + function getSelectedContent( + model: Model, + selection: Selection | DocumentSelection + ): DocumentFragment; + + function insertContent( + model: Model, + content: DocumentFragment | Item, + selectable?: Selection | DocumentSelection | Position | Element | Iterable | Range | null + ): void; + + function modifySelection( + model: Model, + selection: Selection | DocumentSelection, + options?: {direction?: "forward" | "backward", unit?: "character" | "codePoint" | "word"} + ): void; + + function injectSelectionPostFixer( + model: Model + ): void; + } + + // engine/model/batch + + class Batch { + // TODO + } + + // engine/model/differ + + class Differ { + // TODO + } + + // engine/model/document + + class Document { + // TODO + } + + // engine/model/documentfragment + + class DocumentFragment { + readonly childCount: number; + readonly isEmpty: boolean; + readonly markers: Map; + readonly maxOffset: number; + readonly parent: null; + readonly root: DocumentFragment; + + protected constructor(children?: Node | Iterable); + [Symbol.iterator](): Iterator; + getChild(index: number): Node | null; + getChildIndex(node: Node): number | null; + getChildStartOffset(node: Node): number | null; + getChildren(): Iterable; + getNodeByPath(relativePath: number[]): Node | DocumentFragment; + getPath(): number[]; /*TS3.0: []*/ + is(type: string): boolean; + offsetToIndex(offset: number): number; + toJSON(): Object; + protected _appendChild(items: Item | Iterable): void; + protected _insertChild(index: number, items: Item | Iterable): void; + protected _removeChildren(index: number, howMany?: number): Node[]; + + static fromJSON(json: object): DocumentFragment; + } + + // engine/model/documentselection + + class DocumentSelection { + // TODO + } + + // engine/model/element + + class Element extends Node { + readonly childCount: number; + readonly isEmpty: boolean; + readonly maxOffset: number; + readonly name: string; + + protected constructor( + name: string, + attrs?: Map | ReadonlyArray<[string, any]>, + children?: Node | Iterable + ); + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildStartOffset(node: Node): number; + getChildren(): Iterable; + getNodeByPath(relativePath: number[]): Node; + is(type: string, name?: string): boolean; + offsetToIndex(offset: number): number; + toJSON(): object; + protected _appendChild(nodes: Item | Iterable): void; + protected _clone(deep?: boolean): Element; + protected _insertChild(index: number, items: Item | Iterable): void; + protected _removeChildren(index: number, howMany?: number): Node[]; + + static fromJSON(json: object): Element; + } + + // engine/model/history + + class History { + // TODO + } + + // engine/model/item + + type Item = Node | TextProxy; + + // engine/model/liveposition + + class LivePosition { + // TODO + } + + // engine/model/liverange + + class LiveRange { + // TODO + } + + // engine/model/markercollection + + class Marker { + // TODO + } + + class MarkerCollection { + // TODO + } + + // engine/model/model + + class Model implements ckutils.Emitter, ckutils.Observable { + readonly document: Document; + readonly markers: MarkerCollection; + readonly schema: Schema; + + applyOperation(operation: operation.Operation): void; + change(callback: Function): any; + deleteContent(selection: Selection | DocumentSelection, batch: Batch, options: {leaveUnmerged?: boolean, doNotResetEntireContent?: boolean}): void; + destroy(): void; + enqueueChange(batchOrType: Batch | "transparent" | "default", callback: Function): void; + getSelectedContent(selection: Selection | DocumentSelection): DocumentFragment; + hasContent(rangeOrElement: Range | Element): boolean; + insertContent(content: DocumentFragment | Item, selectable?: Selection | DocumentSelection | Position | Element | Iterable | Range | null): void; + modifySelection(selection: Selection | DocumentSelection, options?: {direction?: "forward" | "backward", unit?: "character" | "codePoint" | "word"}): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + // engine/model/node + + class Node { + readonly document: Document | null; + readonly endOffset: number | null; + readonly index: number | null; + readonly nextSibling: Node | null; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly previousSibling: Node | null; + readonly root: Node | DocumentFragment; + readonly startOffset: number | null; + + constructor(attrs?: Map | ReadonlyArray<[string, any]>); + getAncestors(options: {includeSelf: boolean, parentFirst: boolean}): Node[]; + getAttribute(key: string): any /*| undefined*/; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getCommonAncestor(node: Node, options?: {includeSelf: boolean}): Element | DocumentFragment | null; + getPath(): number[]; + hasAttribute(key: string): boolean; + + is(type: "element"): this is Element; + is(type: "rootElement"): this is RootElement; + is(type: "text"): this is Text; + is(type: "textProxy"): this is TextProxy; + is(type: "documentFragment"): this is DocumentFragment; + is(type: string, name: string): boolean; + + isAfter(node: Node): boolean; + isBefore(node: Node): boolean; + toJSON(): object; + } + + type NodeSet = Node | TextProxy | string | NodeList | DocumentFragment | Iterable; + + // engine/model/nodelist + + class NodeList implements Iterable { + readonly length: number; + readonly maxOffset: number; + + [Symbol.iterator](): Iterator; + getNode(index: number): Node | null; + getNodeIndex(node: Node): number | null; + getNodeStartOffset(node: Node): number | null; + indexToOffset(index: number): number; + offsetToIndex(offset: number): number; + toJSON(): Node[]; + } + + // engine/model/position + + class Position { + readonly index: number; + readonly isAtEnd: boolean; + readonly isAtStart: boolean; + readonly nodeAfter: Node | null; + readonly nodeBefore: Node; + offset: number; + readonly parent: Element; + readonly path: number[]; + readonly root: Element | DocumentFragment; + stickiness: PositionStickiness; + readonly textNode: Text | null; + + constructor(root: Element | DocumentFragment, path: number[], stickiness?: PositionStickiness); + compareWith(otherPosition: Position): PositionRelation; + getAncestors(): Item[]; + getCommonAncestor(position: Position): Element | DocumentFragment | null; + getCommonPath(position: Position): number[]; + getLastMatchingPosition(skip: (t: TreeWalkerValue) => boolean, options: object): Position; + getParentPath(): number[]; + getShiftedBy(shift: number): Position; + getTransformedByOperation(operation: operation.Operation): Position; + hasSameParentAs(position: Position): boolean; + isAfter(otherPosition: Position): boolean; + isBefore(otherPosition: Position): boolean; + isEqual(otherPosition: Position): boolean; + isTouching(otherPosition: Position): boolean; + toJSON(): object; + + static createAfter(item: Item): Position; + static createAt(itemOrPosition: Item | Position, offset?: number | "end" | "before" | "after"): void; + static createBefore(item: Item): Position; + static createFromParentAndOffset(parent: Element | DocumentFragment, offset: number): Position; + static createFromPosition(position: Position): Position; + static fromJSON(json: object, doc: Document): Position; + } + + type PositionRelation = "before" | "after" | "same"; + + type PositionStickiness = "toNone" | "toNext" | "toPrevious"; + + // engine/model/range + + class Range implements Iterable { + readonly end: Position; + isCollapsed: boolean; + isFlat: boolean; + root: Element | DocumentFragment; + readonly start: Position; + + constructor(start: Position, end?: Position); + [Symbol.iterator](): Iterator; + containsItem(item: Item): void; + containsPosition(position: Position): boolean; + containsRange(otherRange: Range, loose?: boolean): boolean; + getCommonAncestor(): Element | DocumentFragment | null; + getDifference(otherRange: Range): Range[]; + getIntersection(otherRange: Range): Range | null; + getMinimalFlatRanges(): Range[]; + getPositions(options: object): Iterable; + getTransformedByOperation(operation: operation.Operation): Range[]; + getTransformedByOperations(operations: Iterable): Range[]; + getWalker(options: { + startPosition: Position, + singleCharacters: boolean, + shallow: boolean, + ignoreElementEnd: boolean, + }): void; + isEqual(otherRange: Range): boolean; + isIntersecting(otherRange: Range): boolean; + toJSON(): object; + } + + function getItems(options: object): Iterable; + + // engine/model/rootelement + + class RootElement extends Element { + readonly document: Document | null; + readonly rootName: string; + + constructor(doc: Document, name: string, rootName: string); + // TODO: toJSON(): string; + } + + // engine/model/schema + + class Schema { + // TODO + } + + class SchemaContext { + // TODO + } + + interface SchemaCompiledItemDefinition { + name: string; + allowIn: string | string[]; + allowAttributes: string | string[]; + isBlock: boolean; + isLimit: boolean; + isObject: boolean; + } + + type SchemaContextDefinition = Node | Position | SchemaContext | string | Array; + + interface SchemaContextItem { + name: string; + getAttributeKeys: Iterable; + getAttribute: (key: string) => string; + } + + interface SchemaItemDefinition { + allowIn: string | string[]; + allowAttributes: string | string[]; + allowContentOf: string | string[]; + allowWhere: string | string[]; + allowAttributesOf: string | string[]; + inheritTypesFrom: string | string[]; + inheritAllFrom: string | string[]; + isBlock: boolean; + isLimit: boolean; + isObject: boolean; + } + + // engine/model/selection + + class Selection implements ckutils.Emitter { + // TODO + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + } + + // engine/model/text + + class Text extends Node { + readonly data: string; + protected _data: string; + + protected constructor(data: string, attrs?: Map | ReadonlyArray<[string, any]>); + toJSON(): object; + protected _clone(): Text; + + static fromJSON(json: object): Text; + } + + // engine/model/textproxy + + class TextProxy { + readonly data: string; + readonly document: Document | null; + readonly endOffset: number; + readonly isPartial: boolean; + readonly offsetInText: number; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly root: Node | DocumentFragment; + readonly startOffset: number; + readonly textNode: Text; + + protected constructor(textNode: Text, offsetInText: number, length: number); + getAncestors(options: {includeSelf?: boolean, parentFirst?: boolean}): Array; + getAttribute(key: string): any; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getPath(): number[]; + hasAttribute(key: string): boolean; + is(type: "textProxy"): this is TextProxy; + is(type: string): boolean; + } + + // engine/model/treewalker + + class TreeWalker implements Iterable { + readonly boundaries: Range; + readonly direction: "backward" | "forward"; + readonly ignoreElementEnd: boolean; + readonly position: Position; + readonly shallow: boolean; + readonly singleCharacters: boolean; + + constructor(options?: { + direction?: "forward" | "backward", + boundaries?: Range, + startPosition: Position, + singleCharacters?: boolean, + shallow?: boolean, + ignoreElementEnd?: boolean + }); + [Symbol.iterator](): Iterator; + next(): TreeWalkerValue; + skip(skip: (t: TreeWalkerValue) => boolean): void; + } + + interface TreeWalkerValue { + item: Item; + length: number; + nextPosition: Position; + previousPosition: Position; + type: TreeWalkerValueType; + } + + type TreeWalkerValueType = "elementStart" | "elementEnd" | "character" | "text"; + + // engine/model/writer + + class Writer { + // TODO + } +} + +export namespace utils { + // engine/utils/bindtwostepcarettoattribute + + function bindTwoStepCaretToAttribute(view: view.View, model: model.Model, emitter: ckutils.Emitter, attribute: string): void; +} + +export namespace view { + namespace observer { + // engine/view/observer/clickobserver + + class ClickObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/compositionobserver + + class CompositionObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/domeventdata + + class DomEventData { + // TODO + } + + // engine/view/observer/domeventobserver + + class DomEventObserver extends Observer { + readonly domEventType: string | string[]; + useCapture: boolean; + + fire(eventType: string, domEvent: Event, additionalData?: Object): void; + onDomEvent(): void; + } + + // engine/view/observer/fakeselectionobserver + + class FakeSelectionObserver extends Observer { + constructor(view: View); + destroy(): void; + observe(): void; + } + + // engine/view/observer/focusobserver + + class FocusObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/keyobserver + + class KeyEventData extends DomEventData implements ckutils.KeystrokeInfo { + // KeystrokeInfo + altKey?: boolean; + ctrlKey?: boolean; + keyCode: number; + keystroke: number; + shiftKey?: boolean; + } + + class KeyObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/mouseobserver + + class MouseObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/mutationobserver + + class MutationObserver extends Observer { + domConverter: DomConverter; + renderer: Renderer; + } + + interface MutatedChildren { + newChildren: Node[]; + node: Element; + oldChildren: Node[]; + type: string; + } + + interface MutatedText { + newText: string; + node: Text; + oldText: string; + type: string; + } + + // engine/view/observer/observer + + class Observer { + readonly document: Document; + readonly isEnabled: boolean; + readonly view: View; + + constructor(view: View); + destroy(): void; + disable(): void; + enable(): void; + observe(domElement: HTMLElement, name: string): void; + } + + // engine/view/observer/selectionobserver + + class SelectionObserver extends Observer { + readonly domConverter: DomConverter; + readonly mutationObserver: MutationObserver; + readonly selection: DocumentSelection; + } + } + + // engine/view/attributeelement + + class AttributeElement extends Element { + readonly id: string | number; + readonly priority: number; + protected _clonesGroup: Set | null; + protected _id: string | number; + protected _priority: number; + + static DEFAULT_PRIORITY: number; + + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getElementsWithSameId(): Set; + getFillerOffset(): number | null; + isSimilar(otherElement: Element): boolean; + protected _clone(deep: boolean): AttributeElement; + } + + // engine/view/containerelement + + class ContainerElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): number | null; + } + + // engine/view/document + + class Document implements ckutils.Emitter, ckutils.Observable { + readonly isComposing: boolean; + readonly isFocused: boolean; + isReadOnly: boolean; + readonly roots: ckutils.Collection; + readonly selection: DocumentSelection; + + constructor(); + getRoot(name?: string): RootEditableElement | null; + registerPostFixer(postFixer: (downcastWriter: DowncastWriter) => boolean): void; + protected _callPostFixers(writer: DowncastWriter): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + type ChangeType = "children" | "attributes" | "text"; + + // engine/view/documentfragment + + class DocumentFragment { + readonly childCount: number; + readonly isEmpty: boolean; + readonly parent: null; + readonly root: DocumentFragment; + protected _children: Element[]; + + protected constructor(children?: Node | Iterable); + [Symbol.iterator](): Iterator; + _appendChild(items: Item | Iterable): number; + _insertChild(index: number, items: Item | Iterable): number; + _removeChildren(index: number, howMany?: number): Node[]; + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildren(): Iterable; + is(type: string): boolean; + } + + // engine/view/documentselection + + class DocumentSelection { + // TODO + } + + // engine/view/domconverter + + class DomConverter { + // TODO + } + + // engine/view/downcastwriter + + class DowncastWriter { + // TODO + } + + // engine/view/editableelement + + class EditableElement extends ContainerElement { + // TODO + } + + // engine/view/element + + class Element extends Node { + readonly childCount: number; + readonly isEmpty: boolean; + readonly name: string; + protected _attrs: Map; + protected _children: Node[]; + protected _classes: Set; + protected _customProperties: Map; + protected _styles: Map; + + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + _removeChildren(index: number, howMany?: number): Node[]; + _removeClass(className: string[] | string): void; + findAncestor(patterns: Object | string | RegExp | Function): Element | null; + getAttribute(key: string): string | undefined; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildren(): Iterable; + getClassNames(): Iterable; + getCustomProperties(): Iterable; + getCustomProperty(key: string | symbol): any; + getFillerOffset(): void; + getIdentity(): string; + getStyle(property: string): string | undefined; + getStyleNames(): Iterable; + hasAttribute(key: string): boolean; + hasClass(className: string): void; + hasStyle(property: string): void; + is(type: string, name?: string): boolean; + isSimilar(otherElement: Element): boolean; + protected _addClass(className: string[] | string): void; + protected _appendChild(items: Item | Iterable): number; + protected _clone(deep?: boolean): Element; + protected _insertChild(index: number, items: Item | Iterable): number; + protected _removeAttribute(key: string): boolean; + protected _removeCustomProperty(key: string | symbol): boolean; + protected _removeStyle(property: string[] | string): void; + protected _setAttribute(key: string, value: string): void; + protected _setCustomProperty(key: string | symbol, value: any): void; + protected _setStyle(property: string | {[key: string]: string}, value?: string): void; + } + + // engine/view/elementdefinition + + type ElementDefinition = string | { + attributes?: {[key: string]: string}; + classes?: string | string[]; + name: string; + priority?: number; + styles?: {[key: string]: string}; + }; + + // engine/view/emptyelement + + class EmptyElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): null; + } + + // engine/view/filler + + const INLINE_FILLER_LENGTH: number; + + const INLINE_FILLER: string; + + function BR_FILLER(): void; + + function NBSP_FILLER(): void; + + function getDataWithoutFiller(domText: Text): string; + + function injectQuirksHandling(view: View): void; + + function isBlockFiller(domNode: /*TODO globals.*/Node, blockFiller: Function): boolean; + + function isInlineFiller(domText: /*TODO globals.*/Text): boolean; + + function startsWithFiller(domNode: /*TODO globals.*/Text): boolean; + + // engine/view/item + + type Item = Node | TextProxy; + + // engine/view/matcher + + class Matcher { + // TODO + } + + type MatcherPattern = + ((element: Element) => null | {name: boolean; attribute?: string[]; }) | + string | + RegExp | + { + attributes?: {[key: string]: string | RegExp | boolean}; + classes?: string | RegExp | Array; + name?: string | RegExp; + styles?: {[key: string]: string | RegExp}; + }; + + // engine/view/node + + class Node { + readonly document: Document | null; + readonly index: number | null; + readonly nextSibling: Node | null; + readonly parent: Element | DocumentFragment | null; + readonly previousSibling: Node | null; + readonly root: Node | DocumentFragment; + + constructor(); + _fireChange(type: ChangeType, node: Node): void; + getAncestors(options: {includeSelf: boolean, parentFirst?: boolean}): Array; + getCommonAncestor(node: Node, options: {includeSelf?: boolean}): Element | DocumentFragment | null; + getPath(): number[]; + + is(type: "element"): this is Element; + is(type: "containerElement"): this is ContainerElement; + is(type: "attributeElement"): this is AttributeElement; + is(type: "emptyElement"): this is EmptyElement; + is(type: "uiElement"): this is UIElement; + is(type: "documentFragment"): this is DocumentFragment; + is(type: "text"): this is Text; + is(type: "textProxy"): this is TextProxy; + is(type: string, name: string): boolean; + + isAfter(node: Node): boolean; + isBefore(node: Node): boolean; + isSimilar(otherElement: Node): boolean; + toJSON(): object; + protected _clone(): Node; + protected _remove(): void; + } + + // engine/view/placeholder + + function attachPlaceholder(view: View, element: Element, placeholderText: string, checkFunction?: Function): void; + + function detachPlaceholder(view: View, element: Element): void; + + // engine/view/position + + class Position { + // TODO + } + + type PositionRelation = "before" | "after" | "same" | "different"; + + // engine/view/range + + class Range { + // TODO + } + + // engine/view/renderer + + class Renderer { + // TODO + } + + // engine/view/rooteditableelement + + class RootEditableElement extends EditableElement { + // TODO + } + + // engine/view/selection + + class Selection { + // TODO + } + + // engine/view/text + + class Text extends Node { + readonly data: string; + protected _data: string; + protected _textData: string; + + protected constructor(data: string); + isSimilar(otherNode: Text): boolean; + protected _clone(): Text; + } + + // engine/view/textproxy + + class TextProxy { + readonly data: string; + readonly document: Document | null; + readonly isPartial: boolean; + readonly offsetInText: number; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly root: Node | DocumentFragment; + readonly textNode: Text; + + protected constructor(textNode: Text, offsetInText: number, length: number); + getAncestors(options: {includeSelf?: boolean, parentFirst?: boolean}): Array; + is(type: "textProxy"): this is TextProxy; + is(type: string): boolean; + } + + // engine/view/treewalker + + class TreeWalker { + readonly boundaries: Range; + readonly direction: TreeWalkerDirection; + readonly ignoreElementEnd: boolean; + readonly position: Position; + readonly shallow: boolean; + readonly singleCharacters: boolean; + + constructor(options: { + boundaries?: Range, + startPosition?: Position, + direction?: TreeWalkerDirection, + singleCharacters?: boolean, + shallow?: boolean, + ignoreElementEnd?: boolean; + }); + [Symbol.iterator](): Iterator; + next(): TreeWalkerValue; + skip(skip: (treeWalkerValue: TreeWalkerValue) => boolean): void; + } + + type TreeWalkerDirection = "forward" | "backward"; + + interface TreeWalkerValue { + item: Item; + length: number; + nextPosition: Position; + previousPosition: Position; + type: TreeWalkerValueType; + } + + type TreeWalkerValueType = "elementStart" | "elementEnd" | "text"; + + // engine/view/uielement + + class UIElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): null; + render(domDocument: /*TODO: globals.*/Document): HTMLElement; + toDomElement(domDocument: /*TODO: globals.*/Document): HTMLElement; + } + + // engine/view/upcastwriter + + class UpcastWriter { + // TODO + } + + // engine/view/view + + class View implements ckutils.Emitter, ckutils.Observable { + // TODO + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } +} diff --git a/types/ckeditor__ckeditor5-engine/tsconfig.json b/types/ckeditor__ckeditor5-engine/tsconfig.json new file mode 100644 index 0000000000..36da122d77 --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ckeditor__ckeditor5-engine-tests.ts" + ] +} diff --git a/types/ckeditor__ckeditor5-engine/tslint.json b/types/ckeditor__ckeditor5-engine/tslint.json new file mode 100644 index 0000000000..6a214f0cfd --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/tslint.json @@ -0,0 +1,20 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": { + "options": [ + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + }, + "no-empty-interface": false, + "quotemark": [ + true, + "double", + "avoid-escape", + "avoid-template" + ] + } +} diff --git a/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts b/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts index 82c272a6ec..19f21f667a 100644 --- a/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts +++ b/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts @@ -489,24 +489,30 @@ utils.mapsEqual(map, map); // utils/mix ================================================================== -class Editor { - b: () => number; -} - interface SomeMixin { a: () => string; } +class Editor implements SomeMixin { + a: () => string; + b() { return 3; } +} + const SomeMixin = { - a() { - return "a"; - } + a() { return "a"; } +}; + +const SomeMixinNum = { + a() { return 3; } }; utils.mix(Editor, SomeMixin); -const mixEditor = new Editor() as Editor & SomeMixin; -mixEditor.a(); -mixEditor.b(); +// $ExpectError +utils.mix(Editor, SomeMixinNum); + +const editor = new Editor(); +str = editor.a(); +num = editor.b(); // utils/nth ================================================================== diff --git a/types/ckeditor__ckeditor5-utils/index.d.ts b/types/ckeditor__ckeditor5-utils/index.d.ts index 8d9d50e889..50571483f8 100644 --- a/types/ckeditor__ckeditor5-utils/index.d.ts +++ b/types/ckeditor__ckeditor5-utils/index.d.ts @@ -367,7 +367,11 @@ export class KeystrokeHandler { destroy(): void; listenTo(emitter: Emitter): void; press(keyEvtData: KeystrokeInfo): boolean; - set(keystroke: string | Array, callback: Function, options?: {priority?: PriorityString | number}): void; + set( + keystroke: string | Array, + callback: (keyEvtData: KeystrokeInfo, cancel: () => void) => void, + options?: {priority?: PriorityString | number} + ): void; } // utils/locale @@ -392,7 +396,7 @@ export function mapsEqual(mapsA: Map, mapsB: Map): boolean; // utils/mix -export function mix(baseClass: {new(): any}, ...mixins: any[]): void; +export function mix(baseClass: {new(...p: any[]): T}, ...mixins: Array>): void; // utils/nth diff --git a/types/conf/conf-tests.ts b/types/conf/conf-tests.ts index 1da0e4de2d..ce67cd4799 100644 --- a/types/conf/conf-tests.ts +++ b/types/conf/conf-tests.ts @@ -4,18 +4,24 @@ const conf = new Conf(); new Conf({ defaults: { foo: 'bar', - unicorn: 'rainbow' + unicorn: 'rainbow', }, - configName: '', - projectName: 'foo', - cwd: '' }); +new Conf({ configName: '' }); +new Conf({ projectName: 'foo' }); +new Conf({ cwd: '' }); +new Conf({ encryptionKey: '' }); +new Conf({ encryptionKey: new Buffer('') }); +new Conf({ encryptionKey: new Uint8Array([1]) }); +new Conf({ encryptionKey: new DataView(new ArrayBuffer(2)) }); +new Conf({ fileExtension: '.foo' }); + // $ExpectError new Conf({ defaults: { foo: 'bar', - unicorn: ['rainbow'] - } + unicorn: ['rainbow'], + }, }); conf.set('foo', 'bar'); conf.set('hello', 1); @@ -28,10 +34,17 @@ conf.get('foo', null); // $ExpectError conf.delete('foo'); conf.has('foo'); // $ExpectType boolean conf.clear(); +conf.onDidChange('foo', (oldVal, newVal) => { + // $ExpectType string | number | boolean | undefined + oldVal; + // $ExpectType string | number | boolean | undefined + newVal; +}); +conf.size; // $ExpectType number conf.store = { foo: 'bar', - unicorn: 'rainbow' + unicorn: 'rainbow', }; conf.path; // $ExpectType string diff --git a/types/conf/index.d.ts b/types/conf/index.d.ts index e58dc3ede7..57d7285a3e 100644 --- a/types/conf/index.d.ts +++ b/types/conf/index.d.ts @@ -1,31 +1,37 @@ -// Type definitions for conf 1.4 +// Type definitions for conf 2.1 // Project: https://github.com/sindresorhus/conf // Definitions by: Sam Verschueren // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -interface Options { - defaults?: {[key: string]: T}; - configName?: string; - projectName?: string; - cwd?: string; -} +/// declare class Conf implements Iterable<[string, T]> { - store: {[key: string]: T}; + store: { [key: string]: T }; readonly path: string; - readonly size: number; + readonly size: number; - constructor(options?: Options); - get(key: string, defaultValue?: T): T; - set(key: string, val: T): void; - set(object: {[key: string]: T}): void; - has(key: string): boolean; - delete(key: string): void; - clear(): void; - onDidChange(key: string, callback: (oldVal: any, newVal: any) => void): void; - [Symbol.iterator](): Iterator<[string, T]>; + constructor(options?: Conf.Options); + get(key: string, defaultValue?: T): T; + set(key: string, val: T): void; + set(object: { [key: string]: T }): void; + has(key: string): boolean; + delete(key: string): void; + clear(): void; + onDidChange(key: string, callback: (oldVal: T | undefined, newVal: T | undefined) => void): void; + [Symbol.iterator](): Iterator<[string, T]>; +} + +declare namespace Conf { + interface Options { + defaults?: { [key: string]: T }; + configName?: string; + projectName?: string; + cwd?: string; + encryptionKey?: string | Buffer | NodeJS.TypedArray | DataView; + fileExtension?: string; + } } export = Conf; diff --git a/types/conf/tsconfig.json b/types/conf/tsconfig.json index 84d6bf7657..479fa6b41f 100644 --- a/types/conf/tsconfig.json +++ b/types/conf/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "conf-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/conf/v1/conf-tests.ts b/types/conf/v1/conf-tests.ts new file mode 100644 index 0000000000..4ee492da8d --- /dev/null +++ b/types/conf/v1/conf-tests.ts @@ -0,0 +1,41 @@ +import Conf = require('conf'); + +const conf = new Conf(); +new Conf({ + defaults: { + foo: 'bar', + unicorn: 'rainbow', + }, + configName: '', + projectName: 'foo', + cwd: '', +}); +// $ExpectError +new Conf({ + defaults: { + foo: 'bar', + unicorn: ['rainbow'], + }, +}); +conf.set('foo', 'bar'); +conf.set('hello', 1); +conf.set('unicorn', false); +conf.set('null', null); // $ExpectError + +conf.get('foo'); // $ExpectType string | number | boolean +conf.get('foo', 'bar'); // $ExpectType string | number | boolean +conf.get('foo', null); // $ExpectError +conf.delete('foo'); +conf.has('foo'); // $ExpectType boolean +conf.clear(); + +conf.store = { + foo: 'bar', + unicorn: 'rainbow', +}; +conf.path; // $ExpectType string + +for (const [key, value] of conf) { + key; // $ExpectType string + value; // $ExpectType string | number | boolean +} diff --git a/types/conf/v1/index.d.ts b/types/conf/v1/index.d.ts new file mode 100644 index 0000000000..f08cff1584 --- /dev/null +++ b/types/conf/v1/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for conf 1.4 +// Project: https://github.com/sindresorhus/conf +// Definitions by: Sam Verschueren +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface Options { + defaults?: { [key: string]: T }; + configName?: string; + projectName?: string; + cwd?: string; +} + +declare class Conf implements Iterable<[string, T]> { + store: { [key: string]: T }; + readonly path: string; + readonly size: number; + + constructor(options?: Options); + get(key: string, defaultValue?: T): T; + set(key: string, val: T): void; + set(object: { [key: string]: T }): void; + has(key: string): boolean; + delete(key: string): void; + clear(): void; + onDidChange(key: string, callback: (oldVal: any, newVal: any) => void): void; + [Symbol.iterator](): Iterator<[string, T]>; +} + +export = Conf; diff --git a/types/conf/v1/tsconfig.json b/types/conf/v1/tsconfig.json new file mode 100644 index 0000000000..86b3a62f41 --- /dev/null +++ b/types/conf/v1/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "conf": [ + "conf/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "conf-tests.ts" + ] +} diff --git a/types/conf/v1/tslint.json b/types/conf/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/conf/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/d3-hierarchy/d3-hierarchy-tests.ts b/types/d3-hierarchy/d3-hierarchy-tests.ts index 16b372993d..b5982a4d5f 100644 --- a/types/d3-hierarchy/d3-hierarchy-tests.ts +++ b/types/d3-hierarchy/d3-hierarchy-tests.ts @@ -12,6 +12,7 @@ import * as d3Hierarchy from 'd3-hierarchy'; // Preparatory Steps // ----------------------------------------------------------------------- +let str: string; let num: number; let numOrUndefined: number | undefined; let size: [number, number]; @@ -825,22 +826,34 @@ copiedPackNode = packRootNode.copy(); // Pack Siblings and Enclosure // ----------------------------------------------------------------------- -interface CircleData extends d3Hierarchy.PackCircle { - v: string; -} - -let circles: CircleData[] = [ +const radius = [ { r: 10, v: 'a' }, - { r: 1, v: 'b' }, + { r: 30, v: 'b' }, { r: 20, v: 'c' } ]; // packSiblings -circles = d3Hierarchy.packSiblings(circles); +const circles = d3Hierarchy.packSiblings(radius); +str = circles[0].v; +num = circles[0].r; +num = circles[0].x; +num = circles[0].y; // packEnclose -let enclosure: { r: number, x: number, y: number }; +const moreCircles = [ + { r: 10, v: 'a', x: 0, y: 10 }, + { r: 30, v: 'b', x: 5, y: 15 }, + { r: 20, v: 'c', x: 7, y: 30 } +]; -enclosure = d3Hierarchy.packEnclose(circles); +const circle = d3Hierarchy.packEnclose(moreCircles); +num = circle.r; +num = circle.x; +num = circle.y; +// $ExpectError +str = circle.v; // fails, property 'v' does not exist + +// $ExpectError +d3Hierarchy.packEnclose(radius); diff --git a/types/d3-hierarchy/index.d.ts b/types/d3-hierarchy/index.d.ts index 0ec823cc78..fb5ebd5656 100644 --- a/types/d3-hierarchy/index.d.ts +++ b/types/d3-hierarchy/index.d.ts @@ -802,7 +802,7 @@ export function pack(): PackLayout; // Pack Siblings and Enclosure // ----------------------------------------------------------------------- -export interface PackCircle { +export interface PackRadius { /** * The radius of the circle. */ @@ -819,10 +819,25 @@ export interface PackCircle { y?: number; } +export interface PackCircle { + /** + * The radius of the circle. + */ + r: number; + + /** + * The x-coordinate of the circle’s center. + */ + x: number; + + /** + * The y-coordinate of the circle’s center. + */ + y: number; +} + // TODO: Since packSiblings manipulates the circles array in place, technically the x and y properties // are optional on invocation, but will be created after execution for each entry. -// For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment -// on the mandatory nature, then to create separate interfaces and having to deal with recasting. /** * Packs the specified array of circles, each of which must have a `circle.r` property specifying the circle’s radius. @@ -830,7 +845,7 @@ export interface PackCircle { * * @param circles The specified array of circles to pack. */ -export function packSiblings(circles: Datum[]): Datum[]; +export function packSiblings(circles: Datum[]): Array; /** * Computes the smallest circle that encloses the specified array of circles, each of which must have @@ -839,4 +854,4 @@ export function packSiblings(circles: Datum[]): Datum[ * * @param circles The specified array of circles to pack. */ -export function packEnclose(circles: Datum[]): { r: number, x: number, y: number }; +export function packEnclose(circles: Datum[]): PackCircle; diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index c758e83448..42393b9e82 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -9,7 +9,7 @@ import * as d3Zoom from 'd3-zoom'; import { ArrayLike, select, Selection, event } from 'd3-selection'; import { Transition } from 'd3-transition'; -import { scaleLinear, ScaleLinear } from 'd3-scale'; +import { scaleLinear, ScaleLinear, ScaleTime, scaleTime } from 'd3-scale'; import { interpolateZoom, interpolate, interpolateArray, ZoomInterpolator, ZoomView } from 'd3-interpolate'; // -------------------------------------------------------------------------- @@ -248,15 +248,15 @@ let zoomInterpolatorFactory: (a: ZoomView, b: ZoomView) => ZoomInterpolator; // Basic case without casting basicInterpolatorFactory = svgZoom.interpolate(); -// Assuming it is know that a specialized interpolation factory was used. E.g. ZoomInterpolator also has a duration -// argument +// Assuming it is know that a specialized interpolation factory was used. E.g. ZoomInterpolator also has a duration argument zoomInterpolatorFactory = svgZoom.interpolate<(a: ZoomView, b: ZoomView) => ZoomInterpolator>(); // on() -------------------------------------------------------------------- // chainable svgZoom = svgZoom.on('zoom', zoomedSVGOverlay); -// svgZoom = svgZoom.on('zoom', zoomedCanvas); // fails, zoom event handler has wrong this and datum type +// $ExpectError +svgZoom = svgZoom.on('zoom', zoomedCanvas); // fails, zoom event handler has wrong this and datum type let zoomHandler: ((this: SVGRectElement, datum: SVGDatum, index: number, group: SVGRectElement[] | ArrayLike) => void) | undefined; zoomHandler = svgZoom.on('zoom'); @@ -297,7 +297,8 @@ const svgOverlayTransition = svgOverlay.transition(); // use on selection svgZoom.transform(svgOverlay, d3Zoom.zoomIdentity); -// svgZoom.transform(groupsSelection, d3Zoom.zoomIdentity); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.transform(groupsSelection, d3Zoom.zoomIdentity); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.transform(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -308,9 +309,11 @@ svgZoom.transform(svgOverlay, function(datum, index, groups) { console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return d3Zoom.zoomIdentity; }); + // use on transition svgOverlayTransition.call(svgZoom.transform, d3Zoom.zoomIdentity); -// svgZoom.transform(groupsTransition, d3Zoom.zoomIdentity); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.transform(groupsTransition, d3Zoom.zoomIdentity); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.transform(svgOverlayTransition, d3Zoom.zoomIdentity); svgZoom.transform(svgOverlayTransition, function(datum, index, groups) { @@ -327,7 +330,8 @@ svgZoom.transform(svgOverlayTransition, function(datum, index, groups) { // use on selection svgZoom.translateBy(svgOverlay, 20, 50); -// svgZoom.translateBy(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateBy(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.translateBy( svgOverlay, @@ -376,7 +380,8 @@ svgZoom.translateBy( // use on transition svgZoom.translateBy(svgOverlayTransition, 20, 50); -// svgZoom.translateBy(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateBy(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.translateBy( svgOverlayTransition, @@ -427,7 +432,8 @@ svgZoom.translateBy( // use on selection svgZoom.translateTo(svgOverlay, 20, 50); -// svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.translateTo( svgOverlay, @@ -476,7 +482,8 @@ svgZoom.translateTo( // use on transition svgZoom.translateTo(svgOverlayTransition, 20, 50); -// svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.translateTo( svgOverlayTransition, @@ -527,7 +534,8 @@ svgZoom.translateTo( // use on selection svgZoom.scaleBy(svgOverlay, 3); -// svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.scaleBy(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -540,7 +548,8 @@ svgZoom.scaleBy(svgOverlay, function(datum, index, groups) { }); // use on transition svgZoom.scaleBy(svgOverlayTransition, 3); -// svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.scaleBy(svgOverlayTransition, function(datum, index, groups) { const that: SVGRectElement = this; @@ -556,7 +565,8 @@ svgZoom.scaleBy(svgOverlayTransition, function(datum, index, groups) { // use on selection svgZoom.scaleTo(svgOverlay, 3); -// svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.scaleTo(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -569,7 +579,8 @@ svgZoom.scaleTo(svgOverlay, function(datum, index, groups) { }); // use on transition svgZoom.scaleTo(svgOverlayTransition, 3); -// svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.scaleTo(svgOverlayTransition, function(datum, index, groups) { const that: SVGRectElement = this; @@ -616,15 +627,18 @@ const invertedPoint: [number, number] = zTransform.invert([150, 240]); const invertedX: number = zTransform.invertX(150); const invertedY: number = zTransform.invertY(240); -// TODO: reScaleX, reScaleY - let linearScale: ScaleLinear = scaleLinear(); +let timeScale: ScaleTime = scaleTime(); linearScale = zTransform.rescaleX(linearScale); linearScale = zTransform.rescaleY(linearScale); +timeScale = zTransform.rescaleX(timeScale); +timeScale = zTransform.rescaleY(timeScale); + const transformation: string = zTransform.toString(); +zTransform = zTransform.scale(2); zTransform = zTransform.translate(50, 40); // zoomIdentity ------------------------------------------------------------- diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index 827390b871..3f6100d4b8 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for d3JS d3-zoom module 1.7 // Project: https://github.com/d3/d3-zoom/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -26,12 +29,12 @@ export type ZoomedElementBaseType = Element; * that can be passed into zoomTransform methods rescaleX and rescaleY */ export interface ZoomScale { - domain(): number[]; - domain(domain: number[]): this; + domain(): number[] | Date[]; + domain(domain: Array): this; range(): number[]; range(range: number[]): this; copy(): ZoomScale; - invert(value: number): number; + invert(value: number): number | Date; } // -------------------------------------------------------------------------- diff --git a/types/db-migrate-base/db-migrate-base-tests.ts b/types/db-migrate-base/db-migrate-base-tests.ts index e9c46f4873..b094be1280 100644 --- a/types/db-migrate-base/db-migrate-base-tests.ts +++ b/types/db-migrate-base/db-migrate-base-tests.ts @@ -318,4 +318,4 @@ db.runSqlAsync('DROP TABLE `pets`').then(onResolve); /// allAsync(sql, [params]) db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); -db.allAsync('SELECT * FROM `module_user`').then(onResolve); \ No newline at end of file +db.allAsync('SELECT * FROM `module_user`').then(onResolve); diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index fdb89d3823..4e2b45cd55 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -478,6 +478,7 @@ export namespace Ember { const addObserver: typeof EmberObjectObserversNs.addObserver; const removeObserver: typeof EmberObjectObserversNs.removeObserver; const get: typeof EmberObjectNs.get; + const notifyPropertyChange: typeof EmberObjectNs.notifyPropertyChange; const getWithDefault: typeof EmberObjectNs.getWithDefault; const getProperties: typeof EmberObjectNs.getProperties; const setProperties: typeof EmberObjectNs.setProperties; diff --git a/types/ember/test/object.ts b/types/ember/test/object.ts index 060bf8ca81..853ed46d46 100755 --- a/types/ember/test/object.ts +++ b/types/ember/test/object.ts @@ -65,4 +65,11 @@ export class Foo2 extends Ember.Object { name }); } + + bar() { + Ember.notifyPropertyChange(this, 'name'); + Ember.notifyPropertyChange(this); // $ExpectError + Ember.notifyPropertyChange('name'); // $ExpectError + Ember.notifyPropertyChange(this, 'name', 'bar'); // $ExpectError + } } diff --git a/types/ember__object/index.d.ts b/types/ember__object/index.d.ts index f915bdc82a..06e417999d 100644 --- a/types/ember__object/index.d.ts +++ b/types/ember__object/index.d.ts @@ -385,6 +385,8 @@ export function defineProperty( meta?: any ): void; +export function notifyPropertyChange(obj: object, keyName: string): void; + declare module '@ember/utils/-private/types' { interface TypeLookup { class: typeof EmberObject; diff --git a/types/ember__object/test/object.ts b/types/ember__object/test/object.ts index b47aa22ffb..391ac183a9 100644 --- a/types/ember__object/test/object.ts +++ b/types/ember__object/test/object.ts @@ -1,4 +1,4 @@ -import EmberObject, { computed } from "@ember/object"; +import EmberObject, { computed, notifyPropertyChange } from "@ember/object"; const LifetimeHooks = EmberObject.extend({ resource: null as {} | null, @@ -47,6 +47,12 @@ class Foo extends EmberObject { b: 11 }); } + bar() { + notifyPropertyChange(this, 'name'); + notifyPropertyChange(this); // $ExpectError + notifyPropertyChange('name'); // $ExpectError + notifyPropertyChange(this, 'name', 'bar'); // $ExpectError + } } // TODO: enable after TS 3.0 https://github.com/typed-ember/ember-cli-typescript/issues/291 diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 75dee784de..aa69df28ad 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Text } from 'react-native'; +import { Text, AccessibilityInfo } from 'react-native'; import { Accelerometer, @@ -8,40 +8,46 @@ import { AdMobInterstitial, AdMobRewarded, Amplitude, - Asset, - AuthSession, - Audio, AppLoading, + Asset, + Audio, + AuthSession, BarCodeScanner, - BlurViewProps, BlurView, Brightness, + Calendar, Camera, CameraObject, + Constants, DocumentPicker, + EdgeInsets, + EdgePadding, + EventUserLocation, Facebook, FacebookAds, - FileSystem, - ImagePicker, - ImageManipulator, FaceDetector, - Linking, - Svg, + FileSystem, + Haptic, + ImageManipulator, + ImagePicker, IntentLauncherAndroid, KeepAwake, + KmlMapEvent, LinearGradient, + Linking, + Location, + MailComposer, + MapEvent, + MapStyleElement, + MapView, + MediaLibrary, Permissions, PublisherBanner, + Region, registerRootComponent, ScreenOrientation, - SQLite, - Calendar, - MailComposer, - Location, - Updates, - MediaLibrary, - Haptic, - Constants + Svg, + Updates } from 'expo'; const reverseGeocode: Promise = Location.reverseGeocodeAsync({ @@ -837,6 +843,100 @@ async () => { result.status === 'saved'; }; +// #region MapView +const initialRegion: Region = { + latitude: 0, + longitude: 0, + latitudeDelta: 0, + longitudeDelta: 0, +}; + +const edgePadding: EdgePadding = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const edgeInsets: EdgeInsets = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const mapStyleElements: MapStyleElement[] = [{ + featureType: 'featureType', + elementType: 'elementType', + stylers: [{}, {}], +}]; + +const mapEventCallback = (event: MapEvent) => console.log(event); +const regionCallback = (region: Region) => console.log(region); +const kmlCallback = (kml: KmlMapEvent) => console.log(kml); +const userLocationCallback = (event: EventUserLocation) => console.log(event); + +() => ( + ({})} + onKmlReady={kmlCallback} + onRegionChange={regionCallback} + onRegionChangeComplete={regionCallback} + onPress={mapEventCallback} + onLongPress={mapEventCallback} + onUserLocationChange={userLocationCallback} + onPanDrag={mapEventCallback} + onPoiClick={(event: MapEvent<{ placeId: string, name: string }>) => console.log(event)} + onMarkerPress={(event: MapEvent<{ action: 'marker-press', id: string }>) => console.log(event)} + onMarkerSelect={(event: MapEvent<{ action: 'marker-select', id: string }>) => console.log(event)} + onMarkerDeselect={(event: MapEvent<{ action: 'marker-deselect', id: string }>) => console.log(event)} + onCalloutPress={(event: MapEvent<{ action: 'callout-press' }>) => console.log(event)} + onMarkerDragStart={mapEventCallback} + onMarkerDrag={mapEventCallback} + onMarkerDragEnd={mapEventCallback} + + minZoomLevel={0} + maxZoomLevel={0} + kmlSrc="src" + style={{ flex: 1 }} + /> +); +// #endegion + async () => { const updateEventListener: Updates.UpdateEventListener = ({ type, manifest, message }) => { switch (type) { @@ -916,6 +1016,7 @@ async () => { return true; } }; + // #region MediaLibrary async () => { const mlAsset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('localUri'); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 9e48e391d8..55dc4ffd06 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -16,6 +16,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +export * from 'react-native-maps'; +export { default as MapView } from 'react-native-maps'; + import { EventSubscription } from 'fbemitter'; import { Component, ComponentClass, Ref, ComponentType } from 'react'; import { diff --git a/types/expo/package.json b/types/expo/package.json new file mode 100644 index 0000000000..4abdc24638 --- /dev/null +++ b/types/expo/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "react-native-maps": "*" + } +} diff --git a/types/file-type/file-type-tests.ts b/types/file-type/file-type-tests.ts index 640d2c8fb0..d49a964829 100644 --- a/types/file-type/file-type-tests.ts +++ b/types/file-type/file-type-tests.ts @@ -1,6 +1,8 @@ import fileType = require("file-type"); +// $ExpectType FileTypeResult | null fileType(new Buffer([0xFF, 0xD8, 0xFF])); fileType(new Uint8Array([0xFF, 0xD8, 0xFF])); -const minimumBytes: number = fileType.minimumBytes; +// $ExpectType number +fileType.minimumBytes; diff --git a/types/file-type/index.d.ts b/types/file-type/index.d.ts index 2a0deee26a..c902dc384e 100644 --- a/types/file-type/index.d.ts +++ b/types/file-type/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for file-type 5.2 +// Type definitions for file-type 10.6 // Project: https://github.com/sindresorhus/file-type // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk // BendingBender @@ -8,7 +8,17 @@ export = FileType; -declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult; +/** + * The file type is detected by checking the + * [magic number](http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + * + * @param buf It only needs the first `.minimumBytes` bytes. The exception is detection of + * `docx`, `pptx`, and `xlsx` which potentially requires reading the whole file. + * @returns an Object with: + * - ext - One of the [supported file types](https://github.com/sindresorhus/file-type/blob/master/readme.md#supported-file-types) + * - mime - The [MIME type](http://en.wikipedia.org/wiki/Internet_media_type) + */ +declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult | null; declare namespace FileType { interface FileTypeResult { @@ -16,5 +26,9 @@ declare namespace FileType { mime: string; } + /** + * The minimum amount of bytes needed to detect a file type. Currently, + * it's 4100 bytes, but it can change, so don't hard-code it. + */ const minimumBytes: number; } diff --git a/types/file-type/tsconfig.json b/types/file-type/tsconfig.json index 499b81459c..1894b908af 100644 --- a/types/file-type/tsconfig.json +++ b/types/file-type/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "file-type-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 3e323f8c44..ec2359ed5a 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1428,7 +1428,7 @@ export interface RouteOptionsPreObject { /** * key name used to assign the response of the method to in request.pre and request.preResponses. */ - assign: string; + assign?: string; /** * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. */ diff --git a/types/internal-ip/index.d.ts b/types/internal-ip/index.d.ts index a82dd8c913..1bed7e9059 100644 --- a/types/internal-ip/index.d.ts +++ b/types/internal-ip/index.d.ts @@ -1,7 +1,12 @@ -// Type definitions for internal-ip 2.0 +// Type definitions for internal-ip 3.0 // Project: https://github.com/sindresorhus/internal-ip#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function v6(): Promise; -export function v4(): Promise; +export const v6: IPGetterFn; +export const v4: IPGetterFn; + +export interface IPGetterFn { // tslint:disable-line:interface-name + (): Promise; + sync(): string | null; +} diff --git a/types/internal-ip/internal-ip-tests.ts b/types/internal-ip/internal-ip-tests.ts index e94ec9f510..1b383de2f3 100644 --- a/types/internal-ip/internal-ip-tests.ts +++ b/types/internal-ip/internal-ip-tests.ts @@ -1,10 +1,15 @@ import * as internalIp from 'internal-ip'; -let str: string; internalIp.v6().then(ip => { - str = ip; + // $ExpectType string | null + ip; }); +// $ExpectType string | null +internalIp.v6.sync(); internalIp.v4().then(ip => { - str = ip; + // $ExpectType string | null + ip; }); +// $ExpectType string | null +internalIp.v4.sync(); diff --git a/types/internal-ip/tsconfig.json b/types/internal-ip/tsconfig.json index 746718e07c..99d54932e0 100644 --- a/types/internal-ip/tsconfig.json +++ b/types/internal-ip/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "internal-ip-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/internal-ip/v2/index.d.ts b/types/internal-ip/v2/index.d.ts new file mode 100644 index 0000000000..a82dd8c913 --- /dev/null +++ b/types/internal-ip/v2/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for internal-ip 2.0 +// Project: https://github.com/sindresorhus/internal-ip#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function v6(): Promise; +export function v4(): Promise; diff --git a/types/internal-ip/v2/internal-ip-tests.ts b/types/internal-ip/v2/internal-ip-tests.ts new file mode 100644 index 0000000000..e94ec9f510 --- /dev/null +++ b/types/internal-ip/v2/internal-ip-tests.ts @@ -0,0 +1,10 @@ +import * as internalIp from 'internal-ip'; + +let str: string; +internalIp.v6().then(ip => { + str = ip; +}); + +internalIp.v4().then(ip => { + str = ip; +}); diff --git a/types/internal-ip/v2/tsconfig.json b/types/internal-ip/v2/tsconfig.json new file mode 100644 index 0000000000..bae5b7feb8 --- /dev/null +++ b/types/internal-ip/v2/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "internal-ip": [ + "internal-ip/v2" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "internal-ip-tests.ts" + ] +} diff --git a/types/internal-ip/v2/tslint.json b/types/internal-ip/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/internal-ip/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery/JQuery.d.ts b/types/jquery/JQuery.d.ts index 78602a2d8b..cbcc12d956 100644 --- a/types/jquery/JQuery.d.ts +++ b/types/jquery/JQuery.d.ts @@ -7304,10 +7304,12 @@ $( "body" ).on( "click", "p", foo ); $( "body" ).off( "click", "p", foo ); ``` */ - off(events: string, + off( + events: TType, selector: JQuery.Selector, - handler: JQuery.TypeEventHandler | - false): this; + handler: JQuery.TypeEventHandler | + false + ): this; /** * Remove an event handler. * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as @@ -7337,10 +7339,12 @@ $( "form" ).on( "keypress.validator", "input[type='text']", validate ); $( "form" ).off( ".validator" ); ``` */ - off(events: string, + off( + events: TType, selector_handler?: JQuery.Selector | - JQuery.TypeEventHandler | - false): this; + JQuery.TypeEventHandler | + false + ): this; /** * Remove an event handler. * @param events An object where the string keys represent one or more space-separated event types and optional @@ -11968,9 +11972,10 @@ $( "p" ).bind( "click", foo ); // ... Now foo will be called when paragraphs are $( "p" ).unbind( "click", foo ); // ... foo will no longer be called. ``` */ - unbind(event: string, - handler: JQuery.TypeEventHandler | - false + unbind( + event: TType, + handler: JQuery.TypeEventHandler | + false ): this; /** * Remove a previously-attached event handler from the elements. @@ -12062,10 +12067,11 @@ $( "body" ).delegate( "p", "click", foo ); $( "body" ).undelegate( "p", "click", foo ); ``` */ - undelegate(selector: JQuery.Selector, - eventType: string, - handler: JQuery.TypeEventHandler | - false + undelegate( + selector: JQuery.Selector, + eventType: TType, + handler: JQuery.TypeEventHandler | + false ): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. diff --git a/types/jquery/JQueryStatic.d.ts b/types/jquery/JQueryStatic.d.ts index 20d3a9e8c5..4ba7653e69 100644 --- a/types/jquery/JQueryStatic.d.ts +++ b/types/jquery/JQueryStatic.d.ts @@ -148,21 +148,26 @@ $( "div", xml.responseXML ); $( document.body ).css( "background", "black" ); ``` */ - // Using a unified signature is not possible due to a TypeScript 2.4 bug (DefinitelyTyped#27810) - (element: T): JQuery; + // NOTE: `HTMLSelectElement` is both an Element and an Array-Like Object but jQuery treats it as an Element. + (element: HTMLSelectElement): JQuery; /** * Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. - * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + * @param element_elementArray _@param_ `element_elementArray` + *
+ * * `element` — A DOM element to wrap in a jQuery object.
+ * * `elementArray` — An array containing a set of DOM elements to wrap in a jQuery object. * @see \`{@link https://api.jquery.com/jQuery/ }\` * @since 1.0 + * @example ​ ````Set the background color of the page to black. +```javascript +$( document.body ).css( "background", "black" ); +``` * @example ​ ````Hide all the input elements within a form. ```javascript $( myForm.elements ).hide(); ``` */ - // Using a unified signature is not possible due to a TypeScript 2.4 bug (DefinitelyTyped#27810) - // tslint:disable-next-line:unified-signatures - (elementArray: T[]): JQuery; + (element_elementArray: T | ArrayLike): JQuery; /** * Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. * @param selection An existing jQuery object to clone. diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index b1f63f3ecf..9e4dea80ee 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -160,6 +160,9 @@ function JQueryStatic() { // $ExpectType JQuery $([new HTMLSelectElement()]); + // $ExpectType JQuery + $(document.querySelectorAll('p')); + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/19597#issuecomment-378218432 function issue_19597_378218432() { const myDiv = $(document.createElement('div')); @@ -3969,12 +3972,17 @@ function JQuery() { function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } + // $ExpectType JQuery $('table').off('myEvent', 'td', defaultData); // $ExpectType JQuery $('table').off('myEvent', 'td', customData); + // $ExpectType JQuery + $('table').off('mousedown', 'td', specificEventType); + // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -3987,6 +3995,9 @@ function JQuery() { // $ExpectType JQuery $('table').off('myEvent', customData); + // $ExpectType JQuery + $('table').off('mousedown', specificEventType); + // $ExpectType JQuery $('table').off('myEvent', false); @@ -4486,12 +4497,17 @@ function JQuery() { function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } + // $ExpectType JQuery $('p').unbind('myEvent', defaultData); // $ExpectType JQuery $('p').unbind('myEvent', customData); + // $ExpectType JQuery + $('p').unbind('mousedown', specificEventType); + // $ExpectType JQuery $('p').unbind('myEvent', false); @@ -4511,12 +4527,17 @@ function JQuery() { function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } + // $ExpectType JQuery $('table').undelegate('td', 'click', defaultData); // $ExpectType JQuery $('table').undelegate('td', 'click', customData); + // $ExpectType JQuery + $('table').undelegate('td', 'mousedown', specificEventType); + // $ExpectType JQuery $('table').undelegate('td', 'click', false); diff --git a/types/match-media-mock/match-media-mock-tests.ts b/types/match-media-mock/match-media-mock-tests.ts index dc35cff40b..25fe411dd1 100644 --- a/types/match-media-mock/match-media-mock-tests.ts +++ b/types/match-media-mock/match-media-mock-tests.ts @@ -7,7 +7,7 @@ matchMediaMock('(max-width: 991px)').matches // false matchMediaMock('(max-width: 1240px)').matches // true const mediaQueryList = matchMediaMock('(max-width: 991px)'); -const listener = (mql: MediaQueryList) => { }; +const listener = function (this: MediaQueryList) { }; mediaQueryList.addListener(listener) mediaQueryList.removeListener(listener) diff --git a/types/materialize-css/autoinit.d.ts b/types/materialize-css/autoinit.d.ts new file mode 100644 index 0000000000..c3e9009b1d --- /dev/null +++ b/types/materialize-css/autoinit.d.ts @@ -0,0 +1,6 @@ +declare namespace M { + /** + * Automatically initialize components. + */ + function AutoInit(context?: Element): void; +} diff --git a/types/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index f8502cafb4..3be768a216 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -9,6 +9,7 @@ /// /// +/// /// /// /// diff --git a/types/node/inspector.d.ts b/types/node/inspector.d.ts index 3a2bb35afe..a9d0f1140a 100644 --- a/types/node/inspector.d.ts +++ b/types/node/inspector.d.ts @@ -1912,6 +1912,90 @@ declare module "inspector" { } } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + + interface StartParameterType { + traceConfig: TraceConfig; + } + + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + + namespace NodeWorker { + type WorkerID = string; + + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + /** * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. */ @@ -1958,6 +2042,7 @@ declare module "inspector" { * `messageAdded` notification. */ post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** * Continues execution until specific location is reached. */ @@ -2155,6 +2240,7 @@ declare module "inspector" { * Steps over the statement. */ post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** * Enables console to refer to the node with given id via $x (see Command Line API for more details * $x functions). @@ -2193,6 +2279,7 @@ declare module "inspector" { post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; @@ -2250,6 +2337,7 @@ declare module "inspector" { * @experimental */ post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + /** * Add handler to promise with given promise object id. */ @@ -2360,11 +2448,47 @@ declare module "inspector" { * @experimental */ post(method: "Runtime.terminateExecution", callback?: (err: Error | null) => void): void; + /** * Returns supported domains. */ post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + // Events addListener(event: string, listener: (...args: any[]) => void): this; @@ -2464,6 +2588,33 @@ declare module "inspector" { */ addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; emit(event: "Console.messageAdded", message: InspectorNotification): boolean; @@ -2486,6 +2637,11 @@ declare module "inspector" { emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; emit(event: "Runtime.executionContextsCleared"): boolean; emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; on(event: string, listener: (...args: any[]) => void): this; @@ -2584,6 +2740,33 @@ declare module "inspector" { */ on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; /** @@ -2681,6 +2864,33 @@ declare module "inspector" { */ once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; /** @@ -2778,6 +2988,33 @@ declare module "inspector" { */ prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; /** @@ -2874,6 +3111,33 @@ declare module "inspector" { * call). */ prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; } // Top Level API diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 37f8272e87..e2e24dad68 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -4725,6 +4725,10 @@ import * as constants from 'constants'; const pauseReason: string = message.params.reason; }); session.on('Debugger.resumed', () => {}); + // Node Inspector events + session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { + const value: Array<{}> = message.params.value; + }); } } diff --git a/types/node/scripts/generate-inspector/event-emitter.ts b/types/node/scripts/generate-inspector/event-emitter.ts index 658109d6b2..3d3410633f 100644 --- a/types/node/scripts/generate-inspector/event-emitter.ts +++ b/types/node/scripts/generate-inspector/event-emitter.ts @@ -66,10 +66,11 @@ export const createListeners = (events: Event[]): string[] => { "", ...createListenerBlockFn("prependOnceListener")(events), ].reduce((acc, next, index, arr) => { - // removes trailing and consecutive empty lines + // removes leading, trailing and consecutive empty lines + const isFirst = index === 0; const isLast = index === arr.length - 1; const followsEmptyLine = acc.length > 0 && acc[acc.length - 1] === ""; - if ((isLast || followsEmptyLine) && next === "") { + if ((isFirst || isLast || followsEmptyLine) && next === "") { return acc; } else { acc.push(next); diff --git a/types/node/scripts/generate-inspector/generate-substitute-args.ts b/types/node/scripts/generate-inspector/generate-substitute-args.ts index 0054e9a85c..cd12eff1a8 100644 --- a/types/node/scripts/generate-inspector/generate-substitute-args.ts +++ b/types/node/scripts/generate-inspector/generate-substitute-args.ts @@ -4,17 +4,21 @@ import { capitalize, createDocs, flattenArgs, hasElements, isObjectReference } f const INDENT = " "; +// Turns a type into a type representing an array of that type +const arrify = (typeString: string) => { + return typeString === '{}' ? `Array<${typeString}>` : `${typeString}[]`; +} + // Converts DevTools type to TS type const createTypeString = (type: schema.Field, domain?: string): string => { return isObjectReference(type) ? type.$ref : - type.type === "any" ? "any" : + type.type === "any" ? "any" : type.type === "integer" ? "number" : type.type === "number" ? "number" : type.type === "boolean" ? "boolean" : type.type === "string" ? "string" : - type.type === "array" ? `${createTypeString(type.items, domain)}[]` : - type.type === "object" ? "{}" // this code path is likely never exercised - : "never"; + type.type === "array" ? arrify(createTypeString(type.items, domain)) : + type.type === "object" ? "{}" : "never"; // "never" has yet to be observed }; // Helper for createInterface -- constructs a list of interface fields @@ -138,7 +142,7 @@ export const generateSubstituteArgs = (protocol: schema.Schema): { [propName: st .map(item => item.commands .map(command => createPostFunctions(command, item.domain)) .reduce(flattenArgs(""), [])) - .reduce(flattenArgs(), []); + .reduce(flattenArgs(""), []); const eventOverloads: string[] = createListeners(protocol.domains .map(item => { diff --git a/types/node/scripts/generate-inspector/index.ts b/types/node/scripts/generate-inspector/index.ts index eb5da5ef2e..f555105e37 100644 --- a/types/node/scripts/generate-inspector/index.ts +++ b/types/node/scripts/generate-inspector/index.ts @@ -2,25 +2,55 @@ // [tag] corresponds to a tag name in the node-core repository. import { execSync } from "child_process"; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; +import { existsSync, readFileSync, writeFileSync } from "fs"; import * as https from "https"; import * as schema from "./devtools-protocol-schema"; import { generateSubstituteArgs } from "./generate-substitute-args"; -import { flattenArgs, substitute, trimRight } from "./utils"; +import { substitute, trimRight } from "./utils"; +import { string } from "parsimmon"; + +const httpsGet = (url: string) => new Promise((resolve, reject) => { + https.get(url, res => { + const frames: Buffer[] = []; + res.on("data", (data: Buffer) => { + frames.push(data); + }); + res.on("end", () => { + resolve(Buffer.concat(frames).toString("utf8")); + }); + res.on("error", (err: Error) => { + reject(err); + }); + }); +}); // Input arguments const tag = process.argv[2] || process.version; -const PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/deps/v8/src/inspector/js_protocol.json`; - -const devToolsPath = `${__dirname}/../../node_modules/devtools-protocol`; - -function writeProtocolToFile(json: string) { - const protocol: schema.Schema = JSON.parse(json); +const V8_PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/deps/v8/src/inspector/js_protocol.json`; +const NODE_PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/src/inspector/node_protocol.pdl`; +const INSPECTOR_PROTOCOL_REMOTE = `https://chromium.googlesource.com/deps/inspector_protocol`; +const INSPECTOR_PROTOCOL_LOCAL_DIR = "/tmp/inspector_protocol"; +/** + * Given a list of Inspector protocol definitions, write an inspector.d.ts + * containing all of those definitions merged together. + * @param jsonProtocols A list of Inspector protocol definitions. + */ +function writeProtocolsToFile(jsonProtocols: string[]) { + const combinedProtocol: schema.Schema = { + version: { major: '', minor: '' }, // doesn't matter + domains: [] + }; + for (const json of jsonProtocols) { + if (json) { + const protocol: schema.Schema = JSON.parse(json); + combinedProtocol.domains.push(...protocol.domains); + } + } + const substituteArgs = generateSubstituteArgs(combinedProtocol); const template = readFileSync(`${__dirname}/inspector.d.ts.template`, "utf8"); - - const substituteArgs = generateSubstituteArgs(protocol); + const inspectorDts = substitute(template, substituteArgs).split("\n") .map(line => trimRight(line)) .join("\n"); @@ -28,12 +58,24 @@ function writeProtocolToFile(json: string) { writeFileSync("./inspector.d.ts", inspectorDts, "utf8"); } -https.get(PROTOCOL_URL, res => { - const frames: Buffer[] = []; - res.on("data", (data: Buffer) => { - frames.push(data); - }); - res.on("end", () => { - writeProtocolToFile(Buffer.concat(frames).toString("utf8")); - }); -}); +/** + * Given a PDL-formatted string, return a JSON-formatted string. + * Note that this function run blocking shell commands, as it depends on an + * external script to do the conversion. + * @param pdl A PDL-formatted string. + */ +function convertPdlToJson(pdl: string): string { + if (!existsSync(INSPECTOR_PROTOCOL_LOCAL_DIR)) { + execSync(`git clone ${INSPECTOR_PROTOCOL_REMOTE} ${INSPECTOR_PROTOCOL_LOCAL_DIR}`); + } + writeFileSync("/tmp/inspector_protocol.pdl", pdl); + execSync(`${INSPECTOR_PROTOCOL_LOCAL_DIR}/convert_protocol_to_json.py /tmp/inspector_protocol.pdl /tmp/inspector_protocol.json`); + return readFileSync("/tmp/inspector_protocol.json", 'utf8'); +} + +// "Main" -- get the V8 built-in inspector protocol definition, as well as the +// Node extensions, and then write this to inspector.d.ts. +Promise.all([ + httpsGet(V8_PROTOCOL_URL), + httpsGet(NODE_PROTOCOL_URL).then(convertPdlToJson).catch(() => '') +]).then(writeProtocolsToFile).catch(console.error); diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 3e7f64375f..b8b06bd1f2 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -9421,7 +9421,7 @@ declare namespace Office { } /** - * The InternetHeaders object represents properties that are preserved after the item leaves Exchange and converted to a MIME message. + * The InternetHeaders object represents properties that are preserved after the message item leaves Exchange and is converted to a MIME message. * These properties are stored as x-headers in the MIME message. * * InternetHeaders are stored as key/value pairs on a per-item basis. @@ -15225,7 +15225,7 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read * * Item IDs retrieved via EWS or via the itemId property use a different format than the format used by REST APIs (such as the - * {@link https://docs.microsoft.com/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations | Outlook Mail API} or the {@link http://graph.microsoft.io/ | Microsoft Graph}. + * {@link https://docs.microsoft.com/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations | Outlook Mail API} or the {@link https://graph.microsoft.io/ | Microsoft Graph}. * The convertToRestId method converts an EWS-formatted ID into the proper format for REST. * * @param itemId An item ID formatted for Exchange Web Services (EWS) diff --git a/types/public-ip/index.d.ts b/types/public-ip/index.d.ts index 463a1a2d18..58fb81aa93 100644 --- a/types/public-ip/index.d.ts +++ b/types/public-ip/index.d.ts @@ -1,12 +1,16 @@ -// Type definitions for public-ip 2.3 +// Type definitions for public-ip 2.4 // Project: https://github.com/sindresorhus/public-ip#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function v4(options?: Options): Promise; -export function v6(options?: Options): Promise; +export function v4(options?: Options): CancelablePromise; +export function v6(options?: Options): CancelablePromise; export interface Options { https?: boolean; timeout?: number; } + +export type CancelablePromise = Promise & { + cancel(): void; +}; diff --git a/types/public-ip/public-ip-tests.ts b/types/public-ip/public-ip-tests.ts index e7e0540bbe..6e5983bc99 100644 --- a/types/public-ip/public-ip-tests.ts +++ b/types/public-ip/public-ip-tests.ts @@ -1,16 +1,17 @@ import * as publicIp from 'public-ip'; -let str: string; publicIp.v4().then(ip => { - str = ip; + ip; // $ExpectType string }); -publicIp.v4({https: false, timeout: 10}).then(ip => { - str = ip; +publicIp.v4({ https: false, timeout: 10 }).then(ip => { + ip; // $ExpectType string }); +publicIp.v4().cancel(); publicIp.v6().then(ip => { - str = ip; + ip; // $ExpectType string }); -publicIp.v6({https: false, timeout: 10}).then(ip => { - str = ip; +publicIp.v6({ https: false, timeout: 10 }).then(ip => { + ip; // $ExpectType string }); +publicIp.v6().cancel(); diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index e727155520..5f07b253f3 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -15,6 +15,10 @@ import * as React from "react"; import * as Popper from "popper.js"; +export function registerLocale(localeName: string, localeData: {}): void; +export function setDefaultLocale(localeName: string): void; +export function getDefaultLocale(): string; + export interface ReactDatePickerProps { adjustDateOnChange?: boolean; allowSameDay?: boolean; @@ -24,6 +28,7 @@ export interface ReactDatePickerProps { calendarContainer?(props: { children: React.ReactNode[] }): React.ReactNode; children?: React.ReactNode; className?: string; + clearButtonTitle?: string; customInput?: React.ReactNode; customInputRef?: string; dateFormat?: string | string[]; @@ -38,6 +43,7 @@ export interface ReactDatePickerProps { filterDate?(date: Date): boolean; fixedHeight?: boolean; forceShowMonthNavigation?: boolean; + formatWeekDay?(date: Date): string; formatWeekNumber?(date: Date): string | number; highlightDates?: Date[]; id?: string; @@ -53,18 +59,19 @@ export interface ReactDatePickerProps { minTime?: Date; monthsShown?: number; name?: string; + nextMonthButtonLabel?: string; onBlur?(event: React.FocusEvent): void; onChange(date: Date | null, event: React.SyntheticEvent | undefined): void; onChangeRaw?(event: React.FocusEvent): void; onClickOutside?(event: React.MouseEvent): void; onFocus?(event: React.FocusEvent): void; + onInputClick?(): void; + onInputError?(err: {code: number; msg: string}): void; onKeyDown?(event: React.KeyboardEvent): void; onMonthChange?(date: Date): void; onSelect?(date: Date, event: React.SyntheticEvent | undefined): void; onWeekSelect?(firstDayOfWeek: Date, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; - onInputClick?(): void; onYearChange?(date: Date): void; - onInputError?(err: {code: number; msg: string}): void; open?: boolean; openToDate?: Date; peekNextMonth?: boolean; @@ -75,7 +82,18 @@ export interface ReactDatePickerProps { popperPlacement?: string; popperProps?: {}; preventOpenOnFocus?: boolean; + previousMonthButtonLabel?: string; readOnly?: boolean; + renderCustomHeader?(params: { + date: Date; + changeYear(year: number): void; + changeMonth(month: number): void; + decreaseMonth(): void; + increaseMonth(): void; + prevMonthButtonDisabled: boolean; + nextMonthButtonDisabled: boolean; + }): React.ReactNode; + renderDayContents?(dayOfMonth: number): React.ReactNode; required?: boolean; scrollableMonthYearDropdown?: boolean; scrollableYearDropdown?: boolean; @@ -104,20 +122,6 @@ export interface ReactDatePickerProps { weekLabel?: string; withPortal?: boolean; yearDropdownItemNumber?: number; - formatWeekDay?(date: Date): string; - clearButtonTitle?: string; - previousMonthButtonLabel?: string; - nextMonthButtonLabel?: string; - renderCustomHeader?(params: { - date: Date; - changeYear(year: number): void; - changeMonth(month: number): void; - decreaseMonth(): void; - increaseMonth(): void; - prevMonthButtonDisabled: boolean; - nextMonthButtonDisabled: boolean; - }): React.ReactNode; - renderDayContents?(dayOfMonth: number): React.ReactNode; } declare const ReactDatePicker: React.ClassicComponentClass; export default ReactDatePicker; diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 4a3fd93cac..b47c08ed73 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -1,17 +1,121 @@ import * as React from 'react'; -import DatePicker from 'react-datepicker'; +import DatePicker, { + registerLocale, + setDefaultLocale, + getDefaultLocale, +} from 'react-datepicker'; + +registerLocale('en-GB', { options: { weekStartsOn: 1 } }); +setDefaultLocale('en-GB'); +const defaultLocale = getDefaultLocale();

} + className="" + clearButtonTitle="" + customInput={} + customInputRef="" + dateFormat="" + dateFormatCalendar="" + dayClassName={date => ''} + disabled + disabledKeyboardNavigation + dropdownMode="scroll" + endDate={new Date()} + excludeDates={[new Date()]} + excludeTimes={[new Date()]} + filterDate={date => true} + fixedHeight + forceShowMonthNavigation + formatWeekDay={date => ''} + formatWeekNumber={date => 0} + highlightDates={[new Date()]} + id="" + includeDates={[new Date()]} + includeTimes={[new Date()]} + injectTimes={[new Date()]} + inline + isClearable + locale="" + maxDate={new Date()} + maxTime={new Date()} + minDate={new Date()} + minTime={new Date()} + monthsShown={1} + name="" + nextMonthButtonLabel="" + onBlur={event => null} onChange={(date: Date | null) => {}} + onChangeRaw={event => null} + onClickOutside={event => null} + onFocus={event => null} + onInputClick={() => null} + onInputError={err => err.code + err.msg} + onKeyDown={event => null} + onMonthChange={date => null} + onSelect={(date, event) => null} + onWeekSelect={(firstDayOfWeek, weekNumber, event) => null} onYearChange={(date: Date) => {}} + open + openToDate={new Date()} + peekNextMonth + placeholderText="" + popperClassName="" + popperContainer={props =>
} popperModifiers={{ flip: { - enabled: false - } + enabled: false, + }, }} - includeTimes={[new Date()]} + popperPlacement="" + popperProps={{}} + preventOpenOnFocus + previousMonthButtonLabel="" + readOnly + renderCustomHeader={({ + date, + changeYear, + changeMonth, + decreaseMonth, + increaseMonth, + prevMonthButtonDisabled, + nextMonthButtonDisabled, + }) =>
} + renderDayContents={dayOfMonth =>
} + required + scrollableMonthYearDropdown + scrollableYearDropdown + selected={new Date()} + selectsEnd + selectsStart + shouldCloseOnSelect + showDisabledMonthNavigation + showMonthDropdown + showMonthYearDropdown + showTimeSelect + showTimeSelectOnly + showWeekNumbers + showYearDropdown + startDate={new Date()} + startOpen + tabIndex={1} + timeCaption="" + timeFormat="" + timeIntervals={1} + title="" + todayButton={
} + useShortMonthInDropdown + useWeekdaysShort + value="" + weekLabel="" + withPortal + yearDropdownItemNumber={1} > -
- +
+ ; diff --git a/types/react-table/lib/hoc/selectTable.d.ts b/types/react-table/lib/hoc/selectTable.d.ts index fd6d9bf42c..d1fc5d8392 100644 --- a/types/react-table/lib/hoc/selectTable.d.ts +++ b/types/react-table/lib/hoc/selectTable.d.ts @@ -1,4 +1,4 @@ -import { ComponentType } from 'react'; +import { ComponentType, ComponentClass } from 'react'; import { TableProps } from '../../index'; @@ -49,8 +49,8 @@ export interface SelectTableHOCOptions { } declare function selectTableHOC>( - Component: ComponentType, + WrappedComponent: ComponentType, options?: SelectTableHOCOptions -): ComponentType; +): ComponentClass; export default selectTableHOC; diff --git a/types/react-table/lib/hoc/treeTable.d.ts b/types/react-table/lib/hoc/treeTable.d.ts index 35d1522119..e696ceda02 100644 --- a/types/react-table/lib/hoc/treeTable.d.ts +++ b/types/react-table/lib/hoc/treeTable.d.ts @@ -1,9 +1,9 @@ -import { ComponentType } from 'react'; +import { ComponentType, ComponentClass } from 'react'; import { TableProps } from '../../index'; declare function treeTableHOC>( - Component: ComponentType -): ComponentType; + WrappedComponent: ComponentType +): ComponentClass; export default treeTableHOC; diff --git a/types/react-table/test/select-table-tests.tsx b/types/react-table/test/select-table-tests.tsx index a4ed4d4f25..fe4ee5c694 100644 --- a/types/react-table/test/select-table-tests.tsx +++ b/types/react-table/test/select-table-tests.tsx @@ -52,6 +52,7 @@ ReactDOM.render( {...selectTableAdditionalProps} data={data} columns={columns} + ref={React.createRef()} />, document.getElementById('root') ); diff --git a/types/react-table/test/tree-table-tests.tsx b/types/react-table/test/tree-table-tests.tsx index a099124c61..6bb9461f78 100644 --- a/types/react-table/test/tree-table-tests.tsx +++ b/types/react-table/test/tree-table-tests.tsx @@ -4,7 +4,7 @@ import * as ReactDOM from 'react-dom'; import ReactTable, { Column } from 'react-table'; import treeTableHOC from 'react-table/lib/hoc/treeTable'; -const SelectTable = treeTableHOC(ReactTable); +const TreeTable = treeTableHOC(ReactTable); const data = [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }]; @@ -14,6 +14,6 @@ const columns: Column[] = [ ]; ReactDOM.render( - , + , document.getElementById('root') ); diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 0ee637ab5a..fc9ec4f15f 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -273,10 +273,10 @@ declare module 'recompose' { // fromRenderProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#fromrenderprops export function fromRenderProps( - RenderPropsComponent: StatelessComponent, - propsMapper: (props: TRenderProps) => Partial, + RenderPropsComponent: Component, + propsMapper: (props: TRenderProps) => TInner, renderPropName?: string - ): ComponentEnhancer; + ): ComponentEnhancer; // Static property helpers: https://github.com/acdlite/recompose/blob/master/docs/API.md#static-property-helpers diff --git a/types/recompose/recompose-tests.tsx b/types/recompose/recompose-tests.tsx index a0ba38a87a..53cf796fd6 100644 --- a/types/recompose/recompose-tests.tsx +++ b/types/recompose/recompose-tests.tsx @@ -521,18 +521,30 @@ function testFromRenderProps() { interface InnerProps { renderValue: string; - outterValue: number; } interface OutterProps { outterValue: number; } - const RenderPropComponent: React.StatelessComponent<{ - render: (renderProps: RenderProps) => React.ReactElement; - }> = ({ render }) => render({ value: 'test' }); + interface ComponentProps { + renderValue: string; + outterValue: number; + } - const component: React.StatelessComponent = ({ renderValue }) =>
{renderValue}
; + interface RenderComponentProps { + render: (renderProps: RenderProps) => React.ReactElement; + } + + class RenderPropComponent extends React.Component { + render () { + return this.props.render({ value: 'test' }); + } + } + + const component: React.StatelessComponent = ({ outterValue, renderValue }) => ( +
{outterValue}{renderValue}
+ ); const Enhanced = fromRenderProps( RenderPropComponent, diff --git a/types/redux-action/index.d.ts b/types/redux-action/index.d.ts index dc5b9e5229..51c3cc3b61 100644 --- a/types/redux-action/index.d.ts +++ b/types/redux-action/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/coderhaoxin/redux-action // Definitions by: newraina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /** * inspired by @types/redux-actions, thanks. diff --git a/types/redux-action/package.json b/types/redux-action/package.json index 0a14f5edc6..7cc600c266 100644 --- a/types/redux-action/package.json +++ b/types/redux-action/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "redux": "^3.6.0", - "redux-thunk": "^2.2.0" + "redux": "^4.0.1" } } diff --git a/types/redux-action/redux-action-tests.ts b/types/redux-action/redux-action-tests.ts index 2290ed9a3f..d1b065c08f 100644 --- a/types/redux-action/redux-action-tests.ts +++ b/types/redux-action/redux-action-tests.ts @@ -1,5 +1,4 @@ import * as ReduxAction from 'redux-action'; -import * as ReduxThunk from 'redux-thunk'; import * as Redux from 'redux'; interface Payload { @@ -11,7 +10,7 @@ const dispatch: Redux.Dispatch = (...args: any[]): any => { }; const actionCreator0 = ReduxAction.createAction('get items'); -dispatch(actionCreator0(1)) +actionCreator0(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: Payload = action.payload; @@ -19,7 +18,7 @@ dispatch(actionCreator0(1)) const actionCreator1 = ReduxAction.createAction(); -dispatch(actionCreator1(1)) +actionCreator1(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: Payload = action.payload; @@ -27,7 +26,7 @@ dispatch(actionCreator1(1)) const actionCreator2 = ReduxAction.createAction('get items', (name: string) => name); -dispatch(actionCreator2(1)) +actionCreator2(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -35,7 +34,7 @@ dispatch(actionCreator2(1)) const actionCreator3 = ReduxAction.createAction('get items', (name: string) => Promise.resolve(name)); -dispatch(actionCreator3(1)) +actionCreator3(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -43,7 +42,7 @@ dispatch(actionCreator3(1)) const actionCreator4 = ReduxAction.createAction((name: string) => name); -dispatch(actionCreator4(1)) +actionCreator4(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -51,7 +50,7 @@ dispatch(actionCreator4(1)) const actionCreator5 = ReduxAction.createAction((name: string) => 1); -dispatch(actionCreator5('items')) +actionCreator5('items')(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: number = action.payload; @@ -59,7 +58,7 @@ dispatch(actionCreator5('items')) const actionCreator6 = ReduxAction.createAction((name: string) => 1); -dispatch(actionCreator6('items', false)) +actionCreator6('items', false)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: number = action.payload; @@ -80,4 +79,4 @@ const reducer = ReduxAction.createReducer({ name: 'name' }, { } }); -const combinedReducer: Redux.Reducer = Redux.combineReducers({ reducer }); +const combinedReducer: Redux.Reducer<{ reducer: State }> = Redux.combineReducers<{ reducer: State }>({ reducer }); diff --git a/types/slate-react/index.d.ts b/types/slate-react/index.d.ts index 540316befc..30e54f2a02 100644 --- a/types/slate-react/index.d.ts +++ b/types/slate-react/index.d.ts @@ -6,7 +6,7 @@ // Patrick Sachs // Brandon Shelton // Irwan Fario Subastian -// Sebastian Greaves +// Hanna Greaves // Francesco Agnoletto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -18,8 +18,7 @@ import { Block, Inline, Operations, - Schema, - Stack, + SchemaProperties, Value, Operation, MarkProperties, @@ -112,7 +111,7 @@ export interface BasicEditorProps { plugins?: Plugin[]; readOnly?: boolean; role?: string; - schema?: Schema; + schema?: SchemaProperties; spellCheck?: boolean; style?: React.CSSProperties; tabIndex?: number; @@ -121,15 +120,11 @@ export interface BasicEditorProps { export type EditorProps = BasicEditorProps & Plugin; export interface EditorState { - schema: Schema; value: Value; - stack: Stack; } export class Editor extends React.Component implements Controller { controller: CoreEditor; - schema: Schema; - stack: Stack; readonly plugins: Plugin[]; readonly operations: Immutable.List; @@ -137,7 +132,7 @@ export class Editor extends React.Component implements readonly value: Value; // Instance methods - resolveController(plugins: Plugin[], schema: Schema, commands: any[], queries: any[]): void; + resolveController(plugins: Plugin[], schema: SchemaProperties, commands: any[], queries: any[]): void; // Controller addMark: CoreEditor['addMark']; diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 9ee697cb43..2538bea6f9 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -53,39 +53,9 @@ export interface SchemaProperties { inlines?: RulesByNodeType; } -export class Schema extends Immutable.Record({}) { - stack: Stack; - rules: Rules[]; - - static create(properties: SchemaProperties | Schema): Schema; - static fromJSON(object: SchemaProperties): Schema; - static fromJS(object: SchemaProperties): Schema; - static isSchema(maybeSchema: any): maybeSchema is Schema; - - validateNode(node: Node): Error | void; - testNode(node: Node): boolean; - assertNode(node: Node): boolean; - getNodeRules(node: Node): any[]; - isVoid(node: Node): boolean; - isAtomic(mark: Mark): boolean; - normalizeNode(node: Node): () => void; - testRules(object: any, rules: object | any[]): boolean; - validateRules( - object: any, - rule: object | any[], - rules: any[] | null, - options?: object - ): Error | void; - - toJSON(): SchemaProperties; - toJS(): SchemaProperties; -} - export interface ValueProperties { document?: Document; selection?: Selection; - history?: History; - schema?: Schema; data?: Data; decorations?: Immutable.List | null; } @@ -93,8 +63,6 @@ export interface ValueProperties { export interface ValueJSON { document?: DocumentJSON; selection?: Selection; - history?: History; - schema?: Schema; data?: Data; decorations?: Immutable.List | null; object?: "value"; @@ -105,8 +73,6 @@ export type Path = Immutable.List | string; export class Value extends Immutable.Record({}) { document: Document; selection: Selection; - history: History; - schema: Schema; data: Data; object: "value"; decorations: Immutable.List; @@ -350,9 +316,6 @@ export class Text extends Immutable.Record({}) { ): Text; splitText(offset: number): Text[]; mergeText(text: Text): Text; - normalize(schema: Schema): () => void | null; - validate(schema: Schema): Error | null; - getFirstInvalidNode(schema: Schema): Text | null; setLeaves(leaves: Immutable.List): Text; } @@ -446,13 +409,12 @@ declare class BaseNode< getChild(path: Path): Node | null; getClosestBlock(path: Path): Block | null; getClosestInline(path: Path): Inline | null; - getClosestVoid(path: Path, schema: Schema): Node | null; + getClosestVoid(key: string | Path): Node | null; getClosest(path: Path, iterator: (node: Node) => boolean): Node | null; getCommonAncestor(a: Path, b: Path): Node; - getDecorations(stack: Stack): Immutable.List; + getDecorations(editor: Editor): Immutable.List; getDepth(path: Path, startAt?: number): number; getDescendant(path: Path): Node | null; - getFirstInvalidNode(schema: Schema): Node | null; getFirstText(): Text | null; getFragmentAtRange(range: Range): Document; getFurthest(path: Path, iterator: (node: Node) => boolean): Node | null; @@ -514,7 +476,7 @@ declare class BaseNode< hasInlineChildren(): boolean; hasDescendant(path: Path): boolean; hasNode(path: Path): boolean; - hasVoidParent(path: Path, schema: Schema): boolean; + hasVoidParent(path: Path, editor: Editor): boolean; insertNode(path: Path, node: Node): Node; insertText( path: Path, @@ -528,7 +490,7 @@ declare class BaseNode< mapDescendants(iterator: () => void): Node; mergeNode(path: Path): Node; moveNode(path: Path, newPath: Path, newIndex?: number): Node; - normalize(schema: Schema): () => void | void; + normalize(editor: Editor): () => void | void; refinedNOde(path: Path, key: string): Node | null; refindPath(path: Path, key: string): Immutable.List | null; regenerateKey(): Node; @@ -548,7 +510,7 @@ declare class BaseNode< properties: MarkProperties ): Node; splitNode(path: Path, position: number, properties: NodeProperties): Node; - validate(schema: Schema): Error | void; + validate(editor: Editor): Error | void; } export interface MarkProperties { @@ -914,61 +876,6 @@ export interface Operations { invert: (operation: Operation) => Operation; } -export interface StackProperties { - plugins?: any[]; -} - -export interface StackJSON { - object: "stack"; - plugins: any[]; -} - -export class Stack extends Immutable.Record({}) { - object: "stack"; - plugins: any[]; - - static create(attrs: StackProperties): Stack; - static isStack(maybeStack: any): maybeStack is Stack; - - static fromJSON(properties: StackJSON): Stack; - static fromJS(properties: StackJSON): Stack; - toJSON(options: any): object; -} - -export interface HistoryProperties { - undos?: Operation[]; - redos?: Operation[]; -} - -export interface HistoryJSON { - object: "history"; - undos: any[]; - redos: any[]; -} - -export interface HistoryOptions { - merge?: boolean; - skip?: boolean; -} - -export class History extends Immutable.Record({}) { - redos: Stack; - undos: Stack; - object: "history"; - - static create(attrs: History | HistoryProperties): History; - static createOperationsList( - oeprations?: Immutable.List | Operation[] - ): Immutable.List; - static fromJSON(object: HistoryJSON): History; - static fromJS(object: HistoryJSON): History; - static isHistory(maybeHistory: any): maybeHistory is History; - - save(operation: Operation, options?: HistoryOptions): History; - toJSON(): HistoryJSON; - toJS(): HistoryJSON; -} - export type ErrorCode = | "child_object_invalid" | "child_required" diff --git a/types/subsume/index.d.ts b/types/subsume/index.d.ts index 7ec2f9d568..e42c97cd4f 100644 --- a/types/subsume/index.d.ts +++ b/types/subsume/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for subsume 1.0 +// Type definitions for subsume 2.0 // Project: https://github.com/sindresorhus/subsume#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,6 +7,7 @@ export = Subsume; declare class Subsume { static parse(text: string, id: string): Subsume.ParseResult; + static parseAll(text: string, ids?: string[]): Subsume.ParseResults; id: string; prefix: string; @@ -23,4 +24,9 @@ declare namespace Subsume { data?: string; rest: string; } + + interface ParseResults { + data: Map; + rest: string; + } } diff --git a/types/subsume/subsume-tests.ts b/types/subsume/subsume-tests.ts index 263553733a..56234d275b 100644 --- a/types/subsume/subsume-tests.ts +++ b/types/subsume/subsume-tests.ts @@ -18,5 +18,13 @@ res; // $ExpectType ParseResult res.data; // $ExpectType string | undefined res.rest; // $ExpectType string -const input = 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; -Subsume.parse(text, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult +const input = + 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; +Subsume.parse(input, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult + +const input2 = + 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## ' + + 'random@@[7febcd0b3806fbc48c01d7cea4ed1218]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1218]## ' + + 'text@@[7febcd0b3806fbc48c01d7cea4ed1217]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1217]##'; +Subsume.parseAll(input2); // $ExpectType ParseResults +Subsume.parseAll(input2, ['7febcd0b3806fbc48c01d7cea4ed1219']); // $ExpectType ParseResults diff --git a/types/subsume/tsconfig.json b/types/subsume/tsconfig.json index b29ec71ee8..7eefbf76e9 100644 --- a/types/subsume/tsconfig.json +++ b/types/subsume/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "subsume-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/subsume/v1/index.d.ts b/types/subsume/v1/index.d.ts new file mode 100644 index 0000000000..7ec2f9d568 --- /dev/null +++ b/types/subsume/v1/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for subsume 1.0 +// Project: https://github.com/sindresorhus/subsume#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Subsume; + +declare class Subsume { + static parse(text: string, id: string): Subsume.ParseResult; + + id: string; + prefix: string; + postfix: string; + regex: RegExp; + + constructor(id?: string); + compose(text: string): string; + parse(text: string): Subsume.ParseResult; +} + +declare namespace Subsume { + interface ParseResult { + data?: string; + rest: string; + } +} diff --git a/types/subsume/v1/subsume-tests.ts b/types/subsume/v1/subsume-tests.ts new file mode 100644 index 0000000000..263553733a --- /dev/null +++ b/types/subsume/v1/subsume-tests.ts @@ -0,0 +1,22 @@ +import Subsume = require('subsume'); + +const subsume = new Subsume(); +new Subsume('foo'); + +subsume.id; // $ExpectType string +subsume.prefix; // $ExpectType string +subsume.postfix; // $ExpectType string +subsume.regex; // $ExpectType RegExp + +const text = subsume.compose('🦄'); +text; // $ExpectType string + +const output = `some${text} random text`; + +const res = subsume.parse(output); +res; // $ExpectType ParseResult +res.data; // $ExpectType string | undefined +res.rest; // $ExpectType string + +const input = 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; +Subsume.parse(text, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult diff --git a/types/subsume/v1/tsconfig.json b/types/subsume/v1/tsconfig.json new file mode 100644 index 0000000000..0e0565e161 --- /dev/null +++ b/types/subsume/v1/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "subsume": [ + "subsume/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "subsume-tests.ts" + ] +} diff --git a/types/subsume/v1/tslint.json b/types/subsume/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/subsume/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 2e4cad4929..08b64250c8 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -24,6 +24,7 @@ // Julian Strecker // Zhang Hao // Konstantin Lukaschenko +// Daniel Yim // Definitions: https://github.com//DefinitelyTyped // TypeScript Version: 2.8 @@ -45,6 +46,7 @@ export * from "./three-FirstPersonControls"; export * from "./three-gltfexporter"; export * from "./three-gltfloader"; export * from "./three-lensflare"; +export * from "./three-mapcontrols"; export * from "./three-maskpass"; export * from "./three-mtlloader"; export * from "./three-objloader"; diff --git a/types/three/three-mapcontrols.d.ts b/types/three/three-mapcontrols.d.ts new file mode 100644 index 0000000000..66ff8a0982 --- /dev/null +++ b/types/three/three-mapcontrols.d.ts @@ -0,0 +1,71 @@ +import { + Camera, + EventDispatcher, + MOUSE, + Object3D, + Vector3 +} from "./three-core"; + +export class MapControls extends EventDispatcher { + constructor(object: Camera, domElement?: HTMLElement); + + object: Camera; + domElement: HTMLElement | HTMLDocument; + + // API + enabled: boolean; + target: Vector3; + + enableZoom: boolean; + zoomSpeed: number; + minDistance: number; + maxDistance: number; + enableRotate: boolean; + rotateSpeed: number; + enablePan: boolean; + keyPanSpeed: number; + maxZoom: number; + minZoom: number; + panSpeed: number; + autoRotate: boolean; + autoRotateSpeed: number; + minPolarAngle: number; + maxPolarAngle: number; + minAzimuthAngle: number; + maxAzimuthAngle: number; + enableKeys: boolean; + screenSpacePanning: boolean; + keys: { LEFT: number; UP: number; RIGHT: number; BOTTOM: number }; + mouseButtons: { LEFT: MOUSE; MIDDLE: MOUSE; RIGHT: MOUSE }; + enableDamping: boolean; + dampingFactor: number; + target0: Vector3; + position0: Vector3; + zoom0: number; + + rotateLeft(angle?: number): void; + + rotateUp(angle?: number): void; + + panLeft(distance?: number): void; + + panUp(distance?: number): void; + + pan(deltaX: number, deltaY: number): void; + + dollyIn(dollyScale: number): void; + + dollyOut(dollyScale: number): void; + + saveState(): void; + + update(): boolean; + + reset(): void; + + dispose(): void; + + getPolarAngle(): number; + + getAzimuthalAngle(): number; +} diff --git a/types/universal-router/index.d.ts b/types/universal-router/index.d.ts index eb698fc8bf..8dd2357f03 100644 --- a/types/universal-router/index.d.ts +++ b/types/universal-router/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for universal-router 6.0 +// Type definitions for universal-router 7.0 // Project: https://github.com/kriasoft/universal-router // Definitions by: Jack Moore // Tomek Łaziuk // Lodin +// acidghost // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -101,7 +102,7 @@ export interface Options { context?: C; baseUrl?: string; resolveRoute?: (context: ActionContext & C, params: Params) => any; - errorHandler?: (error: Error & { context: C, code: number }) => any; + errorHandler?: (error: Error & { status: number }, context: C) => any; } /** diff --git a/types/universal-router/universal-router-tests.ts b/types/universal-router/universal-router-tests.ts index 02c79fb062..40b5ac32c1 100644 --- a/types/universal-router/universal-router-tests.ts +++ b/types/universal-router/universal-router-tests.ts @@ -12,10 +12,10 @@ new UniversalRouter( user: 'name', }, baseUrl: '/base', - errorHandler: (error) => { + errorHandler: (error, context) => { console.error(error); - console.dir(error.context); - return error.code === 404 + console.dir(context); + return error.status === 404 ? '

Page Not Found

' : '

Oops! Something went wrong

'; }, diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 408e434441..b40fedfd46 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -3501,20 +3501,20 @@ declare namespace wx { */ interface InputEvent extends BuiltInEvent< - "input", - { - value: string; - cursor: number; - } - > {} + "input", + { + value: string; + cursor: number; + } + > {} interface FormEvent extends BuiltInEvent< - "form", - { - value: { [name: string]: string | boolean | number }; - } - > {} + "form", + { + value: { [name: string]: string | boolean | number }; + } + > {} interface ScrollEvent extends BuiltInEvent<"scroll", {}> {} @@ -3528,12 +3528,12 @@ declare namespace wx { interface TouchEvent extends BuiltInEvent< - T, - { - x: number; - y: number; - } - > { + T, + { + x: number; + y: number; + } + > { touches: Touch[]; changedTouches: Touch[]; } @@ -4096,6 +4096,79 @@ declare namespace wx { } // #endregion // #region App里的onLaunch、onShow回调参数 + + type SceneValues = + | 1001 + | 1005 + | 1006 + | 1007 + | 1008 + | 1011 + | 1012 + | 1013 + | 1014 + | 1017 + | 1019 + | 1020 + | 1022 + | 1023 + | 1024 + | 1025 + | 1026 + | 1027 + | 1028 + | 1029 + | 1030 + | 1031 + | 1032 + | 1034 + | 1035 + | 1036 + | 1037 + | 1038 + | 1039 + | 1042 + | 1043 + | 1044 + | 1045 + | 1046 + | 1047 + | 1048 + | 1049 + | 1052 + | 1053 + | 1054 + | 1056 + | 1057 + | 1058 + | 1059 + | 1064 + | 1067 + | 1068 + | 1069 + | 1071 + | 1072 + | 1073 + | 1074 + | 1077 + | 1078 + | 1079 + | 1081 + | 1082 + | 1084 + | 1089 + | 1090 + | 1091 + | 1092 + | 1095 + | 1096 + | 1097 + | 1099 + | 1102 + | 1103 + | 1104 + | number; + interface LaunchOptions { /** * 打开小程序的路径 @@ -4107,8 +4180,78 @@ declare namespace wx { query: object; /** * 打开小程序的[场景值](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/app-service/scene.html) + * + * - 1001: 发现栏小程序主入口,「最近使用」列表(基础库2.2.4版本起包含「我的小程序」列表) + * - 1005: 顶部搜索框的搜索结果页 + * - 1006: 发现栏小程序主入口搜索框的搜索结果页 + * - 1007: 单人聊天会话中的小程序消息卡片 + * - 1008: 群聊会话中的小程序消息卡片 + * - 1011: 扫描二维码 + * - 1012: 长按图片识别二维码 + * - 1013: 手机相册选取二维码 + * - 1014: 小程序模板消息 + * - 1017: 前往体验版的入口页 + * - 1019: 微信钱包 + * - 1020: 公众号 profile 页相关小程序列表 + * - 1022: 聊天顶部置顶小程序入口 + * - 1023: 安卓系统桌面图标 + * - 1024: 小程序 profile 页 + * - 1025: 扫描一维码 + * - 1026: 附近小程序列表 + * - 1027: 顶部搜索框搜索结果页「使用过的小程序」列表 + * - 1028: 我的卡包 + * - 1029: 卡券详情页 + * - 1030: 自动化测试下打开小程序 + * - 1031: 长按图片识别一维码 + * - 1032: 手机相册选取一维码 + * - 1034: 微信支付完成页 + * - 1035: 公众号自定义菜单 + * - 1036: App 分享消息卡片 + * - 1037: 小程序打开小程序 + * - 1038: 从另一个小程序返回 + * - 1039: 摇电视 + * - 1042: 添加好友搜索框的搜索结果页 + * - 1043: 公众号模板消息 + * - 1044: 带 shareTicket 的小程序消息卡片 [详情]((转发#获取更多转发信息)) + * - 1045: 朋友圈广告 + * - 1046: 朋友圈广告详情页 + * - 1047: 扫描小程序码 + * - 1048: 长按图片识别小程序码 + * - 1049: 手机相册选取小程序码 + * - 1052: 卡券的适用门店列表 + * - 1053: 搜一搜的结果页 + * - 1054: 顶部搜索框小程序快捷入口 + * - 1056: 音乐播放器菜单 + * - 1057: 钱包中的银行卡详情页 + * - 1058: 公众号文章 + * - 1059: 体验版小程序绑定邀请页 + * - 1064: 微信连Wi-Fi状态栏 + * - 1067: 公众号文章广告 + * - 1068: 附近小程序列表广告 + * - 1069: 移动应用 + * - 1071: 钱包中的银行卡列表页 + * - 1072: 二维码收款页面 + * - 1073: 客服消息列表下发的小程序消息卡片 + * - 1074: 公众号会话下发的小程序消息卡片 + * - 1077: 摇周边 + * - 1078: 连Wi-Fi成功页 + * - 1079: 微信游戏中心 + * - 1081: 客服消息下发的文字链 + * - 1082: 公众号会话下发的文字链 + * - 1084: 朋友圈广告原生页 + * - 1089: 微信聊天主界面下拉,「最近使用」栏(基础库2.2.4版本起包含「我的小程序」栏) + * - 1090: 长按小程序右上角菜单唤出最近使用历史 + * - 1091: 公众号文章商品卡片 + * - 1092: 城市服务入口 + * - 1095: 小程序广告组件 + * - 1096: 聊天记录 + * - 1097: 微信支付签约页 + * - 1099: 页面内嵌插件 + * - 1102: 公众号 profile 页服务预览 + * - 1103: 发现栏小程序主入口,「我的小程序」列表(基础库2.2.4版本起废弃) + * - 1104: 微信聊天主界面下拉,「我的小程序」栏(基础库2.2.4版本起废弃) */ - scene: number; + scene: SceneValues; /** * shareTicket,详见 获取更多[转发信息](https://mp.weixin.qq.com/debug/wxadoc/dev/api/share.html#获取更多转发信息) */ diff --git a/types/wx-js-sdk-dt/index.d.ts b/types/wx-js-sdk-dt/index.d.ts index 23b5388336..3f09527450 100644 --- a/types/wx-js-sdk-dt/index.d.ts +++ b/types/wx-js-sdk-dt/index.d.ts @@ -617,6 +617,14 @@ declare namespace wx { * 支付成功后的回调函数 */ success(res: any): void; + /** + * 支付取消后的回调函数 + */ + cancel?(res: any): void; + /** + * 支付失败后的回调函数 + */ + fail?(res: any): void; } /** diff --git a/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts b/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts index deeb753b29..212c9a79c1 100644 --- a/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts +++ b/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts @@ -61,7 +61,9 @@ wx.chooseWXPay({ nonceStr: '', package: '', paySign: '', - success: (res) => {} + success: (res) => {}, + cancel: (res) => {}, + fail: (res) => {} }); wx.getLocation({