diff --git a/notNeededPackages.json b/notNeededPackages.json index 4a3280ccb0..f5abb1bec7 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1,11 +1,23 @@ { "packages": [ + { + "libraryName": "ag-grid", + "typingsPackageName": "ag-grid", + "sourceRepoURL": "https://github.com/ceolter/ag-grid", + "asOfVersion": "3.2.0" + }, { "libraryName": "ajv", "typingsPackageName": "ajv", "sourceRepoURL": "https://github.com/epoberezkin/ajv", "asOfVersion": "1.0.0" }, + { + "libraryName": "angular-ui-router-default", + "typingsPackageName": "angular-ui-router-default", + "sourceRepoURL": "https://github.com/nonplus/angular-ui-router-default", + "asOfVersion": "0.0.5" + }, { "libraryName": "antd", "typingsPackageName": "antd", @@ -60,6 +72,12 @@ "sourceRepoURL": "http://www.babylonjs.com/", "asOfVersion": "2.4.1" }, + { + "libraryName": "base64url", + "typingsPackageName": "base64url", + "sourceRepoURL": "https://github.com/brianloveswords/base64url", + "asOfVersion": "2.0.0" + }, { "libraryName": "BigInteger.js", "typingsPackageName": "big-integer", diff --git a/types/ag-grid/ag-grid-tests.ts b/types/ag-grid/ag-grid-tests.ts deleted file mode 100644 index 7c4ebb0c8c..0000000000 --- a/types/ag-grid/ag-grid-tests.ts +++ /dev/null @@ -1,136 +0,0 @@ - -checkGridOptions({}); -checkColDef({}); - -function checkGridOptions(gridOptions: ag.grid.GridOptions): void { - - gridOptions.virtualPaging = true; - gridOptions.toolPanelSuppressPivot = true; - gridOptions.toolPanelSuppressValues = true; - gridOptions.rowsAlreadyGrouped = true; - gridOptions.suppressRowClickSelection = true; - gridOptions.suppressCellSelection = true; - gridOptions.sortingOrder = ['asc','desc']; - gridOptions.suppressMultiSort = true; - gridOptions.suppressHorizontalScroll = true; - gridOptions.unSortIcon = true; - gridOptions.rowHeight = 0; - gridOptions.rowBuffer = 0; - gridOptions.enableColResize = true; - gridOptions.enableCellExpressions = true; - gridOptions.enableSorting = true; - gridOptions.enableServerSideSorting = true; - gridOptions.enableFilter = true; - gridOptions.enableServerSideFilter = true; - gridOptions.colWidth = 0; - gridOptions.suppressMenuHide = true; - gridOptions.singleClickEdit = true; - gridOptions.debug = true; - gridOptions.icons = {}; - gridOptions.angularCompileRows = true; - gridOptions.angularCompileFilters = true; - gridOptions.angularCompileHeaders = true; - gridOptions.localeText = {}; - gridOptions.localeTextFunc = function() {} - gridOptions.suppressScrollLag = true; - gridOptions.groupSuppressAutoColumn = true; - gridOptions.groupSelectsChildren = true; - gridOptions.groupHidePivotColumns = true; - gridOptions.groupIncludeFooter = true; - gridOptions.groupUseEntireRow = true; - gridOptions.groupSuppressRow = true; - gridOptions.groupSuppressBlankHeader = true; - gridOptions.forPrint = true; - gridOptions.groupColumnDef = {}; - gridOptions.context = {}; - gridOptions.rowStyle = {color: 'red'}; - gridOptions.rowClass = 'green'; - gridOptions.groupDefaultExpanded = false; - gridOptions.slaveGrids = []; - gridOptions.rowSelection = 'single'; - gridOptions.rowDeselection = true; - gridOptions.rowData = []; - gridOptions.floatingTopRowData = []; - gridOptions.floatingBottomRowData = []; - gridOptions.showToolPanel = true; - gridOptions.groupKeys = ['a','b'] - gridOptions.groupAggFields = ['a','b'] - gridOptions.columnDefs = []; - gridOptions.datasource = {}; - gridOptions.pinnedColumnCount = 0; - gridOptions.groupHeaders = true; - gridOptions.headerHeight = 0; - gridOptions.groupRowInnerRenderer = function(params) {}; - gridOptions.groupRowRenderer = {}; - gridOptions.isScrollLag = function() {return true;} - gridOptions.isExternalFilterPresent = function() { return true; }; - gridOptions.doesExternalFilterPass = function(node: ag.grid.RowNode) { return false; }; - gridOptions.getRowStyle = function() {}; - gridOptions.getRowClass = function() {}; - gridOptions.headerCellRenderer = function() {}; - gridOptions.groupAggFunction = function(nodes: any[]) {}; - gridOptions.onReady = function(api: any) {}; - gridOptions.onModelUpdated = function() {}; - gridOptions.onCellClicked = function(params) {}; - gridOptions.onCellDoubleClicked = function(params) {}; - gridOptions.onCellContextMenu = function(params) {}; - gridOptions.onCellValueChanged = function(params) {}; - gridOptions.onCellFocused = function(params) {}; - gridOptions.onRowSelected = function(params) {}; - gridOptions.onSelectionChanged = function() {}; - gridOptions.onBeforeFilterChanged = function() {}; - gridOptions.onAfterFilterChanged = function() {}; - gridOptions.onFilterModified = function() {}; - gridOptions.onBeforeSortChanged = function() {}; - gridOptions.onAfterSortChanged = function() {}; - gridOptions.onVirtualRowRemoved = function(params) {}; - gridOptions.onRowClicked = function(params) {}; - gridOptions.api = null; - gridOptions.columnApi = null; - -} - -function checkColDef(colDef: ag.grid.ColDef): void { - - colDef.sort = 'test'; - colDef.sortedAt = 0; - colDef.sortingOrder = ['asc','desc']; - colDef.headerName = 'test'; - colDef.field = 'test'; - colDef.headerValueGetter = 'test'; - colDef.colId = 'test'; - colDef.hide = true; - colDef.headerTooltip = 'test'; - colDef.valueGetter = 'test'; - colDef.headerCellRenderer = {}; - colDef.headerClass = 'test'; - colDef.width = 0; - colDef.minWidth = 0; - colDef.maxWidth = 0; - colDef.cellClass = 'test'; - colDef.cellStyle = {color: 'test'}; - colDef.cellRenderer = function() {}; - colDef.floatingCellRenderer = function() {}; - colDef.aggFunc = 'test'; - colDef.comparator = function() {}; - colDef.checkboxSelection = true; - colDef.suppressMenu = true; - colDef.suppressSorting = true; - colDef.unSortIcon = true; - colDef.suppressSizeToFit = true; - colDef.suppressResize = true; - colDef.headerGroup = 'test'; - colDef.headerGroupShow = 'test'; - colDef.editable = true; - colDef.newValueHandler = function() {}; - colDef.volatile = true; - colDef.template = 'test'; - colDef.templateUrl = 'test'; - colDef.filter = 'test'; - colDef.filterParams = {}; - colDef.onCellValueChanged = function() {}; - colDef.onCellClicked = function() {}; - colDef.onCellDoubleClicked = function() {}; - colDef.onCellContextMenu = function() {}; - colDef.cellClassRules = {}; -} diff --git a/types/ag-grid/index.d.ts b/types/ag-grid/index.d.ts deleted file mode 100644 index 3fe37571b1..0000000000 --- a/types/ag-grid/index.d.ts +++ /dev/null @@ -1,1991 +0,0 @@ -// Type definitions for ag-grid v2.1.2 -// Project: http://www.ag-grid.com/ -// Definitions by: Niall Crosby -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace ag.grid { - class ColumnChangeEvent { - private type; - private column; - private columnGroup; - private fromIndex; - private toIndex; - private pinnedColumnCount; - constructor(type: string); - toString(): string; - withColumn(column: Column): ColumnChangeEvent; - withColumnGroup(columnGroup: ColumnGroup): ColumnChangeEvent; - withFromIndex(fromIndex: number): ColumnChangeEvent; - withPinnedColumnCount(pinnedColumnCount: number): ColumnChangeEvent; - withToIndex(toIndex: number): ColumnChangeEvent; - getFromIndex(): number; - getToIndex(): number; - getPinnedColumnCount(): number; - getType(): string; - getColumn(): Column; - getColumnGroup(): ColumnGroup; - isPivotChanged(): boolean; - isValueChanged(): boolean; - isIndividualColumnResized(): boolean; - } -} -declare namespace ag.grid { - class Utils { - private static isSafari; - private static isIE; - static iterateObject(object: any, callback: (key: string, value: any) => void): void; - static cloneObject(object: any): any; - static map(array: TItem[], callback: (item: TItem) => TResult): TResult[]; - static forEach(array: T[], callback: (item: T, index: number) => void): void; - static filter(array: T[], callback: (item: T) => boolean): T[]; - static assign(object: any, source: any): void; - static getFunctionParameters(func: any): any; - static find(collection: any, predicate: any, value: any): any; - static toStrings(array: T[]): string[]; - static iterateArray(array: T[], callback: (item: T, index: number) => void): void; - static isNode(o: any): boolean; - static isElement(o: any): boolean; - static isNodeOrElement(o: any): boolean; - static addChangeListener(element: HTMLElement, listener: EventListener): void; - static makeNull(value: any): any; - static removeAllChildren(node: HTMLElement): void; - static removeElement(parent: HTMLElement, cssSelector: string): void; - static removeFromParent(node: Element): void; - static isVisible(element: HTMLElement): boolean; - /** - * loads the template and returns it as an element. makes up for no simple way in - * the dom api to load html directly, eg we cannot do this: document.createElement(template) - */ - static loadTemplate(template: string): Node; - static querySelectorAll_addCssClass(eParent: any, selector: string, cssClass: string): void; - static querySelectorAll_removeCssClass(eParent: any, selector: string, cssClass: string): void; - static querySelectorAll_replaceCssClass(eParent: any, selector: string, cssClassToRemove: string, cssClassToAdd: string): void; - static addOrRemoveCssClass(element: HTMLElement, className: string, addOrRemove: boolean): void; - static addCssClass(element: HTMLElement, className: string): void; - static offsetHeight(element: HTMLElement): number; - static offsetWidth(element: HTMLElement): number; - static removeCssClass(element: HTMLElement, className: string): void; - static removeFromArray(array: T[], object: T): void; - static defaultComparator(valueA: any, valueB: any): number; - static formatWidth(width: number | string): string; - /** - * Tries to use the provided renderer. - */ - static useRenderer(eParent: Element, eRenderer: (params: TParams) => Node | string, params: TParams): void; - /** - * If icon provided, use this (either a string, or a function callback). - * if not, then use the second parameter, which is the svgFactory function - */ - static createIcon(iconName: any, gridOptionsWrapper: any, colDefWrapper: any, svgFactoryFunc: () => Node): HTMLSpanElement; - static addStylesToElement(eElement: any, styles: any): void; - static getScrollbarWidth(): number; - static isKeyPressed(event: KeyboardEvent, keyToCheck: number): boolean; - static setVisible(element: HTMLElement, visible: boolean): void; - static isBrowserIE(): boolean; - static isBrowserSafari(): boolean; - } -} -declare namespace ag.grid { - class Constants { - static STEP_EVERYTHING: number; - static STEP_FILTER: number; - static STEP_SORT: number; - static STEP_MAP: number; - static ASC: string; - static DESC: string; - static ROW_BUFFER_SIZE: number; - static MIN_COL_WIDTH: number; - static SUM: string; - static MIN: string; - static MAX: string; - static KEY_TAB: number; - static KEY_ENTER: number; - static KEY_BACKSPACE: number; - static KEY_DELETE: number; - static KEY_ESCAPE: number; - static KEY_SPACE: number; - static KEY_DOWN: number; - static KEY_UP: number; - static KEY_LEFT: number; - static KEY_RIGHT: number; - } -} -declare namespace ag.grid { - class Column { - static colIdSequence: number; - colDef: ColDef; - actualWidth: any; - visible: any; - colId: any; - pinned: boolean; - index: number; - aggFunc: string; - pivotIndex: number; - sort: string; - sortedAt: number; - constructor(colDef: ColDef, actualWidth: any); - isGreaterThanMax(width: number): boolean; - getMinimumWidth(): number; - setMinimum(): void; - } -} -declare namespace ag.grid { - class ColumnGroup { - pinned: any; - name: any; - allColumns: Column[]; - displayedColumns: Column[]; - expandable: boolean; - expanded: boolean; - actualWidth: number; - constructor(pinned: any, name: any); - getMinimumWidth(): number; - addColumn(column: any): void; - calculateExpandable(): void; - calculateActualWidth(): void; - calculateDisplayedColumns(): void; - addToVisibleColumns(colsToAdd: any): void; - } -} -declare namespace ag.grid { - class GridOptionsWrapper { - private gridOptions; - private groupHeaders; - private headerHeight; - private rowHeight; - private floatingTopRowData; - private floatingBottomRowData; - init(gridOptions: GridOptions, eventService: EventService): void; - isRowSelection(): boolean; - isRowDeselection(): boolean; - isRowSelectionMulti(): boolean; - getContext(): any; - isVirtualPaging(): boolean; - isShowToolPanel(): boolean; - isToolPanelSuppressPivot(): boolean; - isToolPanelSuppressValues(): boolean; - isRowsAlreadyGrouped(): boolean; - isGroupSelectsChildren(): boolean; - isGroupHidePivotColumns(): boolean; - isGroupIncludeFooter(): boolean; - isGroupSuppressBlankHeader(): boolean; - isSuppressRowClickSelection(): boolean; - isSuppressCellSelection(): boolean; - isSuppressMultiSort(): boolean; - isGroupSuppressAutoColumn(): boolean; - isForPrint(): boolean; - isSuppressHorizontalScroll(): boolean; - isUnSortIcon(): boolean; - isSuppressMenuHide(): boolean; - getRowStyle(): any; - getRowClass(): any; - getRowStyleFunc(): any; - getRowClassFunc(): any; - getHeaderCellRenderer(): any; - getApi(): GridApi; - isEnableColResize(): boolean; - isSingleClickEdit(): boolean; - getGroupDefaultExpanded(): any; - getGroupKeys(): string[]; - getGroupAggFunction(): (nodes: any[]) => any; - getGroupAggFields(): string[]; - getRowData(): any[]; - isGroupUseEntireRow(): boolean; - getGroupColumnDef(): any; - isGroupSuppressRow(): boolean; - isAngularCompileRows(): boolean; - isAngularCompileFilters(): boolean; - isAngularCompileHeaders(): boolean; - isDebug(): boolean; - getColumnDefs(): any[]; - getDatasource(): any; - getRowBuffer(): number; - isEnableSorting(): boolean; - isEnableCellExpressions(): boolean; - isEnableServerSideSorting(): boolean; - isEnableFilter(): boolean; - isEnableServerSideFilter(): boolean; - isSuppressScrollLag(): boolean; - getIcons(): any; - getIsScrollLag(): () => boolean; - getSortingOrder(): string[]; - getSlaveGrids(): GridOptions[]; - getGroupRowRenderer(): Object | Function; - getRowHeight(): number; - getHeaderHeight(): number; - setHeaderHeight(headerHeight: number): void; - isGroupHeaders(): boolean; - setGroupHeaders(groupHeaders: boolean): void; - getFloatingTopRowData(): any[]; - setFloatingTopRowData(rows: any[]): void; - getFloatingBottomRowData(): any[]; - setFloatingBottomRowData(rows: any[]): void; - isExternalFilterPresent(): boolean; - doesExternalFilterPass(node: RowNode): boolean; - getGroupRowInnerRenderer(): (params: any) => void; - getColWidth(): number; - private checkForDeprecated(); - getPinnedColCount(): number; - getLocaleTextFunc(): Function; - globalEventHandler(eventName: string, event?: any): void; - private getCallbackForEvent(eventName); - } -} -declare namespace ag.grid { - class LoggerFactory { - private logging; - init(gridOptionsWrapper: GridOptionsWrapper): void; - create(name: string): Logger; - } - class Logger { - private logging; - private name; - constructor(name: string, logging: boolean); - log(message: string): void; - } -} -declare namespace ag.grid { - class Events { - /** A new set of columns has been entered, everything has potentially changed. */ - static EVENT_COLUMN_EVERYTHING_CHANGED: string; - /** A pivot column was added, removed or order changed. */ - static EVENT_COLUMN_PIVOT_CHANGE: string; - /** A value column was added, removed or agg function was changed. */ - static EVENT_COLUMN_VALUE_CHANGE: string; - /** A column was moved */ - static EVENT_COLUMN_MOVED: string; - /** One or more columns was shown / hidden */ - static EVENT_COLUMN_VISIBLE: string; - /** A column group was opened / closed */ - static EVENT_COLUMN_GROUP_OPENED: string; - /** One or more columns was resized. If just one, the column in the event is set. */ - static EVENT_COLUMN_RESIZED: string; - /** One or more columns was resized. If just one, the column in the event is set. */ - static EVENT_COLUMN_PINNED_COUNT_CHANGED: string; - static EVENT_MODEL_UPDATED: string; - static EVENT_CELL_CLICKED: string; - static EVENT_CELL_DOUBLE_CLICKED: string; - static EVENT_CELL_CONTEXT_MENU: string; - static EVENT_CELL_VALUE_CHANGED: string; - static EVENT_CELL_FOCUSED: string; - static EVENT_ROW_SELECTED: string; - static EVENT_SELECTION_CHANGED: string; - static EVENT_BEFORE_FILTER_CHANGED: string; - static EVENT_AFTER_FILTER_CHANGED: string; - static EVENT_FILTER_MODIFIED: string; - static EVENT_BEFORE_SORT_CHANGED: string; - static EVENT_AFTER_SORT_CHANGED: string; - static EVENT_VIRTUAL_ROW_REMOVED: string; - static EVENT_ROW_CLICKED: string; - static EVENT_READY: string; - } -} -declare namespace ag.grid { - class EventService { - private allListeners; - private globalListeners; - private getListenerList(eventType); - addEventListener(eventType: string, listener: Function): void; - addGlobalListener(listener: Function): void; - removeEventListener(eventType: string, listener: Function): void; - removeGlobalListener(listener: Function): void; - dispatchEvent(eventType: string, event?: any): void; - } -} -declare namespace ag.grid { - class MasterSlaveService { - private gridOptionsWrapper; - private columnController; - private gridPanel; - private logger; - private eventService; - private consuming; - init(gridOptionsWrapper: GridOptionsWrapper, columnController: ColumnController, gridPanel: GridPanel, loggerFactory: LoggerFactory, eventService: EventService): void; - private fireEvent(callback); - private onEvent(callback); - private fireColumnEvent(event); - fireHorizontalScrollEvent(horizontalScroll: number): void; - onScrollEvent(horizontalScroll: number): void; - onColumnEvent(event: ColumnChangeEvent): void; - } -} -declare namespace ag.grid { - class ColumnApi { - private _columnController; - constructor(_columnController: ColumnController); - sizeColumnsToFit(gridWidth: any): void; - hideColumns(colIds: any, hide: any): void; - columnGroupOpened(group: ColumnGroup, newValue: boolean): void; - getColumnGroup(name: string): ColumnGroup; - getDisplayNameForCol(column: any): string; - getColumn(key: any): Column; - setState(columnState: any): void; - getState(): [any]; - isPinning(): boolean; - getVisibleColAfter(col: Column): Column; - getVisibleColBefore(col: Column): Column; - setColumnVisible(column: Column, visible: boolean): void; - getAllColumns(): Column[]; - getDisplayedColumns(): Column[]; - getPivotedColumns(): Column[]; - getValueColumns(): Column[]; - moveColumn(fromIndex: number, toIndex: number): void; - movePivotColumn(fromIndex: number, toIndex: number): void; - setColumnAggFunction(column: Column, aggFunc: string): void; - setColumnWidth(column: Column, newWidth: number): void; - removeValueColumn(column: Column): void; - addValueColumn(column: Column): void; - removePivotColumn(column: Column): void; - setPinnedColumnCount(count: number): void; - addPivotColumn(column: Column): void; - getHeaderGroups(): ColumnGroup[]; - hideColumn(colId: any, hide: any): void; - } - class ColumnController { - private gridOptionsWrapper; - private angularGrid; - private selectionRendererFactory; - private expressionService; - private masterSlaveController; - private allColumns; - private visibleColumns; - private displayedColumns; - private pivotColumns; - private valueColumns; - private columnGroups; - private setupComplete; - private valueService; - private pinnedColumnCount; - private eventService; - constructor(); - init(angularGrid: Grid, selectionRendererFactory: SelectionRendererFactory, gridOptionsWrapper: GridOptionsWrapper, expressionService: ExpressionService, valueService: ValueService, masterSlaveController: MasterSlaveService, eventService: EventService): void; - getColumnApi(): ColumnApi; - isSetupComplete(): boolean; - getHeaderGroups(): ColumnGroup[]; - getPinnedContainerWidth(): number; - addPivotColumn(column: Column): void; - setPinnedColumnCount(count: number): void; - removePivotColumn(column: Column): void; - addValueColumn(column: Column): void; - removeValueColumn(column: Column): void; - private doesColumnExistInGrid(column); - setColumnWidth(column: Column, newWidth: number): void; - private updateGroupWidthsAfterColumnResize(column); - setColumnAggFunction(column: Column, aggFunc: string): void; - movePivotColumn(fromIndex: number, toIndex: number): void; - moveColumn(fromIndex: number, toIndex: number): void; - getBodyContainerWidth(): number; - getValueColumns(): Column[]; - getPivotedColumns(): Column[]; - getDisplayedColumns(): Column[]; - getAllColumns(): Column[]; - setColumnVisible(column: Column, visible: boolean): void; - getVisibleColBefore(col: any): Column; - getVisibleColAfter(col: Column): Column; - isPinning(): boolean; - getState(): [any]; - setState(columnState: any): void; - getColumns(keys: any[]): Column[]; - getColumn(key: any): Column; - getDisplayNameForCol(column: any): string; - getColumnGroup(name: string): ColumnGroup; - onColumnsChanged(): void; - private checkForDeprecatedItems(columnDefs); - columnGroupOpened(group: ColumnGroup, newValue: boolean): void; - hideColumns(colIds: any, hide: any): void; - private updateModel(); - private updateDisplayedColumns(); - sizeColumnsToFit(gridWidth: any): void; - private buildGroups(); - private updateGroups(); - private updateVisibleColumns(); - private updatePinnedColumns(); - private createColumns(colDefs); - private createPivotColumns(); - private createValueColumns(); - private createDummyColumn(field); - private calculateColInitialWidth(colDef); - private getTotalColWidth(includePinned); - } -} -declare namespace ag.grid { - interface CsvExportParams { - skipHeader?: boolean; - skipFooters?: boolean; - skipGroups?: boolean; - fileName?: string; - } - class CsvCreator { - private rowController; - private columnController; - private grid; - private valueService; - constructor(rowController: InMemoryRowController, columnController: ColumnController, grid: Grid, valueService: ValueService); - exportDataAsCsv(params?: CsvExportParams): void; - getDataAsCsv(params?: CsvExportParams): string; - private createValueForGroupNode(node); - private escape(value); - } -} -declare namespace ag.grid { - class ExpressionService { - private expressionToFunctionCache; - private logger; - init(loggerFactory: LoggerFactory): void; - evaluate(expression: string, params: any): any; - private createExpressionFunction(expression); - private createFunctionBody(expression); - } -} -declare namespace ag.grid { - interface TextAndNumberFilterParameters { - /** What to do when new rows are loaded. The default is to reset the filter, to keep it in line with 'set' filters. If you want to keep the selection, then set this value to 'keep'. */ - newRowsAction?: string; - } -} -declare namespace ag.grid { - class TextFilter implements Filter { - private filterParams; - private filterChangedCallback; - private filterModifiedCallback; - private localeTextFunc; - private valueGetter; - private filterText; - private filterType; - private api; - private eGui; - private eFilterTextField; - private eTypeSelect; - private applyActive; - private eApplyButton; - init(params: any): void; - onNewRowsLoaded(): void; - afterGuiAttached(): void; - doesFilterPass(node: any): boolean; - getGui(): any; - isFilterActive(): boolean; - private createTemplate(); - private createGui(); - private setupApply(); - private onTypeChanged(); - private onFilterChanged(); - private filterChanged(); - private createApi(); - private getApi(); - } -} -declare namespace ag.grid { - class NumberFilter implements Filter { - private filterParams; - private filterChangedCallback; - private filterModifiedCallback; - private localeTextFunc; - private valueGetter; - private filterNumber; - private filterType; - private api; - private eGui; - private eFilterTextField; - private eTypeSelect; - private applyActive; - private eApplyButton; - init(params: any): void; - onNewRowsLoaded(): void; - afterGuiAttached(): void; - doesFilterPass(node: any): boolean; - getGui(): any; - isFilterActive(): boolean; - private createTemplate(); - private createGui(); - private setupApply(); - private onTypeChanged(); - private filterChanged(); - private onFilterChanged(); - private createApi(); - private getApi(); - } -} -declare namespace ag.grid { - interface ColDef { - /** If sorting by default, set it here. Set to 'asc' or 'desc' */ - sort?: string; - /** If sorting more than one column by default, the milliseconds when this column was sorted, so we know what order to sort the columns in. */ - sortedAt?: number; - /** The sort order, provide an array with any of the following in any order ['asc','desc',null] */ - sortingOrder?: string[]; - /** The name to render in the column header */ - headerName: string; - /** The field of the row to get the cells data from */ - field: string; - /** Expression or function to get the cells value. */ - headerValueGetter?: string | Function; - /** The unique ID to give the column. This is optional. If missing, the ID will default to the field. If both field and colId are missing, a unique ID will be generated. - * This ID is used to identify the column in the API for sorting, filtering etc. */ - colId?: string; - /** Set to true for this column to be hidden. Naturally you might think, it would make more sense to call this field 'visible' and mark it false to hide, - * however we want all default values to be false and we want columns to be visible by default. */ - hide?: boolean; - /** Tooltip for the column header */ - headerTooltip?: string; - /** Expression or function to get the cells value. */ - valueGetter?: string | Function; - /** To provide custom rendering to the header. */ - headerCellRenderer?: Function | Object; - /** CSS class for the header */ - headerClass?: string | string[] | ((params: any) => string | string[]); - /** Initial width, in pixels, of the cell */ - width?: number; - /** Min width, in pixels, of the cell */ - minWidth?: number; - /** Max width, in pixels, of the cell */ - maxWidth?: number; - /** Class to use for the cell. Can be string, array of strings, or function. */ - cellClass?: string | string[] | ((cellClassParams: any) => string | string[]); - /** An object of css values. Or a function returning an object of css values. */ - cellStyle?: {} | ((params: any) => {}); - /** A function for rendering a cell. */ - cellRenderer?: Function | {}; - /** A function for rendering a floating cell. */ - floatingCellRenderer?: Function | {}; - /** Name of function to use for aggregation. One of [sum,min,max]. */ - aggFunc?: string; - /** Comparator function for custom sorting. */ - comparator?: Function; - /** Set to true to render a selection checkbox in the column. */ - checkboxSelection?: boolean; - /** Set to true if no menu should be shown for this column header. */ - suppressMenu?: boolean; - /** Set to true if no sorting should be done for this column. */ - suppressSorting?: boolean; - /** Set to true if you want the unsorted icon to be shown when no sort is applied to this column. */ - unSortIcon?: boolean; - /** Set to true if you want this columns width to be fixed during 'size to fit' operation. */ - suppressSizeToFit?: boolean; - /** Set to true if you do not want this column to be resizable by dragging it's edge. */ - suppressResize?: boolean; - /** If grouping columns, the group this column belongs to. */ - headerGroup?: string; - /** Whether to show the column when the group is open / closed. */ - headerGroupShow?: string; - /** Set to true if this col is editable, otherwise false. Can also be a function to have different rows editable. */ - editable?: boolean | (Function); - /** Callbacks for editing.See editing section for further details. */ - newValueHandler?: Function; - /** If true, this cell gets refreshed when api.softRefreshView() gets called. */ - volatile?: boolean; - /** Cell template to use for cell. Useful for AngularJS cells. */ - template?: string; - /** Cell template URL to load template from to use for cell. Useful for AngularJS cells. */ - templateUrl?: string; - /** one of the built in filter names: [set, number, text], or a filter function*/ - filter?: string | Function; - /** The filter params are specific to each filter! */ - filterParams?: SetFilterParameters | TextAndNumberFilterParameters; - /** Rules for applying css classes */ - cellClassRules?: { - [cssClassName: string]: (Function | string); - }; - /** Callbacks for editing.See editing section for further details. */ - onCellValueChanged?: Function; - /** Function callback, gets called when a cell is clicked. */ - onCellClicked?: Function; - /** Function callback, gets called when a cell is double clicked. */ - onCellDoubleClicked?: Function; - /** Function callback, gets called when a cell is right clicked. */ - onCellContextMenu?: Function; - } -} -declare namespace ag.grid { - class SetFilterModel { - private colDef; - private filterParams; - private rowModel; - private valueGetter; - private allUniqueValues; - private availableUniqueValues; - private displayedValues; - private miniFilter; - private selectedValuesCount; - private selectedValuesMap; - private showingAvailableOnly; - private usingProvidedSet; - private doesRowPassOtherFilters; - constructor(colDef: ColDef, rowModel: any, valueGetter: any, doesRowPassOtherFilters: any); - refreshAfterNewRowsLoaded(keepSelection: any, isSelectAll: boolean): void; - refreshAfterAnyFilterChanged(): void; - private createAllUniqueValues(); - private createAvailableUniqueValues(); - private getUniqueValues(filterOutNotAvailable); - setMiniFilter(newMiniFilter: any): boolean; - getMiniFilter(): any; - private processMiniFilter(); - getDisplayedValueCount(): any; - getDisplayedValue(index: any): any; - selectEverything(): void; - isFilterActive(): boolean; - selectNothing(): void; - getUniqueValueCount(): any; - getUniqueValue(index: any): any; - unselectValue(value: any): void; - selectValue(value: any): void; - isValueSelected(value: any): boolean; - isEverythingSelected(): boolean; - isNothingSelected(): boolean; - getModel(): any; - setModel(model: any, isSelectAll: boolean): void; - } -} -/** The filter parameters for set filter */ -declare namespace ag.grid { - interface SetFilterParameters { - /** Same as cell renderer for grid (you can use the same one in both locations). Setting it separatly here allows for the value to be rendered differently in the filter. */ - cellRenderer?: Function; - /** The height of the cell. */ - cellHeight?: number; - /** The values to display in the filter. */ - values?: any; - /** What to do when new rows are loaded. The default is to reset the filter, as the set of values to select from can have changed. If you want to keep the selection, then set this value to 'keep'. */ - newRowsAction?: string; - /** If true, the filter will not remove items that are no longer availabe due to other filters. */ - suppressRemoveEntries?: boolean; - } -} -declare namespace ag.grid { - class SetFilter implements Filter { - private eGui; - private filterParams; - private rowHeight; - private model; - private filterChangedCallback; - private filterModifiedCallback; - private valueGetter; - private rowsInBodyContainer; - private colDef; - private localeTextFunc; - private cellRenderer; - private eListContainer; - private eFilterValueTemplate; - private eSelectAll; - private eListViewport; - private eMiniFilter; - private api; - private applyActive; - private eApplyButton; - init(params: any): void; - afterGuiAttached(): void; - isFilterActive(): boolean; - doesFilterPass(node: any): boolean; - getGui(): any; - onNewRowsLoaded(): void; - onAnyFilterChanged(): void; - private createTemplate(); - private createGui(); - private setupApply(); - private setContainerHeight(); - private drawVirtualRows(); - private ensureRowsRendered(start, finish); - private removeVirtualRows(rowsToRemove); - private insertRow(value, rowIndex); - private onCheckboxClicked(eCheckbox, value); - private filterChanged(); - private onMiniFilterChanged(); - private refreshVirtualRows(); - private clearVirtualRows(); - private onSelectAll(); - private updateAllCheckboxes(checked); - private addScrollListener(); - getApi(): any; - private createApi(); - } -} -declare namespace ag.grid { - class PopupService { - private ePopupParent; - init(ePopupParent: any): void; - positionPopup(eventSource: any, ePopup: any, minWidth: any): void; - addAsModalPopup(eChild: any, closeOnEsc: boolean): (event: any) => void; - } -} -declare namespace ag.grid { - interface RowNode { - /** Unique ID for the node. Can be though of as the index of the row in the original list, - * however exceptions apply so don't depend on uniqueness. */ - id?: number; - /** The user provided data */ - data?: any; - /** The parent node to this node, or empty if top level */ - parent?: RowNode; - /** How many levels this node is from the top */ - level?: number; - /** True if this node is a group node (ie has children) */ - group?: boolean; - /** True if this is the first child in this group */ - firstChild?: boolean; - /** True if this is the last child in this group */ - lastChild?: boolean; - /** The index of this node in the group */ - childIndex?: number; - /** True if this row is a floating row */ - floating?: boolean; - /** True if this row is a floating top row */ - floatingTop?: boolean; - /** True if this row is a floating bottom row */ - floatingBottom?: boolean; - /** If using quick filter, stores a string representation of the row for searching against */ - quickFilterAggregateText?: string; - /** Groups only - True if row is a footer. Footers have group = true and footer = true */ - footer?: boolean; - /** Groups only - Children of this group */ - children?: RowNode[]; - /** Groups only - The field we are pivoting on eg Country*/ - field?: string; - /** Groups only - The key for the pivot eg Ireland, UK, USA */ - key?: any; - /** Groups only - Filtered children of this group */ - childrenAfterFilter?: RowNode[]; - /** Groups only - Sorted children of this group */ - childrenAfterSort?: RowNode[]; - /** Groups only - Number of children and grand children */ - allChildrenCount?: number; - /** Groups only - True if group is expanded, otherwise false */ - expanded?: boolean; - /** Groups only - If doing footers, reference to the footer node for this group */ - sibling?: RowNode; - /** Not to be used, internal temporary map used by the grid when creating groups */ - _childrenMap?: {}; - } -} -declare namespace ag.grid { - class FilterManager { - private $compile; - private $scope; - private gridOptionsWrapper; - private grid; - private allFilters; - private rowModel; - private popupService; - private valueService; - private columnController; - private quickFilter; - private advancedFilterPresent; - private externalFilterPresent; - init(grid: Grid, gridOptionsWrapper: GridOptionsWrapper, $compile: any, $scope: any, columnController: ColumnController, popupService: PopupService, valueService: ValueService): void; - setFilterModel(model: any): void; - private setModelOnFilterWrapper(filter, newModel); - getFilterModel(): any; - setRowModel(rowModel: any): void; - isAdvancedFilterPresent(): boolean; - isAnyFilterPresent(): boolean; - isFilterPresentForCol(colId: any): any; - private doesFilterPass(node, filterToSkip?); - setQuickFilter(newFilter: any): boolean; - onFilterChanged(): void; - isQuickFilterPresent(): boolean; - doesRowPassOtherFilters(filterToSkip: any, node: any): boolean; - doesRowPassFilter(node: any, filterToSkip?: any): boolean; - private aggregateRowForQuickFilter(node); - refreshDisplayedValues(): void; - onNewRowsLoaded(): void; - private createValueGetter(column); - getFilterApi(column: Column): any; - private getOrCreateFilterWrapper(column); - private createFilterWrapper(column); - private assertMethodHasNoParameters(theMethod); - showFilter(column: Column, eventSource: any): void; - } -} -declare namespace ag.grid { - class TemplateService { - templateCache: any; - waitingCallbacks: any; - $scope: any; - init($scope: any): void; - getTemplate(url: any, callback: any): any; - handleHttpResult(httpResult: any, url: any): void; - } -} -declare namespace ag.grid { - class SelectionRendererFactory { - private angularGrid; - private selectionController; - init(angularGrid: any, selectionController: any): void; - createSelectionCheckbox(node: any, rowIndex: any): HTMLInputElement; - } -} -declare namespace ag.vdom { - class VElement { - static idSequence: number; - private id; - private elementAttachedListeners; - constructor(); - getId(): number; - addElementAttachedListener(listener: (element: Element) => void): void; - protected fireElementAttached(element: Element): void; - elementAttached(element: Element): void; - toHtmlString(): string; - } -} -declare namespace ag.vdom { - class VHtmlElement extends VElement { - private type; - private classes; - private eventListeners; - private attributes; - private children; - private innerHtml; - private style; - private bound; - private element; - constructor(type: string); - getElement(): HTMLElement; - setInnerHtml(innerHtml: string): void; - addStyles(styles: any): void; - private attachEventListeners(node); - addClass(newClass: string): void; - removeClass(oldClass: string): void; - addClasses(classes: string[]): void; - toHtmlString(): string; - private toHtmlStringChildren(); - private toHtmlStringAttributes(); - private toHtmlStringClasses(); - private toHtmlStringStyles(); - appendChild(child: any): void; - setAttribute(key: string, value: string): void; - addEventListener(event: string, listener: EventListener): void; - elementAttached(element: Element): void; - fireElementAttachedToChildren(element: Element): void; - } -} -declare namespace ag.vdom { - class VWrapperElement extends VElement { - private wrappedElement; - constructor(wrappedElement: Element); - toHtmlString(): string; - elementAttached(element: Element): void; - } -} -declare namespace ag.grid { - class RenderedCell { - private vGridCell; - private vSpanWithValue; - private vCellWrapper; - private vParentOfValue; - private checkboxOnChangeListener; - private column; - private data; - private node; - private rowIndex; - private editingCell; - private scope; - private isFirstColumn; - private gridOptionsWrapper; - private expressionService; - private selectionRendererFactory; - private rowRenderer; - private selectionController; - private $compile; - private templateService; - private cellRendererMap; - private eCheckbox; - private columnController; - private valueService; - private eventService; - private value; - private checkboxSelection; - constructor(isFirstColumn: any, column: any, $compile: any, rowRenderer: RowRenderer, gridOptionsWrapper: GridOptionsWrapper, expressionService: ExpressionService, selectionRendererFactory: SelectionRendererFactory, selectionController: SelectionController, templateService: TemplateService, cellRendererMap: { - [key: string]: any; - }, node: any, rowIndex: number, scope: any, columnController: ColumnController, valueService: ValueService, eventService: EventService); - getColumn(): Column; - private getValue(); - getVGridCell(): ag.vdom.VHtmlElement; - private getDataForRow(); - private setupComponents(); - startEditing(key?: number): void; - focusCell(forceBrowserFocus: boolean): void; - private stopEditing(eInput, blurListener, reset?); - createParams(): any; - createEvent(event: any, eventSource: any): any; - private addCellDoubleClickedHandler(); - private addCellContextMenuHandler(); - isCellEditable(): any; - private addCellClickedHandler(); - private populateCell(); - private addStylesFromCollDef(); - private addClassesFromCollDef(); - private addClassesFromRules(); - private addCellNavigationHandler(); - private isKeycodeForStartEditing(key); - createSelectionCheckbox(): void; - setSelected(state: boolean): void; - private createParentOfValue(); - isVolatile(): boolean; - refreshCell(): void; - private putDataIntoCell(); - private useCellRenderer(cellRenderer); - private addClasses(); - } -} -declare namespace ag.grid { - class RenderedRow { - vPinnedRow: any; - vBodyRow: any; - private renderedCells; - private scope; - private node; - private rowIndex; - private cellRendererMap; - private gridOptionsWrapper; - private parentScope; - private angularGrid; - private columnController; - private expressionService; - private rowRenderer; - private selectionRendererFactory; - private $compile; - private templateService; - private selectionController; - private pinning; - private eBodyContainer; - private ePinnedContainer; - private valueService; - private eventService; - constructor(gridOptionsWrapper: GridOptionsWrapper, valueService: ValueService, parentScope: any, angularGrid: Grid, columnController: ColumnController, expressionService: ExpressionService, cellRendererMap: { - [key: string]: any; - }, selectionRendererFactory: SelectionRendererFactory, $compile: any, templateService: TemplateService, selectionController: SelectionController, rowRenderer: RowRenderer, eBodyContainer: HTMLElement, ePinnedContainer: HTMLElement, node: any, rowIndex: number, eventService: EventService); - onRowSelected(selected: boolean): void; - softRefresh(): void; - getRenderedCellForColumn(column: Column): RenderedCell; - getCellForCol(column: Column): any; - destroy(): void; - private destroyScope(); - isDataInList(rows: any[]): boolean; - isNodeInList(nodes: RowNode[]): boolean; - isGroup(): boolean; - private drawNormalRow(); - private bindVirtualElement(vElement); - private createGroupRow(); - private createGroupSpanningEntireRowCell(padding); - setMainRowWidth(width: number): void; - private createChildScopeOrNull(data); - private addDynamicStyles(); - private createRowContainer(); - getRowNode(): any; - getRowIndex(): any; - refreshCells(colIds: string[]): void; - private addDynamicClasses(); - } -} -declare namespace ag.grid { - class SvgFactory { - static theInstance: SvgFactory; - static getInstance(): SvgFactory; - createFilterSvg(): Element; - createColumnShowingSvg(): Element; - createColumnHiddenSvg(): Element; - createMenuSvg(): Element; - createArrowUpSvg(): Element; - createArrowLeftSvg(): Element; - createArrowDownSvg(): Element; - createArrowRightSvg(): Element; - createSmallArrowDownSvg(): Element; - createArrowUpDownSvg(): Element; - } -} -declare namespace ag.grid { - function groupCellRendererFactory(gridOptionsWrapper: GridOptionsWrapper, selectionRendererFactory: SelectionRendererFactory, expressionService: ExpressionService): (params: any) => HTMLSpanElement; -} -declare namespace ag.grid { - class RowRenderer { - private columnModel; - private gridOptionsWrapper; - private angularGrid; - private selectionRendererFactory; - private gridPanel; - private $compile; - private $scope; - private selectionController; - private expressionService; - private templateService; - private cellRendererMap; - private rowModel; - private firstVirtualRenderedRow; - private lastVirtualRenderedRow; - private focusedCell; - private valueService; - private eventService; - private renderedRows; - private renderedTopFloatingRows; - private renderedBottomFloatingRows; - private eAllBodyContainers; - private eAllPinnedContainers; - private eBodyContainer; - private eBodyViewport; - private ePinnedColsContainer; - private eFloatingTopContainer; - private eFloatingTopPinnedContainer; - private eFloatingBottomContainer; - private eFloatingBottomPinnedContainer; - private eParentsOfRows; - init(columnModel: any, gridOptionsWrapper: GridOptionsWrapper, gridPanel: GridPanel, angularGrid: Grid, selectionRendererFactory: SelectionRendererFactory, $compile: any, $scope: any, selectionController: SelectionController, expressionService: ExpressionService, templateService: TemplateService, valueService: ValueService, eventService: EventService): void; - setRowModel(rowModel: any): void; - onIndividualColumnResized(column: Column): void; - setMainRowWidths(): void; - private findAllElements(gridPanel); - refreshAllFloatingRows(): void; - private refreshFloatingRows(renderedRows, rowData, pinnedContainer, bodyContainer, isTop); - refreshView(refreshFromIndex?: any): void; - softRefreshView(): void; - refreshRows(rowNodes: RowNode[]): void; - refreshCells(rowNodes: RowNode[], colIds: string[]): void; - rowDataChanged(rows: any): void; - private refreshAllVirtualRows(fromIndex); - refreshGroupRows(): void; - private removeVirtualRow(rowsToRemove, fromIndex?); - private unbindVirtualRow(indexToRemove); - drawVirtualRows(): void; - getFirstVirtualRenderedRow(): number; - getLastVirtualRenderedRow(): number; - private ensureRowsRendered(); - private insertRow(node, rowIndex, mainRowWidth); - getRenderedNodes(): any[]; - getIndexOfRenderedNode(node: any): number; - navigateToNextCell(key: any, rowIndex: number, column: Column): void; - private getNextCellToFocus(key, lastCellToFocus); - onRowSelected(rowIndex: number, selected: boolean): void; - focusCell(eCell: any, rowIndex: number, colIndex: number, colDef: ColDef, forceBrowserFocus: any): void; - getFocusedCell(): any; - setFocusedCell(rowIndex: any, colIndex: any): void; - startEditingNextCell(rowIndex: any, column: any, shiftKey: any): void; - } -} -declare namespace ag.grid { - class SelectionController { - private eParentsOfRows; - private angularGrid; - private gridOptionsWrapper; - private $scope; - private rowRenderer; - private selectedRows; - private selectedNodesById; - private rowModel; - private eventService; - init(angularGrid: Grid, gridPanel: GridPanel, gridOptionsWrapper: GridOptionsWrapper, $scope: any, rowRenderer: RowRenderer, eventService: EventService): void; - private initSelectedNodesById(); - getSelectedNodesById(): any; - getSelectedRows(): any; - getSelectedNodes(): any; - getBestCostNodeSelection(): any; - setRowModel(rowModel: any): void; - deselectAll(): void; - selectAll(): void; - selectNode(node: any, tryMulti: any, suppressEvents?: any): void; - private recursivelySelectAllChildren(node, suppressEvents?); - private recursivelyDeselectAllChildren(node); - private doWorkOfSelectNode(node, suppressEvents); - private addCssClassForNode_andInformVirtualRowListener(node); - private doWorkOfDeselectAllNodes(nodeToKeepSelected?); - private deselectRealNode(node); - private removeCssClassForNode(node); - deselectIndex(rowIndex: any): void; - deselectNode(node: any): void; - selectIndex(index: any, tryMulti: any, suppressEvents?: any): void; - private syncSelectedRowsAndCallListener(suppressEvents?); - private recursivelyCheckIfSelected(node); - isNodeSelected(node: any): boolean; - private updateGroupParentsIfNeeded(); - } -} -declare namespace ag.grid { - class RenderedHeaderElement { - private eRoot; - private dragStartX; - constructor(eRoot: HTMLElement); - getERoot(): HTMLElement; - destroy(): void; - refreshFilterIcon(): void; - refreshSortIcon(): void; - onDragStart(): void; - onDragging(dragChange: number): void; - onIndividualColumnResized(column: Column): void; - addDragHandler(eDraggableElement: any): void; - stopDragging(listenersToRemove: any): void; - } -} -declare namespace ag.grid { - class RenderedHeaderCell extends RenderedHeaderElement { - private static DEFAULT_SORTING_ORDER; - private eHeaderCell; - private eSortAsc; - private eSortDesc; - private eSortNone; - private eFilterIcon; - private column; - private gridOptionsWrapper; - private parentScope; - private childScope; - private filterManager; - private columnController; - private $compile; - private angularGrid; - private parentGroup; - private startWidth; - constructor(column: Column, parentGroup: RenderedHeaderGroupCell, gridOptionsWrapper: GridOptionsWrapper, parentScope: any, filterManager: FilterManager, columnController: ColumnController, $compile: any, angularGrid: Grid, eRoot: HTMLElement); - getGui(): HTMLElement; - destroy(): void; - private createScope(); - private addAttributes(); - private addClasses(); - private addMenu(); - private addSortIcons(headerCellLabel); - private setupComponents(); - private useRenderer(headerNameValue, headerCellRenderer, headerCellLabel); - refreshFilterIcon(): void; - refreshSortIcon(): void; - private getNextSortDirection(); - private addSortHandling(headerCellLabel); - onDragStart(): void; - onDragging(dragChange: number): void; - onIndividualColumnResized(column: Column): void; - private addHeaderClassesFromCollDef(); - } -} -declare namespace ag.grid { - class RenderedHeaderGroupCell extends RenderedHeaderElement { - private eHeaderGroup; - private eHeaderGroupCell; - private eHeaderCellResize; - private columnGroup; - private gridOptionsWrapper; - private columnController; - private children; - private groupWidthStart; - private childrenWidthStarts; - private minWidth; - private parentScope; - private filterManager; - private $compile; - private angularGrid; - constructor(columnGroup: ColumnGroup, gridOptionsWrapper: GridOptionsWrapper, columnController: ColumnController, eRoot: HTMLElement, angularGrid: Grid, parentScope: any, filterManager: FilterManager, $compile: any); - getGui(): HTMLElement; - destroy(): void; - refreshFilterIcon(): void; - refreshSortIcon(): void; - onIndividualColumnResized(column: Column): void; - private setupComponents(); - private isColumnInOurDisplayedGroup(column); - private setWidthOfGroupHeaderCell(); - private addGroupExpandIcon(eGroupCellLabel); - onDragStart(): void; - onDragging(dragChange: any): void; - } -} -declare namespace ag.grid { - class HeaderRenderer { - private gridOptionsWrapper; - private columnController; - private angularGrid; - private filterManager; - private $scope; - private $compile; - private ePinnedHeader; - private eHeaderContainer; - private eRoot; - private headerElements; - init(gridOptionsWrapper: GridOptionsWrapper, columnController: ColumnController, gridPanel: GridPanel, angularGrid: Grid, filterManager: FilterManager, $scope: any, $compile: any): void; - private findAllElements(gridPanel); - refreshHeader(): void; - private insertHeadersWithGrouping(); - private insertHeadersWithoutGrouping(); - updateSortIcons(): void; - updateFilterIcons(): void; - onIndividualColumnResized(column: Column): void; - } -} -declare namespace ag.grid { - class GroupCreator { - private valueService; - init(valueService: ValueService): void; - group(rowNodes: RowNode[], groupedCols: Column[], expandByDefault: any): RowNode[]; - isExpanded(expandByDefault: any, level: any): boolean; - } -} -declare namespace ag.grid { - class InMemoryRowController { - private gridOptionsWrapper; - private columnController; - private angularGrid; - private filterManager; - private $scope; - private allRows; - private rowsAfterGroup; - private rowsAfterFilter; - private rowsAfterSort; - private rowsAfterMap; - private model; - private groupCreator; - private valueService; - private eventService; - constructor(); - init(gridOptionsWrapper: GridOptionsWrapper, columnController: ColumnController, angularGrid: any, filterManager: FilterManager, $scope: any, groupCreator: GroupCreator, valueService: ValueService, eventService: EventService): void; - private createModel(); - getModel(): any; - forEachInMemory(callback: Function): void; - forEachNode(callback: Function): void; - forEachNodeAfterFilter(callback: Function): void; - forEachNodeAfterFilterAndSort(callback: Function): void; - private recursivelyWalkNodesAndCallback(list, callback); - updateModel(step: any): void; - private defaultGroupAggFunctionFactory(valueColumns, valueKeys); - doAggregate(): void; - expandOrCollapseAll(expand: boolean, rowNodes: RowNode[]): void; - private recursivelyClearAggData(nodes); - private recursivelyCreateAggData(nodes, groupAggFunction, level); - private doSort(); - private recursivelyResetSort(rowNodes); - private sortList(nodes, sortOptions); - private updateChildIndexes(nodes); - onPivotChanged(): void; - private doPivoting(); - private doFilter(); - private filterItems(rowNodes); - private recursivelyResetFilter(nodes); - setAllRows(rows: RowNode[], firstId?: number): void; - private recursivelyAddIdToNodes(nodes, index); - private recursivelyCheckUserProvidedNodes(nodes, parent, level); - private getTotalChildCount(rowNodes); - private doGroupMapping(); - private addToMap(mappedData, originalNodes); - private createFooterNode(groupNode); - } -} -declare namespace ag.grid { - class VirtualPageRowController { - rowRenderer: any; - datasourceVersion: any; - gridOptionsWrapper: any; - angularGrid: any; - datasource: any; - virtualRowCount: any; - foundMaxRow: any; - pageCache: any; - pageCacheSize: any; - pageLoadsInProgress: any; - pageLoadsQueued: any; - pageAccessTimes: any; - accessTime: any; - maxConcurrentDatasourceRequests: any; - maxPagesInCache: any; - pageSize: any; - overflowSize: any; - init(rowRenderer: any, gridOptionsWrapper: any, angularGrid: any): void; - setDatasource(datasource: any): void; - reset(): void; - createNodesFromRows(pageNumber: any, rows: any): any; - removeFromLoading(pageNumber: any): void; - pageLoadFailed(pageNumber: any): void; - pageLoaded(pageNumber: any, rows: any, lastRow: any): void; - putPageIntoCacheAndPurge(pageNumber: any, rows: any): void; - checkMaxRowAndInformRowRenderer(pageNumber: any, lastRow: any): void; - isPageAlreadyLoading(pageNumber: any): boolean; - doLoadOrQueue(pageNumber: any): void; - addToQueueAndPurgeQueue(pageNumber: any): void; - findLeastRecentlyAccessedPage(pageIndexes: any): number; - checkQueueForNextLoad(): void; - loadPage(pageNumber: any): void; - requestIsDaemon(datasourceVersionCopy: any): boolean; - getVirtualRow(rowIndex: any): any; - forEachNode(callback: any): void; - getModel(): { - getVirtualRow: (index: any) => any; - getVirtualRowCount: () => any; - forEachInMemory: (callback: any) => void; - forEachNode: (callback: any) => void; - forEachNodeAfterFilter: (callback: any) => void; - forEachNodeAfterFilterAndSort: (callback: any) => void; - }; - } -} -declare namespace ag.grid { - class PaginationController { - eGui: any; - btNext: any; - btPrevious: any; - btFirst: any; - btLast: any; - lbCurrent: any; - lbTotal: any; - lbRecordCount: any; - lbFirstRowOnPage: any; - lbLastRowOnPage: any; - ePageRowSummaryPanel: any; - angularGrid: any; - callVersion: any; - gridOptionsWrapper: any; - datasource: any; - pageSize: any; - rowCount: any; - foundMaxRow: any; - totalPages: any; - currentPage: any; - init(angularGrid: any, gridOptionsWrapper: any): void; - setDatasource(datasource: any): void; - reset(): void; - setTotalLabels(): void; - calculateTotalPages(): void; - pageLoaded(rows: any, lastRowIndex: any): void; - updateRowLabels(): void; - loadPage(): void; - isCallDaemon(versionCopy: any): boolean; - onBtNext(): void; - onBtPrevious(): void; - onBtFirst(): void; - onBtLast(): void; - isZeroPagesToDisplay(): boolean; - enableOrDisableButtons(): void; - createTemplate(): string; - getGui(): any; - setupComponents(): void; - } -} -declare namespace ag.grid { - class BorderLayout { - private eNorthWrapper; - private eSouthWrapper; - private eEastWrapper; - private eWestWrapper; - private eCenterWrapper; - private eOverlayWrapper; - private eCenterRow; - private eNorthChildLayout; - private eSouthChildLayout; - private eEastChildLayout; - private eWestChildLayout; - private eCenterChildLayout; - private isLayoutPanel; - private fullHeight; - private layoutActive; - private eGui; - private id; - private childPanels; - private centerHeightLastTime; - private sizeChangeListners; - constructor(params: any); - addSizeChangeListener(listener: Function): void; - fireSizeChanged(): void; - private setupPanels(params); - private setupPanel(content, ePanel); - getGui(): any; - doLayout(): boolean; - private layoutChild(childPanel); - private layoutHeight(); - private layoutHeightFullHeight(); - private layoutHeightNormal(); - getCentreHeight(): number; - private layoutWidth(); - setEastVisible(visible: any): void; - setOverlayVisible(visible: any): void; - setSouthVisible(visible: any): void; - } -} -declare namespace ag.grid { - class GridPanel { - private masterSlaveService; - private gridOptionsWrapper; - private columnModel; - private rowRenderer; - private rowModel; - private layout; - private forPrint; - private scrollWidth; - private scrollLagCounter; - private eBodyViewport; - private eRoot; - private eBody; - private eBodyContainer; - private ePinnedColsContainer; - private eHeaderContainer; - private ePinnedHeader; - private eHeader; - private eParentsOfRows; - private eBodyViewportWrapper; - private ePinnedColsViewport; - private eFloatingTop; - private ePinnedFloatingTop; - private eFloatingTopContainer; - private eFloatingBottom; - private ePinnedFloatingBottom; - private eFloatingBottomContainer; - init(gridOptionsWrapper: GridOptionsWrapper, columnModel: ColumnController, rowRenderer: RowRenderer, masterSlaveService: MasterSlaveService): void; - getLayout(): BorderLayout; - private setupComponents(); - getPinnedFloatingTop(): HTMLElement; - getFloatingTopContainer(): HTMLElement; - getPinnedFloatingBottom(): HTMLElement; - getFloatingBottomContainer(): HTMLElement; - private createTemplate(); - ensureIndexVisible(index: any): void; - ensureColIndexVisible(index: any): void; - showLoading(loading: any): void; - getWidthForSizeColsToFit(): number; - setRowModel(rowModel: any): void; - getBodyContainer(): HTMLElement; - getBodyViewport(): HTMLElement; - getPinnedColsContainer(): HTMLElement; - getHeaderContainer(): HTMLElement; - getRoot(): HTMLElement; - getPinnedHeader(): HTMLElement; - getRowsParent(): HTMLElement[]; - private queryHtmlElement(selector); - private findElements(); - private mouseWheelListener(event); - setBodyContainerWidth(): void; - setPinnedColContainerWidth(): void; - showPinnedColContainersIfNeeded(): void; - onBodyHeightChange(): void; - private sizeHeaderAndBody(); - private sizeHeaderAndBodyNormal(); - private sizeHeaderAndBodyForPrint(); - setHorizontalScrollPosition(hScrollPosition: number): void; - private addScrollListener(); - private requestDrawVirtualRows(); - private scrollHeader(bodyLeftPosition); - private scrollPinned(bodyTopPosition); - } -} -declare namespace ag.grid { - class DragAndDropService { - static theInstance: DragAndDropService; - static getInstance(): DragAndDropService; - dragItem: any; - constructor(); - stopDragging(): void; - setDragCssClasses(eListItem: any, dragging: any): void; - addDragSource(eDragSource: any, dragSourceCallback: any): void; - onMouseDownDragSource(eDragSource: any, dragSourceCallback: any): void; - addDropTarget(eDropTarget: any, dropTargetCallback: any): void; - } -} -declare namespace ag.grid { - class AgList { - private eGui; - private uniqueId; - private modelChangedListeners; - private itemSelectedListeners; - private beforeDropListeners; - private itemMovedListeners; - private dragSources; - private emptyMessage; - private eFilterValueTemplate; - private eListParent; - private model; - private cellRenderer; - private readOnly; - constructor(); - setReadOnly(readOnly: boolean): void; - setEmptyMessage(emptyMessage: any): void; - getUniqueId(): any; - addStyles(styles: any): void; - addCssClass(cssClass: any): void; - addDragSource(dragSource: any): void; - addModelChangedListener(listener: Function): void; - addItemSelectedListener(listener: any): void; - addItemMovedListener(listener: any): void; - addBeforeDropListener(listener: any): void; - private fireItemMoved(fromIndex, toIndex); - private fireModelChanged(); - private fireItemSelected(item); - private fireBeforeDrop(item); - private setupComponents(); - setModel(model: any): void; - getModel(): any; - setCellRenderer(cellRenderer: any): void; - refreshView(): void; - private insertRows(); - private insertBlankMessage(); - private setupAsDropTarget(); - private externalAcceptDrag(dragEvent); - private externalDrop(dragEvent); - private externalNoDrop(); - private addItemToList(newItem); - private addDragAndDropToListItem(eListItem, item); - private internalAcceptDrag(targetColumn, dragItem, eListItem); - private internalDrop(targetColumn, draggedColumn); - private internalNoDrop(eListItem); - private dragAfterThisItem(targetColumn, draggedColumn); - private setDropCssClasses(eListItem, state); - getGui(): any; - } -} -declare namespace ag.grid { - class ColumnSelectionPanel { - private gridOptionsWrapper; - private columnController; - private cColumnList; - layout: any; - private eRootPanel; - constructor(columnController: ColumnController, gridOptionsWrapper: GridOptionsWrapper, eventService: EventService); - private columnsChanged(); - getDragSource(): any; - private columnCellRenderer(params); - private setupComponents(); - private onItemMoved(fromIndex, toIndex); - getGui(): any; - } -} -declare namespace ag.grid { - class GroupSelectionPanel { - gridOptionsWrapper: any; - columnController: ColumnController; - inMemoryRowController: any; - cColumnList: any; - layout: any; - constructor(columnController: ColumnController, inMemoryRowController: any, gridOptionsWrapper: GridOptionsWrapper, eventService: EventService); - private columnsChanged(); - addDragSource(dragSource: any): void; - private columnCellRenderer(params); - private setupComponents(); - private onBeforeDrop(newItem); - private onItemMoved(fromIndex, toIndex); - } -} -declare namespace ag.grid { - class AgDropdownList { - private itemSelectedListeners; - private eValue; - private agList; - private eGui; - private hidePopupCallback; - private selectedItem; - private cellRenderer; - private popupService; - constructor(popupService: PopupService); - setWidth(width: any): void; - addItemSelectedListener(listener: any): void; - fireItemSelected(item: any): void; - setupComponents(): void; - itemSelected(item: any): void; - onClick(): void; - getGui(): any; - setSelected(item: any): void; - setCellRenderer(cellRenderer: any): void; - refreshView(): void; - setModel(model: any): void; - } -} -declare namespace ag.grid { - class ValuesSelectionPanel { - private gridOptionsWrapper; - private columnController; - private cColumnList; - private layout; - private popupService; - constructor(columnController: ColumnController, gridOptionsWrapper: GridOptionsWrapper, popupService: PopupService, eventService: EventService); - getLayout(): any; - private columnsChanged(); - addDragSource(dragSource: any): void; - private cellRenderer(params); - private setupComponents(); - private beforeDropListener(newItem); - } -} -declare namespace ag.grid { - class VerticalStack { - isLayoutPanel: any; - childPanels: any; - eGui: any; - constructor(); - addPanel(panel: any, height: any): void; - getGui(): any; - doLayout(): void; - } -} -declare namespace ag.grid { - class ToolPanel { - layout: any; - constructor(); - init(columnController: any, inMemoryRowController: any, gridOptionsWrapper: GridOptionsWrapper, popupService: PopupService, eventService: EventService): void; - } -} -declare namespace ag.grid { - interface GridOptions { - virtualPaging?: boolean; - toolPanelSuppressPivot?: boolean; - toolPanelSuppressValues?: boolean; - rowsAlreadyGrouped?: boolean; - suppressRowClickSelection?: boolean; - suppressCellSelection?: boolean; - sortingOrder?: string[]; - suppressMultiSort?: boolean; - suppressHorizontalScroll?: boolean; - unSortIcon?: boolean; - rowHeight?: number; - rowBuffer?: number; - enableColResize?: boolean; - enableCellExpressions?: boolean; - enableSorting?: boolean; - enableServerSideSorting?: boolean; - enableFilter?: boolean; - enableServerSideFilter?: boolean; - colWidth?: number; - suppressMenuHide?: boolean; - singleClickEdit?: boolean; - debug?: boolean; - icons?: any; - angularCompileRows?: boolean; - angularCompileFilters?: boolean; - angularCompileHeaders?: boolean; - localeText?: any; - localeTextFunc?: Function; - suppressScrollLag?: boolean; - groupSuppressAutoColumn?: boolean; - groupSelectsChildren?: boolean; - groupHidePivotColumns?: boolean; - groupIncludeFooter?: boolean; - groupUseEntireRow?: boolean; - groupSuppressRow?: boolean; - groupSuppressBlankHeader?: boolean; - forPrint?: boolean; - groupColumnDef?: any; - context?: any; - rowStyle?: any; - rowClass?: any; - groupDefaultExpanded?: any; - slaveGrids?: GridOptions[]; - rowSelection?: string; - rowDeselection?: boolean; - rowData?: any[]; - floatingTopRowData?: any[]; - floatingBottomRowData?: any[]; - showToolPanel?: boolean; - groupKeys?: string[]; - groupAggFields?: string[]; - columnDefs?: any[]; - datasource?: any; - pinnedColumnCount?: number; - groupHeaders?: boolean; - headerHeight?: number; - groupRowInnerRenderer?(params: any): void; - groupRowRenderer?: Function | Object; - isScrollLag?(): boolean; - isExternalFilterPresent?(): boolean; - doesExternalFilterPass?(node: RowNode): boolean; - getRowStyle?: any; - getRowClass?: any; - headerCellRenderer?: any; - groupAggFunction?(nodes: any[]): any; - onReady?(api: any): void; - onModelUpdated?(): void; - onCellClicked?(params: any): void; - onCellDoubleClicked?(params: any): void; - onCellContextMenu?(params: any): void; - onCellValueChanged?(params: any): void; - onCellFocused?(params: any): void; - onRowSelected?(params: any): void; - onSelectionChanged?(): void; - onBeforeFilterChanged?(): void; - onAfterFilterChanged?(): void; - onFilterModified?(): void; - onBeforeSortChanged?(): void; - onAfterSortChanged?(): void; - onVirtualRowRemoved?(params: any): void; - onRowClicked?(params: any): void; - api?: GridApi; - columnApi?: ColumnApi; - } -} -declare namespace ag.grid { - class GridApi { - private grid; - private rowRenderer; - private headerRenderer; - private filterManager; - private columnController; - private inMemoryRowController; - private selectionController; - private gridOptionsWrapper; - private gridPanel; - private valueService; - private masterSlaveService; - private eventService; - private csvCreator; - constructor(grid: Grid, rowRenderer: RowRenderer, headerRenderer: HeaderRenderer, filterManager: FilterManager, columnController: ColumnController, inMemoryRowController: InMemoryRowController, selectionController: SelectionController, gridOptionsWrapper: GridOptionsWrapper, gridPanel: GridPanel, valueService: ValueService, masterSlaveService: MasterSlaveService, eventService: EventService); - /** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */ - __getMasterSlaveService(): MasterSlaveService; - getDataAsCsv(params?: CsvExportParams): string; - exportDataAsCsv(params?: CsvExportParams): void; - setDatasource(datasource: any): void; - onNewDatasource(): void; - setRowData(rowData: any): void; - setRows(rows: any): void; - onNewRows(): void; - setFloatingTopRowData(rows: any[]): void; - setFloatingBottomRowData(rows: any[]): void; - onNewCols(): void; - setColumnDefs(colDefs: ColDef[]): void; - unselectAll(): void; - refreshRows(rowNodes: RowNode[]): void; - refreshCells(rowNodes: RowNode[], colIds: string[]): void; - rowDataChanged(rows: any): void; - refreshView(): void; - softRefreshView(): void; - refreshGroupRows(): void; - refreshHeader(): void; - isAnyFilterPresent(): boolean; - isAdvancedFilterPresent(): boolean; - isQuickFilterPresent(): boolean; - getModel(): any; - onGroupExpandedOrCollapsed(refreshFromIndex: any): void; - expandAll(): void; - collapseAll(): void; - addVirtualRowListener(rowIndex: any, callback: any): void; - setQuickFilter(newFilter: any): void; - selectIndex(index: any, tryMulti: any, suppressEvents: any): void; - deselectIndex(index: any): void; - selectNode(node: any, tryMulti: any, suppressEvents: any): void; - deselectNode(node: any): void; - selectAll(): void; - deselectAll(): void; - recomputeAggregates(): void; - sizeColumnsToFit(): void; - showLoading(show: any): void; - isNodeSelected(node: any): boolean; - getSelectedNodesById(): { - [nodeId: number]: RowNode; - }; - getSelectedNodes(): RowNode[]; - getSelectedRows(): any[]; - getBestCostNodeSelection(): any; - getRenderedNodes(): any[]; - ensureColIndexVisible(index: any): void; - ensureIndexVisible(index: any): void; - ensureNodeVisible(comparator: any): void; - forEachInMemory(callback: Function): void; - forEachNode(callback: Function): void; - forEachNodeAfterFilter(callback: Function): void; - forEachNodeAfterFilterAndSort(callback: Function): void; - getFilterApiForColDef(colDef: any): any; - getFilterApi(key: any): any; - getColumnDef(key: any): ColDef; - onFilterChanged(): void; - setSortModel(sortModel: any): void; - getSortModel(): any; - setFilterModel(model: any): void; - getFilterModel(): any; - getFocusedCell(): any; - setFocusedCell(rowIndex: any, colIndex: any): void; - setHeaderHeight(headerHeight: number): void; - setGroupHeaders(groupHeaders: boolean): void; - showToolPanel(show: any): void; - isToolPanelShowing(): boolean; - hideColumn(colId: any, hide: any): void; - hideColumns(colIds: any, hide: any): void; - getColumnState(): [any]; - setColumnState(state: any): void; - doLayout(): void; - getValue(colDef: ColDef, data: any, node: any): any; - addEventListener(eventType: string, listener: Function): void; - addGlobalListener(listener: Function): void; - removeEventListener(eventType: string, listener: Function): void; - removeGlobalListener(listener: Function): void; - refreshPivot(): void; - } -} -declare namespace ag.grid { - class ValueService { - private gridOptionsWrapper; - private expressionService; - private columnController; - init(gridOptionsWrapper: GridOptionsWrapper, expressionService: ExpressionService, columnController: ColumnController): void; - getValue(colDef: ColDef, data: any, node: any): any; - private executeValueGetter(valueGetter, data, colDef, node); - private getValueCallback(data, node, field); - } -} -declare namespace ag.grid { - class Grid { - private virtualRowCallbacks; - private gridOptions; - private gridOptionsWrapper; - private inMemoryRowController; - private doingVirtualPaging; - private paginationController; - private virtualPageRowController; - private finished; - private selectionController; - private columnController; - private rowRenderer; - private headerRenderer; - private filterManager; - private valueService; - private masterSlaveService; - private eventService; - private toolPanel; - private gridPanel; - private eRootPanel; - private toolPanelShowing; - private doingPagination; - private usingInMemoryModel; - private rowModel; - constructor(eGridDiv: any, gridOptions: any, globalEventListener?: Function, $scope?: any, $compile?: any, quickFilterOnScope?: any); - getRowModel(): any; - private periodicallyDoLayout(); - private setupComponents($scope, $compile, eUserProvidedDiv, globalEventListener); - private onColumnChanged(event); - refreshPivot(): void; - getEventService(): EventService; - private onIndividualColumnResized(column); - showToolPanel(show: any): void; - isToolPanelShowing(): boolean; - isUsingInMemoryModel(): boolean; - setDatasource(datasource?: any): void; - private refreshHeaderAndBody(); - setFinished(): void; - onQuickFilterChanged(newFilter: any): void; - onFilterModified(): void; - onFilterChanged(): void; - onRowClicked(event: any, rowIndex: any, node: any): void; - showLoadingPanel(show: any): void; - private setupColumns(); - updateModelAndRefresh(step: any, refreshFromIndex?: any): void; - setRows(rows?: any, firstId?: any): void; - ensureNodeVisible(comparator: any): void; - getFilterModel(): any; - setFocusedCell(rowIndex: any, colIndex: any): void; - getSortModel(): any; - setSortModel(sortModel: any): void; - onSortingChanged(): void; - addVirtualRowListener(rowIndex: any, callback: any): void; - onVirtualRowSelected(rowIndex: any, selected: any): void; - onVirtualRowRemoved(rowIndex: any): void; - setColumnDefs(colDefs?: ColDef[]): void; - updateBodyContainerWidthAfterColResize(): void; - updatePinnedColContainerWidthAfterColResize(): void; - doLayout(): void; - } -} -declare namespace ag.grid { - class ComponentUtil { - static SIMPLE_PROPERTIES: string[]; - static SIMPLE_NUMBER_PROPERTIES: string[]; - static SIMPLE_BOOLEAN_PROPERTIES: string[]; - static WITH_IMPACT_NUMBER_PROPERTIES: string[]; - static WITH_IMPACT_BOOLEAN_PROPERTIES: string[]; - static WITH_IMPACT_OTHER_PROPERTIES: string[]; - static CALLBACKS: string[]; - static ALL_PROPERTIES: string[]; - static copyAttributesToGridOptions(gridOptions: GridOptions, component: any): GridOptions; - static processOnChange(changes: any, gridOptions: GridOptions, component: any): void; - static toBoolean(value: any): boolean; - static toNumber(value: any): number; - } -} -declare namespace ag.grid { - class AgGridNg2 { - private elementDef; - private _agGrid; - private _initialised; - private gridOptions; - private api; - private columnApi; - modelUpdated: any; - cellClicked: any; - cellDoubleClicked: any; - cellContextMenu: any; - cellValueChanged: any; - cellFocused: any; - rowSelected: any; - selectionChanged: any; - beforeFilterChanged: any; - afterFilterChanged: any; - filterModified: any; - beforeSortChanged: any; - afterSortChanged: any; - virtualRowRemoved: any; - rowClicked: any; - ready: any; - columnEverythingChanged: any; - columnPivotChanged: any; - columnValueChanged: any; - columnMoved: any; - columnVisible: any; - columnGroupOpened: any; - columnResized: any; - columnPinnedCountChanged: any; - virtualPaging: boolean; - toolPanelSuppressPivot: boolean; - toolPanelSuppressValues: boolean; - rowsAlreadyGrouped: boolean; - suppressRowClickSelection: boolean; - suppressCellSelection: boolean; - sortingOrder: string[]; - suppressMultiSort: boolean; - suppressHorizontalScroll: boolean; - unSortIcon: boolean; - rowHeight: number; - rowBuffer: number; - enableColResize: boolean; - enableCellExpressions: boolean; - enableSorting: boolean; - enableServerSideSorting: boolean; - enableFilter: boolean; - enableServerSideFilter: boolean; - colWidth: number; - suppressMenuHide: boolean; - debug: boolean; - icons: any; - angularCompileRows: boolean; - angularCompileFilters: boolean; - angularCompileHeaders: boolean; - localeText: any; - localeTextFunc: Function; - groupSuppressAutoColumn: boolean; - groupSelectsChildren: boolean; - groupHidePivotColumns: boolean; - groupIncludeFooter: boolean; - groupUseEntireRow: boolean; - groupSuppressRow: boolean; - groupSuppressBlankHeader: boolean; - groupColumnDef: any; - forPrint: boolean; - context: any; - rowStyle: any; - rowClass: any; - headerCellRenderer: any; - groupDefaultExpanded: any; - slaveGrids: GridOptions[]; - rowSelection: string; - rowDeselection: boolean; - rowData: any[]; - floatingTopRowData: any[]; - floatingBottomRowData: any[]; - showToolPanel: boolean; - groupKeys: string[]; - groupAggFunction: (nodes: any[]) => void; - groupAggFields: string[]; - columnDefs: any[]; - datasource: any; - pinnedColumnCount: number; - quickFilterText: string; - groupHeaders: boolean; - headerHeight: number; - constructor(elementDef: any); - onInit(): void; - onChange(changes: any): void; - private globalEventListener(eventType, event); - } -} -declare namespace ag.grid { -} -declare var exports: any; -declare var module: any; -declare namespace ag.grid { - interface Filter { - getGui(): any; - isFilterActive(): boolean; - doesFilterPass(params: any): boolean; - afterGuiAttached?(params?: { - hidePopup?: Function; - }): void; - onNewRowsLoaded?(): void; - } -} diff --git a/types/aggregate-error/aggregate-error-tests.ts b/types/aggregate-error/aggregate-error-tests.ts new file mode 100644 index 0000000000..4d434ff746 --- /dev/null +++ b/types/aggregate-error/aggregate-error-tests.ts @@ -0,0 +1,9 @@ +import AggregateError = require('aggregate-error'); + +const err = new AggregateError([new Error('foo'), 'bar']); + +for (const el of Array.from(err)) { + let err: Error = el; +} + +throw err; diff --git a/types/aggregate-error/index.d.ts b/types/aggregate-error/index.d.ts new file mode 100644 index 0000000000..8c8c4cd3b2 --- /dev/null +++ b/types/aggregate-error/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for aggregate-error 1.0 +// Project: https://github.com/sindresorhus/aggregate-error#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = AggregateError; + +declare class AggregateError extends Error implements Iterable { + constructor(errors: Iterable); + + [Symbol.iterator](): Iterator; +} diff --git a/types/ag-grid/tsconfig.json b/types/aggregate-error/tsconfig.json similarity index 75% rename from types/ag-grid/tsconfig.json rename to types/aggregate-error/tsconfig.json index fd05cca8e1..253c743b98 100644 --- a/types/ag-grid/tsconfig.json +++ b/types/aggregate-error/tsconfig.json @@ -1,17 +1,12 @@ { - "files": [ - "index.d.ts", - "ag-grid-tests.ts" - ], "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,5 +14,9 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } -} \ No newline at end of file + }, + "files": [ + "index.d.ts", + "aggregate-error-tests.ts" + ] +} diff --git a/types/aggregate-error/tslint.json b/types/aggregate-error/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/aggregate-error/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 58e1ae5dd6..36a43329f6 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -61,6 +61,9 @@ declare module 'angular' { controllerAs(controllerAs?: string): T; parent(parent?: string | Element | JQuery): T; // default: root node ariaLabel(ariaLabel: string): T; + openFrom(from: string | Element | Event | { top: number, left: number }): T; + closeTo(to: string | Element | { top: number, left: number }): T; + multiple(multiple: boolean): T; } // tslint:disable-next-line no-empty-interface diff --git a/types/angular-ui-router-default/angular-ui-router-default-tests.ts b/types/angular-ui-router-default/angular-ui-router-default-tests.ts deleted file mode 100644 index 39e792e3a1..0000000000 --- a/types/angular-ui-router-default/angular-ui-router-default-tests.ts +++ /dev/null @@ -1,39 +0,0 @@ -import * as angular from "angular"; - -angular.module("test", [ - "ui.router", - "ui.router.default" -]) - .config(function($stateProvider: angular.ui.IStateProvider) { - $stateProvider - .state('concrete', { - // no abstract or default - }) - .state('string', { - abstract: true, - default: 'concrete' - }) - .state('func_str', { - abstract: true, - default: function($rootScope): string { return $rootScope.test; } - }) - .state('func_promise', { - abstract: true, - default: function($q: ng.IQService): ng.IPromise { - return $q.when("concrete"); - } - }) - .state('injection_str', { - abstract: true, - default: ["$rootScope", function($rootScope) { - return $rootScope.test; - }] - }) - .state('injection_promise', { - abstract: true, - default: ["$q", function($q: ng.IQService) { - return $q.when("concrete"); - }] - }) - ; - }); diff --git a/types/angular-ui-router-default/index.d.ts b/types/angular-ui-router-default/index.d.ts deleted file mode 100644 index 98bb93b51b..0000000000 --- a/types/angular-ui-router-default/index.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Type definitions for angular-ui-router-default 0.5 -// Project: https://github.com/nonplus/angular-ui-router-default -// Definitions by: Stepan Riha -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -import * as aur from "angular-ui-router"; - -declare module "angular" { - namespace ui { - export type StateDefaultSpecifier = string - | ((...args: any[]) => string) - | ((...args: any[]) => ng.IPromise) - | (string | ((...args: any[]) => string))[] - | (string | ((...args: any[]) => ng.IPromise))[]; - interface IState { - default?: StateDefaultSpecifier - } - } -} diff --git a/types/asenv/asenv-tests.ts b/types/asenv/asenv-tests.ts new file mode 100644 index 0000000000..0448672d10 --- /dev/null +++ b/types/asenv/asenv-tests.ts @@ -0,0 +1,26 @@ +import { unlessProduction, isDevelopment, isTest, isProduction, getEnv, setEnv } from 'asenv'; +import { equal, throws } from 'assert'; + +// Test isDevelopment() +setEnv('development'); +equal(getEnv(), 'development', 'Should return be true'); +equal(isDevelopment(), true, 'NODE_ENV should be "development"'); +equal(isTest(), false, 'NODE_ENV should be "development"'); +equal(isProduction(), false, 'NODE_ENV should be "development"'); +equal(unlessProduction(() => true), true, "Shound return true"); + +// Test isTest() +setEnv('test'); +equal(getEnv(), 'test', 'Should return be true'); +equal(isDevelopment(), false, 'NODE_ENV should be "test"'); +equal(isTest(), true, 'NODE_ENV should be "test"'); +equal(isProduction(), false, 'NODE_ENV should be "test"'); +equal(unlessProduction(() => true), true, "Shound return true"); + +// Test isProduction() +setEnv('production'); +equal(getEnv(), 'production', 'Should return be true'); +equal(isDevelopment(), false, 'NODE_ENV should be "production"'); +equal(isTest(), false, 'NODE_ENV should be "production"'); +equal(isProduction(), true, 'NODE_ENV should be "production"'); +equal(unlessProduction(() => true), false, "Shound return false"); diff --git a/types/asenv/index.d.ts b/types/asenv/index.d.ts new file mode 100644 index 0000000000..f127664d13 --- /dev/null +++ b/types/asenv/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for asenv 1.1 +// Project: https://github.com/a-labo/asenv#readme +// Definitions by: Remisery +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export function getEnv(): string; + +export function isDevelopment(): boolean; + +export function isProduction(): boolean; + +export function isTest(): boolean; + +export function setEnv(env: string): void; + +export function unlessProduction(handle: () => any): any; diff --git a/types/asenv/tsconfig.json b/types/asenv/tsconfig.json new file mode 100644 index 0000000000..129dd1caf0 --- /dev/null +++ b/types/asenv/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "asenv-tests.ts" + ] +} diff --git a/types/asenv/tslint.json b/types/asenv/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/asenv/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index bf92ae899f..01f00c75c8 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -98,9 +98,9 @@ export class Scope { bindingIdentifierEquals(name: string, node: Node): boolean; - getBinding(name: string): Binding; + getBinding(name: string): Binding | undefined; - getOwnBinding(name: string): Binding; + getOwnBinding(name: string): Binding | undefined; getBindingIdentifier(name: string): t.Identifier; diff --git a/types/base64-js/base64-js-tests.ts b/types/base64-js/base64-js-tests.ts index 402ce43e88..f9bb761f22 100644 --- a/types/base64-js/base64-js-tests.ts +++ b/types/base64-js/base64-js-tests.ts @@ -2,4 +2,4 @@ import * as base64js from "base64-js"; base64js.byteLength(""); // $ExpectType number base64js.toByteArray(""); // $ExpectType Uint8Array -base64js.fromByteArray(new Uint8Array(0)); // $ExpectTpe string +base64js.fromByteArray(new Uint8Array(0)); // $ExpectType string diff --git a/types/base64url/base64url-tests.ts b/types/base64url/base64url-tests.ts deleted file mode 100644 index f9f206fbc9..0000000000 --- a/types/base64url/base64url-tests.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as base64url from "base64url"; - -// default -let str = base64url("some value"); -str = base64url("some value", "hex"); -str = base64url(new Buffer("some value")); - -// encode -str = base64url.encode("some value"); -str = base64url.encode("some value", "hex"); -str = base64url.encode(new Buffer("some value")); - -// decode -str = base64url.decode("ADA="); -str = base64url.decode("ADA=", "binary"); - -// toBase64 -str = base64url.toBase64("ADA="); -str = base64url.toBase64(new Buffer("ADA=", "base64")); - -// fromBase64 -str = base64url.fromBase64("ADA="); - -let buf = base64url.toBase64("ADA="); \ No newline at end of file diff --git a/types/base64url/index.d.ts b/types/base64url/index.d.ts deleted file mode 100644 index e99ae3d2b3..0000000000 --- a/types/base64url/index.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Type definitions for base64url v2.0.0 -// Project: https://github.com/brianloveswords/base64url -// Definitions by: Stepan Miroshin -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -/** - * For encoding and decoding base64url! - * v2.0.0 - */ - -/** - * Encoding type - */ -declare type Encoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "utf16le" | "base64" | "binary" | "hex" - -interface IBase64Url { - /** - * Encode input to base64url - * @param {string} input Incoming input - * @param {Encoding} encoding Default 'utf8' - * @return {string} - */ - (input: string, encoding?: Encoding): string; - /** - * Encode input to base64url - * @param {Buffer} input Incoming value - */ - (inout: Buffer): string; - /** - * Encode input to base64url - * - * @param {string} input Incoming input - * @param {Encoding} encoding Default 'utf8' - * @returns {string} - */ - encode(input: string, encoding?: Encoding): string; - /** - * Encode input to base64url - * @param {Buffer} input Incoming value - */ - encode(input: Buffer): string; - /** - * Convert a base64url encoded string into a raw string. - * @param {string} base64url base64url encoded string - * @param {Encoding} encoding Encoding defaults to 'utf8' - * @returns {string} - */ - decode(base64url: string, encoding?: string): string; - /** - * Convert a base64url encoded string to a base64 encoded string - * @param {string | Buffer} base64url base64url encoded value - * @returns {string} - */ - toBase64(base64url: string | Buffer): string; - /** - * Convert a base64 encoded string to a base64url encoded string - * @param {string} base64 encoded string - * @returns {string} - */ - fromBase64(base64: string): string; - /** - * Convert a base64url encoded string to a Buffer - * @param {string} base64url encoded string - * @returns {Buffer} - */ - toBuffer(base64url: string): Buffer; -} - -declare const base64url: IBase64Url; -export = base64url; \ No newline at end of file diff --git a/types/canvasjs/canvasjs-tests.ts b/types/canvasjs/canvasjs-tests.ts index e9120ec9c3..dffa33e9a2 100644 --- a/types/canvasjs/canvasjs-tests.ts +++ b/types/canvasjs/canvasjs-tests.ts @@ -1,248 +1,246 @@ +import * as CanvasJS from "canvasjs"; - -namespace CanvasJS.Tests { - // Column Chart - var columnChart = new CanvasJS.Chart("chartContainer", - { - title: { - text: "Top Oil Reserves", - }, - axisY: { - title: "Reserves(MMbbl)" - }, - legend: { - verticalAlign: "bottom", - horizontalAlign: "center" - }, - theme: "theme2", - data: [ - { - type: "column", - showInLegend: true, - legendMarkerColor: "grey", - legendText: "MMbbl = one million barrels", - dataPoints: [ - { y: 297571, label: "Venezuela" }, - { y: 267017, label: "Saudi" }, - { y: 175200, label: "Canada" }, - { y: 154580, label: "Iran" }, - { y: 116000, label: "Russia" }, - { y: 97800, label: "UAE" }, - { y: 20682, label: "US" }, - { y: 20350, label: "China" } - ] - } - ] - }); - columnChart.render(); - - // Line Chart - var lineChart = new CanvasJS.Chart("chartContainer", - { - theme: "theme2", - title: { - text: "Earthquakes - per month" - }, - axisX: { - valueFormatString: "MMM", - interval: 1, - intervalType: "month" - - }, - axisY: { - includeZero: false - - }, - data: [ - { - type: "line", - //lineThickness: 3, - dataPoints: [ - { x: new Date(2012, 0, 1), y: 450 }, - { x: new Date(2012, 1, 1), y: 414 }, - { x: new Date(2012, 2, 1), y: 520, indexLabel: "highest", markerColor: "red", markerType: "triangle" }, - { x: new Date(2012, 3, 1), y: 460 }, - { x: new Date(2012, 4, 1), y: 450 }, - { x: new Date(2012, 5, 1), y: 500 }, - { x: new Date(2012, 6, 1), y: 480 }, - { x: new Date(2012, 7, 1), y: 480 }, - { x: new Date(2012, 8, 1), y: 410, indexLabel: "lowest", markerColor: "DarkSlateGrey", markerType: "cross" }, - { x: new Date(2012, 9, 1), y: 500 }, - { x: new Date(2012, 10, 1), y: 480 }, - { x: new Date(2012, 11, 1), y: 510 } - - ] - } - - - ] - }); - lineChart.render(); - - // Spline Chart - var splineChart = new CanvasJS.Chart("chartContainer", - { - theme: "theme2", - title: { - text: "Game of Thrones, Viewers of the first airing on HBO" - }, - axisY: { - includeZero: false, - // suffix: " k", - valueFormatString: "#,,.", - suffix: " mn" - }, - toolTip: { - shared: true - }, - data: [ - { - type: "spline", - showInLegend: true, - name: "Season 2", - // markerSize: 0, - // color: "rgba(54,158,173,.6)", - dataPoints: [ - { label: "Ep. 1", y: 3858000 }, - { label: "Ep. 2", y: 3759000 }, - { label: "Ep. 3", y: 3766000 }, - { label: "Ep. 4", y: 3654000 }, - { label: "Ep. 5", y: 3903000 }, - { label: "Ep. 6", y: 3879000 }, - { label: "Ep. 7", y: 3694000 }, - { label: "Ep. 8", y: 3864000 }, - { label: "Ep. 9", y: 3384000 }, - { label: "Ep. 10", y: 4200000 } - - ] - }, - { - type: "spline", - showInLegend: true, - // markerSize: 0, - name: "Season 1", - dataPoints: [ - { label: "Ep. 1", y: 2220000 }, - { label: "Ep. 2", y: 2200000 }, - { label: "Ep. 3", y: 2440000 }, - { label: "Ep. 4", y: 2450000 }, - { label: "Ep. 5", y: 2580000 }, - { label: "Ep. 6", y: 2440000 }, - { label: "Ep. 7", y: 2400000 }, - { label: "Ep. 8", y: 2720000 }, - { label: "Ep. 9", y: 2660000 }, - { label: "Ep. 10", y: 3040000 } - - ] - } - ], - legend: { - cursor: "pointer", - itemclick: function (e) { - if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) { - e.dataSeries.visible = false; - } - else { - e.dataSeries.visible = true; - } - splineChart.render(); - } - - }, - }); - splineChart.render(); - - // Bar Chart - var barChart = new CanvasJS.Chart("chartContainer", { - +// Column Chart +let columnChart = new CanvasJS.Chart("chartContainer", + { title: { - text: "Fortune Global 500 Companies by Country" - }, - axisX: { - interval: 1, - gridThickness: 0, - labelFontSize: 10, - labelFontStyle: "normal", - labelFontWeight: "normal", - labelFontFamily: "Lucida Sans Unicode" + text: "Top Oil Reserves", }, axisY: { - interlacedColor: "rgba(1,77,101,.2)", - gridColor: "rgba(1,77,101,.1)" + title: "Reserves(MMbbl)" }, + legend: { + verticalAlign: "bottom", + horizontalAlign: "center" + }, + theme: "theme2", data: [ { - type: "bar", - name: "companies", - axisYType: "secondary", - color: "#014D65", + type: "column", + showInLegend: true, + legendMarkerColor: "grey", + legendText: "MMbbl = one million barrels", dataPoints: [ - { y: 5, label: "Sweden" }, - { y: 6, label: "Taiwan" }, - { y: 7, label: "Russia" }, - { y: 8, label: "Spain" }, - { y: 8, label: "Brazil" }, - { y: 8, label: "India" }, - { y: 9, label: "Italy" }, - { y: 9, label: "Australia" }, - { y: 12, label: "Canada" }, - { y: 13, label: "South Korea" }, - { y: 13, label: "Netherlands" }, - { y: 15, label: "Switzerland" }, - { y: 28, label: "Britain" }, - { y: 32, label: "Germany" }, - { y: 32, label: "France" }, - { y: 68, label: "Japan" }, - { y: 73, label: "China" }, - { y: 132, label: "US" } + { y: 297571, label: "Venezuela" }, + { y: 267017, label: "Saudi" }, + { y: 175200, label: "Canada" }, + { y: 154580, label: "Iran" }, + { y: 116000, label: "Russia" }, + { y: 97800, label: "UAE" }, + { y: 20682, label: "US" }, + { y: 20350, label: "China" } ] } ] }); - barChart.render(); +columnChart.render(); +let option = columnChart.get("title"); +columnChart.print(); +columnChart.exportChart({ format: "jpg" }); +columnChart.destroy(); +columnChart.axisX[0].convertPixelToValue(20); +columnChart.toolTip.get("text"); - // Pie Chart - var pieChart = new CanvasJS.Chart("chartContainer", - { - title: { - text: "Desktop Search Engine Market Share, Dec-2012" - }, - legend: { - verticalAlign: "center", - horizontalAlign: "left", - fontSize: 20, - fontFamily: "Helvetica" - }, - theme: "theme2", - data: [ - { - type: "pie", - indexLabelFontFamily: "Garamond", - indexLabelFontSize: 20, - indexLabel: "{label} {y}%", - startAngle: -20, - showInLegend: true, - toolTipContent: "{legendText} {y}%", - dataPoints: [ - { y: 83.24, legendText: "Google", label: "Google" }, - { y: 8.16, legendText: "Yahoo!", label: "Yahoo!" }, - { y: 4.67, legendText: "Bing", label: "Bing" }, - { y: 1.67, legendText: "Baidu", label: "Baidu" }, - { y: 0.98, legendText: "Others", label: "Others" } - ] - } - ] - }); - pieChart.render(); - - addColorSet("MyColorSet", [ - "123456", - "blue", - "red", - "orange" - ]); - - addCultureInfo("js", { - days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] +// Line Chart +let lineChart = new CanvasJS.Chart("chartContainer", + { + theme: "theme2", + title: { + text: "Earthquakes - per month" + }, + axisX: { + valueFormatString: "MMM", + interval: 1, + intervalType: "month" + }, + axisY: { + includeZero: false + }, + data: [ + { + type: "line", + // lineThickness: 3, + dataPoints: [ + { x: new Date(2012, 0, 1), y: 450 }, + { x: new Date(2012, 1, 1), y: 414 }, + { x: new Date(2012, 2, 1), y: 520, indexLabel: "highest", markerColor: "red", markerType: "triangle" }, + { x: new Date(2012, 3, 1), y: 460 }, + { x: new Date(2012, 4, 1), y: 450 }, + { x: new Date(2012, 5, 1), y: 500 }, + { x: new Date(2012, 6, 1), y: 480 }, + { x: new Date(2012, 7, 1), y: 480 }, + { x: new Date(2012, 8, 1), y: 410, indexLabel: "lowest", markerColor: "DarkSlateGrey", markerType: "cross" }, + { x: new Date(2012, 9, 1), y: 500 }, + { x: new Date(2012, 10, 1), y: 480 }, + { x: new Date(2012, 11, 1), y: 510 } + ] + } + ] }); -} +lineChart.render(); + +// Spline Chart +let splineChart = new CanvasJS.Chart("chartContainer", + { + theme: "theme2", + title: { + text: "Game of Thrones, Viewers of the first airing on HBO" + }, + axisY: { + includeZero: false, + // suffix: " k", + valueFormatString: "#,,.", + suffix: " mn" + }, + toolTip: { + shared: true + }, + data: [ + { + type: "spline", + showInLegend: true, + name: "Season 2", + // markerSize: 0, + // color: "rgba(54,158,173,.6)", + dataPoints: [ + { label: "Ep. 1", y: 3858000 }, + { label: "Ep. 2", y: 3759000 }, + { label: "Ep. 3", y: 3766000 }, + { label: "Ep. 4", y: 3654000 }, + { label: "Ep. 5", y: 3903000 }, + { label: "Ep. 6", y: 3879000 }, + { label: "Ep. 7", y: 3694000 }, + { label: "Ep. 8", y: 3864000 }, + { label: "Ep. 9", y: 3384000 }, + { label: "Ep. 10", y: 4200000 } + ] + }, + { + type: "spline", + showInLegend: true, + // markerSize: 0, + name: "Season 1", + dataPoints: [ + { label: "Ep. 1", y: 2220000 }, + { label: "Ep. 2", y: 2200000 }, + { label: "Ep. 3", y: 2440000 }, + { label: "Ep. 4", y: 2450000 }, + { label: "Ep. 5", y: 2580000 }, + { label: "Ep. 6", y: 2440000 }, + { label: "Ep. 7", y: 2400000 }, + { label: "Ep. 8", y: 2720000 }, + { label: "Ep. 9", y: 2660000 }, + { label: "Ep. 10", y: 3040000 } + ] + } + ], + legend: { + cursor: "pointer", + itemclick: (e) => { + if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) { + e.dataSeries.visible = false; + } else { + e.dataSeries.visible = true; + } + splineChart.render(); + } + }, + }); +splineChart.render(); + +// Bar Chart +let barChart = new CanvasJS.Chart("chartContainer", { + title: { + text: "Fortune Global 500 Companies by Country" + }, + axisX: { + interval: 1, + gridThickness: 0, + labelFontSize: 10, + labelFontStyle: "normal", + labelFontWeight: "normal", + labelFontFamily: "Lucida Sans Unicode" + }, + axisY: { + interlacedColor: "rgba(1,77,101,.2)", + gridColor: "rgba(1,77,101,.1)" + }, + data: [ + { + type: "bar", + name: "companies", + axisYType: "secondary", + color: "#014D65", + dataPoints: [ + { y: 5, label: "Sweden" }, + { y: 6, label: "Taiwan" }, + { y: 7, label: "Russia" }, + { y: 8, label: "Spain" }, + { y: 8, label: "Brazil" }, + { y: 8, label: "India" }, + { y: 9, label: "Italy" }, + { y: 9, label: "Australia" }, + { y: 12, label: "Canada" }, + { y: 13, label: "South Korea" }, + { y: 13, label: "Netherlands" }, + { y: 15, label: "Switzerland" }, + { y: 28, label: "Britain" }, + { y: 32, label: "Germany" }, + { y: 32, label: "France" }, + { y: 68, label: "Japan" }, + { y: 73, label: "China" }, + { y: 132, label: "US" } + ] + } + ] +}); +barChart.render(); + +// Pie Chart +let pieChart = new CanvasJS.Chart("chartContainer", + { + title: { + text: "Desktop Search Engine Market Share, Dec-2012" + }, + legend: { + verticalAlign: "center", + horizontalAlign: "left", + fontSize: 20, + fontFamily: "Helvetica" + }, + theme: "theme2", + data: [ + { + type: "pie", + indexLabelFontFamily: "Garamond", + indexLabelFontSize: 20, + indexLabel: "{label} {y}%", + startAngle: -20, + showInLegend: true, + toolTipContent: "{legendText} {y}%", + dataPoints: [ + { y: 83.24, legendText: "Google", label: "Google" }, + { y: 8.16, legendText: "Yahoo!", label: "Yahoo!" }, + { y: 4.67, legendText: "Bing", label: "Bing" }, + { y: 1.67, legendText: "Baidu", label: "Baidu" }, + { y: 0.98, legendText: "Others", label: "Others" } + ] + } + ] + }); +pieChart.render(); + +CanvasJS.addColorSet("MyColorSet", [ + "123456", + "blue", + "red", + "orange" +]); + +CanvasJS.addCultureInfo("js", { + days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] +}); + +CanvasJS.formatNumber(20); + +CanvasJS.formatDate(new Date()); diff --git a/types/canvasjs/index.d.ts b/types/canvasjs/index.d.ts index 79a168f2d0..0796aa40a0 100644 --- a/types/canvasjs/index.d.ts +++ b/types/canvasjs/index.d.ts @@ -1,992 +1,1693 @@ -// Type definitions for CanvasJS v1.5.1 +// Type definitions for CanvasJS 1.9 // Project: http://canvasjs.com/ -// Definitions by: Mark Overholt +// Definitions by: ShuYin Zhang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace CanvasJS { class Chart { - /** - * The current options of the chart. - */ + * The current options of the chart. + */ options: ChartOptions; - /** - * Initializes a new instance of CanvasJS Chart. - * @param containerId the DOM ID of the location where the chart is to be rendered - * @param options the options used to render the chart - */ + * All Title options become available as properties after Chart Render. You can access them either via get method or dot notation. But you can change / set those values only via set method. + */ + title: ChartTitle; + /** + * The subtitles of the chart. + * You can access them either via get method or dot notation. But you can change / set those values only via set method. + */ + subtitles: ChartTitle[]; + /** + * The toolTip of the chart. + */ + toolTip: ChartToolTip; + axisX: ChartAxisX[]; + axisX2: ChartAxisX[]; + axisY: ChartAxisY[]; + axisY2: ChartAxisY[]; + stripLines: ChartStrip[]; + data: ChartDataSeries[]; + /** + * Initializes a new instance of CanvasJS Chart. + * @param containerId the DOM ID of the location where the chart is to be rendered + * @param options the options used to render the chart + */ constructor(containerId: string, options?: ChartOptions); /** - * Renders the chart. - * @param options an optional set of options that will override the constructed values. - */ - render(options?: ChartOptions): void; + * Renders the chart. + */ + render(): void; + /** + * Returns the specified property of Chart. + * @param propertyName Name of the property. + */ + get(propertyName: string): any; + /** + * Sets the specified property of Chart. + * Notes: + * 1. Chart should be rendered before you can use this method. + * 2. Because the chart updates each time set is called by default, + * it is recommended to disable auto update (set updateChart to false) till the last step if you have to set multiple properties. + * Otherwise it can affect performance because of repeated chart rendering. You can see an example below. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: ChartOptions, updateChart?: boolean): void; + /** + * Adds a new element of given type to the specified array. For example, it can be used to add new Axis to axisY array. + * Notes: + * 1. Chart should be rendered before you can use this method. + * 2. Chart renders automatically after addTo() operation. + * @param propertyName Name of the property + * @param options Option for the new element + * @param index Index of the array where the new element is to be added. Defaults to the length (end) of array. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + addTo(propertyName: string, options: ChartAxisXOptions | ChartAxisYOptions | ChartDataSeriesOptions, index?: number, updateChart?: boolean): void; + /** + * Export the chart as image (jpg / png). + * @param options Setting when export + */ + exportChart(options: { format: "jpg" | "png", toDataURL?: boolean, fileName?: string }): void; + /** + * Prints the Chart. + * Chart should be rendered before you can use this method. + */ + print(): void; + /** + * Removes the chart references internally, thus making the chart eligible for garbage collection, in turn clearing up the memory. + * Notes: + * 1. On calling chart.destroy(), chart won’t be responsive unless new chart is created. + * 2. chart.destroy() should be called before using the same variable to hold a newly allocated object/chart to prevent memory leaks. + */ + destroy(): void; } /** - * Adds a new chart color set - * @param the name of the color set - * @param an array of colors. - */ + * Adds a new chart color set + * @param colorSetName name of the color set + * @param colorSetArray array of colors. + */ function addColorSet(colorSetName: string, colorSetArray: string[]): void; - /** - * Adds a new culture info for your chart - * @param culture the name of the culture - * @param the information used by this culture - */ + * Adds a new culture info for your chart + * @param culture the name of the culture + * @param info information used by this culture + */ function addCultureInfo(culture: string, info: CultureInfo): void; + /** + * Formats number according to the given formatString(optional) & culture(optional). + * @param number Number to format. + * @param formatString Default formatString is “#,##0.##” . + * @param culture Default culture is “en” + */ + function formatNumber(number: number, formatString?: string, culture?: string): string; + /** + * Formats date/timestamp according to the given formatString(optional) & culture(optional). + * @param date Date type or timestamp number. + * @param formatString Default formatString is “DD MMM YYYY”. + * @param culture Default culture is “en”. + */ + function formatDate(date: Date | number, formatString?: string, culture?: string): void; interface CultureInfo { /** - * Character used to separate fractional part from the whole number. - */ + * Character used to separate fractional part from the whole number. + * Default: "." + * Example: “.“ ”,” + */ decimalSeparator?: string; /** - * Also referred to as Thousand Separator - */ + * Also referred to as Thousand Separator. + * Default: “,” + * Example: “,”, “.” + */ digitGroupSeparator?: string; /** - * Text is shown inside the Button till v1.4 - * v1.5 onwards Text is shown as tooltip. - */ + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + * Default: "Zoom" + * Example: “zoom”, etc + */ zoomText?: string; /** - * Text is shown inside the Button till v1.4 - * v1.5 onwards Text is shown as tooltip. - */ + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + * Default: “Pan” + * Example: “pan”, etc + */ panText?: string; /** - * Text is shown inside the Button till v1.4 - * v1.5 onwards Text is shown as tooltip. - */ + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + * Default: “Reset” + * Example: “reset”, etc + */ resetText?: string; /** - * Set text is shown instead of Save as PNG. - */ + * Set text is shown instead of Save as PNG. + * Default: “Save as PNG” + * Example: “save as png”, etc + */ savePNGText?: string; /** - * Set text is shown instead of Save as JPG. - */ + * Set text is shown instead of Save as JPG. + * Default: “Save as JPG” + * Example: “save as jpg”, etc + */ saveJPGText?: string; /** - * Tool Tip for Menu Button. - */ + * Tool Tip for Menu Button. + * Default: “More Options” + * Example: “More Options”, etc + */ menuText?: string; /** - * Day names starting from Sunday. Should be exactly 7 in total. - */ + * Day names starting from Sunday. Should be exactly 7 in total. + * Default: [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”] + * Example: [“domingo”, “lunes”, “martes”, “miércoles”, “jueves”, “viernes”, “sábado”] + */ days?: string[]; /** - * Short Day names starting from Sunday. Should be exactly 7 in total. - */ + * Short Day names starting from Sunday. Should be exactly 7 in total. + * Default: [“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”] + * Example: [“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”] + */ shortDays?: string[]; /** - * Month Names starting from January - */ + * Month Names starting from January. + * Default: [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”] + * Example: [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”] + */ months?: string[]; /** - * Short Month Names starting from January - */ + * Short Month Names starting from January. + * Default: [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”] + * Example: [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”] + */ shortMonths?: string[]; } interface ChartOptions { /** - * Enables / Disables Chart interactivity like toolTip, mouse and touch events - * Default: true - * Example: false, true - */ + * Enables / Disables Chart interactivity like toolTip, mouse and touch events. + * Default: true + * Example: false, true + */ interactivityEnabled?: boolean; /** - * Enables Animation while rendering the Chart. - * Default: true - * Example: false, true - */ + * Sets the duration of animation in milliseconds. + * Default: 1200 + * Example: 1000, 500 etc. + */ + animationDuration?: number; + /** + * Enables Animation while rendering the Chart. + * Default: true + * Example: false, true + */ animationEnabled?: boolean; /** - * While exporting any chart, "Chart" is used as the default fine name with corresponding extension "jpg" or "png". You can override this name using exportFileName property. - * Default: Chart - */ + * While exporting any chart, "Chart" is used as the default fine name with corresponding extension "jpg" or "png". You can override this name using exportFileName property. + * Default: Chart + */ exportFileName?: string; /** - * Setting exportEnabled to true enables the export feature. As of now JPG & PNG formats are supported. Export feature is available in all Chart Types. - * Default: false - * Options: true, false - */ + * Setting exportEnabled to true enables the export feature. As of now JPG & PNG formats are supported. Export feature is available in all Chart Types. + * Default: false + * Options: true, false + */ exportEnabled?: boolean; /** - * Setting zoomEnabled to true enables zooming and panning feature of Chart. This way you can zoom into an area of interest when there is a large amount of data. This will also allow you to pan through the chart. If not set, the property is automatically enabled for large number of dataPoints. You can switch between zooming & panning using the toolbar that appears on the chart. After Zooming in, you can reset the chart by clicking the reset button. - * Default: false - * Options: true, false - */ + * Setting zoomEnabled to true enables zooming and panning feature of Chart. + * This way you can zoom into an area of interest when there is a large amount of data. + * This will also allow you to pan through the chart. + * If not set, the property is automatically enabled for large number of dataPoints. You can switch between zooming & panning using the toolbar that appears on the chart. + * After Zooming in, you can reset the chart by clicking the reset button. + * Default: false + * Options: true, false + */ zoomEnabled?: boolean; /** - * Sets the theme of the Chart. Various predefined themes are bundled along with the library. User can easily switch these themes by changing theme property to the below mentioned options. - * Default: "theme1" - * Options: "theme1","theme2", "theme3" - */ + * Sets the theme of the Chart. Various predefined themes are bundled along with the library. User can easily switch these themes by changing theme property to the below mentioned options. + * Default: "theme1" + * Options: "theme1","theme2", "theme3" + */ theme?: string; /** - * Sets the background color of entire Chart Area. Values can be "HTML Color Name", "hex code" or "rgba values" - * Default: "white" - * Example: "yellow", "#F5DEB3".. - */ + * Sets the background color of entire Chart Area. Values can be "HTML Color Name", "hex code" or "rgba values" + * Default: "white" + * Example: "yellow", "#F5DEB3".. + */ backgroundColor?: string; /** - * Sets the colorSet of the Chart. Color Set is an array of colors that are used to render data. Various predefined Color Sets are bundled along with the library. You can either choose from the pre-defined Color Sets or define your own Color Set. - * Default: "colorset1" or as defined in the selected theme - * Example: "colorSet1", "colorSet2", "colorSet3" - */ + * Sets the colorSet of the Chart. Color Set is an array of colors that are used to render data. Various predefined Color Sets are bundled along with the library. + * You can either choose from the pre-defined Color Sets or define your own Color Set. + * Default: "colorset1" or as defined in the selected theme + * Example: "colorSet1", "colorSet2", "colorSet3" + */ colorSet?: string; /** - * CanvasJS allows you to localize various culture / language / country specific elements in the Chart like number formatting style – where you can choose which character to use as a decimal separator and as a digit group separator (also referred to as a thousand separator). By default CanvasJS is set to Neutral English Culture – "en". - * Default: "en" - */ + * CanvasJS allows you to localize various culture / language / country specific elements in the Chart like number formatting style – where you can choose + * which character to use as a decimal separator and as a digit group separator (also referred to as a thousand separator). + * By default CanvasJS is set to Neutral English Culture – "en". + * Default: "en" + */ culture?: string; /** - * Sets the width of the Chart. - * Default: Takes chart container’s width by default. If the width is not set for the chart container, defaults to 500. - * Example: 380, 500, 720 - */ + * Sets the width of the Chart. + * Default: Takes chart container’s width by default. If the width is not set for the chart container, defaults to 500. + * Example: 380, 500, 720 + */ width?: number; /** - * Sets the width of the Chart - * Default: Takes chart container’s height by default. If the height is not set for the chart container, defaults to 400. - * Example: 260, 300, 400 - */ + * Sets the width of the Chart + * Default: Takes chart container’s height by default. If the height is not set for the chart container, defaults to 400. + * Example: 260, 300, 400 + */ height?: number; /** - * Title allows you to set content, appearance and position of Chart’s Title. - */ + * dataPointMaxWidth sets the maximum width of dataPoints in column / bar, ohlc and candlestick, charts. + * This allows you to limit the width of dataPoints when there are very few of them in the chart. + * At the same time, when the number of dataPoints increase, chart reduces their width so that they don’t overlap. + * Default : Automatically calculated based on the chart size. + * Example : 10, 20, 30, etc. + */ + dataPointMaxWidth?: number; + /** + * Title allows you to set content, appearance and position of Chart’s Title. + */ title: ChartTitleOptions; /** - * Whenever the chart contains multiple dataSeries, it is recommended to represent each dataSeries in a legend. This way it becomes easier for the user to know what exactly is represented by each of the dataSeries. In case of Pie and Doughnut charts, an entry is created for each dataPoint and in rest of the chart types entries are created for each dataSeries. - * You can selectively show or hide a dataSeries in the Legend using showInLegend property of dataSeries. - */ + * Whenever the chart contains multiple dataSeries, it is recommended to represent each dataSeries in a legend. + * This way it becomes easier for the user to know what exactly is represented by each of the dataSeries. + * In case of Pie and Doughnut charts, an entry is created for each dataPoint and in rest of the chart types entries are created for each dataSeries. + * You can selectively show or hide a dataSeries in the Legend using showInLegend property of dataSeries. + */ legend?: ChartLegendOptions; /** - * axisX object lets you set various parameters of X Axis like interval, grid lines, etc. It is mostly horizontal, except when we are working with Bar Charts, where axisX is vertical. - */ - axisX?: ChartAxisXOptions; + * axisX object lets you set various parameters of X Axis like interval, grid lines, etc. It is mostly horizontal, except when we are working with Bar Charts, where axisX is vertical. + */ + axisX?: ChartAxisXOptions | ChartAxisXOptions[]; /** - * axisY object lets you set various parameters of Y Axis like interval, grid lines, etc. It is mostly vertical, except when we are working with Bar Charts, where axisY is horizontal. - */ - axisY?: ChartAxisYOptions; + * axisX2 is the secondary axis which renders on the opposite of primary axis (axisX). + * It is mostly horizontal on top, except when we are working with Bar Charts, where axisX2 is vertical on right. + */ + axisX2?: ChartAxisXOptions | ChartAxisXOptions[]; /** - * toolTip object lets user set behaviour of toolTip at global level like enabling/disabling animation, setting Border Color, sharing toolTip between multiple dataSeries, etc. You can also disable the toolTip by setting enabled property to false. - */ + * axisY object lets you set various parameters of Y Axis like interval, grid lines, etc. It is mostly vertical, except when we are working with Bar Charts, where axisY is horizontal. + */ + axisY?: ChartAxisYOptions | ChartAxisYOptions[]; + /** + * axisY2 is the secondary axis which renders on the opposite of primary axis (axisY). It is mostly vertical, except when we are working with Bar Charts, where axisY2 is horizontal. + */ + axisY2?: ChartAxisYOptions | ChartAxisYOptions[]; + /** + * toolTip object lets user set behaviour of toolTip at global level like enabling/disabling animation, setting Border Color, sharing toolTip between multiple dataSeries, etc. + * You can also disable the toolTip by setting enabled property to false. + */ toolTip?: ChartToolTipOptions; /** - * data is an array of dataSeries Objects. - */ - data: ChartDataOptions[]; + * data is an array of dataSeries Objects. + */ + data: ChartDataSeriesOptions[]; + /** + * subtitles is a collection of subtitle elements. This allows you to have as many subtitles as you want in a chart. + * subtitle allows you to set content, appearance and position of Chart’s subtitle. subtitle is very much like title except that its font size is lesser than title by default. + */ + subtitles?: ChartTitleOptions[]; } - interface ChartTitleOptions { + class ChartTitleOptions { /** - * Sets the Title’s text. - * Default: null - * Example: "Chart title" - */ + * Sets the Title’s text. + * Default: null + * Example: "Chart title" + */ text?: string; /** - * This property lets you align the Chart Title vertically. - * Default: "top" - * Options: "top", "center", "bottom" - */ + * This property lets you align the Chart Title vertically. + * Default: "top" + * Options: "top", "center", "bottom" + */ verticalAlign?: string; /** - * This property lets you align the Chart Title horizontally. - * Default: "center" - * Options: "left", "right", "center" - */ + * This property lets you align the Chart Title horizontally. + * Default: "center" + * Options: "left", "right", "center" + */ horizontalAlign?: string; /** - * Sets the font Size of Chart Title in pixels. - * Default: Automatically Calculated based on Chart Size - * Example: 16,18,22 .. - */ + * Sets the font Size of Chart Title in pixels. + * Default: 20 + * Example: 16,18,22 .. + */ fontSize?: number; /** - * Sets the Font Family of Chart Title. - * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" - * Example: "arial" , "tahoma", "verdana" .. - */ + * Sets the Font Family of Chart Title. + * Default: "calibri, Optima, Candara, verdana, Geneva, sans-serif" + * Example: "arial" , "tahoma", "verdana" .. + */ fontFamily?: string; /** - * Sets the Font Weight used in the Chart Title. - * Default: "bold" - * Options: "lighter", "normal", "bold" , "bolder" - */ + * Sets the Font Weight used in the Chart Title. + * Default: "normal" + * Options: "lighter", "normal", "bold" , "bolder" + */ fontWeight?: string; /** - * Sets the font color of Chart Title. The value of fontColor can be a "HTML Color Name" or "hex" code . - * Default: "#3A3A3A" - * Example: "red", "#FAC003" .. - */ + * Sets the font color of Chart Title. The value of fontColor can be a "HTML Color Name" or "hex" code . + * Default: "black" + * Example: "red", "#FAC003" .. + */ fontColor?: string; /** - * Sets the fontStyle of Chart Title. fontStyle can be set to one of the below options. - * Default: "normal" - * Options: "normal", "italic" , "oblique" - */ + * Sets the fontStyle of Chart Title. fontStyle can be set to one of the below options. + * Default: "normal" + * Options: "normal", "italic" , "oblique" + */ fontStyle?: string; /** - * Sets the thickness of border around the Title in pixels. To display border around title, set the borderThickness to a number greater than zero. - * Default: 0 - * Example: 2,4 .. - */ + * Sets the thickness of border around the Title in pixels. To display border around title, set the borderThickness to a number greater than zero. + * Default: 0 + * Example: 2,4 .. + */ borderThickness?: number; /** - * To display rounded borders around the title, set the cornerRadius of title. Higher the value, more rounded are the corners. - * Default: 0 - * Options: 5,8 .. - */ + * To display rounded borders around the title, set the cornerRadius of title. Higher the value, more rounded are the corners. + * Default: 0 + * Options: 5,8 .. + */ cornerRadius?: number; /** - * Sets the color of border around Chart Title. Values of borderColor can be "HTML Color Name" or "hex" code . - * Default: "black" - * Example: "red", "#FF0000" .. - */ + * Sets the color of border around Chart Title. Values of borderColor can be "HTML Color Name" or "hex" code . + * Default: "black" + * Example: "red", "#FF0000" .. + */ borderColor?: string; /** - * Sets the background color of Chart Title. Values can be "HTML Color Name" or "hex" code. - * Default: null - * Example: "red", "#FF0000" .. - */ + * Sets the background color of Chart Title. Values can be "HTML Color Name" or "hex" code. + * Default: null + * Example: "red", "#FF0000" .. + */ backgroundColor?: string; /** - * This property lets you set margin around the Chart Title in pixels. - * Default: 10 - * Example: 4,12 .. - */ + * This property lets you set margin around the Chart Title in pixels. + * Default: 5 + * Example: 4,12 .. + */ margin?: number; /** - * This property allows you to set the padding for Chart Title - * Default: 0 - * Example: 5, 8 .. - */ + * This property allows you to set the padding for Chart Title + * Default: 0 + * Example: 5, 8 .. + */ padding?: number; + /** + * Wrap specifies whether to wrap the title once its width crosses maxWidth or not. If it is set to false, title gets clipped after reaching maxWidth. + * Default: true; + * Example : true, false + */ + wrap?: boolean; + /** + * Sets the maximum width of title after which it gets wrapped or clipped depending on whether wrap is set to true (default) or false. + * Default: Automatically calculated based on the chart size. + * Example: 200, 400 .. + */ + maxWidth?: number; + /** + * When dockInsidePlotArea is set to true, title renders inside the plot area there by giving more space to plot area. + * Default: false + * Example: false, true. + */ + dockInsidePlotArea?: boolean; } - interface ChartLegendOptions { + class ChartTitle extends ChartTitleOptions { /** - * Sets the cursor type for legend items. - * Default: "default" - * Examples: "pointer", "crosshair" .. - */ - cursor?: string; + * Can be accessed via get method or dot notation. + */ + readonly bounds: { + x1: number, + x2: number, + y1: number, + y2: number, + }; + /** + * Returns the specified property of title. + * @param propertyName Name of the property. + */ + get(propertyName: string): string | number | boolean; + /** + * Sets the specified property of Title. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: string | number | boolean, updateChart: boolean): void; + /** + * Removes title of the chart. + */ + remove(): void; + } + class ChartLegendOptions { /** - * Sets the font Size of Legend Text in pixels. - * Default: 12 - * Example: 16,18,22 .. - */ + * Sets the cursor type for legend items. + * Default: "default" + * Examples: "pointer", "crosshair" .. + */ + cursor?: string; + /** + * Sets the font Size of Legend Text in pixels. + * Default: 20 + * Example: 16,18,22 .. + */ fontSize?: number; /** - * Sets the Font Family of Legend Text. - * Default: "calibri" - * Example: "arial" , "tahoma", "verdana" .. - */ + * Sets the Font Family of Legend Text. + * Default: "calibri" + * Example: "arial" , "tahoma", "verdana" .. + */ fontFamily?: string; /** - * Sets the font color of Legend Text . The value of fontColor can be a "HTML Color Name" or "hex" code . - * Default: "black" - * Example: "red", "#FAC003" .. - */ + * Sets the font color of Legend Text . The value of fontColor can be a "HTML Color Name" or "hex" code . + * Default: "black" + * Example: "red", "#FAC003" .. + */ fontColor?: string; /** - * Sets the Font Weight of Legend Text. - * Default: "normal" - * Example: "lighter", "normal", "bold" , "bolder" - */ + * Sets the Font Weight of Legend Text. + * Default: "normal" + * Example: "lighter", "normal", "bold" , "bolder" + */ fontWeight?: string; /** - * Sets the fontStyle of Legend Text. fontStyle can be set to one of the below options. - * Default: "normal" - * Example: "normal", "italic" , "oblique" - */ + * Sets the fontStyle of Legend Text. fontStyle can be set to one of the below options. + * Default: "normal" + * Example: "normal", "italic" , "oblique" + */ fontStyle?: string; /** - * This property lets you align the Legend Position vertically. - * Default: "bottom" - * Example: "top", "center", "bottom" - */ + * This property lets you align the Legend Position vertically. + * Default: "bottom" + * Example: "top", "center", "bottom" + */ verticalAlign?: string; /** - * This property lets you align the Legend Position horizontally. - * Default: "right" - * Example: "left", "right", "center" - */ + * This property lets you align the Legend Position horizontally. + * Default: "right" + * Example: "left", "right", "center" + */ horizontalAlign?: string; /** - * Sets the mouseover event handler for the legend, which is triggered when the user moves the mouse(input device) over a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. - * @param event a chart event - */ + * Sets the margin between marker and text of each item inside legend. + * Default: Automatically calculated based on the chart size. + * Example: 4,12 .. + */ + markerMargin?: number; + /** + * Sets the mouseover event handler for the legend, which is triggered when the user moves the mouse(input device) over a legend item. + * After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ itemmouseover?: (event: ChartEvent) => void; /** - * Sets the mousemove event handler for the legend, which is triggered when the user moves the mouse(input device) within a legend item. When the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. - * @param event a chart event - */ + * Sets the mousemove event handler for the legend, which is triggered when the user moves the mouse(input device) within a legend item. + * When the event is triggered, the event related data is passed as a parameter to the assigned event handler. + * Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ itemmousemove?: (event: ChartEvent) => void; /** - * Sets the mouseout event handler for the legend, which is triggered when the user moves the mouse pointer outside a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. - * @param event a chart event - */ + * Sets the mouseout event handler for the legend, which is triggered when the user moves the mouse pointer outside a legend item. + * After the event is triggered, the event related data is passed as a parameter to the assigned event handler. + * Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ itemmouseout?: (event: ChartEvent) => void; /** - * Sets the click event handler for the legend, which is triggered when the user clicks on a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. - * @param event a chart event - */ + * Sets the click event handler for the legend, which is triggered when the user clicks on a legend item. + * After the event is triggered, the event related data is passed as a parameter to the assigned event handler. + * Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ itemclick?: (event: ChartEvent) => void; + /** + * Setting reversed property to true shows legend items in reverse order. + * Default: false; + * Example: true, false + */ + reversed?: boolean; + /** + * Sets the maximum width of legend. If any item is longer than the maxWidth, it gets wrapped or clipped depending on the itemWrap property. itemWrap is true by default. + * Whenever items are stacked horizontally, new items are moved to the next row once maxWidth is reached. + * Default: Automatically calculated based on the chart size. + * Example: 100, 200, 500 etc. + */ + maxWidth?: number; + /** + * Sets the maximum height of legend. Once the maximum height is reached, remaining legend items are not shown when horizontally stacked (while on top or bottom or plotArea) + * and a new column is created when items are vertically stacked (when displayed to the left or right of plotArea). + * Default: Automatically calculated based on chart size. + * Example: 100,200, 300 etc. + */ + maxHeight?: number; + /** + * Sets the maximum width of individual legend items after which they get wrapped or clipped depending on whether itemWrap is set to true (default) or false. + * itemMaxWidth can’t be greater than maxWidth of legend. + * Default: Automatically calculated based on the chart size. + * Example: 100, 150, 200 etc. + */ + itemMaxWidth?: number; + /** + * Sets the width of individual legend items after which the it gets wrapped or clipped depending on whether itemWrap is set to true (default) or false. + * itemWidth can’t be greater than itemMaxWidth and maxWidth of legend. + * Default: Automatically calculated based on chart size. + * Example: 100, 200, 300 etc. + */ + itemWidth?: number; + /** + * itemWrap specifies whether to wrap or clip legendText once its width crosses itemMaxWidth / maxWidth. + * Default: true + * Example: true, false + */ + itemWrap?: boolean; + /** + * A custom formatter function that returns text to be displayed inside individual legend items. + */ + itemTextFormatter?(e?: { chart: Chart, legend: ChartLegendOptions, dataSeries: ChartDataSeriesOptions, dataPoint: ChartDataPoint }): string; + /** + * When dockInsidePlotArea is set to true, legend renders inside the plot area there by giving more space to plot area. + * Default: false + * Example: true, false + */ + dockInsidePlotArea?: boolean; + } + + class ChartLegend extends ChartLegendOptions { + /** + * Returns the specified property of legend. + * @param propertyName Name of the property. + */ + get(propertyName: string): number | string | boolean; + /** + * Sets the specified property of legend. + * @param propertyName Name of the property. + * @param value Name of the property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: number | string | boolean, updateChart?: boolean): void; } interface ChartEvent { /** - * The x value of the item - */ + * The x value of the item + */ x: any; /** - * The y value of the item - */ + * The y value of the item + */ y: number; /** - * The chart object - */ + * The chart object + */ chart: Chart; /** - * The datapoint options - */ + * The datapoint options + */ dataPoint: ChartDataPoint; /** - * The data series options - */ - dataSeries: ChartDataOptions; + * The data series options + */ + dataSeries: ChartDataSeriesOptions; /** - * The index of the data point - */ + * The index of the data point + */ dataPointIndex: number; /** - * The index of the data series - */ + * The index of the data series + */ dataSeriesIndex: number; } - interface ChartAxisOptions { + class ChartAxisOptions { /** - * Sets the Axis Title. - * Default: null - * Example: "Axis X Title" - */ + * Sets the Axis Title. + * Default: null + * Example: "Axis X Title" + */ title?: string; /** - * Sets the Font Color of Axis Title. The value of titleFontColor can be a "HTML Color Name" or "hex" code . - * Default: "#666666" - * Example: "red", "#006400" . - */ + * Sets the Font Color of Axis Title. The value of titleFontColor can be a "HTML Color Name" or "hex" code . + * Default: "#666666" + * Example: "red", "#006400" . + */ titleFontColor?: string; /** - * Sets the Font Size of Axis Title in pixels. - * Default: Automatically Calculated based on Chart Size - * Example: 16, 25 .. - */ + * Sets the Font Size of Axis Title in pixels. + * Default: 20 + * Example: 16, 25 .. + */ titleFontSize?: number; /** - * Sets the Font Family of Axis Title. - * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" - * Example: "calibri", "tahoma, "verdana" .. - */ + * Sets the Font Family of Axis Title. + * Default: "arial" + * Example: "calibri", "tahoma, "verdana" .. + */ titleFontFamily?: string; /** - * Sets the Font Weight used in the Axis Title. It can be set to one of the options below. - * Default: "normal" - * Options: "lighter", "normal", "bold" , "bolder" - */ + * Sets the Font Weight used in the Axis Title. It can be set to one of the options below. + * Default: "normal" + * Options: "lighter", "normal", "bold" , "bolder" + */ titleFontWeight?: string; /** - * Sets the Font Style of Axis Title. It can be set to one of the below options. - * Default: "normal" - * Options: "normal", "italic" , "oblique" - */ + * Sets the Font Style of Axis Title. It can be set to one of the below options. + * Default: "normal" + * Options: "normal", "italic" , "oblique" + */ titleFontStyle?: string; /** - * This property lets you set margin between chart’s boundary and Axis. - * Default: 2 - * Example: 8, 10.. - */ + * This property lets you set margin between chart’s boundary and Axis. + * Default: 2 + * Example: 8, 10.. + */ margin?: number; /** - * Sets the angle for Axis Labels. - * Default: null - * Example: 20, 45, -30 .. - */ - labelAngle?: number; - /** - * Sets the Axis Label color. The value of labelFontColor can be a "HTML Color Name" or "hex" code . - * Default: "grey" - * Example: "red", "#FAC003" .. - */ - labelFontColor?: string; - /** - * Sets the Axis Label Font Size in pixels. - * Default: Automatically Calculated based on Chart Size - * Example: 16, 18, 22.. - */ - labelFontSize?: number; - /** - * Sets the Font Family of Axis labels. - * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" - * Example: "calibri", "tahoma", "verdana" .. - */ - labelFontFamily?: string; - /** - * Set the font Weight used in Axis Labels. It can be set to one of the options below. - * Default: "normal" - * Options: "lighter", "normal", "bold" , "bolder" - */ - labelFontWeight?: string; - /** - * Sets the Font Style of Axis Labels. It can be set to one of the below options. - * Default: "normal" - * Options: "italic", "oblique", "normal" - */ - labelFontStyle?: string; - /** - * A string that prepends all the labels on axisX. - * Default: null - * Example: "$","cat".. - */ - prefix?: string; - /** - * A string that appends all the labels on axisX. - * Default: null - * Example: "$","cat".. - */ - suffix?: string; - /** - * Defines how values must be formatted before they appear on Axis X. You can format numbers and date time values using this property. Below you will find descriptive table explaining various specifiers with example. - */ - valueFormatString?: string; - /** - * Sets the distance between Tick Marks, Grid Lines and Interlaced Colors. - * Default: Automatically Calculated - * Example: 50, 75.. - */ - interval?: number; - /** - * intervalType is the unit of interval property. intervalType is by default set to "number" and hence you need to specify the interval type (eg "week", "month", etc) depending on the type of interval you intend to set. If required interval is 3 months, you need to provide interval as 3 and intervalType as "month" - * Default: Automatically handled when interval property is not set. Defaults to "number" when you set the interval. - * Option: "number","millisecond" ,"second"," minute", "hour", "day", "month" ,"year" - * Example: for interval as 15 minutes, set interval as 15, and set intervalType as "minute", - */ - intervalType?: string; - /** - * Sets the length of Tick Marks that are drawn on the Axis. - * Default: 5 - * Example: 10, 14.. - */ - tickLength?: number; - /** - * Sets the color of Tick Marks drawn on the axis. The value of tickColor can be a "HTML Color Name" or "hex" code . - * Default: "#BBBBBB" - * Example: "red", "#006400". - */ - tickColor?: string; - /** - * Sets the thickness of the Tick Marks in pixels. - * Default: 2 - * Example: 3, 4.. - */ - tickThickness?: number; - /** - * Sets the color of Axis line. Axis line color can be a "HTML Color Name" or "hex" code . - * Default: "#BBBBBB" - * Example: "blue","#21AB13".. - */ + * Sets the color of Axis line. Axis line color can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "blue","#21AB13".. + */ lineColor?: string; /** - * Sets the Thickness of Axis line in pixels. - * Default: 2 - * Example: 2, 4.. - */ - lineThickness?: string; + * Sets the Thickness of Axis line in pixels. + * Default: 2 + * Example: 2, 4.. + */ + lineThickness?: number; /** - * Sets the Interlacing Color that alternates between the set interval. If the interval is not set explicitly, then the auto calculated interval is considered. The value of interlacedColor can be a "HTML Color Name" or "hex" code . - * Default: null - * Example: "#F8F1E4", "#FEFDDF" …. - */ - interlaceColor?: string; + * Sets the dash type for axisY. + * Default: "solid" + * Supported Dash Types: + * “solid” + * “shortDash” + * “shortDot” + * “shortDashDot” + * “shortDashDotDot” + * “dot” + * “dash” + * “dashDot” + * “longDash” + * “longDashDot” + * “longDashDotDot” + */ + lineDashType?: string; /** - * Sets the Thickness of Grid Lines. To display grid on Axis X, set the Grid Thickness to a number greater than zero. - * Default: 0 - * Example: 2,4 .. - */ - gridThickness?: number; - /** - * Sets the Color of Grid Lines. Value of gridColor can be a "HTML Color Name" or "hex" code . - * Default: "#BBBBBB" - * Example: "red", "#FEFDDF" .. - */ - gridColor?: string; - - /** - * Sets the Interlacing Color that alternates between the set interval. - * If the interval is not set explicitly, then the auto calculated interval is considered. - * The value of interlacedColor can be an "HTML Color Name" or "hex" code. - * Default: null - * Example: "#F8F1E4", "#FEFDDF" - */ - interlacedColor?: string; - - /** - * Strip Lines are vertical or horizontal lines used to highlight/mark a certain region on the plot area. You can choose whether to draw a line at a specific position or shade a region on the plot area. Strip Lines are sometimes referred to as trend lines. - * If you want to just mark a certain position on the axis, you can set the value attribute and it’ll draw a line at that position with the set thickness. If you want to shade a region instead, you need to set startValue and endValue attributes. This will fill the area within the specified range. - * In the case you set startValue and endValue attributes, value and thickness attributes are ignored (as either a single thread of line can exist, or a shaded region between two given points). - * Strip Lines can be displayed using AxisX or AxisY’s stripLines array. This allows you to have one or more strip lines on both x & y axis. - */ - stripLines?: ChartStripLines; - } - - interface ChartStripLines { - /** - * Sets the point where the stripLine has to be plotted or drawn along the axis X. - * Default: null - * Example: 20,30,100,50 - */ - value?: number; - /** - * Sets the point where the stripLine’s shaded region begins on the x-axis. - * Default: null - * Example: 20,30,100,50 - */ - startValue?: number; - /** - * Sets the point where the stripLine’s shaded region ends on the x-axis. - * Default: null - * Example: 50,60,200,300 - */ - endValue?: number; - /** - * Sets the thickness of the stripLine in pixels. - * Default: 2 - * Example: 2,4,5,6 - */ - thickness?: number; - /** - * Sets the color of the stripLine. - * Default: "orange" - * Example: "green", "#23EA23" - */ - color?: string; - /** - * Sets the label of the stripLine. These are shown on top of axis labels. - * Default: "" (empty string) - * Example: "Threshold", "Deaths in 1920" - */ - label?: string; - /** - * Sets the background color of stripLine’s label. - * Default: "#eeeeee" - * Example: "red","#fabd76" - */ - labelBackgroundColor?: string; - /** - * Sets the font-family of stripLine’s label. If the first font is not found in the system from the specified font-family list, it tries to use the next font in the list. - * Default: "arial" - * Example: "Arial, Trebuchet MS, Tahoma, sans-serif" - */ - labelFontFamily?: string; - /** - * Sets the font color of label. - * Default: "orange" - * Example: "blue","#4135e9" - */ - labelFontColor?: string; - /** - * Sets the font size of the label in pixels. - * Default: 12 - * Example: 18,19,20,22 - */ - labelFontSize?: number; - /** - * Sets the font weight of stripLine’s label. - * Default: "normal" - * Example: "lighter","normal","bold","bolder" - */ - labelFontWeight?: string; - /** - * Sets the font style of stripLine’s label. - * Default: "normal" - * Example: "normal","italic","oblique" - */ - labelFontStyle?: string; - } - - interface ChartAxisXOptions extends ChartAxisOptions { - /** - * Sets the minimum value of Axis. Values smaller than minimum are clipped. - * Default: Automatically Calculated based on the data - * Example: 100, 350.. - */ - minimum?: number | Date; - /** - * Sets the maximum value permitted on Axis. Values greater than maximum are clipped. - * Default: Automatically Calculated based on the data - * Example: 100, 350.. - */ - maximum?: number | Date; - } - - interface ChartAxisYOptions extends ChartAxisOptions { - /** - * When includeZero is set to true, axisY sets the range in such a way that Zero is a part of it. It is set to true by default. But, whenever y values are very big and difference among dataPoints are hard to judge, setting includeZero to false makes axisY to set a range that makes the differences prominently visible. - * Default: true - * Example: true, false - */ - includeZero?: boolean; - - /** - * Sets the minimum value of Axis. Values smaller than minimum are clipped. - * Default: Automatically Calculated based on the data - * Example: 100, 350.. - */ + * Sets the minimum value of Axis. Values smaller than minimum are clipped. minimum also sets the lower limit while panning chart. + * Default: Automatically Calculated based on the data. + * Example: 100, 350.. + */ minimum?: number; /** - * Sets the maximum value permitted on Axis. Values greater than maximum are clipped. - * Default: Automatically Calculated based on the data - * Example: 100, 350.. - */ + * Sets the maximum value permitted on Axis. Values greater than maximum are clipped. maximum also set the upper limit while panning chart. + * Default: Automatically Calculated based on the data. + * Example: 100, 350.. + */ maximum?: number; + /** + * Viewport is the visible range of the axis and viewportMinimum allows you to set its minimum value. + * This can be used in combination with viewportMaximum in order to zoom into a certain region programmatically. + * Default: Automatically Calculated based on the data. + * Example: -100, 350.. + */ + viewportMinimum?: number; + /** + * Viewport is the visible range of the axis and viewportMinimum allows you to set its minimum value. + * This can be used in combination with viewportMaximum in order to zoom into a certain region programmatically. + * Default: Automatically Calculated based on the data. + * Example: -100, 350.. + */ + viewportMaximum?: number; } - interface ChartToolTipOptions { + class ChartStripLinesOptions { /** - * Enables or Disables the toolTip for the chart. - * Default: True - * Example: True, False - */ - enabled?: boolean; + * Sets the point where the stripLine has to be plotted or drawn along the axis X. + * Default: null + * Example: 20,30,100,50 + */ + value?: number; /** - * In a Multi-Series or a Combination Chart, it is often required to display all values common to x value in a single bubble. Setting shared to true will show in a common bubble all the values of y from each series next to their name. - * Default: True - * Example: True, False - */ - shared?: boolean; + * Sets the point where the stripLine’s shaded region begins on the x-axis. + * Default: null + * Example: 20,30,100,50 + */ + startValue?: number; /** - * toolTip for entire chart can be set by adding content at toolTip object. content can either be a string or a custom function that returns HTML/String to be displayed inside the toolTip. - * Default: auto - */ - content?: string; + * Sets the point where the stripLine’s shaded region ends on the x-axis. + * Default: null + * Example: 50,60,200,300 + */ + endValue?: number; /** - * While mouse hovers from one dataPoint to another there is a smooth transition in toolTip. This effect can be controlled by animationEnabled Property. Setting it to false, will disable the animation and toolTip will directly switch from one dataPoint to the other. - * Default: True - * Example: True, False - */ - animationEnabled?: boolean; + * Sets the thickness of the stripLine in pixels. + * Default: 2 + * Example: 2,4,5,6 + */ + thickness?: number; /** - * Sets the border color around Tool Tip. When not set it takes the color of corresponding dataSeries or dataPoint. - * Default: dataSeries color/ dataPoint color - * Example: "red", "#808080".. - */ - borderColor?: string; - } - - interface ChartDataCommon { - /** - * Sets the dataPoint Name. dataPoint name is shown in various places like toolTip & legend unless overridden. - * Default: Automatically Named ("dataPoint 1", "dataPoint 2" .. ) - * Example: "apple", "mango" .. - */ - name?: string; - /** - * Sets the color of dataSeries. The value of tickColor can be a "HTML Color Name" or "Hex Code". - * Default: Automatically set from Theme. - * Example: "red", "green" .. - */ + * Sets the color of the stripLine. + * Default: "orange" + * Example: "green", "#23EA23" + */ color?: string; /** - * Instead of setting string values for all indexLabels, you can also use keywords like x, y, etc that will automatically show corresponding properties as indexLabel. This will allow you to define indexLabel at the series level once. While setting indexLabel you specify a keyword by enclosing it in flower brackets like {x}, {y}, {color}, etc. - * Range Charts have two indexLabels – one for each y value. This requires the use of a special keyword #index to show index label on either sides of the column/bar/area. - * eg: indexLabel: "{x}: {y[#index]}" - * Important keywords to keep in mind are. {x}, {y}, {name}, {label}. - * Default: null - * Example: "{label}", "Win", "x: {x}, y: {y} " - */ + * Sets the label of the stripLine. These are shown on top of axis labels. + * Default: "" (empty string) + * Example: "Threshold", "Deaths in 1920" + */ + label?: string; + /** + * labelPlacement allows you to place stripline’s Label either inside or outside of plotArea. + * Default: “inside” + * Options: “inside”, “outside” + */ + labelPlacement?: string; + /** + * labelAlign allows you to place the stripline’s Label far, center or near the axis. + * Default: “far” + * Options: “far”, “center”, “near” + */ + labelAlign?: string; + /** + * Setting labelWrap to true wraps the labels at labelMaxWidth. Clips the same when set to false. It overrides the labelWrap set at axis level. + * Default: true + * Example: true, false. + */ + labelWrap: boolean; + /** + * labelMaxWidth defines the maximum width of labels after which they get wrapped or clipped depending on labelWrap’s value. + * It overrides the labelMaxWidth value set at axis level. + * Default: Automatically calculated based on the length of label. + * Example: 4, 20, 100 etc. + */ + labelMaxWidth: number; + /** + * Sets the background color of stripLine’s label. + * Default: "#eeeeee" + * Example: "red","#fabd76" + */ + labelBackgroundColor?: string; + /** + * Sets the font-family of stripLine’s label. If the first font is not found in the system from the specified font-family list, it tries to use the next font in the list. + * Default: "arial" + * Example: "Arial, Trebuchet MS, Tahoma, sans-serif" + */ + labelFontFamily?: string; + /** + * Sets the font color of label. + * Default: "orange" + * Example: "blue","#4135e9" + */ + labelFontColor?: string; + /** + * Sets the font size of the label in pixels. + * Default: 12 + * Example: 18,19,20,22 + */ + labelFontSize?: number; + /** + * Sets the font weight of stripLine’s label. + * Default: "normal" + * Example: "lighter","normal","bold","bolder" + */ + labelFontWeight?: string; + /** + * Sets the font style of stripLine’s label. + * Default: "normal" + * Example: "normal","italic","oblique" + */ + labelFontStyle?: string; + /** + * stripLine is displayed on top of dataPoints when showOnTop is set to true. + * Default: false + * Example: true, false + */ + showOnTop?: boolean; + /** + * Sets the Dash Type for stripLine. + * Default: solid + * Example: “dot”, “dash”, etc. + */ + lineDashType?: string; + /** + * Sets opacity of stripLine. + * Default: null + * Example: .1, .5, 1 etc. + */ + opacity?: number; + /** + * A custom formatter function that returns stripLine’s label. + */ + labelFormatter?(e?: { chart: Chart, axis: ChartAxisYOptions, stripline: ChartStripLinesOptions }): string; + } + + class ChartStrip extends ChartStripLinesOptions { + /** + * Returns the specified property of stripLines. + * @param propertyName Name of the property + */ + get(propertyName: string): number | string | boolean; + /** + * Sets the specified property of stripLines. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: number | string | boolean, updateChart: boolean): void; + /** + * Removes specified stripLine from stripLines Array. + */ + remove(): void; + } + + class ChartAxisXOptions extends ChartAxisOptions { + /** + * TitleWrap specifies whether to wrap or clip axis title once its width crosses titleMaxWidth. + * Default: true + * Options: true, false + */ + titleWrap?: boolean; + /** + * Sets the maximum width of title after which it gets wrapped or clipped depending on whether titleWrap is set to true (default) or false. + * Default: Automatically calculated based on the length of axis. + * Example: 100, 200... + */ + titleMaxWidth?: number; + /** + * Sets the Axis Label background color. The value of labelBackgroundColor can be a “HTML Color Name” or “hex” code. + * Default: “transparent” + * Example: “red”,”#fabd76″ + */ + labelBackgroundColor?: string; + /** + * Sets the maximum width of label after which it gets wrapped or clipped depending on whether labelWrap is set to true (default) or false. + * Default: Automatically calculated based on the length of label. + * Example: 4, 20, 100 etc. + */ + labelMaxWidth?: number; + /** + * labelWrap specifies whether to wrap or clip label once its width crosses labelMaxWidth. + * Default: true + * Example: true, false + */ + labelWrap?: boolean; + /** + * Setting labelAutoFit to true automatically wraps and/or rotates and/or reduces font size of label when they are too long and overlaps, + * finds the best-fit and automatically manages label overlapping. + * Default: true + * Options: true, false + */ + labelAutoFit?: boolean; + /** + * Sets the angle for Axis Labels. + * Notes: + * 1.Units in degrees. + * 2.Values can be positive or negative. + * Default: null; + * Example: 20, 45, -30.. + */ + labelAngle?: number; + /** + * Sets the Font Family of Axis labels. + * Default: “calibri, optima, Candara, Verdana, Geneva, sans-serif” + * Example: “calibri”, “tahoma”, “verdana” .. + */ + labelFontFamily?: string; + /** + * Sets the Axis Label color. The value of labelFontColor can be a "HTML Color Name" or "hex" code . + * Default: "grey" + * Example: "red", "#FAC003" .. + */ + labelFontColor?: string; + /** + * Sets the Axis Label Font Size in pixels. + * Default: Automatically Calculated based on Chart Size + * Example: 16, 18, 22.. + */ + labelFontSize?: number; + /** + * Set the font Weight used in Axis Labels. It can be set to one of the options below. + * Default: "normal" + * Options: "lighter", "normal", "bold" , "bolder" + */ + labelFontWeight?: string; + /** + * Sets the Font Style of Axis Labels. It can be set to one of the below options. + * Default: "normal" + * Options: "italic", "oblique", "normal" + */ + labelFontStyle?: string; + /** + * A string that prepends all the labels on axisX. + * Default: null + * Example: "$","cat".. + */ + prefix?: string; + /** + * A string that appends all the labels on axisX. + * Default: null + * Example: "$","cat".. + */ + suffix?: string; + /** + * Defines how values must be formatted before they appear on Axis X. + * You can format numbers and date time values using this property. + * More Detail: https://canvasjs.com/docs/charts/chart-options/axisx/valueformatstring/ + */ + valueFormatString?: string; + /** + * Sets the distance between Tick Marks, Grid Lines and Interlaced Colors. + * Default: Automatically Calculated + * Example: 50, 75.. + */ + interval?: number; + /** + * intervalType is the unit of interval property. + * intervalType is by default set to "number" and hence you need to specify the interval type (eg "week", "month", etc) depending on the type of interval you intend to set. + * If required interval is 3 months, you need to provide interval as 3 and intervalType as "month" + * Default: Automatically handled when interval property is not set. Defaults to "number" when you set the interval. + * Option: "number","millisecond" ,"second"," minute", "hour", "day", "month" ,"year" + * Example: for interval as 15 minutes, set interval as 15, and set intervalType as "minute", + */ + intervalType?: string; + /** + * Setting reversed property to true shows axis in reverse order. + * Default: false + * Options: true, false + */ + reversed?: boolean; + /** + * Setting logarithmic property to true changes axis scale to logarithmic scale. Default Logarithm Base is 10 – which you can customize using logarithmBase property. + * Default: false + * Options: true, false + */ + logarithmic?: boolean; + /** + * Sets the logarithm base for Axis X. Works only when logarithm property is set to true. + * Default: 10 + * Options: 2, 16, Math.E, .. + */ + logarithmBase?: number; + /** + * Sets the length of Tick Marks that are drawn on the Axis. + * Default: 5 + * Example: 10, 14.. + */ + tickLength?: number; + /** + * Sets the color of Tick Marks drawn on the axis. The value of tickColor can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "red", "#006400". + */ + tickColor?: string; + /** + * Sets the thickness of the Tick Marks in pixels. + * Default: 2 + * Example: 3, 4.. + */ + tickThickness?: number; + /** + * Sets the Interlacing Color that alternates between the set interval. + * If the interval is not set explicitly, then the auto calculated interval is considered. The value of interlacedColor can be a “HTML Color Name” or “hex” code. + * Default: null + * Example: "#F8F1E4", "#FEFDDF"... + */ + interlacedColor?: string; + /** + * Sets the Thickness of Grid Lines. To display grid on Axis X, set the Grid Thickness to a number greater than zero. + * Default: 0 + * Example: 2,4 .. + */ + gridThickness?: number; + /** + * Sets the Color of Grid Lines. Value of gridColor can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "red", "#FEFDDF" .. + */ + gridColor?: string; + /** + * Sets the Dash Type for grid lines on axisX. + * Default: solid + * Options: “solid”, “shortDash”, “shortDot”, “shortDashDot”, “shortDashDotDot”, “dot”, “dash”, “dashDot”, “longDash”, “longDashDot”, “longDashDotDot” + */ + gridDashType?: string; + /** + * A custom formatter function that returns label to be displayed on axisX. + * Notes: + * 1.labelFormatter function should return a string. + * 2.You can use formatNumber and formatDate functions to format number/date values inside the formatter function. + */ + labelFormatter?(e: { chart: Chart, axis: ChartAxisYOptions, value: number, label: string }): string; + /** + * Strip Lines / Trend Lines are vertical or horizontal lines used to highlight/mark a certain region on the plot area. + * You can choose whether to draw a line at a specific position or shade a region on the plot area. Strip Lines are also referred to as Trend Lines. + */ + stripLines?: ChartStripLinesOptions | ChartStripLinesOptions[]; + } + + class ChartAxisX extends ChartAxisXOptions { + /** + * Returns the specified property of Axis. + * @param propertyName Name of the property. + */ + get(propertyName: string): string | number | boolean; + /** + * Sets the specified property of Axis. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: string | number | boolean, updateChart: boolean): void; + /** + * Removes specified axis from axis Array. + */ + remove(): void; + /** + * Adds a new element of given type to the specified array. For example, it can be used to add new stripLine to stripLines array. + * @param propertyName Name of the property. + * @param options Option for the new element. + * @param index Index of the array where the new element is to be added. Defaults to the length (end) of array. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + addTo(propertyName: string, options: ChartStripLinesOptions, index?: number, updateChart?: boolean): void; + /** + * Return the pixel coordinate of the given value over axis. + * @param value Numeric value over Axis + */ + convertValueToPixel(value: number): number; + /** + * Return the value along Axis for given pixel coordinate. + * @param pixel pixel value over Axis + */ + convertPixelToValue(pixel: number): number; + } + class ChartAxisYOptions extends ChartAxisXOptions { + /** + * When includeZero is set to true, axisY sets the range in such a way that Zero is a part of it. It is set to true by default. + * But, whenever y values are very big and difference among dataPoints are hard to judge, + * setting includeZero to false makes axisY to set a range that makes the differences prominently visible. + * Default: true + * Example: true, false + */ + includeZero?: boolean; + } + + class ChartAxisY extends ChartAxisYOptions { + /** + * Returns the specified property of Axis. + * @param propertyName Name of the property. + */ + get(propertyName: string): string | number | boolean; + /** + * Sets the specified property of Axis. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: string | number | boolean, updateChart: boolean): void; + /** + * Removes specified axis from axis Array. + */ + remove(): void; + /** + * Adds a new element of given type to the specified array. For example, it can be used to add new stripLine to stripLines array. + * @param propertyName Name of the property. + * @param options Option for the new element. + * @param index Index of the array where the new element is to be added. Defaults to the length (end) of array. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + addTo(propertyName: string, options: ChartStripLinesOptions, index?: number, updateChart?: boolean): void; + /** + * Return the pixel coordinate of the given value over axis. + * @param value Numeric value over Axis + */ + convertValueToPixel(value: number): number; + /** + * Return the value along Axis for given pixel coordinate. + * @param pixel pixel value over Axis + */ + convertPixelToValue(pixel: number): number; + } + + class ChartToolTipOptions { + /** + * While mouse hovers from one dataPoint to another there is a smooth transition in toolTip. + * This effect can be controlled by animationEnabled Property. Setting it to false, will disable the animation and toolTip will directly switch from one dataPoint to the other. + * Default: True + * Example: True, False + */ + animationEnabled?: boolean; + /** + * Enables or Disables the toolTip for the chart. + * Default: True + * Example: True, False + */ + enabled?: boolean; + /** + * In a Multi-Series or a Combination Chart, it is often required to display all values common to x value in a single bubble. + * Setting shared to true will show in a common bubble all the values of y from each series next to their name. + * Default: True + * Example: True, False + */ + shared?: boolean; + /** + * Sets the border color around Tool Tip. When not set it takes the color of corresponding dataSeries or dataPoint. + * Default: dataSeries color/ dataPoint color + * Example: "red", "#808080".. + */ + borderColor?: string; + /** + * toolTip for entire chart can be set by adding content at toolTip object. + * content can either be a string or a custom function that returns HTML/String to be displayed inside the toolTip. + * Default: auto + */ + content?: string; + /** + * Sets the Font Color of toolTipContent. The value of fontColor can be a “HTML Color Name” or “hex” code. + * Default: “black” + * Example: “red”, “#FAC003″ .. + */ + fontColor?: string; + /** + * Sets the Font Style of ToolTip Content. It can be set to one of the below options. + * Default: “italic” + * Example: “normal”, “italic” , “oblique” + */ + fontStyle?: string; + /** + * Sets the font Size of ToolTip Content in pixels. + * Default: 14 + * Example: 16,18,22 .. + */ + fontSize?: number; + /** + * Sets the Font Family of ToolTip Content. + * Default: “Calibri, Arial, Georgia, serif” + * Example: “arial” , “tahoma”, “verdana” .. + */ + fontFamily?: string; + /** + * Set the font Weight of ToolTip Content. + * Default: “normal” + * Example: “lighter”, “normal”, “bold” , “bolder” + */ + fontWeight?: string; + /** + * Sets the thickness of border around the toolTip in pixels. To display border around toolTip, set the borderThickness to a number greater than zero. Setting it to zero removes the border. + * Default: 2 + * Example: 2,4 .. + */ + borderThickness?: number; + /** + * Setting a value higher than 0 makes the corners of toolTip rounded. Higher the value, more rounded the corners are. + * Default: 5 + * Options: 2,3,8 .. + */ + cornerRadius?: number; + /** + * Reverses the order in which items inside toolTip are shown. + * Default: false + * Example: true, false + */ + reversed?: boolean; + /** + * A custom formatter function that returns the content (text/html) to be displayed inside the toolTip. + */ + contentFormatter?(e: { chart: Chart, toolTip: ChartToolTipOptions, entries: Array<{ dataPoint: ChartDataPoint, dataSeries: ChartDataSeriesOptions }> }): string; + /** + * Sets the background color of toolTip. Values can be “HTML Color Name” or “hex” code. + * Default: white + * Example: “red”, “#FF0000” .. + */ + backgroundColor?: string; + } + + class ChartToolTip extends ChartToolTipOptions { + /** + * Returns the specified property of legend. + * @param propertyName Name of the property. + */ + get(propertyName: string): number | string | boolean; + /** + * Sets the specified property of legend. + * @param propertyName Name of the property. + * @param value Name of the property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: number | string | boolean, updateChart?: boolean): void; + } + + class ChartDataCommon { + /** + * Sets the dataPoint Name. dataPoint name is shown in various places like toolTip & legend unless overridden. + * Default: Automatically Named ("dataPoint 1", "dataPoint 2" .. ) + * Example: "apple", "mango" .. + */ + name?: string; + /** + * Sets the color of dataSeries. The value of tickColor can be a "HTML Color Name" or "Hex Code". + * Default: Automatically set from Theme. + * Example: "red", "green" .. + */ + color?: string; + /** + * Enables or Disables highlighting of dataPoints on mouse hover. + * Default: true + * Example: true,false + */ + highlightEnabled?: boolean; + /** + * Instead of setting string values for all indexLabels, you can also use keywords like x, y, etc that will automatically show corresponding properties as indexLabel. + * This will allow you to define indexLabel at the series level once. While setting indexLabel you specify a keyword by enclosing it in flower brackets like {x}, {y}, {color}, etc. + * Range Charts have two indexLabels – one for each y value. This requires the use of a special keyword #index to show index label on either sides of the column/bar/area. + * eg: indexLabel: "{x}: {y[#index]}" + * Important keywords to keep in mind are. {x}, {y}, {name}, {label}. + * Default: null + * Example: "{label}", "Win", "x: {x}, y: {y} " + */ indexLabel?: string; /** - * Using this property you can define whether to render indexLabel "inside" or "outside" the dataPoint. - * Default: "outside" - * Example: "outside", "inside" - */ + * Sets the Dash Type for indexLabel’s line. It is applicable only for pie and doughnut charts when indexLabelPlacement is set to “outside”. + * For other chart-types, indexLabelLineThickness should be set greater than zero. + * Default: solid + * Example: “dot”, “dash”, etc. + */ + indexLabelLineDashType?: string; + /** + * A custom formatter function which returns the text to be displayed as indexLabel on dataPoints. + * @param e event object + */ + indexLabelFormatter?(e: { chart: Chart, dataSeries: ChartDataSeriesOptions, dataPoint: ChartDataPoint, index?: number, total?: number, pencent?: number }): string; + /** + * Using this property you can define whether to render indexLabel "inside" or "outside" the dataPoint. + * Default: "outside" + * Example: "outside", "inside" + */ indexLabelPlacement?: string; /** - * Sets the Orientation of indexLabel to "horizontal" or "vertical". - * Default: "horizontal" - * Options: "horizontal", "vertical" - */ + * Sets the Orientation of indexLabel to "horizontal" or "vertical". + * Default: "horizontal" + * Options: "horizontal", "vertical" + */ indexLabelOrientation?: string; /** - * Sets the Background color of Index Labels. The value of indexLabelBackgroundColor can be a "HTML Color Name" or "Hex Code". - * Default: null - * Example: "red", "#FAC003" .. - */ + * Sets the Background color of Index Labels. The value of indexLabelBackgroundColor can be a "HTML Color Name" or "Hex Code". + * Default: null + * Example: "red", "#FAC003" .. + */ indexLabelBackgroundColor?: string; /** - * Sets the Index Label’s Font Style. It can be set to one of the below options. - * Default: "normal" - * Options: "italic", "oblique", "normal" - */ + * Sets the Index Label’s Font Style. It can be set to one of the below options. + * Default: "normal" + * Options: "italic", "oblique", "normal" + */ indexLabelFontStyle?: string; /** - * Sets the Index Label’s Font color. The value of IndexLabelFontColor can be a "HTML Color Name" or "Hex Code". - * Default: "grey" - * Example: "red", "#FAC003" .. - */ + * Sets the Index Label’s Font color. The value of IndexLabelFontColor can be a "HTML Color Name" or "Hex Code". + * Default: "grey" + * Example: "red", "#FAC003" .. + */ indexLabelFontColor?: string; /** - * Sets the Index Label’s Font Size in pixels. - * Default: 18 - * Example: 12, 16, 22.. - */ + * Sets the Index Label’s Font Size in pixels. + * Default: 18 + * Example: 12, 16, 22.. + */ indexLabelFontSize?: number; /** - * Sets the Index Label’s Font Family. - * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" - * Example: "calibri", "tahoma", "verdana".. - */ + * Sets the Index Label’s Font Family. + * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" + * Example: "calibri", "tahoma", "verdana".. + */ indexLabelFontFamily?: string; /** - * Sets the Index Label’s Font Weight. It can be set to one of the below options. - * Default: "normal" - * Example: "lighter", "normal" ,"bold" , "bolder" - */ + * Sets the Index Label’s Font Weight. It can be set to one of the below options. + * Default: "normal" + * Example: "lighter", "normal" ,"bold" , "bolder" + */ indexLabelFontWeight?: string; /** - * Sets the color of line connecting index labels with their dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacment is outside. The value of indexLineColor can be a "HTML Color Name" or "Hex Code". - * Default: "lightgrey" - * Example: "red", "#FAC003" .. - */ + * Sets the color of line connecting index labels with their dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacment is outside. + * The value of indexLineColor can be a "HTML Color Name" or "Hex Code". + * Default: "lightgrey" + * Example: "red", "#FAC003" .. + */ indexLabelLineColor?: string; /** - * Sets the thickness of line connecting indexLabel with its corresponding dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacement is set to "outside". - * Default: 2 - * Example: 4, 6 - */ - indexLabelLineThickness?: string; + * Sets the thickness of line connecting indexLabel with its corresponding dataPoint. + * It is only applicable for pie and doughnut chart when indexLabelPlacement is set to "outside". + * Default: 2 + * Example: 4, 6 + */ + indexLabelLineThickness?: number; /** - * Default Tooltip can be modified at dataSeries or dataPoint level. You can add content to be displayed in toolTip using toolTipContent. toolTipContent set at dataPoint will override toolTipContent set at dataSeries level. - * Default: auto set depending on chart type. - */ + * Default Tooltip can be modified at dataSeries or dataPoint level. You can add content to be displayed in toolTip using toolTipContent. + * toolTipContent set at dataPoint will override toolTipContent set at dataSeries level. + * Default: auto set depending on chart type. + */ toolTipContent?: string; /** - * Sets marker type to be rendered at each dataPoint. While markers are helpful in highlighting individual dataPoints, they do not help much when the dataPoints are crowded. In case of large number of dataPoints it is recommended to disable markers in order to improve the appearance and performance of chart. - * Same marker type is also used in legend unless overridden by legendMarkerType property. - * Default: "circle" - * Options: "none", "circle", "square", "triangle" and "cross" - */ + * Sets marker type to be rendered at each dataPoint. While markers are helpful in highlighting individual dataPoints, they do not help much when the dataPoints are crowded. + * In case of large number of dataPoints it is recommended to disable markers in order to improve the appearance and performance of chart. + * Same marker type is also used in legend unless overridden by legendMarkerType property. + * Default: "circle" + * Options: "none", "circle", "square", "triangle" and "cross" + */ markerType?: string; /** - * Sets the color of marker that is displayed on the Chart. Legend Marker for the series uses the same Color as set here unless overridden using legendMarkerColor property. - * Default: dataSeries Color - * Example: "red", "#008000" .. - */ + * Sets the color of marker that is displayed on the Chart. Legend Marker for the series uses the same Color as set here unless overridden using legendMarkerColor property. + * Default: dataSeries Color + * Example: "red", "#008000" .. + */ markerColor?: string; /** - * Sets the Size of the marker that is drawn. To display marker in area Chart, set markerSize to a value greater than zero. For line, scatter chart, size it is automatically set unless overridden. - * Default: auto. Zero for area chart - * Example: 5, 10.. - */ + * Sets the Size of the marker that is drawn. To display marker in area Chart, set markerSize to a value greater than zero. + * For line, scatter chart, size it is automatically set unless overridden. + * Default: auto. Zero for area chart + * Example: 5, 10.. + */ markerSize?: number; /** - * Sets the border color around marker. Value of markerBorderColor can be "HTML Color Name" or "hex code". - * Default: dataSeries color. - * Example: "red", "#008000" .. - */ + * Sets the border color around marker. Value of markerBorderColor can be "HTML Color Name" or "hex code". + * Default: dataSeries color. + * Example: "red", "#008000" .. + */ markerBorderColor?: string; /** - * Sets the thickness of the Marker’s Border in pixels. - * Default: 1 - * Example: 2,4 .. - */ + * Sets the thickness of the Marker’s Border in pixels. + * Default: 1 + * Example: 2,4 .. + */ markerBorderThickness?: number; /** - * Sets the text that describes the dataSeries in legend. - * Default: "DataSeries 1", "DataSeries 2" ..etc - * Example: "2010", "2011".. - */ + * Sets the text that describes the dataSeries in legend. + * Default: "DataSeries 1", "DataSeries 2" ..etc + * Example: "2010", "2011".. + */ legendText?: string; /** - * Sets the Legend Marker to one of the options below. This property is used to override the default marker in legend, which is same as dataSeries Marker Type. - * Default: same as markerType - * Options: "circle", "square", "cross" and "triangle" - */ + * Sets the Legend Marker to one of the options below. This property is used to override the default marker in legend, which is same as dataSeries Marker Type. + * Default: same as markerType + * Options: "circle", "square", "cross" and "triangle" + */ legendMarkerType?: string; /** - * Sets the click event handler for dataSeries which is triggered when user clicks on a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. - * Default: null - */ - click?: (event: ChartEvent) => void; - /** - * Sets the color of marker that is displayed on legend. This property overrides default Marker’s Color in Legend, which is same as dataSeries Marker Color. Value of legendMarkerColor can be "HTML Color Name" or "hex code". - * Default: dataSeries marker color - * Example: "red", "#008000" .. - */ + * Sets the color of marker that is displayed on legend. This property overrides default Marker’s Color in Legend, which is same as dataSeries Marker Color. + * Value of legendMarkerColor can be "HTML Color Name" or "hex code". + * Default: dataSeries marker color + * Example: "red", "#008000" .. + */ legendMarkerColor?: string; /** - * Sets the mouseover event handler for dataSeries which is triggered when user moves Mouse Over a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. - * Default: null - */ + * Sets the border color around the legend marker. Value of legendMarkerBorderColor can be “color names” or “hex code”. + * Default: dataSeries color. + * Example: “red”, “#008000” .. + */ + legendMarkerBorderColor?: string; + /** + * Sets the thickness of the legend’s Marker Border in pixels. + * Default: 0 + * Example: 2, 4 .. + */ + legendMarkerBorderThickness?: number; + /** + * Sets the click event handler for dataSeries which is triggered when user clicks on a dataSeries. + * Upon event, a parameter that contains event related data is sent to the assigned event handler. + * Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + click?: (event: ChartEvent) => void; + /** + * Sets the mouseover event handler for dataSeries which is triggered when user moves Mouse Over a dataSeries. + * Upon event, a parameter that contains event related data is sent to the assigned event handler. + * Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ mouseover?: (event: ChartEvent) => void; /** - * Sets the mousemove event handler for dataSeries which is triggered when user Moves mouse on a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. - * Default: null - */ + * Sets the mousemove event handler for dataSeries which is triggered when user Moves mouse on a dataSeries. + * Upon event, a parameter that contains event related data is sent to the assigned event handler. + * Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ mousemove?: (event: ChartEvent) => void; /** - * Sets the mouseout event handler for dataSeries which is triggered when user moves mouse out of a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. - * Default: null - */ + * Sets the mouseout event handler for dataSeries which is triggered when user moves mouse out of a dataSeries. + * Upon event, a parameter that contains event related data is sent to the assigned event handler. + * Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ mouseout?: (event: ChartEvent) => void; } - interface ChartDataOptions extends ChartDataCommon { + class ChartDataSeriesOptions extends ChartDataCommon { /** - * Sets the visibility of dataSeries. Data Series is visible by default and you can hide the same by setting visible property to false. - * Default: true - * Example: true, false - */ + * Sets the visibility of dataSeries. Data Series is visible by default and you can hide the same by setting visible property to false. + * Default: true + * Example: true, false + */ visible?: boolean; /** - * Sets the type of chart to be rendered for corresponding dataSeries. One can choose from the following options. - * Default: "column" - * Options: - * "line" - * "column" - * "bar" - * "area" - * "spline" - * "splineArea" - * "stepLine" - * "scatter" - * "bubble" - * "stackedColumn" - * "stackedBar" - * "stackedArea" - * "stackedColumn100" - * "stackedBar100" - * "stackedArea100" - * "pie" - * "doughnut" - */ + * Sets the type of chart to be rendered for corresponding dataSeries. One can choose from the following options. + * Default: "column" + * Options: + * "line" + * "column" + * "bar" + * "area" + * "spline" + * "splineArea" + * "stepLine" + * "scatter" + * "bubble" + * "stackedColumn" + * "stackedBar" + * "stackedArea" + * "stackedColumn100" + * "stackedBar100" + * "stackedArea100" + * "pie" + * "doughnut" + */ type?: string; /** - * Setting axisYType lets you choose between primary and secondary Y Axis for a dataSeries to plot against. By choosing "secondary" Axis you can plot the series against axisY2. - * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. - * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary Y axis. - * Default: "primary" - * Options: "primary", "secondary" - */ + * Setting axisXType lets you choose between primary and secondary X Axis for a dataSeries to plot against. By choosing “secondary” Axis you can plot the series against axisX2. + * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary X axis. + */ + axisXType?: string; + /** + * Setting axisYType lets you choose between primary and secondary Y Axis for a dataSeries to plot against. By choosing "secondary" Axis you can plot the series against axisY2. + * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary Y axis. + * Default: "primary" + * Options: "primary", "secondary" + */ axisYType?: string; /** - * This defines the data type of x values. Data Type is normally figured out by default based on the object type that is assigned to x. But if you are providing time stamp (which is integer) values instead of Date objects, you’ll have to explicitly set the xValueType to "dateTime". - * Default: Automatically Calculated - * Options: "number", "dateTime" - */ + * Setting axisXIndex lets you choose to which X axis the dataSeries should be attached. + * In case of Multi-Series or Combinational Charts, one can assign some series to first X axis and rest to another axis. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against first axis. + */ + axisXIndex?: number; + /** + * Setting axisYIndex lets you choose to which Y axis the dataSeries should be attached to. + * In case of Multi-Series or Combinational Charts, one can assign some series to first Y axis and rest to another axis. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against first axis. + */ + axisYIndex?: number; + /** + * This defines the data type of x values. Data Type is normally figured out by default based on the object type that is assigned to x. + * But if you are providing time stamp (which is integer) values instead of Date objects, you’ll have to explicitly set the xValueType to "dateTime". + * Default: Automatically Calculated + * Options: "number", "dateTime" + */ xValueType?: string; /** - * Defines how y axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. - */ + * Defines how y axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. + */ yValueFormatString?: string; /** - * Defines how x axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. - */ + * Defines how x axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. + */ xValueFormatString?: string; /** - * Defines how z values is formatted before they appear on the indexLabel or toolTip. You can format numbers using this property. - */ + * Defines how z values is formatted before they appear on the indexLabel or toolTip. You can format numbers using this property. + */ zValueFormatString?: string; /** - * Sets the bevel property, which creates a chiselled effect at the corners of a Column Charts and Bar Charts. - * Default: "true" - * Example: "true", "false" - */ + * Defines how percent values are formatted before they appear on the indexLabel or toolTip. You can format percent values using this property. + */ + percentFormatString?: string; + /** + * Sets the bevel property, which creates a chiselled effect at the corners of a Column Charts and Bar Charts. + * Default: "true" + * Example: "true", "false" + */ bevelEnabled?: boolean; /** - * Sets opacity of the filled color. - * Default: .7 for Area Charts and 1 for all other chart types. - */ + * Sets opacity of the filled color. + * Default: .7 for Area Charts and 1 for all other chart types. + */ fillOpacity?: number; /** - * Sets the starting Angle of the Pie or Doughnut Chart in degrees. - * Default: 0 - * Example: 30, 240, -100.. - */ + * Sets the starting Angle of the Pie or Doughnut Chart in degrees. + * Default: 0 + * Example: 30, 240, -100.. + */ startAngle?: number; /** - * Sets the thickness of line in line charts and area charts. - * Default: 2 - * Example: 3,4.. - */ + * innerRadius property allows you to set a Doughnut chart’s inner radius. + * Value can either be in pixels (number – ex: 100) or percent (string – ex: “80%”). Percent values are relative to the outer radius of doughnut chart. + * Default: “70%” + * Example: 200, 150, “90%”, “75%” + */ + innerRadius?: number | string; + /** + * radius property allows you to set the Pie/Doughnut chart’s (outer) radius. + * Value can either be in pixels (number – ex: 100) or percent (string – ex: “80%”). Percent values are relative to the plot area’s size. + * By default, a pie/doughnut chart’s size(radius) changes in order to best fit the indexLabels. This can lead to charts of different sizes in the same page. + * In order to override this behavior and set equal sizes to all pie/doughnut charts in a page, you can use radius property. + * Default: Automatically calculate in order to best fit the indexLabels. + * Example: 200, 150, “90%”, “75%” + */ + radius?: number | string; + /** + * Sets the thickness of line in line charts and area charts. + * Default: 2 + * Example: 3,4.. + */ lineThickness?: number; /** - * Setting this property to true makes the dataSeries to appear in legend. In case of pie/ doughnut chart, dataPoints of the single series chart appear in legend. - * Default: false - * Options: false, true - */ + * Setting this property to true makes the dataSeries to appear in legend. In case of pie/ doughnut chart, dataPoints of the single series chart appear in legend. + * Default: false + * Options: false, true + */ showInLegend?: boolean; /** - * In candle Stick chart, when Closing Price is greater than Opening price, the body is filled with white by default and it can be overridden by risingColor property. - * Default: "white" - * Options: "red", "#DD7E86", etc. - */ + * Enables or disables exploding of Pie/Doughnut segment on click. + * Default: true + * Options: false, true + */ + explodeOnClick?: boolean; + /** + * In candle Stick chart, when Closing Price is greater than Opening price, the body is filled with white by default and it can be overridden by risingColor property. + * Default: "white" + * Options: "red", "#DD7E86", etc. + */ risingColor?: string; /** - * It represents collection dataPoint inside dataSeries . - */ + * It represents collection dataPoint inside dataSeries. + */ dataPoints: ChartDataPoint[]; + /** + * By default, a line breaks wherever a null dataPoint (y = null) is present. + * You can change this behaviour to draw a line between adjacent non-null dataPoints by setting connectNullData to true. + * Default: false + * Example: true, false + */ + connectNullData?: boolean; + /** + * Sets the Line Dash Type of line wherever null data is present. + * Note: + * 1.Will effect only if connectNullData is set to true. + * 2.Supported with all Line and Area Charts. + * 3.Not Supported on IE8. + * Default: "dash" + * Supported Line Dash Types: + * “solid” + * “shortDash” + * “shortDot” + * “shortDashDot” + * “shortDashDotDot” + * "dot" + * “dash” + * “dashDot” + * “longDash” + * “longDashDot” + * “longDashDotDot” + */ + nullDataLineDashType?: string; + } + + class ChartDataSeries extends ChartDataSeriesOptions { + /** + * Returns the specified property of dataSeries + * @param propertyName Name of the property. + */ + get(propertyName: string): boolean | string | number | ChartDataPoint; + /** + * Sets the specified property of dataSeries. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: boolean | string | number | ChartDataPoint, updateChart: boolean): void; + /** + * Adds a new element of given type to the specified array. For example, it can be used to add new dataPoint to datPoints array. + * @param propertyName Name of the property + * @param options Option for the new element + * @param index Index of the array where the new element is to be added. Defaults to the length (end) of array. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + addTo(propertyName: string, options: ChartDataPoint, index?: number, updateChart?: boolean): void; + /** + * Removes specified dataSeries from data Array. + */ + remove(): void; } interface ChartDataPoint extends ChartDataCommon { /** - * Sets the x value. It determines the position of the dataPoint on X Axis. It can be numeric or a dateTime value. Values can be positive or Negative. - * Default: null - * Example: 10, 20, 30 .. - * new Date(2011, 08, 01) - */ - x?: any; + * Sets the x value. It determines the position of the dataPoint on X Axis. It can be numeric or a dateTime value. Values can be positive or Negative. + * If no x value is provided, they are automatically set sequentially starting from zero + * Default: null + * Example: 10, 20, 30 .. + * new Date(2011, 08, 01) + */ + x?: number | Date; /** - * Sets the y value of dataPoint. It determines the position of dataPoint on Y Axis. Values can be positive or Negative - * Default: null - * Example: 5, 20, -30 .. - */ - y?: number; + * Sets the y value of dataPoint. It determines the position of dataPoint on Y Axis. Values can be positive or Negative + * Default: null + * Example: 5, 20, -30 .. + */ + y?: number | null; /** - * Sets the z value of dataPoint. It is only applicable in case of Bubble chart. This value determines the size of the bubble. - * Default: 1 - * Example: 10, 20, 35.. - */ + * Sets the z value of dataPoint. It is only applicable in case of Bubble chart. This value determines the size of the bubble. + * Default: 1 + * Example: 10, 20, 35.. + */ z?: number; /** - * Sets label value of a dataPoint. The value appears next to the dataPoint on axisX Line. If not provided, it takes x value for label. - * Default: x value - * Example: "label1", "label2".. - */ + * Sets label value of a dataPoint. The value appears next to the dataPoint on axisX Line. If not provided, it takes x value for label. + * Default: x value + * Example: "label1", "label2".. + */ label?: string; /** - * Sets the exploded value of dataPoint. It is applicable only in case of Pie and Doughnut Charts. This property causes the Pie/Doughnut slice to separate out. - * Default: true - * Example: true, false - */ + * Sets the exploded value of dataPoint. It is applicable only in case of Pie and Doughnut Charts. This property causes the Pie/Doughnut slice to separate out. + * Default: true + * Example: true, false + */ exploded?: boolean; - /** - * Sets the color of marker that is displayed on legend. This property works only with Pie and Doughnut charts. Value of legendMarkerColor can be "HTML Color Name" or "hex" code. - * Default: dataSeries marker color - * Example: "red", "#008000".. - */ - legendMarkerColor?: string; } } +declare function CanvasJS(): void; +export = CanvasJS; +export as namespace CanvasJS; diff --git a/types/canvasjs/tsconfig.json b/types/canvasjs/tsconfig.json index 218036fa08..459ca95138 100644 --- a/types/canvasjs/tsconfig.json +++ b/types/canvasjs/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "canvasjs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/canvasjs/tslint.json b/types/canvasjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/canvasjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai-http/chai-http-tests.ts b/types/chai-http/chai-http-tests.ts index 83e434f9e1..c9c80c31ed 100644 --- a/types/chai-http/chai-http-tests.ts +++ b/types/chai-http/chai-http-tests.ts @@ -39,7 +39,7 @@ chai.request(app) chai.request(app) .get('/search') - .query({name: 'foo', limit: 10}); + .query({ name: 'foo', limit: 10 }); chai.request(app) .put('/user/me') @@ -98,3 +98,9 @@ function test1() { } when(chai.request(app).get('/')).done(() => console.log('success'), () => console.log('failure')); + +Promise.resolve(1) + .then(val => chai.request(app).get(`/user/${val}`)) + .then(res => { + chai.expect(res).to.have.status(200); + }); diff --git a/types/chai-http/index.d.ts b/types/chai-http/index.d.ts index 88ab7f8b84..5b09d7fd28 100644 --- a/types/chai-http/index.d.ts +++ b/types/chai-http/index.d.ts @@ -1,8 +1,10 @@ // Type definitions for chai-http 3.0 // Project: https://github.com/chaijs/chai-http // Definitions by: Wim Looman -// Liam Jones +// Liam Jones +// Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// @@ -60,9 +62,9 @@ declare global { end(callback?: (err: any, res: Response) => void): FinishedRequest; } - interface FinishedRequest { - then(success?: (res: Response) => void, failure?: (err: any) => void): FinishedRequest; - catch(failure?: (err: any) => void): FinishedRequest; + interface FinishedRequest{ + then(success?: (res: T) => TR1 | PromiseLike, failure?: (err: any) => TR2 | PromiseLike): FinishedRequest; + catch(failure?: (err: any) => void): FinishedRequest; } interface Agent { diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index ee61cf5575..42ba4c1804 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -7366,7 +7366,7 @@ declare namespace chrome.webRequest { interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent {} interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { - addListener(callback: (details: WebAuthenticationChallengeDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + addListener(callback: (details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; } interface WebResponseErrorEvent extends _WebResponseHeadersEvent {} diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index b95da5774f..287f1d1a5e 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -54,18 +54,29 @@ let mixedOrUndefinedExtent: [d3Array.Primitive | NumCoercible, d3Array.Primitive let dateOrUndefinedExtent: [Date, Date] | [undefined, undefined]; let numbersArray = [10, 20, 30, 40, 50]; -const numbersOrUndefinedArray = [10, 20, undefined, null, 40, 50]; -const stringyNumbersArray = ['10', '20', '30', '40', '50']; -const numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)]; -const dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; -const mixedObjectArray = [ +let numbersOrUndefinedArray = [10, 20, undefined, null, 40, 50]; +let stringyNumbersArray = ['10', '20', '30', '40', '50']; +let numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)]; +let dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; + +let mixedObjectArray = [ new MixedObject(10, new Date(2016, 6, 1)), new MixedObject(20, new Date(2016, 7, 30)), new MixedObject(30, new Date(2015, 3, 15)), new MixedObject(40, new Date(2014, 3, 15)), new MixedObject(50, new Date(2017, 4, 15)) ]; -const mixedObjectOrUndefinedArray = [...mixedObjectArray, undefined]; + +let mixedObjectOrUndefinedArray = [...mixedObjectArray, undefined]; + +let typedArray = Uint8Array.from(numbersArray); +let readonlyNumbersArray = numbersArray as ReadonlyArray; +let readonlyNumbersOrUndefinedArray = numbersOrUndefinedArray as ReadonlyArray; +let readonlyStringyNumbersArray = stringyNumbersArray as ReadonlyArray; +let readonlyNumericArray = numericArray as ReadonlyArray; +let readonlyDateArray = dateArray as ReadonlyArray; +let readonlyMixedObjectArray = mixedObjectArray as ReadonlyArray; +let readonlyMixedObjectOrUndefinedArray = mixedObjectOrUndefinedArray as ReadonlyArray; function accessorMixedObjectToNum(datum: MixedObject, index: number, array: MixedObject[]): number { return datum.num; @@ -104,6 +115,14 @@ strOrUndefined = d3Array.max(stringyNumbersArray); numericOrUndefined = d3Array.max(numericArray); dateOrUndefined = d3Array.max(dateArray); +// ArrayLike test cases + +numOrUndefined = d3Array.max(typedArray); +numOrUndefined = d3Array.max(readonlyNumbersOrUndefinedArray); +strOrUndefined = d3Array.max(readonlyStringyNumbersArray); +numericOrUndefined = d3Array.max(readonlyNumericArray); +dateOrUndefined = d3Array.max(readonlyDateArray); + // with accessors numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNum); @@ -112,6 +131,7 @@ numericOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumeric) dateOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToDate); numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumOrUndefined); strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefined = d3Array.max(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // min() ----------------------------------------------------------------------- @@ -122,6 +142,14 @@ strOrUndefined = d3Array.min(stringyNumbersArray); numericOrUndefined = d3Array.min(numericArray); dateOrUndefined = d3Array.min(dateArray); +// ArrayLike test cases + +numOrUndefined = d3Array.min(typedArray); +numOrUndefined = d3Array.min(readonlyNumbersOrUndefinedArray); +strOrUndefined = d3Array.min(readonlyStringyNumbersArray); +numericOrUndefined = d3Array.min(readonlyNumericArray); +dateOrUndefined = d3Array.min(readonlyDateArray); + // with accessors numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNum); @@ -130,6 +158,7 @@ numericOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumeric) dateOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToDate); numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumOrUndefined); strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefined = d3Array.max(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // extent() -------------------------------------------------------------------- @@ -140,6 +169,14 @@ strOrUndefinedExtent = d3Array.extent(stringyNumbersArray); numericOrUndefinedExtent = d3Array.extent(numericArray); dateOrUndefinedExtent = d3Array.extent(dateArray); +// ArrayLike test cases + +numOrUndefinedExtent = d3Array.extent(typedArray); +numOrUndefinedExtent = d3Array.extent(readonlyNumbersOrUndefinedArray); +strOrUndefinedExtent = d3Array.extent(readonlyStringyNumbersArray); +numericOrUndefinedExtent = d3Array.extent(readonlyNumericArray); +dateOrUndefinedExtent = d3Array.extent(readonlyDateArray); + // with accessors numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNum); @@ -148,6 +185,7 @@ mixedOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToN dateMixedOrUndefined = d3Array.extent(mixedObjectArray, accessorMixedObjectToDate); numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumOrUndefined); strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefinedExtent = d3Array.extent(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // mean() ---------------------------------------------------------------------- @@ -155,8 +193,14 @@ numOrUndefined = d3Array.mean(numbersArray); numOrUndefined = d3Array.mean(numericArray); numOrUndefined = d3Array.mean(numbersOrUndefinedArray); +numOrUndefined = d3Array.mean(typedArray); +numOrUndefined = d3Array.mean(readonlyNumbersOrUndefinedArray); +numOrUndefined = d3Array.mean(readonlyNumericArray); +numOrUndefined = d3Array.mean(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.mean(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.mean(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.mean(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // median() -------------------------------------------------------------------- @@ -164,8 +208,14 @@ numOrUndefined = d3Array.median(numbersArray); numOrUndefined = d3Array.median(numericArray); numOrUndefined = d3Array.median(numbersOrUndefinedArray); +numOrUndefined = d3Array.median(typedArray); +numOrUndefined = d3Array.median(readonlyNumbersArray); +numOrUndefined = d3Array.median(readonlyNumericArray); +numOrUndefined = d3Array.median(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.median(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.median(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.median(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // quantile() ------------------------------------------------------------------ @@ -173,8 +223,14 @@ numOrUndefined = d3Array.quantile(numbersArray, 0.5); numOrUndefined = d3Array.quantile(numericArray, 0.5); numOrUndefined = d3Array.quantile(numbersOrUndefinedArray, 0.5); +numOrUndefined = d3Array.quantile(typedArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumbersArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumericArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumbersOrUndefinedArray, 0.5); + numOrUndefined = d3Array.quantile(mixedObjectArray, 0.5, accessorMixedObjectToNum); numOrUndefined = d3Array.quantile(mixedObjectOrUndefinedArray, 0.5, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.quantile(readonlyMixedObjectOrUndefinedArray, 0.5, accessorMixedObjectToNumOrUndefined); // sum() ----------------------------------------------------------------------- @@ -182,8 +238,14 @@ numOrUndefined = d3Array.sum(numbersArray); numOrUndefined = d3Array.sum(numericArray); numOrUndefined = d3Array.sum(numbersOrUndefinedArray); +numOrUndefined = d3Array.sum(typedArray); +numOrUndefined = d3Array.sum(readonlyNumbersArray); +numOrUndefined = d3Array.sum(readonlyNumericArray); +numOrUndefined = d3Array.sum(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.sum(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.sum(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.sum(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // deviation() ----------------------------------------------------------------- @@ -191,8 +253,14 @@ numOrUndefined = d3Array.deviation(numbersArray); numOrUndefined = d3Array.deviation(numericArray); numOrUndefined = d3Array.deviation(numbersOrUndefinedArray); +numOrUndefined = d3Array.deviation(typedArray); +numOrUndefined = d3Array.deviation(readonlyNumbersArray); +numOrUndefined = d3Array.deviation(readonlyNumericArray); +numOrUndefined = d3Array.deviation(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.deviation(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.deviation(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.deviation(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // variance() ------------------------------------------------------------------ @@ -200,16 +268,29 @@ numOrUndefined = d3Array.variance(numbersArray); numOrUndefined = d3Array.variance(numericArray); numOrUndefined = d3Array.variance(numbersOrUndefinedArray); +numOrUndefined = d3Array.variance(typedArray); +numOrUndefined = d3Array.variance(readonlyNumbersArray); +numOrUndefined = d3Array.variance(readonlyNumericArray); +numOrUndefined = d3Array.variance(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.variance(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.variance(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.variance(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // ----------------------------------------------------------------------------- // Test Searching Arrays // ----------------------------------------------------------------------------- +numbersArray = [0, 2, 3, 4, 7, 8]; +stringyNumbersArray = ['0', '2', '3', '4', '7', '8']; +dateArray = [new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)]; +typedArray = Uint8Array.from(numbersArray); + // scan() ---------------------------------------------------------------------- numOrUndefined = d3Array.scan(numbersArray); +numOrUndefined = d3Array.scan(typedArray); +numOrUndefined = d3Array.scan(readonlyNumbersArray); numOrUndefined = d3Array.scan(mixedObjectArray, (a, b) => { const aElem: MixedObject = a; @@ -217,53 +298,113 @@ numOrUndefined = d3Array.scan(mixedObjectArray, (a, b) => { return a.num - b.num; }); +numOrUndefined = d3Array.scan(readonlyMixedObjectArray, (a, b) => { + const aElem: MixedObject = a; + const bElem: MixedObject = b; + return a.num - b.num; +}); + numOrUndefined = d3Array.scan(mixedObjectOrUndefinedArray, (a, b) => { const aElem: MixedObject | undefined = a; const bElem: MixedObject | undefined = b; return a && b ? a.num - b.num : NaN; }); +numOrUndefined = d3Array.scan(readonlyMixedObjectOrUndefinedArray, (a, b) => { + const aElem: MixedObject | undefined = a; + const bElem: MixedObject | undefined = b; + return a && b ? a.num - b.num : NaN; +}); + // bisectLeft() ---------------------------------------------------------------- -num = d3Array.bisectLeft([0, 2, 3, 4, 7, 8], 4); -num = d3Array.bisectLeft([0, 2, 3, 4, 7, 8], 4, 1); -num = d3Array.bisectLeft([0, 2, 3, 4, 7, 8], 4, 1, 4); +num = d3Array.bisectLeft(numbersArray, 4); +num = d3Array.bisectLeft(numbersArray, 4, 1); +num = d3Array.bisectLeft(numbersArray, 4, 1, 4); -num = d3Array.bisectLeft(['0', '2', '3', '4', '7', '8'], '21'); -num = d3Array.bisectLeft(['0', '2', '3', '4', '7', '8'], '21', 1); -num = d3Array.bisectLeft(['0', '2', '3', '4', '7', '8'], '21', 1, 4); +num = d3Array.bisectLeft(stringyNumbersArray, '21'); +num = d3Array.bisectLeft(stringyNumbersArray, '21', 1); +num = d3Array.bisectLeft(stringyNumbersArray, '21', 1, 4); -num = d3Array.bisectLeft([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1)); -num = d3Array.bisectLeft([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1); -num = d3Array.bisectLeft([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1, 2); +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisectLeft(typedArray, 4); +num = d3Array.bisectLeft(typedArray, 4, 1); +num = d3Array.bisectLeft(typedArray, 4, 1, 4); + +num = d3Array.bisectLeft(readonlyNumbersArray, 4); +num = d3Array.bisectLeft(readonlyNumbersArray, 4, 1); +num = d3Array.bisectLeft(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21'); +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1), 1, 2); // bisectRight() --------------------------------------------------------------- -num = d3Array.bisectRight([0, 2, 3, 4, 7, 8], 4); -num = d3Array.bisectRight([0, 2, 3, 4, 7, 8], 4, 1); -num = d3Array.bisectRight([0, 2, 3, 4, 7, 8], 4, 1, 4); +num = d3Array.bisectRight(numbersArray, 4); +num = d3Array.bisectRight(numbersArray, 4, 1); +num = d3Array.bisectRight(numbersArray, 4, 1, 4); -num = d3Array.bisectRight(['0', '2', '3', '4', '7', '8'], '21'); -num = d3Array.bisectRight(['0', '2', '3', '4', '7', '8'], '21', 1); -num = d3Array.bisectRight(['0', '2', '3', '4', '7', '8'], '21', 1, 4); +num = d3Array.bisectRight(stringyNumbersArray, '21'); +num = d3Array.bisectRight(stringyNumbersArray, '21', 1); +num = d3Array.bisectRight(stringyNumbersArray, '21', 1, 4); -num = d3Array.bisectRight([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1)); -num = d3Array.bisectRight([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1); -num = d3Array.bisectRight([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1, 2); +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisectRight(typedArray, 4); +num = d3Array.bisectRight(typedArray, 4, 1); +num = d3Array.bisectRight(typedArray, 4, 1, 4); + +num = d3Array.bisectRight(readonlyNumbersArray, 4); +num = d3Array.bisectRight(readonlyNumbersArray, 4, 1); +num = d3Array.bisectRight(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21'); +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1), 1, 2); // bisect() -------------------------------------------------------------------- -num = d3Array.bisect([0, 2, 3, 4, 7, 8], 4); -num = d3Array.bisect([0, 2, 3, 4, 7, 8], 4, 1); -num = d3Array.bisect([0, 2, 3, 4, 7, 8], 4, 1, 4); +num = d3Array.bisect(numbersArray, 4); +num = d3Array.bisect(numbersArray, 4, 1); +num = d3Array.bisect(numbersArray, 4, 1, 4); -num = d3Array.bisect(['0', '2', '3', '4', '7', '8'], '21'); -num = d3Array.bisect(['0', '2', '3', '4', '7', '8'], '21', 1); -num = d3Array.bisect(['0', '2', '3', '4', '7', '8'], '21', 1, 4); +num = d3Array.bisect(stringyNumbersArray, '21'); +num = d3Array.bisect(stringyNumbersArray, '21', 1); +num = d3Array.bisect(stringyNumbersArray, '21', 1, 4); -num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1)); -num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1); -num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1, 2); +num = d3Array.bisect(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisect(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisect(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisect(typedArray, 4); +num = d3Array.bisect(typedArray, 4, 1); +num = d3Array.bisect(typedArray, 4, 1, 4); + +num = d3Array.bisect(readonlyNumbersArray, 4); +num = d3Array.bisect(readonlyNumbersArray, 4, 1); +num = d3Array.bisect(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisect(readonlyStringyNumbersArray, '21'); +num = d3Array.bisect(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisect(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1), 1, 2); // bisector() ------------------------------------------------------------------ @@ -283,11 +424,19 @@ num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14) num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14), 1); num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14), 3, 4); +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14)); +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14), 1); +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14), 3, 4); + // bisect right num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14)); num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14), 1); num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14), 3, 4); +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14)); +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14), 1); +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14), 3, 4); + // ascending() ----------------------------------------------------------------- num = d3Array.ascending(undefined, 20); @@ -308,32 +457,44 @@ num = d3Array.descending(new Date(2016, 6, 13), new Date(2016, 6, 14)); // merge() --------------------------------------------------------------------- -let testArrays: MixedObject[][] = [ - [ - new MixedObject(10, new Date(2016, 6, 1)), - new MixedObject(20, new Date(2016, 7, 30)), - new MixedObject(30, new Date(2015, 3, 15)), - new MixedObject(40, new Date(2014, 3, 15)), - new MixedObject(50, new Date(2017, 4, 15)) - ], - [ - new MixedObject(40, new Date(2016, 3, 1)), - new MixedObject(50, new Date(2016, 9, 30)), - ] +let testArray1 = [ + new MixedObject(10, new Date(2016, 6, 1)), + new MixedObject(20, new Date(2016, 7, 30)), + new MixedObject(30, new Date(2015, 3, 15)), + new MixedObject(40, new Date(2014, 3, 15)), + new MixedObject(50, new Date(2017, 4, 15)) ]; +let testArray2 = [ + new MixedObject(40, new Date(2016, 3, 1)), + new MixedObject(50, new Date(2016, 9, 30)), +]; + +let testArrays: MixedObject[][] = [testArray1, testArray2]; + +let readonlyTestArray1 = testArray1 as ReadonlyArray; +let readonlyTestArray2 = testArray2 as ReadonlyArray; +let readonlyTestArrays = [testArray1, testArray2] as ReadonlyArray>; + let mergedArray: MixedObject[]; mergedArray = d3Array.merge(testArrays); // inferred type mergedArray = d3Array.merge(testArrays); // explicit type // mergedArray = d3Array.merge([[10, 40, 30], [15, 30]]); // fails, type mismatch +// mergedArray = d3Array.merge([testArray1, [15, 30]]); // fails, type mismatch + +mergedArray = d3Array.merge(readonlyTestArrays); // inferred type +mergedArray = d3Array.merge(readonlyTestArrays); // explicit type // cross() --------------------------------------------------------------------- let crossed: Array<[string, number]>; -crossed = d3Array.cross(['x', 'y'], [1, 2]); -crossed = d3Array.cross(['x', 'y'], [1, 2]); +const chars = ['x', 'y']; +const nums = [1, 2]; + +crossed = d3Array.cross(chars, nums); +crossed = d3Array.cross(chars, nums); let strArray: string[] = d3Array.cross([2, 3], [5, 6], (a, b) => (a + b) + 'px'); strArray = d3Array.cross([2, 3], [5, 6], (a, b) => { @@ -342,6 +503,21 @@ strArray = d3Array.cross([2, 3], [5, 6], (a, b) => { return (aa + bb) + 'px'; }); +const readonlyChars = chars as ReadonlyArray; +const readonlyNums = new Uint8Array(nums); + +crossed = d3Array.cross(readonlyChars, readonlyNums); +crossed = d3Array.cross(readonlyChars, readonlyNums); + +strArray = d3Array.cross([2, 3] as ReadonlyArray, new Uint8ClampedArray([5, 6]), (a, b) => (a + b) + 'px'); +strArray = d3Array.cross([2, 3] as ReadonlyArray, new Uint8ClampedArray([5, 6]), (a, b) => { + const aa: number = a; + const bb: number = b; + return (aa + bb) + 'px'; +}); + +d3Array.cross(new Uint8Array([1, 2, 3, 4, 5]), new Uint8Array([10, 20, 30, 40, 50])); + // pairs() --------------------------------------------------------------------- let pairs: Array<[MixedObject, MixedObject]>; @@ -355,10 +531,21 @@ numbersArray = d3Array.pairs(mergedArray, (a, b) => { return bb.num - aa.num; }); +const readonlyMergedArray = mergedArray as ReadonlyArray; +pairs = d3Array.pairs(readonlyMergedArray); + +numbersArray = d3Array.pairs(readonlyMergedArray, (a, b) => b.num - a.num); +numbersArray = d3Array.pairs(readonlyMergedArray, (a, b) => { + const aa: MixedObject = a; + const bb: MixedObject = b; + return bb.num - aa.num; +}); + // permute() ------------------------------------------------------------------- // getting a permutation of array elements mergedArray = d3Array.permute(mergedArray, [1, 0, 2, 5, 3, 4, 6]); +mergedArray = d3Array.permute(readonlyMergedArray, [1, 0, 2, 5, 3, 4, 6]); // Getting an ordered array with object properties @@ -380,10 +567,20 @@ numbersArray = d3Array.range(1, 10, 0.5); // shuffle() ------------------------------------------------------------------- mergedArray = d3Array.shuffle(mergedArray); - mergedArray = d3Array.shuffle(mergedArray, 1); - mergedArray = d3Array.shuffle(mergedArray, 1, 3); +// mergedArray = d3Array.shuffle(readonlyMergedArray); // fails, shuffle mutates input array in-place + +// Test each TypedArray explicitly. Can't use ArrayLike in this case because shuffle is mutable and ArrayLike would include ReadonlyArray +let resultInt8: Int8Array = d3Array.shuffle(new Int8Array(numbersArray)); +let resultUint8: Uint8Array = d3Array.shuffle(new Uint8Array(numbersArray)); +let resultUint8Clamped: Uint8ClampedArray = d3Array.shuffle(new Uint8ClampedArray(numbersArray)); +let resultInt16: Int16Array = d3Array.shuffle(new Int16Array(numbersArray)); +let resultUint6: Uint16Array = d3Array.shuffle(new Uint16Array(numbersArray)); +let resultInt32: Int32Array = d3Array.shuffle(new Int32Array(numbersArray)); +let resultUint32: Uint32Array = d3Array.shuffle(new Uint32Array(numbersArray)); +let resultFloat32: Float32Array = d3Array.shuffle(new Float32Array(numbersArray)); +let resultFloat64: Float64Array = d3Array.shuffle(new Float64Array(numbersArray)); // ticks() --------------------------------------------------------------------- @@ -399,32 +596,13 @@ numDiff = d3Array.tickStep(1, 10, 5); // transpose() ----------------------------------------------------------------- -testArrays = d3Array.transpose([ - [ - new MixedObject(10, new Date(2016, 6, 1)), - new MixedObject(50, new Date(2017, 4, 15)) - ], - [ - new MixedObject(40, new Date(2016, 3, 1)), - new MixedObject(50, new Date(2016, 9, 30)), - ] -]); +testArrays = d3Array.transpose([testArray1, testArray2]); +testArrays = d3Array.transpose([readonlyTestArray1, readonlyTestArray2] as ReadonlyArray>); // zip() ----------------------------------------------------------------------- -testArrays = d3Array.zip( - [ - new MixedObject(10, new Date(2016, 6, 1)), - new MixedObject(20, new Date(2016, 7, 30)), - new MixedObject(30, new Date(2015, 3, 15)), - new MixedObject(40, new Date(2014, 3, 15)), - new MixedObject(50, new Date(2017, 4, 15)) - ], - [ - new MixedObject(40, new Date(2016, 3, 1)), - new MixedObject(50, new Date(2016, 9, 30)), - ] -); +testArrays = d3Array.zip(testArray1, testArray2); +testArrays = d3Array.zip(readonlyTestArray1, readonlyTestArray2); // ----------------------------------------------------------------------------- // Test Histogram @@ -447,7 +625,7 @@ testHistogram = d3Array.histogram(); testHistogram = testHistogram.value((d, i, data) => { const datum: MixedObject = d; // d is of type MixedObject const index: number = i; // i is number - const array: MixedObject[] = data; // data is of type MixedObject[] + const array: ArrayLike = data; // data is of type MixedObject[] return datum.date; }); @@ -496,8 +674,10 @@ testHistogram = testHistogram.thresholds(tScale.ticks(timeYear)); // Use histogram generator ===================================================== +numbersArray = [-1, 0, 1, 1, 3, 20, 234]; + let defaultBins: Array>; -defaultBins = defaultHistogram([-1, 0, 1, 1, 3, 20, 234]); +defaultBins = defaultHistogram(numbersArray); let defaultBin: d3Array.Bin; defaultBin = defaultBins[0]; @@ -509,6 +689,7 @@ num = defaultBin.x1; // bin upper bound is number let testBins: Array>; testBins = testHistogram(mixedObjectArray); +testBins = testHistogram(readonlyMixedObjectArray); let testBin: d3Array.Bin; testBin = testBins[0]; @@ -520,8 +701,18 @@ date = testBin.x1; // bin upper bound is Date // Histogram Tresholds ========================================================= -num = d3Array.thresholdFreedmanDiaconis([-1, 0, 1, 1, 3, 20, 234], -1, 234); +numbersArray = [-1, 0, 1, 1, 3, 20, 234]; +typedArray = new Uint8Array(numbersArray); +readonlyNumbersArray = numbersArray as ReadonlyArray; -num = d3Array.thresholdScott([-1, 0, 1, 1, 3, 20, 234], -1, 234); +num = d3Array.thresholdFreedmanDiaconis(numbersArray, -1, 234); +num = d3Array.thresholdFreedmanDiaconis(typedArray, -1, 234); +num = d3Array.thresholdFreedmanDiaconis(readonlyNumbersArray, -1, 234); -num = d3Array.thresholdSturges([-1, 0, 1, 1, 3, 20, 234]); +num = d3Array.thresholdScott(numbersArray, -1, 234); +num = d3Array.thresholdScott(typedArray, -1, 234); +num = d3Array.thresholdScott(readonlyNumbersArray, -1, 234); + +num = d3Array.thresholdSturges(numbersArray); +num = d3Array.thresholdSturges(typedArray); +num = d3Array.thresholdSturges(readonlyNumbersArray); diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index aee2ef38c7..67cd291f22 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -28,133 +28,133 @@ export interface Numeric { /** * Return the maximum value in the array of strings using natural order. */ -export function max(array: string[]): string | undefined; +export function max(array: ArrayLike): string | undefined; /** * Return the maximum value in the array of numbers using natural order. */ -export function max(array: T[]): T | undefined; +export function max(array: ArrayLike): T | undefined; /** * Return the maximum value in the array using natural order and a projection function to map values to strings. */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined; +export function max(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): string | undefined; /** * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined; +export function max(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): U | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: string[]): string | undefined; +export function min(array: ArrayLike): string | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[]): T | undefined; +export function min(array: ArrayLike): T | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined; +export function min(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): string | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined; +export function min(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): U | undefined; /** * Return the min and max simultaneously. */ -export function extent(array: string[]): [string, string] | [undefined, undefined]; +export function extent(array: ArrayLike): [string, string] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: T[]): [T, T] | [undefined, undefined]; +export function extent(array: ArrayLike): [T, T] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): [string, string] | [undefined, undefined]; +export function extent(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): [string, string] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): [U, U] | [undefined, undefined]; +export function extent(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): [U, U] | [undefined, undefined]; /** * Return the mean of an array of numbers */ -export function mean(array: Array): number | undefined; -export function mean(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; +export function mean(array: ArrayLike): number | undefined; +export function mean(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; /** * Return the median of an array of numbers */ -export function median(array: Array): number | undefined; -export function median(array: T[], accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined; +export function median(array: ArrayLike): number | undefined; +export function median(array: ArrayLike, accessor: (element: T, i: number, array: ArrayLike) => number | undefined | null): number | undefined; /** * Returns the p-quantile of an array of numbers */ -export function quantile(array: Array, p: number): number | undefined; -export function quantile(array: T[], p: number, accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined; +export function quantile(array: ArrayLike, p: number): number | undefined; +export function quantile(array: ArrayLike, p: number, accessor: (element: T, i: number, array: ArrayLike) => number | undefined | null): number | undefined; /** * Compute the sum of an array of numbers. */ -export function sum(array: Array): number; +export function sum(array: ArrayLike): number; /** * Compute the sum of an array, using the given accessor to convert values to numbers. */ -export function sum(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number; +export function sum(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array of numbers. */ -export function deviation(array: Array): number | undefined; +export function deviation(array: ArrayLike): number | undefined; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array, * using the given accessor to convert values to numbers. */ -export function deviation(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; +export function deviation(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array of numbers. */ -export function variance(array: Array): number | undefined; +export function variance(array: ArrayLike): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array, * using the given accessor to convert values to numbers. */ -export function variance(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; +export function variance(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; // -------------------------------------------------------------------------------------- // Searching Arrays // -------------------------------------------------------------------------------------- -export function scan(array: number[], comparator?: (a: number, b: number) => number): number | undefined; -export function scan(array: T[], comparator: (a: T, b: T) => number): number | undefined; +export function scan(array: ArrayLike, comparator?: (a: number, b: number) => number): number | undefined; +export function scan(array: ArrayLike, comparator: (a: T, b: T) => number): number | undefined; -export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number; -export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number; -export function bisectLeft(array: Date[], x: Date, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: Date, lo?: number, hi?: number): number; -export function bisectRight(array: number[], x: number, lo?: number, hi?: number): number; -export function bisectRight(array: string[], x: string, lo?: number, hi?: number): number; -export function bisectRight(array: Date[], x: Date, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: Date, lo?: number, hi?: number): number; export const bisect: typeof bisectRight; export interface Bisector { - left(array: T[], x: U, lo?: number, hi?: number): number; - right(array: T[], x: U, lo?: number, hi?: number): number; + left(array: ArrayLike, x: U, lo?: number, hi?: number): number; + right(array: ArrayLike, x: U, lo?: number, hi?: number): number; } export function bisector(comparator: (a: T, b: U) => number): Bisector; @@ -184,7 +184,7 @@ export function descending(a: Primitive | undefined, b: Primitive | undefined): * @param a First input array. * @param b Second input array. */ -export function cross(a: S[], b: T[]): Array<[S, T]>; +export function cross(a: ArrayLike, b: ArrayLike): Array<[S, T]>; /** * Returns the Cartesian product of the two arrays a and b. @@ -195,12 +195,12 @@ export function cross(a: S[], b: T[]): Array<[S, T]>; * @param b Second input array. * @param reducer A reducer function taking as input an element from "a" and "b" and returning a reduced value. */ -export function cross(a: S[], b: T[], reducer: (a: S, b: T) => U): U[]; +export function cross(a: ArrayLike, b: ArrayLike, reducer: (a: S, b: T) => U): U[]; /** * Merges the specified arrays into a single array. */ -export function merge(arrays: T[][]): T[]; +export function merge(arrays: ArrayLike>): T[]; /** * For each adjacent pair of elements in the specified array, returns a new array of tuples of elements i and i - 1. @@ -208,7 +208,7 @@ export function merge(arrays: T[][]): T[]; * * @param array Array of input elements */ -export function pairs(array: T[]): Array<[T, T]>; +export function pairs(array: ArrayLike): Array<[T, T]>; /** * For each adjacent pair of elements in the specified array, in order, invokes the specified reducer function passing the element i and element i - 1. * Returns the resulting array of pair-wise reduced elements. @@ -217,17 +217,17 @@ export function pairs(array: T[]): Array<[T, T]>; * @param array Array of input elements * @param reducer A reducer function taking as input to adjecent elements of the input array and returning a reduced value. */ -export function pairs(array: T[], reducer: (a: T, b: T) => U): U[]; +export function pairs(array: ArrayLike, reducer: (a: T, b: T) => U): U[]; /** * Given the specified array, return an array corresponding to the list of indices in 'keys'. */ -export function permute(array: { [key: number]: T }, keys: number[]): T[]; +export function permute(array: { [key: number]: T }, keys: ArrayLike): T[]; /** * Given the specified object, return an array corresponding to the list of property names in 'keys'. */ -export function permute(object: { [key: string]: T }, keys: string[]): T[]; +export function permute(object: { [key: string]: T }, keys: ArrayLike): T[]; /** * Generates a 0-based numeric sequence. The output range does not include 'stop'. @@ -243,6 +243,15 @@ export function range(start: number, stop: number, step?: number): number[]; * Randomizes the order of the specified array using the Fisher–Yates shuffle. */ export function shuffle(array: T[], lo?: number, hi?: number): T[]; +export function shuffle(array: Int8Array, lo?: number, hi?: number): Int8Array; +export function shuffle(array: Uint8Array, lo?: number, hi?: number): Uint8Array; +export function shuffle(array: Uint8ClampedArray, lo?: number, hi?: number): Uint8ClampedArray; +export function shuffle(array: Int16Array, lo?: number, hi?: number): Int16Array; +export function shuffle(array: Uint16Array, lo?: number, hi?: number): Uint16Array; +export function shuffle(array: Int32Array, lo?: number, hi?: number): Int32Array; +export function shuffle(array: Uint32Array, lo?: number, hi?: number): Uint32Array; +export function shuffle(array: Float32Array, lo?: number, hi?: number): Float32Array; +export function shuffle(array: Float64Array, lo?: number, hi?: number): Float64Array; /** * Generate an array of approximately count + 1 uniformly-spaced, nicely-rounded values between start and stop (inclusive). @@ -289,14 +298,14 @@ export function tickStep(start: number, stop: number, count: number): number; /** * Transpose a matrix provided in Array of Arrays format. */ -export function transpose(matrix: T[][]): T[][]; +export function transpose(matrix: ArrayLike>): T[][]; /** * Returns an array of arrays, where the ith array contains the ith element from each of the argument arrays. * The returned array is truncated in length to the shortest array in arrays. If arrays contains only a single array, the returned array * contains one-element arrays. With no arguments, the returned array is empty. */ -export function zip(...arrays: T[][]): T[][]; +export function zip(...arrays: Array>): T[][]; // -------------------------------------------------------------------------------------- // Histogram @@ -310,20 +319,20 @@ export interface Bin extends Array { /** * Type definition for threshold generator which returns the count of recommended thresholds */ -export type ThresholdCountGenerator = (values: number[], min?: number, max?: number) => number; +export type ThresholdCountGenerator = (values: ArrayLike, min?: number, max?: number) => number; /** * Type definition for threshold generator which returns an array of recommended thresholds */ -export type ThresholdArrayGenerator = (values: Value[], min?: Value, max?: Value) => Value[]; +export type ThresholdArrayGenerator = (values: ArrayLike, min?: Value, max?: Value) => Value[]; export interface HistogramGenerator { - (data: Datum[]): Array>; - value(): (d: Datum, i: number, data: Datum[]) => Value; - value(valueAccessor: (d: Datum, i: number, data: Datum[]) => Value): this; - domain(): (values: Value[]) => [Value, Value]; + (data: ArrayLike): Array>; + value(): (d: Datum, i: number, data: ArrayLike) => Value; + value(valueAccessor: (d: Datum, i: number, data: ArrayLike) => Value): this; + domain(): (values: ArrayLike) => [Value, Value]; domain(domain: [Value, Value]): this; - domain(domainAccessor: (values: Value[]) => [Value, Value]): this; + domain(domainAccessor: (values: ArrayLike) => [Value, Value]): this; thresholds(): ThresholdCountGenerator | ThresholdArrayGenerator; /** * Divide the domain uniformly into approximately count bins. IMPORTANT: This threshold @@ -357,7 +366,7 @@ export interface HistogramGenerator { * @param thresholds Array of threshold values used for binning. The elements must * be of the same type as the materialized values of the histogram. */ - thresholds(thresholds: Value[]): this; + thresholds(thresholds: ArrayLike): this; /** * Set a threshold accessor function, which returns the array of values to be used as * thresholds in determining the bins. @@ -379,8 +388,8 @@ export function histogram(): HistogramGenera // Histogram Thresholds // -------------------------------------------------------------------------------------- -export function thresholdFreedmanDiaconis(values: number[], min: number, max: number): number; // of type ThresholdCountGenerator +export function thresholdFreedmanDiaconis(values: ArrayLike, min: number, max: number): number; // of type ThresholdCountGenerator -export function thresholdScott(values: number[], min: number, max: number): number; // of type ThresholdCountGenerator +export function thresholdScott(values: ArrayLike, min: number, max: number): number; // of type ThresholdCountGenerator -export function thresholdSturges(values: number[]): number; // of type ThresholdCountGenerator +export function thresholdSturges(values: ArrayLike): number; // of type ThresholdCountGenerator diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 00c9302740..5516e43559 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -715,6 +715,8 @@ declare namespace Draft { createEntity(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): ContentState; getEntity(key: string): EntityInstance; getLastCreatedEntityKey(): string; + mergeEntityData(key: string, toMerge: { [key: string]: any }): ContentState; + getBlockMap(): BlockMap; getSelectionBefore(): SelectionState; diff --git a/types/electron-packager/index.d.ts b/types/electron-packager/index.d.ts index 99b232388b..7a4504c386 100644 --- a/types/electron-packager/index.d.ts +++ b/types/electron-packager/index.d.ts @@ -63,8 +63,8 @@ declare namespace electronPackager { OriginalFilename?: string; ProductName?: string; InternalName?: string; - "requested-execution-level": any; - "application-manifest": any; + "requested-execution-level"?: "asInvoker" | "highestAvailable" | "requireAdministrator"; + "application-manifest"?: string; } /** Electron-packager Options. */ @@ -188,7 +188,7 @@ declare namespace electronPackager { /** * The URL protocol scheme(s) to associate the app with */ - protocol?: string; + protocol?: string[]; /** * The descriptive name(s) of the URL protocol scheme(s) specified via the protocol option. * Maps to the CFBundleURLName metadata property. diff --git a/types/fetch-mock/fetch-mock-tests.ts b/types/fetch-mock/fetch-mock-tests.ts index c9b1737a47..02e360026e 100644 --- a/types/fetch-mock/fetch-mock-tests.ts +++ b/types/fetch-mock/fetch-mock-tests.ts @@ -1,4 +1,5 @@ import * as fetchMock from "fetch-mock"; +import { MockResponse } from "fetch-mock"; fetchMock.mock("http://test.com", 200); fetchMock.mock(/test\.com/, 200); @@ -65,3 +66,6 @@ const myMatcher: fetchMock.MockMatcherFunction = ( url: string, opts: fetchMock.MockRequest ) => true; + +fetchMock.flush().then(resolved => resolved.forEach(console.log)); +fetchMock.flush().catch(r => r); diff --git a/types/fetch-mock/index.d.ts b/types/fetch-mock/index.d.ts index f1c109bb53..4b89b1decd 100644 --- a/types/fetch-mock/index.d.ts +++ b/types/fetch-mock/index.d.ts @@ -1,6 +1,9 @@ -// Type definitions for fetch-mock 5.8 +// Type definitions for fetch-mock 5.12 // Project: https://github.com/wheresrhys/fetch-mock -// Definitions by: Alexey Svetliakov , Tamir Duberstein , Risto Keravuori +// Definitions by: Alexey Svetliakov +// Tamir Duberstein +// Risto Keravuori +// Chris Sinclair // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -333,6 +336,12 @@ declare namespace fetchMock { */ reset(): this; + /** + * Returns a promise that resolves once all fetches handled by fetch-mock + * have resolved. + */ + flush(): Promise; + /** * Returns all calls to fetch, grouped by whether fetch-mock matched * them or not. diff --git a/types/flatpickr/index.d.ts b/types/flatpickr/index.d.ts index fce4214c90..eb29ddfa14 100644 --- a/types/flatpickr/index.d.ts +++ b/types/flatpickr/index.d.ts @@ -70,6 +70,7 @@ declare namespace Flatpickr { weekNumbers?: boolean; wrap?: boolean; locale?: string | Locale; + plugins?: any[]; } interface Locale { diff --git a/types/google-cloud__storage/bucket.d.ts b/types/google-cloud__storage/bucket.d.ts deleted file mode 100644 index 75829380cf..0000000000 --- a/types/google-cloud__storage/bucket.d.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { ReadStream } from "fs"; -import { Channel, ChannelConfig } from "./channel"; -import { File } from "./file"; -import { - Acl, - ApiResponse, - UploadOptions -} from "./storage"; - -/** - * A bucket in the cloud. - */ -export class Bucket { - acl: Acl; - combine(sources: string[] | File[], destination: string [] | File[]): Promise<[File, ApiResponse]>; - create(config?: BucketConfig): Promise<[Bucket, ApiResponse]>; - createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]>; - delete(): Promise<[ApiResponse]>; - deleteFiles(query?: BucketQuery): Promise; - exists(): Promise<[boolean]>; - file(name: string, options?: BucketFileOptions): File; - get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]>; - getFiles(query?: BucketQuery): Promise<[File[]]>; - getFilesStream(query?: BucketQuery): ReadStream; - getMetadata(): Promise<[BucketMetadata, ApiResponse]>; - id: string; - makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]>; - makePublic(options?: BucketPrivacyOptions): Promise<[File[]]>; - metadata: BucketMetadata; - name: string; - setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]>; - upload(localPath: string, options?: UploadOptions): Promise<[File]>; -} - -/** - * Bucket configuration. - */ -export interface BucketConfig { - coldline?: boolean; - dra?: boolean; - location?: string; - multiRegional?: boolean; - nearline?: boolean; - regional?: boolean; - versioning?: { - enabled?: boolean - }; -} - -/** - * Options for getting a file. - */ -export interface BucketFileOptions { - generation?: string | number; -} - -/** - * Options for getting a bucket. - */ -export interface BucketGetOptions { - autoCreate?: boolean; -} - -/** - * Bucket metadata. - */ -export interface BucketMetadata { - etag?: string; - id?: string; - kind?: string; - location?: string; - metageneration?: string; - name?: string; - projectNumber?: string; - selfLink?: string; - storageClass?: string; - timeCreated?: string; - updated?: string; -} - -/** - * The options for making the bucket private. - */ -export interface BucketPrivacyOptions { - includeFiles?: boolean; - force?: boolean; -} - -/** - * Query a bucket. - */ -export interface BucketQuery { - autoPaginate?: boolean; - delimiter?: string; - prefix?: string; - maxApiCalls?: number; - maxResults?: number; - pageToken?: string; - versions?: boolean; -} \ No newline at end of file diff --git a/types/google-cloud__storage/channel.d.ts b/types/google-cloud__storage/channel.d.ts deleted file mode 100644 index ede6d73e3d..0000000000 --- a/types/google-cloud__storage/channel.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { ApiResponse } from "./storage"; - -/** - * This class allows you interact with Google Cloud Storage. - */ -export class Channel { - stop(): Promise<[ApiResponse]>; -} - -/** - * Channel configuration. - */ -export interface ChannelConfig { - address: string; -} diff --git a/types/google-cloud__storage/file.d.ts b/types/google-cloud__storage/file.d.ts deleted file mode 100644 index bc212d3786..0000000000 --- a/types/google-cloud__storage/file.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { ReadStream, WriteStream } from "fs"; -import { Bucket } from "./bucket"; -import { - Acl, - ApiResponse, - DownloadOptions, - ReadStreamOptions, - UploadOptions, - WriteStreamOptions -} from "./storage"; - -/** - * Options for specifying the content length range. - */ -export interface ContentLengthRange { - max?: number; - min?: number; -} - -/** - * A file in the cloud. - */ -export class File { - acl: Acl; - copy(destination: string | Bucket | File): Promise<[File, ApiResponse]>; - createReadStream(options?: ReadStreamOptions): ReadStream; - createWriteStream(options?: WriteStreamOptions): WriteStream; - delete(): Promise<[ApiResponse]>; - download(options?: DownloadOptions): Promise<[string]>; - exists(): Promise<[boolean]>; - get(): Promise<[File, ApiResponse]>; - getMetadata(): Promise<[FileMetadata, ApiResponse]>; - getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]>; - getSignedUrl(config?: SignedUrlConfig): Promise<[string]>; - makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]>; - makePublic(): Promise<[ApiResponse]>; - move(destination: string | Bucket | File): Promise<[File, ApiResponse]>; - name: string; - save(data: string, options?: WriteStreamOptions): Promise; - setEncryptionKey(encryptionKey: string | Buffer): File; - setMetadata(metadata: FileMetadata): Promise<[ApiResponse]>; -} - -/** - * File metadata. - */ -export interface FileMetadata { - contentType?: string; -} - -/** - * Options when setting the file as private. - */ -export interface FilePrivateOptions { - strict?: boolean; -} - -/** - * A signed policy allowing a user to upload a file with a POST. - */ -export interface SignedPolicy { - base64?: string; - signature?: string; - string?: string; -} - -/** - * Options when obtaining the signed policy. - */ -export interface SignedPolicyOptions { - acl?: string; - contentLengthRange?: ContentLengthRange; - equals?: string[] | [string[]]; - expires?: number | string; - max?: number; - min?: number; - startsWith?: string[] | [string[]]; - successRedirect?: string; - successStatus?: string; -} - -/** - * Options when obtaining a temporary signed URL for a file. - */ -export interface SignedUrlConfig { - action: string; - cname?: string; - contentMd5?: string; - contentType?: string; - expires?: number | string; - extensionHeaders?: {[key: string]: string}; - promptSaveAs?: string; - responseDisposition?: string; - responseType?: string; -} diff --git a/types/google-cloud__storage/google-cloud__storage-tests.ts b/types/google-cloud__storage/google-cloud__storage-tests.ts index a301aa063c..b46b4766a1 100644 --- a/types/google-cloud__storage/google-cloud__storage-tests.ts +++ b/types/google-cloud__storage/google-cloud__storage-tests.ts @@ -3,83 +3,83 @@ import * as fs from "fs"; // import Google Cloud Storage import { - Acl, - Bucket, - Channel, - File, - ApiResponse, - BucketConfig, - BucketFileOptions, - BucketGetOptions, - BucketMetadata, - BucketPrivacyOptions, - BucketQuery, - ChannelConfig, - DownloadOptions, - FileMetadata, - FilePrivateOptions, - ReadStreamOptions, - SignedPolicy, - SignedPolicyOptions, - SignedUrlConfig, - WriteStreamOptions, - UploadOptions, - Storage + Acl, + Bucket, + Channel, + File, + ApiResponse, + BucketConfig, + BucketFileOptions, + BucketGetOptions, + BucketMetadata, + BucketPrivacyOptions, + BucketQuery, + ChannelConfig, + DownloadOptions, + FileMetadata, + FilePrivateOptions, + ReadStreamOptions, + SignedPolicy, + SignedPolicyOptions, + SignedUrlConfig, + WriteStreamOptions, + UploadOptions } from "@google-cloud/storage"; +import * as CloudStorage from "@google-cloud/storage"; /** * Test the storage service. * @class TestStorage */ export class TestStorage { - // constants - static BUCKET_CONFIG: BucketConfig = { - multiRegional: true - }; + // constants + static BUCKET_CONFIG: BucketConfig = { + multiRegional: true + }; - // import Storage class - static gcs: Storage = new Storage(); + // import Storage class + static gcs = CloudStorage(); - // the bucket - private buckets: Bucket[] = []; + // the bucket + private buckets: Bucket[] = []; - /** - * @constructor - */ - constructor() { - // nothing to do - } + /** + * @constructor + */ + constructor() { + // nothing to do + } - /** - * Returns the bucket. - * @method bucket - * @param {string} name - * @return {Bucket} - */ - bucket(name: string): Bucket { - return TestStorage.gcs.bucket(name); - } + /** + * Returns the bucket. + * @method bucket + * @param {string} name + * @return {Bucket} + */ + bucket(name: string): Bucket { + return TestStorage.gcs.bucket(name); + } - /** - * Create a new bucket. - * @param {string} name - * @param {BucketConfig} metadata - * @return {Promise<[Bucket, ApiResponse]>} - */ - createBucket(name: string, config?: BucketConfig): Promise<[Bucket, ApiResponse]> { - // overwrite default values with custom config - config = Object.assign(TestStorage.BUCKET_CONFIG, config); + /** + * Create a new bucket. + * @param {string} name + * @param {BucketConfig} metadata + * @return {Promise<[Bucket, ApiResponse]>} + */ + createBucket(name: string, config?: BucketConfig): Promise<[Bucket, ApiResponse]> { + // overwrite default values with custom config + config = Object.assign(TestStorage.BUCKET_CONFIG, config); - return TestStorage.gcs.createBucket(name, config); - } + return TestStorage.gcs.createBucket(name, config); + } - /** - * Query for buckets. - * @param {BucketQuery} query - */ - getBuckets(query?: BucketQuery): Promise<[Bucket[]]> { - return TestStorage.gcs.getBuckets(query); - } + /** + * Query for buckets. + * @param {BucketQuery} query + */ + getBuckets(query?: BucketQuery): Promise<[Bucket[]]> { + return TestStorage.gcs.getBuckets(query); + } } /** @@ -87,143 +87,143 @@ export class TestStorage { * @class TestBucket */ export class TestBucket { - // the bucket in the cloud - bucket: Bucket; + // the bucket in the cloud + bucket: Bucket; - /** - * Create a bucket. - * @param {BucketConfig} config - * @return {Promise<[Bucket, ApiResponse]>} - */ - create(config?: BucketConfig): Promise<[Bucket, ApiResponse]> { - return this.bucket.create(config); - } + /** + * Create a bucket. + * @param {BucketConfig} config + * @return {Promise<[Bucket, ApiResponse]>} + */ + create(config?: BucketConfig): Promise<[Bucket, ApiResponse]> { + return this.bucket.create(config); + } - /** - * Create a channel that will be notified when objects in this bucket changes. - * @method createChannel - * @param {string} id - * @param {ChannelConfig} config - * @return {Promise<[Channel, ApiResponse]>} - */ - createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]> { - return this.bucket.createChannel(id, config); - } + /** + * Create a channel that will be notified when objects in this bucket changes. + * @method createChannel + * @param {string} id + * @param {ChannelConfig} config + * @return {Promise<[Channel, ApiResponse]>} + */ + createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]> { + return this.bucket.createChannel(id, config); + } - /** - * Delete the bucket. - * @method delete - * @return {Promise<[ApiResponse]>} - */ - delete(): Promise<[ApiResponse]> { - return this.bucket.delete(); - } + /** + * Delete the bucket. + * @method delete + * @return {Promise<[ApiResponse]>} + */ + delete(): Promise<[ApiResponse]> { + return this.bucket.delete(); + } - /** - * Iterate over the bucket's files, calling file.delete() on each. - * @method deleteFiles - * @return {Promise} - */ - deleteFiles(query?: BucketQuery): Promise { - return this.bucket.deleteFiles(query); - } + /** + * Iterate over the bucket's files, calling file.delete() on each. + * @method deleteFiles + * @return {Promise} + */ + deleteFiles(query?: BucketQuery): Promise { + return this.bucket.deleteFiles(query); + } - /** - * Check if the bucket exists. - * @method exists - * @return {Promise<[boolean]>} - */ - exists(): Promise<[boolean]> { - return this.bucket.exists(); - } + /** + * Check if the bucket exists. + * @method exists + * @return {Promise<[boolean]>} + */ + exists(): Promise<[boolean]> { + return this.bucket.exists(); + } - /** - * Create a File object. - * @method file - * @param {string} name - * @param {BucketFileOptions} options - */ - file(name: string, options?: BucketFileOptions): File { - return this.bucket.file(name); - } + /** + * Create a File object. + * @method file + * @param {string} name + * @param {BucketFileOptions} options + */ + file(name: string, options?: BucketFileOptions): File { + return this.bucket.file(name); + } - /** - * Get a bucket if it exists. - * @method get - * @param {BucketGetOptions} options - */ - get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]> { - return this.bucket.get(options); - } + /** + * Get a bucket if it exists. + * @method get + * @param {BucketGetOptions} options + */ + get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]> { + return this.bucket.get(options); + } - /** - * Get File objects for the files currently in the bucket - * @method getFiles - * @param {BucketQuery} query - * @return {Promise<[File[]]>} - */ - getFiles(query?: BucketQuery): Promise<[File[]]> { - return this.bucket.getFiles(query); - } + /** + * Get File objects for the files currently in the bucket + * @method getFiles + * @param {BucketQuery} query + * @return {Promise<[File[]]>} + */ + getFiles(query?: BucketQuery): Promise<[File[]]> { + return this.bucket.getFiles(query); + } - /** - * Get File objects for the files currently in the bucket as a readable object stream. - * @method getFilesStream - * @param {BucketQuery} query - * @return {ReadStream} - */ - getFilesStream(query?: BucketQuery): fs.ReadStream { - return this.bucket.getFilesStream(query); - } + /** + * Get File objects for the files currently in the bucket as a readable object stream. + * @method getFilesStream + * @param {BucketQuery} query + * @return {ReadStream} + */ + getFilesStream(query?: BucketQuery): fs.ReadStream { + return this.bucket.getFilesStream(query); + } - /** - * Get the bucket's metadata. - * @method getMetadata - * @return {Promise<[BucketMetadata, ApiResponse]>} - */ - getMetadata(): Promise<[BucketMetadata, ApiResponse]> { - return this.bucket.getMetadata(); - } + /** + * Get the bucket's metadata. + * @method getMetadata + * @return {Promise<[BucketMetadata, ApiResponse]>} + */ + getMetadata(): Promise<[BucketMetadata, ApiResponse]> { + return this.bucket.getMetadata(); + } - /** - * Make the bucket listing private. - * @method makePrivate - * @param {} options - * @return Promise<[File[]]> - */ - makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]> { - return this.bucket.makePrivate(options); - } + /** + * Make the bucket listing private. + * @method makePrivate + * @param {} options + * @return Promise<[File[]]> + */ + makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]> { + return this.bucket.makePrivate(options); + } - /** - * Make the bucket publicly readable. - * @method makePublic - * @param {} options - * @return Promise<[File[]]> - */ - makePublic(options?: BucketPrivacyOptions): Promise<[File[]]> { - return this.bucket.makePublic(options); - } + /** + * Make the bucket publicly readable. + * @method makePublic + * @param {} options + * @return Promise<[File[]]> + */ + makePublic(options?: BucketPrivacyOptions): Promise<[File[]]> { + return this.bucket.makePublic(options); + } - /** - * Set the bucket's metadata. - * @method setMetadata - * @param {BucketMetadata} metadata - * @return {Promise<[ApiResponse]>} - */ - setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]> { - return this.bucket.setMetadata(metadata); - } + /** + * Set the bucket's metadata. + * @method setMetadata + * @param {BucketMetadata} metadata + * @return {Promise<[ApiResponse]>} + */ + setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]> { + return this.bucket.setMetadata(metadata); + } - /** - * Upload a file. - * @method upload - * @param {localPath} string - * @param {UploadOptions} options - */ - upload(localPath: string, options?: UploadOptions): Promise<[File]> { - return this.bucket.upload(localPath, options); - } + /** + * Upload a file. + * @method upload + * @param {localPath} string + * @param {UploadOptions} options + */ + upload(localPath: string, options?: UploadOptions): Promise<[File]> { + return this.bucket.upload(localPath, options); + } } /** @@ -231,168 +231,168 @@ export class TestBucket { * @class TestFile */ export class TestFile { - // the file in the cloud - file: File; + // the file in the cloud + file: File; - /** - * Copy this file to another file. - * By default, this will copy the file to the same bucket, but you can choose to copy it to another - * Bucket by providing a Bucket or File object or a URL starting with "gs:// ". - * @method copy - * @param {string} destination - * @return Promise<[File, ApiResponse]> - */ + /** + * Copy this file to another file. + * By default, this will copy the file to the same bucket, but you can choose to copy it to another + * Bucket by providing a Bucket or File object or a URL starting with "gs:// ". + * @method copy + * @param {string} destination + * @return Promise<[File, ApiResponse]> + */ - copy(destination: string | Bucket | File): Promise<[File, ApiResponse]> { - return this.file.copy(destination); - } + copy(destination: string | Bucket | File): Promise<[File, ApiResponse]> { + return this.file.copy(destination); + } - /** - * Create a readable stream to read the contents of the remote file. - * It can be piped to a writable stream or listened to for 'data' events to read a file's contents. - * @method createReadStream - * @param {ReadStreamOptions} options - * @return {ReadStream} - */ - createReadStream(options?: ReadStreamOptions): fs.ReadStream { - return this.file.createReadStream(options); - } + /** + * Create a readable stream to read the contents of the remote file. + * It can be piped to a writable stream or listened to for 'data' events to read a file's contents. + * @method createReadStream + * @param {ReadStreamOptions} options + * @return {ReadStream} + */ + createReadStream(options?: ReadStreamOptions): fs.ReadStream { + return this.file.createReadStream(options); + } - /** - * Create a writable stream to overwrite the contents of the file in your bucket. - * @method createWriteStream - * @param {WriteStreamOptions} options - * @return {WriteStream} - */ - createWriteStream(options?: WriteStreamOptions): fs.WriteStream { - return this.file.createWriteStream(options); - } + /** + * Create a writable stream to overwrite the contents of the file in your bucket. + * @method createWriteStream + * @param {WriteStreamOptions} options + * @return {WriteStream} + */ + createWriteStream(options?: WriteStreamOptions): fs.WriteStream { + return this.file.createWriteStream(options); + } - /** - * Delete the file. - * @method delete - * @return {Promise<[ApiResponse]>} - */ - delete(): Promise<[ApiResponse]> { - return this.file.delete(); - } + /** + * Delete the file. + * @method delete + * @return {Promise<[ApiResponse]>} + */ + delete(): Promise<[ApiResponse]> { + return this.file.delete(); + } - /** - * Convenience method to download a file into memory or to a local destination. - * @method download - * @param {DownloadOptions} options - * @return {Promise<[string]>} - */ - download(options?: DownloadOptions): Promise<[string]> { - return this.file.download(options); - } + /** + * Convenience method to download a file into memory or to a local destination. + * @method download + * @param {DownloadOptions} options + * @return {Promise<[string]>} + */ + download(options?: DownloadOptions): Promise<[string]> { + return this.file.download(options); + } - /** - * Check if the file exists. - * @method exists - * @return {Promise<[boolean]>} - */ - exists(): Promise<[boolean]> { - return this.file.exists(); - } + /** + * Check if the file exists. + * @method exists + * @return {Promise<[boolean]>} + */ + exists(): Promise<[boolean]> { + return this.file.exists(); + } - /** - * Get a file object and its metadata if it exists. - * @method get - * @return {Promise<[File, ApiResponse]>} - */ - get(): Promise<[File, ApiResponse]> { - return this.file.get(); - } + /** + * Get a file object and its metadata if it exists. + * @method get + * @return {Promise<[File, ApiResponse]>} + */ + get(): Promise<[File, ApiResponse]> { + return this.file.get(); + } - /** - * Get the file's metadata. - * @method getMetadata - * @return {Promise<[FileMetadata, ApiResponse]>} - */ - getMetadata(): Promise<[FileMetadata, ApiResponse]> { - return this.file.getMetadata(); - } + /** + * Get the file's metadata. + * @method getMetadata + * @return {Promise<[FileMetadata, ApiResponse]>} + */ + getMetadata(): Promise<[FileMetadata, ApiResponse]> { + return this.file.getMetadata(); + } - /** - * Get a signed policy document to allow a user to upload data with a POST request - * @method getSignedPolicy - * @param {SignedPolicyOptions} options - * @return {Promise<[SignedPolicy]>} - */ - getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]> { - return this.file.getSignedPolicy(options); - } + /** + * Get a signed policy document to allow a user to upload data with a POST request + * @method getSignedPolicy + * @param {SignedPolicyOptions} options + * @return {Promise<[SignedPolicy]>} + */ + getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]> { + return this.file.getSignedPolicy(options); + } - /** - * Get a signed URL to allow limited time access to the file - * @method getSignedUrl - * @param {SignedUrlConfig} config - * @return {Promise<[string]>} - */ - getSignedUrl(config?: SignedUrlConfig): Promise<[string]> { - return this.file.getSignedUrl(config); - } + /** + * Get a signed URL to allow limited time access to the file + * @method getSignedUrl + * @param {SignedUrlConfig} config + * @return {Promise<[string]>} + */ + getSignedUrl(config?: SignedUrlConfig): Promise<[string]> { + return this.file.getSignedUrl(config); + } - /** - * Make a file private to the project and remove all other permissions. - * @method makePrivate - * @param {FilePrivateOptions} options - * @return {Promise<[ApiResponse]>} - */ - makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]> { - return this.file.makePrivate(options); - } + /** + * Make a file private to the project and remove all other permissions. + * @method makePrivate + * @param {FilePrivateOptions} options + * @return {Promise<[ApiResponse]>} + */ + makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]> { + return this.file.makePrivate(options); + } - /** - * Set a file to be publicly readable and maintain all previous permissions. - * @method makePublic - * @return {Promise<[ApiResponse]>} - */ - makePublic(): Promise<[ApiResponse]> { - return this.file.makePublic(); - } + /** + * Set a file to be publicly readable and maintain all previous permissions. + * @method makePublic + * @return {Promise<[ApiResponse]>} + */ + makePublic(): Promise<[ApiResponse]> { + return this.file.makePublic(); + } - /** - * Move this file to another location. - * By default, this will move the file to the same bucket, but you can choose to move it to - * another Bucket by providing a Bucket or File object or a URL beginning with "gs:// ". - * @method move - * @param {string|Bucket|File} destination - * @return {Promise<[File, ApiResponse]>} - */ - move(destination: string | Bucket | File): Promise<[File, ApiResponse]> { - return this.file.move(destination); - } + /** + * Move this file to another location. + * By default, this will move the file to the same bucket, but you can choose to move it to + * another Bucket by providing a Bucket or File object or a URL beginning with "gs:// ". + * @method move + * @param {string|Bucket|File} destination + * @return {Promise<[File, ApiResponse]>} + */ + move(destination: string | Bucket | File): Promise<[File, ApiResponse]> { + return this.file.move(destination); + } - /** - * Write arbitrary data to a file. - * @param {string} data - * @param {WriteStreamOptions} options - * @return {Promise} - */ - save(data: string, options?: WriteStreamOptions): Promise { - return this.file.save(data); - } + /** + * Write arbitrary data to a file. + * @param {string} data + * @param {WriteStreamOptions} options + * @return {Promise} + */ + save(data: string, options?: WriteStreamOptions): Promise { + return this.file.save(data); + } - /** - * The Storage API allows you to use a custom key for server-side encryption. - * @param {string|Buffer} encryptionKey - * @return {File} - */ - setEncryptionKey(encryptionKey: string | Buffer): File { - return this.file.setEncryptionKey(encryptionKey); - } + /** + * The Storage API allows you to use a custom key for server-side encryption. + * @param {string|Buffer} encryptionKey + * @return {File} + */ + setEncryptionKey(encryptionKey: string | Buffer): File { + return this.file.setEncryptionKey(encryptionKey); + } - /** - * Merge the given metadata with the current remote file's metadata. - * This will set metadata if it was previously unset or update previously set metadata. - * To unset previously set metadata, set its value to null. - * @method setMetadata - * @param {FileMetadata} metadata - * @return {Promise<[ApiResponse]>} - */ - setMetadata(metadata: FileMetadata): Promise<[ApiResponse]> { - return this.file.setMetadata(metadata); - } + /** + * Merge the given metadata with the current remote file's metadata. + * This will set metadata if it was previously unset or update previously set metadata. + * To unset previously set metadata, set its value to null. + * @method setMetadata + * @param {FileMetadata} metadata + * @return {Promise<[ApiResponse]>} + */ + setMetadata(metadata: FileMetadata): Promise<[ApiResponse]> { + return this.file.setMetadata(metadata); + } } diff --git a/types/google-cloud__storage/index.d.ts b/types/google-cloud__storage/index.d.ts index 6141f8ee6b..dcea17e5d4 100644 --- a/types/google-cloud__storage/index.d.ts +++ b/types/google-cloud__storage/index.d.ts @@ -5,7 +5,340 @@ /// -export * from "./bucket"; -export * from "./channel"; -export * from "./file"; -export * from "./storage"; +import { ReadStream, WriteStream } from "fs"; + +type PromiseLibrary = () => PromiseLike; + +declare namespace Storage { + /** + * A bucket in the cloud. + */ + class Bucket { + constructor(storage: Storage, name: string); + acl: Storage.Acl; + combine(sources: string[] | File[], destination: string[] | File[]): Promise<[File, Storage.ApiResponse]>; + create(config?: BucketConfig): Promise<[Bucket, Storage.ApiResponse]>; + createChannel(id: string, config: ChannelConfig): Promise<[Channel, Storage.ApiResponse]>; + delete(): Promise<[Storage.ApiResponse]>; + deleteFiles(query?: BucketQuery): Promise; + exists(): Promise<[boolean]>; + file(name: string, options?: BucketFileOptions): File; + get(options?: BucketGetOptions): Promise<[Bucket, Storage.ApiResponse]>; + getFiles(query?: BucketQuery): Promise<[File[]]>; + getFilesStream(query?: BucketQuery): ReadStream; + getMetadata(): Promise<[BucketMetadata, Storage.ApiResponse]>; + id: string; + makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]>; + makePublic(options?: BucketPrivacyOptions): Promise<[File[]]>; + metadata: BucketMetadata; + name: string; + setMetadata(metadata?: BucketMetadata): Promise<[Storage.ApiResponse]>; + upload(localPath: string, options?: Storage.UploadOptions): Promise<[File]>; + } + + /** + * Bucket configuration. + */ + interface BucketConfig { + coldline?: boolean; + dra?: boolean; + location?: string; + multiRegional?: boolean; + nearline?: boolean; + regional?: boolean; + versioning?: { + enabled?: boolean + }; + } + + /** + * Options for getting a file. + */ + interface BucketFileOptions { + generation?: string | number; + } + + /** + * Options for getting a bucket. + */ + interface BucketGetOptions { + autoCreate?: boolean; + } + + /** + * Bucket metadata. + */ + interface BucketMetadata { + etag?: string; + id?: string; + kind?: string; + location?: string; + metageneration?: string; + name?: string; + projectNumber?: string; + selfLink?: string; + storageClass?: string; + timeCreated?: string; + updated?: string; + } + + /** + * The options for making the bucket private. + */ + interface BucketPrivacyOptions { + includeFiles?: boolean; + force?: boolean; + } + + /** + * Query a bucket. + */ + interface BucketQuery { + autoPaginate?: boolean; + delimiter?: string; + prefix?: string; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + versions?: boolean; + } + + /** + * Options for specifying the content length range. + */ + interface ContentLengthRange { + max?: number; + min?: number; + } + + /** + * A file in the cloud. + */ + class File { + constructor(bucket: Bucket, name: string, options?: BucketFileOptions); + acl: Acl; + copy(destination: string | Bucket | File): Promise<[File, ApiResponse]>; + createReadStream(options?: ReadStreamOptions): ReadStream; + createWriteStream(options?: WriteStreamOptions): WriteStream; + delete(): Promise<[ApiResponse]>; + download(options?: DownloadOptions): Promise<[Buffer]>; + exists(): Promise<[boolean]>; + get(): Promise<[File, ApiResponse]>; + getMetadata(): Promise<[FileMetadata, ApiResponse]>; + getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]>; + getSignedUrl(config?: SignedUrlConfig): Promise<[string]>; + makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]>; + makePublic(): Promise<[ApiResponse]>; + move(destination: string | Bucket | File): Promise<[File, ApiResponse]>; + name: string; + save(data: string, options?: WriteStreamOptions): Promise; + setEncryptionKey(encryptionKey: string | Buffer): File; + setMetadata(metadata: FileMetadata): Promise<[ApiResponse]>; + metadata?: FileMetadata; + } + + /** + * File metadata. + */ + interface FileMetadata { + contentType?: string; + } + + /** + * Options when setting the file as private. + */ + interface FilePrivateOptions { + strict?: boolean; + } + + /** + * A signed policy allowing a user to upload a file with a POST. + */ + interface SignedPolicy { + base64?: string; + signature?: string; + string?: string; + } + + /** + * Options when obtaining the signed policy. + */ + interface SignedPolicyOptions { + acl?: string; + contentLengthRange?: ContentLengthRange; + equals?: string[] | [string[]]; + expires?: number | string; + max?: number; + min?: number; + startsWith?: string[] | [string[]]; + successRedirect?: string; + successStatus?: string; + } + + /** + * Options when obtaining a temporary signed URL for a file. + */ + interface SignedUrlConfig { + action: string; + cname?: string; + contentMd5?: string; + contentType?: string; + expires?: number | string; + extensionHeaders?: { [key: string]: string }; + promptSaveAs?: string; + responseDisposition?: string; + responseType?: string; + } + + /** + * Access control list for storage buckets and files. + */ + interface Acl extends AclActions { + default: AclEntity; + owners: AclEntity; + readers: AclEntity; + writers: AclEntity; + } + + /** + * Actions that can be performed on all ACL entities, including the root Acl. + */ + interface AclActions { + add(options: AclOptions): Promise<[Acl, ApiResponse]>; + delete(options: AclOptions): Promise<[Acl, ApiResponse]>; + get(options: AclOptions): Promise<[Acl, ApiResponse]>; + update(options: AclOptions): Promise<[Acl, ApiResponse]>; + } + + /** + * An object of convenience methods to add or delete reader ACL permissions for a given entity. + */ + interface AclEntity extends AclActions { + addAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; + addAllUsers(): Promise<[Acl, ApiResponse]>; + addDomain(entity: string): Promise<[Acl, ApiResponse]>; + addGroup(entity: string): Promise<[Acl, ApiResponse]>; + addProject(entity: string): Promise<[Acl, ApiResponse]>; + addUser(entity: string): Promise<[Acl, ApiResponse]>; + deleteAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; + deleteAllUsers(): Promise<[Acl, ApiResponse]>; + deleteDomain(entity: string): Promise<[Acl, ApiResponse]>; + deleteGroup(entity: string): Promise<[Acl, ApiResponse]>; + deleteProject(entity: string): Promise<[Acl, ApiResponse]>; + deleteUser(entity: string): Promise<[Acl, ApiResponse]>; + } + + /** + * ACL options. + */ + interface AclOptions { + entity?: string; + role?: string; + generation?: number; + } + + /** + * The response object. + */ + interface ApiResponse { + etag?: string; + id?: string; + kind?: string; + location?: string; + metageneration?: string; + name?: string; + projectNumber?: string; + selfLink?: string; + storageClass?: string; + timeCreated?: string; + updated?: string; + } + + interface Credentials { + client_email?: string; + private_key?: string; + } + + interface ConfigurationObject { + autoRetry?: boolean; + credentials?: Credentials; + email?: string; + keyFilename?: string; + maxRetries?: number; + projectId?: string; + promise?: PromiseLibrary; + } + + /** + * The options when downloading a file. + */ + interface DownloadOptions extends ReadStreamOptions { + destination?: string; + } + + /** + * Options when reading a file stream. + */ + interface ReadStreamOptions { + end?: number; + start?: number; + validation?: string | boolean; + } + + /** + * Options when uploading file to bucket. + */ + interface UploadOptions extends WriteStreamOptions { + destination?: string; + } + + /** + * Options when writing to a file stream. + */ + interface WriteStreamOptions { + gzip?: boolean; + metadata?: FileMetadata; + offset?: number; + predefinedAcl?: string; + private?: boolean; + public?: boolean; + resumable?: boolean; + uri?: string; + validation?: string | boolean; + } + + /** + * The Storage class allows you interact with Google Cloud Storage. + */ + class Storage { + constructor(config?: ConfigurationObject); + acl: Acl; + bucket(name: string | Bucket): Bucket; + channel(id: string, resourceId: string): Channel; + createBucket(name: string, metadata?: BucketConfig): Promise<[Bucket, ApiResponse]>; + getBuckets(query?: BucketQuery): Promise<[Bucket[]]>; + getBucketsStream(query?: BucketQuery): Promise<[ReadStream]>; + Channel: (storage: Storage, id: string, resourceId: string) => Channel; + File: (bucket: Bucket, name: string, opts: BucketFileOptions) => File; + Bucket: (storage: Storage, name: string) => Bucket; + } + + /** + * This class allows you interact with Google Cloud Storage. + */ + class Channel { + constructor(storage: Storage, id: string, resourceId: string); + stop(): Promise<[Storage.ApiResponse]>; + } + + /** + * Channel configuration. + */ + interface ChannelConfig { + address: string; + } +} + +declare function Storage(config?: Storage.ConfigurationObject): Storage.Storage; + +export = Storage; diff --git a/types/google-cloud__storage/storage.d.ts b/types/google-cloud__storage/storage.d.ts deleted file mode 100644 index 34cbb3bef2..0000000000 --- a/types/google-cloud__storage/storage.d.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { ReadStream } from "fs"; -import { Bucket, BucketConfig, BucketQuery } from "./bucket"; -import { Channel } from "./channel"; -import { FileMetadata } from "./file"; - -/** - * Access control list for storage buckets and files. - */ -export class Acl extends AclActions { - default: AclEntity; - owners: AclEntity; - readers: AclEntity; - writers: AclEntity; -} - -/** - * Actions that can be performed on all ACL entities, including the root Acl. - */ -export class AclActions { - add(options: AclOptions): Promise<[Acl, ApiResponse]>; - delete(options: AclOptions): Promise<[Acl, ApiResponse]>; - get(options: AclOptions): Promise<[Acl, ApiResponse]>; - update(options: AclOptions): Promise<[Acl, ApiResponse]>; -} - -/** - * An object of convenience methods to add or delete reader ACL permissions for a given entity. - */ -export class AclEntity extends AclActions { - addAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; - addAllUsers(): Promise<[Acl, ApiResponse]>; - addDomain(entity: string): Promise<[Acl, ApiResponse]>; - addGroup(entity: string): Promise<[Acl, ApiResponse]>; - addProject(entity: string): Promise<[Acl, ApiResponse]>; - addUser(entity: string): Promise<[Acl, ApiResponse]>; - deleteAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; - deleteAllUsers(): Promise<[Acl, ApiResponse]>; - deleteDomain(entity: string): Promise<[Acl, ApiResponse]>; - deleteGroup(entity: string): Promise<[Acl, ApiResponse]>; - deleteProject(entity: string): Promise<[Acl, ApiResponse]>; - deleteUser(entity: string): Promise<[Acl, ApiResponse]>; -} - -/** - * ACL options. - */ -export interface AclOptions { - entity?: string; - role?: string; - generation?: number; -} - -/** - * The response object. - */ -export interface ApiResponse { - etag?: string; - id?: string; - kind?: string; - location?: string; - metageneration?: string; - name?: string; - projectNumber?: string; - selfLink?: string; - storageClass?: string; - timeCreated?: string; - updated?: string; -} - -export interface Credentials { - client_email?: string; - private_key?: string; -} - -export interface ConfigurationObject { - autoRetry?: boolean; - credentials?: Credentials; - email?: string; - keyFilename?: string; - maxRetries?: number; - projectId?: string; - promise?: PromiseLibrary; -} - -/** - * The options when downloading a file. - */ -export interface DownloadOptions extends ReadStreamOptions { - destination?: string; -} - -/** - * Options when reading a file stream. - */ -export interface ReadStreamOptions { - end?: number; - start?: number; - validation?: string | boolean; -} - -/** - * Options when uploading file to bucket. - */ -export interface UploadOptions extends WriteStreamOptions { - destination?: string; -} - -/** - * Options when writing to a file stream. - */ -export interface WriteStreamOptions { - gzip?: boolean; - metadata?: FileMetadata; - offset?: number; - predefinedAcl?: string; - private?: boolean; - public?: boolean; - resumable?: boolean; - uri?: string; - validation?: string | boolean; -} - -/** - * The Storage class allows you interact with Google Cloud Storage. - */ - export class Storage { - constructor(options?: ConfigurationObject); - acl: Acl; - bucket(name: string|Bucket): Bucket; - channel(id: string, resourceId: string): Channel; - createBucket(name: string, metadata?: BucketConfig): Promise<[Bucket, ApiResponse]>; - getBuckets(query?: BucketQuery): Promise<[Bucket[]]>; - getBucketsStream(query?: BucketQuery): Promise<[ReadStream]>; -} - -export type PromiseLibrary = () => PromiseLike; diff --git a/types/google-cloud__storage/tsconfig.json b/types/google-cloud__storage/tsconfig.json index 1495f211db..f579440bb8 100644 --- a/types/google-cloud__storage/tsconfig.json +++ b/types/google-cloud__storage/tsconfig.json @@ -11,10 +11,10 @@ "typeRoots": [ "../" ], + "types" : [], "paths":{ "@google-cloud/storage": ["google-cloud__storage"] }, - "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, @@ -22,4 +22,4 @@ "index.d.ts", "google-cloud__storage-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/gulp-modernizr/gulp-modernizr-tests.ts b/types/gulp-modernizr/gulp-modernizr-tests.ts new file mode 100644 index 0000000000..86b953b65c --- /dev/null +++ b/types/gulp-modernizr/gulp-modernizr-tests.ts @@ -0,0 +1,8 @@ +import { src, dest } from 'gulp'; +import * as gulpModernizr from 'gulp-modernizr'; + +let s1 = gulpModernizr(); +let s2 = gulpModernizr('filename.js', {}); +let s3 = gulpModernizr({cache: false}); + +src('fixtures.js').pipe(s1).pipe(s2); diff --git a/types/gulp-modernizr/index.d.ts b/types/gulp-modernizr/index.d.ts new file mode 100644 index 0000000000..c9dc3a60b8 --- /dev/null +++ b/types/gulp-modernizr/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for gulp-modernizr 1.0 +// Project: https://github.com/doctyper/gulp-modernizr +// Definitions by: remisery +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import stream = require('stream'); + +declare function GulpModernizr(parames?: GulpModernizr.Params): stream.Transform; +declare function GulpModernizr(file?: string, parames?: GulpModernizr.Params): stream.Transform; + +declare namespace GulpModernizr { + interface Params { + /** + * Avoid unnecessary builds (see Caching section below) + */ + cache?: boolean; + + /** + * Path to the build you're using for development. + */ + devFile?: string | false; + + /** + * Path to save out the built file + */ + dest?: string | false; + + /** + * Based on default settings on http://modernizr.com/download/ + */ + options?: { + classPrefix: string; + enableJSClass: boolean; + enableClasses: boolean; + }; + + /** + * By default, source is uglified before saving + */ + uglify?: boolean; + + /** + * Define any tests you want to explicitly include + */ + tests?: string[]; + + /** + * Useful for excluding any tests that this tool will match + * e.g. you use .notification class for notification elements, + * but don’t want the test for Notification API + */ + excludeTests?: string[]; + + /** + * By default, will crawl your project for references to Modernizr tests + * Set to false to disable + */ + crawl?: boolean; + + /** + * Set to true to pass in buffers via the "files" parameter below + */ + useBuffers?: boolean; + + /** + * By default, this task will crawl all *.js, *.css, *.scss files. + */ + files?: { src: string[] }; + + /** + * Have custom Modernizr tests? Add them here. + */ + customTests?: string[]; + } +} + +export = GulpModernizr; diff --git a/types/gulp-modernizr/tsconfig.json b/types/gulp-modernizr/tsconfig.json new file mode 100644 index 0000000000..28ad6706e0 --- /dev/null +++ b/types/gulp-modernizr/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-modernizr-tests.ts" + ] +} diff --git a/types/gulp-modernizr/tslint.json b/types/gulp-modernizr/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/gulp-modernizr/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gulp-mustache/gulp-mustache-tests.ts b/types/gulp-mustache/gulp-mustache-tests.ts new file mode 100644 index 0000000000..c069a1dd02 --- /dev/null +++ b/types/gulp-mustache/gulp-mustache-tests.ts @@ -0,0 +1,18 @@ +import * as mustache from "gulp-mustache"; +// noinspection ES6UnusedImports +import { Transform } from "stream"; + +mustache({ // $ExpectType Transform + msg: "Hello Gulp!" +}); + +mustache({ // $ExpectType Transform + msg: "Hello Gulp!", + nested_value: "I am nested.", + another_value: "1 2 3" +}, {}, { + some_inner_partial: "

{{nested_value}}

", + another_partial: "
{{another_value}}
" +}); + +mustache('your_json_file.json', {}, {}); // $ExpectType Transform diff --git a/types/gulp-mustache/index.d.ts b/types/gulp-mustache/index.d.ts new file mode 100644 index 0000000000..3b01944b19 --- /dev/null +++ b/types/gulp-mustache/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for gulp-mustache v 3.0 +// Project: https://github.com/rogeriopvl/gulp-mustache +// Definitions by: Christopher Durham +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from "stream"; + +declare namespace GulpMustache { + type View = Hash | string | undefined; + + interface Hash { + [key: string]: string; + } + + interface Options { + extension?: string; + tags?: ReadonlyArray | undefined; + } +} + +declare function GulpMustache(view: GulpMustache.View, + options?: GulpMustache.Options, + partials?: GulpMustache.Hash): Transform; + +export = GulpMustache; diff --git a/types/gulp-mustache/tsconfig.json b/types/gulp-mustache/tsconfig.json new file mode 100644 index 0000000000..df7c5074b4 --- /dev/null +++ b/types/gulp-mustache/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-mustache-tests.ts" + ] +} diff --git a/types/gulp-mustache/tslint.json b/types/gulp-mustache/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-mustache/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gulp-pug/gulp-pug-tests.ts b/types/gulp-pug/gulp-pug-tests.ts new file mode 100644 index 0000000000..1820c2c375 --- /dev/null +++ b/types/gulp-pug/gulp-pug-tests.ts @@ -0,0 +1,8 @@ +import { src, dest } from 'gulp'; +import * as gulpPug from 'gulp-pug'; + +let s1 = gulpPug(); +let s2 = gulpPug({}); +let s3 = gulpPug({ basedir: '.' }); + +src('fixtures.js').pipe(s1).pipe(s2).pipe(s3); diff --git a/types/gulp-pug/index.d.ts b/types/gulp-pug/index.d.ts new file mode 100644 index 0000000000..46a8a79239 --- /dev/null +++ b/types/gulp-pug/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for gulp-pug 3.3 +// Project: https://github.com/pugjs/gulp-pug#readme +// Definitions by: remisery +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import stream = require('stream'); + +import { Options } from 'pug'; + +declare function GulpPug(params?: GulpPug.Params): stream.Transform; + +declare namespace GulpPug { + interface Params extends Options { + locals?: any; + data?: any; + client?: boolean; + pug?: any; + verbose?: boolean; + } +} + +export = GulpPug; diff --git a/types/gulp-pug/tsconfig.json b/types/gulp-pug/tsconfig.json new file mode 100644 index 0000000000..58c3140198 --- /dev/null +++ b/types/gulp-pug/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-pug-tests.ts" + ] +} diff --git a/types/gulp-pug/tslint.json b/types/gulp-pug/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/gulp-pug/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gulp-size/gulp-size-tests.ts b/types/gulp-size/gulp-size-tests.ts index 9aea965329..4a325abe27 100644 --- a/types/gulp-size/gulp-size-tests.ts +++ b/types/gulp-size/gulp-size-tests.ts @@ -1,6 +1,3 @@ - - - import * as gulp from 'gulp'; import * as size from 'gulp-size'; import * as debug from 'gulp-debug'; @@ -11,9 +8,8 @@ gulp.task('default', () => .pipe(gulp.dest('dist')) ); - gulp.task('default', () => { - var s = size(); + let s = size(); return gulp.src('fixture.js') .pipe(s) @@ -21,6 +17,5 @@ gulp.task('default', () => { .pipe(debug({title: 'Total size ' + s.prettySize})); }); - size(); size({showFiles: true, gzip: true}); diff --git a/types/gulp-size/index.d.ts b/types/gulp-size/index.d.ts index 374c58565e..088b916984 100644 --- a/types/gulp-size/index.d.ts +++ b/types/gulp-size/index.d.ts @@ -1,16 +1,18 @@ -// Type definitions for gulp-size v1.2.3 +// Type definitions for gulp-size 2.1 // Project: https://github.com/sindresorhus/gulp-size // Definitions by: Tanguy Krotoff +// Remisery // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - declare namespace size { interface Options { showFiles?: boolean; gzip?: boolean; title?: string; + pretty?: boolean; + showTotal?: boolean; } interface SizeStream extends NodeJS.ReadWriteStream { diff --git a/types/gulp-size/tsconfig.json b/types/gulp-size/tsconfig.json index fe93b09ba6..0e924d2b94 100644 --- a/types/gulp-size/tsconfig.json +++ b/types/gulp-size/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -22,4 +22,4 @@ "index.d.ts", "gulp-size-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/gulp-size/tslint.json b/types/gulp-size/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/gulp-size/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gulp-uglify/composer.d.ts b/types/gulp-uglify/composer.d.ts new file mode 100644 index 0000000000..ec592ad5e8 --- /dev/null +++ b/types/gulp-uglify/composer.d.ts @@ -0,0 +1,18 @@ +import * as UglifyJS from 'uglify-js'; +import * as GulpUglify from 'gulp-uglify'; + +interface Composer { + (uglify: Uglify, log: Logger): typeof GulpUglify; +} + +interface Uglify { + minify: typeof UglifyJS.minify; +} + +interface Logger { + warn: typeof console.warn; +} + +declare const composer: Composer; + +export = composer; diff --git a/types/gulp-uglify/gulp-uglify-tests.ts b/types/gulp-uglify/gulp-uglify-tests.ts index 499ac15a37..172d7cae0b 100644 --- a/types/gulp-uglify/gulp-uglify-tests.ts +++ b/types/gulp-uglify/gulp-uglify-tests.ts @@ -1,17 +1,19 @@ import * as gulp from 'gulp'; import * as uglify from 'gulp-uglify'; +import pump = require('pump'); +import uglifyjs = require('uglify-js'); +import composer = require('gulp-uglify/composer'); -gulp.task('compress', function() { - var tsResult = gulp.src('lib/*.ts') +gulp.task('compress', () => { + const tsResult = gulp.src('lib/*.ts') .pipe(uglify()) .pipe(gulp.dest('dist')); }); -gulp.task('compress2', function() { - var tsResult = gulp.src('lib/*.ts') +gulp.task('compress2', () => { + const tsResult = gulp.src('lib/*.ts') .pipe(uglify({ mangle: false, - preserveComments: "some", compress: false, output: { max_line_len: 300 @@ -19,3 +21,34 @@ gulp.task('compress2', function() { })) .pipe(gulp.dest('dist')); }); + +gulp.task('compress', (cb) => { + pump([ + gulp.src('lib/*.js'), + uglify(), + gulp.dest('dist') + ], + cb + ); +}); + +const minify = composer(uglifyjs, console); + +gulp.task('compress', (cb) => { + // the same options as described above + const options = {}; + + pump([ + gulp.src('lib/*.js'), + minify(options), + gulp.dest('dist') + ], + cb + ); +}); + +gulp.task('compress', () => { + return gulp.src('lib/*.js') + .pipe(minify()) + .pipe(gulp.dest('dist')); +}); diff --git a/types/gulp-uglify/index.d.ts b/types/gulp-uglify/index.d.ts index 7dafe43efa..4b86c2f2e0 100644 --- a/types/gulp-uglify/index.d.ts +++ b/types/gulp-uglify/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for gulp-uglify +// Type definitions for gulp-uglify 3.0 // Project: https://github.com/terinjokes/gulp-uglify // Definitions by: Christopher Haws +// Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -23,14 +24,6 @@ declare namespace GulpUglify { * Pass an object to specify custom compressor options. Pass false to skip compression completely. */ compress?: UglifyJS.CompressorOptions | boolean; - - /** - * A convenience option for options.output.comments. Defaults to preserving no comments. - * all - Preserve all comments in code blocks - * some - Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license, @cc_on) - * function - Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false. - */ - preserveComments?: string | ((node: any, comment: UglifyJS.Tokenizer) => boolean); } } diff --git a/types/gulp-uglify/tsconfig.json b/types/gulp-uglify/tsconfig.json index d0ae9de799..16668a9b9f 100644 --- a/types/gulp-uglify/tsconfig.json +++ b/types/gulp-uglify/tsconfig.json @@ -6,20 +6,18 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], - "paths": { - "q": [ "q/v0" ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", + "composer.d.ts", "gulp-uglify-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/gulp-uglify/tslint.json b/types/gulp-uglify/tslint.json new file mode 100644 index 0000000000..a4bcc87748 --- /dev/null +++ b/types/gulp-uglify/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "callable-types": false + } +} diff --git a/types/helmet/index.d.ts b/types/helmet/index.d.ts index ee37b7d298..c5883ae70b 100644 --- a/types/helmet/index.d.ts +++ b/types/helmet/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for helmet // Project: https://github.com/helmetjs/helmet -// Definitions by: Cyril Schumacher , Evan Hahn +// Definitions by: Cyril Schumacher , Evan Hahn , Elliot Blackburn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import express = require('express'); @@ -19,7 +19,8 @@ declare namespace helmet { ieNoOpen?: boolean, noCache?: boolean, noSniff?: boolean, - xssFilter?: boolean | IHelmetXssFilterConfiguration + xssFilter?: boolean | IHelmetXssFilterConfiguration, + expectCt?: boolean | IHelmetExpectCtConfiguration, } export interface IHelmetContentSecurityPolicyDirectiveFunction { @@ -96,6 +97,12 @@ declare namespace helmet { setOnOldIE?: boolean; } + export interface IHelmetExpectCtConfiguration { + enforce?: boolean; + maxAge?: number; + reportUri?: string; + } + /** * @summary Interface for helmet class. * @interface @@ -179,5 +186,12 @@ declare namespace helmet { * @return {RequestHandler} The Request handler. */ xssFilter(options?: IHelmetXssFilterConfiguration): express.RequestHandler; + + /** + * @summary Adds the "Expect-CT" header. + * @param {helmet.IHelmetExpectCtConfiguration} options + * @returns {e.RequestHandler} + */ + expectCt(options?: IHelmetExpectCtConfiguration): express.RequestHandler; } } diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 914fb83f96..f8ae716c13 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -1455,6 +1455,11 @@ declare namespace Highcharts { * @since 3.0.8 */ drillup?(event: Event): void; + /** + * Fires after drilling up from all drilldown series. + * @since 4.2.4 + */ + drillupall?(event: Event): void; /** * Fires when the chart is finished loading. One parameter, event, is passed to the function. This contains common * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index 5ddc56420c..a17ee094c2 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -242,6 +242,7 @@ function test_ChartOptions() { click: () => { }, drilldown: () => { }, drillup: () => { }, + drillupall: () => { }, load: () => { }, redraw: () => { }, selection: () => { } diff --git a/types/hpp/hpp-tests.ts b/types/hpp/hpp-tests.ts new file mode 100644 index 0000000000..21432f3d3f --- /dev/null +++ b/types/hpp/hpp-tests.ts @@ -0,0 +1,17 @@ +import * as express from 'express'; +import * as hpp from 'hpp'; + +const app = express(); + +app.use(hpp()); + +app.use(hpp({ + checkBody: true, + checkBodyOnlyForContentType: 'urlencoded', + checkQuery: true, + whitelist: ['foo', 'bar'] +})); + +app.use(hpp({ + whitelist: 'foobar' +})); diff --git a/types/hpp/index.d.ts b/types/hpp/index.d.ts new file mode 100644 index 0000000000..6328df7d70 --- /dev/null +++ b/types/hpp/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for hpp 0.2 +// Project: https://github.com/analog-nico/hpp +// Definitions by: Michael Strobel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as express from 'express'; + +declare namespace hpp { + interface Options { + checkBody?: boolean; + checkBodyOnlyForContentType?: string; + checkQuery?: boolean; + whitelist?: string | string[]; + } +} + +declare function hpp(options?: hpp.Options): express.RequestHandler; + +export = hpp; diff --git a/types/hpp/tsconfig.json b/types/hpp/tsconfig.json new file mode 100644 index 0000000000..e355d78a8c --- /dev/null +++ b/types/hpp/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hpp-tests.ts" + ] +} diff --git a/types/hpp/tslint.json b/types/hpp/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hpp/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-url-superb/index.d.ts b/types/is-url-superb/index.d.ts new file mode 100644 index 0000000000..9369edc65e --- /dev/null +++ b/types/is-url-superb/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-url-superb 2.0 +// Project: https://github.com/sindresorhus/is-url-superb +// Definitions by: Michael Strobel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isUrl; + +declare function isUrl(str: string): boolean; diff --git a/types/is-url-superb/is-url-superb-tests.ts b/types/is-url-superb/is-url-superb-tests.ts new file mode 100644 index 0000000000..c804fc1b34 --- /dev/null +++ b/types/is-url-superb/is-url-superb-tests.ts @@ -0,0 +1,5 @@ +import isUrl = require('is-url-superb'); + +const url1: boolean = isUrl('http://todomvc.com'); +const url2: boolean = isUrl('//todomvc.com'); +const url3: boolean = isUrl('unicorn'); diff --git a/types/is-url-superb/tsconfig.json b/types/is-url-superb/tsconfig.json new file mode 100644 index 0000000000..069affddab --- /dev/null +++ b/types/is-url-superb/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-url-superb-tests.ts" + ] +} diff --git a/types/is-url-superb/tslint.json b/types/is-url-superb/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-url-superb/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/iso-3166-2/index.d.ts b/types/iso-3166-2/index.d.ts new file mode 100644 index 0000000000..42129fb444 --- /dev/null +++ b/types/iso-3166-2/index.d.ts @@ -0,0 +1,52 @@ +// Type definitions for iso-3166-2 0.6 +// Project: https://github.com/olahol/iso-3166-2.js +// Definitions by: Matt Rollins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type InfoOrEmptyRecord = T | {}; + +export namespace CountryInfo { + interface Partial { + name: string; + sub: SubdivisionInfo.Map; + } + interface Full extends Partial { + code: string; + } + + interface Map { + // full data if this country has been retrieved with country() at least once + [code: string]: Full | Partial; + } +} +export type CountryInfo = CountryInfo.Full; + +export namespace SubdivisionInfo { + interface Partial { + type: string; + name: string; + } + interface Full extends Partial { + countryName: string; + countryCode: string; + code: string; + regionCode: string; + } + + interface Map { + // full data if this subdivision has been retrieved with subdivision() at least once + [code: string]: Full | Partial; + } +} +export type SubdivisionInfo = SubdivisionInfo.Full; + +export function subdivision(countryCodeOrFullSubdivisionCode: string, subdivisionCodeOrName?: string): InfoOrEmptyRecord; + +export function country(countryCodeOrName: string): InfoOrEmptyRecord; + +export const data: CountryInfo.Map; + +// map of alpha 3 codes to alpha 3 codes +export const codes: { + [alpha3: string]: string +}; diff --git a/types/iso-3166-2/iso-3166-2-tests.ts b/types/iso-3166-2/iso-3166-2-tests.ts new file mode 100644 index 0000000000..0a0bca345a --- /dev/null +++ b/types/iso-3166-2/iso-3166-2-tests.ts @@ -0,0 +1,50 @@ +import * as iso3166 from "iso-3166-2"; + +// subdivision() and country() return {} on failure, which is nearly impossible to separate from a valid response in TypeScript; +// until a PR can be accepted on the original repo, this workaround makes accessing the original type possible. +function wrap(rawResult: T|{}): T|null { + if (Object.keys(rawResult).length) + return rawResult as T; + else + return null; +} + +iso3166.subdivision("SE-O"); +iso3166.subdivision("US-IN"); + +iso3166.subdivision("SWE", "O"); +iso3166.subdivision("US", "Indiana"); + +const indiana = wrap(iso3166.subdivision("US-IN")); +if (indiana) { + const name: string = indiana.name; + const type: string = indiana.type; + const code: string = indiana.code; + const regionCode: string = indiana.regionCode; + const countryCode: string = indiana.countryCode; + const countryName: string = indiana.countryName; +} + +iso3166.country("US"); +iso3166.country("SE"); +iso3166.country("SWE"); + +iso3166.country("United States"); +iso3166.country("Sweden"); + +const sweden = wrap(iso3166.country("SE")); +if (sweden) { + const name: string = sweden.name; + const subNameO: string = sweden.sub["SE-O"].name; + const code: string = sweden.code; +} + +const unitedStates = iso3166.data["US"]; +{ + const name: string = unitedStates.name; + const subNameIN: string = unitedStates.sub["US-IN"].name; +} + +const alpha3 = "SWE"; +const alpha2 = "SE"; +const codesWork = (alpha2 === iso3166.codes[alpha3]); diff --git a/types/iso-3166-2/tsconfig.json b/types/iso-3166-2/tsconfig.json new file mode 100644 index 0000000000..7ed345dd25 --- /dev/null +++ b/types/iso-3166-2/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iso-3166-2-tests.ts" + ] +} diff --git a/types/iso-3166-2/tslint.json b/types/iso-3166-2/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/iso-3166-2/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 267f1d4a1a..6506ddbb8e 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -175,7 +175,7 @@ declare namespace jest { type ProvidesCallback = (cb: DoneCallback) => any; - type Lifecycle = (fn: ProvidesCallback) => any; + type Lifecycle = (fn: ProvidesCallback, timeout?: number) => any; /** * Creates a test closure diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 4f780fd83b..ad63cc0a75 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -480,6 +480,12 @@ describe('strictNullChecks', () => { }); }); +describe('beforeEach with timeout', () => { + beforeEach(() => { + // this shouldn't take more than a second + }, 1000); +}); + class TestApi { constructor() { } testProp: boolean; diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 024dcc3ab8..d0e80de159 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -3017,7 +3017,7 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/after/} * @since 1.0 */ - after(...contents: Array | JQuery>): this; + after(...contents: Array | JQuery>): this; /** * Insert content, specified by the parameter, after each element in the set of matched elements. * @@ -3029,7 +3029,7 @@ interface JQuery extends Iterable * @since 1.4 * @since 1.10 */ - after(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + after(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; /** * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. * @@ -3133,7 +3133,7 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/append/} * @since 1.0 */ - append(...contents: Array | JQuery>): this; + append(...contents: Array | JQuery>): this; /** * Insert content, specified by the parameter, to the end of each element in the set of matched elements. * @@ -3144,7 +3144,7 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/append/} * @since 1.4 */ - append(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + append(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; /** * Insert every element in the set of matched elements to the end of the target. * @@ -3191,7 +3191,7 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/before/} * @since 1.0 */ - before(...contents: Array | JQuery>): this; + before(...contents: Array | JQuery>): this; /** * Insert content, specified by the parameter, before each element in the set of matched elements. * @@ -3203,7 +3203,7 @@ interface JQuery extends Iterable * @since 1.4 * @since 1.10 */ - before(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + before(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 /** * Attach a handler to an event for the elements. @@ -4595,7 +4595,7 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/prepend/} * @since 1.0 */ - prepend(...contents: Array | JQuery>): this; + prepend(...contents: Array | JQuery>): this; /** * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. * @@ -4606,7 +4606,7 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/prepend/} * @since 1.4 */ - prepend(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + prepend(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; /** * Insert every element in the set of matched elements to the beginning of the target. * diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index d223be9d5c..d81dd3b6f3 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -5130,7 +5130,7 @@ function JQuery() { function manipulation() { function after() { // $ExpectType JQuery - $('p').after('

', new Element(), new Text(), $('p'), [new Element(), new Text()]); + $('p').after('

', new Element(), new Text(), $('p').contents(), [new Element(), new Text()]); // $ExpectType JQuery $('p').after(function(index, html) { @@ -5189,13 +5189,13 @@ function JQuery() { // $ExpectType string html; - return $('p'); + return $('p').contents(); }); } function append() { // $ExpectType JQuery - $('p').append('

', new Element(), new Text(), $('p'), [new Element(), new Text()]); + $('p').append('

', new Element(), new Text(), $('p').contents(), [new Element(), new Text()]); // $ExpectType JQuery $('p').append(function(index, html) { @@ -5254,7 +5254,7 @@ function JQuery() { // $ExpectType string html; - return $('p'); + return $('p').contents(); }); // $ExpectType JQuery @@ -5263,7 +5263,7 @@ function JQuery() { function before() { // $ExpectType JQuery - $('p').before('

', new Element(), new Text(), $('p'), [new Element(), new Text()]); + $('p').before('

', new Element(), new Text(), $('p').contents(), [new Element(), new Text()]); // $ExpectType JQuery $('p').before(function(index, html) { @@ -5322,13 +5322,13 @@ function JQuery() { // $ExpectType string html; - return $('p'); + return $('p').contents(); }); } function prepend() { // $ExpectType JQuery - $('p').prepend('

', new Element(), new Text(), $('p'), [new Element(), new Text()]); + $('p').prepend('

', new Element(), new Text(), $('p').contents(), [new Element(), new Text()]); // $ExpectType JQuery $('p').prepend(function(index, html) { @@ -5387,7 +5387,7 @@ function JQuery() { // $ExpectType string html; - return $('p'); + return $('p').contents(); }); } diff --git a/types/jsonwebtoken/index.d.ts b/types/jsonwebtoken/index.d.ts index 246d107dbb..335a6f52b7 100644 --- a/types/jsonwebtoken/index.d.ts +++ b/types/jsonwebtoken/index.d.ts @@ -83,6 +83,8 @@ export interface SignCallback { (err: Error, encoded: string): void; } +export type Secret = string | Buffer | {key: string, passphrase: string} + /** * Synchronously sign the given payload into a JSON Web Token string * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string @@ -90,7 +92,7 @@ export interface SignCallback { * @param {SignOptions} [options] - Options for the signature * @returns {String} The JSON Web Token string */ -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: string | Buffer, options?: SignOptions): string; +export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, options?: SignOptions): string; /** * Sign the given payload into a JSON Web Token string @@ -99,8 +101,8 @@ export declare function sign(payload: string | Buffer | object, secretOrPrivateK * @param {SignOptions} [options] - Options for the signature * @param {Function} callback - Callback to get the encoded token on */ -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: string | Buffer, callback: SignCallback): void; -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: string | Buffer, options: SignOptions, callback: SignCallback): void; +export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, callback: SignCallback): void; +export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, options: SignOptions, callback: SignCallback): void; /** * Synchronously verify given token using a secret or a public key to get a decoded token diff --git a/types/jsonwebtoken/jsonwebtoken-tests.ts b/types/jsonwebtoken/jsonwebtoken-tests.ts index 650f80d2bc..9e495d31cb 100644 --- a/types/jsonwebtoken/jsonwebtoken-tests.ts +++ b/types/jsonwebtoken/jsonwebtoken-tests.ts @@ -36,6 +36,10 @@ token = jwt.sign(testObject, 'shhhhh', { keyid: "theKeyId"}); cert = fs.readFileSync('private.key'); // get private key token = jwt.sign(testObject, cert, { algorithm: 'RS256'}); +// sign with encrypted RSA SHA256 private key (only PEM encoding is supported) +const privKey: Buffer = fs.readFileSync('encrypted_private.key'); // get private key +const secret = {key: privKey.toString(), passphrase: 'keypwd'} +token = jwt.sign(testObject, secret, { algorithm: 'RS256' }); // the algorithm option is mandatory in this case // sign asynchronously jwt.sign(testObject, cert, { algorithm: 'RS256' }, function(err: Error, token: string) { diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 1a20c7f969..73ba5dd792 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -15,6 +15,7 @@ export class Client { export class KafkaClient extends Client { constructor(options?: KafkaClientOptions); on(eventName: "ready", cb: () => any): this; + on(eventName: "reconnect", cb: () => void): this; on(eventName: "error", cb: (error: any) => any): this; connect(): void; } diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 10974f11a2..c2a9a3d41e 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -11,6 +11,10 @@ declare namespace mapboxgl { export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; export function setRTLTextPlugin(pluginURL: string, callback: Function): void; + type LngLatLike = number[] | LngLat; + type LngLatBoundsLike = number[][] | LngLatLike[] | LngLatBounds; + type PointLike = number[] | Point; + /** * Map */ @@ -35,7 +39,7 @@ declare namespace mapboxgl { getBounds(): mapboxgl.LngLatBounds; - setMaxBounds(lnglatbounds?: mapboxgl.LngLatBounds | number[][]): this; + setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; setMinZoom(minZoom?: number): this; @@ -45,11 +49,11 @@ declare namespace mapboxgl { getMaxZoom(): number; - project(lnglat: mapboxgl.LngLat | number[]): mapboxgl.Point; + project(lnglat: LngLatLike): mapboxgl.Point; - unproject(point: mapboxgl.Point | number[]): mapboxgl.LngLat; + unproject(point: PointLike): mapboxgl.LngLat; - queryRenderedFeatures(pointOrBox?: mapboxgl.Point|number[]|mapboxgl.Point[]|number[][], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; + queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; querySourceFeatures(sourceID: string, parameters?: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; @@ -121,11 +125,11 @@ declare namespace mapboxgl { getCenter(): mapboxgl.LngLat; - setCenter(center: LngLat|number[], eventData?: mapboxgl.EventData): this; + setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - panTo(lnglat: mapboxgl.LngLat, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; + panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; getZoom(): number; @@ -151,7 +155,7 @@ declare namespace mapboxgl { setPitch(pitch: number, eventData?: EventData): this; - fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number | mapboxgl.PaddingOptions, offset?: Point|number[],maxZoom?: number }, eventData?: mapboxgl.EventData): this; + fitBounds(bounds: LngLatBoundsLike, options?: { linear?: boolean, easing?: Function, padding?: number | mapboxgl.PaddingOptions, offset?: PointLike, maxZoom?: number }, eventData?: mapboxgl.EventData): this; jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; @@ -191,7 +195,7 @@ declare namespace mapboxgl { boxZoom?: boolean; /** initial map center */ - center?: mapboxgl.LngLat | number[]; + center?: LngLatLike; /** Style class names with which to initialize the map */ classes?: string[]; @@ -223,7 +227,7 @@ declare namespace mapboxgl { logoPosition?: boolean; /** If set, the map is constrained to the given bounds. */ - maxBounds?: mapboxgl.LngLatBounds | number[][]; + maxBounds?: LngLatBoundsLike; /** Maximum zoom of the map */ maxZoom?: number; @@ -434,7 +438,7 @@ declare namespace mapboxgl { getLngLat(): mapboxgl.LngLat; - setLngLat(lnglat: mapboxgl.LngLat | number[]): this; + setLngLat(lnglat: LngLatLike): this; setText(text: string): this; @@ -450,7 +454,7 @@ declare namespace mapboxgl { anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; - offset?: number | Point | number[] | { [key:string]: Point | number[];}; + offset?: number | PointLike | { [key:string]: PointLike;}; } export interface Style { @@ -613,16 +617,22 @@ declare namespace mapboxgl { /** Return a LngLat as a string */ toString(): string; - static convert(input: number[]|mapboxgl.LngLat): mapboxgl.LngLat; + toBounds(radius: number): LngLatBounds; + + static convert(input: LngLatLike): mapboxgl.LngLat; } /** * LngLatBounds */ export class LngLatBounds { - sw: LngLat | number[]; - ne: LngLat | number[]; - constructor(sw?: LngLat, ne?: LngLat); + sw: LngLatLike; + ne: LngLatLike; + constructor(sw?: LngLatLike, ne?: LngLatLike); + + setNorthEast(ne: LngLatLike): this; + + setSouthWest(sw: LngLatLike): this; /** Extend the bounds to include a given LngLat or LngLatBounds. */ extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; @@ -661,7 +671,7 @@ declare namespace mapboxgl { toString(): string; /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ - static convert(input: mapboxgl.LngLatBounds | number[] | number[][]): mapboxgl.LngLatBounds; + static convert(input: LngLatBoundsLike): mapboxgl.LngLatBounds; } /** @@ -710,11 +720,11 @@ declare namespace mapboxgl { angleWithSep(x: number, y: number): number; - static convert(a: Array | Point): Point; + static convert(a: PointLike): Point; } export class Marker { - constructor(element?: HTMLElement, options?: { offset?: Point | number[] }); + constructor(element?: HTMLElement, options?: { offset?: PointLike }); addTo(map: Map): this; @@ -722,7 +732,7 @@ declare namespace mapboxgl { getLngLat(): LngLat; - setLngLat(lngLat: LngLat | number[]): this; + setLngLat(lngLat: LngLatLike): this; setPopup(popup?: Popup): this; @@ -807,7 +817,7 @@ declare namespace mapboxgl { duration?: number; easing?: Function; /** point, origin of movement relative to map center */ - offset?: Point | number[]; + offset?: PointLike; /** When set to false, no animation happens */ animate?: boolean; } @@ -817,7 +827,7 @@ declare namespace mapboxgl { */ export interface CameraOptions { /** Map center */ - center?: mapboxgl.LngLat | number[]; + center?: LngLatLike; /** Map zoom level */ zoom?: number; /** Map rotation bearing in degrees counter-clockwise from north */ @@ -825,7 +835,7 @@ declare namespace mapboxgl { /** Map angle in degrees at which the camera is looking at the ground */ pitch?: number; /** If zooming, the zoom center (defaults to map center) */ - around?: mapboxgl.LngLat | number[]; + around?: LngLatLike; } /** @@ -891,7 +901,7 @@ declare namespace mapboxgl { metadata?: any; ref?: string; - source?: string; + source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; "source-layer"?: string; @@ -959,10 +969,10 @@ declare namespace mapboxgl { } export interface LinePaint { "line-opacity"?: number | StyleFunction; - "line-color"?: string| StyleFunction; + "line-color"?: string | StyleFunction; "line-translate"?: number[]; "line-translate-anchor"?: "map" | "viewport"; - "line-width"?: number; + "line-width"?: number | StyleFunction; "line-gap-width"?: number | StyleFunction; "line-offset"?: number | StyleFunction; "line-blur"?: number | StyleFunction; diff --git a/types/marked/index.d.ts b/types/marked/index.d.ts index 63dad27b30..a4dc048cc8 100644 --- a/types/marked/index.d.ts +++ b/types/marked/index.d.ts @@ -1,9 +1,38 @@ -// Type definitions for Marked +// Type definitions for Marked 0.3 // Project: https://github.com/chjj/marked // Definitions by: William Orr +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface MarkedStatic { +export as namespace marked; + +export = marked; +/** + * Compiles markdown to HTML. + * + * @param src String of markdown source to be compiled + * @param callback Function called when the markdownString has been fully parsed when using async highlighting + * @return String of compiled HTML + */ +declare function marked(src: string, callback: (error: any | undefined, parseResult: string) => void): string; + +/** + * Compiles markdown to HTML. + * + * @param src String of markdown source to be compiled + * @param options Hash of options + * @param callback Function called when the markdownString has been fully parsed when using async highlighting + * @return String of compiled HTML + */ +declare function marked(src: string, options?: marked.MarkedOptions, callback?: (error: any | undefined, parseResult: string) => void): string; + +declare namespace marked { + /** + * @param src String of markdown source to be compiled + * @param options Hash of options + */ + function lexer(src: string, options?: MarkedOptions): TokensList; + /** * Compiles markdown to HTML. * @@ -11,7 +40,7 @@ interface MarkedStatic { * @param callback Function called when the markdownString has been fully parsed when using async highlighting * @return String of compiled HTML */ - (src: string, callback: Function): string; + function parse(src: string, callback: (error: any | undefined, parseResult: string) => void): string; /** * Compiles markdown to HTML. @@ -21,144 +50,232 @@ interface MarkedStatic { * @param callback Function called when the markdownString has been fully parsed when using async highlighting * @return String of compiled HTML */ - (src: string, options?: MarkedOptions, callback?: Function): string; + function parse(src: string, options?: MarkedOptions, callback?: (error: any | undefined, parseResult: string) => void): string; /** - * @param src String of markdown source to be compiled + * @param src Tokenized source as array of tokens * @param options Hash of options */ - lexer(src: string, options?: MarkedOptions): any[]; - - /** - * Compiles markdown to HTML. - * - * @param src String of markdown source to be compiled - * @param callback Function called when the markdownString has been fully parsed when using async highlighting - * @return String of compiled HTML - */ - parse(src: string, callback: Function): string; - - /** - * Compiles markdown to HTML. - * - * @param src String of markdown source to be compiled - * @param options Hash of options - * @param callback Function called when the markdownString has been fully parsed when using async highlighting - * @return String of compiled HTML - */ - parse(src: string, options?: MarkedOptions, callback?: Function): string; - - /** - * @param options Hash of options - */ - parser(src: any[], options?: MarkedOptions): string; + function parser(src: TokensList, options?: MarkedOptions): string; /** * Sets the default options. * * @param options Hash of options */ - setOptions(options: MarkedOptions): MarkedStatic; - - Renderer: { - new(): MarkedRenderer; + function setOptions(options: MarkedOptions): typeof marked; + + class Renderer { + constructor(options?: MarkedOptions); + code(code: string, language: string, isEscaped: boolean): string; + blockquote(quote: string): string; + html(html: string): string; + heading(text: string, level: number, raw: string): string; + hr(): string; + list(body: string, ordered: boolean): string; + listitem(text: string): string; + paragraph(text: string): string; + table(header: string, body: string): string; + tablerow(content: string): string; + tablecell(content: string, flags: { + header: boolean; + align: 'center' | 'left' | 'right' | null; + }): string; + strong(text: string): string; + em(text: string): string; + codespan(code: string): string; + br(): string; + del(text: string): string; + link(href: string, title: string, text: string): string; + image(href: string, title: string, text: string): string; + text(text: string): string; } - - Parser: { - new(options: MarkedOptions): MarkedParser; + + class Lexer { + rules: Rules; + tokens: TokensList; + constructor(options?: MarkedOptions); + lex(src: string): TokensList; + } + + interface Rules { + [ruleName: string]: RegExp | Rules; + } + + type TokensList = Token[] & { + links: { + [key: string]: { href: string; title: string; } + } + }; + + type Token = + Tokens.Space + | Tokens.Code + | Tokens.Heading + | Tokens.Table + | Tokens.Hr + | Tokens.BlockquoteStart + | Tokens.BlockquoteEnd + | Tokens.ListStart + | Tokens.LooseItemStart + | Tokens.ListItemStart + | Tokens.ListItemEnd + | Tokens.ListEnd + | Tokens.Paragraph + | Tokens.HTML + | Tokens.Text; + + namespace Tokens { + interface Space { + type: 'space'; + } + + interface Code { + type: 'code'; + lang?: string; + text: string; + } + + interface Heading { + type: 'heading'; + depth: number; + text: string; + } + + interface Table { + type: 'table'; + header: string[]; + align: Array<'center' | 'left' | 'right' | null>; + cells: string[][]; + } + + interface Hr { + type: 'hr'; + } + + interface BlockquoteStart { + type: 'blockquote_start'; + } + + interface BlockquoteEnd { + type: 'blockquote_end'; + } + + interface ListStart { + type: 'list_start'; + ordered: boolean; + } + + interface LooseItemStart { + type: 'loose_item_start'; + } + + interface ListItemStart { + type: 'list_item_start'; + } + + interface ListItemEnd { + type: 'list_item_end'; + } + + interface ListEnd { + type: 'list_end'; + } + + interface Paragraph { + type: 'paragraph'; + pre?: boolean; + text: string; + } + + interface HTML { + type: 'html'; + pre: boolean; + text: string; + } + + interface Text { + type: 'text'; + text: string; + } + } + + interface MarkedOptions { + /** + * Type: object Default: new Renderer() + * + * An object containing functions to render tokens to HTML. + */ + renderer?: Renderer; + + /** + * Enable GitHub flavored markdown. + */ + gfm?: boolean; + + /** + * Enable GFM tables. This option requires the gfm option to be true. + */ + tables?: boolean; + + /** + * Enable GFM line breaks. This option requires the gfm option to be true. + */ + breaks?: boolean; + + /** + * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. + */ + pedantic?: boolean; + + /** + * Sanitize the output. Ignore any HTML that has been input. + */ + sanitize?: boolean; + + /** + * Optionally sanitize found HTML with a sanitizer function. + */ + sanitizer?(html: string): string; + + /** + * Mangle autolinks (). + */ + mangle?: boolean; + + /** + * Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic. + */ + smartLists?: boolean; + + /** + * Shows an HTML error message when rendering fails. + */ + silent?: boolean; + + /** + * A function to highlight code blocks. The function takes three arguments: code, lang, and callback. + */ + highlight?(code: string, lang: string, callback?: (error: any | undefined, code: string) => void): string; + + /** + * Set the prefix for code block classes. + */ + langPrefix?: string; + + /** + * Use "smart" typograhic punctuation for things like quotes and dashes. + */ + smartypants?: boolean; + + /** + * Set the prefix for header tag ids. + */ + headerPrefix?: string; + + /** + * Generate closing slash for self-closing tags (
instead of
) + */ + xhtml?: boolean; } } - -interface MarkedRenderer { - code(code: string, language: string): string; - blockquote(quote: string): string; - html(html: string): string; - heading(text: string, level: number, raw: string): string; - hr(): string; - list(body: string, ordered: boolean): string; - listitem(text: string): string; - paragraph(text: string): string; - table(header: string, body: string): string; - tablerow(content: string): string; - tablecell(content: string, flags: { - header: boolean, - align: string - }): string; - strong(text: string): string; - em(text: string): string; - codespan(code: string): string; - br(): string; - del(text: string): string; - link(href: string, title: string, text: string): string; - image(href: string, title: string, text: string): string; - text(text: string): string; -} - -interface MarkedParser { - parse(source: any[]): string -} - -interface MarkedOptions { - /** - * Type: object Default: new Renderer() - * - * An object containing functions to render tokens to HTML. - */ - renderer?: MarkedRenderer; - - /** - * Enable GitHub flavored markdown. - */ - gfm?: boolean; - - /** - * Enable GFM tables. This option requires the gfm option to be true. - */ - tables?: boolean; - - /** - * Enable GFM line breaks. This option requires the gfm option to be true. - */ - breaks?: boolean; - - /** - * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. - */ - pedantic?: boolean; - - /** - * Sanitize the output. Ignore any HTML that has been input. - */ - sanitize?: boolean; - - /** - * Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic. - */ - smartLists?: boolean; - - /** - * Shows an HTML error message when rendering fails. - */ - silent?: boolean; - - /** - * A function to highlight code blocks. The function takes three arguments: code, lang, and callback. - */ - highlight? (code: string, lang: string, callback?: Function): string; - - /** - * Set the prefix for code block classes. - */ - langPrefix?: string; - - /** - * Use "smart" typograhic punctuation for things like quotes and dashes. - */ - smartypants?: boolean; -} - -declare module "marked" { - export = marked; -} - -declare var marked: MarkedStatic; diff --git a/types/marked/marked-tests.ts b/types/marked/marked-tests.ts index 6263b2fff2..9499de3a56 100644 --- a/types/marked/marked-tests.ts +++ b/types/marked/marked-tests.ts @@ -1,8 +1,6 @@ - - import * as marked from 'marked'; -var options: MarkedOptions = { +const options: marked.MarkedOptions = { gfm: true, tables: true, breaks: false, @@ -10,8 +8,8 @@ var options: MarkedOptions = { sanitize: true, smartLists: true, silent: false, - highlight: function (code: string, lang: string) { - return ''; + highlight(code: string, lang: string) { + return ''; }, langPrefix: 'lang-', smartypants: false, @@ -19,10 +17,10 @@ var options: MarkedOptions = { }; function callback() { - console.log('callback called'); + console.log('callback called'); } -marked.setOptions(options); +const myOldMarked: typeof marked = marked.setOptions(options); console.log(marked('i am using __markdown__.')); console.log(marked('i am using __markdown__.', options)); @@ -34,11 +32,16 @@ console.log(marked.parse('i am using __markdown__.', options)); console.log(marked.parse('i am using __markdown__.', callback)); console.log(marked.parse('i am using __markdown__.', options, callback)); -var text = 'something'; -var tokens = marked.lexer(text, options); +const text = 'something'; +const tokens: marked.TokensList = marked.lexer(text, options); console.log(marked.parser(tokens)); -var renderer = new marked.Renderer(); -renderer.heading = function(text, level, raw) { +const lexer = new marked.Lexer(options); +const tokens2 = lexer.lex(text); +console.log(tokens2); +const re: RegExp | marked.Rules = lexer.rules['code']; + +const renderer = new marked.Renderer(); +renderer.heading = (text, level, raw) => { return text + level.toString() + raw; }; diff --git a/types/marked/tslint.json b/types/marked/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/marked/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 8373997f5c..9cacfe1136 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1234,6 +1234,7 @@ declare namespace __MaterialUI { autoWidth?: boolean; className?: string; disabled?: boolean; + iconButton?: React.ReactNode; iconStyle?: React.CSSProperties; labelStyle?: React.CSSProperties; listStyle?: React.CSSProperties; @@ -1242,6 +1243,8 @@ declare namespace __MaterialUI { onChange?(e: TouchTapEvent, index: number, menuItemValue: any): void; onClose?(e: TouchTapEvent): void; openImmediately?: boolean; + selectedMenuItemStyle?: React.CSSProperties; + selectionRenderer?(value: any, menuItem: any): void; style?: React.CSSProperties; underlineStyle?: React.CSSProperties; value?: any; @@ -1849,6 +1852,8 @@ declare namespace __MaterialUI { autoFocus?: boolean; min?: number; max?: number; + maxlength?: string; + minlegnth?: string; step?: number; autoComplete?: string; } diff --git a/types/merge2/index.d.ts b/types/merge2/index.d.ts index 3e9c30b6c9..0f503e48d1 100644 --- a/types/merge2/index.d.ts +++ b/types/merge2/index.d.ts @@ -1,23 +1,53 @@ -// Type definitions for merge2 v0.3.6 +// Type definitions for merge2 1.1 // Project: https://github.com/teambition/merge2 // Definitions by: Tanguy Krotoff +// Chigozirim C. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +import { DuplexOptions } from 'stream'; -interface IOptions { - end?: boolean; - objectMode?: boolean; +type StreamType = NodeJS.ReadableStream | Merge2Stream; + +interface Merge2Stream extends NodeJS.ReadWriteStream { + /** + * @summary Add more streams to an existing merged stream + * + * @param {...(StreamType|StreamType[])} args streams to add + * + * @return The merged stream + */ + add(...args: Array): Merge2Stream; + + /** + * @summary It will emit 'queueDrain' when all streams merged. + * If you set end === false in options, this event give you a notice that + * you should add more streams to merge, or end the mergedStream. + * + * @param {string} event The 'queueDrain' event + * + * @return This stream + */ + on(event: 'queueDrain', callback: () => void): this; } -interface IMerge2Stream extends NodeJS.ReadWriteStream { - add(...args: Array>): IMerge2Stream; -} +/** + * @summary This function takes an arbitrary number of streams and returns a + * Merge2Stream. + * + * @description If a DuplexOption is specified, it has to be specified last in the + * argument list + * + * @see { @link https://github.com/teambition/merge2#api } + * + * @param {...(StreamType|StreamType[])} args StreamTypes + * @param {DuplexOptions} opts Optional DuplexOption to be specified last + * + * @return A merged duplex stream + */ +declare function IMerge2(...args: Array): Merge2Stream; -interface IMerge2 { - (...args: Array | IOptions>): IMerge2Stream; -} +declare namespace IMerge2 {} -declare var _tmp: IMerge2; -export = _tmp; +export = IMerge2; diff --git a/types/merge2/merge2-tests.ts b/types/merge2/merge2-tests.ts index 8f95b82bda..823ef8f389 100644 --- a/types/merge2/merge2-tests.ts +++ b/types/merge2/merge2-tests.ts @@ -1,8 +1,5 @@ - - - -import gulp = require('gulp'); -import * as merge2 from "merge2"; +import * as gulp from 'gulp'; +import * as merge2 from 'merge2'; gulp.task('app-js', () => merge2( @@ -21,44 +18,39 @@ gulp.task('app-js', () => .pipe(gulp.dest('static/dist/js/')) ); +const stream1 = gulp.src('*.html'); +const stream2 = gulp.src('*.html'); +const stream3 = gulp.src('*.html'); +const stream4 = gulp.src('*.html'); +const stream5 = gulp.src('*.html'); +const stream6 = gulp.src('*.html'); +const stream7 = gulp.src('*.html'); -var stream1 = gulp.src('*.html'); -var stream2 = gulp.src('*.html'); -var stream3 = gulp.src('*.html'); -var stream4 = gulp.src('*.html'); -var stream5 = gulp.src('*.html'); -var stream6 = gulp.src('*.html'); -var stream7 = gulp.src('*.html'); - - -var stream = merge2([stream1, stream2], stream3, {end: false}) -//... +let stream = merge2([stream1, stream2], stream3, {end: false}); +// ... stream.add(stream4, stream5); -//.. +// .. stream.end(); - // equal to merge2([stream1, stream2], stream3) -var stream = merge2(); +stream = merge2(); stream.add([stream1, stream2]); stream.add(stream3); - // merge order: // 1. merge `stream1`; // 2. merge `stream2` and `stream3` in parallel after `stream1` merged; // 3. merge 'stream4' after `stream2` and `stream3` merged; -var stream = merge2(stream1, [stream2, stream3], stream4); +stream = merge2(stream1, [stream2, stream3], stream4); // merge order: // 1. merge `stream5` and `stream6` in parallel after `stream4` merged; // 2. merge 'stream7' after `stream5` and `stream6` merged; stream.add([stream5, stream6], stream7); - // nest merge // equal to merge2(stream1, stream2, stream6, stream3, [stream4, stream5]); -var streamA = merge2(stream1, stream2); -var streamB = merge2(stream3, [stream4, stream5]); -var stream = merge2(streamA, streamB); +const streamA = merge2(stream1, stream2); +const streamB = merge2(stream3, [stream4, stream5]); +stream = merge2(streamA, streamB); streamA.add(stream6); diff --git a/types/merge2/tslint.json b/types/merge2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/merge2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/nightmare/index.d.ts b/types/nightmare/index.d.ts index 0dd7b31b97..150cb3e912 100644 --- a/types/nightmare/index.d.ts +++ b/types/nightmare/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Nightmare 1.6.5 // Project: https://github.com/segmentio/nightmare // Definitions by: horiuchi +// Sam Yang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -78,6 +79,7 @@ declare namespace Nightmare { proxyAuth?: string; cookiesFile?: string; phantomPath?: string; + show?: boolean; } export interface IRequest { diff --git a/types/nightmare/nightmare-tests.ts b/types/nightmare/nightmare-tests.ts index a9251192b3..310cb46067 100644 --- a/types/nightmare/nightmare-tests.ts +++ b/types/nightmare/nightmare-tests.ts @@ -318,3 +318,4 @@ new Nightmare() .use(testTitle('test term')) .run(done); +new Nightmare({show: true}); \ No newline at end of file diff --git a/types/nodemailer/index.d.ts b/types/nodemailer/index.d.ts index 1b745ed08c..cbaa9b8228 100644 --- a/types/nodemailer/index.d.ts +++ b/types/nodemailer/index.d.ts @@ -63,10 +63,14 @@ export declare function createTransport(options?: directTransport.DirectOptions, * Create an SMTP transporter */ export declare function createTransport(options?: smtpTransport.SmtpOptions, defaults?: Object): Transporter; +/** + * Create an SMTP transporter using a connection url + */ +export declare function createTransport(connectionUrl: string, defaults?: Object): Transporter; /** * Create an AWS SES transporter */ -export declare function createTransport(options?: sesTransport.SesOptions, defaults?: Object): Transporter +export declare function createTransport(options?: sesTransport.SesOptions, defaults?: Object): Transporter; /** * Create a transporter from a given implementation */ diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index 2552b9696d..cd26579189 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -10,6 +10,18 @@ var transporter: nodemailer.Transporter = nodemailer.createTransport({ } }); +// create reusable transporter object using SMTP connection url using default options +transporter = nodemailer.createTransport("smtps://gmail.user@gmail.com:userpass@gmail/?pool=true"); + +// create reusable transporter object using SMTP connection url and specify some options +transporter = nodemailer.createTransport("smtps://gmail.user@gmail.com:userpass@gmail/?pool=true", + { + from: 'sender@address', + headers: { + 'My-Awesome-Header': '123' + } + }); + // create reusable transporter object using SES transport and set default values for mail options. transporter = nodemailer.createTransport({ SES: new AWS.SES() diff --git a/types/numjs/index.d.ts b/types/numjs/index.d.ts index af464b7410..e9712c912d 100644 --- a/types/numjs/index.d.ts +++ b/types/numjs/index.d.ts @@ -123,9 +123,9 @@ export interface NdArray extends BaseNdArray { * Converts {NdArray} to a native JavaScript {Array} * */ - tolist(): T[]; + tolist(): LT[]; - valueOf(): T[]; + valueOf(): LT[]; /** * Stringify the array to make it readable in the console, by a human. @@ -523,17 +523,17 @@ export namespace images { */ const moon: NdArray; } - function read(input: string): NdArray; - function save(img: NdArray, dest: string): void; - function resize(img: NdArray, height: number, width: number): NdArray; - function sat(img: NdArray): NdArray; - function ssat(img: NdArray): NdArray; - function sobel(img: NdArray): NdArray; - function scharr(img: NdArray): NdArray; - function areaSum(h0: number, w0: number, H: number, W: number, SAT: NdArray): number; - function areaValue(img: NdArray): number; - function rgb2gray(img: NdArray): NdArray; - function flip(img: NdArray): NdArray; + function read(input: string): NdArray; + function save(img: NdArray, dest: string): void; + function resize(img: NdArray, height: number, width: number): NdArray; + function sat(img: NdArray): NdArray; + function ssat(img: NdArray): NdArray; + function sobel(img: NdArray): NdArray; + function scharr(img: NdArray): NdArray; + function areaSum(h0: number, w0: number, H: number, W: number, SAT: NdArray): number; + function areaValue(img: NdArray): number; + function rgb2gray(img: NdArray): NdArray; + function flip(img: NdArray): NdArray; } export function array(arr: NjArray, dtype?: BaseNdArray.DataType): NdArray; diff --git a/types/numjs/numjs-tests.ts b/types/numjs/numjs-tests.ts index b13cf60fb0..2b82c1b16f 100644 --- a/types/numjs/numjs-tests.ts +++ b/types/numjs/numjs-tests.ts @@ -21,3 +21,5 @@ arr.transpose(1, 0, 2); const b = nj.array([2, 3, 4]); const c = nj.uint8([1, 2, 3]); + +const d = nj.array([[2], [3, 4]]); diff --git a/types/p-all/index.d.ts b/types/p-all/index.d.ts new file mode 100644 index 0000000000..8abf47f672 --- /dev/null +++ b/types/p-all/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for p-all 1.0 +// Project: https://github.com/sindresorhus/p-all#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = pAll; + +declare function pAll( + tasks: [PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, + PromiseFactory, PromiseFactory, PromiseFactory], + options?: pAll.Options): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; +declare function pAll( + tasks: [PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, + PromiseFactory, PromiseFactory], + options?: pAll.Options): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; +declare function pAll( + tasks: [PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, + PromiseFactory], + options?: pAll.Options): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; +declare function pAll( + tasks: [PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory], + options?: pAll.Options): Promise<[T1, T2, T3, T4, T5, T6, T7]>; +declare function pAll( + tasks: [PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory], + options?: pAll.Options): Promise<[T1, T2, T3, T4, T5, T6]>; +declare function pAll( + tasks: [PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory], + options?: pAll.Options): Promise<[T1, T2, T3, T4, T5]>; +declare function pAll( + tasks: [PromiseFactory, PromiseFactory, PromiseFactory, PromiseFactory], + options?: pAll.Options): Promise<[T1, T2, T3, T4]>; +declare function pAll(tasks: [PromiseFactory, PromiseFactory, PromiseFactory], options?: pAll.Options): Promise<[T1, T2, T3]>; +declare function pAll(tasks: [PromiseFactory, PromiseFactory], options?: pAll.Options): Promise<[T1, T2]>; +declare function pAll(tasks: [PromiseFactory], options?: pAll.Options): Promise<[T1]>; +declare function pAll(tasks: Iterable> | Array>, options?: pAll.Options): Promise; + +type PromiseFactory = () => Promise | PromiseLike; + +declare namespace pAll { + interface Options { + concurrency?: number; + } +} diff --git a/types/p-all/p-all-tests.ts b/types/p-all/p-all-tests.ts new file mode 100644 index 0000000000..f6be092250 --- /dev/null +++ b/types/p-all/p-all-tests.ts @@ -0,0 +1,14 @@ +import pAll = require('p-all'); + +const actions: [() => Promise, () => Promise, () => Promise, () => Promise] = [ + () => Promise.resolve('sindresorhus.com'), + () => Promise.resolve('ava.li'), + () => Promise.resolve(), + () => Promise.resolve(1) +]; + +pAll(actions, {concurrency: 2}).then(result => { + let str: string = result[0]; + let str2: string = result[1]; + let num: number = result[3]; +}); diff --git a/types/p-all/tsconfig.json b/types/p-all/tsconfig.json new file mode 100644 index 0000000000..711f36cb72 --- /dev/null +++ b/types/p-all/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "p-all-tests.ts" + ] +} diff --git a/types/p-all/tslint.json b/types/p-all/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-all/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-any/index.d.ts b/types/p-any/index.d.ts new file mode 100644 index 0000000000..0354ec661a --- /dev/null +++ b/types/p-any/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for p-any 1.1 +// Project: https://github.com/sindresorhus/p-any#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import AggregateErrorModule = require('aggregate-error'); + +export = pAny; + +declare function pAny( + values: [Value, Value, Value, Value, Value, Value, Value, Value, Value, Value], + options?: pAny.Options): Promise; +declare function pAny( + values: [Value, Value, Value, Value, Value, Value, Value, Value, Value], + options?: pAny.Options): Promise; +declare function pAny( + values: [Value, Value, Value, Value, Value, Value, Value, Value], + options?: pAny.Options): Promise; +declare function pAny( + values: [Value, Value, Value, Value, Value, Value, Value], + options?: pAny.Options): Promise; +declare function pAny(values: [Value, Value, Value, Value, Value, Value], + options?: pAny.Options): Promise; +declare function pAny(values: [Value, Value, Value, Value, Value], + options?: pAny.Options): Promise; +declare function pAny(values: [Value, Value, Value, Value], + options?: pAny.Options): Promise; +declare function pAny(values: [Value, Value, Value], options?: pAny.Options): Promise; +declare function pAny(values: [Value, Value], options?: pAny.Options): Promise; +declare function pAny(values: Iterable> | Array>, options?: pAny.Options): Promise; + +type Value = T | PromiseLike; + +declare namespace pAny { + interface Options { + filter?(value: T): boolean; + } + + const AggregateError: typeof AggregateErrorModule; +} diff --git a/types/p-any/p-any-tests.ts b/types/p-any/p-any-tests.ts new file mode 100644 index 0000000000..e2eeda8423 --- /dev/null +++ b/types/p-any/p-any-tests.ts @@ -0,0 +1,24 @@ +import got = require('got'); +import pAny = require('p-any'); + +pAny([ + got.head('github.com').then(() => 'github'), + got.head('google.com').then(() => 'google'), + got.head('twitter.com').then(() => 'twitter'), +]).then(first => { + let str: string = first; +}); + +pAny(new Set([ + got.head('github.com').then(() => 'github'), + got.head('google.com').then(() => 'google'), + got.head('twitter.com').then(() => 'twitter'), +]), { + filter(str: string) { + return true; + } +}).then(first => { + let str: string = first; +}); + +throw new pAny.AggregateError([]); diff --git a/types/p-any/tsconfig.json b/types/p-any/tsconfig.json new file mode 100644 index 0000000000..564eabff80 --- /dev/null +++ b/types/p-any/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "p-any-tests.ts" + ] +} diff --git a/types/p-any/tslint.json b/types/p-any/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-any/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-event/index.d.ts b/types/p-event/index.d.ts new file mode 100644 index 0000000000..0fde40d140 --- /dev/null +++ b/types/p-event/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for p-event 1.3 +// Project: https://github.com/sindresorhus/p-event#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = pEvent; + +declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, options: MultiArgsOptions): Promise>; +declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, filter: FilterFn): Promise; +declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, options?: pEvent.Options): Promise; + +declare namespace pEvent { + interface Emitter { + on?: AddRmListenerFn; + addListener?: AddRmListenerFn; + addEventListener?: AddRmListenerFn; + off?: AddRmListenerFn; + removeListener?: AddRmListenerFn; + removeEventListener?: AddRmListenerFn; + } + + interface Options { + rejectionEvents?: string[]; + multiArgs?: boolean; + timeout?: number; + filter?: FilterFn; + } +} + +type AddRmListenerFn = (event: string | symbol, listener: (arg1: T, ...args: TRest[]) => void) => void; +type FilterFn = (el: T) => boolean; + +interface MultiArgsOptions extends pEvent.Options { + multiArgs: true; +} diff --git a/types/p-event/p-event-tests.ts b/types/p-event/p-event-tests.ts new file mode 100644 index 0000000000..d963e22bed --- /dev/null +++ b/types/p-event/p-event-tests.ts @@ -0,0 +1,61 @@ +/// + +import pEvent = require('p-event'); +import * as events from 'events'; +import * as fs from 'fs'; + +class MyEmitter extends events.EventEmitter { +} + +class MyDomEmitter implements EventTarget { + addEventListener(type: 'foo', listener?: (event: Event) => void): void { + } + + dispatchEvent(event: Event): boolean { + return false; + } + + removeEventListener(type: 'foo', listener?: (event: Event) => void): void { + } +} + +pEvent(new MyEmitter(), 'finish') + .then(result => { + console.log(result); + }) + .catch(error => { + console.error(error); + }); + +pEvent(new MyEmitter(), 'finish').then(result => { + const str: string = result; +}); + +pEvent(new MyDomEmitter(), 'finish').then(result => { + const e: Event | undefined = result; +}); + +pEvent(document, 'DOMContentLoaded').then(() => { + console.log('😎'); +}); + +pEvent(new MyEmitter(), 'finish', {multiArgs: true}).then(result => { + const strArr: string[] = result; +}); + +pEvent(new MyEmitter(), '🦄', value => value > 3).then(result => { + const num: number = result; +}); + +async function getOpenReadStream(file: string) { + const stream = fs.createReadStream(file); + await pEvent(stream, 'open'); + return stream; +} + +getOpenReadStream('unicorn.txt') + .then(stream => { + console.log('Is readable:', stream.readable); + stream.pipe(process.stdout); + }) + .catch(console.error); diff --git a/types/angular-ui-router-default/tsconfig.json b/types/p-event/tsconfig.json similarity index 90% rename from types/angular-ui-router-default/tsconfig.json rename to types/p-event/tsconfig.json index 7cda72ddf5..3d45d58840 100644 --- a/types/angular-ui-router-default/tsconfig.json +++ b/types/p-event/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "angular-ui-router-default-tests.ts" + "p-event-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/p-event/tslint.json b/types/p-event/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-event/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-lazy/index.d.ts b/types/p-lazy/index.d.ts new file mode 100644 index 0000000000..e64cfa6fc6 --- /dev/null +++ b/types/p-lazy/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for p-lazy 1.0 +// Project: https://github.com/sindresorhus/p-lazy#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = PLazy; + +declare class PLazy extends Promise { + static from(fn: () => T | PromiseLike): PLazy; +} diff --git a/types/p-lazy/p-lazy-tests.ts b/types/p-lazy/p-lazy-tests.ts new file mode 100644 index 0000000000..d240ae826e --- /dev/null +++ b/types/p-lazy/p-lazy-tests.ts @@ -0,0 +1,23 @@ +import PLazy = require('p-lazy'); + +const lazyPromise = new PLazy((resolve, reject) => { + if (typeof resolve === 'object') { + resolve('foo'); + } else { + reject(new Error()); + } +}); + +let str: string; + +lazyPromise.then(result => str = result); + +Promise.resolve() + .then(() => lazyPromise) + .then(value => str = value); + +let num: number; +PLazy.from(() => Promise.resolve(1)) + .then(value => num = value); +PLazy.from(() => 1) + .then(value => num = value); diff --git a/types/p-lazy/tsconfig.json b/types/p-lazy/tsconfig.json new file mode 100644 index 0000000000..3d90d7b320 --- /dev/null +++ b/types/p-lazy/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "p-lazy-tests.ts" + ] +} diff --git a/types/p-lazy/tslint.json b/types/p-lazy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-lazy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-try/index.d.ts b/types/p-try/index.d.ts new file mode 100644 index 0000000000..82eca22d8c --- /dev/null +++ b/types/p-try/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for p-try 1.0 +// Project: https://github.com/sindresorhus/p-try#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = pTry; + +declare function pTry(cb: () => Promise | PromiseLike | T): Promise; diff --git a/types/p-try/p-try-tests.ts b/types/p-try/p-try-tests.ts new file mode 100644 index 0000000000..054d92e22f --- /dev/null +++ b/types/p-try/p-try-tests.ts @@ -0,0 +1,16 @@ +import pTry = require('p-try'); + +function throws(): never { + throw new Error('foo'); +} + +let str: string; +pTry(() => 'foo').then(value => { + str = value; +}); +pTry(() => Promise.resolve('foo')).then(value => { + str = value; +}); +pTry(throws).then(value => { + str = value; +}); diff --git a/types/p-try/tsconfig.json b/types/p-try/tsconfig.json new file mode 100644 index 0000000000..ea1784a0e7 --- /dev/null +++ b/types/p-try/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "p-try-tests.ts" + ] +} diff --git a/types/p-try/tslint.json b/types/p-try/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-try/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 45f1ac590f..bce11df130 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -793,27 +793,27 @@ declare module 'paper' { * Expands the rectangle by the specified amount in horizontal and vertical directions. * @param amount - the amount to expand the rectangle in both directions */ - expand(amount: number | Size | Point): void; + expand(amount: number | Size | Point): Rectangle; /** * Expands the rectangle by the specified amounts in horizontal and vertical directions. * @param hor - the amount to expand the rectangle in horizontal direction * @param ver - the amount to expand the rectangle in vertical direction */ - expand(hor: number, ver: number): void; + expand(hor: number, ver: number): Rectangle; /** * Scales the rectangle by the specified amount from its center. * @param amount - the amount to scale by */ - scale(amount: number): void; + scale(amount: number): Rectangle; /** * Scales the rectangle in horizontal direction by the specified hor amount and in vertical direction by the specified ver amount from its center. * @param hor - the amount to scale the rectangle in horizontal direction * @param ver - the amount to scale the rectangle in vertical direction */ - scale(hor: number, ver: number): void; + scale(hor: number, ver: number): Rectangle; } /** diff --git a/types/pg-connection-string/index.d.ts b/types/pg-connection-string/index.d.ts index bc2f8bafa5..fa79138728 100644 --- a/types/pg-connection-string/index.d.ts +++ b/types/pg-connection-string/index.d.ts @@ -6,8 +6,8 @@ export function parse(connectionString: string): { host: string; - database: string; - port: string; + database: string | null; + port: string | null; application_name?: string; client_encoding?: string; fallback_application_name?: string; diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index a9c4b949e2..d8f37c6414 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -1,105 +1,378 @@ -// Type definitions for pino v3.0.1 +// Type definitions for pino 4.7 // Project: https://github.com/mcollina/pino.git // Definitions by: Peter Snider +// BendingBender // Definitions: https://github.com/borisyankov/DefinitelyTyped +// TypeScript Version: 2.3 /// -import stream = require('stream'); +import * as stream from 'stream'; +import * as http from 'http'; +import { EventEmitter } from 'events'; +export = P; + +/** + * @param [optionsOrStream]: an options object or a writable stream where the logs will be written. It can also receive some log-line metadata, if the + * relative protocol is enabled. Default: process.stdout + * @returns a new logger instance. + */ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform): P.Logger; + +/** + * @param [options]: an options object + * @param [stream]: a writable stream where the logs will be written. It can also receive some log-line metadata, if the + * relative protocol is enabled. Default: process.stdout + * @returns a new logger instance. + */ declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform): P.Logger; declare namespace P { + /** + * Holds the current log format version (as output in the v property of each log record). + */ + const LOG_VERSION: number; + const levels: LevelMapping; + /** + * Provides functions for serializing objects common to many projects. + */ + const stdSerializers: { + /** + * Generates a JSONifiable object from the HTTP `request` object passed to the `createServer` callback of Node's HTTP server. + */ + req(req: http.IncomingMessage): { + method: string; + url: string; + headers: http.IncomingHttpHeaders; + remoteAddress: string; + remotePort: number; + }; + /** + * Generates a JSONifiable object from the HTTP `response` object passed to the `createServer` callback of Node's HTTP server. + */ + res(res: http.ServerResponse): { statusCode: number; header: string; }; + /** + * Serializes an Error object. + */ + err(err: Error): { + type: string; + message: string; + stack: string; + [key: string]: any; + }; + }; + /** + * Provides functions for generating the timestamp property in the log output. You can set the `timestamp` option during + * initialization to one of these functions to adjust the output format. Alternatively, you can specify your own time function. + * A time function must synchronously return a string that would be a valid component of a JSON string. For example, + * the default function returns a string like `,"time":1493426328206`. + */ + const stdTimeFunctions: { + /** + * The default time function for Pino. Returns a string like `,"time":1493426328206`. + */ + epochTime: TimeFn; + /** + * Returns an ISO formatted string like `,"time":"2017-04-29T004749.354Z"`. It is highly recommended that you avoid this function. + * It incurs a significant performance penalty. + */ + slowTime: TimeFn; + /** + * Returns an empty string. This function is used when the `timestamp` option is set to `false`. + */ + nullTime: TimeFn; + }; - function pretty(opts?: { timeTransOnly?: boolean, levelFirst?: boolean, formatter?: (log: IPinoLog) => string }): stream.Transform; + /** + * Provides access to the CLI log prettifier as an API. + * This can also be enabled via the constructor by setting the `prettyPrint` option to either `true` or a configuration object described in this section. + * @param [options]: an options object + * @returns A transform stream to be used as input for the constructor. + */ + function pretty(options?: PrettyOptions): stream.Transform; - type Level = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'; - interface Headers { - [header: string]: string; - } - - interface IPinoLog { - pid: number - hostname: string - level: number - time: string - msg: string - v: number - } - - interface LevelLabelsToValues { - [level: string]: number; - } - - interface LevelValuesToLabels { - [level: number]: string; - } - - interface Serializers { - req?: (req: any) => any; - res?: (res: any) => any; - err?: (error: Error) => any; + interface LevelMapping { + /** + * Returns the mappings of level names to their respective internal number representation. + */ + values: { [level: string]: number; }; + /** + * Returns the mappings of level internal level numbers to their string representations. + */ + labels: { [level: number]: string; }; } + type TimeFn = () => string; interface LoggerOptions { - // avoid error causes by circular references in the object tree, default true + /** + * Avoid error causes by circular references in the object tree. Default: `true`. + */ safe?: boolean; - // the name of the logger, default undefined + /** + * The name of the logger. Default: `undefined`. + */ name?: string; - // an object containing functions for custom serialization of objects. - // These functions should return an JSONifiable object and they should never throw - serializers?: Serializers; - // Outputs ISO time stamps ('2016-03-09T15:18:53.889Z') instead of Epoch time stamps (1457536759176). - // WARNING: This option carries a 25% performance drop, we recommend using default Epoch timestamps and transforming logs after if required. - // The pino -t command will do this for you (see CLI). default false. + /** + * an object containing functions for custom serialization of objects. + * These functions should return an JSONifiable object and they should never throw. When logging an object, + * each top-level property matching the exact key of a serializer will be serialized using the defined serializer. + */ + serializers?: { [key: string]: SerializerFn }; + /** + * Enables or disables the inclusion of a timestamp in the log message. If a function is supplied, it must + * synchronously return a JSON string representation of the time. If set to `false`, no timestamp will be included in the output. + * See stdTimeFunctions for a set of available functions for passing in as a value for this option. + * Caution: any sort of formatted time will significantly slow down Pino's performance. + */ + timestamp?: TimeFn | false; + /** + * @deprecated + * This option is scheduled to be removed in Pino 5.0.0. Use `timestamp: pino.stdTimeFunctions.slowTime` instead. + * Outputs ISO time stamps ('2016-03-09T15:18:53.889Z') instead of Epoch time stamps (1457536759176). + * WARNING: This option carries a 25% performance drop, we recommend using default Epoch timestamps and transforming logs after if required. + * The pino -t command will do this for you (see CLI). Default: `false`. + */ slowtime?: boolean; - // Enables extreme mode, yields an additional 60% performance (from 250ms down to 100ms per 10000 ops). - // There are trade-off's should be understood before usage. See Extreme mode explained. default false + /** + * Enables extreme mode, yields an additional 60% performance (from 250ms down to 100ms per 10000 ops). + * There are trade-off's should be understood before usage. See Extreme mode explained. Default: `false`. + */ extreme?: boolean; - // enables logging, defaults to true. - enabled?: boolean; - level?: Level | string; + /** + * One of the supported levels or `silent` to disable logging. Any other value defines a custom level and + * requires supplying a level value via `levelVal`. Default: 'info'. + */ + level?: LevelWithSilent | string; + /** + * When defining a custom log level via level, set to an integer value to define the new level. Default: `undefined`. + */ levelVal?: number; - } - - interface Pino { - (optionsOrStream?: LoggerOptions | stream.Writable | stream.Duplex): Logger; - (options: LoggerOptions, stream: stream.Writable | stream.Duplex): Logger; - levels: { - values: LevelLabelsToValues - labels: LevelValuesToLabels + /** + * The string key for the 'message' in the JSON object. Default: "msg". + */ + messageKey?: string; + /** + * Enables pino.pretty. This is intended for non-production configurations. This may be set to a configuration + * object as outlined in http://getpino.io/#/docs/API?id=pretty. Default: `false`. + */ + prettyPrint?: boolean | PrettyOptions; + /** + * This function will be invoked during process shutdown when `extreme` is set to `true`. If you do not specify + * a function, Pino will invoke `process.exit(0)` when no error has occurred, and `process.exit(1)` otherwise. + * If you do specify a function, it is up to you to terminate the process; you must perform only synchronous + * operations at this point. See http://getpino.io/#/docs/extreme for more detail. + */ + onTerminated?(eventName: string, err: any): void; + /** + * Enables logging. Default: `true`. + */ + enabled?: boolean; + /** + * Browser only, see http://getpino.io/#/?id=pino-in-the-browser. + */ + browser?: { + /** + * This option will create a pino-like log object instead of passing all arguments to a console method. + * When `write` is set, `asObject` will always be `true`. + */ + asObject?: boolean, + /** + * Instead of passing log messages to console.log they can be passed to a supplied function. If `write` is + * set to a single function, all logging objects are passed to this function. If write is an object, it can + * have methods that correspond to the levels. When a message is logged at a given level, the corresponding + * method is called. If a method isn't present, the logging falls back to using the `console`. + */ + write?: WriteFn | ({ + fatal?: WriteFn; + error?: WriteFn; + warn?: WriteFn; + info?: WriteFn; + debug?: WriteFn; + trace?: WriteFn; + } & { [logLevel: string]: WriteFn }); }; - LOG_VERSION: number; } - type LevelChangeEventListener = (lvl: string, val: number, prevLvl: string, prevVal: number) => void; - type LevelChangeEvent = 'level-change'; + interface PrettyOptions { + /** + * If set to true, it will only covert the unix timestamp to ISO 8601 date format, and reserialize the JSON (equivalent to pino -t). + */ + timeTransOnly?: boolean; + /** + * A custom function to format the line, is passed the JSON object as an argument and should return a string value. + */ + formatter?(log: LogDescriptor): string; + /** + * If set to true, it will print the name of the log level as the first field in the log line. Default: `false`. + */ + levelFirst?: boolean; + /** + * The key in the JSON object to use as the highlighted message. Default: "msg". + */ + messageKey?: string; + /** + * If set to true, will add color information to the formatted output message. Default: `false`. + */ + forceColor?: boolean; + } - interface Logger { - child(bindings: {}): Logger; - level: Level; + type Level = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'; + type LevelWithSilent = Level | 'silent'; + + type SerializerFn = (value: any) => any; + type WriteFn = (o: object) => void; + + interface LogDescriptor { + pid: number; + hostname: string; + level: number; + time: string; + msg: string; + v: number; + [key: string]: any; + } + + type Logger = BaseLogger & { [key: string]: LogFn; }; + + interface BaseLogger extends EventEmitter { + /** + * Exposes the current version of Pino. + */ + readonly pino: string; + /** + * Holds the current log format version (as output in the v property of each log record). + */ + readonly LOG_VERSION: number; + + levels: LevelMapping; + + /** + * Set this property to the desired logging level. In order of priority, available levels are: + * + * - 'fatal' + * - 'error' + * - 'warn' + * - 'info' + * - 'debug' + * - 'trace' + * + * The logging level is a __minimum__ level. For instance if `logger.level` is `'info'` then all `'fatal'`, `'error'`, `'warn'`, + * and `'info'` logs will be enabled. + * + * You can pass `'silent'` to disable logging. + */ + level: LevelWithSilent | string; + /** + * Returns the integer value for the logger instance's logging level. + */ levelVal: number; - on(event: LevelChangeEvent, listener: LevelChangeEventListener): void; - fatal(msg: string, ...args: any[]): void; - fatal(obj: {}, msg?: string, ...args: any[]): void; - error(msg: string, ...args: any[]): void; - error(obj: {}, msg?: string, ...args: any[]): void; - warn(msg: string, ...args: any[]): void; - warn(obj: {}, msg?: string, ...args: any[]): void; - info(msg: string, ...args: any[]): void; - info(obj: {}, msg?: string, ...args: any[]): void; - debug(msg: string, ...args: any[]): void; - debug(obj: {}, msg?: string, ...args: any[]): void; - trace(msg: string, ...args: any[]): void; - trace(obj: {}, msg?: string, ...args: any[]): void; - levels: { - values: LevelLabelsToValues - labels: LevelValuesToLabels - }; - LOG_VERSION: number; - stdSerializers: Serializers; + + /** + * Defines a new level on the logger instance. Returns `true` on success and `false` if there was a conflict (level name or number already exists). + * When using this method, the current level of the logger instance does not change. You must adjust the level with the `level` property after + * adding your custom level. + * + * @param name: defines the method name of the new level + * @param lvl: value for the level, e.g. `35` is between `info` and `warn` + * @returns whether level was correctly created or not + */ + addLevel(name: string, lvl: number): boolean; + /** + * Registers a listener function that is triggered when the level is changed. + * Note: When browserified, this functionality will only be available if the `events` module has been required elsewhere + * (e.g. if you're using streams in the browser). This allows for a trade-off between bundle size and functionality. + * + * @param event: only ever fires the `'level-change'` event + * @param listener: The listener is passed four arguments: `levelLabel`, `levelValue`, `previousLevelLabel`, `previousLevelValue`. + */ + on(event: 'level-change', listener: LevelChangeEventListener): this; + addListener(event: 'level-change', listener: LevelChangeEventListener): this; + once(event: 'level-change', listener: LevelChangeEventListener): this; + prependListener(event: 'level-change', listener: LevelChangeEventListener): this; + prependOnceListener(event: 'level-change', listener: LevelChangeEventListener): this; + removeListener(event: 'level-change', listener: LevelChangeEventListener): this; + + /** + * Creates a child logger, setting all key-value pairs in `bindings` as properties in the log lines. All serializers will be applied to the given pair. + * Child loggers use the same output stream as the parent and inherit the current log level of the parent at the time they are spawned. + * From v2.x.x the log level of a child is mutable (whereas in v1.x.x it was immutable), and can be set independently of the parent. + * If a `level` property is present in the object passed to `child` it will override the child logger level. + * + * @param bindings: an object of key-value pairs to include in log lines as properties. + * @returns a child logger instance. + */ + child(bindings: { + level?: Level | string; + serializers?: { [key: string]: SerializerFn }; + [key: string]: any; + }): Logger; + + /** + * Log at `'fatal'` level the given msg. If the first argument is an object, all its properties will be included in the JSON line. + * If more args follows `msg`, these will be used to format `msg` using `util.format`. + * + * @param obj: object to be serialized + * @param msg: the log message to write + * @param ...args: format string values when `msg` is a format string + */ + fatal: LogFn; + /** + * Log at `'error'` level the given msg. If the first argument is an object, all its properties will be included in the JSON line. + * If more args follows `msg`, these will be used to format `msg` using `util.format`. + * + * @param obj: object to be serialized + * @param msg: the log message to write + * @param ...args: format string values when `msg` is a format string + */ + error: LogFn; + /** + * Log at `'warn'` level the given msg. If the first argument is an object, all its properties will be included in the JSON line. + * If more args follows `msg`, these will be used to format `msg` using `util.format`. + * + * @param obj: object to be serialized + * @param msg: the log message to write + * @param ...args: format string values when `msg` is a format string + */ + warn: LogFn; + /** + * Log at `'info'` level the given msg. If the first argument is an object, all its properties will be included in the JSON line. + * If more args follows `msg`, these will be used to format `msg` using `util.format`. + * + * @param obj: object to be serialized + * @param msg: the log message to write + * @param ...args: format string values when `msg` is a format string + */ + info: LogFn; + /** + * Log at `'debug'` level the given msg. If the first argument is an object, all its properties will be included in the JSON line. + * If more args follows `msg`, these will be used to format `msg` using `util.format`. + * + * @param obj: object to be serialized + * @param msg: the log message to write + * @param ...args: format string values when `msg` is a format string + */ + debug: LogFn; + /** + * Log at `'trace'` level the given msg. If the first argument is an object, all its properties will be included in the JSON line. + * If more args follows `msg`, these will be used to format `msg` using `util.format`. + * + * @param obj: object to be serialized + * @param msg: the log message to write + * @param ...args: format string values when `msg` is a format string + */ + trace: LogFn; + + /** + * Flushes the content of the buffer in extreme mode. It has no effect if extreme mode is not enabled. + */ + flush(): void; + } + + type LevelChangeEventListener = (lvl: LevelWithSilent | string, val: number, prevLvl: LevelWithSilent | string, prevVal: number) => void; + + interface LogFn { + (msg: string, ...args: any[]): void; + (obj: object, msg?: string, ...args: any[]): void; } } - -export = P; diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 2c9771ad9f..fcb3427114 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -1,40 +1,92 @@ -// This contains all of the code from the docs on https://www.npmjs.com/package/pino +import pino = require('pino'); -import PINO = require('pino'); -import * as stream from 'stream'; +const log = pino(); +const info = log.info; +const error = log.error; -var pino = PINO() -var info = pino.info -var error = pino.error +info('hello world'); +error('this is at error level'); +info('the answer is %d', 42); +info({obj: 42}, 'hello world'); +info({obj: 42, b: 2}, 'hello world'); +info({obj: {aa: 'bbb'}}, 'another'); +setImmediate(info, 'after setImmediate'); +error(new Error('an error')); -info('hello world') -error('this is at error level') -info('the answer is %d', 42) -info({ obj: 42 }, 'hello world') -info({ obj: 42, b: 2 }, 'hello world') -info({ obj: { aa: 'bbb' } }, 'another') -setImmediate(info, 'after setImmediate') -error(new Error('an error')) +let log2: pino.Logger = pino({ + name: 'myapp', + safe: true, + serializers: { + req: pino.stdSerializers.req, + res: pino.stdSerializers.res + } +}); -let instance:PINO.Logger = PINO({ - name: 'myapp', - safe: true, - serializers: { - req: pino.stdSerializers.req, - res: pino.stdSerializers.res - } -}) +let pretty = pino.pretty(); +pretty.pipe(process.stdout); +const log3 = pino({ + name: 'app', + safe: true +}, pretty); +log3.child({widget: 'foo'}).info('hello'); +log3.child({widget: 'bar'}).warn('hello 2'); -let version:number = pino.LOG_VERSION -let levels:Object = pino.levels +pino({ + browser: { + write(o) { + } + } +}); -let pretty:stream.Transform = PINO.pretty() +pino({ + browser: { + write: { + info(o) { + }, + error(o) { + } + } + } +}); -let logger2:PINO.Logger = PINO({ - name: 'app', - safe: true -}, pretty) +if ('pino' in log) console.log(`pino version: ${log.pino}`); +log.child({a: 'property'}).info('hello child!'); +log.level = 'error'; +log.info('nope'); +const child = log.child({foo: 'bar'}); +child.info('nope again'); +child.level = 'info'; +child.info('hooray'); +log.info('nope nope nope'); +log.child({foo: 'bar', level: 'debug'}).debug('debug!'); +const customSerializers = { + test() { + return 'this is my serializer'; + } +}; +pino().child({serializers: customSerializers}).info({test: 'should not show up'}); +const child2 = log.child({father: true}); +const childChild = child2.child({baby: true}); -var logger = instance -logger.child({ a: 'property' }).info('hello child!') +log.level = 'info'; +if (log.levelVal === 30) { + console.log('logger level is `info`'); +} + +log.addLevel('myLevel', 35); +log.level = 'myLevel'; +log.myLevel('a message'); + +const listener = (lvl: any, val: any, prevLvl: any, prevVal: any) => { + console.log(lvl, val, prevLvl, prevVal); +}; +log.on('level-change', (lvl, val, prevLvl, prevVal) => { + console.log(lvl, val, prevLvl, prevVal); +}); +log.level = 'trace'; +log.removeListener('level-change', listener); +log.level = 'info'; + +pino.levels.values.error === 50; +pino.levels.labels[50] === 'error'; diff --git a/types/pino/tsconfig.json b/types/pino/tsconfig.json index a5370240d2..733bb5bc9a 100644 --- a/types/pino/tsconfig.json +++ b/types/pino/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "pino-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/pino/tslint.json b/types/pino/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pino/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pino/v3/index.d.ts b/types/pino/v3/index.d.ts new file mode 100644 index 0000000000..560f5bea48 --- /dev/null +++ b/types/pino/v3/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for pino 3.0 +// Project: https://github.com/mcollina/pino.git +// Definitions by: Peter Snider +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +import stream = require('stream'); + +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform): P.Logger; + +declare namespace P { + function pretty(opts?: { timeTransOnly?: boolean, levelFirst?: boolean, formatter?(log: IPinoLog): string }): stream.Transform; + + type Level = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'; + interface Headers { + [header: string]: string; + } + + // tslint:disable-next-line interface-name + interface IPinoLog { + pid: number; + hostname: string; + level: number; + time: string; + msg: string; + v: number; + } + + interface LevelLabelsToValues { + [level: string]: number; + } + + interface LevelValuesToLabels { + [level: number]: string; + } + + interface Serializers { + req?(req: any): any; + res?(res: any): any; + err?(error: Error): any; + } + + interface LoggerOptions { + // avoid error causes by circular references in the object tree, default true + safe?: boolean; + // the name of the logger, default undefined + name?: string; + // an object containing functions for custom serialization of objects. + // These functions should return an JSONifiable object and they should never throw + serializers?: Serializers; + // Outputs ISO time stamps ('2016-03-09T15:18:53.889Z') instead of Epoch time stamps (1457536759176). + // WARNING: This option carries a 25% performance drop, we recommend using default Epoch timestamps and transforming logs after if required. + // The pino -t command will do this for you (see CLI). default false. + slowtime?: boolean; + // Enables extreme mode, yields an additional 60% performance (from 250ms down to 100ms per 10000 ops). + // There are trade-off's should be understood before usage. See Extreme mode explained. default false + extreme?: boolean; + // enables logging, defaults to true. + enabled?: boolean; + level?: Level | string; + levelVal?: number; + } + + interface Pino { + (optionsOrStream?: LoggerOptions | stream.Writable | stream.Duplex): Logger; + (options: LoggerOptions, stream: stream.Writable | stream.Duplex): Logger; + levels: { + values: LevelLabelsToValues + labels: LevelValuesToLabels + }; + LOG_VERSION: number; + } + + type LevelChangeEventListener = (lvl: string, val: number, prevLvl: string, prevVal: number) => void; + type LevelChangeEvent = 'level-change'; + + interface Logger { + child(bindings: {}): Logger; + level: Level; + levelVal: number; + on(event: LevelChangeEvent, listener: LevelChangeEventListener): void; + fatal(msg: string, ...args: any[]): void; + fatal(obj: {}, msg?: string, ...args: any[]): void; + error(msg: string, ...args: any[]): void; + error(obj: {}, msg?: string, ...args: any[]): void; + warn(msg: string, ...args: any[]): void; + warn(obj: {}, msg?: string, ...args: any[]): void; + info(msg: string, ...args: any[]): void; + info(obj: {}, msg?: string, ...args: any[]): void; + debug(msg: string, ...args: any[]): void; + debug(obj: {}, msg?: string, ...args: any[]): void; + trace(msg: string, ...args: any[]): void; + trace(obj: {}, msg?: string, ...args: any[]): void; + levels: { + values: LevelLabelsToValues + labels: LevelValuesToLabels + }; + LOG_VERSION: number; + stdSerializers: Serializers; + } +} + +export = P; diff --git a/types/pino/v3/pino-tests.ts b/types/pino/v3/pino-tests.ts new file mode 100644 index 0000000000..fb3dad2d9c --- /dev/null +++ b/types/pino/v3/pino-tests.ts @@ -0,0 +1,39 @@ +// This contains all of the code from the docs on https://www.npmjs.com/package/pino + +import PINO = require('pino'); +import * as stream from 'stream'; + +const pino = PINO(); +const info = pino.info; +const error = pino.error; + +info('hello world'); +error('this is at error level'); +info('the answer is %d', 42); +info({ obj: 42 }, 'hello world'); +info({ obj: 42, b: 2 }, 'hello world'); +info({ obj: { aa: 'bbb' } }, 'another'); +setImmediate(info, 'after setImmediate'); +error(new Error('an error')); + +let instance: PINO.Logger = PINO({ + name: 'myapp', + safe: true, + serializers: { + req: pino.stdSerializers.req, + res: pino.stdSerializers.res + } +}); + +let version: number = pino.LOG_VERSION; +let levels: {} = pino.levels; + +let pretty: stream.Transform = PINO.pretty(); + +let logger2: PINO.Logger = PINO({ + name: 'app', + safe: true +}, pretty); + +const logger = instance; +logger.child({ a: 'property' }).info('hello child!'); diff --git a/types/pino/v3/tsconfig.json b/types/pino/v3/tsconfig.json new file mode 100644 index 0000000000..86c9bbdaf2 --- /dev/null +++ b/types/pino/v3/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "pino": [ "pino/v3" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pino-tests.ts" + ] +} diff --git a/types/pino/v3/tslint.json b/types/pino/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pino/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/raven/index.d.ts b/types/raven/index.d.ts index 7c1fd4926e..610122ab66 100644 --- a/types/raven/index.d.ts +++ b/types/raven/index.d.ts @@ -11,8 +11,8 @@ import { EventEmitter } from 'events'; export const version: string; export function config(dsn: string | false, options?: ConstructorOptions): Client; -export function wrap(func: () => void, onErr?: () => void): () => void; -export function wrap(options: any, func: () => void, onErr?: () => void): () => void; +export function wrap(func: () => T): () => T; +export function wrap(options: any, func: () => T): () => T; export function interceptErr(ctx: any): Client; export function setContext(ctx: any): Client; export function captureException(e: Error, cb?: CaptureCallback): string; @@ -23,8 +23,8 @@ export function mergeContext(ctx: any): Client; export function getContext(): any; export function requestHandler(): (req: IncomingMessage, res: ServerResponse, next: () => void) => void; export function errorHandler(): (e: Error, req: IncomingMessage, res: ServerResponse, next: () => void) => void; -export function context(ctx: any, func: () => void, onErr?: () => void): Client; -export function context(func: () => void, onErr?: () => void): Client; +export function context(ctx: any, func: () => T): T; +export function context(func: () => T): T; export function captureBreadcrumb(breadcrumb: any): void; export function disableConsoleAlerts(): void; export function consoleAlert(msg: string): void; @@ -33,9 +33,9 @@ export function parseDSN(dsn: string | false): parsedDSN; export class Client extends EventEmitter { constructor(options: ConstructorOptions); constructor(dsn: string, options?: ConstructorOptions); - config(dsn: string, options?: ConstructorOptions): Client; - install(options?: ConstructorOptions, cb?: () => void): Client; - setContext(ctx: any): Client; + config(dsn: string, options?: ConstructorOptions): this; + install(options?: ConstructorOptions, cb?: () => void): this; + setContext(ctx: any): this; requestHandler(): (req: IncomingMessage, res: ServerResponse, next: () => void) => void; errorHandler(): (e: Error, req: IncomingMessage, res: ServerResponse, next: () => void) => void; captureException(error: Error, cb?: CaptureCallback): string; @@ -45,8 +45,9 @@ export class Client extends EventEmitter { captureBreadcrumb(breadcrumb: any): void; setUserContext(data: UserData): void; setDataCallback(fn: DataCallback): void; - context(ctx: any, func: () => void, onErr?: () => void): Client; - context(func: () => void, onErr?: () => void): Client; + setShouldSendCallback(fn: ShouldSendCallback): this; + context(ctx: any, func: () => T): T; + context(func: () => T): T; process(kwargs: any, cb?: () => void): void; process(eventId: string, kwargs: any, cb?: () => void): void; } @@ -59,11 +60,15 @@ export interface ConstructorOptions { tags?: { [key: string]: string }; extra?: { [key: string]: any }; dataCallback?: DataCallback; + shouldSendCallback?: ShouldSendCallback; transport?(): void; captureUnhandledRejections?: boolean; autoBreadcrumbs?: boolean | any; + parseUser?: boolean | string[] | parseUserCallback; } +export type parseUserCallback = (req: any) => any; + export interface UserData { id: string; handle?: string; @@ -83,6 +88,8 @@ export type CaptureCallback = (err: { [key: string]: any }, eventId: any) => voi export type DataCallback = (data: { [key: string]: any }) => void; +export type ShouldSendCallback = (data: { [key: string]: any }) => boolean; + export type TransportCallback = (options: { [key: string]: any }) => void; export interface CaptureOptions { diff --git a/types/raven/raven-tests.ts b/types/raven/raven-tests.ts index d419b32d12..4d96e7eafa 100644 --- a/types/raven/raven-tests.ts +++ b/types/raven/raven-tests.ts @@ -3,6 +3,11 @@ import * as Raven from 'raven'; const dsn = '___DSN___'; const client = Raven.config(dsn, { autoBreadcrumbs: true }).install(); +Raven.config(dsn, { + logger: 'logger', + parseUser: ['id', 'name'], + autoBreadcrumbs: false, +}); console.log(Raven.version); Raven.config(dsn).install({ captureUnhandledRejections: true }); client.setContext({}); diff --git a/types/rc-tooltip/index.d.ts b/types/rc-tooltip/index.d.ts index 84068dd920..c24f0018fd 100644 --- a/types/rc-tooltip/index.d.ts +++ b/types/rc-tooltip/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for rc-tooltip v3.4.2 // Project: https://github.com/react-component/tooltip // Definitions by: rhysd +// ahstro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -26,7 +27,7 @@ declare namespace Tooltip { placement?: Placement | Object; align?: Object; onPopupAlign?: (popupDomNode: Element, align: Object) => void; - overlay: React.ReactElement | (() => React.ReactElement); + overlay: React.ReactNode; arrowContent?: React.ReactNode; getTooltipContainer?: () => Element; destroyTooltipOnHide?: boolean; diff --git a/types/rc-tooltip/rc-tooltip-tests.tsx b/types/rc-tooltip/rc-tooltip-tests.tsx index 751ffc43ec..832a292e97 100644 --- a/types/rc-tooltip/rc-tooltip-tests.tsx +++ b/types/rc-tooltip/rc-tooltip-tests.tsx @@ -9,6 +9,13 @@ ReactDOM.render( document.querySelector('.app') ); +ReactDOM.render( + + hover + , + document.querySelector('.app') +); + ReactDOM.render( , Marks Polakovs +// Definitions by: Karol Janyst , Marks Polakovs , Matthieu Montaudouin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/react-color/lib/components/block/Block.d.ts b/types/react-color/lib/components/block/Block.d.ts index 9b3633265b..e50b84c6ac 100644 --- a/types/react-color/lib/components/block/Block.d.ts +++ b/types/react-color/lib/components/block/Block.d.ts @@ -1,9 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps } from "react-color"; +import { ColorPickerProps, Color } from "react-color"; export interface BlockPickerProps extends ColorPickerProps { colors?: string[]; width?: string; + triangle?: 'hide' | 'top'; + onSwatchHover?(color: Color, event: MouseEvent): void; } export default class BlockPicker extends Component {} diff --git a/types/react-color/lib/components/circle/Circle.d.ts b/types/react-color/lib/components/circle/Circle.d.ts index 045c5a93bb..5b9e79a0b4 100644 --- a/types/react-color/lib/components/circle/Circle.d.ts +++ b/types/react-color/lib/components/circle/Circle.d.ts @@ -1,9 +1,12 @@ import { Component } from "react"; -import { ColorPickerProps } from "react-color"; +import { ColorPickerProps, Color } from "react-color"; export interface CirclePickerProps extends ColorPickerProps { colors?: string[]; width?: string; + circleSize?: number; + circleSpacing?: number; + onSwatchHover?(color: Color, event: MouseEvent): void; } export default class CirclePicker extends Component {} diff --git a/types/react-color/lib/components/compact/Compact.d.ts b/types/react-color/lib/components/compact/Compact.d.ts index a661972a41..125f496f90 100644 --- a/types/react-color/lib/components/compact/Compact.d.ts +++ b/types/react-color/lib/components/compact/Compact.d.ts @@ -1,8 +1,9 @@ import { Component } from "react"; -import { ColorPickerProps } from "react-color"; +import { ColorPickerProps, Color } from "react-color"; export interface CompactPickerProps extends ColorPickerProps { colors?: string[]; + onSwatchHover?(color: Color, event: MouseEvent): void; } export default class CompactPicker extends Component {} diff --git a/types/react-color/lib/components/github/Github.d.ts b/types/react-color/lib/components/github/Github.d.ts index c4b6e7c27c..d0800c9740 100644 --- a/types/react-color/lib/components/github/Github.d.ts +++ b/types/react-color/lib/components/github/Github.d.ts @@ -1,10 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps } from "react-color"; +import { ColorPickerProps, Color } from "react-color"; export interface GithubPickerProps extends ColorPickerProps { colors?: string[]; width?: string; triangle?: 'hide' | 'top-left' | 'top-right'; + onSwatchHover?(color: Color, event: MouseEvent): void; } export default class GithubPicker extends Component {} diff --git a/types/react-color/lib/components/sketch/Sketch.d.ts b/types/react-color/lib/components/sketch/Sketch.d.ts index 3a1ac6c3fe..6018674809 100644 --- a/types/react-color/lib/components/sketch/Sketch.d.ts +++ b/types/react-color/lib/components/sketch/Sketch.d.ts @@ -1,10 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps } from "react-color"; +import { ColorPickerProps, Color } from "react-color"; export interface SketchPickerProps extends ColorPickerProps { disableAlpha?: boolean; presetColors?: string[]; width?: string; + onSwatchHover?(color: Color, event: MouseEvent): void; } export default class SketchPicker extends Component {} diff --git a/types/react-color/lib/components/swatches/Swatches.d.ts b/types/react-color/lib/components/swatches/Swatches.d.ts index d821fc7c3d..af3efb7652 100644 --- a/types/react-color/lib/components/swatches/Swatches.d.ts +++ b/types/react-color/lib/components/swatches/Swatches.d.ts @@ -1,10 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps } from "react-color"; +import { ColorPickerProps, Color } from "react-color"; export interface SwatchesPickerProps extends ColorPickerProps { colors?: string[][]; height?: number; width?: number; + onSwatchHover?(color: Color, event: MouseEvent): void; } export default class SwatchesPicker extends Component {} diff --git a/types/react-color/lib/components/twitter/Twitter.d.ts b/types/react-color/lib/components/twitter/Twitter.d.ts index 84b53dbc7a..3c37ebb8f5 100644 --- a/types/react-color/lib/components/twitter/Twitter.d.ts +++ b/types/react-color/lib/components/twitter/Twitter.d.ts @@ -1,6 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps } from "react-color"; +import { ColorPickerProps, Color } from "react-color"; -export type TwitterPickerProps = ColorPickerProps; +export interface TwitterPickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; + triangle?: 'hide' | 'top-left' | 'top-right'; + onSwatchHover?(color: Color, event: MouseEvent): void; +} export default class TwitterPicker extends Component {} diff --git a/types/react-daum-postcode/index.d.ts b/types/react-daum-postcode/index.d.ts index d5256161f0..cd2713a459 100644 --- a/types/react-daum-postcode/index.d.ts +++ b/types/react-daum-postcode/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-daum-postcode 1.2 +// Type definitions for react-daum-postcode 1.3 // Project: https://github.com/kimminsik-bernard/react-daum-postcode // Definitions by: Sa-ryong Kang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,18 +6,21 @@ import { Component } from 'react'; -export interface DaumPostcodeProps { - onComplete?: any; - width?: any; - height?: any; - autoClose?: any; - autoResize?: any; - animation?: any; - style?: any; - defaultQuery?: any; - theme?: any; +export namespace DaumPostcode { + interface Props { + onComplete: any; + width?: number | string; + height?: number | string; + autoClose?: boolean; + autoResize?: boolean; + animation?: boolean; + style?: any; + defaultQuery?: string; + theme?: any; + scriptUrl?: string; + } } -export default class DaumPostcode extends Component { +export default class DaumPostcode extends Component { render(): JSX.Element; } diff --git a/types/react-daum-postcode/package.json b/types/react-daum-postcode/package.json index ea72a99f2c..54cf661ac8 100644 --- a/types/react-daum-postcode/package.json +++ b/types/react-daum-postcode/package.json @@ -1,5 +1,5 @@ { "dependencies": { - "react-daum-postcode": "^1.2.1" + "react-daum-postcode": "^1.3.0" } } \ No newline at end of file diff --git a/types/react-dom/node-stream/index.d.ts b/types/react-dom/node-stream/index.d.ts new file mode 100644 index 0000000000..449d45b46d --- /dev/null +++ b/types/react-dom/node-stream/index.d.ts @@ -0,0 +1,20 @@ +/// +import { ReactElement } from 'react'; +import * as stream from 'stream'; + +/** + * Render a ReactElement to its initial HTML. This should only be used on the + * server. + * See https://facebook.github.io/react/docs/react-dom-stream.html#rendertostream + */ +export function renderToStream(element: ReactElement): stream.Readable; + +/** + * Similar to renderToStream, except this doesn't create extra DOM attributes + * such as data-react-id that React uses internally. + * See https://facebook.github.io/react/docs/react-dom-stream.html#rendertostaticstream + */ +export function renderToStaticStream(element: ReactElement): stream.Readable; +export const version: string; + +export as namespace ReactDOMNodeStream; diff --git a/types/react-dom/react-dom-tests.ts b/types/react-dom/react-dom-tests.ts index 534b847787..9a60724dae 100644 --- a/types/react-dom/react-dom-tests.ts +++ b/types/react-dom/react-dom-tests.ts @@ -1,7 +1,9 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as ReactDOMServer from 'react-dom/server'; +import * as ReactDOMNodeStream from 'react-dom/node-stream'; import * as ReactTestUtils from 'react-dom/test-utils'; +import * as stream from 'stream'; declare function describe(desc: string, f: () => void): void; declare function it(desc: string, f: () => void): void; @@ -37,6 +39,16 @@ describe('ReactDOMServer', () => { }); }); +describe('ReactDOMNodeStream', () => { + it('renderToStream', () => { + const content: stream.Readable = ReactDOMNodeStream.renderToStream(React.createElement('div')); + }); + + it('renderToStaticStream', () => { + const content: stream.Readable = ReactDOMNodeStream.renderToStaticStream(React.createElement('div')); + }); +}); + describe('React dom test utils', () => { it('Simulate', () => { const element = document.createElement('div'); diff --git a/types/react-dom/tsconfig.json b/types/react-dom/tsconfig.json index c93c6f8195..8c270fabed 100644 --- a/types/react-dom/tsconfig.json +++ b/types/react-dom/tsconfig.json @@ -3,6 +3,7 @@ "index.d.ts", "react-dom-tests.ts", "server/index.d.ts", + "node-stream/index.d.ts", "test-utils/index.d.ts" ], "compilerOptions": { @@ -22,4 +23,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/types/react-faux-dom/index.d.ts b/types/react-faux-dom/index.d.ts index 0a363de3f0..59c771527d 100644 --- a/types/react-faux-dom/index.d.ts +++ b/types/react-faux-dom/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for react-faux-dom 3.1 +// Type definitions for react-faux-dom 3.2 // Project: https://github.com/Olical/react-faux-dom // Definitions by: Ali Taheri Moghaddar +// Cleve Littlefield // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -28,3 +29,10 @@ export function createElement(nodeName: string): Element; export function createElementNS(namespace: string, nodeName: string): Element; export function compareDocumentPosition(): number; + +export interface ReactFauxDomProps { + connectFauxDOM?(node: string, name: string, discardNode?: any): Element; + animateFauxDOM?(duration: number): void; +} + +export function withFauxDOM

(WrappedComponent: any): React.ClassicComponentClass

; diff --git a/types/react-faux-dom/react-faux-dom-tests.tsx b/types/react-faux-dom/react-faux-dom-tests.tsx index 0410306f6b..2d864744bc 100644 --- a/types/react-faux-dom/react-faux-dom-tests.tsx +++ b/types/react-faux-dom/react-faux-dom-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import * as d3 from 'd3'; -import { createElement, Element } from 'react-faux-dom'; +import { createElement, Element, ReactFauxDomProps, withFauxDOM } from 'react-faux-dom'; class SomeChart extends React.Component { render() { @@ -21,3 +21,30 @@ class SomeChart extends React.Component { return el.toReact(); } } + +interface ChartProps extends ReactFauxDomProps { + chart?: any; +} + +class MyReactComponent extends React.Component { + componentDidMount() { + if (this.props.connectFauxDOM && this.props.animateFauxDOM) { + const faux = this.props.connectFauxDOM('div', 'chart'); + d3.select(faux) + .append('div') + .html('Hello World!'); + this.props.animateFauxDOM(800); + } + } + + render() { + return

+

Here is some fancy data:

+
+ {this.props.chart} +
+
; + } +} + +const AdvancedComponent = withFauxDOM(MyReactComponent); diff --git a/types/react-native-modalbox/index.d.ts b/types/react-native-modalbox/index.d.ts index 9bd075fbe0..57b8ddeff1 100644 --- a/types/react-native-modalbox/index.d.ts +++ b/types/react-native-modalbox/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native-modalbox 1.3 +// Type definitions for react-native-modalbox 1.4 // Project: https://github.com/maxs15/react-native-modalbox#readme // Definitions by: Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -149,6 +149,14 @@ export interface ModalProps extends ViewProperties { */ backButtonClose?: boolean; + /** + * + * Default is false + * @type {boolean} + * @memberof ModalProps + */ + coverScreen?: boolean; + /** * If the modal should appear open without animation upon first mount * diff --git a/types/react-native-sensor-manager/index.d.ts b/types/react-native-sensor-manager/index.d.ts new file mode 100644 index 0000000000..248fb84e09 --- /dev/null +++ b/types/react-native-sensor-manager/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for react-native-sensor-manager 0.1 +// Project: https://github.com/kprimice/react-native-sensor-manager +// Definitions by: Sahin Vardar +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export * from 'react-native' + +interface SensorManager { + startAccelerometer(delay: number): void; + stopAccelerometer(): void; + startGyroscope(delay: number): void; + stopGyroscope(): void; + startMagnetometer(delay: number): void; + stopMagnetometer(): void; + startStepCounter(delay: number): void; + stopStepCounter(): void; + startThermometer(delay: number): void; + stopThermometer(): void; + startMotionValue(delay: number): void; + stopMotionValue(): void; + startOrientation(delay: number): void; + stopOrientation(): void; + startProximity(delay: number): void; + stopProximity(): void; + startLightSensor(delay: number): void; + stopLightSensor(): void; +} + +declare module 'react-native' { + export interface DeviceEventEmitterStatic { + addListener(event: 'Accelerometer' | 'Gyroscope' | 'Magnetometer', callback: (data: {x: number, y: number, z: number}) => void): EmitterSubscription; + addListener(event: 'Orientation', callback: (data: {azimuth: number, pitch: number, roll: number}) => void): EmitterSubscription; + addListener(event: 'StepCounter', callback: (data: {steps: number}) => void): EmitterSubscription; + addListener(event: 'Thermometer', callback: (data: {temp: number}) => void): EmitterSubscription; + addListener(event: 'LightSensor', callback: (data: {light: number}) => void): EmitterSubscription; + addListener(event: 'Proximity', callback: (data: {isNear: boolean, value: number, maxRange: number}) => void): EmitterSubscription ; + } + + export interface NativeModulesStatic { + SensorManager: SensorManager + } +} diff --git a/types/react-native-sensor-manager/react-native-sensor-manager-tests.ts b/types/react-native-sensor-manager/react-native-sensor-manager-tests.ts new file mode 100644 index 0000000000..746b68744f --- /dev/null +++ b/types/react-native-sensor-manager/react-native-sensor-manager-tests.ts @@ -0,0 +1,73 @@ +import { DeviceEventEmitter, NativeModules } from 'react-native' + +const SensorManager = NativeModules.SensorManager + +let num: number; +let bool: boolean; + +SensorManager.startAccelerometer(num); +SensorManager.stopAccelerometer(); + +SensorManager.startGyroscope(num); +SensorManager.stopGyroscope(); + +SensorManager.startMagnetometer(num); +SensorManager.stopMagnetometer(); + +SensorManager.startStepCounter(num); +SensorManager.stopStepCounter(); + +SensorManager.startThermometer(num); +SensorManager.stopThermometer(); + +SensorManager.startMotionValue(num); +SensorManager.stopMotionValue(); + +SensorManager.startOrientation(num); +SensorManager.stopOrientation(); + +SensorManager.startProximity(num); +SensorManager.stopProximity(); + +SensorManager.startLightSensor(num); +SensorManager.stopLightSensor(); + + +DeviceEventEmitter.addListener('Accelerometer', (data) => { + num = data.x; + num = data.y; + num = data.z; +}); + + +DeviceEventEmitter.addListener('Gyroscope', (data) => { + num = data.x; + num = data.y; + num = data.z; +}); + +DeviceEventEmitter.addListener('Magnetometer', (data) => { + num = data.x; + num = data.y; + num = data.z; +}); + +DeviceEventEmitter.addListener('Orientation', (data) => { + num = data.azimuth; + num = data.pitch; + num = data.roll; +}); + +DeviceEventEmitter.addListener('Thermometer', (data) => { + num = data.temp; +}); + +DeviceEventEmitter.addListener('LightSensor', (data) => { + num = data.light; +}); + +DeviceEventEmitter.addListener('Proximity', (data) => { + bool = data.isNear; + num = data.value; + num = data.value; +}); diff --git a/types/base64url/tsconfig.json b/types/react-native-sensor-manager/tsconfig.json similarity index 90% rename from types/base64url/tsconfig.json rename to types/react-native-sensor-manager/tsconfig.json index d362086905..15d71dd648 100644 --- a/types/base64url/tsconfig.json +++ b/types/react-native-sensor-manager/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "base64url-tests.ts" + "react-native-sensor-manager-tests.ts" ] } \ No newline at end of file diff --git a/types/react-native-sensor-manager/tslint.json b/types/react-native-sensor-manager/tslint.json new file mode 100644 index 0000000000..816b158d9d --- /dev/null +++ b/types/react-native-sensor-manager/tslint.json @@ -0,0 +1,20 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "align": false, + "array-type": false, + "comment-format": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "no-misused-new": false, + "no-consecutive-blank-lines": false, + "no-empty-interface": false, + "no-padding": false, + "no-var": false, + "prefer-declare-function": false, + "prefer-method-signature": false, + "semicolon": false, + "strict-export-declare-modifiers": false + } +} diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 7e850992fc..c3d3fe9114 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native 0.46 +// Type definitions for react-native 0.47 // Project: https://github.com/facebook/react-native // Definitions by: Eloy Durán // Fedor Nezhivoi @@ -4512,6 +4512,7 @@ export interface TouchableNativeFeedbackProperties extends TouchableWithoutFeedb * type is available on Android API level 21+ */ background?: BackgroundPropType + useForeground?: boolean } /** @@ -8926,6 +8927,12 @@ export var NativeEventEmitter: NativeEventEmitter * adding all event listeners directly to RCTNativeAppEventEmitter. */ export var NativeAppEventEmitter: RCTNativeAppEventEmitter + +/** + * Empty interface which can be augmented by other type definitions for the NativeModules var below. + */ +interface NativeModulesStatic {} + /** * Native Modules written in ObjectiveC/Swift/Java exposed via the RCTBridge * Define lazy getters for each module. These will return the module if already loaded, or load it if not. @@ -8933,7 +8940,7 @@ export var NativeAppEventEmitter: RCTNativeAppEventEmitter * Use: * const MyModule = NativeModules.ModuleName */ -export var NativeModules: any +export var NativeModules: NativeModulesStatic export var Platform: PlatformStatic export var PixelRatio: PixelRatioStatic diff --git a/types/react-notification-system-redux/index.d.ts b/types/react-notification-system-redux/index.d.ts index 43161bfa55..1e009a4f46 100644 --- a/types/react-notification-system-redux/index.d.ts +++ b/types/react-notification-system-redux/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-notification-system-redux 1.0 +// Type definitions for react-notification-system-redux 1.1 // Project: https://github.com/gor181/react-notification-system-redux // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -35,4 +35,5 @@ declare namespace Notifications { const info: NotificationShow; const success: NotificationShow; const warning: NotificationShow; + function removeAll(): Action; } diff --git a/types/react-notification-system-redux/package.json b/types/react-notification-system-redux/package.json index e52256ea90..36ce503807 100644 --- a/types/react-notification-system-redux/package.json +++ b/types/react-notification-system-redux/package.json @@ -2,4 +2,4 @@ "dependencies": { "redux": "^3.6.0" } -} \ No newline at end of file +} diff --git a/types/react-notification-system-redux/react-notification-system-redux-tests.tsx b/types/react-notification-system-redux/react-notification-system-redux-tests.tsx index 2225fa744a..631147976a 100644 --- a/types/react-notification-system-redux/react-notification-system-redux-tests.tsx +++ b/types/react-notification-system-redux/react-notification-system-redux-tests.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import { createStore, Store } from "redux"; import { Notification } from "react-notification-system"; import * as Notifications from "react-notification-system-redux"; -import { reducer, show, hide, info, error, warning, success, NotificationLevel } from "react-notification-system-redux"; +import { reducer, removeAll, show, hide, info, error, warning, success, NotificationLevel } from "react-notification-system-redux"; class Test extends React.Component { private test() { @@ -20,6 +20,7 @@ class Test extends React.Component { hide(notification); hide("uid"); hide(123); + removeAll(); } render() { diff --git a/types/react-router-redux/index.d.ts b/types/react-router-redux/index.d.ts index 3af56972e3..86ba9f2116 100644 --- a/types/react-router-redux/index.d.ts +++ b/types/react-router-redux/index.d.ts @@ -25,7 +25,7 @@ export interface ConnectedRouterProps { } export class ConnectedRouter extends React.Component> {} -export const LOCATION_CHANGE: string; +export const LOCATION_CHANGE = '@@router/LOCATION_CHANGE'; export interface RouterState { location: Location | null; @@ -33,7 +33,7 @@ export interface RouterState { export const routerReducer: Reducer; -export const CALL_HISTORY_METHOD: string; +export const CALL_HISTORY_METHOD = '@@router/CALL_HISTORY_METHOD'; export function push(location: LocationDescriptor, state?: LocationState): RouterAction; export function replace(location: LocationDescriptor, state?: LocationState): RouterAction; diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index 24ef712a05..abfed81047 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -20,14 +20,16 @@ declare namespace ReactSelectClass { class Async extends React.Component { } class AsyncCreatable extends React.Component { } + type HandlerRendererResult = JSX.Element | null | false; + // Handlers type FocusOptionHandler = (option: Option) => void; type SelectValueHandler = (option: Option) => void; - type ArrowRendererHandler = (props: ArrowRendererProps) => JSX.Element; + type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; type FilterOptionHandler = (option: Option, filter: string) => Option; type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; - type InputRendererHandler = (props: { [key: string]: any }) => JSX.Element; - type MenuRendererHandler = (props: MenuRendererProps) => JSX.Element; + type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; + type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; type OnCloseHandler = () => void; type OnInputChangeHandler = (inputValue: string) => void; type OnInputKeyDownHandler = React.KeyboardEventHandler; @@ -35,8 +37,8 @@ declare namespace ReactSelectClass { type OnOpenHandler = () => void; type OnFocusHandler = React.FocusEventHandler; type OnBlurHandler = React.FocusEventHandler; - type OptionRendererHandler = (option: Option) => JSX.Element; - type ValueRendererHandler = (option: Option) => JSX.Element; + type OptionRendererHandler = (option: Option) => HandlerRendererResult; + type ValueRendererHandler = (option: Option) => HandlerRendererResult; type OnValueClickHandler = (value: string, event: React.MouseEvent) => void; type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; type IsValidNewOptionHandler = (arg: { label: string }) => boolean; diff --git a/types/react-select/react-select-tests.tsx b/types/react-select/react-select-tests.tsx index 3dd010536f..13d64d32ce 100644 --- a/types/react-select/react-select-tests.tsx +++ b/types/react-select/react-select-tests.tsx @@ -151,4 +151,24 @@ describe("Examples", () => { } } }); + + it("Input render with false renderer props", () => { + false} + inputRenderer={props => false} + menuRenderer={props => false} + optionRenderer={props => false} + valueRenderer={props => false} + />; + }); + + it("Input render with null renderer props", () => { + null} + inputRenderer={props => null} + menuRenderer={props => null} + optionRenderer={props => null} + valueRenderer={props => null} + />; + }); }); diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 6b5b163048..261b8886d1 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -346,12 +346,48 @@ declare namespace React { // ---------------------------------------------------------------------- interface ComponentLifecycle { + /** + * Called immediately before mounting occurs, and before `Component#render`. + * Avoid introducing any side-effects or subscriptions in this method. + */ componentWillMount?(): void; + /** + * Called immediately after a compoment is mounted. Setting state here will trigger re-rendering. + */ componentDidMount?(): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling `Component#setState` generally does not trigger this method. + */ componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called to determine whether the change in props and state should trigger a re-render. + * + * `Component` always returns true. + * `PureComponent` implements a shallow comparison on props and state and returns true if any + * props or states have changed. + * + * If false is returned, `Component#render`, `componentWillUpdate` + * and `componentDidUpdate` will not be called. + */ shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call `Component#setState` here. + */ componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + /** + * Called immediately after updating occurs. Not called for the initial render. + */ componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, prevContext: any): void; + /** + * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as + * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`. + */ componentWillUnmount?(): void; /** * Catches exceptions generated in descendant components. Unhandled exceptions will cause diff --git a/types/redux-first-router/index.d.ts b/types/redux-first-router/index.d.ts index e1f62e1014..5acbe08493 100644 --- a/types/redux-first-router/index.d.ts +++ b/types/redux-first-router/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for redux-first-router 1.4 +// Type definitions for redux-first-router 1.9 // Project: https://github.com/faceyspacey/redux-first-router#readme // Definitions by: Valbrand +// viggyfresh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -38,9 +39,23 @@ export interface RoutesMap { export interface ReceivedAction { type: string; - payload: object; + payload: Payload; meta?: object; - navKey?: string | null; + query?: object; + search?: string; + navKey?: Nullable; +} + +export interface ReceivedActionMeta { + type: string; + payload: Payload; + query?: object; + navKey?: Nullable; + meta: { + notFoundPath?: string; + query?: object; + search?: string; + }; } export interface HistoryData { @@ -52,13 +67,17 @@ export interface HistoryData { export interface Location { pathname: string; type: string; - payload: object; + payload: Payload; + query?: object; + search?: string; } export interface LocationState { pathname: string; type: string; - payload: object; + payload: Payload; + query?: object; + search?: string; prev: Location; kind: Nullable; history: Nullable; @@ -80,7 +99,7 @@ export interface NavigationAction { routeName?: string; actions?: NavigationAction[]; action?: NavigationAction; - params?: object; + params?: Params; meta?: object; } @@ -88,17 +107,21 @@ export interface Meta { location: ActionMetaLocation; notFoundPath?: string; navigation?: NavigationAction; + query?: object; + search?: string; } export interface Action { type: string; - payload: object; + payload: Payload; meta: Meta; - navKey?: string; + query?: object; + navKey?: Nullable; } export interface HistoryLocation { pathname: string; + search?: string; } export type HistoryAction = string; @@ -110,7 +133,7 @@ export type ScrollBehavior = object; export interface Router { getStateForActionOriginal(action: object, state: Nullable): Nullable; getStateForAction(action: object, state: Nullable): Nullable; - getPathAndParamsForState(state: object): { path: Nullable, params: Nullable }; + getPathAndParamsForState(state: object): { path: Nullable, params: Nullable }; getActionForPathAndParams(path: string): Nullable; } @@ -122,6 +145,14 @@ export interface Navigators { [key: string]: Navigator; } +export type SelectLocationState = (state: object) => LocationState; +export type SelectTitleState = (state: object) => string; + +export interface QuerySerializer { + stringify(params: Params): string; + parse(queryString: string): object; +} + export interface NavigatorsConfig { navigators: Navigators; patchNavigators(navigators: Navigators): void; @@ -144,17 +175,22 @@ export interface NavigatorsConfig { } export interface Options { - title?: string; - location?: string; + title?: string | SelectTitleState; + location?: string | SelectLocationState; notFoundPath?: string; scrollTop?: boolean; onBeforeChange?(dispatch: Dispatch, getState: StateGetter): void; onAfterChange?(dispatch: Dispatch, getState: StateGetter): void; onBackNext?(dispatch: Dispatch, getState: StateGetter): void; restoreScroll?(history: History): ScrollBehavior; + initialDispatch?: boolean; + querySerializer?: QuerySerializer; navigators?: NavigatorsConfig; } +export type Params = object; +export type Payload = object; + export type ScrollUpdater = (performedByUser: boolean) => void; export const NOT_FOUND: string; @@ -170,10 +206,11 @@ export function canGoBack(): boolean; export function canGoForward(): boolean; export function connectRoutes(history: History, routesMap: RoutesMap, options?: Options): { - reducer: Reducer + reducer: Reducer, middleware: Middleware, thunk(store: Store): Promise>, - enhancer: GenericStoreEnhancer + enhancer: GenericStoreEnhancer, + initialDispatch?(): void }; export function go(n: number): void; diff --git a/types/redux-first-router/redux-first-router-tests.ts b/types/redux-first-router/redux-first-router-tests.ts index aab3f8c2a0..fc913aebcf 100644 --- a/types/redux-first-router/redux-first-router-tests.ts +++ b/types/redux-first-router/redux-first-router-tests.ts @@ -26,8 +26,11 @@ const routesMap = { const { reducer, middleware, - enhancer -} = connectRoutes(history, routesMap); + enhancer, + initialDispatch +} = connectRoutes(history, routesMap, { + initialDispatch: false +}); const dumbMiddleware: Middleware = (store: MiddlewareAPI) => (next: Dispatch) => (action: Action) => { next(action); diff --git a/types/shelljs/index.d.ts b/types/shelljs/index.d.ts index f2a74bc561..d2bc88875c 100644 --- a/types/shelljs/index.d.ts +++ b/types/shelljs/index.d.ts @@ -7,6 +7,7 @@ /// import child = require("child_process"); +import glob = require("glob"); /** * Changes to directory dir for the duration of the script @@ -524,10 +525,6 @@ export function touch(options: touchOptionsArray, files: string[]): void; // Configuration -export interface GlobOptions { - [key: string]: any; -} - export interface ShellConfig { /** * Suppresses all command output if true, except for echo() calls. Default is false. @@ -549,9 +546,9 @@ export interface ShellConfig { /** * Passed to glob.sync() instead of the default options ({}). - * @type {Object} + * @type {glob.IOptions} */ - globOptions: GlobOptions; + globOptions: glob.IOptions; /** * Absolute path of the Node binary. Default is null (inferred). diff --git a/types/smoothscroll-polyfill/index.d.ts b/types/smoothscroll-polyfill/index.d.ts new file mode 100644 index 0000000000..1940dc3eec --- /dev/null +++ b/types/smoothscroll-polyfill/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for smoothscroll-polyfill 0.3 +// Project: https://iamdustan.github.io/smoothscroll +// Definitions by: Michael Strobel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function polyfill(): void; diff --git a/types/smoothscroll-polyfill/smoothscroll-polyfill-tests.ts b/types/smoothscroll-polyfill/smoothscroll-polyfill-tests.ts new file mode 100644 index 0000000000..798a8be8af --- /dev/null +++ b/types/smoothscroll-polyfill/smoothscroll-polyfill-tests.ts @@ -0,0 +1,3 @@ +import { polyfill } from 'smoothscroll-polyfill'; + +polyfill(); diff --git a/types/smoothscroll-polyfill/tsconfig.json b/types/smoothscroll-polyfill/tsconfig.json new file mode 100644 index 0000000000..8f54f5ebfc --- /dev/null +++ b/types/smoothscroll-polyfill/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "smoothscroll-polyfill-tests.ts" + ] +} diff --git a/types/smoothscroll-polyfill/tslint.json b/types/smoothscroll-polyfill/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/smoothscroll-polyfill/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/source-map/index.d.ts b/types/source-map/index.d.ts index 310b969f14..0bf31eb438 100644 --- a/types/source-map/index.d.ts +++ b/types/source-map/index.d.ts @@ -1,136 +1,332 @@ -// Type definitions for source-map v0.5.6 +// Type definitions for source-map 0.5 // Project: https://github.com/mozilla/source-map -// Definitions by: Morten Houston Ludvigsen +// Definitions by: Morten Houston Ludvigsen , +// Ron Buckton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = SourceMap; export as namespace sourceMap; -declare namespace SourceMap { - interface StartOfSourceMap { - file?: string; - sourceRoot?: string; - skipValidation?: boolean; - } - - interface RawSourceMap { - version: number; - sources: string[]; - names: string[]; - sourceRoot?: string; - sourcesContent?: string[]; - mappings: string; - file: string; - } - - interface Position { - line: number; - column: number; - } - - interface MappedPosition extends Position { - source: string; - name?: string; - } - - interface MappingItem { - source: string; - generatedLine: number; - generatedColumn: number; - originalLine: number; - originalColumn: number; - name: string; - } - - interface Mapping { - generated: Position; - original: Position; - source: string; - name?: string; - } - - interface CodeWithSourceMap { - code: string; - map: SourceMapGenerator; - } - - class SourceMapConsumer { - public static GENERATED_ORDER: number; - public static ORIGINAL_ORDER: number; - - constructor(rawSourceMap: RawSourceMap | string); - - public computeColumnSpans(): void; - - public originalPositionFor(generatedPosition: Position): MappedPosition; - - public generatedPositionFor(originalPosition: MappedPosition): Position; - - public allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; - - public hasContentsOfAllSources(): boolean; - - public sourceContentFor(source: string, returnNullOnMissing?: boolean): string; - - public eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; - } - - class SourceMapGenerator { - constructor(startOfSourceMap?: StartOfSourceMap); - - public static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; - - public addMapping(mapping: Mapping): void; - - public setSourceContent(sourceFile: string, sourceContent: string): void; - - public applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; - - public toString(): string; - - public toJSON(): RawSourceMap; - } - - class SourceNode { - children: SourceNode []; - sourceContents: any; - line: number; - column: number; - source: string; - name: string; - - constructor(); - constructor(line: number, column: number, source: string); - constructor( - line: number, - column: number, - source: string, - chunks?: (string | SourceNode)[] | SourceNode | string, - name?: string - ); - - public static fromStringWithSourceMap( - code: string, - sourceMapConsumer: SourceMapConsumer, - relativePath?: string - ): SourceNode; - - public add(chunk: (string | SourceNode)[] | SourceNode | string): SourceNode; - - public prepend(chunk: (string | SourceNode)[] | SourceNode | string): SourceNode; - - public setSourceContent(sourceFile: string, sourceContent: string): void; - - public walk(fn: (chunk: string, mapping: MappedPosition) => void): void; - - public walkSourceContents(fn: (file: string, content: string) => void): void; - - public join(sep: string): SourceNode; - - public replaceRight(pattern: string, replacement: string): SourceNode; - - public toString(): string; - - public toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; - } +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; + skipValidation?: boolean; +} + +export interface RawSourceMap { + version: number; + sources: string[]; + names: string[]; + sourceRoot?: string; + sourcesContent?: string[]; + mappings: string; + file: string; +} + +export interface RawIndexMap extends StartOfSourceMap { + version: number; + sections: RawSection[]; +} + +export interface RawSection { + offset: Position; + map: RawSourceMap; +} + +export interface Position { + line: number; + column: number; +} + +export interface NullablePosition { + line: number | null; + column: number | null; + lastColumn: number | null; +} + +export interface MappedPosition { + source: string; + line: number; + column: number; + name?: string; +} + +export interface NullableMappedPosition { + source: string | null; + line: number | null; + column: number | null; + name: string | null; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export interface SourceMapConsumer { + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + computeColumnSpans(): void; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + originalPositionFor(generatedPosition: Position & { bias?: number }): NullableMappedPosition; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + generatedPositionFor(originalPosition: MappedPosition & { bias?: number }): NullablePosition; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + allGeneratedPositionsFor(originalPosition: MappedPosition): NullablePosition[]; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources(): boolean; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param callback + * The function that is called with each mapping. + * @param context + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param order + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface SourceMapConsumerConstructor { + prototype: SourceMapConsumer; + + GENERATED_ORDER: number; + ORIGINAL_ORDER: number; + GREATEST_LOWER_BOUND: number; + LEAST_UPPER_BOUND: number; + + new (rawSourceMap: RawSourceMap): BasicSourceMapConsumer; + new (rawSourceMap: RawIndexMap): IndexedSourceMapConsumer; + new (rawSourceMap: RawSourceMap | RawIndexMap | string): BasicSourceMapConsumer | IndexedSourceMapConsumer; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param sourceMap + * The source map that will be consumed. + */ + fromSourceMap(sourceMap: SourceMapGenerator): BasicSourceMapConsumer; +} + +export const SourceMapConsumer: SourceMapConsumerConstructor; + +export interface BasicSourceMapConsumer extends SourceMapConsumer { + file: string; + sourceRoot: string; + sources: string[]; + sourcesContent: string[]; +} + +export interface BasicSourceMapConsumerConstructor { + prototype: BasicSourceMapConsumer; + + new (rawSourceMap: RawSourceMap | string): BasicSourceMapConsumer; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param sourceMap + * The source map that will be consumed. + */ + fromSourceMap(sourceMap: SourceMapGenerator): BasicSourceMapConsumer; +} + +export const BasicSourceMapConsumer: BasicSourceMapConsumerConstructor; + +export interface IndexedSourceMapConsumer extends SourceMapConsumer { + sources: string[]; +} + +export interface IndexedSourceMapConsumerConstructor { + prototype: IndexedSourceMapConsumer; + + new (rawSourceMap: RawIndexMap | string): IndexedSourceMapConsumer; +} + +export const IndexedSourceMapConsumer: IndexedSourceMapConsumerConstructor; + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param sourceMapConsumer The SourceMap. + */ + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + addMapping(mapping: Mapping): void; + + /** + * Set the source content for a source file. + */ + setSourceContent(sourceFile: string, sourceContent: string): void; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param sourceMapConsumer The source map to be applied. + * @param sourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param sourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + + toString(): string; + + toJSON(): RawSourceMap; +} + +export class SourceNode { + children: SourceNode[]; + sourceContents: any; + line: number; + column: number; + source: string; + name: string; + + constructor(); + constructor( + line: number, + column: number, + source: string, + chunks?: Array<(string | SourceNode)> | SourceNode | string, + name?: string + ); + + static fromStringWithSourceMap( + code: string, + sourceMapConsumer: SourceMapConsumer, + relativePath?: string + ): SourceNode; + + add(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode; + + prepend(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode; + + setSourceContent(sourceFile: string, sourceContent: string): void; + + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + + walkSourceContents(fn: (file: string, content: string) => void): void; + + join(sep: string): SourceNode; + + replaceRight(pattern: string, replacement: string): SourceNode; + + toString(): string; + + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; } diff --git a/types/source-map/source-map-tests.ts b/types/source-map/source-map-tests.ts index 4e584d2338..883abdda91 100644 --- a/types/source-map/source-map-tests.ts +++ b/types/source-map/source-map-tests.ts @@ -2,7 +2,7 @@ import SourceMap = require('source-map'); function testSourceMapConsumer() { function testConstructor() { - var scm: SourceMap.SourceMapConsumer; + let scm: SourceMap.SourceMapConsumer; // create with full RawSourceMap scm = new SourceMap.SourceMapConsumer({ @@ -31,33 +31,52 @@ function testSourceMapConsumer() { mappings: 'foo', file: 'sdf' }); + + // create from index map + let iscm: SourceMap.IndexedSourceMapConsumer = new SourceMap.SourceMapConsumer({ + version: 3, + sections: [ + { offset: { line: 0, column: 0 }, map: { + version: 3, + sources: ['foo', 'bar'], + names: ['foo', 'bar'], + mappings: 'foo', + file: 'foo' + } } + ] + }); + + let scg: SourceMap.SourceMapGenerator; + let bscm: SourceMap.BasicSourceMapConsumer = SourceMap.SourceMapConsumer.fromSourceMap(scg); } function testOriginalPositionFor(scm: SourceMap.SourceMapConsumer) { - var origPos: SourceMap.MappedPosition; + let origPos: SourceMap.MappedPosition; origPos = scm.originalPositionFor({ line: 42, column: 42 }); + origPos = scm.originalPositionFor({ line: 42, column: 42, bias: SourceMap.SourceMapConsumer.LEAST_UPPER_BOUND }); } function testAllGeneratedPositionsFor(scm: SourceMap.SourceMapConsumer) { - var origPos: SourceMap.MappedPosition; - var origPoses: SourceMap.Position[]; + let origPos: SourceMap.MappedPosition; + let origPoses: SourceMap.Position[]; origPoses = scm.allGeneratedPositionsFor(origPos); } function testGeneratedPositionFor(scm: SourceMap.SourceMapConsumer) { - var genPos: SourceMap.Position; + let genPos: SourceMap.Position; genPos = scm.generatedPositionFor({ line: 42, column: 42, source: 'foo' }); genPos = scm.generatedPositionFor({ line: 42, column: 42, source: 'foo', name: 'bar' }); + genPos = scm.generatedPositionFor({ line: 42, column: 42, source: 'foo', name: 'bar', bias: SourceMap.SourceMapConsumer.LEAST_UPPER_BOUND }); } function testSourceContentFor(scm: SourceMap.SourceMapConsumer) { - var content: string; + let content: string; content = scm.sourceContentFor('foo'); } function testEachMapping(scm: SourceMap.SourceMapConsumer) { - var x: SourceMap.MappingItem; - var context: {}; + let x: SourceMap.MappingItem; + let context: {}; scm.eachMapping(mapping => { x = mapping; }); scm.eachMapping(mapping => { x = mapping; }, context); @@ -68,7 +87,7 @@ function testSourceMapConsumer() { function testSourceMapGenerator() { function testConstructor() { - var generator: SourceMap.SourceMapGenerator; + let generator: SourceMap.SourceMapGenerator; generator = new SourceMap.SourceMapGenerator(); generator = new SourceMap.SourceMapGenerator({ @@ -113,14 +132,14 @@ function testSourceMapGenerator() { } function testToString(generator: SourceMap.SourceMapGenerator) { - var str: string; + let str: string; str = generator.toString(); } } function testSourceNode() { function testConstructor() { - var node: SourceMap.SourceNode; + let node: SourceMap.SourceNode; node = new SourceMap.SourceNode(); node = new SourceMap.SourceNode(42, 42, 'foo'); @@ -130,7 +149,7 @@ function testSourceNode() { } function testFromStringWithSourceMap(scm: SourceMap.SourceMapConsumer) { - var node: SourceMap.SourceNode; + let node: SourceMap.SourceNode; node = SourceMap.SourceNode.fromStringWithSourceMap('foo', scm); node = SourceMap.SourceNode.fromStringWithSourceMap('foo', scm, 'bar'); @@ -153,15 +172,15 @@ function testSourceNode() { } function testWalk(node: SourceMap.SourceNode) { - var chunk: string; - var mapping: SourceMap.MappedPosition; + let chunk: string; + let mapping: SourceMap.MappedPosition; node.walk((c, m) => { chunk = c; mapping = m; }); } function testWalkSourceContents(node: SourceMap.SourceNode) { - var file: string; - var content: string; + let file: string; + let content: string; node.walkSourceContents((f, c) => { file = f; content = c; }); } @@ -175,12 +194,12 @@ function testSourceNode() { } function testToString(node: SourceMap.SourceNode) { - var str: string; + let str: string; str = node.toString(); } function testToStringWithSourceMap(node: SourceMap.SourceNode, sos: SourceMap.StartOfSourceMap) { - var result: SourceMap.CodeWithSourceMap; + let result: SourceMap.CodeWithSourceMap; result = node.toStringWithSourceMap(); result = node.toStringWithSourceMap(sos); } diff --git a/types/source-map/tslint.json b/types/source-map/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/source-map/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/spectacle/index.d.ts b/types/spectacle/index.d.ts index 12716fb32c..41f0d1df79 100644 --- a/types/spectacle/index.d.ts +++ b/types/spectacle/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Spectacle 1.1.1 +// Type definitions for Spectacle 1.2.0 // Project: https://github.com/FormidableLabs/victory // Definitions by: Zachary Maybury // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -45,15 +45,18 @@ declare module "spectacle" { bgDarken?:number } + export type Theme = { [key: string ]: string | number } + export interface SpectacleProps { - theme?:{ [key: string ]: string | number } + theme?: Theme } export interface DeckProps { transition?:transitionType[], transitionDuration?:number, progress?:progressType, - controls?:boolean + controls?:boolean, + theme?: Theme } export interface SlideProps extends BaseProps { @@ -147,4 +150,15 @@ declare module "spectacle" { export class TableItem extends React.Component {} export class Text extends React.Component {} -} \ No newline at end of file +} + +declare module "spectacle/lib/utils/preloader" { + const preloader: (obj: object) => void; + export default preloader; +} + +declare module "spectacle/lib/themes/default" { + import { Theme } from "spectacle"; + const createTheme: (...args: object[]) => Theme; + export default createTheme; +} diff --git a/types/spectacle/spectacle-tests.tsx b/types/spectacle/spectacle-tests.tsx index cfe052a1f1..f0a0b65e5a 100644 --- a/types/spectacle/spectacle-tests.tsx +++ b/types/spectacle/spectacle-tests.tsx @@ -21,6 +21,28 @@ import { Text } from "spectacle"; +// Import image preloader util +import preloader from 'spectacle/lib/utils/preloader' + +// Import theme +import createTheme from 'spectacle/lib/themes/default' + +const images = { + city: 'a-url' +} + +preloader(images) + +const theme = createTheme({ + primary: 'white', + secondary: '#1F2022', + tertiary: '#03A9FC', + quartenary: '#CECECE' +}, { + primary: 'Montserrat', + secondary: 'Helvetica' +}) + export class SpectacleTest extends React.Component { callback() { alert('Callback: ' + JSON.stringify(arguments)); diff --git a/types/storybook__addon-options/index.d.ts b/types/storybook__addon-options/index.d.ts index b60230784b..2638cdab8d 100644 --- a/types/storybook__addon-options/index.d.ts +++ b/types/storybook__addon-options/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @storybook/addon-options 3.0 +// Type definitions for @storybook/addon-options 3.2 // Project: https://github.com/storybooks/storybook // Definitions by: Joscha Feth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -13,6 +13,7 @@ export interface Options { showSearchBox?: boolean; downPanelInRight?: boolean; sortStoriesByKind?: boolean; + hierarchySeparator?: RegExp | string; } export function setOptions(options: Options): void; diff --git a/types/storybook__addon-options/storybook__addon-options-tests.ts b/types/storybook__addon-options/storybook__addon-options-tests.ts index c4a53edf05..b88cf0504f 100644 --- a/types/storybook__addon-options/storybook__addon-options-tests.ts +++ b/types/storybook__addon-options/storybook__addon-options-tests.ts @@ -9,4 +9,9 @@ setOptions({ showSearchBox: false, downPanelInRight: false, sortStoriesByKind: false, + hierarchySeparator: /\//, +}); + +setOptions({ + hierarchySeparator: '.', }); diff --git a/types/swagger-tools/index.d.ts b/types/swagger-tools/index.d.ts index a697e9d7e8..7ff9abea40 100644 --- a/types/swagger-tools/index.d.ts +++ b/types/swagger-tools/index.d.ts @@ -13,6 +13,7 @@ export interface SwaggerRouterOptionsControllers { export interface SwaggerRouterOptions { controllers?: SwaggerRouterOptionsControllers | string | string[]; + ignoreMissingHandlers?: boolean; useStubs?: boolean; } diff --git a/types/wallabyjs/index.d.ts b/types/wallabyjs/index.d.ts index 6c4d332de0..da966291b5 100644 --- a/types/wallabyjs/index.d.ts +++ b/types/wallabyjs/index.d.ts @@ -15,7 +15,7 @@ declare module 'wallabyjs' { * @property {string[] | IWallabyFilePattern[]} files - Specifies an array of source files or file name patterns to copy * to the local cache. * @property {Function=} postprocessor - Function that runs for every batch of file changes after all compilers and preprocessors. - * @property {Function=} preprocessor - Function that runs for every batch of file changes after all compilers. + * @property {Function=} preprocessors - Function that runs for every batch of file changes after all compilers. * @property {string=} testFramework - Specifies the name and version of the testing framework you are using for your tests. * @property {string[] | IWallabyFilePattern[]} tests - Specifies an array of test files or test file name patterns to copy * to the local cache. @@ -24,12 +24,12 @@ declare module 'wallabyjs' { * @see {@link https://wallabyjs.com/docs/config/overview.html} for details. */ export interface IWallabyConfig { - comilers?: IWallabyCompilers; + compilers?: IWallabyCompilers; debug?: boolean; env?: IWallabyEnvironment; files: string[] | IWallabyFilePattern[]; postprocessor?: IWallabyProcessor; - preprocessor?: IWallabyProcessor; + preprocessors?: IWallabyProcessor; testFramework?: string; tests: string[] | IWallabyFilePattern[]; workers?: IWallabyWorkers; diff --git a/types/wallabyjs/wallabyjs-tests.ts b/types/wallabyjs/wallabyjs-tests.ts index 5e6c90e0a4..141e55d708 100644 --- a/types/wallabyjs/wallabyjs-tests.ts +++ b/types/wallabyjs/wallabyjs-tests.ts @@ -21,7 +21,7 @@ export class WallabyConfig implements wallabyjs.IWallabyConfig { '**/*.ts': file => file.content + '\n// this is TypeScript' }; - public postprocessors: wallabyjs.IWallabyProcessor = { + public postprocessor: wallabyjs.IWallabyProcessor = { '**/*.js': file => file.content + '\n// this is JavaScript', '**/*.ts': file => file.content + '\n// this is TypeScript' }; diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index d316572aab..503b87181c 100644 --- a/types/webappsec-credential-management/index.d.ts +++ b/types/webappsec-credential-management/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for W3C (WebAppSec) Credential Management API Level 1, 0.2 +// Type definitions for W3C (WebAppSec) Credential Management API Level 1, 0.3 // Project: https://github.com/w3c/webappsec-credential-management // Definitions by: Iain McGinniss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -// Spec: http://www.w3.org/TR/2016/WD-credential-management-1-20160425/ +// Spec: https://www.w3.org/TR/2017/WD-credential-management-1-20170804 /* ************************* FETCH MODIFICATIONS ******************************* * The credential management spec modifies fetch(), by adding a new @@ -80,14 +80,35 @@ interface CredentialsContainer { */ store(credential: Credential): Promise; + /** + * Create a {@link Credential} asynchronously. + * + * @see {@link https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#dom-credentialscontainer-create} + */ + create(options: CredentialCreationOptions): Promise; + /** * Ask the credential manager to require user mediation before returning * credentials for the origin in which the method is called. This might be * called after a user signs out of a website, for instance, in order to * ensure that they are not automatically signed back in next time they * visits. + * + * @deprecated Use {@link preventSilentAccess} instead. + * @see {@link https://www.w3.org/TR/2016/WD-credential-management-1-20160425/#dom-credentialscontainer-requireusermediation} */ requireUserMediation(): Promise; + + /** + * Ask the credential manager to require user mediation before returning + * credentials for the origin in which the method is called. This might be + * called after a user signs out of a website, for instance, in order to + * ensure that they are not automatically signed back in next time they + * visits. + * + * @see {@link https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#dom-credentialscontainer-preventsilentaccess} + */ + preventSilentAccess(): Promise; } /** @@ -246,6 +267,11 @@ declare class FederatedCredential extends SiteBoundCredential { readonly protocol: string|null; } +/** + * @see {@link https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#enumdef-credentialmediationrequirement} + */ +type CredentialMediationRequirement = 'silent'|'optional'|'required'; + /** * @see {@link https://www.w3.org/TR/credential-management-1/#dictdef-credentialrequestoptions} */ @@ -265,8 +291,40 @@ interface CredentialRequestOptions { /** * If {@code true}, the user agent will only attempt to provide a Credential * without user interaction. Defaults to {@code false}. + * + * @deprecated Use {@link mediation} instead. */ unmediated?: boolean; + + /** + * This property specifies the mediation requirements for a given credential + * request. + */ + mediation?: CredentialMediationRequirement; +} + +/** + * @see {@link https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#typedefdef-passwordcredentialinit} + */ +type PasswordCredentialInit = PasswordCredentialData|HTMLFormElement; + +/** + * @see {@link https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#dictdef-federatedcredentialinit} + */ +type FederatedCredentialInit = FederatedCredentialData; + +/** + * @see {@link https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#dictdef-credentialcreationoptions} + */ +interface CredentialCreationOptions { + /** + * @see {@link https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#dictdef-federatedcredentialinit} + */ + password?: PasswordCredentialInit; + /** + * @see {@link https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#dom-credentialcreationoptions-federated} + */ + federated?: FederatedCredentialInit; } /** diff --git a/types/webappsec-credential-management/webappsec-credential-management-tests.ts b/types/webappsec-credential-management/webappsec-credential-management-tests.ts index 148b604a69..43a2e78aa9 100644 --- a/types/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/types/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -21,6 +21,51 @@ function passwordBasedSignIn() { }); } +// https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#mediation-examples +function signInMediationSilent() { + window.addEventListener('load', _ => { + if (!navigator.credentials) { + return; + } + navigator.credentials.get({ + password: true, + mediation: 'silent' + }).then((credential) => { + // Hooray! Let’s sign the user in using these credentials! + }); + }); +} + +// https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#mediation-examples +function signInMediationRequired() { + window.addEventListener('load', _ => { + if (!navigator.credentials) { + return; + } + navigator.credentials.get({ + password: true, + mediation: 'required' + }).then((credential) => { + // Hooray! Let’s sign the user in using these credentials! + }); + }); +} + +// https://www.w3.org/TR/2017/WD-credential-management-1-20170804/#mediation-examples +function signInMediationOptional() { + window.addEventListener('load', _ => { + if (!navigator.credentials) { + return; + } + navigator.credentials.get({ + password: true, + mediation: 'optional' + }).then((credential) => { + // Hooray! Let’s sign the user in using these credentials! + }); + }); +} + // federated sign-in example from Section 1.2.2: // https://www.w3.org/TR/credential-management-1/#examples-federated-signin function federatedSignIn() { @@ -121,7 +166,7 @@ function formEncodedPost(credential: PasswordCredential, token: string) { // requireUserMediation example: not included in the spec, but included here // to ensure it typechecks correctly. -function signOut() { +function signOutDeprecated() { if (!navigator.credentials) { return; } @@ -130,3 +175,57 @@ function signOut() { document.location.assign('/'); }); } + +function signOut() { + if (!navigator.credentials) { + return; + } + + navigator.credentials.preventSilentAccess().then(() => { + document.location.assign('/'); + }); +} + +// Example not included in spec but added to ensure it typechecks +// correctly. +function createPasswordCredential() { + if (!navigator.credentials) { + return; + } + + navigator.credentials.create({ + password: {id: 'username', password: 'password'} + }).then((credential) => { + // Credential created! + }); +} + +// Example not included in spec but added to ensure it typechecks +// correctly. +function createPasswordCredentialWithForm() { + if (!navigator.credentials) { + return; + } + + const formElt = document.querySelector('#form') as HTMLFormElement; + + navigator.credentials.create({ + password: formElt + }).then((credential) => { + // Credential created! + }); +} + +// Example not included in spec but added to ensure it typechecks +// correctly. +function createFederatedCredential() { + if (!navigator.credentials) { + return; + } + + navigator.credentials.create({ + federated: {id: 'username', provider: 'provider'} + }).then((credential) => { + // Credential created! + }); +} diff --git a/types/webdriverio/index.d.ts b/types/webdriverio/index.d.ts index ea34a6c034..a3d7a08d99 100644 --- a/types/webdriverio/index.d.ts +++ b/types/webdriverio/index.d.ts @@ -421,7 +421,7 @@ declare namespace WebdriverIO { mochaOpts?: { [name: string]: any; }; jasmineNodeOpts?: { [name: string]: any; }; cucumberOpts?: { [name: string]: any; }; - services?: string | ((...args: any[]) => void); + services?: string[] | ((...args: any[]) => void); screenshotPath?: string; specs?: string[]; seleniumLogs?: string; diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 3dd1a08583..14517ae3d6 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -848,6 +848,10 @@ declare namespace webpack { constructor(); } + class NamedChunksPlugin extends Plugin { + constructor(); + } + class NoEmitOnErrorsPlugin extends Plugin { constructor(); } diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 89110f06c6..6ee9f35e59 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -2137,6 +2137,24 @@ declare namespace wx { } } +declare namespace wx { + interface Touch { + identifier: number; + pageX: number; + pageY: number; + clientX: number; + clientY: number; + } + interface TouchEvent extends BaseEvent { + detail: { + x: number; + y: number; + }; + touches: Touch[]; + changedTouches: Touch[]; + } +} + declare var App: wx.AppConstructor; /**